code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
import Database.LMDB
import System.Exit
import System.Environment
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as L
import Data.Maybe
import Data.Monoid
import Text.Printf
import Control.Applicative
import Control.Monad
import Control.DeepSeq (force)
import System.Process
import Database.LMDB.Flags
import Data.Word
import Data.List (sortBy,sort)
import Data.Ord (comparing)
import Data.Int
import Data.Bits
import Data.Binary
import Foreign.Ptr
import Foreign.Storable
import qualified Data.ByteString.Internal as S
import Foreign.Marshal.Alloc
import Foreign.ForeignPtr
import Control.Exception
import System.Directory
import qualified Data.Binary as Binary
aliases = [ ("listTables","list")
, ("createTable","create")
, ("deleteTable","drop")
, ("clearTable","clear")
, ("insertKey","insert")
, ("deleteKey","delete")
, ("lookupVal","lookup")
, ("keysOf","keys")
, ("valsOf","vals")
]
formatAssocList width indent as = h width (B.length indent) indent as
where
h _ _ str [] = str
h max tot str ((x,y):ys) = if l x y ys + tot > max then let str' = B.concat [str,"\n",indent,b x y ys]
in h max 0 str' ys
else let str' = B.concat [str,b x y ys]
in h max (tot + l x y ys) str' ys
b x y xs = B.concat [x," => ",y,if null xs then "\n" else ", "]
l x y xs = B.length (b x y xs)
formatList width indent as = h width (B.length indent) indent as
where
h _ _ str [] = str
h max tot str (y:ys) = if l y ys + tot > max then let str' = B.concat [str,"\n",indent,b y ys]
in h max 0 str' ys
else let str' = B.concat [str,b y ys]
in h max (tot + l y ys) str' ys
b y xs = B.concat [y,if null xs then "\n" else ", "]
l y xs = B.length (b y xs)
unaliasArgs args | length args < 2 = return args
unaliasArgs args@(a:b:args') = do
bPath <- doesDirectoryExist (B.unpack a)
if bPath then return (a:f b:args')
else return args
where f x = case lookup x aliases of
Just y -> y
Nothing -> x
usage :: IO ()
usage = let cs =
[ [" ","list"]
, [" ","create",tbl]
, [" ","drop ",tbl]
, [" ","clear ",tbl]
, ["{*} ","insert",atbl,key,val]
, ["{*} ","delete",atbl,key]
, ["{*} ","keys ",atbl]
, ["{*} ","vals ",atbl]
, ["{*} ","lookup",atbl,key]
-- , ["{*} ",path,"toList ",atbl]
-- Variation of toList
, [" ","show ",mtbl]
]
ds=[ -- Copy commands
["{+} copyTable",bool,path,tbl,path,mtbl]
]
path = "<path>"
tbl = "<table>"
mtbl = "[<table>]"
atbl = "(@|<table>)"
key = "<key>"
val = "<value>"
bool = "[true|false]"
fmt xs = " " <> B.unwords xs
in do
putStrLn "Usage: lmdbtool [-p] <path> <Infix-Command>"
putStrLn " lmdbtool [-p] copyTable (true|false) <path> <table> <path> [<table>]"
putStrLn ""
putStrLn " -p Accept final parameter on stdin"
putStrLn ""
putStrLn "Infix Commands:" >> mapM_ (B.putStrLn . fmt) cs
putStrLn ""
putStrLn "Prefix Command{✗}:" >> mapM_ (B.putStrLn . fmt) ds
putStrLn ""
putStrLn "Notes: {*} These commands accept ‘@’ as name of Main table (unnamedDB)."
putStrLn " To match library, ‘lookupVal’ is accepted as an alias for ‘lookup’."
putStrLn ""
putStrLn " {+} On copy commands, ‘true’ indicates to allow duplicate keys."
putStrLn " To copy a single key, pipe the output of ‘lookup’ into ‘insert’."
putStrLn ""
putStrLn " {✗} Any Infix command can also be written prefix."
putStrLn ""
putStrLn "Aliases:"
B.putStrLn (formatAssocList 80 " " (sortBy (comparing fst) aliases))
main :: IO ()
main = do
args <- map B.pack <$> getArgs
let u = B.unpack
v = void
putPair (x,y) = B.putStrLn (f x <> ": " <> f y)
putPairI n (x,y) = B.putStrLn (B.replicate n ' ' <> f x <> ": " <> f y)
-- TODO special support for _counters
--putPairI' n (x,y) = B.putStrLn (B.replicate n ' ' <> f x <> ": " <> g y)
f x = case B.readInteger x of
Just (n,"") -> B.pack $ show x
Nothing -> x
-- TODO special support for _counters
--g x = case Binary.decode (L.fromChunks [x]) of
-- Just n -> B.pack $ show (n::Word32)
-- Nothing -> x
putTbl path tbl = do
putStrLn "---"
B.putStr tbl >> putStrLn ":"
-- TODO special support for _counters
--let putit = if "_counter" `B.isPrefixOf` tbl then putPairI' else putPairI
mapM_ (putPairI 2) =<< toList (u path) tbl
args' <- if take 1 args == ["-p"] then drop 1 . (args ++) . (:[]) <$> B.getLine
else return args
args'' <- unaliasArgs args'
let reserved = ("newKey":"newTbl":"show":"copyTable":as ++ bs) where (as,bs) = unzip aliases
let checkpath mbpath action = do
case mbpath of
Just path -> do
bExists <- doesDirectoryExist (u path)
when (bExists && path `elem` reserved) $ do
putStrLn "For safety, lmdbtool does not operate on lmdb environments with names that are acceptable lmdbtool commands, or reserved."
putStrLn "The following names are reserved:"
B.putStrLn (formatList 80 " " (sort reserved))
putStrLn "To rename an environment, simply rename the folder which contains data.mdb.\n"
exitFailure
action
Nothing -> action
let (mbpath,args''') = case args'' of
["copyTable","true",path] -> (Just path, args'') -- prefix command, leave it alone
["copyTable","false",path]-> (Just path, args'') -- prefix command, leave it alone
("copyTable":_) -> (Nothing, args'') -- prefix command, leave it alone
(x:path:xs) | x `elem` reserved -> (Just path,path:x:xs) -- infix as prefix, so convert it to expected infix
(path:x:xs) | x `elem` reserved -> (Just path,args'') -- already infix, leave it alone
_ -> (Nothing,args'') -- usage >> exitFailure
checkpath mbpath $
case args''' of
[path,"list"] -> mapM_ B.putStrLn =<< listTables (u path)
[path,"create",tbl] -> v $ createTable (u path) tbl
[path,"drop",tbl] -> v $ deleteTable (u path) tbl
[path,"clear",tbl] -> clearTable (u path) tbl
[path,"insert","@",key,val] -> v $ insertKeyUnnamed (u path) key val
[path,"insert",tbl,key,val] -> v $ insertKey (u path) tbl key val
[path,"delete","@",key] -> v $ deleteKeyUnnamed (u path) key
[path,"delete",tbl,key] -> v $ deleteKey (u path) tbl key
[path,"keys","@"] -> mapM_ B.putStrLn =<< keysOfUnnamed (u path)
[path,"keys",tbl] -> mapM_ (putKey (u path) tbl) =<< keysOf (u path) tbl
[path,"vals","@"] -> mapM_ B.putStrLn =<< valsOfUnnamed (u path)
[path,"vals",tbl] -> mapM_ (putVal (u path) tbl) =<< valsOf (u path) tbl
[path,"lookup","@",key] -> B.putStrLn =<< fromMaybe "" <$> lookupValUnnamed (u path) key
[path,"lookup",tbl,key] -> B.putStrLn =<< fromMaybe "" <$> lookupVal (u path) tbl key
-- [path,"toList","@"] -> print =<< toListUnnamed (u path)
-- [path,"toList",tbl] -> print =<< toList (u path) tbl
-- Variation of toList
[path,"show",tbl] -> mapM_ putPair =<< toList (u path) tbl
[path,"show"] -> mapM_ (putTbl path) =<< listTables (u path)
-- Copy commands
["copyTable","true",path,tbl,dest] -> v $ copyTable True (u path) tbl (u dest) tbl
["copyTable","false",path,tbl,dest] -> v $ copyTable False (u path) tbl (u dest) tbl
["copyTable","true",path,tbl,dest,tbl2] -> v $ copyTable True (u path) tbl (u dest) tbl2
["copyTable","false",path,tbl,dest,tbl2]-> v $ copyTable False (u path) tbl (u dest) tbl2
_ -> usage
lookupValUnnamed x k = withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
mb <- unsafeFetch d k
case mb of
Just (val,final) -> do
force val `seq` final
return (Just val)
Nothing -> return Nothing
insertKeyUnnamed x k v = withDBSCreateIfMissing x $ \dbs -> do
d <- unnamedDB dbs
add d k v
deleteKeyUnnamed x k = withDBSCreateIfMissing x $ \dbs -> do
d <- unnamedDB dbs
delete d k
keysOfUnnamed x = withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
(keysVals,final) <- unsafeDumpToList d
let keys = map (B.copy . fst) keysVals
force keys `seq` final
return keys
valsOfUnnamed x = withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
(keysVals,final) <- unsafeDumpToList d
let vals = map (B.copy . snd) keysVals
force vals `seq` final
return vals
toListUnnamed x = withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
(xs,final) <- unsafeDumpToList d
let ys = map copy xs
copy (x,y) = (B.copy x, B.copy y)
force ys `seq` final
return ys
printInt64 bstr = let x :: Int64
x = decode (L.fromChunks [bstr])
in print x
printWord64 bstr =
let x :: Word64
x = decode (L.fromChunks [bstr])
in print x
printInt32 bstr = let x :: Int32
x = decode (L.fromChunks [bstr])
in print x
printWord32 bstr =let x :: Word32
x = decode (L.fromChunks [bstr])
in print x
printLengthPrefixed bstr =
let x :: B.ByteString
x = decode (L.fromChunks [bstr])
in B.putStrLn x
putVal x tbl = \str -> withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
mb <- unsafeFetch d (tbl <> "FLAGS")
let f :: B.ByteString -> Word64
f x = decode (L.fromChunks [x])
case mb of
Nothing -> B.putStrLn str
Just (x,fin) -> do
{-let (fptr,_,_) = S.toForeignPtr x
in withForeignPtr fptr $ \ptr -> do
flags <- peek (castPtr ptr)-}
let flags = decode (L.fromChunks [x])
case () of
_ | (flags `has` flagValInt64) -> fin >> printInt64 str
_ | (flags `has` flagValInt32) -> fin >> printInt32 str
_ | (flags `has` flagValWord64) -> fin >> printWord64 str
_ | (flags `has` flagValWord32) -> fin >> printWord32 str
_ | (flags `has` flagValLengthPrefixed) -> fin >> printLengthPrefixed str
_ | (flags `has` flagValBinary) -> fin >> printBinary str
putKey x tbl = \str -> withDBSDo x $ \dbs -> do
d <- unnamedDB dbs
mb <- unsafeFetch d (tbl <> "FLAGS")
let f :: B.ByteString -> Word64
f x = decode (L.fromChunks [x])
case mb of
Nothing -> B.putStrLn str
Just (x,fin) -> do
{-let (fptr,_,_) = S.toForeignPtr x
in withForeignPtr fptr $ \ptr -> do
flags <- peek (castPtr ptr)-}
let flags = decode (L.fromChunks [x])
case () of
_ | (flags `has` flagKeyInt64) -> fin >> printInt64 str
_ | (flags `has` flagKeyInt32) -> fin >> printInt32 str
_ | (flags `has` flagKeyWord64) -> fin >> printWord64 str
_ | (flags `has` flagKeyWord32) -> fin >> printWord32 str
_ | (flags `has` flagKeyLengthPrefixed) -> fin >> printLengthPrefixed str
_ | (flags `has` flagKeyBinary) -> fin >> printBinary str
printBinary s = do
xxdResult <- readCreateProcessWithExitCode (shell "xxd") (B.unpack s)
case xxdResult of
(ExitSuccess,out,"") -> putStrLn out
_ -> putStrLn "(ERROR: Is xxd installed?)"
| jimcrayne/lmdb-bindings | tools/lmdbtool.hs | agpl-3.0 | 13,322 | 0 | 24 | 4,987 | 4,161 | 2,134 | 2,027 | 252 | 29 |
-- | How to use symbolic map (serial and parallel).
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DataKinds #-}
module Main ( main ) where
import Data.Proxy ( Proxy(..) )
import Data.Time.Clock ( getCurrentTime, diffUTCTime )
import Linear ( V2(..), V3(..) )
import Text.Printf ( printf )
import Casadi.DM ( DM )
import Casadi.SX ( SX )
import Casadi.MX ( MX )
import qualified Dyno.TypeVecs as TV
import Dyno.View.Fun ( Fun, callDM, callSym, toFun )
import Dyno.View.MapFun ( MapStrategy(..), mapFun )
import Dyno.View.M ( M, hcat', hsplit', vcat, vsplit )
import Dyno.View.JVec ( JVec(..) )
import Dyno.Vectorize ( Id(..) )
import Dyno.View.View ( J, JV )
type N = 300
-- some random function
f0' :: J (JV V2) SX -> J (JV V3) SX
f0' x = vcat $ V3 (g (100000 :: Int) x0) x1 (2*x1)
where
V2 x0 x1 = vsplit x
g 0 y = y
g k y = g (k-1) (sin y)
main :: IO ()
main = do
let dummyInput :: M (JV V2) (JVec N (JV Id)) DM
dummyInput = hcat' $ fmap (\x -> vcat (V2 x (2*x)))
(TV.tvlinspace 0 (2*pi))
show dummyInput `seq` return ()
-- make a dummy function that's moderately expensive to evaluate
putStrLn "creating dummy function..."
f0 <- toFun "f0" f0' mempty
:: IO (Fun (J (JV V2)) (J (JV V3)))
let runOne :: String
-> Fun
(M (JV V2) (JVec N (JV Id)))
(M (JV V3) (JVec N (JV Id)))
-> IO ()
runOne name someMap = do
putStrLn $ "evaluating " ++ name ++ "..."
t0 <- getCurrentTime
_ <- callDM someMap dummyInput
t1 <- getCurrentTime
printf "evaluated %s in %.3f seconds\n"
name (realToFrac (diffUTCTime t1 t0) :: Double)
let naiveFun :: M (JV V2) (JVec N (JV Id)) MX -> M (JV V3) (JVec N (JV Id)) MX
naiveFun xs = hcat' ys
where
ys :: TV.Vec N (M (JV V3) (JV Id) MX)
ys = fmap (callSym f0) xs'
xs' :: TV.Vec N (M (JV V2) (JV Id) MX)
xs' = hsplit' xs
naive <- toFun "naive_map" naiveFun mempty
unroll <- mapFun (Proxy :: Proxy N) f0 Unroll
:: IO (Fun
(M (JV V2) (JVec N (JV Id)))
(M (JV V3) (JVec N (JV Id))))
ser <- mapFun (Proxy :: Proxy N) f0 Serial
:: IO (Fun
(M (JV V2) (JVec N (JV Id)))
(M (JV V3) (JVec N (JV Id))))
par <- mapFun (Proxy :: Proxy N) f0 OpenMP
runOne "naive map" naive
runOne "unrolled symbolic_map" unroll
runOne "serial symbolic map" ser
runOne "parallel symbolic map" par
| ghorn/dynobud | dynobud/examples/ParallelMap.hs | lgpl-3.0 | 2,537 | 0 | 18 | 780 | 1,115 | 577 | 538 | 64 | 2 |
{-# LANGUAGE FlexibleInstances #-}
module LogicGoats where
-- 1.
class TooMany a where
tooMany :: a -> Bool
instance TooMany (Int, String) where
tooMany (n,_) = n > 42
-- 2.
instance TooMany (Int, Int) where
tooMany (x,y) = (x+y) > 42
-- 3.
instance (Num a, TooMany a) => TooMany (a, a) where
tooMany (x, y) = tooMany (x + y)
| dmp1ce/Haskell-Programming-Exercises | Chapter 11/Exercises: Logic Goats.hs | unlicense | 340 | 0 | 8 | 76 | 150 | 85 | 65 | 10 | 0 |
module MonadServ.Types where
import Data.Maybe
import Control.Concurrent.MVar ( MVar, newEmptyMVar, tryTakeMVar, tryPutMVar, withMVar, takeMVar, putMVar )
import Network
import System.IO ( stdout, stderr, stdin, hFlush, hPutStr, hPutStrLn
, hGetLine, hGetChar, hGetBuffering, hSetBuffering, Handle
, BufferMode(..)
)
import MonadServ.HttpMonad
type ServerCommand st = ( String , ServerConfig st -> Srv st () )
--type ServerCommand = (String, String )
data ServerConfig st
= SrvDesc
{ serverCommands :: [ServerCommand st]
-- , evaluateFunc :: String -> Srv st ()
, greetingText :: Maybe String
, beforePrompt :: Srv st ()
, prompt :: st -> IO String
-- , exceptionHandler :: Ex.Exception -> Sh st ()
-- , historyFile :: Maybe FilePath
, maxHistoryEntries :: Int
, historyEnabled :: Bool
, port :: Int
, docRoot :: FilePath
}
data InternalServerState st bst
= InternalServerState
{ evalVar :: MVar (Maybe (st))
, evalTest :: MVar String
, cancelHandler :: IO ()
, backendState :: bst
, sock :: Socket
}
data ServerBackend bst
= SrvBackend
{ initBackend :: IO bst
, shutdownBackend :: bst -> IO ()
, outputString :: bst -> Maybe Handle -> BackendOutput -> IO ()
, flushOutput :: bst -> IO ()
, getSingleChar :: bst -> String -> IO (Maybe Char)
, getInput :: bst -> String -> IO (Maybe String)
, addHistory :: bst -> String -> IO ()
-- , setWordBreakChars :: bst -> String -> IO ()
-- , getWordBreakChars :: bst -> IO String
, onCancel :: bst -> IO ()
-- , setAttemptedCompletionFunction :: bst -> CompletionFunction -> IO ()
, setDefaultCompletionFunction :: bst -> Maybe (String -> IO [String]) -> IO ()
, completeFilename :: bst -> String -> IO [String]
, completeUsername :: bst -> String -> IO [String]
, clearHistoryState :: bst -> IO ()
, setMaxHistoryEntries :: bst -> Int -> IO ()
, getMaxHistoryEntries :: bst -> IO Int
-- , readHistory :: bst -> FilePath -> IO ()
-- , writeHistory :: bst -> FilePath -> IO ()
}
templateBackend :: a -> ServerBackend a
templateBackend bst = SrvBackend
{ initBackend = return bst
, shutdownBackend = \_ -> do putStrLn "ya'll come back now..."
return ()
, outputString = \_ h -> basicOutput h
, flushOutput = \_ -> do putStrLn "flush"
return ()
, getSingleChar = \_ _ -> return Nothing
, getInput = \_ _ -> return Nothing
, addHistory = \_ _ -> return ()
-- , setWordBreakChars = \_ _ -> return ()
-- , getWordBreakChars = \_ -> return defaultWordBreakChars
, onCancel = \_ -> return ()
-- , setAttemptedCompletionFunction = \_ _ -> return ()
, setDefaultCompletionFunction = \_ _ -> return ()
, completeFilename = \_ _ -> return []
, completeUsername = \_ _ -> return []
, clearHistoryState = \_ -> return ()
, setMaxHistoryEntries = \_ _ -> return ()
, getMaxHistoryEntries = \_ -> return 0
-- , readHistory = \_ _ -> return ()
-- , writeHistory = \_ _ -> return ()
}
templateServerConfig = SrvDesc
{ serverCommands = []
, greetingText = Just "Welcome now my friends..."
, prompt = \_ -> return "> "
, beforePrompt = srvPutStrLn "waiting for request...(before connection accepted.)"
, maxHistoryEntries = 0
, historyEnabled = True
, port = 8080
, docRoot = "/var/www/"
}
-- | Creates a simple shell description from a list of shell commmands and
-- an evalation function.
mkServerConfig :: [ServerCommand st]
-> ServerConfig st
mkServerConfig cmds =
templateServerConfig
{ serverCommands = cmds
}
basicOutput :: Maybe Handle -> BackendOutput -> IO ()
basicOutput (Just handle) out = do
hPutStr stdout out
hPutStr handle out
basicOutput Nothing out = hPutStr stdout out
| jcaldwell/monadserv | src/MonadServ/Types.hs | bsd-2-clause | 4,963 | 0 | 15 | 2,066 | 995 | 559 | 436 | 79 | 1 |
module Data.Hexagon.DiagonalsSpec where
import SpecHelper
spec :: Spec
spec = do
describe "Data.Hexagon.Diagonals" $ do
context "context" $ do
it "does something" $ do
True `shouldBe` True
main :: IO ()
main = hspec spec
| alios/hexagon | test/Data/Hexagon/DiagonalsSpec.hs | bsd-3-clause | 246 | 0 | 16 | 60 | 77 | 39 | 38 | 10 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Scripts.Execute where
import ClassyPrelude
import Stats.CsvStream
import Appian.Client
import Appian.Instances
import Appian
import Scripts.Common
import qualified Streaming.Prelude as S
import qualified Data.Csv as Csv
import Network.HTTP.Client ( newManager, managerModifyResponse, ResponseTimeout, ManagerSettings
, managerResponseTimeout, responseTimeoutMicro
)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Control.Monad.Trans.Resource
import Servant.Client
import Control.Monad.Logger
import Scripts.ProducerConsumer
import Control.Arrow
import qualified Control.Concurrent.Async.Pool as Pool
runIt :: (Csv.FromNamedRecord a, Show a, HasLogin a) => (a -> Appian b) -> Bounds -> HostUrl -> LogMode -> CsvPath -> RampupTime -> NThreads -> IO [Maybe (Either ServantError (Either ScriptError b))]
runIt f bounds (HostUrl hostUrl) logMode csvInput (RampupTime delay) (NThreads n) = do
mgr <- newManager $ setTimeout (responseTimeoutMicro 90000000000) $ tlsManagerSettings { managerModifyResponse = cookieModifier }
let env = ClientEnv mgr (BaseUrl Https hostUrl 443 mempty)
appianState = newAppianState bounds
runResourceT $ runStdoutLoggingT $ runParallel $ Parallel (nThreads n) (S.zip (S.each [0..]) $ void (csvStreamByName csvInput)) (\(i, a) -> do
let d = (i * (delay `div` n))
tid <- threadId
logDebugN $ tshow tid <> ": " <> tshow a
res <- liftIO $ runAppianT logMode (f a) appianState env (getLogin a)
logResult res
return res
)
newtype RampupTime = RampupTime Int
deriving (Show, Eq, Num)
mkRampup :: Int -> RampupTime
mkRampup n = RampupTime $ n * 1000000
setTimeout :: ResponseTimeout -> ManagerSettings -> ManagerSettings
setTimeout timeout settings = settings { managerResponseTimeout = timeout }
logResult :: (MonadLogger m, MonadThreadId m) => Either ServantError (Either ScriptError a) -> m ()
logResult (Left err) = do
tid <- threadId
logErrorN $ tshow tid <> ": " <> tshow err
logResult (Right (Left err)) = do
tid <- threadId
logErrorN $ tshow tid <> ": " <> tshow err
logResult (Right (Right _)) = return ()
exhaustiveProducer :: (Csv.FromNamedRecord a, MonadResource m, MonadLogger m) => TBQueue a -> CsvPath -> m String
exhaustiveProducer q = csvStreamByName >>> S.mapM_ (atomically . writeTBQueue q)
-- Must take a look at how I can return the results from this.
runScriptExhaustive :: (Csv.FromNamedRecord a, Show a, HasLogin a) => (a -> Appian b) -> Bounds -> HostUrl -> LogMode -> CsvPath -> NThreads -> NumRecords -> IO ()
runScriptExhaustive f bounds (HostUrl hostUrl) logMode csvInput nThreads (NumRecords numRecords) = do
mgr <- newManager $ setTimeout (responseTimeoutMicro 90000000000) $ tlsManagerSettings { managerModifyResponse = cookieModifier }
let env = ClientEnv mgr (BaseUrl Https hostUrl 443 mempty)
appianState = newAppianState bounds
confs <- csvStreamByName >>> S.take numRecords >>> S.toList >>> runResourceT >>> runStdoutLoggingT $ csvInput
execTaskGroup_ nThreads (\a -> runStdoutLoggingT $ do
res <- liftIO $ runAppianT logMode (f a) appianState env (getLogin a)
logResult res
) $ S.fst' confs
execTaskGroup :: Traversable t => NThreads -> (a -> IO b) -> t a -> IO (t b)
execTaskGroup (NThreads n) f args = Pool.withTaskGroup n $ \group -> Pool.mapConcurrently group f args
execTaskGroup_ :: Traversable t => NThreads -> (a -> IO b) -> t a -> IO ()
execTaskGroup_ n f args = execTaskGroup n f args >> return ()
| limaner2002/EPC-tools | USACScripts/src/Scripts/Execute.hs | bsd-3-clause | 4,474 | 0 | 19 | 1,485 | 1,230 | 626 | 604 | 63 | 1 |
-- | A test for ensuring that GHC's supporting language extensions remains in
-- sync with Cabal's own extension list.
--
-- If you have ended up here due to a test failure, please see
-- Note [Adding a language extension] in compiler/main/DynFlags.hs.
module Main (main) where
import Control.Monad
import Data.List
import DynFlags
import Language.Haskell.Extension
main :: IO ()
main = do
let ghcExtensions = map flagSpecName xFlags
cabalExtensions = map show [ toEnum 0 :: KnownExtension .. ]
ghcOnlyExtensions = ghcExtensions \\ cabalExtensions
cabalOnlyExtensions = cabalExtensions \\ ghcExtensions
check "GHC-only flags" expectedGhcOnlyExtensions ghcOnlyExtensions
check "Cabal-only flags" expectedCabalOnlyExtensions cabalOnlyExtensions
check :: String -> [String] -> [String] -> IO ()
check title expected got
= do let unexpected = got \\ expected
missing = expected \\ got
showProblems problemType problems
= unless (null problems) $
do putStrLn (title ++ ": " ++ problemType)
putStrLn "-----"
mapM_ putStrLn problems
putStrLn "-----"
putStrLn ""
showProblems "Unexpected flags" unexpected
showProblems "Missing flags" missing
-- See Note [Adding a language extension] in compiler/main/DynFlags.hs.
expectedGhcOnlyExtensions :: [String]
expectedGhcOnlyExtensions = ["RelaxedLayout",
"AlternativeLayoutRule",
"AlternativeLayoutRuleTransitional",
"EmptyDataDeriving",
"BlockArguments",
"NumericUnderscores"]
expectedCabalOnlyExtensions :: [String]
expectedCabalOnlyExtensions = ["Generics",
"ExtensibleRecords",
"RestrictedTypeSynonyms",
"HereDocuments",
"NewQualifiedOperators",
"XmlSyntax",
"RegularPatterns",
"SafeImports",
"Safe",
"Unsafe",
"Trustworthy"]
| shlevy/ghc | testsuite/tests/driver/T4437.hs | bsd-3-clause | 2,355 | 0 | 16 | 884 | 342 | 183 | 159 | 45 | 1 |
-- #hide
module Data.Time.Clock.CTimeval where
#ifndef mingw32_HOST_OS
-- All Unix-specific, this
#if __GLASGOW_HASKELL__ >= 709
import Foreign
#else
import Foreign.Safe
#endif
import Foreign.C
data CTimeval = MkCTimeval CLong CLong
instance Storable CTimeval where
sizeOf _ = (sizeOf (undefined :: CLong)) * 2
alignment _ = alignment (undefined :: CLong)
peek p = do
s <- peekElemOff (castPtr p) 0
mus <- peekElemOff (castPtr p) 1
return (MkCTimeval s mus)
poke p (MkCTimeval s mus) = do
pokeElemOff (castPtr p) 0 s
pokeElemOff (castPtr p) 1 mus
foreign import ccall unsafe "time.h gettimeofday" gettimeofday :: Ptr CTimeval -> Ptr () -> IO CInt
-- | Get the current POSIX time from the system clock.
getCTimeval :: IO CTimeval
getCTimeval = with (MkCTimeval 0 0) (\ptval -> do
throwErrnoIfMinus1_ "gettimeofday" $ gettimeofday ptval nullPtr
peek ptval
)
#endif
| DavidAlphaFox/ghc | libraries/time/lib/Data/Time/Clock/CTimeval.hs | bsd-3-clause | 889 | 0 | 11 | 162 | 280 | 142 | 138 | 19 | 1 |
{-# LANGUAGE FlexibleContexts, RankNTypes #-}
module EC2Tests.SecurityGroupTests
( runSecurityGroupTests
)
where
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Text (Text)
import Test.Hspec
import Cloud.AWS.EC2
import Cloud.AWS.EC2.Types
import qualified Cloud.AWS.EC2.Util as Util
import Util
import EC2Tests.Util
region :: Text
region = "ap-northeast-1"
runSecurityGroupTests :: IO ()
runSecurityGroupTests = hspec $ do
describeSecurityGroupsTest
createAndDeleteSecurityGroupTest
authorizeAndRevokeSecurityGroupIngressTest
authorizeAndRevokeSecurityGroupEgressTest
describeSecurityGroupsTest :: Spec
describeSecurityGroupsTest = do
describe "describeSecurityGroups" $ do
it "doesn't throw any exception" $ do
testEC2 region (describeSecurityGroups [] [] []) `miss` anyConnectionException
createAndDeleteSecurityGroupTest :: Spec
createAndDeleteSecurityGroupTest = do
describe "{create,delete}SecurityGroup" $ do
it "doesn't throw any exception" $ do
testEC2' region (
withSecurityGroup "createAndDeleteSecurityGroupTest" "For testing" Nothing $ const (return ())
) `miss` anyConnectionException
authorizeAndRevokeSecurityGroupIngressTest :: Spec
authorizeAndRevokeSecurityGroupIngressTest = do
describe "{authorize,revoke}SecurityGroupIngress" $ do
context "with IpRanges" $ do
it "doesn't throw any exception" $ do
testEC2' region (do
withSecurityGroup sgName "For testing" Nothing $ \msg -> do
let req = toReq sgName msg
perms = [perm1]
authorizeSecurityGroupIngress req perms
revokeSecurityGroupIngress req perms
) `miss` anyConnectionException
context "with Groups" $ do
it "doesn't throw any exception" $ do
testEC2' region (do
withSecurityGroup sgName "For testing" Nothing $ \msg -> do
withSecurityGroup sgName2 "For testing" Nothing $ \msg2 -> do
Util.sleep 5
let req = toReq sgName2 msg2
perms = [perm2 sgName msg]
authorizeSecurityGroupIngress req perms
revokeSecurityGroupIngress req perms
-- To test "GroupName" version
withSecurityGroup sgName2 "For testing" Nothing $ \_ -> do
let req = toReq sgName2 Nothing
perms = [perm2 sgName msg]
authorizeSecurityGroupIngress req perms
revokeSecurityGroupIngress req perms
) `miss` anyConnectionException
where
toReq name = maybe (SecurityGroupRequestGroupName name) SecurityGroupRequestGroupId
sgName = "authorizeSecurityGroupIngressTest"
perm1 = IpPermission
{ ipPermissionIpProtocol = "tcp"
, ipPermissionFromPort = Just 80
, ipPermissionToPort = Just 80
, ipPermissionGroups = []
, ipPermissionIpRanges = ["192.0.2.0/24", "198.51.100.0/24"]
}
sgName2 = sgName <> "2"
perm2 name msg = IpPermission
{ ipPermissionIpProtocol = "tcp"
, ipPermissionFromPort = Just 80
, ipPermissionToPort = Just 80
, ipPermissionGroups = [toPair name msg]
, ipPermissionIpRanges = []
}
authorizeAndRevokeSecurityGroupEgressTest :: Spec
authorizeAndRevokeSecurityGroupEgressTest = do
describe "authorizeSecurityGroupEgress" $ do
context "with IpRanges" $ do
it "doesn't throw any exception" $ do
testEC2' region (do
withVpc "10.0.0.0/24" $ \Vpc{vpcId = vpc} ->
withSecurityGroup sgName "For testing" (Just vpc) $ \msg -> do
let sg = fromMaybe (error "No GroupId") msg
perms = [perm1]
authorizeSecurityGroupEgress sg perms
revokeSecurityGroupEgress sg perms
) `miss` anyConnectionException
context "with Groups" $ do
it "doesn't throw any exception" $ do
testEC2' region (do
withVpc "10.0.0.0/24" $ \Vpc{vpcId = vpc} ->
withSecurityGroup sgName "For testing" (Just vpc) $ \msg ->
withSecurityGroup sgName2 "For testing" (Just vpc) $ \msg2 -> do
let sg = fromMaybe (error "No GroupId") msg2
perms = [perm2 sgName msg]
authorizeSecurityGroupEgress sg perms
revokeSecurityGroupEgress sg perms
) `miss` anyConnectionException
where
sgName = "authorizeSecurityGroupEgressTest"
perm1 = IpPermission
{ ipPermissionIpProtocol = "tcp"
, ipPermissionFromPort = Just 80
, ipPermissionToPort = Just 80
, ipPermissionGroups = []
, ipPermissionIpRanges = ["192.0.2.0/24", "198.51.100.0/24"]
}
sgName2 = sgName <> "2"
perm2 name msg = IpPermission
{ ipPermissionIpProtocol = "tcp"
, ipPermissionFromPort = Just 1433
, ipPermissionToPort = Just 1433
, ipPermissionGroups = [toPair name msg]
, ipPermissionIpRanges = []
}
toPair :: Text -> Maybe Text -> UserIdGroupPair
toPair _ (Just sg) = UserIdGroupPair
{ userIdGroupPairUserId = Nothing
, userIdGroupPairGroupId = Just sg
, userIdGroupPairGroupName = Nothing
}
toPair name Nothing = UserIdGroupPair
{ userIdGroupPairUserId = Nothing
, userIdGroupPairGroupId = Nothing
, userIdGroupPairGroupName = Just name
}
| worksap-ate/aws-sdk | test/EC2Tests/SecurityGroupTests.hs | bsd-3-clause | 5,959 | 0 | 34 | 2,015 | 1,211 | 621 | 590 | 122 | 1 |
module Exercises1010 where
stops = "pbtdkg"
vowels = "aeiou"
{-
1.
To decompose this,
The strings each need to be broken down into individual lists.
The stop-vowel-stop combinations must be combvined into 3-tuples.
It should enumerate all the possible combinations and generate the words.
The simplest way to do this is using a list comprehension.
-}
-- a)
stopsVowelsCombinations a b = [ (x, y, z) | x <- a, y <- b, z <- a ]
-- b)
stopsVowelsCombinationsP a b = [ (x, y, z) | x <- a, y <- b, z <- a, x == 'p' ]
-- c) the function from (a) doesn't need to change, actually
nouns = ["Dog", "Cat", "Elephant", "Zebra", "Monkey"]
verbs = ["chases", "claws", "bites", "eats"]
nounVerbCombinations a b = [ (x, y, z) | x <- a, y <- b, z <- a ]
-- 2. This function calculates the average length of the words in a string.
-- It's Type should be String -> Int
seekritFunc x =
div (sum (map length (words x)))
(length (words x))
-- 3.
seekritFunc' :: (Fractional a) => String -> a
seekritFunc' x =
(/) (realToFrac (sum (map length (words x))))
(realToFrac (length (words x)))
-- Rewriting Functions using Folds
-- 1.
myOr :: [Bool] -> Bool
myOr = foldr (||) False
-- 2.
myAny :: (a -> Bool) -> [a] -> Bool
myAny f = foldr (\a b -> f a || b) False
-- 3.
myElem :: Eq a => a -> [a] -> Bool
myElem x = foldr (\a b -> x == a || b) False
myElem' :: Eq a => a -> [a] -> Bool
myElem' x = any (== x)
-- 4.
myReverse :: [a] -> [a]
myReverse = foldl (flip (:)) []
-- 5.
myMap :: (a -> b) -> [a] -> [b]
myMap f = foldr (\a b -> f a : b ) []
-- 6.
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f = foldr (\a b -> if f a then a : b else b) []
-- 7.
squish :: [[a]] -> [a]
squish = foldr (++) []
-- 8.
squishMap :: (a -> [b]) -> [a] -> [b]
squishMap f = foldr (\a b -> f a ++ b) []
squishMap' f = foldr ((++) . f) []
-- 9.
squishAgain :: [[a]] -> [a]
squishAgain = squishMap id
-- 10.
myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
myMaximumBy _ [] = undefined
myMaximumBy f (x:xs) = foldl (\a b -> if f a b == GT then a else b) x xs
-- myMaximumBy f = foldl1 (\a b -> if f a b == GT then a else b)
-- 11.
myMinimumBy :: (a -> a -> Ordering) -> [a] -> a
myMinimumBy _ [] = undefined
myMinimumBy f (x:xs) = foldl (\a b -> if f a b == LT then a else b) x xs
| pdmurray/haskell-book-ex | src/ch10/Exercises10.10.hs | bsd-3-clause | 2,310 | 0 | 13 | 572 | 990 | 547 | 443 | 42 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -Wall #-}
-- |
-- Module : Network.Mail.Client.Gmail
-- License : BSD3
-- Maintainer : Enzo Haussecker
-- Stability : Experimental
-- Portability : Unknown
--
-- A dead simple SMTP Client for sending Gmail.
module Network.Mail.Client.Gmail (
-- ** Sending
sendGmail
-- ** Exceptions
, GmailException(..)
) where
import Control.Monad (forever, forM)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Control.Exception (Exception, bracket, throw)
import Data.Attoparsec.ByteString.Char8 as P
import Data.ByteString.Char8 as B (ByteString, pack)
import Data.ByteString.Base64.Lazy (encode)
import Data.ByteString.Lazy.Char8 as L (ByteString, hPutStrLn, readFile)
import Data.ByteString.Lazy.Search (replace)
import Data.Conduit
import Data.Conduit.Attoparsec (sinkParser)
import Data.Default (def)
import Data.Monoid ((<>))
import Data.Text as S (Text, pack)
import Data.Text.Lazy as L (Text, fromChunks)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Typeable (Typeable)
import Network (PortID(PortNumber), connectTo)
import Network.Mail.Mime hiding (renderMail)
import Network.TLS
import Network.TLS.Extra (ciphersuite_all)
import Prelude hiding (any, readFile)
import System.FilePath (takeExtension, takeFileName)
import System.IO hiding (readFile)
import System.Timeout (timeout)
data GmailException =
ParseError String
| Timeout
deriving (Show, Typeable)
instance Exception GmailException
-- |
-- Send an email from your Gmail account using the
-- simple message transfer protocol with transport
-- layer security. If you have 2-step verification
-- enabled on your account, then you will need to
-- retrieve an application specific password before
-- using this function. Below is an example using
-- ghci, where Alice sends an Excel spreadsheet to
-- Bob.
--
-- > >>> :set -XOverloadedStrings
-- > >>> :module Network.Mail.Mime Network.Mail.Client.Gmail
-- > >>> sendGmail "alice" "password" (Address (Just "Alice") "alice@gmail.com") [Address (Just "Bob") "bob@example.com"] [] [] "Excel Spreadsheet" "Hi Bob,\n\nThe Excel spreadsheet is attached.\n\nRegards,\n\nAlice" ["Spreadsheet.xls"] 10000000
--
sendGmail
:: L.Text -- ^ username
-> L.Text -- ^ password
-> Address -- ^ from
-> [Address] -- ^ to
-> [Address] -- ^ cc
-> [Address] -- ^ bcc
-> S.Text -- ^ subject
-> L.Text -- ^ body
-> [FilePath] -- ^ attachments
-> Int -- ^ timeout (in microseconds)
-> L.Text -- ^ client IP or FQDN
-> IO ()
sendGmail user pass from to cc bcc subject body attachments micros client = do
let handle = connectTo "smtp.gmail.com" $ PortNumber 587
bracket handle hClose $ \ hdl -> do
recvSMTP hdl micros "220"
sendSMTP hdl ehlo
recvSMTP hdl micros "250"
sendSMTP hdl "STARTTLS"
recvSMTP hdl micros "220"
let context = contextNew hdl params
bracket context cClose $ \ ctx -> do
handshake ctx
sendSMTPS ctx ehlo
recvSMTPS ctx micros "250"
sendSMTPS ctx "AUTH LOGIN"
recvSMTPS ctx micros "334"
sendSMTPS ctx username
recvSMTPS ctx micros "334"
sendSMTPS ctx password
recvSMTPS ctx micros "235"
sendSMTPS ctx sender
recvSMTPS ctx micros "250"
sendSMTPS ctx recipient
recvSMTPS ctx micros "250"
sendSMTPS ctx "DATA"
recvSMTPS ctx micros "354"
sendSMTPS ctx =<< mail
recvSMTPS ctx micros "250"
sendSMTPS ctx "QUIT"
recvSMTPS ctx micros "221"
where username = encode $ encodeUtf8 user
password = encode $ encodeUtf8 pass
ehlo = "EHLO " <> encodeUtf8 client
sender = "MAIL FROM: " <> angleBracket [from]
recipient = "RCPT TO: " <> angleBracket (to ++ cc ++ bcc)
mail = renderMail from to cc bcc subject body attachments
-- |
-- Consume the SMTP packet stream.
sink :: B.ByteString -> Sink (Maybe B.ByteString) (ResourceT IO) ()
sink code = (awaitForever $ maybe (throw Timeout) yield) =$= sinkParser (parser code)
-- |
-- Parse the SMTP packet stream.
parser :: B.ByteString -> P.Parser ()
parser code = do
reply <- P.take 3
if code /= reply
then throw . ParseError $ "Expected SMTP reply code " ++ show code ++ ", but recieved SMTP reply code " ++ show reply ++ "."
else anyChar >>= \ case
' ' -> return ()
'-' -> manyTill anyChar endOfLine >> parser code
_ -> throw $ ParseError "Unexpected character."
-- |
-- Define the TLS client parameters.
params :: ClientParams
params = (defaultParamsClient "smtp.gmail.com" "587")
{ clientSupported = def { supportedCiphers = ciphersuite_all }
, clientShared = def { sharedValidationCache = noValidate }
} where noValidate = ValidationCache (\_ _ _ -> return ValidationCachePass) -- This is not secure!
(\_ _ _ -> return ())
-- |
-- Terminate the TLS connection.
cClose :: Context -> IO ()
cClose ctx = bye ctx >> contextClose ctx
-- |
-- Display the first email address in the
-- given list using angle bracket formatting.
angleBracket :: [Address] -> L.ByteString
angleBracket = \ case [] -> ""; (Address _ email:_) -> "<" <> encodeUtf8 (fromChunks [email]) <> ">"
-- |
-- Send an unencrypted.
sendSMTP :: Handle -> L.ByteString -> IO ()
sendSMTP = L.hPutStrLn
-- |
-- Send an encrypted message.
sendSMTPS :: Context -> L.ByteString -> IO ()
sendSMTPS ctx msg = sendData ctx sent
where
sent = msg <> "\r\n"
-- |
-- Receive an unencrypted.
recvSMTP :: Handle -> Int -> B.ByteString -> IO ()
recvSMTP hdl micros code =
runResourceT $ source $$ sink code
where source = forever $ liftIO chunk >>= yield
chunk = timeout micros $ append <$> hGetLine hdl
append = flip (<>) "\n" . B.pack
-- |
-- Receive an encrypted message.
recvSMTPS :: Context -> Int -> B.ByteString -> IO ()
recvSMTPS ctx micros code =
runResourceT $ source $$ sink code
where source = forever $ liftIO chunk >>= yield
chunk = timeout micros $ recvData ctx
-- |
-- Render an email using the RFC 2822 message format.
renderMail
:: Address -- ^ from
-> [Address] -- ^ to
-> [Address] -- ^ cc
-> [Address] -- ^ bcc
-> S.Text -- ^ subject
-> L.Text -- ^ body
-> [FilePath] -- ^ attachments
-> IO L.ByteString
renderMail from to cc bcc subject body attach = do
parts <- forM attach $ \ path -> do
content <- readFile path
let mime = getMime $ takeExtension path
file = Just . S.pack $ takeFileName path
return $! [Part mime Base64 file [] content]
let plain = [Part "text/plain; charset=utf-8" QuotedPrintableText Nothing [] $ encodeUtf8 body]
mail <- renderMail' . Mail from to cc bcc headers $ plain : parts
return $! replace "\n." ("\n.." :: L.ByteString) mail <> "\r\n.\r\n"
where headers = [("Subject", subject)]
-- |
-- Get the mime type for the given file extension.
getMime :: String -> S.Text
getMime = \ case
".3dm" -> "x-world/x-3dmf"
".3dmf" -> "x-world/x-3dmf"
".a" -> "application/octet-stream"
".aab" -> "application/x-authorware-bin"
".aam" -> "application/x-authorware-map"
".aas" -> "application/x-authorware-seg"
".abc" -> "text/vnd.abc"
".acgi" -> "text/html"
".afl" -> "video/animaflex"
".ai" -> "application/postscript"
".aif" -> "audio/aiff"
".aifc" -> "audio/aiff"
".aiff" -> "audio/aiff"
".aim" -> "application/x-aim"
".aip" -> "text/x-audiosoft-intra"
".ani" -> "application/x-navi-animation"
".aos" -> "application/x-nokia-9000-communicator-add-on-software"
".aps" -> "application/mime"
".arc" -> "application/octet-stream"
".arj" -> "application/arj"
".art" -> "image/x-jg"
".asf" -> "video/x-ms-asf"
".asm" -> "text/x-asm"
".asp" -> "text/asp"
".asx" -> "application/x-mplayer2"
".au" -> "audio/basic"
".avi" -> "application/x-troff-msvideo"
".avs" -> "video/avs-video"
".bcpio" -> "application/x-bcpio"
".bin" -> "application/mac-binary"
".bm" -> "image/bmp"
".bmp" -> "image/bmp"
".boo" -> "application/book"
".book" -> "application/book"
".boz" -> "application/x-bzip2"
".bsh" -> "application/x-bsh"
".bz" -> "application/x-bzip"
".bz2" -> "application/x-bzip2"
".c" -> "text/plain"
".c++" -> "text/plain"
".cat" -> "application/vnd.ms-pki.seccat"
".cc" -> "text/plain"
".ccad" -> "application/clariscad"
".cco" -> "application/x-cocoa"
".cdf" -> "application/cdf"
".cer" -> "application/pkix-cert"
".cha" -> "application/x-chat"
".chat" -> "application/x-chat"
".class" -> "application/java"
".com" -> "application/octet-stream"
".conf" -> "text/plain"
".cpio" -> "application/x-cpio"
".cpp" -> "text/x-c"
".cpt" -> "application/mac-compactpro"
".crl" -> "application/pkcs-crl"
".crt" -> "application/pkix-cert"
".csh" -> "application/x-csh"
".css" -> "application/x-pointplus"
".cxx" -> "text/plain"
".dcr" -> "application/x-director"
".deepv" -> "application/x-deepv"
".def" -> "text/plain"
".der" -> "application/x-x509-ca-cert"
".dif" -> "video/x-dv"
".dir" -> "application/x-director"
".dl" -> "video/dl"
".doc" -> "application/msword"
".dot" -> "application/msword"
".dp" -> "application/commonground"
".drw" -> "application/drafting"
".dump" -> "application/octet-stream"
".dv" -> "video/x-dv"
".dvi" -> "application/x-dvi"
".dwf" -> "drawing/x-dwf (old)"
".dwg" -> "application/acad"
".dxf" -> "application/dxf"
".dxr" -> "application/x-director"
".el" -> "text/x-script.elisp"
".elc" -> "application/x-bytecode.elisp (compiled elisp)"
".env" -> "application/x-envoy"
".eps" -> "application/postscript"
".es" -> "application/x-esrehber"
".etx" -> "text/x-setext"
".evy" -> "application/envoy"
".exe" -> "application/octet-stream"
".f" -> "text/plain"
".f77" -> "text/x-fortran"
".f90" -> "text/plain"
".fdf" -> "application/vnd.fdf"
".fif" -> "application/fractals"
".fli" -> "video/fli"
".flo" -> "image/florian"
".flx" -> "text/vnd.fmi.flexstor"
".fmf" -> "video/x-atomic3d-feature"
".for" -> "text/plain"
".fpx" -> "image/vnd.fpx"
".frl" -> "application/freeloader"
".funk" -> "audio/make"
".g" -> "text/plain"
".g3" -> "image/g3fax"
".gif" -> "image/gif"
".gl" -> "video/gl"
".gsd" -> "audio/x-gsm"
".gsm" -> "audio/x-gsm"
".gsp" -> "application/x-gsp"
".gss" -> "application/x-gss"
".gtar" -> "application/x-gtar"
".gz" -> "application/x-compressed"
".gzip" -> "application/x-gzip"
".h" -> "text/plain"
".hdf" -> "application/x-hdf"
".help" -> "application/x-helpfile"
".hgl" -> "application/vnd.hp-hpgl"
".hh" -> "text/plain"
".hlb" -> "text/x-script"
".hlp" -> "application/hlp"
".hpg" -> "application/vnd.hp-hpgl"
".hpgl" -> "application/vnd.hp-hpgl"
".hqx" -> "application/binhex"
".hs" -> "text/x-haskell"
".hta" -> "application/hta"
".htc" -> "text/x-component"
".htm" -> "text/html"
".html" -> "text/html"
".htmls" -> "text/html"
".htt" -> "text/webviewhtml"
".htx" -> "text/html"
".ice" -> "x-conference/x-cooltalk"
".ico" -> "image/x-icon"
".idc" -> "text/plain"
".ief" -> "image/ief"
".iefs" -> "image/ief"
".iges" -> "application/iges"
".igs" -> "application/iges"
".ima" -> "application/x-ima"
".imap" -> "application/x-httpd-imap"
".inf" -> "application/inf"
".ins" -> "application/x-internett-signup"
".ip" -> "application/x-ip2"
".isu" -> "video/x-isvideo"
".it" -> "audio/it"
".iv" -> "application/x-inventor"
".ivr" -> "i-world/i-vrml"
".ivy" -> "application/x-livescreen"
".jam" -> "audio/x-jam"
".jav" -> "text/plain"
".java" -> "text/plain"
".jcm" -> "application/x-java-commerce"
".jfif" -> "image/jpeg"
".jfif-tbnl" -> "image/jpeg"
".jpe" -> "image/jpeg"
".jpeg" -> "image/jpeg"
".jpg" -> "image/jpeg"
".jps" -> "image/x-jps"
".js" -> "application/x-javascript"
".jut" -> "image/jutvision"
".kar" -> "audio/midi"
".ksh" -> "application/x-ksh"
".la" -> "audio/nspaudio"
".lam" -> "audio/x-liveaudio"
".latex" -> "application/x-latex"
".lha" -> "application/lha"
".lhx" -> "application/octet-stream"
".list" -> "text/plain"
".lma" -> "audio/nspaudio"
".log" -> "text/plain"
".lsp" -> "application/x-lisp"
".lst" -> "text/plain"
".lsx" -> "text/x-la-asf"
".ltx" -> "application/x-latex"
".lzh" -> "application/octet-stream"
".lzx" -> "application/lzx"
".m" -> "text/plain"
".m1v" -> "video/mpeg"
".m2a" -> "audio/mpeg"
".m2v" -> "video/mpeg"
".m3u" -> "audio/x-mpequrl"
".man" -> "application/x-troff-man"
".map" -> "application/x-navimap"
".mar" -> "text/plain"
".mbd" -> "application/mbedlet"
".mc$" -> "application/x-magic-cap-package-1.0"
".mcd" -> "application/mcad"
".mcf" -> "image/vasa"
".mcp" -> "application/netmc"
".me" -> "application/x-troff-me"
".mht" -> "message/rfc822"
".mhtml" -> "message/rfc822"
".mid" -> "application/x-midi"
".midi" -> "application/x-midi"
".mif" -> "application/x-frame"
".mime" -> "message/rfc822"
".mjf" -> "audio/x-vnd.audioexplosion.mjuicemediafile"
".mjpg" -> "video/x-motion-jpeg"
".mm" -> "application/base64"
".mme" -> "application/base64"
".mod" -> "audio/mod"
".moov" -> "video/quicktime"
".mov" -> "video/quicktime"
".movie" -> "video/x-sgi-movie"
".mp2" -> "audio/mpeg"
".mp3" -> "audio/mpeg3"
".mpa" -> "audio/mpeg"
".mpc" -> "application/x-project"
".mpe" -> "video/mpeg"
".mpeg" -> "video/mpeg"
".mpg" -> "audio/mpeg"
".mpga" -> "audio/mpeg"
".mpp" -> "application/vnd.ms-project"
".mpt" -> "application/x-project"
".mpv" -> "application/x-project"
".mpx" -> "application/x-project"
".mrc" -> "application/marc"
".ms" -> "application/x-troff-ms"
".mv" -> "video/x-sgi-movie"
".my" -> "audio/make"
".mzz" -> "application/x-vnd.audioexplosion.mzz"
".nap" -> "image/naplps"
".naplps" -> "image/naplps"
".nc" -> "application/x-netcdf"
".ncm" -> "application/vnd.nokia.configuration-message"
".nif" -> "image/x-niff"
".niff" -> "image/x-niff"
".nix" -> "application/x-mix-transfer"
".nsc" -> "application/x-conference"
".nvd" -> "application/x-navidoc"
".o" -> "application/octet-stream"
".oda" -> "application/oda"
".omc" -> "application/x-omc"
".omcd" -> "application/x-omcdatamaker"
".omcr" -> "application/x-omcregerator"
".p" -> "text/x-pascal"
".p10" -> "application/pkcs10"
".p12" -> "application/pkcs-12"
".p7a" -> "application/x-pkcs7-signature"
".p7c" -> "application/pkcs7-mime"
".p7m" -> "application/pkcs7-mime"
".p7r" -> "application/x-pkcs7-certreqresp"
".p7s" -> "application/pkcs7-signature"
".part" -> "application/pro_eng"
".pas" -> "text/pascal"
".pbm" -> "image/x-portable-bitmap"
".pcl" -> "application/vnd.hp-pcl"
".pct" -> "image/x-pict"
".pcx" -> "image/x-pcx"
".pdb" -> "chemical/x-pdb"
".pdf" -> "application/pdf"
".pfunk" -> "audio/make"
".pgm" -> "image/x-portable-graymap"
".pic" -> "image/pict"
".pict" -> "image/pict"
".pkg" -> "application/x-newton-compatible-pkg"
".pko" -> "application/vnd.ms-pki.pko"
".pl" -> "text/plain"
".plx" -> "application/x-pixclscript"
".pm" -> "image/x-xpixmap"
".pm4" -> "application/x-pagemaker"
".pm5" -> "application/x-pagemaker"
".png" -> "image/png"
".pnm" -> "application/x-portable-anymap"
".pot" -> "application/mspowerpoint"
".pov" -> "model/x-pov"
".ppa" -> "application/vnd.ms-powerpoint"
".ppm" -> "image/x-portable-pixmap"
".pps" -> "application/mspowerpoint"
".ppt" -> "application/mspowerpoint"
".ppz" -> "application/mspowerpoint"
".pre" -> "application/x-freelance"
".prt" -> "application/pro_eng"
".ps" -> "application/postscript"
".psd" -> "application/octet-stream"
".pvu" -> "paleovu/x-pv"
".pwz" -> "application/vnd.ms-powerpoint"
".py" -> "text/x-script.phyton"
".pyc" -> "applicaiton/x-bytecode.python"
".qcp" -> "audio/vnd.qcelp"
".qd3" -> "x-world/x-3dmf"
".qd3d" -> "x-world/x-3dmf"
".qif" -> "image/x-quicktime"
".qt" -> "video/quicktime"
".qtc" -> "video/x-qtc"
".qti" -> "image/x-quicktime"
".qtif" -> "image/x-quicktime"
".ra" -> "audio/x-pn-realaudio"
".ram" -> "audio/x-pn-realaudio"
".ras" -> "application/x-cmu-raster"
".rast" -> "image/cmu-raster"
".rexx" -> "text/x-script.rexx"
".rf" -> "image/vnd.rn-realflash"
".rgb" -> "image/x-rgb"
".rm" -> "application/vnd.rn-realmedia"
".rmi" -> "audio/mid"
".rmm" -> "audio/x-pn-realaudio"
".rmp" -> "audio/x-pn-realaudio"
".rng" -> "application/ringing-tones"
".rnx" -> "application/vnd.rn-realplayer"
".roff" -> "application/x-troff"
".rp" -> "image/vnd.rn-realpix"
".rpm" -> "audio/x-pn-realaudio-plugin"
".rt" -> "text/richtext"
".rtf" -> "application/rtf"
".rtx" -> "application/rtf"
".rv" -> "video/vnd.rn-realvideo"
".s" -> "text/x-asm"
".s3m" -> "audio/s3m"
".saveme" -> "application/octet-stream"
".sbk" -> "application/x-tbook"
".scm" -> "application/x-lotusscreencam"
".sdml" -> "text/plain"
".sdp" -> "application/sdp"
".sdr" -> "application/sounder"
".sea" -> "application/sea"
".set" -> "application/set"
".sgm" -> "text/sgml"
".sgml" -> "text/sgml"
".sh" -> "application/x-bsh"
".shar" -> "application/x-bsh"
".shtml" -> "text/html"
".sid" -> "audio/x-psid"
".sit" -> "application/x-sit"
".skd" -> "application/x-koan"
".skm" -> "application/x-koan"
".skp" -> "application/x-koan"
".skt" -> "application/x-koan"
".sl" -> "application/x-seelogo"
".smi" -> "application/smil"
".smil" -> "application/smil"
".snd" -> "audio/basic"
".sol" -> "application/solids"
".spc" -> "application/x-pkcs7-certificates"
".spl" -> "application/futuresplash"
".spr" -> "application/x-sprite"
".sprite" -> "application/x-sprite"
".src" -> "application/x-wais-source"
".ssi" -> "text/x-server-parsed-html"
".ssm" -> "application/streamingmedia"
".sst" -> "application/vnd.ms-pki.certstore"
".step" -> "application/step"
".stl" -> "application/sla"
".stp" -> "application/step"
".sv4cpio" -> "application/x-sv4cpio"
".sv4crc" -> "application/x-sv4crc"
".svf" -> "image/vnd.dwg"
".svr" -> "application/x-world"
".swf" -> "application/x-shockwave-flash"
".t" -> "application/x-troff"
".talk" -> "text/x-speech"
".tar" -> "application/x-tar"
".tbk" -> "application/toolbook"
".tcl" -> "application/x-tcl"
".tcsh" -> "text/x-script.tcsh"
".tex" -> "application/x-tex"
".texi" -> "application/x-texinfo"
".texinfo" -> "application/x-texinfo"
".text" -> "application/plain"
".tgz" -> "application/gnutar"
".tif" -> "image/tiff"
".tiff" -> "image/tiff"
".tr" -> "application/x-troff"
".tsi" -> "audio/tsp-audio"
".tsp" -> "application/dsptype"
".tsv" -> "text/tab-separated-values"
".turbot" -> "image/florian"
".txt" -> "text/plain"
".uil" -> "text/x-uil"
".uni" -> "text/uri-list"
".unis" -> "text/uri-list"
".unv" -> "application/i-deas"
".uri" -> "text/uri-list"
".uris" -> "text/uri-list"
".ustar" -> "application/x-ustar"
".uu" -> "application/octet-stream"
".uue" -> "text/x-uuencode"
".vcd" -> "application/x-cdlink"
".vcs" -> "text/x-vcalendar"
".vda" -> "application/vda"
".vdo" -> "video/vdo"
".vew" -> "application/groupwise"
".viv" -> "video/vivo"
".vivo" -> "video/vivo"
".vmd" -> "application/vocaltec-media-desc"
".vmf" -> "application/vocaltec-media-file"
".voc" -> "audio/voc"
".vos" -> "video/vosaic"
".vox" -> "audio/voxware"
".vqe" -> "audio/x-twinvq-plugin"
".vqf" -> "audio/x-twinvq"
".vql" -> "audio/x-twinvq-plugin"
".vrml" -> "application/x-vrml"
".vrt" -> "x-world/x-vrt"
".vsd" -> "application/x-visio"
".vst" -> "application/x-visio"
".vsw" -> "application/x-visio"
".w60" -> "application/wordperfect6.0"
".w61" -> "application/wordperfect6.1"
".w6w" -> "application/msword"
".wav" -> "audio/wav"
".wb1" -> "application/x-qpro"
".wbmp" -> "image/vnd.wap.wbmp"
".web" -> "application/vnd.xara"
".wiz" -> "application/msword"
".wk1" -> "application/x-123"
".wmf" -> "windows/metafile"
".wml" -> "text/vnd.wap.wml"
".wmlc" -> "application/vnd.wap.wmlc"
".wmls" -> "text/vnd.wap.wmlscript"
".wmlsc" -> "application/vnd.wap.wmlscriptc"
".word" -> "application/msword"
".wp" -> "application/wordperfect"
".wp5" -> "application/wordperfect"
".wp6" -> "application/wordperfect"
".wpd" -> "application/wordperfect"
".wq1" -> "application/x-lotus"
".wri" -> "application/mswrite"
".wrl" -> "application/x-world"
".wrz" -> "model/vrml"
".wsc" -> "text/scriplet"
".wsrc" -> "application/x-wais-source"
".wtk" -> "application/x-wintalk"
".xbm" -> "image/x-xbitmap"
".xdr" -> "video/x-amt-demorun"
".xgz" -> "xgl/drawing"
".xif" -> "image/vnd.xiff"
".xl" -> "application/excel"
".xla" -> "application/excel"
".xlb" -> "application/excel"
".xlc" -> "application/excel"
".xld" -> "application/excel"
".xlk" -> "application/excel"
".xll" -> "application/excel"
".xlm" -> "application/excel"
".xls" -> "application/excel"
".xlt" -> "application/excel"
".xlv" -> "application/excel"
".xlw" -> "application/excel"
".xm" -> "audio/xm"
".xml" -> "application/xml"
".xmz" -> "xgl/movie"
".xpix" -> "application/x-vnd.ls-xpix"
".xpm" -> "image/x-xpixmap"
".x-png" -> "image/png"
".xsr" -> "video/x-amt-showrun"
".xwd" -> "image/x-xwd"
".xyz" -> "chemical/x-pdb"
".z" -> "application/x-compress"
".zip" -> "application/x-compressed"
".zoo" -> "application/octet-stream"
".zsh" -> "text/x-script.zsh"
_ -> "application/octet-stream"
| abailly/smtps-gmail | Network/Mail/Client/Gmail.hs | bsd-3-clause | 24,925 | 0 | 17 | 6,968 | 4,537 | 2,335 | 2,202 | 592 | 449 |
{-# LANGUAGE UndecidableInstances, FlexibleInstances, TypeSynonymInstances #-}
{-# OPTIONS_HADDOCK prune, show-extensions #-}
-----------------------------------------------------------------------------
-- |
-- Module : ForSyDe.Core.Utility.Plot
-- Copyright : (c) George Ungureanu, KTH/ICT/ESY 2015-2017
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : ugeorge@kth.se
-- Stability : experimental
-- Portability : portable
--
-- This module imports plotting and data dumping functions working
-- with "plottable" data types, i.e. instances of the 'Plot' and
-- 'Plottable' type classes.
-----------------------------------------------------------------------------
module ForSyDe.Atom.Utility.Plot (
-- * User API
-- | The following commands are frequently used as part of the
-- normal modeling routine.
-- ** Configuration settings
Config(..), defaultCfg, silentCfg, noJunkCfg,
-- ** Data preparation
prepare, prepareL, prepareV,
-- ** Dumping and plotting data
showDat, dumpDat, plotGnu, heatmapGnu,
showLatex, dumpLatex, plotLatex,
-- * The data types
-- | Below the data types involved are shown and the plottable
-- structures are documented.
Plottable(..), Plot(..), PInfo(..), Samples, PlotData
) where
import Control.Arrow
import Control.Exception
import Control.Monad (unless, when)
import Data.List (intercalate, intersperse, unwords)
import System.Directory (createDirectoryIfMissing)
import System.Exit (ExitCode(..))
import System.Process
import qualified ForSyDe.Atom.ExB.Absent as AE (
AbstExt(..))
import qualified ForSyDe.Atom.MoC.SY.Core as SY (
Signal, SY(..), signal )
import qualified ForSyDe.Atom.MoC.DE.Core as DE (
SignalBase, DE(..), signal )
import qualified ForSyDe.Atom.MoC.DE.React.Core as RE (
SignalBase, RE(..), signal )
import qualified ForSyDe.Atom.MoC.CT.Core as CT (
Signal, CT(..), signal, evalTs, tag)
import qualified ForSyDe.Atom.MoC.SDF.Core as SDF (
Signal, SDF(..), signal)
import qualified ForSyDe.Atom.MoC.TimeStamp as Ts (
TimeStamp )
import qualified ForSyDe.Atom.MoC.Time as T (
Time )
import ForSyDe.Atom.MoC.Stream (
Stream(..), fromStream, takeS)
import qualified ForSyDe.Atom.Skel.Vector as V (
Vector(..), fromVector, take, vector)
import qualified ForSyDe.Atom.Prob as P (
Histogram(..)
)
-------------------------- TYPES --------------------------
-- | Record structure containing configuration settings for the
-- plotting commands.
data Config =
Cfg { verbose :: Bool -- ^ verbose printouts on terminal
, path :: String -- ^ directory where all dumped files will be found
, title :: String -- ^ base name for dumped files
, rate :: Float -- ^ sample rate if relevant. Useful for explicit-tagged signals, ignored otherwise.
, xmax :: Float -- ^ Maximum X coordinate. Mandatory for infinite structures, optional otherwise.
, labels :: [String] -- ^ list of labels with the names of the structures plotted
, fire :: Bool -- ^ if relevant, fires a plotting or compiling program.
, other :: Bool -- ^ if relevant, dumps additional scripts and plots.
} deriving (Show)
-- | Default configuration: verbose, dump everything possible, fire
-- whatever program needed. Check source for settings.
--
-- Example usage:
--
-- >>> defaultCfg {xmax = 15, verbose = False, labels = ["john","doe"]}
-- Cfg {verbose = False, path = "./fig", title = "plot", rate = 1.0e-2, xmax = 15.0, labels = ["john","doe"], fire = True, other = True}
defaultCfg = Cfg { path = "./fig"
, title = "plot"
, rate = 0.01
, xmax = 200
, labels = replicate 10 ""
, verbose = True
, fire = True
, other = True
}
-- | Silent configuration: does not fire any program or print our
-- unnecessary info. Check source for settings.
silentCfg = Cfg { path = "./fig"
, title = "plot"
, rate = 0.01
, xmax = 200
, labels = replicate 10 ""
, verbose = False
, fire = False
, other = True
}
-- | Clean configuration: verbose, does not dump more than necessary,
-- fire whatever program needed. Check source for settings.
noJunkCfg = Cfg { path = "./fig"
, title = "plot"
, rate = 0.01
, xmax = 200
, labels = repeat ""
, verbose = True
, fire = True
, other = False
}
-- | Static information of each plottable data type.
data PInfo = Info { typeid :: String -- ^ id used usually in implicit tags
, command :: String -- ^ LaTeX identifier
, measure :: String -- ^ unit of measure
, style :: String -- ^ style tweaking in the GNUplot script
, stacking:: Bool -- ^ if the plot is stacking
, sparse :: Bool -- ^ if the sampled data is sparse instead of dense
} deriving (Show)
-- | Alias for sampled data
type Samples = [(String, String)]
-- | Alias for a data set 'prepare'd to be plotted.
type PlotData = (Config, PInfo, [(String,Samples)])
-------------------------- CLASSES --------------------------
-- | This class gathers all ForSyDe-Atom structures that can be
-- plotted.
class Plot a where
{-# MINIMAL (sample | sample') , takeUntil, getInfo #-}
-- | Samples the data according to a given step size.
sample :: Float -> a -> Samples
sample _ = sample'
------------------------
-- | Samples the data according to the internal structure.
sample' :: a -> Samples
sample' = sample 0.00001
------------------------
-- | Takes the first samples until a given tag.
takeUntil :: Float -> a -> a
------------------------
-- | Returns static information about the data type.
getInfo :: a -> PInfo
------------------------
-- | This class gathers types which can be sampled and converted to a
-- numerical string which can be read and interpreted by a plotter
-- engine.
class Plottable a where
-- | Transforms the input type into a coordinate string.
toCoord :: a -> String
-------------------------- INSTANCES --------------------------
-- | Time stamps
instance {-# OVERLAPPING #-} Plottable Ts.TimeStamp where
toCoord = init . show
-- | Absent-extended plottable types
instance (Show a, Plottable a) => Plottable (AE.AbstExt a) where
-- toCoord = show
toCoord AE.Abst = "_"
toCoord (AE.Prst a) = toCoord a
-- | Vectors of plottable types
instance (Plottable a) => Plottable (V.Vector a) where
toCoord = (++) "<" . unwords . map toCoord . V.fromVector
-- toCoord = concat . map (\v -> (show $ realToFrac v) ++ " ") .
-- V.fromVector
-- | Real numbers that can be converted to a floating point representation
instance {-# OVERLAPPABLE #-} (Show a, Real a) => Plottable a where
toCoord = show . realToFrac
-- | For plotting 'ForSyDe.Atom.MoC.SDF.SDF' signals.
instance Plottable a => Plot (SDF.Signal a) where
sample' = zip (map show [0..]) . fromStream . fmap vToSamp
where vToSamp (SDF.SDF a) = toCoord a
------------------------
takeUntil n = takeS (truncate n)
------------------------
getInfo _ = Info { typeid = "sig-sdf"
, command = "SY"
, measure = "token"
, style = "impulses lw 3"
, stacking = True
, sparse = False
}
-- | 'ForSyDe.Atom.MoC.SY.SY' signals.
instance Plottable a => Plot (SY.Signal a) where
sample' = zip (map show [0..]) . fromStream . fmap vToSamp
where vToSamp (SY.SY a) = toCoord a
------------------------
takeUntil n = takeS (truncate n)
------------------------
getInfo _ = Info { typeid = "sig-sy"
, command = "SY"
, measure = "sample"
, style = "impulses lw 3"
, stacking = True
, sparse = False
}
-- | For plotting 'ForSyDe.Atom.MoC.DE.DE' signals.
instance (Plottable a, Show t, Real t, Fractional t, Num t, Ord t, Eq t) =>
Plot (DE.SignalBase t a) where
sample' = map v2s . fromStream
where v2s (DE.DE t v) = (toCoord t, toCoord v)
-- sample' sig = concat $ zipWith v2s ((head lst):lst) lst
-- where lst = fromStream sig
-- v2s (DE.DE pt pv) (DE.DE t v)
-- = [(toCoord t, toCoord pv), (toCoord t, toCoord v)]
------------------------
takeUntil n = until (realToFrac n)
where until _ NullS = NullS
until u (DE.DE t v:-NullS)
| t < u = DE.DE t v :- DE.DE u v :- NullS
| otherwise = DE.DE u v :- NullS
until u (DE.DE t v:-xs)
| t < u = DE.DE t v :- until u xs
| otherwise = DE.DE u v :- NullS
------------------------
getInfo _ = Info { typeid = "sig-de"
, command = "DE"
, measure = "timestamp"
, style = "lines lw 2"
, stacking = False
, sparse = True
}
-- | For plotting 'ForSyDe.Atom.MoC.RE.React.RE' signals.
instance (Plottable a, Show t, Real t, Fractional t, Num t, Ord t, Eq t) =>
Plot (RE.SignalBase t a) where
sample' = map v2s . fromStream
where v2s (RE.RE t v) = (toCoord t, toCoord v)
-- sample' sig = concat $ zipWith v2s ((head lst):lst) lst
-- where lst = fromStream sig
-- v2s (RE.RE pt pv) (RE.RE t v)
-- = [(toCoord t, toCoord pv), (toCoord t, toCoord v)]
------------------------
takeUntil n = until (realToFrac n)
where until _ NullS = NullS
until u (RE.RE t v:-NullS)
| t < u = RE.RE t v :- RE.RE u v :- NullS
| otherwise = RE.RE u v :- NullS
until u (RE.RE t v:-xs)
| t < u = RE.RE t v :- until u xs
| otherwise = RE.RE u v :- NullS
------------------------
getInfo _ = Info { typeid = "sig-de"
, command = "RE"
, measure = "timestamp"
, style = "lines lw 2"
, stacking = False
, sparse = True
}
-- | For plotting 'ForSyDe.Atom.MoC.CT.CT' signals.
instance (Plottable a) => Plot (CT.Signal a) where
sample stepsize = evalSamples 0
where evalSamples t s@(x:-y:-xs)
| CT.tag y <= t = evalSamples t (y:-xs)
| otherwise = (toCoord t,
toCoord $ CT.evalTs t x) :
evalSamples (t + step) s
evalSamples _ (_:-NullS) = []
evalSamples _ NullS = []
step = realToFrac stepsize
------------------------
takeUntil n = until (realToFrac n)
where until _ NullS = NullS
until u (CT.CT t p f:-NullS)
| t < u = CT.CT t p f :- CT.CT u p f :- NullS
| otherwise = CT.CT u p f :- NullS
until u (CT.CT t p f:-xs)
| t < u = CT.CT t p f :- until u xs
| otherwise = CT.CT u p f :- NullS
------------------------
getInfo _ = Info { typeid = "sig-ct"
, command = "CT"
, measure = "time (s)"
, style = "lines"
, stacking = False
, sparse = False
}
-- | For plotting vectors of coordinates
instance Plottable a => Plot (V.Vector a) where
sample' = zip (map show [1..]) . V.fromVector . fmap toCoord
------------------------
takeUntil n = V.take (truncate n)
------------------------
getInfo _ = Info { typeid = "vect"
, command = "NONE"
, measure = "index"
, style = "impulses lw 3"
, stacking = True
, sparse = False
}
-- | For plotting vectors of coordinates
instance Plot P.Histogram where
sample' = map (toCoord *** toCoord) . P.getBins
------------------------
takeUntil n = P.Hist . take (truncate n) . P.getBins
------------------------
getInfo _ = Info { typeid = "hist"
, command = "HIST"
, measure = "bin"
, style = "boxes"
, stacking = True
, sparse = False
}
-------------------------- PREPARE --------------------------
-- | Prepares a single plottable data structure to be dumped and/or
-- plotted.
prepare :: (Plot a)
=> Config -- ^ configuration settings
-> a -- ^ plottable data type
-> PlotData -- ^ structure ready for dumping
prepare cfg = prepareL cfg . (:[])
-- | Prepares a vector of plottable data structures to be dumped
-- and/or plotted. See 'prepare'.
prepareV :: (Plot a) => Config -> V.Vector a -> PlotData
prepareV cfg = prepareL cfg . V.fromVector
-- | Prepares a list of plottable data structures to be dumped and/or
-- plotted. See 'prepare'.
prepareL :: (Plot a) => Config -> [a] -> PlotData
prepareL cfg x = (cfg, getInfo (head x), zipWith3 prep [1..] lbls x)
where prep i l s = (mkLbl i l s, sample sr $ takeUntil supx s)
mkLbl i "" s = typeid (getInfo s) ++ show i
mkLbl _ l _ = l
-- extract settings
lbls = labels cfg
sr = rate cfg
supx = xmax cfg
-------------------------- SAMPLE DATA --------------------------
-- | Prints out the sampled contents of a 'prepare'd data set.
showDat :: PlotData -> IO ()
showDat (_,_,pdata) = putStrLn $ intercalate "\n\n" $ map showD pdata
where
showD (label,samp) = label ++ " = \n"
++ intercalate "\n" (map showS samp)
showS (tag,value) = "\t" ++ tag ++ "\t" ++ value
-- | Dumps the sampled contents of a 'prepare'd data set into separate
-- @.dat@ files.
dumpDat :: PlotData -> IO [String]
dumpDat (cfg, _, pdata) = do
createDirectoryIfMissing True dpath
files <- mapM dump pdata
when verb $ putStrLn ("Dumped " ++ allLabels ++ " in " ++ dpath)
return files
where
dump (lbl,samp) = let name = mkFileNm lbl
in do writeFile name (dumpSamp samp)
return name
mkFileNm label = dpath ++ "/" ++ replChar "$<>{}" '_' label ++ ".dat"
dumpSamp = concatMap (\(x,y) -> x ++" "++ y ++ "\n")
allLabels= drop 2 $ foldl (\s (l,_)-> s ++ ", " ++ l) "" pdata
-- extract settings
dpath = path cfg
verb = verbose cfg
-------------------------- GNUPLOT --------------------------
-- | Generates a GNUplot script and @.dat@ files for plotting the
-- sampled contents of a 'prepare'd data set. Depending on the
-- configuration settings, it also dumps LaTeX and PDF plots, and
-- fires the script.
--
-- __OBS:__ needless to say that <http://www.gnuplot.info/ GNUplot>
-- needs to be installed in order to use this command. Also, in order
-- to fire GNUplot from a ghci session you might need to install
-- @gnuplot-x11@.
plotGnu :: PlotData -> IO ()
plotGnu pdata@(cfg,info,samps) = do
datFiles <- dumpDat $ alterForGnuPlot pdata
-- Write the gnuplot title to a file; Try several times to be able
-- to open multiple plots in the same session
script <- tryNTimes 10 basename $ writePlotScript datFiles
_ <- if fireGnuplot then system ("gnuplot -persist " ++ script)
else return ExitSuccess
when isVerbose $ putStrLn ("Signal(s) " ++ allLabels ++ " plotted.")
where
writePlotScript dat f = writeFile f $ mkPlotScript cfg info dat
allLabels = drop 2 $ foldl (\s (l,_)-> s ++ ", " ++ l) "" samps
-- extract settings
fireGnuplot = fire cfg
isVerbose = verbose cfg
basename = path cfg ++ "/" ++ title cfg
-- | Similar to 'plotGnu' but creates a heatmap plot using the GNUplot
-- engine. For this, the input needs to contain at least two columns
-- of data, otherwise the plot does not show anything, i.e. the
-- samples need to be lists or vectors of two or more elements.
--
-- __OBS:__ same dependencies are needed as for 'plotGnu'.
heatmapGnu :: PlotData -> IO ()
heatmapGnu pdata@(cfg,info,samps) = do
datFiles <- dumpDat $ alterForGnuHeatmap pdata
script <- tryNTimes 10 basename $ writeHeatmapScript datFiles
_ <- if fireGnuplot then system ("gnuplot -persist " ++ script)
else return ExitSuccess
when isVerbose $ putStrLn ("Signal(s) " ++ allLabels ++ " plotted"
++ " as heatmaps.")
where
writeHeatmapScript dat f = writeFile f $ mkHeatmapScript cfg info dat
allLabels = drop 2 $ foldl (\s (l,_)-> s ++ ", " ++ l) "" samps
-- extract settings
fireGnuplot = fire cfg
isVerbose = verbose cfg
basename = path cfg ++ "/" ++ title cfg ++ "-heat"
----------- not exported -----------
alterForGnuPlot :: PlotData -> PlotData
alterForGnuPlot (cfg,info,lsamp) = (cfg, info, map alter lsamp)
where
alter (label, samp)
| sparse info = (label, map handler $ mkDe samp)
| otherwise = (label, map handler samp)
mkDe samp@(fs:_) = concat $ zipWith dup (fs:samp) samp
dup (pt,pv) (t,v) = [(t,pv), (t,v)]
handler (t,"_") = (t,"\n")
handler (t,v)
| head v == '<' = (t, tail v)
| otherwise = (t, v)
alterForGnuHeatmap :: PlotData -> PlotData
alterForGnuHeatmap (cfg,info,lsamp) = (cfg, info, map alter lsamp)
where
alter (label, samp)
| sparse info = (label, map noTag $ mkDe $ map handler samp)
| otherwise = (label, map (noTag . handler) samp)
mkDe [] = []
mkDe ((t,v):[]) = [(t,v)]
mkDe ((t,v):(ft,fv):xs)
| itfl >= ftfl = (t,v) : mkDe ((ft,fv):xs)
| otherwise = (t,v) : mkDe ((show itfl,v):(ft,fv):xs)
where itfl =(read t::Float) + (rate cfg)
ftfl = read ft::Float
noTag (_,v) = ("",v)
handler (t,"_") = (t,"0")
handler (t,v)
| head v == '<' = (t, tail v)
| otherwise = (t, v)
mkPlotScript :: Config -> PInfo -> [FilePath] -> String
mkPlotScript cfg info files =
(if plotTitle == "plot" then "" else "set title \"" ++ plotTitle ++ "\"\n")
++ "set xlabel \"" ++ unitOfMeasure ++ "\" \n"
++ (if command info == "HIST" then
"set style fill solid\nset boxwidth 0.5\n"
else "")
++ "set xzeroaxis\n"
++ "plot " ++ plotCmds ++ "\n"
++ epsCmd ++ latexCmd ++ pdfCmd
where
plotCmds = intercalate ",\\\n " $ zipWith3 pCmd [0..] files plotLb
pCmd i f l = "\t\"" ++ f ++ "\"" ++ stackCmd i ++ " with "
++ plotStyle ++ " title \""++ l ++ "\""
stackCmd i = if isStacking then
" using ($1+0." ++ show i ++ "):2"
else ""
epsCmd = if plotOther then
"set terminal postscript eps color\n"
++ "set output \"" ++ plotName ++".eps\"\n"
++ "replot \n"
else ""
latexCmd = if plotOther then
"set terminal epslatex color\n"
++ "set output \"" ++ plotName ++"-latex.eps\"\n"
++ "replot\n"
else ""
pdfCmd = if plotOther then
"set terminal pdf\n"
++ "set output \"" ++ plotName ++".pdf\"\n"
++ "replot\n"
else ""
plotName = plotPath ++ "/" ++ plotId ++ "-" ++ plotTitle
-- extract styles
unitOfMeasure = measure info
plotStyle = style info
plotId = typeid info
isStacking = stacking info
-- extract settings
plotPath = path cfg
plotTitle = title cfg
plotOther = other cfg
plotLb = labels cfg
mkHeatmapScript :: Config -> PInfo -> [FilePath] -> String
mkHeatmapScript cfg info files =
(if plotTitle == "plot" then "" else "set title \"" ++ plotTitle ++ "\"\n")
++ "set xlabel \"index\" \n"
++ "set ylabel \"" ++ unitOfMeasure ++ "\" \n"
++ "set yrange [-0.5" ++ scale ++ ":" ++ plotXmax
++ "+0.5" ++ scale ++ "]\n"
++ "set palette rgbformula -7,2,-7\n"
++ "set multiplot layout 1," ++ show (length files) ++ "\n"
++ plotCmds ++ "\n"
++ "unset multiplot\n"
++ epsCmd ++ latexCmd ++ pdfCmd
where
plotCmds = intercalate ",\n" $ zipWith3 pCmd [0..] files plotLb
pCmd i f l = "set title \"" ++ l ++ "\"\n"
++ "plot \"" ++ f ++ "\" matrix "
++ "using 1:" ++ scaley ++ ":3 "
++ "with image title \"\""
epsCmd = if plotOther then
"set terminal postscript eps color\n"
++ "set output \"" ++ plotName ++".eps\"\n"
++ "replot \n"
else ""
latexCmd = if plotOther then
"set terminal epslatex color\n"
++ "set output \"" ++ plotName ++"-latex.eps\"\n"
++ "replot\n"
else ""
pdfCmd = if plotOther then
"set terminal pdf\n"
++ "set output \"" ++ plotName ++".pdf\"\n"
++ "replot\n"
else ""
plotName = plotPath ++ "/" ++ plotId ++ "-" ++ plotTitle
-- extract styles
unitOfMeasure = measure info
plotStyle = style info
plotId = typeid info
isStacking = stacking info
isSparse = sparse info
scale = if isSparse then "*" ++ plotRate else ""
scaley = if isSparse then "($2*"++ plotRate ++ ")" else "2"
-- extract settings
plotPath = path cfg
plotTitle = title cfg
plotOther = other cfg
plotLb = labels cfg
plotXmax = show $ xmax cfg
plotRate = show $ rate cfg
-------------------------- LATEX --------------------------
-- | Prints out a LaTeX environment from a 'prepare'd data set. This
-- environment should be paste inside a @tikzpicture@ in a document
-- title which imports the ForSyDe-LaTeX package.
showLatex :: PlotData -> IO ()
showLatex pdata = putStrLn $ mkLatex pdata
-- | Dumps a set of formatted data files with the extension @.flx@
-- that can be imported by a LaTeX document which uses the
-- ForSyDe-LaTeX package.
dumpLatex :: PlotData -> IO [String]
dumpLatex (cfg, _, pdata) = do
createDirectoryIfMissing True dpath
files <- mapM dump pdata
when verb $ putStrLn ("Dumped " ++ allLabels ++ " in " ++ dpath)
return files
where
dump (lbl,samp) = let name = mkFileNm lbl
in do writeFile name (dumpSamp samp)
return name
mkFileNm label = dpath ++ "/" ++ replChar "$<>{}" '_' label ++ ".flx"
dumpSamp = intercalate ",\n" . map (\(x,y) -> y ++" : "++ x)
allLabels= drop 2 $ foldl (\s (l,_)-> s ++ ", " ++ l) "" pdata
-- extract settings
dpath = path cfg
verb = verbose cfg
-- | Creates a standalone LaTeX document which uses the ForSyDe-LaTeX
-- package, plotting a 'prepare'd data set. Depending on the
-- configuration settings, the command @pdflatex@ may also be invoked
-- to compile a pdf image.
--
-- __OBS:__ A LaTeX compiler is required to run the @pdflatex@
-- command. The <https://github.com/forsyde/forsyde-latex ForSyDe-LaTeX>
-- package also needs to be installed according to the instructions on
-- the project web page.
plotLatex :: PlotData -> IO ()
plotLatex pdata@(cfg,_,_) = do
createDirectoryIfMissing True filepath
writeFile filename $ mkLatexFile $ mkLatex pdata
when isVerbose $ putStrLn ("Dumped LaTeX title " ++ filename)
_ <- if fireLatex then
system ("pdflatex -output-directory=" ++ filepath
++ " " ++ filename)
else return ExitSuccess
when (isVerbose && fireLatex) $ putStrLn ("Compiled PDF in " ++ filepath)
where
-- extract settings
isVerbose = verbose cfg
filename = path cfg ++ "/" ++ title cfg ++ ".tex"
filepath = path cfg
fireLatex = fire cfg
----------- not exported -----------
alterForLatex :: PlotData -> PlotData
alterForLatex (cfg,info,lsamp) = (cfg, info, map alter lsamp)
where
alter (label, samp) = (label, map handler samp)
handler (t,"_") = (t,"$\\bot$")
handler (t,v)
| head v == '<' = (t, "$\\langle$ "
++ tail v
++ " $\\rangle$")
| otherwise = (t, v)
mkLatex :: PlotData -> String
mkLatex = latexCmd . alterForLatex
where
latexCmd (cfg, info, lsamp)
-- SIGNAL plots
| command info `elem` ["SY","DE","RE","CT"] =
" \\begin{signals" ++ mocStr ++ "}[]{"
++ lastX ++ "}\n"
++ concatMap toSignal lsamp
++ " \\end{signals" ++ mocStr ++ "}\n"
-- HISTOGRAM plots
| command info `elem` ["HIST"] =
" \\begin{axis}[ybar,ytick=\\empty,axis x line*=bottom,axis y line*=left]\n"
++ concatMap toPlot lsamp
++ "\n \\end{axis}\n"
| otherwise = error "mkLatex: plot for this type not implemented."
where
------ SIGNAL helpers ------
toSignal (label,samp) =
" \\signal" ++ mocStr ++ "[name= " ++ label ++ "]{"
++ intercalate "," (map showEvent samp) ++ "}\n"
showEvent (t,v) = v ++ ":" ++ t
mocStr = command info
lastX = show $ xmax cfg
------ HISTOGRAM helpers ------
toPlot (_,sp) = " \\addplot coordinates {" ++ concatMap showBin sp ++ "};"
showBin (t,v) = "(" ++ v ++ "," ++ t ++ ")"
mkLatexFile :: String -> String
mkLatexFile cmd =
"\\documentclass{standalone}\n"
++ "\\usepackage[plot]{forsyde}\n"
++ "\\begin{document}\n"
++ "\\begin{tikzpicture}[]\n"
++ cmd
++ "\\end{tikzpicture}\n"
++ "\\end{document}\n"
-------------------------- UTILITIES --------------------------
replChar :: String -- all characters in this set are replaced by '_'
-> Char -- Char to replace with
-> String -- the string where characters are replaced
-> String -- the result string with all characters replaced
replChar [] _ s = s
replChar _ _ [] = []
replChar rSet rCh (c:s) | c `elem` rSet = rCh : replChar rSet rCh s
| otherwise = c : replChar rSet rCh s
tryNTimes :: Int -> String -> (String -> IO ()) -> IO String
tryNTimes n base a
| n <= 0 = error "tryNTimes: not succedded"
| n > 0 = catch (action fname a) (handler a)
where handler :: (String -> IO()) -> IOError -> IO String
handler a _ = tryNTimes (n-1) base a
fname = base ++ show n ++ ".gnuplot"
action :: String -> (String -> IO ()) -> IO String
action fname a = do a fname
return fname
tryNTimes _ _ _ = error "tryNTimes: Unexpected pattern."
| forsyde/forsyde-atom | src/ForSyDe/Atom/Utility/Plot.hs | bsd-3-clause | 27,042 | 0 | 29 | 8,276 | 6,610 | 3,596 | 3,014 | 458 | 7 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------------------
-- |
-- Module: HipChat.AddOn.WebPanel
--
-- WebPanels aka sidebars
--
-- https://www.hipchat.com/docs/apiv2/webpanels
-- https://developer.atlassian.com/hipchat/guide/sidebar
--------------------------------------------------------------------------------
module HipChat.AddOn.WebPanel where
import HipChat.AddOn.Types (AuthenticationMethod, Icon, Name)
import HipChat.Types (Key, URL)
import HipChat.Util (ToFromJSON)
import Control.Lens.AsText (AsText)
import qualified Control.Lens.AsText as AsText
import Data.Aeson (FromJSON, ToJSON, parseJSON, toJSON)
import Data.Default (Default)
import Data.String (IsString, fromString)
import GHC.Generics (Generic)
data WebPanelLocation = RightSidebar
deriving (Eq, Show, Generic, Default)
instance AsText WebPanelLocation where
enc _ = "hipchat.sidebar.right"
dec "hipchat.sidebar.right" = Just RightSidebar
dec _ = Nothing
instance IsString WebPanelLocation where
fromString = AsText.fromString
instance ToJSON WebPanelLocation where
toJSON = AsText.toJSON
instance FromJSON WebPanelLocation where
parseJSON = AsText.parseJSON
data WebPanel = WebPanel
{ webPanelAuthentication :: Maybe AuthenticationMethod
-- ^ The authentication method for this webpanel. Defaults to JWT.
, webPanelIcon :: Maybe Icon
-- ^ Icon to display on the left side of the webPanel title.
, webPanelKey :: Key
-- ^ Unique key (in the context of the integration) to identify this webPanel. Valid length range: 1 - 40.
, webPanelLocation :: WebPanelLocation
-- ^ The location of this webPanel Valid values: hipchat.sidebar.right.
, webPanelName :: Name
-- ^ The display name of the webPanel.
, webPanelUrl :: URL
-- ^ The URL of the resource providing the view content.
, webPanelWeight :: Maybe Int
-- ^ Determines the order in which webPanel appear.
-- Web panels are displayed top to bottom or left to right in order of ascending weight.
-- Defaults to 100.
} deriving (Eq, Generic, Show)
mkWebPanel :: Key -> Name -> URL -> WebPanel
mkWebPanel key' name url = WebPanel Nothing Nothing key' RightSidebar name url Nothing
instance ToFromJSON WebPanel
| mjhopkins/hipchat | src/HipChat/AddOn/WebPanel.hs | bsd-3-clause | 2,525 | 0 | 9 | 555 | 372 | 221 | 151 | 37 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Applicative
import Control.Lens hiding (children, transform)
import Data.Functor.Identity(Identity, runIdentity)
import Data.Monoid
import qualified Data.Text as T
import Prelude hiding (div)
import VirtualHom.Element
import VirtualHom.Internal.Handler
import VirtualHom.Html hiding (content, main)
import VirtualHom.Rendering(renderingOptions)
import VirtualHom.Bootstrap(container, row, btnDefault)
import VirtualHom.Components
counterComp :: Component ()
counterComp = component 0 $ \(state, _) ->
[row & children .~ [
p & content .~ ("This button has been clicked " <> (T.pack $ show state) <> " times"),
btnDefault
& content .~ "Click"
& callbacks . click ?~ (\_ -> update $ over _1 succ)
]]
data CompState = CompState {
_counter1 :: Component (),
_counter2 :: Component ()
}
makeLenses ''CompState
initialState = CompState counterComp counterComp
theUI = component initialState $ \tpl -> [container & children .~ (inner tpl)] where
inner = (++) <$> subComponent' (_1.counter1) <*> subComponent' (_1.counter2)
main :: IO ()
main = do
let options = renderingOptions "virtual-hom"
renderComponent options theUI ()
| j-mueller/virtual-hom | examples/components/Main.hs | bsd-3-clause | 1,282 | 0 | 16 | 226 | 390 | 218 | 172 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.MVar
import Data.Attoparsec.ByteString
import qualified Data.Text as T
import Network.URI
import System.Environment (getArgs)
import System.INotify
import System.IO
import System.Posix.Daemonize (daemonize)
import System.Process (system)
------------------------------------------------------------------------------
main = daemonize $ do
file:[] <- getArgs
-- Get the length of the log file.
offset <- withFile file ReadMode $ (\h -> hSeek h SeekFromEnd 0 >> hTell h)
stop <- newEmptyMVar
n <- initINotify
m <- newMVar offset
-- Watch for modification.
desc <- addWatch n [Modify] file (callback m file)
-- wait forever
takeMVar stop
removeWatch desc
return ()
-- | Seek to the point 'm'. Starting from 'm', get contents until the
-- end of the logfile. give it to 'processLogLine'.
callback :: MVar Integer -> FilePath -> Event -> IO ()
callback m fp (Modified _ _) = do
off <- takeMVar m
hdl <- openFile fp ReadMode
hSeek hdl AbsoluteSeek off
xs <- hGetContents hdl
putMVar m $ off + fromIntegral (length xs)
processLogLine (T.pack xs)
hClose hdl
return ()
-- | Parse the Group ID and source IP of the snort alert. Use iptables
-- to block the source IP if gid==115.
processLogLine xs = do
let gid = parseGid xs
ip = parseSrcIp xs
case (gid, ip) of
(115, Just x) -> blacklist x >> return ()
_ -> return ()
-- | Execute iptables
blacklist ip = system . T.unpack $ "iptables -I FORWARD -p all -s " `T.append` ip `T.append` " -j REJECT"
parseSrcIp :: T.Text -> Maybe T.Text
parseSrcIp line = let ipstr = extractip . extractsrcsection . extractipsection $ line in
case (isIPv4address . T.unpack $ ipstr) of
True -> Just ipstr
False -> Nothing
where extractipsection = Prelude.head . Prelude.drop 1 . T.splitOn "}" . Prelude.head
. Prelude.drop 2 . T.splitOn (T.pack "[**]")
extractsrcsection = Prelude.head . Prelude.take 1 . T.words
extractip = Prelude.head . T.split (== ':')
parseGid :: T.Text -> Int
parseGid = readInt . extractGid . Prelude.take 1 . T.words . Prelude.head . Prelude.drop 1 . T.splitOn (T.pack "[**]")
where extractGid = T.drop 1 . Prelude.head . T.split (== ':') . Prelude.head
readInt = read . T.unpack
{-| Example Rule: (note that gid should be 115)
alert tcp $E any -> $H 21 (msg:"ET EXPLOIT VSFTPD Backdoor User Login Smiley"; flow:established,to_server; content:"USER "; depth:5; content:"|3a 29|"; distance:0; classtype:attempted-admin; gid:115; sid:2013188; rev:4;)
-}
-- Example "Snort Fast Log" lines
logline :: T.Text
logline = "06/12-15:55:12.377292 [**] [155:2013188:4] ET EXPLOIT VSFTPD Backdoor User Login Smiley [**] [Classification: Attempted Administrator Privilege Gain] [Priority: 1] {TCP} 192.168.1.213:53573 -> 192.168.4.2:21"
logline' :: T.Text
logline' = "06/12-17:15:05.575953 [**] [115:9999999:1] PHPSESSID Detected [**] [Classification: Web Application Attack] [Priority: 1] {TCP} 192.168.1.213:36016 -> 192.168.4.2:80"
{-| ghci tests:
> (parseGid logline, parseSrcIp logline)
(155,Just "192.168.1.213")
> (parseGid logline', parseSrcIp logline')
(115,Just "192.168.1.213")
-}
| aycanirican/hblacklist | src/Main.hs | bsd-3-clause | 3,562 | 0 | 13 | 795 | 795 | 402 | 393 | 57 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
module Data.Vector.Utils
( binarySearchByKey
, salami
) where
import Data.Bits
import Data.Vector.Generic (Vector)
import qualified Data.Vector.Generic as G
import Data.Function
{-# INLINE binarySearchByKey #-}
binarySearchByKey :: ( Vector v (e k a)
, Ord k )
=> (e k a -> k)
-> v (e k a)
-> k
-> Int
binarySearchByKey getKey v k = go 0 (G.length v)
where
go !l !r
| r <= l = l
| otherwise = case getKey (G.unsafeIndex v c) `compare` k of
LT -> go (c + 1) r
EQ -> c
GT -> go l c
where c = (r + l) `shiftR` 1
salami :: (Vector v e) => Int -> v e -> [v e]
salami n v | len <= n = elementwise 0
| otherwise = slicewise 0 1
where
elementwise i | i == len = []
| otherwise = G.unsafeSlice i 1 v : elementwise (i + 1)
slicewise l i | i == n = [G.unsafeSlice l (len - l) v]
| otherwise = let r = floor $ sliceSize * fromIntegral i
in G.unsafeSlice l (r - l) v : slicewise r (i + 1)
len = G.length v
sliceSize = on (/) fromIntegral len n :: Double
| schernichkin/BSPM | graphomania/src/Data/Vector/Utils.hs | bsd-3-clause | 1,316 | 0 | 13 | 529 | 504 | 256 | 248 | 34 | 3 |
module Spec where
import Control.Monad.CanSpec
import Test.Tasty
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Testing..."
[spec]
| athanclark/monad-can | test/Spec.hs | bsd-3-clause | 167 | 0 | 6 | 30 | 51 | 29 | 22 | 8 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Loupe
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : Rank2Types
--
-- This module exports a minimalist API for working with lenses in highly
-- monomorphic settings.
-------------------------------------------------------------------------------
module Control.Lens.Loupe
(
ALens, ALens'
, cloneLens
, storing
, (^#)
, ( #~ ), ( #%~ ), ( #%%~ ), (<#~), (<#%~)
, ( #= ), ( #%= ), ( #%%= ), (<#=), (<#%=)
-- * Deprecated Aliases
, Loupe, SimpleLoupe
) where
import Control.Lens.Internal.Context
import Control.Lens.Lens
import Control.Lens.Type
-- | This is an older alias for a type-restricted form of lens that is able to be passed around
-- in containers monomorphically.
--
-- Deprecated. This has since been renamed to 'ALens' for consistency.
type Loupe s t a b = LensLike (Pretext (->) a b) s t a b
{-# DEPRECATED Loupe "use ALens" #-}
-- | @
-- type 'SimpleLoupe' = 'Simple' 'Loupe'
-- @
--
-- Deprecated for two reasons. 'Loupe' is now 'ALens', and we no longer use the verbose @SimpleFoo@ naming
-- convention, this has since been renamed to 'ALens'' for consistency.
type SimpleLoupe s a = Loupe s s a a
{-# DEPRECATED SimpleLoupe "use ALens'" #-}
| hvr/lens | src/Control/Lens/Loupe.hs | bsd-3-clause | 1,443 | 0 | 8 | 264 | 177 | 130 | 47 | 16 | 0 |
import System.Environment
import QueryArrow.Serialization
import System.Directory
import Network.Socket
import System.IO
import QueryArrow.RPC.Message
import QueryArrow.Chopper.Data
import Test.Hspec
import Control.Monad
import System.Process
import Data.List
import Text.Parsec
import qualified Text.Parsec.Token as P
import Control.Monad.IO.Class
import qualified Data.Map as M
import Data.Time.Clock
import QueryArrow.Syntax.Term
normalizeResultSet :: ResultSet -> ResultSet
normalizeResultSet rset@(ResultSetError _) = rset
normalizeResultSet (ResultSetNormal rl) = ResultSetNormal rl
sortResultSet :: ResultSet -> ResultSet
sortResultSet rset@(ResultSetError _) = rset
sortResultSet (ResultSetNormal rl) = ResultSetNormal (sort rl)
lexer :: P.GenTokenParser String () IO
lexer = P.makeTokenParser P.LanguageDef {
P.reservedNames = ["skip"],
P.commentStart = "",
P.commentEnd = "",
P.commentLine = "",
P.nestedComments = False,
P.identStart = letter,
P.identLetter = letter <|> digit <|> oneOf "._-",
P.opStart = oneOf "",
P.opLetter = oneOf "",
P.reservedOpNames = [],
P.caseSensitive = True
}
identifier :: ParsecT String () IO String
identifier = P.identifier lexer
integer :: ParsecT String () IO Integer
integer = P.integer lexer
reserved :: String -> ParsecT String () IO ()
reserved = P.reserved lexer
testp :: Handle -> Bool -> String -> Maybe Handle -> ParsecT String () IO ()
testp log dryrun addr h0 = do
try eof <|> try (do
reserved "skip"
ref <- identifier
liftIO $ putStrLn ("skipped " ++ ref)
) <|> (do
replicateM_ 10 (char '=')
n <- integer
act0 <- replicateM (fromInteger n) anyChar
_ <- newline
let act = read act0
h1 <- liftIO $ case act of
SendAction qs ->
if dryrun
then do
putStrLn ("send " ++ show qs)
return h0
else do
h <- getConnection addr h0
-- hPutStrLn log ("send " ++ show qs)
sendMsgPack h qs
case qs of
QuerySet _ Quit _ -> do
hClose h
return Nothing
_ ->
return (Just h)
RecvAction rs ->
if dryrun
then do
putStrLn ("recv " ++ show rs)
return h0
else do
h <- getConnection addr h0
mRs2 <- receiveMsgPack h :: IO (Maybe ResultSet)
case mRs2 of
Nothing -> expectationFailure "cannot parse message"
Just rs2 ->
let rs2' = normalizeResultSet rs2 in
-- if rs2' /= rs
-- then
sortResultSet rs2' `shouldBe` sortResultSet rs
-- else return ()
return (Just h)
testp log dryrun addr h1)
getConnection :: String -> Maybe Handle -> IO Handle
getConnection addr h0 = do
case h0 of
Nothing -> connect1 addr
Just h -> return h
connect1 :: String -> IO Handle
connect1 addr = do
sock <- socket AF_UNIX Stream defaultProtocol
connect sock (SockAddrUnix addr)
socketToHandle sock ReadWriteMode
connect2 :: Bool -> String -> IO (Maybe Handle)
connect2 dryrun addr =
if dryrun
then return Nothing
else Just <$> connect1 addr
main :: IO ()
main = do
dryrun <- read <$> getEnv "qat_dryrun"
udsaddr <- getEnv "qat_udsaddr"
inp <- getEnv "qat_inp"
list <- getEnv "qat"
setupscript <- getEnv "qat_setup"
files <- lines <$> readFile list
logfilehandle <- openFile "/tmp/qat" WriteMode
ti <- getCurrentTime
hspec $ do
describe "setup" $ do
it "setup" $ do
setup <- readFile setupscript
let commands = lines setup
h <- connect1 udsaddr
mapM_ (\command -> if command == "" || ("//" `isPrefixOf` command)
then return ()
else do
sendMsgPack h (QuerySet mempty (Dynamic command) mempty)
mrset <- receiveMsgPack h :: IO (Maybe ResultSet)
case mrset of
Just (ResultSetError err) -> error (show err)
Just (ResultSetNormal _) -> return ()
Nothing -> error "cannot parse response") (commands ++ ["nextid(x)"] -- this account for the test iput run by the install script
)
sendMsgPack h Quit
hClose h
describe "all tests" $ do
zipWithM_ (\filepath n -> it filepath $ do
t0 <- getCurrentTime
hdlinp <- openFile (inp ++ "/" ++ filepath) ReadMode
cnt <- hGetContents hdlinp
h <- connect2 dryrun udsaddr
res <- runParserT (testp logfilehandle dryrun udsaddr h) () filepath cnt
res `shouldBe` Right ()
t1 <- liftIO $ getCurrentTime
hClose hdlinp
liftIO $ putStrLn (show n ++ "/" ++ show (length files) ++ " " ++ show (diffUTCTime t1 t0) ++ " avg: " ++ show (diffUTCTime t1 ti / fromIntegral n))) files [1..]
hClose logfilehandle
| xu-hao/QueryArrow | test-QueryArrow/app/runner/TestRunner.hs | bsd-3-clause | 5,808 | 0 | 29 | 2,343 | 1,588 | 767 | 821 | 138 | 6 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
This module provides replacements for the 'httpServe' and 'quickHttpServe'
functions exported by 'Snap.Http.Server'. By taking a 'Initializer' as an argument,
these functions simplify the glue code that is needed to use Snap Extensions.
In particular, 'Snap.Extension.Server.Hint' provides function with identical
type signatures to the ones exported by this module, but which dynamically
reload their code on each request. See the README for details.
-}
#ifdef HINT
module Snap.Extension.Server.Hint
#else
module Snap.Extension.Server
#endif
( ConfigExtend
, httpServe
, quickHttpServe
, defaultConfig
, getReloadHandler
, setReloadHandler
, module Snap.Http.Server.Config
) where
import Control.Applicative
import Control.Arrow
import Control.Exception (SomeException)
import Control.Monad
import Control.Monad.CatchIO
import Data.ByteString (ByteString)
import qualified Data.ByteString.UTF8 as U
import Data.Maybe
import Data.Monoid
import Prelude hiding (catch)
import Snap.Extension
#ifdef HINT
import Snap.Loader.Hint
#endif
import Snap.Http.Server (simpleHttpServe, setUnicodeLocale)
import qualified Snap.Http.Server.Config as C
import Snap.Http.Server.Config hiding ( defaultConfig
, completeConfig
, getOther
, setOther
)
import Snap.Util.GZip
import Snap.Types
import System.IO
------------------------------------------------------------------------------
-- | 'ConfigExtend' is similar to the 'Config' exported by 'Snap.Http.Server',
-- but is augmented with a @reloadHandler@ field which can be accessed using
-- 'getReloadHandler' and 'setReloadHandler'.
type ConfigExtend s = Config
(SnapExtend s) (IO [(ByteString, Maybe ByteString)] -> SnapExtend s ())
------------------------------------------------------------------------------
getReloadHandler :: ConfigExtend s -> Maybe
(IO [(ByteString, Maybe ByteString)] -> SnapExtend s ())
getReloadHandler = C.getOther
------------------------------------------------------------------------------
setReloadHandler :: (IO [(ByteString, Maybe ByteString)] -> SnapExtend s ())
-> ConfigExtend s
-> ConfigExtend s
setReloadHandler = C.setOther
------------------------------------------------------------------------------
-- | These are the default values for all the fields in 'ConfigExtend'.
--
-- > hostname = "localhost"
-- > address = "0.0.0.0"
-- > port = 8000
-- > accessLog = "log/access.log"
-- > errorLog = "log/error.log"
-- > locale = "en_US"
-- > compression = True
-- > verbose = True
-- > errorHandler = prints the error message
-- > reloadHandler = prints the result of each reload handler (error/success)
--
defaultConfig :: ConfigExtend s
defaultConfig = setReloadHandler handler C.defaultConfig
where
handler = path "admin/reload" . defaultReloadHandler
------------------------------------------------------------------------------
-- | Completes a partial 'Config' by filling in the unspecified values with
-- the default values from 'defaultConfig'.
completeConfig :: ConfigExtend s -> ConfigExtend s
completeConfig = mappend defaultConfig
------------------------------------------------------------------------------
-- | Starts serving HTTP requests using the given handler, with settings from
-- the 'ConfigExtend' passed in. This function never returns; to shut down
-- the HTTP server, kill the controlling thread.
httpServe :: ConfigExtend s
-- ^ Any configuration options which override the defaults
-> Initializer s
-- ^ The 'Initializer' function for the application's monad
-> SnapExtend s ()
-- ^ The application to be served
-> IO ()
httpServe config init handler = do
(state, mkCleanup, mkSnap) <-
runInitializerHint verbose init (catch500 handler) reloader
#ifdef HINT
(cleanup, snap) <- $(loadSnapTH 'state 'mkCleanup 'mkSnap)
#else
(cleanup, snap) <- fmap (mkCleanup &&& mkSnap) state
#endif
let site = compress $ snap
output $ concat ["Listening on ", U.toString address, ":", show port]
_ <- try $ serve $ site :: IO (Either SomeException ())
putStr "\n"
cleanup
output "Shutting down..."
where
handle :: SomeException -> IO ()
handle e = print e
conf = completeConfig config
verbose = fromJust $ getVerbose conf
output = when verbose . hPutStrLn stderr
address = fromJust $ getAddress conf
port = fromJust $ getPort conf
reloader = fromJust $ getReloadHandler conf
compress = if fromJust $ getCompression conf then withCompression else id
catch500 = flip catch $ fromJust $ getErrorHandler conf
serve = simpleHttpServe config
------------------------------------------------------------------------------
-- | Starts serving HTTP using the given handler. The configuration is read
-- from the options given on the command-line, as returned by
-- 'commandLineConfig'.
quickHttpServe :: Initializer s
-- ^ The 'Initializer' function for the application's monad
-> SnapExtend s ()
-- ^ The application to be served
-> IO ()
quickHttpServe r m = commandLineConfig emptyConfig >>= \c -> httpServe c r m
| duairc/snap-extensions | src/Snap/Extension/Server.hs | bsd-3-clause | 5,721 | 0 | 12 | 1,376 | 832 | 466 | 366 | 74 | 2 |
module SecretBox
( tests -- :: Int -> Tests
) where
import Control.Monad
import Data.ByteString (ByteString)
import Crypto.Encrypt.SecretBox
import Crypto.Key
import Crypto.Nonce
import Test.QuickCheck
import Util
--------------------------------------------------------------------------------
-- Authenticated secret-key encryption
secretboxProp :: (SecretKey SecretBox -> Nonce SecretBox -> Bool) -> Property
secretboxProp k = ioProperty $ liftM2 k randomKey randomNonce
roundtrip :: ByteString -> Property
roundtrip xs
= secretboxProp $ \key nonce ->
let enc = encrypt nonce xs key
dec = decrypt nonce enc key
in maybe False (== xs) dec
tests :: Int -> Tests
tests ntests =
[ ("xsalsa20poly1305 roundtrip", wrap roundtrip)
]
where
wrap :: Testable prop => prop -> IO (Bool, Int)
wrap = mkArgTest ntests
| thoughtpolice/hs-nacl | tests/SecretBox.hs | bsd-3-clause | 932 | 0 | 11 | 237 | 229 | 124 | 105 | 22 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Dimensions.DA
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Seal Dimension]
allDimensions =
[ Seal Duration
, Seal Numeral
, Seal Ordinal
, Seal Time
]
| facebookincubator/duckling | Duckling/Dimensions/DA.hs | bsd-3-clause | 420 | 0 | 6 | 80 | 63 | 38 | 25 | 9 | 1 |
{-# LANGUAGE TupleSections, ConstraintKinds #-}
-- | Extra functions for creating processes. Specifically variants that automatically check
-- the 'ExitCode' and capture the 'stdout' \/ 'stderr' handles.
module System.Process.Extra(
module System.Process,
system_, systemOutput, systemOutput_
) where
import Control.Monad
import System.IO.Extra
import System.Process
import System.Exit
import Data.Functor
import Partial
import Prelude
-- | A version of 'system' that also captures the output, both 'stdout' and 'stderr'.
-- Returns a pair of the 'ExitCode' and the output.
systemOutput :: String -> IO (ExitCode, String)
systemOutput x = withTempFile $ \file -> do
exit <- withFile file WriteMode $ \h -> do
(_, _, _, pid) <- createProcess (shell x){std_out=UseHandle h, std_err=UseHandle h}
waitForProcess pid
(exit,) <$> readFile' file
-- | A version of 'system' that throws an error if the 'ExitCode' is not 'ExitSuccess'.
system_ :: Partial => String -> IO ()
system_ x = do
res <- system x
when (res /= ExitSuccess) $
error $ "Failed when running system command: " ++ x
-- | A version of 'system' that captures the output (both 'stdout' and 'stderr')
-- and throws an error if the 'ExitCode' is not 'ExitSuccess'.
systemOutput_ :: Partial => String -> IO String
systemOutput_ x = do
(res,out) <- systemOutput x
when (res /= ExitSuccess) $
error $ "Failed when running system command: " ++ x
pure out
| ndmitchell/extra | src/System/Process/Extra.hs | bsd-3-clause | 1,491 | 0 | 18 | 306 | 322 | 171 | 151 | -1 | -1 |
module FibAsHisto where
-- We would like to do this!
psi Nothing = (0, Nothing) -- 0
-- psi (Just Nothing) = (1, Just Nothing) -- NOT this
psi (Just Nothing) = (1, Just (0, Nothing)) -- 1
psi (Just (Just Nothing)) = (1, Just (1, Just (0, Nothing))) -- 2
psi (Just (Just (Just Nothing))) = (2, Just (1, Just (1, Just (0, Nothing)))) -- 3
psi (Just (Just (Just (Just Nothing)))) = (3, Just (2, Just (1, Just (1, Just (0, Nothing))))) -- 4
psi (Just (Just (Just (Just (Just Nothing))))) = (5, Just (3, Just (2, Just (1, Just (1, Just (0, Nothing)))))) -- 5
psi (Just (Just (Just (Just (Just (Just Nothing)))))) = (8, Just (5, Just (3, Just (2, Just (1, Just (1, Just (0, Nothing))))))) -- 6
{-- couldn't typable
psi' Nothing = (0, Nothing)
psi' (Just Nothing) = (1, Just (psi' Nothing))
psi' (Just n) = case psi' n of
p@(f1, Just (f2, mv)) -> (f1 + f2, Just p)
--}
type Nat = Fix Maybe
data Fix f = In { out :: f (Fix f) }
newtype Ano = Ano (Integer, Maybe Ano)
-- fit a type
psi' :: Nat -> Ano
psi' (In Nothing) = Ano (0, Nothing) -- 0
psi' (In (Just (In Nothing))) = Ano (1, Just (Ano (0, Nothing))) -- 1
psi' (In (Just (In (Just (In Nothing))))) = Ano (1, Just (Ano (1, Just (Ano (0, Nothing))))) -- 2
-- done!
-- this like histo engine
psi'' n = case fmap psi'' (out n) of
p@Nothing -> Ano (0, p)
p@(Just n') -> case sub n' of
Nothing -> Ano (1, p)
Just n'' -> Ano (ex n' + ex n'', p)
-- extract
ex (Ano (x, _)) = x
-- sub
sub (Ano (_, y)) = y
ana psi = In . fmap (ana psi) . psi
toNat = ana psi
where
psi 0 = Nothing
psi n = Just (n-1)
{-
toNat 0 = In Nothing
toNat n = In (Just (toNat (n-1)))
-}
exs (Ano (n, Nothing)) = [n]
exs (Ano (n, Just x)) = n:exs x
fib = ex . psi'' . toNat
| cutsea110/aop | src/FibAsHisto.hs | bsd-3-clause | 1,727 | 0 | 17 | 403 | 919 | 498 | 421 | 29 | 3 |
{- |
Module : Main
Description : Runs the puffy tool kit (ptk)
Copyright : 2014, Peter Harpending
License : BSD3
Maintainer : Peter Harpending <pharpend2@gmail.com>
Stability : experimental
Portability : Linux
-}
module Main where
import Data.Version
import Paths_puffytools
import Ptk.Journal
import System.Console.Argument
import System.Console.Command
import System.Console.Program
versionTree :: Commands IO
versionTree = Node commandVersion []
where
commandVersion = Command
"version"
"Print the version to the console. Meant for use in other programs."
printVersion
printVersion = io . putStr $ showVersion version
helpTree :: Commands IO
helpTree = Node helpCommand []
where
helpCommand = Command "help" "Show this help menu." help
shellTree :: Commands IO
shellTree = Node ptkShell []
where
ptkShell = Command "shell" "PTK REPL (Expiremental)." (io $ interactive commandTree)
help :: Action IO
help = io $ showUsage commandTree
commandTree :: Commands IO
commandTree = Node (Command "ptk" description help) [jTree, journalTree, helpTree, versionTree, shellTree]
where
description = "The Puffy Toolkit, version " ++ showVersion version
main :: IO ()
main = single commandTree
| pharpend/puffytools | ptk/Main.hs | bsd-3-clause | 1,370 | 0 | 10 | 355 | 259 | 138 | 121 | 27 | 1 |
module Main where
main = x
| aavogt/preludeFlag | src/Main.hs | bsd-3-clause | 27 | 0 | 4 | 6 | 9 | 6 | 3 | 2 | 1 |
module Data.HABSim.HABSim
( module Data.HABSim.Types
, sim
) where
import Control.Lens
import Control.Monad.Writer
import qualified Data.DList as D
import qualified Data.HABSim.Internal as I
import Data.HABSim.Lens
import Data.HABSim.Types
import Data.HABSim.Grib2.CSVParse.Types
import qualified Data.HashMap.Lazy as HM
import Data.Maybe (fromMaybe)
import qualified Data.Vector as V
import Debug.Trace
sim
:: Pitch
-> Simulation
-> V.Vector Int -- ^ Vector of pressures to round to from Grib file
-> HM.HashMap Key GribLine
-> (Simulation -> Bool) -- ^ We record the line when this predicate is met
-> Writer (D.DList Simulation) Simulation
sim p
simul@(Simulation
sv
(PosVel lat' lon' alt' vel_x' vel_y' vel_z')
(Burst
mass'
bal_cd'
par_cd'
packages_cd'
launch_time'
burst_vol'
b_volume'
b_press'
b_gmm'
b_temp')
(Wind (WindX wind_x') (WindY wind_y')))
pressureList
gribLines
tellPred
| baseGuard p = do
let pv = PosVel lat' lon' alt' vel_x' vel_y' vel_z'
bv = Burst
mass'
bal_cd'
par_cd'
packages_cd'
launch_time'
burst_vol'
b_volume'
b_press'
b_gmm'
b_temp'
w = Wind windX' windY'
return (Simulation sv pv bv w)
| otherwise = do
let sv' = sv { _simulationTime = sv ^. simulationTime + sv ^. increment }
pv = PosVel nlat nlon nAlt nvel_x nvel_y nvel_z
bv = Burst
mass'
bal_cd'
par_cd'
packages_cd'
launch_time'
burst_vol'
(pitch p nVol b_volume')
(pitch p pres b_press')
b_gmm'
(pitch p (_temp temp) b_temp')
w = Wind windX' windY'
s = Simulation sv' pv bv w
when (tellPred simul) $
tell (D.singleton s)
sim p s pressureList gribLines tellPred
where
-- The guard to use depends on the pitch
baseGuard Ascent = b_volume' >= burst_vol'
baseGuard Descent = alt' < 0
-- Getting pressure and density at current altitude
PressureDensity pres dens temp = I.altToPressure alt'
-- Calculating volume, radius, and crossectional area
nVol = I.newVolume b_press' b_temp' b_volume' pres (_temp temp)
Meter nbRad = I.spRadFromVol nVol
nCAsph = I.cAreaSp nbRad
gdens = I.gas_dens (Mass b_gmm') pres temp
-- Calculating buoyant force
f_buoy = I.buoyancy dens gdens nVol
-- Calculate drag force for winds
f_drag_x =
case p of
Ascent -> I.drag dens vel_x' (windIntpX ^. windX) bal_cd' nCAsph
Descent -> I.drag dens vel_x' (windIntpX ^. windX) packages_cd' 1
f_drag_y =
case p of
Ascent -> I.drag dens vel_y' (windIntpY ^. windY) bal_cd' nCAsph
Descent -> I.drag dens vel_y' (windIntpY ^. windY) packages_cd' 1
f_drag_z =
case p of
Ascent -> I.drag dens vel_z' 0 bal_cd' nCAsph
Descent -> I.drag dens vel_z' 0 par_cd' 1
-- Net forces in z
f_net_z =
case p of
Ascent -> f_buoy - ((-1 * f_drag_z) + (I.force mass' I.g))
Descent -> f_drag_z - (I.force mass' I.g)
-- Calculate Kenimatics
accel_x = I.accel f_drag_x mass'
accel_y = I.accel f_drag_y mass'
accel_z = I.accel f_net_z mass'
nvel_x = I.velo vel_x' accel_x sv
nvel_y = I.velo vel_y' accel_y sv
nvel_z = I.velo vel_z' accel_z sv
Altitude disp_x = I.displacement (Altitude 0.0) nvel_x accel_x sv
Altitude disp_y = I.displacement (Altitude 0.0) nvel_y accel_y sv
nAlt = I.displacement alt' nvel_z accel_z sv
-- Calculate change in corrdinates
-- Because of the relatively small changes, we assume a spherical earth
bearing = atan2 disp_x disp_y
t_disp = (disp_x ** 2 + disp_y ** 2) ** (1 / 2)
ang_dist = t_disp / I.er
latr = lat' * (pi / 180)
lonr = lon' * (pi / 180)
nlatr =
asin (sin latr * cos ang_dist + cos latr * sin ang_dist * cos bearing)
nlonr =
lonr +
atan2 (sin bearing * sin ang_dist * cos latr)
(cos ang_dist - (sin latr * sin nlatr))
nlat = nlatr * (180 / pi)
nlon = nlonr * (180 / pi)
(flat, flon, clat, clon) =
I.latLonBox (Latitude lat') (Longitude lon') 0.25
windCurrentDef lat lon =
fromMaybe
(WindX wind_x', WindY wind_y')
(I.windFromLatLon
lat
lon
(I.roundToClosest (pres/100) pressureList)
gribLines)
(WindX (WindMs windX1), WindY (WindMs windY1)) = windCurrentDef flat flon
(WindX (WindMs windX2), WindY (WindMs windY2)) = windCurrentDef flat clon
(WindX (WindMs windX3), WindY (WindMs windY3)) = windCurrentDef clat flon
(WindX (WindMs windX4), WindY (WindMs windY4)) = windCurrentDef clat clon
(windX', windY') = windCurrentDef (Latitude lat') (Longitude lon')
windIntpX =
WindX . WindMs $
I.biLinIntp
lat'
lon'
windX1
windX2
windX3
windX4
(flat ^. latitude)
(clat ^. latitude)
(flon ^. longitude)
(clon ^. longitude)
windIntpY =
WindY . WindMs $
I.biLinIntp
lat'
lon'
windY1
windY2
windY3
windY4
(flat ^. latitude)
(clat ^. latitude)
(flon ^. longitude)
(clon ^. longitude)
| kg4sgp/habsim | haskell/src/Data/HABSim/HABSim.hs | bsd-3-clause | 5,573 | 0 | 15 | 1,843 | 1,645 | 846 | 799 | 161 | 6 |
{-# OPTIONS -XScopedTypeVariables -XOverloadedStrings #-}
module MFlow.Cookies (
CookieT,
Cookie(..),
contentHtml,
cookieuser,
cookieHeaders,
getCookies,
paranoidEncryptCookie,
paranoidDecryptCookie,
encryptCookie,
decryptCookie
)
where
import Control.Monad(MonadPlus(..), guard, replicateM_, when)
import Data.Char
import Data.Maybe(fromMaybe, fromJust)
import System.IO.Unsafe
import Control.Exception(handle)
import Data.Typeable
import Unsafe.Coerce
import Data.Monoid
import Text.Parsec
import Control.Monad.Identity
import Data.ByteString.Char8 as B
import Web.ClientSession
import System.Environment
--import Debug.Trace
--(!>)= flip trace
contentHtml :: (ByteString, ByteString)
contentHtml= ("Content-Type", "text/html; charset=UTF-8")
type CookieT = (B.ByteString,B.ByteString,B.ByteString,Maybe B.ByteString)
data Cookie
= UnEncryptedCookie CookieT
| EncryptedCookie CookieT
| ParanoidCookie CookieT
deriving (Eq, Read, Show)
cookieuser :: String
cookieuser= "cookieuser"
getCookies httpreq=
case lookup "Cookie" $ httpreq of
Just str -> splitCookies str :: [(B.ByteString, B.ByteString)]
Nothing -> []
cookieHeaders cs = Prelude.map (\c-> ( "Set-Cookie", showCookie c)) cs
showCookie :: Cookie -> B.ByteString
showCookie c@(EncryptedCookie _) = showCookie' $ decryptAndToTuple c
showCookie c@(ParanoidCookie _) = showCookie' $ decryptAndToTuple c
showCookie (UnEncryptedCookie c) = showCookie' c
showCookie' (n,v,p,me) = n <> "=" <> v <>
";path=" <> p <>
showMaxAge me
showMaxAge Nothing = ""
showMaxAge (Just e) = ";Max-age=" <> e
splitCookies cookies = f cookies []
where
f s r | B.null s = r
f xs0 r =
let
xs = B.dropWhile (==' ') xs0
name = B.takeWhile (/='=') xs
xs1 = B.dropWhile (/='=') xs
xs2 = B.dropWhile (=='=') xs1
val = B.takeWhile (/=';') xs2
xs3 = B.dropWhile (/=';') xs2
xs4 = B.dropWhile (==';') xs3
xs5 = B.dropWhile (==' ') xs4
in f xs5 ((name,val):r)
----------------------------
readEnv :: Parsec String () [(String,String)]
readEnv = (do
n <- urlEncoded
string "="
v <- urlEncoded
return (n,v)) `sepBy` (string "&")
urlEncoded :: Parsec String () String
urlEncoded
= many ( alphaNum `mplus` extra `mplus` safe
`mplus` do{ char '+' ; return ' '}
`mplus` do{ char '%' ; hexadecimal }
)
extra :: Parsec String () Char
extra = satisfy (`Prelude.elem` ("!*'(),/\"" ::String))
--
safe :: Parsec String () Char
safe = satisfy (`Prelude.elem` ("$-_." :: String))
----
hexadecimal :: ParsecT String u Identity Char
hexadecimal = do d1 <- hexDigit
d2 <- hexDigit
return .chr $ toInt d1* 16 + toInt d2
where toInt d | isDigit d = ord d - ord '0'
toInt d | isHexDigit d = (ord d - ord 'A') + 10
toInt d = error ("hex2int: illegal hex digit " ++ [d])
decryptCookie :: Cookie -> IO Cookie
decryptCookie c@(UnEncryptedCookie _) = return c
decryptCookie (EncryptedCookie c) = decryptCookie' c
decryptCookie (ParanoidCookie c) = paranoidDecryptCookie c
-- Uses 4 seperate keys, corresponding to the 4 seperate fields in the Cookie.
paranoidEncryptCookie :: CookieT -> IO Cookie
paranoidEncryptCookie (a,b,c,d) = do
key1 <- getKey "CookieKey1.key"
key2 <- getKey "CookieKey2.key"
key3 <- getKey "CookieKey3.key"
key4 <- getKey "CookieKey4.key"
iv1 <- randomIV
iv2 <- randomIV
iv3 <- randomIV
iv4 <- randomIV
return $ ParanoidCookie
( encrypt key1 iv1 a,
encrypt key2 iv2 b,
encrypt key3 iv3 c,
encryptMaybe key4 iv4 d)
paranoidDecryptCookie :: CookieT -> IO Cookie
paranoidDecryptCookie (a,b,c,d) = do
key1 <- getKey "CookieKey1.key"
key2 <- getKey "CookieKey2.key"
key3 <- getKey "CookieKey3.key"
key4 <- getKey "CookieKey4.key"
return $ UnEncryptedCookie
( decryptFM key1 a,
decryptFM key2 b,
decryptFM key3 c,
decryptMaybe key4 d)
-- Uses a single key to encrypt all 4 fields.
encryptCookie :: CookieT -> IO Cookie
encryptCookie (a,b,c,d) = do
key <- getKey "CookieKey.key"
iv1 <- randomIV
iv2 <- randomIV
iv3 <- randomIV
iv4 <- randomIV
return $ EncryptedCookie
( encrypt key iv1 a,
encrypt key iv2 b,
encrypt key iv3 c,
encryptMaybe key iv4 d)
decryptCookie' :: CookieT -> IO Cookie
decryptCookie' (a,b,c,d) = do
key <- getKey "CookieKey.key"
return $ UnEncryptedCookie
( decryptFM key a,
decryptFM key b,
decryptFM key c,
decryptMaybe key d)
encryptMaybe :: Key -> IV -> Maybe ByteString -> Maybe ByteString
encryptMaybe k i (Just s) = Just $ encrypt k i s
encryptMaybe _ _ Nothing = Nothing
decryptMaybe :: Key -> Maybe ByteString -> Maybe ByteString
decryptMaybe k (Just s) = Just $ fromMaybe "" $ decrypt k s
decryptMaybe _ Nothing = Nothing
decryptFM :: Key -> ByteString -> ByteString
decryptFM k b = fromMaybe "" $ decrypt k b
cookieToTuple :: Cookie -> CookieT
cookieToTuple (UnEncryptedCookie c) = c
cookieToTuple (EncryptedCookie c) = c
cookieToTuple (ParanoidCookie c) = c
decryptAndToTuple :: Cookie -> CookieT
decryptAndToTuple = cookieToTuple . unsafePerformIO . decryptCookie
| agocorona/MFlow | src/MFlow/Cookies.hs | bsd-3-clause | 5,578 | 1 | 12 | 1,475 | 1,811 | 940 | 871 | 148 | 3 |
{-# LANGUAGE NoOverloadedStrings, TypeSynonymInstances, GADTs, CPP #-}
{- | Description : Wrapper around GHC API, exposing a single `evaluate` interface that runs
a statement, declaration, import, or directive.
This module exports all functions used for evaluation of IHaskell input.
-}
module IHaskell.Eval.Evaluate (
interpret,
evaluate,
flushWidgetMessages,
Interpreter,
liftIO,
typeCleaner,
globalImports,
formatType,
capturedIO,
) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as CBS
import Control.Concurrent (forkIO, threadDelay)
import Prelude (putChar, head, tail, last, init, (!!))
import Data.List (findIndex, and, foldl1, nubBy)
import Text.Printf
import Data.Char as Char
import Data.Dynamic
import Data.Typeable
import qualified Data.Serialize as Serialize
import System.Directory
#if !MIN_VERSION_base(4,8,0)
import System.Posix.IO (createPipe)
#endif
import System.Posix.IO (fdToHandle)
import System.IO (hGetChar, hFlush)
import System.Random (getStdGen, randomRs)
import Unsafe.Coerce
import Control.Monad (guard)
import System.Process
import System.Exit
import Data.Maybe (fromJust)
import qualified Control.Monad.IO.Class as MonadIO (MonadIO, liftIO)
import qualified MonadUtils (MonadIO, liftIO)
import System.Environment (getEnv)
import qualified Data.Map as Map
import NameSet
import Name
import PprTyThing
import InteractiveEval
import DynFlags
import Type
import Exception (gtry)
import HscTypes
import HscMain
import qualified Linker
import TcType
import Unify
import InstEnv
#if MIN_VERSION_ghc(7, 8, 0)
import GhcMonad (liftIO, withSession)
#else
import GhcMonad (withSession)
#endif
import GHC hiding (Stmt, TypeSig)
import Exception hiding (evaluate)
import Outputable hiding ((<>))
import Packages
import Module hiding (Module)
import qualified Pretty
import FastString
import Bag
import ErrUtils (errMsgShortDoc, errMsgExtraInfo)
import IHaskell.Types
import IHaskell.IPython
import IHaskell.Eval.Parser
import IHaskell.Eval.Lint
import IHaskell.Display
import qualified IHaskell.Eval.Hoogle as Hoogle
import IHaskell.Eval.Util
import IHaskell.Eval.Widgets
import IHaskell.BrokenPackages
import qualified IHaskell.IPython.Message.UUID as UUID
import StringUtils (replace, split, strip, rstrip)
import Paths_ihaskell (version)
import Data.Version (versionBranch)
data ErrorOccurred = Success
| Failure
deriving (Show, Eq)
-- | Set GHC's verbosity for debugging
ghcVerbosity :: Maybe Int
ghcVerbosity = Nothing -- Just 5
ignoreTypePrefixes :: [String]
ignoreTypePrefixes = [ "GHC.Types"
, "GHC.Base"
, "GHC.Show"
, "System.IO"
, "GHC.Float"
, ":Interactive"
, "GHC.Num"
, "GHC.IO"
, "GHC.Integer.Type"
]
typeCleaner :: String -> String
typeCleaner = useStringType . foldl' (.) id (map (`replace` "") fullPrefixes)
where
fullPrefixes = map (++ ".") ignoreTypePrefixes
useStringType = replace "[Char]" "String"
-- MonadIO constraint necessary for GHC 7.6
write :: (MonadIO m, GhcMonad m) => KernelState -> String -> m ()
write state x = when (kernelDebug state) $ liftIO $ hPutStrLn stderr $ "DEBUG: " ++ x
type Interpreter = Ghc
#if MIN_VERSION_ghc(7, 8, 0)
-- GHC 7.8 exports a MonadIO instance for Ghc
#else
instance MonadIO.MonadIO Interpreter where
liftIO = MonadUtils.liftIO
#endif
globalImports :: [String]
globalImports =
[ "import IHaskell.Display()"
, "import qualified Prelude as IHaskellPrelude"
, "import qualified System.Directory as IHaskellDirectory"
, "import qualified IHaskell.Display"
, "import qualified IHaskell.IPython.Stdin"
, "import qualified IHaskell.Eval.Widgets"
, "import qualified System.Posix.IO as IHaskellIO"
, "import qualified System.IO as IHaskellSysIO"
, "import qualified Language.Haskell.TH as IHaskellTH"
]
-- | Run an interpreting action. This is effectively runGhc with initialization and importing. First
-- argument indicates whether `stdin` is handled specially, which cannot be done in a testing
-- environment.
interpret :: String -> Bool -> Interpreter a -> IO a
interpret libdir allowedStdin action = runGhc (Just libdir) $ do
-- If we're in a sandbox, add the relevant package database
sandboxPackages <- liftIO getSandboxPackageConf
initGhci sandboxPackages
case ghcVerbosity of
Just verb -> do
dflags <- getSessionDynFlags
void $ setSessionDynFlags $ dflags { verbosity = verb }
Nothing -> return ()
initializeImports
-- Close stdin so it can't be used. Otherwise it'll block the kernel forever.
dir <- liftIO getIHaskellDir
let cmd = printf "IHaskell.IPython.Stdin.fixStdin \"%s\"" dir
when allowedStdin $ void $
runStmt cmd RunToCompletion
initializeItVariable
-- Run the rest of the interpreter
action
#if MIN_VERSION_ghc(7,10,2)
packageIdString' dflags pkg_key = fromMaybe "(unknown)" (packageKeyPackageIdString dflags pkg_key)
#elif MIN_VERSION_ghc(7,10,0)
packageIdString' dflags = packageKeyPackageIdString dflags
#else
packageIdString' dflags = packageIdString
#endif
-- | Initialize our GHC session with imports and a value for 'it'.
initializeImports :: Interpreter ()
initializeImports = do
-- Load packages that start with ihaskell-*, aren't just IHaskell, and depend directly on the right
-- version of the ihaskell library. Also verify that the packages we load are not broken.
dflags <- getSessionDynFlags
broken <- liftIO getBrokenPackages
displayPackages <- liftIO $ do
(dflags, _) <- initPackages dflags
let Just db = pkgDatabase dflags
packageNames = map (packageIdString' dflags . packageConfigId) db
initStr = "ihaskell-"
-- Name of the ihaskell package, e.g. "ihaskell-1.2.3.4"
iHaskellPkgName = initStr ++ intercalate "."
(map show (versionBranch version))
dependsOnRight pkg = not $ null $ do
pkg <- db
depId <- depends pkg
dep <- filter ((== depId) . installedPackageId) db
let idString = packageIdString' dflags (packageConfigId dep)
guard (iHaskellPkgName `isPrefixOf` idString)
-- ideally the Paths_ihaskell module could provide a way to get the hash too
-- (ihaskell-0.2.0.5-f2bce922fa881611f72dfc4a854353b9), for now. Things will end badly if you also
-- happen to have an ihaskell-0.2.0.5-ce34eadc18cf2b28c8d338d0f3755502 installed.
iHaskellPkg =
case filter (== iHaskellPkgName) packageNames of
[x] -> x
[] -> error
("cannot find required haskell library: " ++ iHaskellPkgName)
_ -> error
("multiple haskell packages " ++ iHaskellPkgName ++ " found")
displayPkgs = [pkgName | pkgName <- packageNames
, Just (x:_) <- [stripPrefix initStr pkgName]
, pkgName `notElem` broken
, isAlpha x]
return displayPkgs
-- Generate import statements all Display modules.
let capitalize :: String -> String
capitalize (first:rest) = Char.toUpper first : rest
importFmt = "import IHaskell.Display.%s"
dropFirstAndLast :: [a] -> [a]
dropFirstAndLast = reverse . drop 1 . reverse . drop 1
toImportStmt :: String -> String
toImportStmt = printf importFmt . concatMap capitalize . dropFirstAndLast . split "-"
displayImports = map toImportStmt displayPackages
-- Import implicit prelude.
importDecl <- parseImportDecl "import Prelude"
let implicitPrelude = importDecl { ideclImplicit = True }
-- Import modules.
imports <- mapM parseImportDecl $ globalImports ++ displayImports
setContext $ map IIDecl $ implicitPrelude : imports
-- Set -fcontext-stack to 100 (default in ghc-7.10). ghc-7.8 uses 20, which is too small.
let contextStackFlag = printf "-fcontext-stack=%d" (100 :: Int)
void $ setFlags [contextStackFlag]
-- | Give a value for the `it` variable.
initializeItVariable :: Interpreter ()
initializeItVariable =
-- This is required due to the way we handle `it` in the wrapper statements - if it doesn't exist,
-- the first statement will fail.
void $ runStmt "let it = ()" RunToCompletion
-- | Publisher for IHaskell outputs. The first argument indicates whether this output is final
-- (true) or intermediate (false).
type Publisher = (EvaluationResult -> IO ())
-- | Output of a command evaluation.
data EvalOut =
EvalOut
{ evalStatus :: ErrorOccurred
, evalResult :: Display
, evalState :: KernelState
, evalPager :: String
, evalMsgs :: [WidgetMsg]
}
cleanString :: String -> String
cleanString x = if allBrackets
then clean
else str
where
str = strip x
l = lines str
allBrackets = all (fAny [isPrefixOf ">", null]) l
fAny fs x = any ($x) fs
clean = unlines $ map removeBracket l
removeBracket ('>':xs) = xs
removeBracket [] = []
-- should never happen:
removeBracket other = error $ "Expected bracket as first char, but got string: " ++ other
-- | Evaluate some IPython input code.
evaluate :: KernelState -- ^ The kernel state.
-> String -- ^ Haskell code or other interpreter commands.
-> Publisher -- ^ Function used to publish data outputs.
-> (KernelState -> [WidgetMsg] -> IO KernelState) -- ^ Function to handle widget messages
-> Interpreter KernelState
evaluate kernelState code output widgetHandler = do
cmds <- parseString (cleanString code)
let execCount = getExecutionCounter kernelState
-- Extract all parse errors.
let justError x@ParseError{} = Just x
justError _ = Nothing
errs = mapMaybe (justError . unloc) cmds
updated <- case errs of
-- Only run things if there are no parse errors.
[] -> do
when (getLintStatus kernelState /= LintOff) $ liftIO $ do
lintSuggestions <- lint cmds
unless (noResults lintSuggestions) $
output $ FinalResult lintSuggestions [] []
runUntilFailure kernelState (map unloc cmds ++ [storeItCommand execCount])
-- Print all parse errors.
errs -> do
forM_ errs $ \err -> do
out <- evalCommand output err kernelState
liftIO $ output $ FinalResult (evalResult out) [] []
return kernelState
return updated { getExecutionCounter = execCount + 1 }
where
noResults (Display res) = null res
noResults (ManyDisplay res) = all noResults res
runUntilFailure :: KernelState -> [CodeBlock] -> Interpreter KernelState
runUntilFailure state [] = return state
runUntilFailure state (cmd:rest) = do
evalOut <- evalCommand output cmd state
-- Get displayed channel outputs. Merge them with normal display outputs.
dispsIO <- extractValue "IHaskell.Display.displayFromChan"
dispsMay <- liftIO dispsIO
let result =
case dispsMay of
Nothing -> evalResult evalOut
Just disps -> evalResult evalOut <> disps
helpStr = evalPager evalOut
-- Output things only if they are non-empty.
let empty = noResults result && null helpStr
unless empty $
liftIO $ output $ FinalResult result [plain helpStr] []
let tempMsgs = evalMsgs evalOut
tempState = evalState evalOut { evalMsgs = [] }
-- Handle the widget messages
newState <- flushWidgetMessages tempState tempMsgs widgetHandler
case evalStatus evalOut of
Success -> runUntilFailure newState rest
Failure -> return newState
storeItCommand execCount = Statement $ printf "let it%d = it" execCount
-- | Compile a string and extract a value from it. Effectively extract the result of an expression
-- from inside the notebook environment.
extractValue :: Typeable a => String -> Interpreter a
extractValue expr = do
compiled <- dynCompileExpr expr
case fromDynamic compiled of
Nothing -> error "Error casting types in Evaluate.hs"
Just result -> return result
flushWidgetMessages :: KernelState
-> [WidgetMsg]
-> (KernelState -> [WidgetMsg] -> IO KernelState)
-> Interpreter KernelState
flushWidgetMessages state evalMsgs widgetHandler = do
-- Capture all widget messages queued during code execution
messagesIO <- extractValue "IHaskell.Eval.Widgets.relayWidgetMessages"
messages <- liftIO messagesIO
-- Handle all the widget messages
let commMessages = evalMsgs ++ messages
liftIO $ widgetHandler state commMessages
safely :: KernelState -> Interpreter EvalOut -> Interpreter EvalOut
safely state = ghandle handler . ghandle sourceErrorHandler
where
handler :: SomeException -> Interpreter EvalOut
handler exception =
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError $ show exception
, evalState = state
, evalPager = ""
, evalMsgs = []
}
sourceErrorHandler :: SourceError -> Interpreter EvalOut
sourceErrorHandler srcerr = do
let msgs = bagToList $ srcErrorMessages srcerr
errStrs <- forM msgs $ \msg -> do
shortStr <- doc $ errMsgShortDoc msg
contextStr <- doc $ errMsgExtraInfo msg
return $ unlines [shortStr, contextStr]
let fullErr = unlines errStrs
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError fullErr
, evalState = state
, evalPager = ""
, evalMsgs = []
}
wrapExecution :: KernelState
-> Interpreter Display
-> Interpreter EvalOut
wrapExecution state exec = safely state $
exec >>= \res ->
return
EvalOut
{ evalStatus = Success
, evalResult = res
, evalState = state
, evalPager = ""
, evalMsgs = []
}
-- | Return the display data for this command, as well as whether it resulted in an error.
evalCommand :: Publisher -> CodeBlock -> KernelState -> Interpreter EvalOut
evalCommand _ (Import importStr) state = wrapExecution state $ do
write state $ "Import: " ++ importStr
evalImport importStr
-- Warn about `it` variable.
return $ if "Test.Hspec" `isInfixOf` importStr
then displayError $ "Warning: Hspec is unusable in IHaskell until the resolution of GHC bug #8639." ++
"\nThe variable `it` is shadowed and cannot be accessed, even in qualified form."
else mempty
evalCommand _ (Module contents) state = wrapExecution state $ do
write state $ "Module:\n" ++ contents
-- Write the module contents to a temporary file in our work directory
namePieces <- getModuleName contents
let directory = "./" ++ intercalate "/" (init namePieces) ++ "/"
filename = last namePieces ++ ".hs"
liftIO $ do
createDirectoryIfMissing True directory
writeFile (directory ++ filename) contents
-- Clear old modules of this name
let modName = intercalate "." namePieces
removeTarget $ TargetModule $ mkModuleName modName
removeTarget $ TargetFile filename Nothing
-- Remember which modules we've loaded before.
importedModules <- getContext
let
-- Get the dot-delimited pieces of the module name.
moduleNameOf :: InteractiveImport -> [String]
moduleNameOf (IIDecl decl) = split "." . moduleNameString . unLoc . ideclName $ decl
moduleNameOf (IIModule imp) = split "." . moduleNameString $ imp
-- Return whether this module prevents the loading of the one we're trying to load. If a module B
-- exist, we cannot load A.B. All modules must have unique last names (where A.B has last name B).
-- However, we *can* just reload a module.
preventsLoading mod =
let pieces = moduleNameOf mod
in last namePieces == last pieces && namePieces /= pieces
-- If we've loaded anything with the same last name, we can't use this. Otherwise, GHC tries to load
-- the original *.hs fails and then fails.
case find preventsLoading importedModules of
-- If something prevents loading this module, return an error.
Just previous -> do
let prevLoaded = intercalate "." (moduleNameOf previous)
return $ displayError $
printf "Can't load module %s because already loaded %s" modName prevLoaded
-- Since nothing prevents loading the module, compile and load it.
Nothing -> doLoadModule modName modName
-- | Directives set via `:set`.
evalCommand output (Directive SetDynFlag flagsStr) state = safely state $ do
write state $ "All Flags: " ++ flagsStr
-- Find which flags are IHaskell flags, and which are GHC flags
let flags = words flagsStr
-- Get the kernel state updater for any IHaskell flag; Nothing for things that aren't IHaskell
-- flags.
ihaskellFlagUpdater :: String -> Maybe (KernelState -> KernelState)
ihaskellFlagUpdater flag = getUpdateKernelState <$> find (elem flag . getSetName) kernelOpts
(ihaskellFlags, ghcFlags) = partition (isJust . ihaskellFlagUpdater) flags
write state $ "IHaskell Flags: " ++ unwords ihaskellFlags
write state $ "GHC Flags: " ++ unwords ghcFlags
if null flags
then do
flags <- getSessionDynFlags
return
EvalOut
{ evalStatus = Success
, evalResult = Display
[ plain $ showSDoc flags $ vcat
[ pprDynFlags False flags
, pprLanguages False flags
]
]
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else do
-- Apply all IHaskell flag updaters to the state to get the new state
let state' = foldl' (.) id (map (fromJust . ihaskellFlagUpdater) ihaskellFlags) state
errs <- setFlags ghcFlags
let display =
case errs of
[] -> mempty
_ -> displayError $ intercalate "\n" errs
-- For -XNoImplicitPrelude, remove the Prelude import. For -XImplicitPrelude, add it back in.
if "-XNoImplicitPrelude" `elem` flags
then evalImport "import qualified Prelude as Prelude"
else when ("-XImplicitPrelude" `elem` flags) $ do
importDecl <- parseImportDecl "import Prelude"
let implicitPrelude = importDecl { ideclImplicit = True }
imports <- getContext
setContext $ IIDecl implicitPrelude : imports
return
EvalOut
{ evalStatus = Success
, evalResult = display
, evalState = state'
, evalPager = ""
, evalMsgs = []
}
evalCommand output (Directive SetExtension opts) state = do
write state $ "Extension: " ++ opts
let set = concatMap (" -X" ++) $ words opts
evalCommand output (Directive SetDynFlag set) state
evalCommand output (Directive LoadModule mods) state = wrapExecution state $ do
write state $ "Load Module: " ++ mods
let stripped@(firstChar:remainder) = mods
(modules, removeModule) =
case firstChar of
'+' -> (words remainder, False)
'-' -> (words remainder, True)
_ -> (words stripped, False)
forM_ modules $ \modl -> if removeModule
then removeImport modl
else evalImport $ "import " ++ modl
return mempty
evalCommand a (Directive SetOption opts) state = do
write state $ "Option: " ++ opts
let (existing, nonExisting) = partition optionExists $ words opts
if not $ null nonExisting
then let err = "No such options: " ++ intercalate ", " nonExisting
in return
EvalOut
{ evalStatus = Failure
, evalResult = displayError err
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else let options = mapMaybe findOption $ words opts
updater = foldl' (.) id $ map getUpdateKernelState options
in return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = updater state
, evalPager = ""
, evalMsgs = []
}
where
optionExists = isJust . findOption
findOption opt =
find (elem opt . getOptionName) kernelOpts
evalCommand _ (Directive GetType expr) state = wrapExecution state $ do
write state $ "Type: " ++ expr
formatType <$> ((expr ++ " :: ") ++) <$> getType expr
evalCommand _ (Directive GetKind expr) state = wrapExecution state $ do
write state $ "Kind: " ++ expr
(_, kind) <- GHC.typeKind False expr
flags <- getSessionDynFlags
let typeStr = showSDocUnqual flags $ ppr kind
return $ formatType $ expr ++ " :: " ++ typeStr
evalCommand _ (Directive LoadFile names) state = wrapExecution state $ do
write state $ "Load: " ++ names
displays <- forM (words names) $ \name -> do
let filename = if ".hs" `isSuffixOf` name
then name
else name ++ ".hs"
contents <- liftIO $ readFile filename
modName <- intercalate "." <$> getModuleName contents
doLoadModule filename modName
return (ManyDisplay displays)
evalCommand publish (Directive ShellCmd ('!':cmd)) state = wrapExecution state $
case words cmd of
"cd":dirs -> do
-- Get home so we can replace '~` with it.
homeEither <- liftIO (try $ getEnv "HOME" :: IO (Either SomeException String))
let home =
case homeEither of
Left _ -> "~"
Right val -> val
let directory = replace "~" home $ unwords dirs
exists <- liftIO $ doesDirectoryExist directory
if exists
then do
-- Set the directory in IHaskell native code, for future shell commands. This doesn't set it for
-- user code, though.
liftIO $ setCurrentDirectory directory
-- Set the directory for user code.
let cmd = printf "IHaskellDirectory.setCurrentDirectory \"%s\"" $
replace " " "\\ " $
replace "\"" "\\\"" directory
runStmt cmd RunToCompletion
return mempty
else return $ displayError $ printf "No such directory: '%s'" directory
cmd -> liftIO $ do
(pipe, handle) <- createPipe'
let initProcSpec = shell $ unwords cmd
procSpec = initProcSpec
{ std_in = Inherit
, std_out = UseHandle handle
, std_err = UseHandle handle
}
(_, _, _, process) <- createProcess procSpec
-- Accumulate output from the process.
outputAccum <- liftIO $ newMVar ""
-- Start a loop to publish intermediate results.
let
-- Compute how long to wait between reading pieces of the output. `threadDelay` takes an
-- argument of microseconds.
ms = 1000
delay = 100 * ms
-- Maximum size of the output (after which we truncate).
maxSize = 100 * 1000
incSize = 200
output str = publish $ IntermediateResult $ Display [plain str]
loop = do
-- Wait and then check if the computation is done.
threadDelay delay
-- Read next chunk and append to accumulator.
nextChunk <- readChars pipe "\n" incSize
modifyMVar_ outputAccum (return . (++ nextChunk))
-- Check if we're done.
exitCode <- getProcessExitCode process
let computationDone = isJust exitCode
when computationDone $ do
nextChunk <- readChars pipe "" maxSize
modifyMVar_ outputAccum (return . (++ nextChunk))
if not computationDone
then do
-- Write to frontend and repeat.
readMVar outputAccum >>= output
loop
else do
out <- readMVar outputAccum
case fromJust exitCode of
ExitSuccess -> return $ Display [plain out]
ExitFailure code -> do
let errMsg = "Process exited with error code " ++ show code
htmlErr = printf "<span class='err-msg'>%s</span>" errMsg
return $ Display
[ plain $ out ++ "\n" ++ errMsg
, html $ printf "<span class='mono'>%s</span>" out ++ htmlErr
]
loop
where
#if MIN_VERSION_base(4,8,0)
createPipe' = createPipe
#else
createPipe' = do
(readEnd, writeEnd) <- createPipe
handle <- fdToHandle writeEnd
pipe <- fdToHandle readEnd
return (pipe, handle)
#endif
-- This is taken largely from GHCi's info section in InteractiveUI.
evalCommand _ (Directive GetHelp _) state = do
write state "Help via :help or :?."
return
EvalOut
{ evalStatus = Success
, evalResult = Display [out]
, evalState = state
, evalPager = ""
, evalMsgs = []
}
where
out = plain $ intercalate "\n"
[ "The following commands are available:"
, " :extension <Extension> - Enable a GHC extension."
, " :extension No<Extension> - Disable a GHC extension."
, " :type <expression> - Print expression type."
, " :info <name> - Print all info for a name."
, " :hoogle <query> - Search for a query on Hoogle."
, " :doc <ident> - Get documentation for an identifier via Hogole."
, " :set -XFlag -Wall - Set an option (like ghci)."
, " :option <opt> - Set an option."
, " :option no-<opt> - Unset an option."
, " :?, :help - Show this help text."
, ""
, "Any prefix of the commands will also suffice, e.g. use :ty for :type."
, ""
, "Options:"
, " lint – enable or disable linting."
, " svg – use svg output (cannot be resized)."
, " show-types – show types of all bound names"
, " show-errors – display Show instance missing errors normally."
, " pager – use the pager to display results of :info, :doc, :hoogle, etc."
]
-- This is taken largely from GHCi's info section in InteractiveUI.
evalCommand _ (Directive GetInfo str) state = safely state $ do
write state $ "Info: " ++ str
-- Get all the info for all the names we're given.
strings <- getDescription str
-- TODO: Make pager work without html by porting to newer architecture
let output = unlines (map htmlify strings)
htmlify str =
printf
"<div style='background: rgb(247, 247, 247);'><form><textarea id='code'>%s</textarea></form></div>"
str
++ script
script =
"<script>CodeMirror.fromTextArea(document.getElementById('code'), {mode: 'haskell', readOnly: 'nocursor'});</script>"
return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = output
, evalMsgs = []
}
evalCommand _ (Directive SearchHoogle query) state = safely state $ do
results <- liftIO $ Hoogle.search query
return $ hoogleResults state results
evalCommand _ (Directive GetDoc query) state = safely state $ do
results <- liftIO $ Hoogle.document query
return $ hoogleResults state results
evalCommand output (Statement stmt) state = wrapExecution state $ evalStatementOrIO output state
(CapturedStmt stmt)
evalCommand output (Expression expr) state = do
write state $ "Expression:\n" ++ expr
-- Try to use `display` to convert our type into the output Dislay If typechecking fails and there
-- is no appropriate typeclass instance, this will throw an exception and thus `attempt` will return
-- False, and we just resort to plaintext.
let displayExpr = printf "(IHaskell.Display.display (%s))" expr :: String
canRunDisplay <- attempt $ exprType displayExpr
-- Check if this is a widget.
let widgetExpr = printf "(IHaskell.Display.Widget (%s))" expr :: String
isWidget <- attempt $ exprType widgetExpr
-- Check if this is a template haskell declaration
let declExpr = printf "((id :: IHaskellTH.DecsQ -> IHaskellTH.DecsQ) (%s))" expr :: String
let anyExpr = printf "((id :: IHaskellPrelude.Int -> IHaskellPrelude.Int) (%s))" expr :: String
isTHDeclaration <- liftM2 (&&) (attempt $ exprType declExpr) (not <$> attempt (exprType anyExpr))
write state $ "Can Display: " ++ show canRunDisplay
write state $ "Is Widget: " ++ show isWidget
write state $ "Is Declaration: " ++ show isTHDeclaration
if isTHDeclaration
then
-- If it typechecks as a DecsQ, we do not want to display the DecsQ, we just want the
-- declaration made.
do
write state "Suppressing display for template haskell declaration"
GHC.runDecls expr
return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else if canRunDisplay
then
-- Use the display. As a result, `it` is set to the output.
useDisplay displayExpr
else do
-- Evaluate this expression as though it's just a statement. The output is bound to 'it', so we can
-- then use it.
evalOut <- evalCommand output (Statement expr) state
let out = evalResult evalOut
showErr = isShowError out
-- If evaluation failed, return the failure. If it was successful, we may be able to use the
-- IHaskellDisplay typeclass.
return $ if not showErr || useShowErrors state
then evalOut
else postprocessShowError evalOut
where
-- Try to evaluate an action. Return True if it succeeds and False if it throws an exception. The
-- result of the action is discarded.
attempt :: Interpreter a -> Interpreter Bool
attempt action = gcatch (action >> return True) failure
where
failure :: SomeException -> Interpreter Bool
failure _ = return False
-- Check if the error is due to trying to print something that doesn't implement the Show typeclass.
isShowError (ManyDisplay _) = False
isShowError (Display errs) =
-- Note that we rely on this error message being 'type cleaned', so that `Show` is not displayed as
-- GHC.Show.Show. This is also very fragile!
"No instance for (Show" `isPrefixOf` msg &&
isInfixOf "print it" msg
where
msg = extractPlain errs
isSvg (DisplayData mime _) = mime == MimeSvg
removeSvg :: Display -> Display
removeSvg (Display disps) = Display $ filter (not . isSvg) disps
removeSvg (ManyDisplay disps) = ManyDisplay $ map removeSvg disps
useDisplay displayExpr = do
-- If there are instance matches, convert the object into a Display. We also serialize it into a
-- bytestring. We get the bytestring IO action as a dynamic and then convert back to a bytestring,
-- which we promptly unserialize. Note that attempting to do this without the serialization to
-- binary and back gives very strange errors - all the types match but it refuses to decode back
-- into a Display. Suppress output, so as not to mess up console. First, evaluate the expression in
-- such a way that we have access to `it`.
io <- isIO expr
let stmtTemplate = if io
then "it <- (%s)"
else "let { it = %s }"
evalOut <- evalCommand output (Statement $ printf stmtTemplate expr) state
case evalStatus evalOut of
Failure -> return evalOut
Success -> wrapExecution state $ do
-- Compile the display data into a bytestring.
let compileExpr = "fmap IHaskell.Display.serializeDisplay (IHaskell.Display.display it)"
displayedBytestring <- dynCompileExpr compileExpr
-- Convert from the bytestring into a display.
case fromDynamic displayedBytestring of
Nothing -> error "Expecting lazy Bytestring"
Just bytestringIO -> do
bytestring <- liftIO bytestringIO
case Serialize.decode bytestring of
Left err -> error err
Right display ->
return $
if useSvg state
then display :: Display
else removeSvg display
isIO expr = attempt $ exprType $ printf "((\\x -> x) :: IO a -> IO a) (%s)" expr
postprocessShowError :: EvalOut -> EvalOut
postprocessShowError evalOut = evalOut { evalResult = Display $ map postprocess disps }
where
Display disps = evalResult evalOut
text = extractPlain disps
postprocess (DisplayData MimeHtml _) = html $ printf
fmt
unshowableType
(formatErrorWithClass "err-msg collapse"
text)
script
where
fmt = "<div class='collapse-group'><span class='btn btn-default' href='#' id='unshowable'>Unshowable:<span class='show-type'>%s</span></span>%s</div><script>%s</script>"
script = unlines
[ "$('#unshowable').on('click', function(e) {"
, " e.preventDefault();"
, " var $this = $(this);"
, " var $collapse = $this.closest('.collapse-group').find('.err-msg');"
, " $collapse.collapse('toggle');"
, "});"
]
postprocess other = other
unshowableType = fromMaybe "" $ do
let pieces = words text
before = takeWhile (/= "arising") pieces
after = init $ unwords $ tail $ dropWhile (/= "(Show") before
firstChar <- headMay after
return $ if firstChar == '('
then init $ tail after
else after
evalCommand _ (Declaration decl) state = wrapExecution state $ do
write state $ "Declaration:\n" ++ decl
boundNames <- evalDeclarations decl
let nonDataNames = filter (not . isUpper . head) boundNames
-- Display the types of all bound names if the option is on. This is similar to GHCi :set +t.
if not $ useShowTypes state
then return mempty
else do
-- Get all the type strings.
dflags <- getSessionDynFlags
types <- forM nonDataNames $ \name -> do
theType <- showSDocUnqual dflags . ppr <$> exprType name
return $ name ++ " :: " ++ theType
return $ Display [html $ unlines $ map formatGetType types]
evalCommand _ (TypeSignature sig) state = wrapExecution state $
-- We purposefully treat this as a "success" because that way execution continues. Empty type
-- signatures are likely due to a parse error later on, and we want that to be displayed.
return $ displayError $ "The type signature " ++ sig ++ "\nlacks an accompanying binding."
evalCommand _ (ParseError loc err) state = do
write state "Parse Error."
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError $ formatParseError loc err
, evalState = state
, evalPager = ""
, evalMsgs = []
}
evalCommand _ (Pragma (PragmaUnsupported pragmaType) pragmas) state = wrapExecution state $
return $ displayError $ "Pragmas of type " ++ pragmaType ++ "\nare not supported."
evalCommand output (Pragma PragmaLanguage pragmas) state = do
write state $ "Got LANGUAGE pragma " ++ show pragmas
evalCommand output (Directive SetExtension $ unwords pragmas) state
hoogleResults :: KernelState -> [Hoogle.HoogleResult] -> EvalOut
hoogleResults state results =
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = output
, evalMsgs = []
}
where
-- TODO: Make pager work with plaintext
fmt = Hoogle.HTML
output = unlines $ map (Hoogle.render fmt) results
doLoadModule :: String -> String -> Ghc Display
doLoadModule name modName = do
-- Remember which modules we've loaded before.
importedModules <- getContext
flip gcatch (unload importedModules) $ do
-- Compile loaded modules.
flags <- getSessionDynFlags
errRef <- liftIO $ newIORef []
setSessionDynFlags
flags
{ hscTarget = objTarget flags
, log_action = \dflags sev srcspan ppr msg -> modifyIORef' errRef (showSDoc flags msg :)
}
-- Load the new target.
target <- guessTarget name Nothing
oldTargets <- getTargets
-- Add a target, but make sure targets are unique!
addTarget target
getTargets >>= return . nubBy ((==) `on` targetId) >>= setTargets
result <- load LoadAllTargets
-- Reset the context, since loading things screws it up.
initializeItVariable
-- Reset targets if we failed.
case result of
Failed -> setTargets oldTargets
Succeeded{} -> return ()
-- Add imports
setContext $
case result of
Failed -> importedModules
Succeeded -> IIDecl (simpleImportDecl $ mkModuleName modName) : importedModules
-- Switch back to interpreted mode.
setSessionDynFlags flags
case result of
Succeeded -> return mempty
Failed -> do
errorStrs <- unlines <$> reverse <$> liftIO (readIORef errRef)
return $ displayError $ "Failed to load module " ++ modName ++ "\n" ++ errorStrs
where
unload :: [InteractiveImport] -> SomeException -> Ghc Display
unload imported exception = do
print $ show exception
-- Explicitly clear targets
setTargets []
load LoadAllTargets
-- Switch to interpreted mode!
flags <- getSessionDynFlags
setSessionDynFlags flags { hscTarget = HscInterpreted }
-- Return to old context, make sure we have `it`.
setContext imported
initializeItVariable
return $ displayError $ "Failed to load module " ++ modName ++ ": " ++ show exception
#if MIN_VERSION_ghc(7,8,0)
objTarget flags = defaultObjectTarget $ targetPlatform flags
#else
objTarget flags = defaultObjectTarget
#endif
keepingItVariable :: Interpreter a -> Interpreter a
keepingItVariable act = do
-- Generate the it variable temp name
gen <- liftIO getStdGen
let rand = take 20 $ randomRs ('0', '9') gen
var name = name ++ rand
goStmt s = runStmt s RunToCompletion
itVariable = var "it_var_temp_"
goStmt $ printf "let %s = it" itVariable
val <- act
goStmt $ printf "let it = %s" itVariable
act
data Captured a = CapturedStmt String
| CapturedIO (IO a)
capturedEval :: (String -> IO ()) -- ^ Function used to publish intermediate output.
-> Captured a -- ^ Statement to evaluate.
-> Interpreter (String, RunResult) -- ^ Return the output and result.
capturedEval output stmt = do
-- Generate random variable names to use so that we cannot accidentally override the variables by
-- using the right names in the terminal.
gen <- liftIO getStdGen
let
-- Variable names generation.
rand = take 20 $ randomRs ('0', '9') gen
var name = name ++ rand
-- Variables for the pipe input and outputs.
readVariable = var "file_read_var_"
writeVariable = var "file_write_var_"
-- Variable where to store old stdout.
oldVariable = var "old_var_"
-- Variable used to store true `it` value.
itVariable = var "it_var_"
voidpf str = printf $ str ++ " IHaskellPrelude.>> IHaskellPrelude.return ()"
-- Statements run before the thing we're evaluating.
initStmts =
[ printf "let %s = it" itVariable
, printf "(%s, %s) <- IHaskellIO.createPipe" readVariable writeVariable
, printf "%s <- IHaskellIO.dup IHaskellIO.stdOutput" oldVariable
, voidpf "IHaskellIO.dupTo %s IHaskellIO.stdOutput" writeVariable
, voidpf "IHaskellSysIO.hSetBuffering IHaskellSysIO.stdout IHaskellSysIO.NoBuffering"
, printf "let it = %s" itVariable
]
-- Statements run after evaluation.
postStmts =
[ printf "let %s = it" itVariable
, voidpf "IHaskellSysIO.hFlush IHaskellSysIO.stdout"
, voidpf "IHaskellIO.dupTo %s IHaskellIO.stdOutput" oldVariable
, voidpf "IHaskellIO.closeFd %s" writeVariable
, printf "let it = %s" itVariable
]
pipeExpr = printf "let %s = %s" (var "pipe_var_") readVariable
goStmt :: String -> Ghc RunResult
goStmt s = runStmt s RunToCompletion
runWithResult (CapturedStmt str) = goStmt str
runWithResult (CapturedIO io) = do
status <- gcatch (liftIO io >> return NoException) (return . AnyException)
return $
case status of
NoException -> RunOk []
AnyException e -> RunException e
-- Initialize evaluation context.
void $ forM initStmts goStmt
-- Get the pipe to read printed output from. This is effectively the source code of dynCompileExpr
-- from GHC API's InteractiveEval. However, instead of using a `Dynamic` as an intermediary, it just
-- directly reads the value. This is incredibly unsafe! However, for some reason the `getContext`
-- and `setContext` required by dynCompileExpr (to import and clear Data.Dynamic) cause issues with
-- data declarations being updated (e.g. it drops newer versions of data declarations for older ones
-- for unknown reasons). First, compile down to an HValue.
Just (_, hValues, _) <- withSession $ liftIO . flip hscStmt pipeExpr
-- Then convert the HValue into an executable bit, and read the value.
pipe <- liftIO $ do
fd <- head <$> unsafeCoerce hValues
fdToHandle fd
-- Keep track of whether execution has completed.
completed <- liftIO $ newMVar False
finishedReading <- liftIO newEmptyMVar
outputAccum <- liftIO $ newMVar ""
-- Start a loop to publish intermediate results.
let
-- Compute how long to wait between reading pieces of the output. `threadDelay` takes an
-- argument of microseconds.
ms = 1000
delay = 100 * ms
-- How much to read each time.
chunkSize = 100
-- Maximum size of the output (after which we truncate).
maxSize = 100 * 1000
loop = do
-- Wait and then check if the computation is done.
threadDelay delay
computationDone <- readMVar completed
if not computationDone
then do
-- Read next chunk and append to accumulator.
nextChunk <- readChars pipe "\n" 100
modifyMVar_ outputAccum (return . (++ nextChunk))
-- Write to frontend and repeat.
readMVar outputAccum >>= output
loop
else do
-- Read remainder of output and accumulate it.
nextChunk <- readChars pipe "" maxSize
modifyMVar_ outputAccum (return . (++ nextChunk))
-- We're done reading.
putMVar finishedReading True
liftIO $ forkIO loop
result <- gfinally (runWithResult stmt) $ do
-- Execution is done.
liftIO $ modifyMVar_ completed (const $ return True)
-- Finalize evaluation context.
void $ forM postStmts goStmt
-- Once context is finalized, reading can finish. Wait for reading to finish to that the output
-- accumulator is completely filled.
liftIO $ takeMVar finishedReading
printedOutput <- liftIO $ readMVar outputAccum
return (printedOutput, result)
data AnyException = NoException
| AnyException SomeException
capturedIO :: Publisher -> KernelState -> IO a -> Interpreter Display
capturedIO publish state action = do
let showError = return . displayError . show
handler e@SomeException{} = showError e
gcatch (evalStatementOrIO publish state (CapturedIO action)) handler
-- | Evaluate a @Captured@, and then publish the final result to the frontend. Returns the final
-- Display.
evalStatementOrIO :: Publisher -> KernelState -> Captured a -> Interpreter Display
evalStatementOrIO publish state cmd = do
let output str = publish . IntermediateResult $ Display [plain str]
case cmd of
CapturedStmt stmt ->
write state $ "Statement:\n" ++ stmt
CapturedIO io ->
write state "Evaluating Action"
(printed, result) <- capturedEval output cmd
case result of
RunOk names -> do
dflags <- getSessionDynFlags
let allNames = map (showPpr dflags) names
isItName name =
name == "it" ||
name == "it" ++ show (getExecutionCounter state)
nonItNames = filter (not . isItName) allNames
output = [plain printed | not . null $ strip printed]
write state $ "Names: " ++ show allNames
-- Display the types of all bound names if the option is on. This is similar to GHCi :set +t.
if not $ useShowTypes state
then return $ Display output
else do
-- Get all the type strings.
types <- forM nonItNames $ \name -> do
theType <- showSDocUnqual dflags . ppr <$> exprType name
return $ name ++ " :: " ++ theType
let joined = unlines types
htmled = unlines $ map formatGetType types
return $
case extractPlain output of
"" -> Display [html htmled]
-- Return plain and html versions. Previously there was only a plain version.
text -> Display [plain $ joined ++ "\n" ++ text, html $ htmled ++ mono text]
RunException exception -> throw exception
RunBreak{} -> error "Should not break."
-- Read from a file handle until we hit a delimiter or until we've read as many characters as
-- requested
readChars :: Handle -> String -> Int -> IO String
readChars handle delims 0 =
-- If we're done reading, return nothing.
return []
readChars handle delims nchars = do
-- Try reading a single character. It will throw an exception if the handle is already closed.
tryRead <- gtry $ hGetChar handle :: IO (Either SomeException Char)
case tryRead of
Right char ->
-- If this is a delimiter, stop reading.
if char `elem` delims
then return [char]
else do
next <- readChars handle delims (nchars - 1)
return $ char : next
-- An error occurs at the end of the stream, so just stop reading.
Left _ -> return []
formatError :: ErrMsg -> String
formatError = formatErrorWithClass "err-msg"
formatErrorWithClass :: String -> ErrMsg -> String
formatErrorWithClass cls =
printf "<span class='%s'>%s</span>" cls .
replace "\n" "<br/>" .
replace useDashV "" .
replace "Ghci" "IHaskell" .
replace "‘interactive:" "‘" .
fixDollarSigns .
rstrip .
typeCleaner
where
fixDollarSigns = replace "$" "<span>$</span>"
useDashV = "\nUse -v to see a list of the files searched for."
isShowError err =
"No instance for (Show" `isPrefixOf` err &&
isInfixOf " arising from a use of `print'" err
formatParseError :: StringLoc -> String -> ErrMsg
formatParseError (Loc line col) =
printf "Parse error (line %d, column %d): %s" line col
formatGetType :: String -> String
formatGetType = printf "<span class='get-type'>%s</span>"
formatType :: String -> Display
formatType typeStr = Display [plain typeStr, html $ formatGetType typeStr]
displayError :: ErrMsg -> Display
displayError msg = Display [plain . typeCleaner $ msg, html $ formatError msg]
mono :: String -> String
mono = printf "<span class='mono'>%s</span>"
| FranklinChen/IHaskell | src/IHaskell/Eval/Evaluate.hs | mit | 50,316 | 0 | 30 | 15,590 | 9,784 | 4,946 | 4,838 | 882 | 30 |
module Rasa.Ext.Cursors
(
-- * Main
cursors
-- * Actions
, delete
, insertText
, findNext
, findNextFrom
, findPrev
, findPrevFrom
-- * Working with Cursor Ranges
, addRange
, getRanges
, setRanges
, rangeDo
, rangeDo_
, overRanges
, moveRangesByN
, moveRangesByC
) where
import Rasa.Ext
import Rasa.Ext.Cursors.Internal.Base
import Rasa.Ext.Cursors.Internal.Actions
-- | Registers listeners for the extension. The user should add this to their config.
cursors :: App ()
cursors = onBufAdded_ $
\(BufAdded bufRef) -> bufDo_ bufRef setStyleProvider
| samcal/rasa | rasa-ext-cursors/src/Rasa/Ext/Cursors.hs | gpl-3.0 | 593 | 0 | 8 | 126 | 114 | 73 | 41 | 23 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ECS.StartTask
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Starts a new task from the specified task definition on the specified
-- container instance or instances. If you want to use the default Amazon
-- ECS scheduler to place your task, use 'RunTask' instead.
--
-- The list of container instances to start tasks on is limited to 10.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_StartTask.html AWS API Reference> for StartTask.
module Network.AWS.ECS.StartTask
(
-- * Creating a Request
startTask
, StartTask
-- * Request Lenses
, sOverrides
, sCluster
, sStartedBy
, sTaskDefinition
, sContainerInstances
-- * Destructuring the Response
, startTaskResponse
, StartTaskResponse
-- * Response Lenses
, strsFailures
, strsTasks
, strsResponseStatus
) where
import Network.AWS.ECS.Types
import Network.AWS.ECS.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'startTask' smart constructor.
data StartTask = StartTask'
{ _sOverrides :: !(Maybe TaskOverride)
, _sCluster :: !(Maybe Text)
, _sStartedBy :: !(Maybe Text)
, _sTaskDefinition :: !Text
, _sContainerInstances :: ![Text]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartTask' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sOverrides'
--
-- * 'sCluster'
--
-- * 'sStartedBy'
--
-- * 'sTaskDefinition'
--
-- * 'sContainerInstances'
startTask
:: Text -- ^ 'sTaskDefinition'
-> StartTask
startTask pTaskDefinition_ =
StartTask'
{ _sOverrides = Nothing
, _sCluster = Nothing
, _sStartedBy = Nothing
, _sTaskDefinition = pTaskDefinition_
, _sContainerInstances = mempty
}
-- | A list of container overrides in JSON format that specify the name of a
-- container in the specified task definition and the overrides it should
-- receive. You can override the default command for a container (that is
-- specified in the task definition or Docker image) with a 'command'
-- override. You can also override existing environment variables (that are
-- specified in the task definition or Docker image) on a container or add
-- new environment variables to it with an 'environment' override.
--
-- A total of 8192 characters are allowed for overrides. This limit
-- includes the JSON formatting characters of the override structure.
sOverrides :: Lens' StartTask (Maybe TaskOverride)
sOverrides = lens _sOverrides (\ s a -> s{_sOverrides = a});
-- | The short name or full Amazon Resource Name (ARN) of the cluster that
-- you want to start your task on. If you do not specify a cluster, the
-- default cluster is assumed..
sCluster :: Lens' StartTask (Maybe Text)
sCluster = lens _sCluster (\ s a -> s{_sCluster = a});
-- | An optional tag specified when a task is started. For example if you
-- automatically trigger a task to run a batch process job, you could apply
-- a unique identifier for that job to your task with the 'startedBy'
-- parameter. You can then identify which tasks belong to that job by
-- filtering the results of a ListTasks call with the 'startedBy' value.
--
-- If a task is started by an Amazon ECS service, then the 'startedBy'
-- parameter contains the deployment ID of the service that starts it.
sStartedBy :: Lens' StartTask (Maybe Text)
sStartedBy = lens _sStartedBy (\ s a -> s{_sStartedBy = a});
-- | The 'family' and 'revision' ('family:revision') or full Amazon Resource
-- Name (ARN) of the task definition that you want to start. If a
-- 'revision' is not specified, the latest 'ACTIVE' revision is used.
sTaskDefinition :: Lens' StartTask Text
sTaskDefinition = lens _sTaskDefinition (\ s a -> s{_sTaskDefinition = a});
-- | The container instance UUIDs or full Amazon Resource Name (ARN) entries
-- for the container instances on which you would like to place your task.
--
-- The list of container instances to start tasks on is limited to 10.
sContainerInstances :: Lens' StartTask [Text]
sContainerInstances = lens _sContainerInstances (\ s a -> s{_sContainerInstances = a}) . _Coerce;
instance AWSRequest StartTask where
type Rs StartTask = StartTaskResponse
request = postJSON eCS
response
= receiveJSON
(\ s h x ->
StartTaskResponse' <$>
(x .?> "failures" .!@ mempty) <*>
(x .?> "tasks" .!@ mempty)
<*> (pure (fromEnum s)))
instance ToHeaders StartTask where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AmazonEC2ContainerServiceV20141113.StartTask" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON StartTask where
toJSON StartTask'{..}
= object
(catMaybes
[("overrides" .=) <$> _sOverrides,
("cluster" .=) <$> _sCluster,
("startedBy" .=) <$> _sStartedBy,
Just ("taskDefinition" .= _sTaskDefinition),
Just ("containerInstances" .= _sContainerInstances)])
instance ToPath StartTask where
toPath = const "/"
instance ToQuery StartTask where
toQuery = const mempty
-- | /See:/ 'startTaskResponse' smart constructor.
data StartTaskResponse = StartTaskResponse'
{ _strsFailures :: !(Maybe [Failure])
, _strsTasks :: !(Maybe [Task])
, _strsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'StartTaskResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'strsFailures'
--
-- * 'strsTasks'
--
-- * 'strsResponseStatus'
startTaskResponse
:: Int -- ^ 'strsResponseStatus'
-> StartTaskResponse
startTaskResponse pResponseStatus_ =
StartTaskResponse'
{ _strsFailures = Nothing
, _strsTasks = Nothing
, _strsResponseStatus = pResponseStatus_
}
-- | Any failed tasks from your 'StartTask' action are listed here.
strsFailures :: Lens' StartTaskResponse [Failure]
strsFailures = lens _strsFailures (\ s a -> s{_strsFailures = a}) . _Default . _Coerce;
-- | A full description of the tasks that were started. Each task that was
-- successfully placed on your container instances will be described here.
strsTasks :: Lens' StartTaskResponse [Task]
strsTasks = lens _strsTasks (\ s a -> s{_strsTasks = a}) . _Default . _Coerce;
-- | The response status code.
strsResponseStatus :: Lens' StartTaskResponse Int
strsResponseStatus = lens _strsResponseStatus (\ s a -> s{_strsResponseStatus = a});
| olorin/amazonka | amazonka-ecs/gen/Network/AWS/ECS/StartTask.hs | mpl-2.0 | 7,557 | 0 | 14 | 1,736 | 1,038 | 625 | 413 | 121 | 1 |
-------------------------------------------------------------------------------------------
-- |
-- Module : Control.Category.Hask
-- Copyright : 2008 Edward Kmett
-- License : BSD
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- Make it clearer when we are dealing with the category (->) that we mean the category
-- of haskell types via its Hom bifunctor (->)
-------------------------------------------------------------------------------------------
module Control.Category.Hask (Hask) where
type Hask = (->)
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Category/Hask.hs | apache-2.0 | 578 | 0 | 5 | 71 | 34 | 27 | 7 | 2 | 0 |
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Depend where
import Common
import Core
import Syntax
import PP
type Graph a = Map a [a]
graph nbors ps = map f ps
where f (i,d) = (i,[v | v <- nbors d, v/=i, v `elem` domain])
domain = dom ps
scc :: Eq a => Graph a -> [[a]]
scc g = dfs g' (concat (dfs g (dom g)))
where g' = [(i,[x | (x,ys) <- g, i `elem` ys]) | (i,_) <- g]
dfs g is = snd (dfs' ([],[]) is)
where dfs' p [] = p
dfs' p@(vs,ns) (x:xs)
| x `elem` vs = dfs' p xs
| otherwise = dfs' (vs', (x:concat ns'):ns) xs
where (vs',ns') = dfs' (x:vs,[]) (nbors x)
nbors i = fromJust (lookup i g)
order ms ns = ns `zip` map (fromJust . flip lookup ms) ns
group ms nss = map (order ms) nss
topSort :: Eq a => (b -> [a]) -> [(a,b)] -> Either [a] [(a,b)]
topSort nbors ms = case dropWhile (null . tail) ns of
[] -> Right (order ms (concat ns))
xs : _ -> Left xs
where ns = scc (graph nbors ms)
groupBinds (Binds _ te es) = map f ess
where gs = scc (graph evars es)
ess = group es gs
f [(x,e)] = Binds (x `elem` evars e) (restrict te [x]) (restrict es [x])
f es' = Binds True (restrict te xs) (restrict es xs)
where xs = dom es'
groupTypes (Types ke ts) = map f tss
where gs = scc (graph tycons ts)
tss = group ts gs
f ts' = Types (restrict ke cs) (restrict ts cs)
where cs = dom ts'
groupMap bs = map f bss
where gs = scc (graph evars bs)
bss = group bs gs
f bs@[(x,b)] = (x `elem` evars b, restrict bs [x])
f bs' = (True, restrict bs xs)
where xs = dom bs'
-- Dependency analysis on Syntax bindlists -------------------------------------------
isFunEqn v (BEqn (LFun v' _) _) = v == v'
isFunEqn v _ = False
graphInfo [] = []
graphInfo (s@(BSig [v] _) : bs)
= (s:bs1, [v], nub (idents bs1)) : graphInfo bs2
where (bs1,bs2) = span (isFunEqn v) bs
graphInfo (e@(BEqn (LFun v _) rh) : bs)
= (e:bs1, [v], nub (idents (e:bs1))) : graphInfo bs2
where (bs1,bs2) = span (isFunEqn v) bs
graphInfo (e@(BEqn (LPat p) rh) : bs)
= ([e], nub (idents p), nub (idents rh)) : graphInfo bs
graphInfo (BSig _ _ : bs) = graphInfo bs
buildGraph :: [([Bind],[Name],[Name])] -> Graph Int
buildGraph vs = zip ns (map findDeps fvss)
where (_,bvss,fvss) = unzip3 vs
ns = [1..]
dict = concatMap mkDict (zip bvss ns)
mkDict (vs,n) = map (\v -> (v,n)) vs
findDeps xs = [n | Just n <- map (flip lookup dict) xs]
groupBindsS :: [Bind] -> [[Bind]]
groupBindsS bs = map f gs
where infos = graphInfo bs
indexedInfos = [1..] `zip` infos
gs = scc (buildGraph infos)
f indices = concat (map (fst3 . snd) (filter ((`elem` indices) . fst) indexedInfos))
| mattias-lundell/timber-llvm | src/Depend.hs | bsd-3-clause | 5,456 | 0 | 14 | 2,105 | 1,589 | 854 | 735 | 68 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import System.Environment (getArgs)
import Data.Int (Int16, Int32)
import GDAL
{-
type BandType = Int16
type SummaryType = Int
sumTypeInf, sumTypeNegInf :: SummaryType
sumTypeInf = maxBound
sumTypeNegInf = minBound
toDouble :: SummaryType -> Double
toDouble = fromIntegral
toSummaryType :: BandType -> SummaryType
toSummaryType = fromIntegral
-}
type SummaryType = Int
bandType = GDT_Int16
sumTypeInf, sumTypeNegInf :: SummaryType
sumTypeInf = maxBound --1/0
sumTypeNegInf = minBound --(-1/0)
toDouble :: SummaryType -> Double
toDouble = fromIntegral
--toSummaryType :: BandType -> SummaryType
toSummaryType = fromIntegral
main :: IO ()
main = withGDAL $ do
[fname] <- getArgs
summary <- runGDAL_ $ do
openReadOnly fname bandType
>>= getBand 1 >>= computeStatistics toSummaryType
print summary
data Acc = Acc
{ accS :: {-# UNPACK #-} !SummaryType
, accSq :: {-# UNPACK #-} !SummaryType
, accMin :: {-# UNPACK #-} !SummaryType
, accMax :: {-# UNPACK #-} !SummaryType
, accCnt :: {-# UNPACK #-} !Int
}
type Summary = (Double, Double, SummaryType, SummaryType)
computeStatistics
:: GDALType a
=> (a -> SummaryType) -> ROBand s a -> GDAL s Summary
computeStatistics toSummaryType'
= fmap sumarize . GDAL.foldl' folder (Acc 0 0 sumTypeInf sumTypeNegInf 0)
where
folder acc NoData = acc
folder Acc{..} (Value v')
= Acc (accS+v) (accSq+v*v) (min accMin v) (max accMax v) (accCnt+1)
where v = toSummaryType' v'
sumarize Acc{..} = (avg, stddev, accMin, accMax)
where
avg = toDouble accS / fromIntegral accCnt
stddev = sqrt (toDouble accSq / fromIntegral accCnt - avg*avg)
| meteogrid/bindings-gdal | exe/RasterStats.hs | bsd-3-clause | 1,792 | 0 | 14 | 352 | 465 | 252 | 213 | 41 | 2 |
module Snap where
import Snap.Core
--import Snap.Http.Server (httpServe)
--import Snap.Http.Server.Config
--import Snap.Util.FileServe (getSafePath, serveDirectoryWith, simpleDirectoryConfig)
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text as T
--import Data.ByteString (ByteString)
import Data.ByteString.UTF8 (fromString)
--------------------
getTextParam :: String -> Snap (Maybe T.Text)
getTextParam = fmap (fmap $ decodeUtf8With lenientDecode) . getParam . fromString
redirectString :: String -> Snap ()
redirectString = redirect . fromString
pathString :: String -> Snap () -> Snap ()
pathString = path . fromString
| pgj/ActiveHs | Snap.hs | bsd-3-clause | 700 | 0 | 10 | 84 | 157 | 90 | 67 | 12 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
-- | This module provides the core widget combinators and rendering
-- routines. Everything this library does is in terms of these basic
-- primitives.
module Brick.Widgets.Core
( -- * Basic rendering primitives
emptyWidget
, raw
, txt
, str
, fill
-- * Padding
, padLeft
, padRight
, padTop
, padBottom
, padLeftRight
, padTopBottom
, padAll
-- * Box layout
, (<=>)
, (<+>)
, hBox
, vBox
-- * Limits
, hLimit
, vLimit
-- * Attribute mangement
, withDefAttr
, withAttr
, forceAttr
, updateAttrMap
-- * Border style management
, withBorderStyle
-- * Cursor placement
, showCursor
-- * Translation
, translateBy
-- * Cropping
, cropLeftBy
, cropRightBy
, cropTopBy
, cropBottomBy
-- * Scrollable viewports
, viewport
, visible
, visibleRegion
-- ** Adding offsets to cursor positions and visibility requests
, addResultOffset
-- ** Cropping results
, cropToContext
)
where
import Control.Applicative
import Control.Lens ((^.), (.~), (&), (%~), to, _1, _2, each, to, ix)
import Control.Monad (when)
import Control.Monad.Trans.State.Lazy
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Class (lift)
import qualified Data.Text as T
import Data.Default
import Data.Monoid ((<>), mempty)
import qualified Data.Map as M
import qualified Data.Function as DF
import Data.List (sortBy, partition)
import Control.Lens (Lens')
import qualified Graphics.Vty as V
import Control.DeepSeq
import Brick.Types
import Brick.Types.Internal
import Brick.Widgets.Border.Style
import Brick.Util (clOffset, clamp)
import Brick.AttrMap
import Brick.Widgets.Internal
-- | When rendering the specified widget, use the specified border style
-- for any border rendering.
withBorderStyle :: BorderStyle -> Widget -> Widget
withBorderStyle bs p = Widget (hSize p) (vSize p) $ withReaderT (& ctxBorderStyleL .~ bs) (render p)
-- | The empty widget.
emptyWidget :: Widget
emptyWidget = raw V.emptyImage
-- | Add an offset to all cursor locations and visbility requests
-- in the specified rendering result. This function is critical for
-- maintaining correctness in the rendering results as they are
-- processed successively by box layouts and other wrapping combinators,
-- since calls to this function result in converting from widget-local
-- coordinates to (ultimately) terminal-global ones so they can be used
-- by other combinators. You should call this any time you render
-- something and then translate it or otherwise offset it from its
-- original origin.
addResultOffset :: Location -> Result -> Result
addResultOffset off = addCursorOffset off . addVisibilityOffset off
addVisibilityOffset :: Location -> Result -> Result
addVisibilityOffset off r = r & visibilityRequestsL.each.vrPositionL %~ (off <>)
addCursorOffset :: Location -> Result -> Result
addCursorOffset off r =
let onlyVisible = filter isVisible
isVisible l = l^.columnL >= 0 && l^.rowL >= 0
in r & cursorsL %~ (\cs -> onlyVisible $ (`clOffset` off) <$> cs)
unrestricted :: Int
unrestricted = 100000
-- | Build a widget from a 'String'. Breaks newlines up and space-pads
-- short lines out to the length of the longest line.
str :: String -> Widget
str s =
Widget Fixed Fixed $ do
c <- getContext
let theLines = fixEmpty <$> (dropUnused . lines) s
fixEmpty [] = " "
fixEmpty l = l
dropUnused l = take (availWidth c) <$> take (availHeight c) l
case force theLines of
[] -> return def
[one] -> return $ def & imageL .~ (V.string (c^.attrL) one)
multiple ->
let maxLength = maximum $ length <$> multiple
lineImgs = lineImg <$> multiple
lineImg lStr = V.string (c^.attrL) (lStr ++ replicate (maxLength - length lStr) ' ')
in return $ def & imageL .~ (V.vertCat lineImgs)
-- | Build a widget from a one-line 'T.Text' value. Behaves the same as
-- 'str'.
txt :: T.Text -> Widget
txt = str . T.unpack
-- | Pad the specified widget on the left. If max padding is used, this
-- grows greedily horizontally; otherwise it defers to the padded
-- widget.
padLeft :: Padding -> Widget -> Widget
padLeft padding p =
let (f, sz) = case padding of
Max -> (id, Greedy)
Pad i -> (hLimit i, hSize p)
in Widget sz (vSize p) $ do
result <- render p
render $ (f $ vLimit (result^.imageL.to V.imageHeight) $ fill ' ') <+>
(Widget Fixed Fixed $ return result)
-- | Pad the specified widget on the right. If max padding is used,
-- this grows greedily horizontally; otherwise it defers to the padded
-- widget.
padRight :: Padding -> Widget -> Widget
padRight padding p =
let (f, sz) = case padding of
Max -> (id, Greedy)
Pad i -> (hLimit i, hSize p)
in Widget sz (vSize p) $ do
result <- render p
render $ (Widget Fixed Fixed $ return result) <+>
(f $ vLimit (result^.imageL.to V.imageHeight) $ fill ' ')
-- | Pad the specified widget on the top. If max padding is used, this
-- grows greedily vertically; otherwise it defers to the padded widget.
padTop :: Padding -> Widget -> Widget
padTop padding p =
let (f, sz) = case padding of
Max -> (id, Greedy)
Pad i -> (vLimit i, vSize p)
in Widget (hSize p) sz $ do
result <- render p
render $ (f $ hLimit (result^.imageL.to V.imageWidth) $ fill ' ') <=>
(Widget Fixed Fixed $ return result)
-- | Pad the specified widget on the bottom. If max padding is used,
-- this grows greedily vertically; otherwise it defers to the padded
-- widget.
padBottom :: Padding -> Widget -> Widget
padBottom padding p =
let (f, sz) = case padding of
Max -> (id, Greedy)
Pad i -> (vLimit i, vSize p)
in Widget (hSize p) sz $ do
result <- render p
render $ (Widget Fixed Fixed $ return result) <=>
(f $ hLimit (result^.imageL.to V.imageWidth) $ fill ' ')
-- | Pad a widget on the left and right. Defers to the padded widget for
-- growth policy.
padLeftRight :: Int -> Widget -> Widget
padLeftRight c w = padLeft (Pad c) $ padRight (Pad c) w
-- | Pad a widget on the top and bottom. Defers to the padded widget for
-- growth policy.
padTopBottom :: Int -> Widget -> Widget
padTopBottom r w = padTop (Pad r) $ padBottom (Pad r) w
-- | Pad a widget on all sides. Defers to the padded widget for growth
-- policy.
padAll :: Int -> Widget -> Widget
padAll v w = padLeftRight v $ padTopBottom v w
-- | Fill all available space with the specified character. Grows both
-- horizontally and vertically.
fill :: Char -> Widget
fill ch =
Widget Greedy Greedy $ do
c <- getContext
return $ def & imageL .~ (V.charFill (c^.attrL) ch (c^.availWidthL) (c^.availHeightL))
-- | Vertical box layout: put the specified widgets one above the other
-- in the specified order (uppermost first). Defers growth policies to
-- the growth policies of the contained widgets (if any are greedy, so
-- is the box).
vBox :: [Widget] -> Widget
vBox [] = emptyWidget
vBox pairs = renderBox vBoxRenderer pairs
-- | Horizontal box layout: put the specified widgets next to each other
-- in the specified order (leftmost first). Defers growth policies to
-- the growth policies of the contained widgets (if any are greedy, so
-- is the box).
hBox :: [Widget] -> Widget
hBox [] = emptyWidget
hBox pairs = renderBox hBoxRenderer pairs
-- | The process of rendering widgets in a box layout is exactly the
-- same except for the dimension under consideration (width vs. height),
-- in which case all of the same operations that consider one dimension
-- in the layout algorithm need to be switched to consider the other.
-- Because of this we fill a BoxRenderer with all of the functions
-- needed to consider the "primary" dimension (e.g. vertical if the
-- box layout is vertical) as well as the "secondary" dimension (e.g.
-- horizontal if the box layout is vertical). Doing this permits us to
-- have one implementation for box layout and parameterizing on the
-- orientation of all of the operations.
data BoxRenderer =
BoxRenderer { contextPrimary :: Lens' Context Int
, contextSecondary :: Lens' Context Int
, imagePrimary :: V.Image -> Int
, imageSecondary :: V.Image -> Int
, limitPrimary :: Int -> Widget -> Widget
, limitSecondary :: Int -> Widget -> Widget
, primaryWidgetSize :: Widget -> Size
, concatenatePrimary :: [V.Image] -> V.Image
, locationFromOffset :: Int -> Location
, padImageSecondary :: Int -> V.Image -> V.Attr -> V.Image
}
vBoxRenderer :: BoxRenderer
vBoxRenderer =
BoxRenderer { contextPrimary = availHeightL
, contextSecondary = availWidthL
, imagePrimary = V.imageHeight
, imageSecondary = V.imageWidth
, limitPrimary = vLimit
, limitSecondary = hLimit
, primaryWidgetSize = vSize
, concatenatePrimary = V.vertCat
, locationFromOffset = Location . (0 ,)
, padImageSecondary = \amt img a ->
let p = V.charFill a ' ' amt (V.imageHeight img)
in V.horizCat [img, p]
}
hBoxRenderer :: BoxRenderer
hBoxRenderer =
BoxRenderer { contextPrimary = availWidthL
, contextSecondary = availHeightL
, imagePrimary = V.imageWidth
, imageSecondary = V.imageHeight
, limitPrimary = hLimit
, limitSecondary = vLimit
, primaryWidgetSize = hSize
, concatenatePrimary = V.horizCat
, locationFromOffset = Location . (, 0)
, padImageSecondary = \amt img a ->
let p = V.charFill a ' ' (V.imageWidth img) amt
in V.vertCat [img, p]
}
-- | Render a series of widgets in a box layout in the order given.
--
-- The growth policy of a box layout is the most unrestricted of the
-- growth policies of the widgets it contains, so to determine the hSize
-- and vSize of the box we just take the maximum (using the Ord instance
-- for Size) of all of the widgets to be rendered in the box.
--
-- Then the box layout algorithm proceeds as follows. We'll use
-- the vertical case to concretely describe the algorithm, but the
-- horizontal case can be envisioned just by exchanging all
-- "vertical"/"horizontal" and "rows"/"columns", etc., in the
-- description.
--
-- The growth policies of the child widgets determine the order in which
-- they are rendered, i.e., the order in which space in the box is
-- allocated to widgets as the algorithm proceeds. This is because order
-- matters: if we render greedy widgets first, there will be no space
-- left for non-greedy ones.
--
-- So we render all widgets with size 'Fixed' in the vertical dimension
-- first. Each is rendered with as much room as the overall box has, but
-- we assume that they will not be greedy and use it all. If they do,
-- maybe it's because the terminal is small and there just isn't enough
-- room to render everything.
--
-- Then the remaining height is distributed evenly amongst all remaining
-- (greedy) widgets and they are rendered in sub-boxes that are as high
-- as this even slice of rows and as wide as the box is permitted to be.
-- We only do this step at all if rendering the non-greedy widgets left
-- us any space, i.e., if there were any rows left.
--
-- After rendering the non-greedy and then greedy widgets, their images
-- are sorted so that they are stored in the order the original widgets
-- were given. All cursor locations and visibility requests in each
-- sub-widget are translated according to the position of the sub-widget
-- in the box.
--
-- All images are padded to be as wide as the widest sub-widget to
-- prevent attribute over-runs. Without this step the attribute used by
-- a sub-widget may continue on in an undesirable fashion until it hits
-- something with a different attribute. To prevent this and to behave
-- in the least surprising way, we pad the image on the right with
-- whitespace using the context's current attribute.
--
-- Finally, the padded images are concatenated together vertically and
-- returned along with the translated cursor positions and visibility
-- requests.
renderBox :: BoxRenderer -> [Widget] -> Widget
renderBox br ws = do
Widget (maximum $ hSize <$> ws) (maximum $ vSize <$> ws) $ do
c <- getContext
let pairsIndexed = zip [(0::Int)..] ws
(his, lows) = partition (\p -> (primaryWidgetSize br $ snd p) == Fixed) pairsIndexed
renderedHis <- mapM (\(i, prim) -> (i,) <$> render prim) his
renderedLows <- case lows of
[] -> return []
ls -> do
let remainingPrimary = c^.(contextPrimary br) - (sum $ (^._2.imageL.(to $ imagePrimary br)) <$> renderedHis)
primaryPerLow = remainingPrimary `div` length ls
padFirst = remainingPrimary - (primaryPerLow * length ls)
secondaryPerLow = c^.(contextSecondary br)
primaries = replicate (length ls) primaryPerLow & ix 0 %~ (+ padFirst)
let renderLow ((i, prim), pri) =
(i,) <$> (render $ limitPrimary br pri
$ limitSecondary br secondaryPerLow
$ cropToContext prim)
if remainingPrimary > 0 then mapM renderLow (zip ls primaries) else return []
let rendered = sortBy (compare `DF.on` fst) $ renderedHis ++ renderedLows
allResults = snd <$> rendered
allImages = (^.imageL) <$> allResults
allPrimaries = imagePrimary br <$> allImages
allTranslatedResults = (flip map) (zip [0..] allResults) $ \(i, result) ->
let off = locationFromOffset br offPrimary
offPrimary = sum $ take i allPrimaries
in addResultOffset off result
-- Determine the secondary dimension value to pad to. In a
-- vertical box we want all images to be the same width to
-- avoid attribute over-runs or blank spaces with the wrong
-- attribute. In a horizontal box we want all images to have
-- the same height for the same reason.
maxSecondary = maximum $ imageSecondary br <$> allImages
padImage img = padImageSecondary br (maxSecondary - imageSecondary br img) img (c^.attrL)
paddedImages = padImage <$> allImages
cropResultToContext $ Result (concatenatePrimary br paddedImages)
(concat $ cursors <$> allTranslatedResults)
(concat $ visibilityRequests <$> allTranslatedResults)
-- | Limit the space available to the specified widget to the specified
-- number of columns. This is important for constraining the horizontal
-- growth of otherwise-greedy widgets. This is non-greedy horizontally
-- and defers to the limited widget vertically.
hLimit :: Int -> Widget -> Widget
hLimit w p =
Widget Fixed (vSize p) $ do
withReaderT (& availWidthL .~ w) $ render $ cropToContext p
-- | Limit the space available to the specified widget to the specified
-- number of rows. This is important for constraining the vertical
-- growth of otherwise-greedy widgets. This is non-greedy vertically and
-- defers to the limited widget horizontally.
vLimit :: Int -> Widget -> Widget
vLimit h p =
Widget (hSize p) Fixed $ do
withReaderT (& availHeightL .~ h) $ render $ cropToContext p
-- | When drawing the specified widget, set the current attribute used
-- for drawing to the one with the specified name. Note that the widget
-- may use further calls to 'withAttr' to override this; if you really
-- want to prevent that, use 'forceAttr'. Attributes used this way still
-- get merged hierarchically and still fall back to the attribute map's
-- default attribute. If you want to change the default attribute, use
-- 'withDefAttr'.
withAttr :: AttrName -> Widget -> Widget
withAttr an p =
Widget (hSize p) (vSize p) $ do
withReaderT (& ctxAttrNameL .~ an) (render p)
-- | Update the attribute map while rendering the specified widget: set
-- its new default attribute to the one that we get by looking up the
-- specified attribute name in the map.
withDefAttr :: AttrName -> Widget -> Widget
withDefAttr an p =
Widget (hSize p) (vSize p) $ do
c <- getContext
withReaderT (& ctxAttrMapL %~ (setDefault (attrMapLookup an (c^.ctxAttrMapL)))) (render p)
-- | When rendering the specified widget, update the attribute map with
-- the specified transformation.
updateAttrMap :: (AttrMap -> AttrMap) -> Widget -> Widget
updateAttrMap f p =
Widget (hSize p) (vSize p) $ do
withReaderT (& ctxAttrMapL %~ f) (render p)
-- | When rendering the specified widget, force all attribute lookups
-- in the attribute map to use the value currently assigned to the
-- specified attribute name.
forceAttr :: AttrName -> Widget -> Widget
forceAttr an p =
Widget (hSize p) (vSize p) $ do
c <- getContext
withReaderT (& ctxAttrMapL .~ (forceAttrMap (attrMapLookup an (c^.ctxAttrMapL)))) (render p)
-- | Build a widget directly from a raw Vty image.
raw :: V.Image -> Widget
raw img = Widget Fixed Fixed $ return $ def & imageL .~ img
-- | Translate the specified widget by the specified offset amount.
-- Defers to the translated width for growth policy.
translateBy :: Location -> Widget -> Widget
translateBy off p =
Widget (hSize p) (vSize p) $ do
result <- render p
return $ addResultOffset off
$ result & imageL %~ (V.translate (off^.columnL) (off^.rowL))
-- | Crop the specified widget on the left by the specified number of
-- columns. Defers to the translated width for growth policy.
cropLeftBy :: Int -> Widget -> Widget
cropLeftBy cols p =
Widget (hSize p) (vSize p) $ do
result <- render p
let amt = V.imageWidth (result^.imageL) - cols
cropped img = if amt < 0 then V.emptyImage else V.cropLeft amt img
return $ addResultOffset (Location (-1 * cols, 0))
$ result & imageL %~ cropped
-- | Crop the specified widget on the right by the specified number of
-- columns. Defers to the translated width for growth policy.
cropRightBy :: Int -> Widget -> Widget
cropRightBy cols p =
Widget (hSize p) (vSize p) $ do
result <- render p
let amt = V.imageWidth (result^.imageL) - cols
cropped img = if amt < 0 then V.emptyImage else V.cropRight amt img
return $ result & imageL %~ cropped
-- | Crop the specified widget on the top by the specified number of
-- rows. Defers to the translated width for growth policy.
cropTopBy :: Int -> Widget -> Widget
cropTopBy rows p =
Widget (hSize p) (vSize p) $ do
result <- render p
let amt = V.imageHeight (result^.imageL) - rows
cropped img = if amt < 0 then V.emptyImage else V.cropTop amt img
return $ addResultOffset (Location (0, -1 * rows))
$ result & imageL %~ cropped
-- | Crop the specified widget on the bottom by the specified number of
-- rows. Defers to the translated width for growth policy.
cropBottomBy :: Int -> Widget -> Widget
cropBottomBy rows p =
Widget (hSize p) (vSize p) $ do
result <- render p
let amt = V.imageHeight (result^.imageL) - rows
cropped img = if amt < 0 then V.emptyImage else V.cropBottom amt img
return $ result & imageL %~ cropped
-- | When rendering the specified widget, also register a cursor
-- positioning request using the specified name and location.
showCursor :: Name -> Location -> Widget -> Widget
showCursor n cloc p =
Widget (hSize p) (vSize p) $ do
result <- render p
return $ result & cursorsL %~ (CursorLocation cloc (Just n):)
hRelease :: Widget -> Maybe Widget
hRelease p =
case hSize p of
Fixed -> Just $ Widget Greedy (vSize p) $ withReaderT (& availWidthL .~ unrestricted) (render p)
Greedy -> Nothing
vRelease :: Widget -> Maybe Widget
vRelease p =
case vSize p of
Fixed -> Just $ Widget (hSize p) Greedy $ withReaderT (& availHeightL .~ unrestricted) (render p)
Greedy -> Nothing
-- | Render the specified widget in a named viewport with the
-- specified type. This permits widgets to be scrolled without being
-- scrolling-aware. To make the most use of viewports, the specified
-- widget should use the 'visible' combinator to make a "visibility
-- request". This viewport combinator will then translate the resulting
-- rendering to make the requested region visible. In addition, the
-- 'Brick.Main.EventM' monad provides primitives to scroll viewports
-- created by this function if 'visible' is not what you want.
--
-- If a viewport receives more than one visibility request, only the
-- first is honored. If a viewport receives more than one scrolling
-- request from 'Brick.Main.EventM', all are honored in the order in
-- which they are received.
viewport :: Name
-- ^ The name of the viewport (must be unique and stable for
-- reliable behavior)
-> ViewportType
-- ^ The type of viewport (indicates the permitted scrolling
-- direction)
-> Widget
-- ^ The widget to be rendered in the scrollable viewport
-> Widget
viewport vpname typ p =
Widget Greedy Greedy $ do
-- First, update the viewport size.
c <- getContext
let newVp = VP 0 0 newSize
newSize = (c^.availWidthL, c^.availHeightL)
doInsert (Just vp) = Just $ vp & vpSize .~ newSize
doInsert Nothing = Just newVp
lift $ modify (& viewportMapL %~ (M.alter doInsert vpname))
-- Then render the sub-rendering with the rendering layout
-- constraint released (but raise an exception if we are asked to
-- render an infinitely-sized widget in the viewport's scrolling
-- dimension)
let Name vpn = vpname
release = case typ of
Vertical -> vRelease
Horizontal -> hRelease
Both -> \w -> vRelease w >>= hRelease
released = case release p of
Just w -> w
Nothing -> case typ of
Vertical -> error $ "tried to embed an infinite-height widget in vertical viewport " <> (show vpn)
Horizontal -> error $ "tried to embed an infinite-width widget in horizontal viewport " <> (show vpn)
Both -> error $ "tried to embed an infinite-width or infinite-height widget in 'Both' type viewport " <> (show vpn)
initialResult <- render released
-- If the rendering state includes any scrolling requests for this
-- viewport, apply those
reqs <- lift $ gets $ (^.scrollRequestsL)
let relevantRequests = snd <$> filter (\(n, _) -> n == vpname) reqs
when (not $ null relevantRequests) $ do
Just vp <- lift $ gets $ (^.viewportMapL.to (M.lookup vpname))
let updatedVp = applyRequests relevantRequests vp
applyRequests [] v = v
applyRequests (rq:rqs) v =
case typ of
Horizontal -> scrollTo typ rq (initialResult^.imageL) $ applyRequests rqs v
Vertical -> scrollTo typ rq (initialResult^.imageL) $ applyRequests rqs v
Both -> scrollTo Horizontal rq (initialResult^.imageL) $
scrollTo Vertical rq (initialResult^.imageL) $
applyRequests rqs v
lift $ modify (& viewportMapL %~ (M.insert vpname updatedVp))
return ()
-- If the sub-rendering requested visibility, update the scroll
-- state accordingly
when (not $ null $ initialResult^.visibilityRequestsL) $ do
Just vp <- lift $ gets $ (^.viewportMapL.to (M.lookup vpname))
let rq = head $ initialResult^.visibilityRequestsL
updatedVp = case typ of
Both -> scrollToView Horizontal rq $ scrollToView Vertical rq vp
Horizontal -> scrollToView typ rq vp
Vertical -> scrollToView typ rq vp
lift $ modify (& viewportMapL %~ (M.insert vpname updatedVp))
-- Get the viewport state now that it has been updated.
Just vp <- lift $ gets (M.lookup vpname . (^.viewportMapL))
-- Then perform a translation of the sub-rendering to fit into the
-- viewport
translated <- render $ translateBy (Location (-1 * vp^.vpLeft, -1 * vp^.vpTop))
$ Widget Fixed Fixed $ return initialResult
-- Return the translated result with the visibility requests
-- discarded
let translatedSize = ( translated^.imageL.to V.imageWidth
, translated^.imageL.to V.imageHeight
)
case translatedSize of
(0, 0) -> return $ translated & imageL .~ (V.charFill (c^.attrL) ' ' (c^.availWidthL) (c^.availHeightL))
& visibilityRequestsL .~ mempty
_ -> render $ cropToContext
$ padBottom Max
$ padRight Max
$ Widget Fixed Fixed $ return $ translated & visibilityRequestsL .~ mempty
scrollTo :: ViewportType -> ScrollRequest -> V.Image -> Viewport -> Viewport
scrollTo Both _ _ _ = error "BUG: called scrollTo on viewport type 'Both'"
scrollTo Vertical req img vp = vp & vpTop .~ newVStart
where
newVStart = clamp 0 (V.imageHeight img - vp^.vpSize._2) adjustedAmt
adjustedAmt = case req of
VScrollBy amt -> vp^.vpTop + amt
VScrollPage Up -> vp^.vpTop - vp^.vpSize._2
VScrollPage Down -> vp^.vpTop + vp^.vpSize._2
VScrollToBeginning -> 0
VScrollToEnd -> V.imageHeight img - vp^.vpSize._2
_ -> vp^.vpTop
scrollTo Horizontal req img vp = vp & vpLeft .~ newHStart
where
newHStart = clamp 0 (V.imageWidth img - vp^.vpSize._1) adjustedAmt
adjustedAmt = case req of
HScrollBy amt -> vp^.vpLeft + amt
HScrollPage Up -> vp^.vpLeft - vp^.vpSize._1
HScrollPage Down -> vp^.vpLeft + vp^.vpSize._1
HScrollToBeginning -> 0
HScrollToEnd -> V.imageWidth img - vp^.vpSize._1
_ -> vp^.vpLeft
scrollToView :: ViewportType -> VisibilityRequest -> Viewport -> Viewport
scrollToView Both _ _ = error "BUG: called scrollToView on 'Both' type viewport"
scrollToView Vertical rq vp = vp & vpTop .~ newVStart
where
curStart = vp^.vpTop
curEnd = curStart + vp^.vpSize._2
reqStart = rq^.vrPositionL.rowL
reqEnd = rq^.vrPositionL.rowL + rq^.vrSizeL._2
newVStart :: Int
newVStart = if reqStart < curStart
then reqStart
else if reqStart > curEnd || reqEnd > curEnd
then reqEnd - vp^.vpSize._2
else curStart
scrollToView Horizontal rq vp = vp & vpLeft .~ newHStart
where
curStart = vp^.vpLeft
curEnd = curStart + vp^.vpSize._1
reqStart = rq^.vrPositionL.columnL
reqEnd = rq^.vrPositionL.columnL + rq^.vrSizeL._1
newHStart :: Int
newHStart = if reqStart < curStart
then reqStart
else if reqStart > curEnd || reqEnd > curEnd
then reqEnd - vp^.vpSize._1
else curStart
-- | Request that the specified widget be made visible when it is
-- rendered inside a viewport. This permits widgets (whose sizes and
-- positions cannot be known due to being embedded in arbitrary layouts)
-- to make a request for a parent viewport to locate them and scroll
-- enough to put them in view. This, together with 'viewport', is what
-- makes the text editor and list widgets possible without making them
-- deal with the details of scrolling state management.
--
-- This does nothing if not rendered in a viewport.
visible :: Widget -> Widget
visible p =
Widget (hSize p) (vSize p) $ do
result <- render p
let imageSize = ( result^.imageL.to V.imageWidth
, result^.imageL.to V.imageHeight
)
-- The size of the image to be made visible in a viewport must have
-- non-zero size in both dimensions.
return $ if imageSize^._1 > 0 && imageSize^._2 > 0
then result & visibilityRequestsL %~ (VR (Location (0, 0)) imageSize :)
else result
-- | Similar to 'visible', request that a region (with the specified
-- 'Location' as its origin and 'V.DisplayRegion' as its size) be made
-- visible when it is rendered inside a viewport. The 'Location' is
-- relative to the specified widget's upper-left corner of (0, 0).
--
-- This does nothing if not rendered in a viewport.
visibleRegion :: Location -> V.DisplayRegion -> Widget -> Widget
visibleRegion vrloc sz p =
Widget (hSize p) (vSize p) $ do
result <- render p
-- The size of the image to be made visible in a viewport must have
-- non-zero size in both dimensions.
return $ if sz^._1 > 0 && sz^._2 > 0
then result & visibilityRequestsL %~ (VR vrloc sz :)
else result
-- | Horizontal box layout: put the specified widgets next to each other
-- in the specified order. Defers growth policies to the growth policies
-- of both widgets. This operator is a binary version of 'hBox'.
(<+>) :: Widget
-- ^ Left
-> Widget
-- ^ Right
-> Widget
(<+>) a b = hBox [a, b]
-- | Vertical box layout: put the specified widgets one above the other
-- in the specified order. Defers growth policies to the growth policies
-- of both widgets. This operator is a binary version of 'vBox'.
(<=>) :: Widget
-- ^ Top
-> Widget
-- ^ Bottom
-> Widget
(<=>) a b = vBox [a, b]
| sisirkoppaka/brick | src/Brick/Widgets/Core.hs | bsd-3-clause | 30,264 | 1 | 27 | 8,113 | 6,474 | 3,438 | 3,036 | -1 | -1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Safe
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- A collection of data types, classes, and functions for interfacing
-- with another programming language.
--
-- Safe API Only.
--
-----------------------------------------------------------------------------
module Foreign.Safe {-# DEPRECATED "Safe is now the default, please use Foreign instead" #-}
( module Data.Bits
, module Data.Int
, module Data.Word
, module Foreign.Ptr
, module Foreign.ForeignPtr
, module Foreign.StablePtr
, module Foreign.Storable
, module Foreign.Marshal
) where
import Data.Bits
import Data.Int
import Data.Word
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.StablePtr
import Foreign.Storable
import Foreign.Marshal
| pparkkin/eta | libraries/base/Foreign/Safe.hs | bsd-3-clause | 1,116 | 0 | 5 | 220 | 115 | 80 | 35 | 19 | 0 |
module Renaming.A2 where
import Renaming.B2
import Renaming.C2
import Renaming.D2
main :: Tree Int ->Bool
main t = isSame (sumSquares (fringe t))
(sumSquares (Renaming.B2.myFringe t)+sumSquares (Renaming.C2.myFringe t))
| kmate/HaRe | test/testdata/Renaming/A2.hs | bsd-3-clause | 240 | 0 | 11 | 46 | 89 | 47 | 42 | 7 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module TH_overloadedlabels where
import Language.Haskell.TH
import GHC.OverloadedLabels
data T = T { sel :: Int}
instance IsLabel "sel" (T -> Int) where
fromLabel (T n) = n
x :: Int
x = $(labelE "sel") (T 5)
y :: Int
y = $( [| #sel |] ) (T 6)
| ezyang/ghc | testsuite/tests/th/TH_overloadedlabels.hs | bsd-3-clause | 457 | 0 | 8 | 79 | 119 | 69 | 50 | 16 | 1 |
-- Tests enhanced polymorphism
module ShouldCompile where
foo xs = let
f :: Eq a => [a] -> [a]
f [] = []
f xs | null (g [True]) = []
| otherwise = tail (g xs)
g :: Eq b => [b] -> [b]
g [] = []
g xs | null (f "hello") = []
| otherwise = tail (f xs)
in f xs
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/tc207.hs | bsd-3-clause | 307 | 2 | 15 | 116 | 175 | 87 | 88 | 11 | 3 |
module Bilinear4 where
import qualified Vector2f as V2
import qualified Vector4f as V4
interpolate :: (V4.T, V4.T, V4.T, V4.T) -> V2.T -> V4.T
interpolate (x0y0, x1y0, x0y1, x1y1) position =
let u0 = V4.interpolate x0y0 (V2.x position) x1y0
u1 = V4.interpolate x0y1 (V2.x position) x1y1
in V4.interpolate u0 (V2.y position) u1
| io7m/r2 | com.io7m.r2.documentation/src/main/resources/com/io7m/r2/documentation/haskell/Bilinear4.hs | isc | 339 | 0 | 12 | 63 | 142 | 79 | 63 | 8 | 1 |
module RPG.Shop where
import Control.Monad (guard, when)
import Control.Arrow ((&&&))
import Data.Maybe (isJust)
class IsItem a where
item :: a -> Item
data Item =
Item { name :: String
, itemCost :: Int
, itemDamage :: Int
, itemArmor :: Int
} deriving (Show, Eq)
newtype Weapon = Weapon Item
deriving (Show, Eq)
instance IsItem Weapon where
item (Weapon i) = i
newtype Armor = Armor Item
deriving (Show, Eq)
instance IsItem Armor where
item (Armor i) = i
newtype Ring = Ring Item
deriving (Show, Eq)
instance IsItem Ring where
item (Ring i) = i
data Equipment =
Equipment { weapon :: Weapon
, equipArmor :: Maybe Armor
, equipRing1 :: Maybe Ring
, equipRing2 :: Maybe Ring
} deriving (Show, Eq)
weapons :: [Weapon]
weapons =
[ Weapon (Item "Dagger" 8 4 0)
, Weapon (Item "Shortsword" 10 5 0)
, Weapon (Item "Warhammer" 25 6 0)
, Weapon (Item "Longsword" 40 7 0)
, Weapon (Item "Greataxe" 74 8 0)
]
armors :: [Armor]
armors =
[ Armor (Item "Leather" 13 0 1)
, Armor (Item "Chainmail" 31 0 2)
, Armor (Item "Splintmail" 53 0 3)
, Armor (Item "Bandedmail" 75 0 4)
, Armor (Item "Platemail" 102 0 5)
]
rings :: [Ring]
rings =
[ Ring (Item "Damage +1" 25 1 0)
, Ring (Item "Damage +2" 50 2 0)
, Ring (Item "Damage +3" 100 3 0)
, Ring (Item "Defense +1" 20 0 1)
, Ring (Item "Defense +2" 40 0 2)
, Ring (Item "Defense +3" 80 0 3)
]
type Arrangement = (Int, Maybe Int, Maybe Int, Maybe Int)
arrangements :: [Arrangement]
arrangements = do
w <- [0..length weapons - 1]
a <- Nothing : map Just [0..length armors - 1]
r1 <- Nothing : map Just [0..length rings - 1]
r2 <- Nothing : map Just [0..length rings - 1]
when (isJust r1 && isJust r2) $
guard (r1 /= r2)
return (w, a, r1, r2)
arrange :: Arrangement -> Equipment
arrange (w, a, r1, r2) =
let weap = weapons !! w
armor' = fmap (armors !!) a
ring1 = fmap (rings !!) r1
ring2 = fmap (rings !!) r2
in Equipment weap armor' ring1 ring2
cost :: Equipment -> Int
cost (Equipment w a r1 r2) = sum [ itemCost (item w)
, cost' a
, cost' r1
, cost' r2
]
where cost' (Just x) = itemCost $ item x
cost' Nothing = 0
allEquipment :: [(Equipment, Int)]
allEquipment = map ((id &&& cost) . arrange) arrangements
| corajr/adventofcode2015 | 21/src/RPG/Shop.hs | mit | 2,504 | 0 | 12 | 783 | 1,026 | 542 | 484 | 78 | 2 |
countingLatticePath :: Int -> Integer
countingLatticePath n = head $ fn (take (n+1) $ repeat 1)
where
fn r@(x:[]) = r -- result
fn xs = let t = tail xs
h = head t * 2
in fn $ foldl (\acc v -> acc ++ [last acc + v]) [h] (tail t)
| samidarko/euler | problem015.hs | mit | 269 | 0 | 16 | 94 | 146 | 74 | 72 | 6 | 2 |
type PhoneNumber = String
type Name = String
type PhoneBook = [(Name, PhoneNumber)]
inPhoneBook :: Name -> PhoneNumber -> PhoneBook -> Bool
inPhoneBook name pnumber pbook = (name, pnumber) `elem` pbook
phoneBook =
[("betty", "555-2938")
,("bonnie", "452-2928")
,("patsy", "493-2928")
,("lucille", "205-2928")
,("wendy", "939-8282")
,("penny", "853-2492")
]
| rglew/lyah | phonebook.hs | mit | 374 | 0 | 7 | 63 | 128 | 80 | 48 | 12 | 1 |
{-# Language DeriveGeneric #-}
{-# Language DeriveFoldable #-}
{-# Language DeriveFunctor #-}
{-# Language DeriveTraversable #-}
module Unison.Remote where
import Data.Aeson (ToJSON(..),FromJSON(..))
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import GHC.Generics
import Unison.Hashable (Hashable, Hashable1)
import qualified Data.ByteString.Base64.URL as Base64
import qualified Data.Text as Text
import qualified Unison.Hashable as H
import qualified Data.Hashable as DH
{-
Representation of the Unison distributed programming API.
data Node
data Local a
data Remote a
at : Node -> a -> Remote a
instance Monad Remote
instance Monad Local
fork : Remote a -> Remote ()
local : Local a -> Remote a
root : Node -> Channel Packet
packet : Remote a -> Packet
`Local` is roughly `IO`, the type of local effects, but has
a few additional functions:
channel : Local (Channel a)
send : a -> Channel a -> Local ()
-- | Registers a callback in a map as a weak ref that sets an MVar
-- if weak ref becomes garbage, remove from the map
receiveAsync : Channel a -> Local (Local a)
-- Can be done a bit more efficiently perhaps
recieve : Channel a -> Local a
awaitAsync : Remote a -> Local (Local a)
await : Remote a -> Local a
For the implementation, a remote computation consists of a step, which evaluates
locally or transfers control to another node, or a step along with a continuation
when the step's result is available. Conceptually represented by the following Haskell type:
data Remote r
= Step r
| forall x . Bind (Step x) (x -> Remote r)
data Step r = Local r | At Node r
Since this data type would not be serializable as a Haskell
data type (would require serializing arbitrary functions), both
`Local` and the `x -> Remote r` are represented as _Unison_
terms, giving the type:
-}
-- `t` will be a Unison term, generally
data Remote t = Step (Step t) | Bind (Step t) t deriving (Generic,Generic1,Show,Eq,Foldable,Functor,Traversable)
instance ToJSON t => ToJSON (Remote t)
instance FromJSON t => FromJSON (Remote t)
newtype Universe = Universe ByteString deriving (Show,Eq,Ord,Generic)
-- Note: start each layer with leading `2` byte, to avoid collisions with
-- terms/types, which start each layer with leading `0`/`1`.
-- See `Hashable1 Type.F`
instance Hashable1 Remote where
hash1 hashCycle hash r = H.accumulate $ tag 2 : case r of
Step s -> [tag 0, hashed1 s]
Bind s t -> [tag 1, hashed1 s, hashed t]
where
tag = H.Tag
hashed1 = H.Hashed . (H.hash1 hashCycle hash)
hashed = H.Hashed . hash
data Step t = Local (Local t) | At Node t deriving (Generic,Generic1,Show,Eq,Foldable,Functor,Traversable)
instance ToJSON t => ToJSON (Step t)
instance FromJSON t => FromJSON (Step t)
instance Hashable1 Step where
hash1 hashCycle hash s = H.accumulate $ case s of
Local l -> [tag 0, hashed1 l]
At n t -> [tag 1, H.accumulateToken n, hashed t]
where
tag = H.Tag
hashed1 = H.Hashed . (H.hash1 hashCycle hash)
hashed = H.Hashed . hash
data Local t
-- fork : Remote a -> Local ()
= Fork (Remote t)
-- channel : Local (Channel a)
| CreateChannel
-- here : Local Node
| Here
-- sleep : Duration -> Local ()
| Sleep Duration
-- receiveAsync : Channel a -> Duration -> Local (Local a)
| ReceiveAsync Channel Duration
-- receive : Channel a -> Local a
| Receive Channel
-- send : Channel a -> a -> Local ()
| Send Channel t
-- spawn : Local Node
| Spawn
| Pure t deriving (Generic,Generic1,Show,Eq,Foldable,Functor,Traversable)
instance ToJSON t => ToJSON (Local t)
instance FromJSON t => FromJSON (Local t)
instance Hashable1 Local where
hash1 hashCycle hash l = H.accumulate $ case l of
Fork r -> [tag 0, hashed1 r]
CreateChannel -> [tag 1]
Here -> [tag 2]
ReceiveAsync c t -> [tag 3, H.accumulateToken c, H.accumulateToken t]
Receive c -> [tag 4, H.accumulateToken c]
Send c t -> [tag 5, H.accumulateToken c, hashed t]
Spawn -> [tag 6]
Sleep (Seconds d) -> [tag 7, H.Double d]
Pure t -> [tag 8, hashed t]
where
tag = H.Tag
hashed1 = H.Hashed . (H.hash1 hashCycle hash)
hashed = H.Hashed . hash
newtype Duration = Seconds { seconds :: Double } deriving (Eq,Ord,Show,Generic)
instance ToJSON Duration
instance FromJSON Duration
instance Hashable Duration where
tokens (Seconds seconds) = [H.Double seconds]
{-
When sending a `Remote` value to a `Node` for evaluation,
the implementation syncs any needed hashes for just the
outermost `Local`, then begins evaluation of the `Local`.
Concurrent with evaluation it syncs any needed hashes for
the continuation of the `Bind` (ignoring this step for a
purely `Local` computation).
When both the `Local` portion of the computation has completed
and any hashes needed by the continuation have also been
synced, the continuation is invoked and evaluated and the
computation is sent to the specified `Node` for its next step.
Note that the computation never 'returns', and it may run forever,
hopping between different nodes. To return a result to some node,
we use some of the effects in `Local` to write the final step to
a channel from which we `receive`.
-}
-- | A node is a host and a public key. For instance: `Node "unisonweb.org" key`
data Node = Node { host :: Text, publicKey :: ByteString } deriving (Eq,Ord,Generic)
instance DH.Hashable Node
instance ToJSON Node where toJSON (Node host key) = toJSON (host, decodeUtf8 (Base64.encode key))
instance FromJSON Node where
parseJSON v = do
(host,key) <- parseJSON v
either fail (pure . Node host) (Base64.decode (encodeUtf8 key))
instance Hashable Node where
tokens (Node host key) = [H.Text host, H.Bytes key]
instance Show Node where
show (Node host key) = "http://" ++ Text.unpack host ++ "/" ++ Text.unpack (decodeUtf8 (Base64.encode key))
newtype Channel = Channel ByteString deriving (Eq,Ord,Generic)
instance Show Channel where
show (Channel id) = Text.unpack (decodeUtf8 (Base64.encode id))
instance ToJSON Channel where toJSON (Channel c) = toJSON (decodeUtf8 (Base64.encode c))
instance FromJSON Channel where
parseJSON v = do
txt <- parseJSON v
either fail (pure . Channel) (Base64.decode (encodeUtf8 txt))
instance Hashable Channel where tokens (Channel c) = H.tokens c
| nightscape/platform | shared/src/Unison/Remote.hs | mit | 6,451 | 0 | 12 | 1,334 | 1,512 | 790 | 722 | 87 | 0 |
module CFDI.Types.Concept where
import CFDI.Chainable
import CFDI.Types.Amount
import CFDI.Types.ConceptTaxes
import CFDI.Types.CustomInfo
import CFDI.Types.MeasurementUnit
import CFDI.Types.ProductDescription
import CFDI.Types.ProductId
import CFDI.Types.ProductOrService
import CFDI.Types.ProductUnit
import CFDI.Types.PropertyAccount
import CFDI.Types.Quantity
import CFDI.XmlNode
import Data.Maybe (catMaybes, maybeToList)
data Concept = Concept
{ conAmount :: Amount
, conCustomInfo :: [CustomInfo]
, conDesc :: ProductDescription
, conDiscount :: Maybe Amount
, conMeasUnit :: MeasurementUnit
, conProdId :: Maybe ProductId
, conProdServ :: ProductOrService
, conPropAcc :: Maybe PropertyAccount
, conQuantity :: Quantity
, conTaxes :: Maybe ConceptTaxes
, conUnit :: Maybe ProductUnit
, conUnitPrice :: Amount
} deriving (Eq, Show)
instance Chainable Concept where
chain c = conProdServ
<@> conProdId
<~> conQuantity
<~> conMeasUnit
<~> conUnit
<~> conDesc
<~> conUnitPrice
<~> conAmount
<~> conDiscount
<~> conTaxes
<~> conCustomInfo
<~~> conPropAcc
<~> (c, "")
instance XmlNode Concept where
attributes n =
[ attr "Importe" $ conAmount n
, attr "Descripcion" $ conDesc n
, attr "ClaveUnidad" $ conMeasUnit n
, attr "ClaveProdServ" $ conProdServ n
, attr "Cantidad" $ conQuantity n
, attr "ValorUnitario" $ conUnitPrice n
] ++ catMaybes
[ attr "Descuento" <$> conDiscount n
, attr "NoIdentificacion" <$> conProdId n
, attr "Unidad" <$> conUnit n
]
children n = maybeToList (renderNode <$> conTaxes n)
++ map renderNode (conCustomInfo n)
++ maybeToList (renderNode <$> conPropAcc n)
nodeName = const "Concepto"
parseNode n = Concept
<$> requireAttribute "Importe" n
<*> parseChildren "InformacionAduanera" n
<*> requireAttribute "Descripcion" n
<*> parseAttribute "Descuento" n
<*> requireAttribute "ClaveUnidad" n
<*> parseAttribute "NoIdentificacion" n
<*> requireAttribute "ClaveProdServ" n
<*> parseChild "CuentaPredial" n
<*> requireAttribute "Cantidad" n
<*> parseChild "Impuestos" n
<*> parseAttribute "Unidad" n
<*> requireAttribute "ValorUnitario" n
| yusent/cfdis | src/CFDI/Types/Concept.hs | mit | 2,408 | 0 | 18 | 607 | 587 | 307 | 280 | 71 | 0 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.RBDVolumeSource
( RBDVolumeSource (..)
, monitors
, image
, fsType
, pool
, user
, keyring
, secretRef
, readOnly
, mkRBDVolumeSource
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions,
deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Kubernetes.Model.V1.LocalObjectReference (LocalObjectReference)
import Prelude hiding (drop, error,
max, min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.
data RBDVolumeSource = RBDVolumeSource
{ _monitors :: !([Text])
, _image :: !(Text)
, _fsType :: !(Maybe Text)
, _pool :: !(Text)
, _user :: !(Text)
, _keyring :: !(Text)
, _secretRef :: !(LocalObjectReference)
, _readOnly :: !(Maybe Bool)
} deriving (Show, Eq, Generic)
makeLenses ''RBDVolumeSource
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''RBDVolumeSource)
instance Arbitrary RBDVolumeSource where
arbitrary = RBDVolumeSource <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a RBDVolumeSource
mkRBDVolumeSource :: [Text] -> Text -> Text -> Text -> Text -> LocalObjectReference -> RBDVolumeSource
mkRBDVolumeSource xmonitorsx ximagex xpoolx xuserx xkeyringx xsecretRefx = RBDVolumeSource xmonitorsx ximagex Nothing xpoolx xuserx xkeyringx xsecretRefx Nothing
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/RBDVolumeSource.hs | mit | 2,508 | 0 | 14 | 862 | 442 | 260 | 182 | 58 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Asterius.Types (JSString (JSString), JSVal (JSVal),
fromJSString, toJSString)
import qualified Control.Foldl as Foldl
import Data.Functor.Identity (Identity (runIdentity))
import Data.Monoid ((<>))
import qualified Data.Text.Lazy as TL
import qualified IgrepCashbook
foreign export javascript "sumIgrepCashbook" sumIgrepCashbook :: JSString -> JSString -> JSString
sumIgrepCashbook :: JSString -> JSString -> JSString
sumIgrepCashbook inPath inContents =
let paths = [fromJSString inPath]
readF _ = return . TL.pack . fromJSString $ inContents
(err, out) =
IgrepCashbook.summaryToConsoleOutput
. runIdentity
$ Foldl.foldM (IgrepCashbook.buildSummary readF) paths
in
toJSString $ TL.unpack (err <> "\n\n\n" <> out)
main :: IO ()
main = return ()
| igrep/igrep-cashbook | hs2/wasm/Main.hs | mit | 944 | 1 | 13 | 254 | 226 | 130 | 96 | 20 | 1 |
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE OverloadedStrings, RecordWildCards, DeriveGeneric #-}
{-|
Copyright : (c) Microsoft
License : MIT
Maintainer : adamsap@microsoft.com
Stability : provisional
Portability : portable
A suite of types describing the abstract syntax tree of the Bond
<https://microsoft.github.io/bond/manual/compiler.html#idl-syntax schema definition language>.
-}
module Language.Bond.Syntax.Types
( -- * Schema definition file
Bond(..)
, QualifiedName
, Import(..)
, Namespace(..)
-- ** Declarations
, Declaration(..)
, Field(..)
, Default(..)
, Modifier(..)
, Constant(..)
-- ** Types
, Type(..)
, TypeParam(..)
, Constraint(..)
-- ** Metadata
, Attribute(..)
-- ** Deprecated
, Language(..)
) where
import Data.Word
-- | Represents fully qualified name
type QualifiedName = [String]
-- | Specifies whether a field is required or optional.
data Modifier =
Optional | -- ^ field is optional and may be omitted during serialization
Required | -- ^ field is required, deserialization will fail if it is missing
RequiredOptional -- ^ deserialization will not fail if the field is missing but it can't be omitted during serialization
deriving (Eq, Show)
-- | Type in the Bond type system
data Type =
BT_Int8 | BT_Int16 | BT_Int32 | BT_Int64 |
BT_UInt8 | BT_UInt16 | BT_UInt32 | BT_UInt64 |
BT_Float | BT_Double |
BT_Bool |
BT_String | BT_WString |
BT_MetaName | BT_MetaFullName |
BT_Blob |
BT_Maybe Type | -- ^ type for fields with the default value of @nothing@
BT_List Type |
BT_Vector Type |
BT_Nullable Type |
BT_Set Type |
BT_Map Type Type |
BT_Bonded Type |
BT_IntTypeArg Int | -- ^ an integer argument in an instance of a generic type 'Alias'
BT_TypeParam TypeParam | -- ^ type parameter of a generic 'Struct' or 'Alias' declaration
BT_UserDefined Declaration [Type] -- ^ user defined type or an instance of a generic type with the specified type arguments
deriving (Eq, Show)
-- | Default value of a field.
data Default =
DefaultBool Bool |
DefaultInteger Integer |
DefaultFloat Double |
DefaultString String |
DefaultEnum String | -- ^ name of an enum 'Constant'
DefaultNothing -- ^ explicitly specified default value of @nothing@
deriving (Eq, Show)
-- | <https://microsoft.github.io/bond/manual/compiler.html#custom-attributes Attribute> for attaching user defined metadata to a 'Declaration' or a 'Field'
data Attribute =
Attribute
{ attrName :: QualifiedName -- attribute name
, attrValue :: String -- value
}
deriving (Eq, Show)
-- | Definition of a 'Struct' field.
data Field =
Field
{ fieldAttributes :: [Attribute] -- zero or more attributes
, fieldOrdinal :: Word16 -- ordinal
, fieldModifier :: Modifier -- field modifier
, fieldType :: Type -- type
, fieldName :: String -- field name
, fieldDefault :: Maybe Default -- optional default value
}
deriving (Eq, Show)
-- | Definition of an 'Enum' constant.
data Constant =
Constant
{ constantName :: String -- enum constant name
, constantValue :: Maybe Int -- optional constant value
}
deriving (Eq, Show)
-- | Constraint on a 'TypeParam'.
data Constraint = Value -- ^ the type parameter allows only value types
deriving (Eq, Show)
-- | Type parameter of a <https://microsoft.github.io/bond/manual/compiler.html#generics generic> 'Struct' or type 'Alias'
data TypeParam =
TypeParam
{ paramName :: String
, paramConstraint :: Maybe Constraint
}
deriving (Eq, Show)
-- | A declaration of a schema type.
data Declaration =
Struct
{ declNamespaces :: [Namespace] -- namespace(s) in which the struct is declared
, declAttributes :: [Attribute] -- zero or more attributes
, declName :: String -- struct identifier
, declParams :: [TypeParam] -- list of type parameters for generics
, structBase :: Maybe Type -- optional base struct
, structFields :: [Field] -- zero or more fields
}
| -- ^ <https://microsoft.github.io/bond/manual/compiler.html#struct-definition struct definition>
Enum
{ declNamespaces :: [Namespace] -- namespace(s) in which the enum is declared
, declAttributes :: [Attribute] -- zero or more attributes
, declName :: String -- enum identifier
, enumConstants :: [Constant] -- one or more enum constant values
}
| -- ^ <https://microsoft.github.io/bond/manual/compiler.html#enum-definition enum definition>
Forward
{ declNamespaces :: [Namespace] -- namespace(s) in which the struct is declared
, declName :: String -- struct identifier
, declParams :: [TypeParam] -- type parameters for generics
}
| -- ^ <https://microsoft.github.io/bond/manual/compiler.html#forward-declaration forward declaration>
Alias
{ declNamespaces :: [Namespace] -- namespace(s) in which the type alias is declared
, declName :: String -- alias identifier
, declParams :: [TypeParam] -- type parameters for generics
, aliasType :: Type -- aliased type
} -- ^ <https://microsoft.github.io/bond/manual/compiler.html#type-aliases type alias definition>
deriving (Eq, Show)
-- | <https://microsoft.github.io/bond/manual/compiler.html#import-statements Import> declaration.
data Import = Import FilePath
deriving (Eq, Show)
-- | Language annotation for namespaces. Note that language-specific
-- namespaces are only supported for backward compatibility and are not
-- recommended.
data Language = Cpp | Cs | Java
deriving (Eq, Show)
-- | <https://microsoft.github.io/bond/manual/compiler.html#namespace-definition Namespace> declaration.
data Namespace =
Namespace
{ nsLanguage :: Maybe Language
, nsName :: QualifiedName
}
deriving (Eq, Show)
-- | The top level type representing the Bond schema definition abstract syntax tree.
data Bond =
Bond
{ bondImports :: [Import]
, bondNamespaces :: [Namespace]
, bondDeclarations :: [Declaration]
}
deriving (Eq, Show)
| alfpark/bond | compiler/src/Language/Bond/Syntax/Types.hs | mit | 7,040 | 0 | 9 | 2,128 | 852 | 554 | 298 | 115 | 0 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
module Protop.Core.Natural
( N(..)
, Zero(..)
, Succ(..)
, Rec(..)
, RECZ(..)
, RECS(..)
, REC(..)
, Add
, add
, Mul
, mul
) where
import Data.Proxy (Proxy(..))
import Numeric.Natural (Natural)
import Protop.Core.Compositions
import Protop.Core.Exponentials
import Protop.Core.Morphisms
import Protop.Core.Objects
import Protop.Core.Products
import Protop.Core.Proofs
import Protop.Core.Setoids
import Protop.Core.Symmetries
import Protop.Core.Terminal
import Protop.Core.Transitivities
data N = N
instance Show N where
show N = "N"
instance IsObject N where
type Domain N = Natural
proxy _ = N
data Zero = Zero
instance Show Zero where
show Zero = "zero"
instance IsMorphism Zero where
type Source Zero = T
type Target Zero = N
onDomains _ = setZero
proxy' _ = Zero
data Succ = Succ
instance Show Succ where
show Succ = "succ"
instance IsMorphism Succ where
type Source Succ = N
type Target Succ = N
onDomains _ = setSucc
proxy' _ = Succ
type CRec z s = ( IsMorphism z
, IsMorphism s
, Source z ~ T
, Target z ~ Source s
, Target s ~ Source s
)
data Rec :: * -> * -> * where
Rec :: CRec z s => z -> s -> Rec z s
instance Show (Rec z s) where
show (Rec z s) = "(Rec " ++ show z ++ " " ++ show s ++ ")"
instance CRec z s => IsMorphism (Rec z s) where
type Source (Rec z s) = N
type Target (Rec z s) = Target z
onDomains (Rec z s) = setRec (z .$ star) (onDomains s)
proxy' _ = Rec (proxy' Proxy) (proxy' Proxy)
data RECZ :: * -> * -> * where
RECZ :: CRec z s => z -> s -> RECZ z s
instance Show (RECZ z s) where
show (RECZ z s) = "(RECZ " ++ show z ++ " " ++ show s ++ ")"
instance CRec z s => IsProof (RECZ z s) where
type Lhs (RECZ z s) = Rec z s :. Zero
type Rhs (RECZ z s) = z
proof (RECZ z _) _ = reflexivity $ z .$ star
proxy'' _ = RECZ (proxy' Proxy) (proxy' Proxy)
data RECS :: * -> * -> * where
RECS :: CRec z s => z -> s -> RECS z s
instance Show (RECS z s) where
show (RECS z s) = "(RECN " ++ show z ++ " " ++ show s ++ ")"
instance CRec z s => IsProof (RECS z s) where
type Lhs (RECS z s) = Rec z s :. Succ
type Rhs (RECS z s) = s :. Rec z s
proof (RECS z s) n = reflexivity $ s :. Rec z s .$ n
proxy'' _ = RECS (proxy' Proxy) (proxy' Proxy)
type CREC z s f pz ps = ( CRec z s
, IsMorphism f
, IsProof pz
, IsProof ps
, Source s ~ N
, Target f ~ Target z
, Lhs pz ~ (f :. Zero)
, Rhs pz ~ z
, Lhs ps ~ (f :. Succ)
, Rhs ps ~ (s :. f)
)
data REC :: * -> * -> * -> * -> * -> * where
REC :: CREC z s f pz ps => z -> s -> f -> pz -> ps -> REC z s f pz ps
instance Show (REC z s f pz ps) where
show (REC z s f pz ps) =
"(REC " ++ show z ++ " " ++ show s ++ " " ++ show f ++ " " ++ show pz ++ " " ++ show ps ++ ")"
instance CREC z s f pz ps => IsProof (REC z s f pz ps) where
type Lhs (REC z s f pz ps) = f
type Rhs (REC z s f pz ps) = Rec z s
proof (REC z s _ pz ps) n = loop 0 $ proof (pz :> SYMM (RECZ z s)) star
where
loop :: Natural -> Proofs (DTarget z) -> PTarget z
loop n' p | n == n' = p
| otherwise = loop (succ n') p'
where
pr :: Proxy (DTarget z)
pr = Proxy
p', p1, p2, p3 :: PTarget z
p' = transitivity pr p1 $ transitivity pr p2 p3
p1 = proof ps n'
p2 = (onProofs $ onDomains s) p
p3 = proof (SYMM $ RECS z s) n'
proxy'' _ = REC (proxy' Proxy) (proxy' Proxy) (proxy' Proxy) (proxy'' Proxy) (proxy'' Proxy)
type Add = Uncurry
(Rec
(Curry T N (Pr2 T N))
(Curry (N :-> N) N (Succ :. Eval N N)))
N
N
add :: Morphism (N :* N) N
add = Morphism $ proxy' (Proxy :: Proxy Add)
type Mul = Uncurry
(Rec
(Curry T N (Zero :. Pr1 T N))
(Curry (N :-> N) N (Add :. (Eval N N :&&& Pr2 (N :-> N) N))))
N
N
mul :: Morphism (N :* N) N
mul = Morphism $ proxy' (Proxy :: Proxy Mul)
| brunjlar/protop | src/Protop/Core/Natural.hs | mit | 4,667 | 0 | 16 | 1,792 | 1,955 | 1,016 | 939 | 129 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
module ZoomHub.Types.ContentMIME
( ContentMIME,
ContentMIME' (ContentMIME),
unContentMIME,
fromText,
)
where
import Codec.MIME.Parse (parseMIMEType)
import Codec.MIME.Type (Type, showType)
import Data.Aeson (ToJSON, Value (String), toJSON)
import Data.Maybe (fromJust)
import qualified Data.Text as T
import Squeal.PostgreSQL (FromValue (..), PG, PGType (PGtext), ToParam (..))
newtype ContentMIME' a = ContentMIME {unContentMIME :: a} deriving (Eq, Show)
type ContentMIME = ContentMIME' Type
toText :: ContentMIME -> T.Text
toText = showType . unContentMIME
fromText :: T.Text -> Maybe ContentMIME
fromText t = ContentMIME <$> parseMIMEType t
-- JSON
instance ToJSON ContentMIME where
toJSON = String . toText
-- Squeal / PostgreSQL
type instance PG ContentMIME = 'PGtext
instance ToParam ContentMIME 'PGtext where
toParam = toParam . toText
instance FromValue 'PGtext ContentMIME where
-- TODO: What if database value is not a valid MIME type?
fromValue = ContentMIME . fromJust . parseMIMEType <$> fromValue @'PGtext
| zoomhub/zoomhub | src/ZoomHub/Types/ContentMIME.hs | mit | 1,219 | 0 | 9 | 191 | 297 | 179 | 118 | 32 | 1 |
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
import Control.Monad (join)
data List a = Nil | Cons a (List a) deriving (Show)
instance Monoid (List a) where
mempty = Nil
Nil `mappend` x = x
x `mappend` Nil = x
Cons x xs `mappend` ys = Cons x (xs `mappend` ys)
instance Functor List where
fmap _ Nil = Nil
fmap f (Cons x xs) = Cons (f x) (fmap f xs)
instance Applicative List where
pure x = Cons x Nil
Nil <*> _ = Nil
_ <*> Nil = Nil
(Cons f fs) <*> xs = fmap f xs `mappend` (fs <*> xs)
concat' :: List (List a) -> List a
concat' Nil = Nil
concat' (Cons x xs) = mappend x (concat' xs)
instance Monad List where
return = pure
Nil >>= _ = Nil
Cons x xs >>= f = concat' $ fmap f (Cons x xs)
instance Arbitrary a => Arbitrary (List a) where
arbitrary = do
a <- arbitrary
b <- arbitrary
elements [Cons a Nil, Cons a (Cons b Nil), Nil]
instance EqProp a => EqProp (List a) where
Nil =-= Nil = property True
Cons x xs =-= Cons y ys = x =-= y .&. xs =-= ys
_ =-= _ = property False
main :: IO ()
main = do
let trigger = undefined :: List (Int,String,Int)
quickBatch $ monoid trigger
quickBatch $ functor trigger
quickBatch $ applicative trigger
quickBatch $ monad trigger
| JustinUnger/haskell-book | ch18/ch18-ex-4.hs | mit | 1,333 | 0 | 12 | 372 | 615 | 303 | 312 | 41 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StaticPointers, TypeFamilies, FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
import Haste.App
newtype LoggingServer a = L (Server a)
deriving (Functor, Applicative, Monad, MonadIO)
warn :: RemotePtr (String -> LoggingServer ())
warn = static (remote $ liftIO . putStrLn . ("WARNING: " ++))
serverComputation :: RemotePtr (Server ())
serverComputation = static (remote $ do
dispatch warn "warning from server"
)
instance Node LoggingServer
instance Node Server
instance Mapping LoggingServer a where
invoke e (L m) = invokeServer e m
main = runApp
[ start (Proxy :: Proxy LoggingServer)
, start (Proxy :: Proxy Server)
] $ do
alert "Logging from the client!"
dispatch warn "warning from client"
dispatch serverComputation
| valderman/haste-app | examples/logging.hs | mit | 839 | 0 | 10 | 142 | 236 | 119 | 117 | 22 | 1 |
{-# htermination compare :: Bool -> Bool -> Ordering #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_compare_8.hs | mit | 57 | 0 | 2 | 10 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Network.Haskbot.Internal.Environment
( Environment (..)
, bootstrap
, HaskbotM
, EnvironT
) where
import Control.Concurrent.STM.TVar (TVar, newTVarIO)
import Control.Monad.Error (Error, ErrorT)
import Control.Monad.Error.Class (noMsg, strMsg)
import Control.Monad.Reader (ReaderT)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy as BL
import qualified Network.Connection as N
import Network.Haskbot.Config (Config)
import qualified Network.HTTP.Conduit as N
import Network.HTTP.Types (Status, internalServerError500, mkStatus)
data Environment = Environment { incQueue :: TVar [BL.ByteString]
, netConn :: N.Manager
, config :: Config
}
type EnvironT m = ReaderT Environment m
type HaskbotM = EnvironT (ErrorT Status IO)
instance Error Status where
noMsg = internalServerError500
strMsg = mkStatus 500 . B8.pack
-- internal functions
bootstrap :: Config -> IO Environment
bootstrap configuration = do
incQueue <- newTVarIO []
netConn <- defNetConn >>= N.newManager
config <- return configuration
return $ Environment {..}
-- private functions
defNetConn :: IO N.ManagerSettings
defNetConn = return $ N.mkManagerSettings tlsInfo Nothing
where tlsInfo = N.TLSSettingsSimple False False False
| bendyworks/haskbot-plugins | haskbot-core-0.2/src/Network/Haskbot/Internal/Environment.hs | mit | 1,399 | 0 | 11 | 290 | 349 | 206 | 143 | 33 | 1 |
-- Helpers/tests/StringsSpec.hs
import Test.Hspec
import Helpers.Strings
main :: IO()
main = hspec $ do
describe "permute" $ do
it "Should permute a short String" $ do
"231" `elem` (permute "123") `shouldBe` True
it "Should permute a long String" $ do
"46123" `elem` (permute "12364") `shouldBe` True
describe "rotate" $ do
it "Should rotate a single Char" $ do
rotate "a" `shouldBe` ["a"]
it "Should rotate a normal Char" $ do
"bcd" `elem` (rotate "cdb") `shouldBe` True
it "Should not permute" $ do
"cbda" `elem` (rotate "abcd") `shouldBe` False
| Sgoettschkes/learning | haskell/ProjectEuler/Helpers/tests/StringsSpec.hs | mit | 658 | 1 | 17 | 198 | 203 | 101 | 102 | 16 | 1 |
-- This is for GHCi use only - it will be replaced by Cabal with the real implementation.
module Paths (getDataDir) where
import System.Directory
getDataDir = getCurrentDirectory
| sevcsik/sevdev-hakyll | generator/Paths.hs | mit | 183 | 0 | 4 | 31 | 20 | 13 | 7 | 3 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Keys
-- Copyright :
-- License : AllRightsReserved
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module App.Keys
(
cintToChar
) where
import qualified Foreign.C.Types (CInt)
cintToChar :: Foreign.C.Types.CInt -> Maybe Char
cintToChar c = case c of
97 -> Just 'a'
98 -> Just 'b'
99 -> Just 'c'
100 -> Just 'd'
101 -> Just 'e'
102 -> Just 'f'
103 -> Just 'g'
104 -> Just 'h'
105 -> Just 'i'
106 -> Just 'j'
107 -> Just 'k'
108 -> Just 'l'
109 -> Just 'm'
110 -> Just 'n'
111 -> Just 'o'
112 -> Just 'p'
113 -> Just 'q'
114 -> Just 'r'
115 -> Just 's'
116 -> Just 't'
117 -> Just 'u'
118 -> Just 'v'
119 -> Just 'w'
120 -> Just 'x'
121 -> Just 'y'
122 -> Just 'z'
_ -> Nothing
{-# INLINE cintToChar #-}
| triplepointfive/hapi | src/App/Keys.hs | gpl-2.0 | 1,033 | 0 | 8 | 307 | 305 | 151 | 154 | 34 | 27 |
{-# LANGUAGE FlexibleInstances, TemplateHaskell, NoMonomorphismRestriction, TupleSections, MultiParamTypeClasses, ScopedTypeVariables, FlexibleContexts, FunctionalDependencies, TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS -Wall #-}
-- {-# OPTIONS -ddump-deriv #-}
module Simplicial.DeltaSet1(
module HomogenousTuples,
module FaceClasses,
module Element,
module Data.SumType,
module Data.Tuple.Index,
DeltaSet1,
face10,
AnySimplex1,
OneSkeletonable(..),
OrdToDim1,
ShowToDim1,
foldAnySimplex1,
biMapAnySimplex1,
vertToAnySimplex1,
edToAnySimplex1,
anySimplex1s,
mkECVC,
-- UnitInterval(..),
UnitIntervalPoint
) where
import HomogenousTuples
import FaceClasses
import Element
import qualified Data.Map as M
import Control.Applicative
import PrettyUtil
import Data.SumType
import Language.Haskell.TH.Lift
import ShortShow
import Data.Tuple.Index
import MathUtil
class (Vertices s, Edges s, Vert s ~ Vert (Ed s), EdgeLike (Ed s)) => DeltaSet1 s where
face10 :: (Vertices e, Verts e ~ (v, v)) => e -> Index2 -> v
face10 = tupleToFun2 . vertices
vertToAnySimplex1 :: v -> AnySimplex1 v e
vertToAnySimplex1 = left'
edToAnySimplex1 :: e -> AnySimplex1 v e
edToAnySimplex1 = right'
type instance L (AnySimplex1 v e) = v
type instance R (AnySimplex1 v e) = e
newtype AnySimplex1 v e = AnySimplex1 (Either v e)
deriving(Show,SubSumTy,SuperSumTy,Eq,Ord)
instance (Pretty v, Pretty e) => Pretty (AnySimplex1 v e) where
prettyPrec prec = foldAnySimplex1 (prettyPrec prec) (prettyPrec prec)
foldAnySimplex1 ::
(v -> r) -> (e -> r) -> AnySimplex1 v e -> r
foldAnySimplex1 = either'
class OneSkeletonable a where
oneSkeleton :: a -> a
mkECVC
:: (Ord v,
Vertices (Element (Eds s)),
Edges s,
Verts (Element (Eds s)) ~ (v, v)) =>
s -> M.Map v [(Ed s, Index2)]
mkECVC s = m
where
m = M.fromListWith (++)
. concatMap (\e ->
toList2
(zipTuple2
(vertices e)
(map2 ((:[]) . (e,)) allIndex2' )))
$ edgeList s
anySimplex1s
:: (Vertices s, Edges s) => s -> [AnySimplex1 (Vert s) (Ed s)]
anySimplex1s =
(++)
<$> (map vertToAnySimplex1 . vertexList)
<*> (map edToAnySimplex1 . edgeList)
biMapAnySimplex1
:: (v -> v') -> (e -> e') -> AnySimplex1 v e -> AnySimplex1 v' e'
biMapAnySimplex1 = (++++)
instance (ShortShow v, ShortShow e) => ShortShow (AnySimplex1 v e) where
shortShow = foldAnySimplex1 shortShow shortShow
deriveLiftMany [''AnySimplex1]
-- data UnitInterval = UnitInterval
--
-- instance Vertices UnitInterval where
-- type Verts UnitInterval = Pair UnitIntervalPoint
-- vertices UnitInterval = (0,1)
--
-- instance Edges UnitInterval where
-- type Eds UnitInterval = OneTuple UnitInterval
-- edges UnitInterval = OneTuple UnitInterval
--
-- instance DeltaSet1 UnitInterval where
class (Show (Vert s), Show (Ed s)) => ShowToDim1 s
instance (Show (Vert s), Show (Ed s)) => ShowToDim1 s
class (Ord (Vert s), Ord (Ed s)) => OrdToDim1 s
instance (Ord (Vert s), Ord (Ed s)) => OrdToDim1 s
| DanielSchuessler/hstri | Simplicial/DeltaSet1.hs | gpl-3.0 | 3,310 | 0 | 20 | 796 | 967 | 532 | 435 | -1 | -1 |
module Graphics.UI.Bottle.MainLoop (mainLoopAnim, mainLoopImage, mainLoopWidget) where
import Control.Applicative ((<$>))
import Control.Concurrent (threadDelay)
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (when)
import Data.IORef
import Data.MRUMemo (memoIO)
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Data.Traversable (traverse, sequenceA)
import Data.Vector.Vector2 (Vector2(..))
import Graphics.DrawingCombinators ((%%))
import Graphics.DrawingCombinators.Utils (Image)
import Graphics.Rendering.OpenGL.GL (($=))
import Graphics.UI.Bottle.Animation(AnimId)
import Graphics.UI.Bottle.Widget(Widget)
import Graphics.UI.GLFW.Events (KeyEvent, GLFWEvent(..), eventLoop)
import qualified Control.Lens as Lens
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.Rendering.OpenGL.GL as GL
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.EventMap as E
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.GLFW as GLFW
mainLoopImage
:: (Widget.Size -> KeyEvent -> IO Bool)
-> (Bool -> Widget.Size -> IO (Maybe Image)) -> IO a
mainLoopImage eventHandler makeImage =
eventLoop handleEvents
where
windowSize = do
(x, y) <- GLFW.getWindowDimensions
return $ Vector2 (fromIntegral x) (fromIntegral y)
handleEvent size (GLFWKeyEvent keyEvent) =
eventHandler size keyEvent
handleEvent _ GLFWWindowClose =
error "Quit" -- TODO: Make close event
handleEvent _ GLFWWindowRefresh = return True
handleEvents events = do
winSize@(Vector2 winSizeX winSizeY) <- windowSize
anyChange <- fmap or $ traverse (handleEvent winSize) events
GL.viewport $=
(GL.Position 0 0,
GL.Size (round winSizeX) (round winSizeY))
mNewImage <- makeImage anyChange winSize
case mNewImage of
Nothing ->
-- TODO: If we can verify that there's sync-to-vblank, we
-- need no sleep here
threadDelay 10000
Just image ->
Draw.clearRender .
(Draw.translate (-1, 1) %%) .
(Draw.scale (2/winSizeX) (-2/winSizeY) %%) $
image
mainLoopAnim
:: (Widget.Size -> IO (Maybe (AnimId -> AnimId)))
-> (Widget.Size -> KeyEvent -> IO (Maybe (AnimId -> AnimId)))
-> (Widget.Size -> IO Anim.Frame)
-> IO Anim.R -> IO a
mainLoopAnim tickHandler eventHandler makeFrame getAnimationHalfLife = do
frameStateVar <- newIORef Nothing
let
handleResult Nothing = return False
handleResult (Just animIdMapping) = do
modifyIORef frameStateVar . fmap $
(_1 .~ 0) .
(_2 . _2 %~ Anim.mapIdentities animIdMapping)
return True
nextFrameState curTime size Nothing = do
dest <- makeFrame size
return $ Just (0, (curTime, dest))
nextFrameState curTime size (Just (drawCount, (prevTime, prevFrame))) =
if drawCount == 0
then do
dest <- makeFrame size
animationHalfLife <- getAnimationHalfLife
let
elapsed = realToFrac (curTime `diffUTCTime` prevTime)
progress = 1 - 0.5 ** (elapsed/animationHalfLife)
return . Just $
case Anim.nextFrame progress dest prevFrame of
Nothing -> (drawCount + 1, (curTime, dest))
Just newFrame -> (0 :: Int, (curTime, newFrame))
else
return $ Just (drawCount + 1, (curTime, prevFrame))
makeImage forceRedraw size = do
when forceRedraw .
modifyIORef frameStateVar $
Lens.mapped . _1 .~ 0
_ <- handleResult =<< tickHandler size
curTime <- getCurrentTime
writeIORef frameStateVar =<<
nextFrameState curTime size =<< readIORef frameStateVar
fmap frameStateResult $ readIORef frameStateVar
frameStateResult Nothing = error "No frame to draw at start??"
frameStateResult (Just (drawCount, (_, frame)))
| drawCount < stopAtDrawCount = Just $ Anim.draw frame
| otherwise = Nothing
-- A note on draw counts:
-- When a frame is dis-similar to the previous the count resets to 0
-- When a frame is similar and animation stops the count becomes 1
-- We then should draw it again (for double buffering issues) at count 2
-- And stop drawing it at count 3.
stopAtDrawCount = 3
imgEventHandler size event =
handleResult =<< eventHandler size event
mainLoopImage imgEventHandler makeImage
compose :: [a -> a] -> a -> a
compose = foldr (.) id
mainLoopWidget :: IO Bool -> (Widget.Size -> IO (Widget IO)) -> IO Anim.R -> IO a
mainLoopWidget widgetTickHandler mkWidgetUnmemod getAnimationHalfLife = do
mkWidgetRef <- newIORef =<< memoIO mkWidgetUnmemod
let
newWidget = writeIORef mkWidgetRef =<< memoIO mkWidgetUnmemod
getWidget size = ($ size) =<< readIORef mkWidgetRef
tickHandler size = do
anyUpdate <- widgetTickHandler
when anyUpdate $ newWidget
widget <- getWidget size
tickResults <-
sequenceA (widget ^. Widget.wEventMap . E.emTickHandlers)
when ((not . null) tickResults) newWidget
return $
case (tickResults, anyUpdate) of
([], False) -> Nothing
_ -> Just . compose $ map (^. Widget.eAnimIdMapping) tickResults
eventHandler size event = do
widget <- getWidget size
mAnimIdMapping <-
(traverse . fmap) (^. Widget.eAnimIdMapping) .
E.lookup event $ widget ^. Widget.wEventMap
case mAnimIdMapping of
Nothing -> return ()
Just _ -> newWidget
return mAnimIdMapping
mkFrame size = (^. Widget.wFrame) <$> getWidget size
mainLoopAnim tickHandler eventHandler mkFrame getAnimationHalfLife
| Mathnerd314/lamdu | bottlelib/Graphics/UI/Bottle/MainLoop.hs | gpl-3.0 | 5,700 | 0 | 19 | 1,311 | 1,654 | 867 | 787 | -1 | -1 |
module PrettyPrint where
import Map
import CommandAST
import Check
import Text.PrettyPrint.HughesPJ hiding (Str)
unescape :: String -> String
unescape [] = []
unescape ('\\':(x:xs)) = case x of
'\\' -> '\\' : unescape xs
'r' -> '\r' : unescape xs
't' -> '\t' : unescape xs
'n' -> '\n' : unescape xs
'\'' -> '\'' : unescape xs
'[' -> '[' : unescape xs
_ -> x : unescape xs
unescape (x:xs) = x : unescape xs
showConst :: Double -> String
showConst n = if fromIntegral (truncate n) < n then show n else show (truncate n)
showExprJSONValid :: Expr -> String
showExprJSONValid Null = "null"
showExprJSONValid (Const n) = showConst n
showExprJSONValid TrueExp = "true"
showExprJSONValid FalseExp = "false"
showExprJSONValid (Str s) = '\"' : (s ++ "\"")
showExprJSONValid (JsonObject o) = showJsonObjectJSONValid (mapToList o)
showExprJSONValid (Array a) = showArrayJSONValid a
showExprJSONValid _ = error "Shouldn't happen (showExprJSONValid)"
showJsonObjectJSONValid :: [(String, Expr)] -> String
showJsonObjectJSONValid [] = "{}"
showJsonObjectJSONValid xs = '{' : sho xs
where sho [(k,e)] = ("\"" ++ (k ++ "\" : ")) ++ showExprJSONValid e ++ "}"
sho ((k,e) : es)= ("\"" ++ (k ++ "\" : ")) ++ showExprJSONValid e ++ ", " ++ sho es
showArrayJSONValid :: [Expr] -> String
showArrayJSONValid [] = "[]"
showArrayJSONValid xs = "\\[" ++ sa xs
where sa [e] = showExprJSONValid e ++ "]"
sa (e:es) = showExprJSONValid e ++ ", " ++ sa es
--
-- Pretty Print
--
precOr, precAnd, precNot, precOpsComp, precPlusMinus, precMulDiv, precNeg :: Int
precOr = 1
precAnd = 2
precNot = 3
precOpsComp = 4
precPlusMinus = 5
precMulDiv = 6
precNeg = 7
precIndex = 8
ppExpr :: Expr -> Doc
ppExpr = ppExpr' 0
where
ppExpr' _ Null = text "null"
ppExpr' _ TrueExp = text "true"
ppExpr' _ FalseExp = text "false"
ppExpr' _ (Var v) = text v
ppExpr' _ (Const n) = text (showConst n)
ppExpr' _ (Str s) = text (show s)
ppExpr' p (Not e) = maybeParens (p > precNot) $
text "~" <> ppExpr' precNot e
ppExpr' p (And e1 e2) = maybeParens (p > precAnd) $
ppExpr' precAnd e1 <+> text "&" <+> ppExpr' precAnd e2
ppExpr' p (Or e1 e2) = maybeParens (p > precOr) $
ppExpr' precOr e1 <+> text "|" <+> ppExpr' precOr e2
ppExpr' p (Equals e1 e2)= maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text "==" <+> ppExpr' precOpsComp e2
ppExpr' p (Greater e1 e2) = maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text ">" <+> ppExpr' precOpsComp e2
ppExpr' p (Lower e1 e2) = maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text "<" <+> ppExpr' precOpsComp e2
ppExpr' p (GreaterEquals e1 e2) = maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text ">=" <+> ppExpr' precOpsComp e2
ppExpr' p (LowerEquals e1 e2) = maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text "<=" <+> ppExpr' precOpsComp e2
ppExpr' p (Negate e) = maybeParens (p > precNeg) $
text "-" <> ppExpr' precNeg e
ppExpr' p (Plus e1 e2) = maybeParens (p > precPlusMinus) $
ppExpr' precPlusMinus e1 <+> text "+" <+> ppExpr' precPlusMinus e2
ppExpr' p (Minus e1 e2) = maybeParens (p > precPlusMinus) $
ppExpr' precPlusMinus e1 <+> text "-" <+> ppExpr' precPlusMinus e2
ppExpr' p (Multiply e1 e2)= maybeParens (p > precMulDiv) $
ppExpr' precMulDiv e1 <+> text "*" <+> ppExpr' precMulDiv e2
ppExpr' p (Divide e1 e2) = maybeParens (p > precMulDiv) $
ppExpr' precMulDiv e1 <+> text "/" <+> ppExpr' precMulDiv e2
ppExpr' p (Index e1 e2) = maybeParens (p > precIndex) $
ppExpr' precIndex e1 <> text "." <> ppExpr' precIndex e2
ppExpr' p (Get e) = maybeParens (p > precOpsComp) $
text "<<" <+> ppExpr' precOpsComp e
ppExpr' p (Post e1 e2) = maybeParens (p > precOpsComp) $
ppExpr' precOpsComp e1 <+> text ">>" <+> ppExpr' precOpsComp e2
ppExpr' _ (JsonObject o)= case mapToList o of
[] -> lbrace <> rbrace
kes -> vcat [ lbrace
, ppKeyExprs kes
, rbrace
]
ppExpr' _ (Array a) = lbrack <> hsep (punctuate comma (map ppExpr a)) <> rbrack
ppKeyExprs :: [(String, Expr)] -> Doc
ppKeyExprs kes = nest 2 (vcat (punctuate comma (map ppKeyExpr kes)))
ppKeyExpr :: (String, Expr) -> Doc
ppKeyExpr (s, e) = ppExpr (Str s) <+> colon <+> ppExpr e
ppStatements :: [Statement] -> Doc
ppStatements ss = nest 2 (vcat (map ppStatement ss))
ppStatement :: Statement -> Doc
ppStatement (Assign v e) = text v <+> equals <+> ppExpr e
ppStatement (If e ss) = vcat [ text "if" <+> ppExpr e <+> colon
, ppStatements ss
]
ppStatement (IfElse e ss1 ss2) = vcat [ text "if" <+> ppExpr e <+> colon
, ppStatements ss1
, text "else:"
, ppStatements ss2
]
ppStatement (While e ss) = vcat [ text "while" <+> ppExpr e <+> colon
, ppStatements ss
]
ppStatement (Do ss e) = vcat [ text "do:"
, ppStatements ss
, text "while" <+> ppExpr e
]
ppStatement (For v e ss) = vcat [ text "for" <+> text v <+> text "in" <+> ppExpr e <+> colon
, ppStatements ss
]
ppType :: Type -> Doc
ppType ArrayType = text "Array"
ppType Number = text "Number"
ppType String = text "String"
ppType Bool = text "Bool"
ppType JSON = text "JSON"
ppArgs :: [(Var, Type)] -> Doc
ppArgs vts = parens (hsep (punctuate comma (map ppArg vts)))
ppArg :: (Var, Type) -> Doc
ppArg (v, t) = ppType t <+> text v
ppComm :: Comm -> Doc
ppComm (Comm vts ss) = vcat [ text "command" <+> ppArgs vts <+> colon
, ppStatements ss
]
prComm :: Comm -> String
prComm = render . ppComm
prType :: Type -> String
prType = render . ppType
prTypes :: [Type] -> String
prTypes ts = render $ hsep (punctuate comma (map ppType ts))
prStatement :: Statement -> String
prStatement = render . ppStatement
prExpr :: Expr -> String
prExpr = render . ppExpr
--
-- Errors messages
--
typeMatchError :: [Type] -> Expr -> String
typeMatchError ts e = "\nExpression: " ++ prExpr e ++ "\ndo not match (any) type expected: " ++ prTypes ts
indexEmptyError :: Type -> Expr -> String
indexEmptyError ArrayType e = "Indexing empty array in expression: " ++ prExpr e
indexEmprtError String e = "Indexing empty string in expression: " ++ prExpr e
| jgalat0/bot | src/PrettyPrint.hs | gpl-3.0 | 7,958 | 0 | 13 | 3,131 | 2,524 | 1,258 | 1,266 | 141 | 25 |
-- | Simple fork example
module Fork (runExample) where
import Control.Concurrent
import Control.Monad
import System.IO
-- | Shows an example on the use of fork
runExample :: IO ()
runExample = do
forkIO $ replicateM_ 100 (putChar 'A')
replicateM_ 100 (putChar 'B')
| capitanbatata/marlows-parconc-exercises | parconc-ch07/src/Fork.hs | gpl-3.0 | 303 | 0 | 10 | 79 | 73 | 39 | 34 | 8 | 1 |
module HEP.Physics.TTBar.Model.SM where
import HEP.Physics.TTBar.Model.Mandelstam
import HEP.Util.Functions
-- | top quark pole mass
mt :: Double
mt = 174.3
-- | Parton-level total cross section of SM : qqbar
-- reference : Nason, Dawson, Ellis <http://141.211.99.67:8080/pub/Study/TTbarPhysics/NasonDawsonEllis1.pdf>
totalXSec_qq_SM :: Double -> Double -> Double
totalXSec_qq_SM alphaS s =
if s > 4.0*mt^(2::Int)
then let rho = 4.0 * mt^(2::Int) / s
beta = sqrt ( 1.0 - rho )
fqqbar = (pi*beta*rho) / 27.0 * (2.0+rho)
in alphaS^(2::Int) / mt^(2::Int) * fqqbar
else 0
-- | Parton-level total cross section of SM : gluglu
-- reference : Nason, Dawson, Ellis <http://141.211.99.67:8080/pub/Study/TTbarPhysics/NasonDawsonEllis1.pdf>
totalXSec_gg_SM :: Double -> Double -> Double
totalXSec_gg_SM alphaS s =
if s > 4.0*mt^(2::Int)
then let rho = 4.0 * mt^(2::Int) / s
beta = sqrt ( 1.0 - rho )
fgg = (pi*beta*rho) / 192.0
* ( 1.0 / beta * (rho^(2::Int) + 16.0*rho+16.0)
* log ((1.0+beta)/(1.0-beta))
- 28.0 - 31.0 * rho )
in alphaS^(2::Int) / mt^(2::Int) * fgg
else 0
-- | Parton-level differential cross section of SM : qqbar
-- reference : PDB chap 39 with correction of beta (need to be checked. )
dsigma_dOmega_qqbar2ttbar_SM :: Two2TwoMomConf -> Double -> Double
dsigma_dOmega_qqbar2ttbar_SM mc alphas =
let s = mandelstamS mc
t = mandelstamT mc
u = mandelstamU mc
rho = 4.0 * mt^(2 :: Int) / s
in if rho > 1.0
then 0.0
else let beta = sqrt (1.0-rho)
in beta * sqr alphas/(9.0*s^(3::Integer))*(sqr(sqr mt-t)+sqr(sqr mt-u)+2.0*sqr mt*s)
-- | Parton-level differential cross section of SM : qqbar
-- reference : PDB chap 39 with correction of beta (need to be checked. )
dsigma_dOmega_gg2ttbar_SM :: Two2TwoMomConf -> Double -> Double
dsigma_dOmega_gg2ttbar_SM mc alphas =
let s = mandelstamS mc
t = mandelstamT mc
u = mandelstamU mc
rho = 4.0 * mt^(2 :: Int) / s
in if rho > 1.0
then 0.0
else let beta = sqrt (1.0-rho)
in beta* (sqr alphas)/(32.0*s)
*(6.0/sqr s*(sqr mt-t)*(sqr mt-u)
-(sqr mt)*(s-4.0*sqr mt)/(3*(sqr mt-t)*(sqr mt-u))
+4.0/3.0*((sqr mt-t)*(sqr mt-u)-2.0*sqr mt*(sqr mt+t))/sqr (sqr mt-t)
+4.0/3.0*((sqr mt-t)*(sqr mt-u)-2.0*sqr mt*(sqr mt+u))/sqr (sqr mt-u)
-3.0*((sqr mt-t)*(sqr mt-u)+(sqr mt)*(u-t))/(s*(sqr mt-t))
-3.0*((sqr mt-t)*(sqr mt-u)+(sqr mt)*(t-u))/(s*(sqr mt-u)))
dsigma_dcosth_qqbar2ttbar_SM :: Two2TwoMomConf -> Double -> Double
dsigma_dcosth_qqbar2ttbar_SM mc alphas = 2.0*pi*dsigma_dOmega_qqbar2ttbar_SM mc alphas
dsigma_dcosth_gg2ttbar_SM :: Two2TwoMomConf -> Double -> Double
dsigma_dcosth_gg2ttbar_SM mc alphas = 2.0*pi*dsigma_dOmega_gg2ttbar_SM mc alphas
| wavewave/ttbar | lib/HEP/Physics/TTBar/Model/SM.hs | gpl-3.0 | 3,023 | 0 | 33 | 810 | 1,227 | 647 | 580 | 54 | 2 |
{-# LANGUAGE RecordWildCards,NamedFieldPuns #-}
module Main where
import System.IO
import Hs243.Console
import Hs243.Logic
import System.Random (getStdRandom,randomR)
main = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdout False
actualmain $ Config (getStdRandom (randomR (0,1)))
(\n -> getStdRandom (randomR (0,n)))
Params { dimension = 5,
base = 3,
winat = 5,
distribution = [0.9] }
| cetu86/hs243 | exe/Main.hs | gpl-3.0 | 556 | 0 | 14 | 190 | 146 | 81 | 65 | 16 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -fno-liberate-case #-}
module Linguistics.ThreeWay.Simple where
import Data.Array.Repa.Index
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Fusion.Stream.Monadic as S
import Data.ByteString.Char8 (ByteString)
import qualified Data.List as L
import Data.Array.Repa.Index
import Data.Array.Repa.Shape
import Data.ByteString.Char8 (ByteString)
import Data.Vector.Fusion.Util (Id(..))
import qualified Data.ByteString.Char8 as B
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import qualified Data.Vector.Fusion.Stream.Monadic as S
import qualified Data.Vector.Unboxed as VU
import System.IO.Unsafe (unsafePerformIO)
import ADP.Fusion
import ADP.Fusion.Chr
import ADP.Fusion.Empty
import ADP.Fusion.Table
import Data.Array.Repa.Index.Points
import Data.PrimitiveArray as PA
import Data.PrimitiveArray.Zero as PA
import Linguistics.Scoring.Simple
import Linguistics.ThreeWay.Common
sScore :: Monad m => VU.Vector Char -> VU.Vector Char -> [Double] -> Double -> SThreeWay m Double Double ByteString ()
sScore !vowels !consonants !scores !gapOpen = SThreeWay
{ loop_loop_step = \ww (Z:.():.():.c ) -> ww + gapOpen + gapOpen + 0 -- 0 is the mnemonic for loop/loop match
, loop_step_loop = \ww (Z:.():.b :.()) -> ww + gapOpen + gapOpen + 0
, loop_step_step = \ww (Z:.():.b :.c ) -> ww + gapOpen + gapOpen + sm b c
, step_loop_loop = \ww (Z:.a :.():.()) -> ww + gapOpen + gapOpen + 0
, step_loop_step = \ww (Z:.a :.():.c ) -> ww + gapOpen + gapOpen + sm a c
, step_step_loop = \ww (Z:.a :.b :.()) -> ww + gapOpen + gapOpen + sm a b
, step_step_step = \ww (Z:.a :.b :.c ) -> ww + sm a b + sm a c + sm b c
, nil_nil_nil = const 0
, h = S.foldl' max (-500000)
} where sm = scoreMatch vowels consonants scores gapOpen
{-# INLINE sm #-}
{-# INLINE sScore #-}
sAlign :: Monad m => SThreeWay m Aligned (S.Stream m Aligned) ByteString ()
sAlign = SThreeWay
{ loop_loop_step = \(w1,w2,w3) (Z:.():.():.c ) -> (w1++ndl, w2++ndl, w3++[c]) -- (w1++padd "" c , w2++padd "" c, w3++prnt c "")
, loop_step_loop = \(w1,w2,w3) (Z:.():.b :.()) -> (w1++ndl, w2++[b], w3++ndl) -- (w1++padd "" b , w2++prnt b "", w3++padd "" b)
, loop_step_step = \(w1,w2,w3) (Z:.():.b :.c ) -> (w1++ndl, w2++[b], w3++[c]) -- (w1++pad2 "" b c, w2++prn2 b c , w3++prn2 c b )
, step_loop_loop = \(w1,w2,w3) (Z:.a :.():.()) -> (w1++[a], w2++ndl, w3++ndl) -- (w1,w2,w3) -- (w1++padd a "" ,
, step_loop_step = \(w1,w2,w3) (Z:.a :.():.c ) -> (w1++[a], w2++ndl, w3++[c]) -- (w1++prnt a c , w2++pad2 a c , w3++prnt c a )
, step_step_loop = \(w1,w2,w3) (Z:.a :.b :.()) -> (w1++[a], w2++[b], w3++ndl) -- (w1,w2,w3)
, step_step_step = \(w1,w2,w3) (Z:.a :.b :.c ) -> (w1++[a], w2++[b], w3++[c]) -- (w1,w2,w3)
, nil_nil_nil = const ([],[],[])
, h = return . id
} where ndl = ["-"]
{-# INLINE sAlign #-}
threeWay vowels consonants scores gapOpen i1 i2 i3 = (ws ! (Z:.pointL 0 n1:.pointL 0 n2:.pointL 0 n3), bt) where
ws = unsafePerformIO (threeWayFill vowels consonants scores gapOpen i1 i2 i3)
n1 = V.length i1
n2 = V.length i2
n3 = V.length i3
bt = backtrack vowels consonants scores gapOpen i1 i2 i3 ws
{-# NOINLINE threeWay #-}
threeWayFill
:: VU.Vector Char
-> VU.Vector Char
-> [Double]
-> Double
-> V.Vector ByteString
-> V.Vector ByteString
-> V.Vector ByteString
-> IO (PA.Unboxed (Z:.PointL:.PointL:.PointL) Double)
threeWayFill vowels consonants scores gapOpen i1 i2 i3 = do
let n1 = V.length i1
let n2 = V.length i2
let n3 = V.length i3
!t' <- newWithM (Z:.pointL 0 0:.pointL 0 0:.pointL 0 0) (Z:.pointL 0 n1:.pointL 0 n2:.pointL 0 n3) 0
let w = mTbl (Z:.EmptyT:.EmptyT:.EmptyT) t'
fillTable3 $ gThreeWay (sScore vowels consonants scores gapOpen) w (chr i1) (chr i2) (chr i3) Empty Empty Empty
freeze t'
{-# NOINLINE threeWayFill #-}
backtrack
:: VU.Vector Char
-> VU.Vector Char
-> [Double]
-> Double
-> V.Vector ByteString
-> V.Vector ByteString
-> V.Vector ByteString
-> PA.Unboxed (Z:.PointL:.PointL:.PointL) Double
-> [Aligned]
backtrack vowels consonants scores gapOpen i1 i2 i3 tbl = unId . S.toList . unId $ g $ Z:.pointL 0 n1 :.pointL 0 n2 :.pointL 0 n3 where
n1 = V.length i1
n2 = V.length i2
n3 = V.length i3
w :: DefBtTbl Id (Z:.PointL:.PointL:.PointL) Double Aligned
w = btTbl (Z:.EmptyT:.EmptyT:.EmptyT) tbl (g :: (Z:.PointL:.PointL:.PointL) -> Id (S.Stream Id Aligned))
(Z:.(_,g)) = gThreeWay (sScore vowels consonants scores gapOpen <** sAlign) w (chr i1) (chr i2) (chr i3) Empty Empty Empty
{-# NOINLINE backtrack #-}
--test s = threeWay (VU.fromList "aeiou") (VU.fromList $ ['a' .. 'z'] L.\\ "aeiou") [3,1,1,0,0,-1] (-1) s' s' s' where
-- s' = V.fromList $ L.map (B.pack . (:[])) $ s
| choener/WordAlignment | _old/ThreeWay/Simple.hs | gpl-3.0 | 4,986 | 0 | 18 | 932 | 2,052 | 1,132 | 920 | 102 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module NGramCrackers.Parsers.Body
(
parseSent
, parseParagraph
, parseMultiPara
, wordString
) where
import Data.Text as T
import Text.Parsec.Text as PT
import Control.Applicative ((<$>), (<*), (*>), (<*>), (<|>), liftA3)
import Data.Functor (void)
import Data.List (concat, unwords)
import Text.ParserCombinators.Parsec hiding ((<|>))
import NGramCrackers.DataTypes
import NGramCrackers.Ops.NG
parseMultiPara :: T.Text -> Either ParseError (DocCol T.Text)
parseMultiPara = parse docBody "unknown"
parseParagraph :: T.Text -> Either ParseError (ParaColl T.Text)
parseParagraph = parse paragraph "unknown"
parseSent :: T.Text -> Either ParseError (SentColl T.Text)
parseSent = parse sentence "unknown"
docMetadata :: [MetaTag]
-- May need to be moved to the Metadata module
docMetadata = undefined
docBody :: PT.Parser (DocCol T.Text)
docBody = endBy paragraph eop
paragraph :: PT.Parser (ParaColl T.Text)
paragraph = endBy sentence eos
sentence :: PT.Parser (SentColl T.Text)
sentence = sepBy sentParts seppr
sentParts :: PT.Parser (NG T.Text)
sentParts = ngram <|> numToNG
ngramSeries :: PT.Parser (SentColl T.Text)
ngramSeries = sepBy ngram seppr
numToNG :: PT.Parser (NG T.Text)
numToNG = fmap ngInject number where number = T.pack <$> many1 digit
{-| This parser is the basis for most all the parsers above. The parser puts
a parsed word into the NG record context. -}
ngram :: PT.Parser (NG T.Text)
ngram = ngInject <$> word where word = T.pack <$> many1 letter
wordString :: PT.Parser T.Text
-- Useful for non-sentence word strings where no numbers need to be parsed.
-- Probably useful for parsing MetaTags
wordString = T.unwords <$> sepBy word seppr where word = T.pack <$> many1 letter
-- The use of T.pack <$> is necessary because of the type many1 letter returns.
-- fmapping T.pack into the Parser makes it possible to return a parser of the
-- appropriate type.
--------------------------------------------------------------------------------
-- Separation parsers, used to parse and discard punctuation
--------------------------------------------------------------------------------
{-| For parsing common within sentence separators.-}
seppr :: PT.Parser ()
-- Since the results of this parser are just thrown away, we need the `void`
-- function from Data.Functor
seppr = void sepprs <|> void newLn
where sepprs = space'
<|> (char ',' *> space')
<|> (char ';' *> space')
<|> (char ':' *> space')
newLn = many1 (char '\n')
space' = char ' '
{-| Intended to parse separators that demarcate the ends of sentences, when
- followed by spaces. Unsure why I was not able to get '. ' and '.' to parse
- as end of sentence markers. Possible solutioon may be to make separate
- parsers and conjoin them in a new one a la sentParts. -}
eos :: PT.Parser ()
eos = void sepprs -- <|> void sngls
where sepprs = (char '.' <* space')
<|> (char '!' <* space')
<|> (char '?' <* space')
{- sngls = (char '.')
<|> (char '!')
<|> (char '?')
-}
space' = many (char ' ')
{-| Intended to parse the '<para>' sequence so common in the SGML documents,
when followed by a a space or newline. Parser may be useful guide for
handling the metadata tags. -}
eop :: PT.Parser ()
eop = void $
char '<' >> many1 letter >> char '>' <* (void space' <|> void newLn)
where space' = char ' '
newLn = many1 (char '\n')
| R-Morgan/NGramCrackers | src/NGramCrackers/Parsers/Body.hs | agpl-3.0 | 3,644 | 0 | 12 | 841 | 778 | 422 | 356 | 58 | 1 |
module Git.Command.Merge (run) where
run :: [String] -> IO ()
run args = return () | wereHamster/yag | Git/Command/Merge.hs | unlicense | 83 | 0 | 7 | 15 | 42 | 23 | 19 | 3 | 1 |
{-#LANGUAGE GADTs#-}
module Data.P440.XML.Render where
import Prelude hiding (sequence)
import Data.Text (Text)
import qualified Data.Map.Lazy as M
import Text.XML
class ToNode a where
toNode :: a -> Node
instance ToNode Node where
toNode = id
class ToSequence a where
toSequence :: a -> [Node]
data Children where
Sequence :: ToSequence s => s -> Children
Single :: ToNode n => n -> Children
instance ToSequence Children where
toSequence (Sequence s) = toSequence s
toSequence (Single n) = [toNode n]
instance (ToNode a) => ToSequence [a] where
toSequence = map toNode
instance (ToNode a) => ToSequence (Maybe a) where
toSequence (Just a) = [toNode a]
toSequence Nothing = []
class Attribute a where
toAttribute :: a -> Maybe Text
instance Attribute Text where
toAttribute = Just
instance (Attribute a) => Attribute (Maybe a) where
toAttribute (Just a) = toAttribute a
toAttribute Nothing = Nothing
(=:) :: (Attribute a) => Name -> a -> (Name, Maybe Text)
name =: value = (name, toAttribute value)
attributes :: [(Name, Maybe Text)] -> M.Map Name Text
attributes =
M.fromList . catMaybes'
where
catMaybes' ls = [(n, x) | (n, Just x) <- ls]
simple :: Name -> Text -> Node
simple name content =
NodeElement $
Element name M.empty [NodeContent content]
complex_ name attributes' =
NodeElement $
Element name (attributes attributes') []
complex :: (ToSequence c) => Name -> [(Name, Maybe Text)] -> [c] -> Node
complex name attributes' content =
NodeElement $
Element name (attributes attributes') (concatMap toSequence content)
| Macil-dev/p440 | src/Data/P440/XML/Render.hs | unlicense | 1,653 | 0 | 11 | 373 | 615 | 326 | 289 | 47 | 1 |
{-#LANGUAGE PatternSynonyms #-}
{-#LANGUAGE ViewPatterns #-}
module SIL where
import Control.DeepSeq
import Control.Monad.Except
import Control.Monad.State.Lazy
import Data.Char
-- if classes were categories, this would be an EndoFunctor?
class EndoMapper a where
endoMap :: (a -> a) -> a -> a
class EitherEndoMapper a where
eitherEndoMap :: (a -> Either e a) -> a -> Either e a
class MonoidEndoFolder a where
monoidFold :: Monoid m => (a -> m) -> a -> m
data IExpr
= Zero -- no special syntax necessary
| Pair !IExpr !IExpr -- {,}
| Env -- identifier
| SetEnv !IExpr
| Defer !IExpr
| Abort !IExpr
| Gate !IExpr
| PLeft !IExpr -- left
| PRight !IExpr -- right
| Trace !IExpr -- trace
deriving (Eq, Show, Ord)
data ExprA a
= ZeroA a
| PairA (ExprA a) (ExprA a) a
| EnvA a
| SetEnvA (ExprA a) a
| DeferA (ExprA a) a
| AbortA (ExprA a) a
| GateA (ExprA a) a
| PLeftA (ExprA a) a
| PRightA (ExprA a) a
| TraceA (ExprA a) a
deriving (Eq, Ord, Show)
-- there must be a typeclass I can derive that does this
getA :: ExprA a -> a
getA (ZeroA a) = a
getA (PairA _ _ a) = a
getA (EnvA a) = a
getA (SetEnvA _ a) = a
getA (DeferA _ a) = a
getA (AbortA _ a) = a
getA (GateA _ a) = a
getA (PLeftA _ a) = a
getA (PRightA _ a) = a
getA (TraceA _ a) = a
newtype EIndex = EIndex { unIndex :: Int } deriving (Eq, Show, Ord)
type IndExpr = ExprA EIndex
instance EndoMapper IExpr where
endoMap f Zero = f Zero
endoMap f (Pair a b) = f $ Pair (endoMap f a) (endoMap f b)
endoMap f Env = f Env
endoMap f (SetEnv x) = f $ SetEnv (endoMap f x)
endoMap f (Defer x) = f $ Defer (endoMap f x)
endoMap f (Abort x) = f $ Abort (endoMap f x)
endoMap f (Gate g) = f $ Gate (endoMap f g)
endoMap f (PLeft x) = f $ PLeft (endoMap f x)
endoMap f (PRight x) = f $ PRight (endoMap f x)
endoMap f (Trace x) = f $ Trace (endoMap f x)
instance EitherEndoMapper IExpr where
eitherEndoMap f Zero = f Zero
eitherEndoMap f (Pair a b) = (Pair <$> eitherEndoMap f a <*> eitherEndoMap f b) >>= f
eitherEndoMap f Env = f Env
eitherEndoMap f (SetEnv x) = (SetEnv <$> eitherEndoMap f x) >>= f
eitherEndoMap f (Defer x) = (Defer <$> eitherEndoMap f x) >>= f
eitherEndoMap f (Abort x) = (Abort <$> eitherEndoMap f x) >>= f
eitherEndoMap f (Gate x) = (Gate <$> eitherEndoMap f x) >>= f
eitherEndoMap f (PLeft x) = (PLeft <$> eitherEndoMap f x) >>= f
eitherEndoMap f (PRight x) = (PRight <$> eitherEndoMap f x) >>= f
eitherEndoMap f (Trace x) = (Trace <$> eitherEndoMap f x) >>= f
instance MonoidEndoFolder IExpr where
monoidFold f Zero = f Zero
monoidFold f (Pair a b) = mconcat [f (Pair a b), monoidFold f a, monoidFold f b]
monoidFold f Env = f Env
monoidFold f (SetEnv x) = mconcat [f (SetEnv x), monoidFold f x]
monoidFold f (Defer x) = mconcat [f (Defer x), monoidFold f x]
monoidFold f (Abort x) = mconcat [f (Abort x), monoidFold f x]
monoidFold f (Gate x) = mconcat [f (Gate x), monoidFold f x]
monoidFold f (PLeft x) = mconcat [f (PLeft x), monoidFold f x]
monoidFold f (PRight x) = mconcat [f (PRight x), monoidFold f x]
monoidFold f (Trace x) = mconcat [f (Trace x), monoidFold f x]
instance NFData IExpr where
rnf Zero = ()
rnf (Pair e1 e2) = rnf e1 `seq` rnf e2
rnf Env = ()
rnf (SetEnv e) = rnf e
rnf (Defer e) = rnf e
rnf (Abort e) = rnf e
rnf (Gate e) = rnf e
rnf (PLeft e) = rnf e
rnf (PRight e) = rnf e
rnf (Trace e) = rnf e
data RunTimeError
= AbortRunTime IExpr
| SetEnvError IExpr
| GenericRunTimeError String IExpr
| ResultConversionError String
deriving (Eq, Ord)
instance Show RunTimeError where
show (AbortRunTime a) = "Abort: " <> (show $ g2s a)
show (SetEnvError e) = "Can't SetEnv: " <> show e
show (GenericRunTimeError s i) = "Generic Runtime Error: " <> s <> " -- " <> show i
show (ResultConversionError s) = "Couldn't convert runtime result to IExpr: " <> s
type RunResult = ExceptT RunTimeError IO
class AbstractRunTime a where
eval :: a -> RunResult a
fromSIL :: IExpr -> a
toSIL :: a -> Maybe IExpr
zero :: IExpr
zero = Zero
pair :: IExpr -> IExpr -> IExpr
pair = Pair
var :: IExpr
var = Env
env :: IExpr
env = Env
twiddle :: IExpr -> IExpr
twiddle x = setenv (pair (defer (pair (pleft (pright env)) (pair (pleft env) (pright (pright env))))) x)
app :: IExpr -> IExpr -> IExpr
--app c i = setenv (twiddle (pair i c))
app c i = setenv (setenv (pair (defer (pair (pleft (pright env)) (pair (pleft env) (pright (pright env)))))
(pair i c)))
check :: IExpr -> IExpr -> IExpr
{-
check c tc = setenv (pair (defer (ite
(app (pleft env) (pright env))
(Abort $ app (pleft env) (pright env))
(pright env)
))
(pair tc c)
)
-}
check c tc = setenv (pair (defer (pright (Abort $ app (pleft env) (pright env))
))
(pair tc c)
)
gate :: IExpr -> IExpr
gate = Gate
pleft :: IExpr -> IExpr
pleft = PLeft
pright :: IExpr -> IExpr
pright = PRight
setenv :: IExpr -> IExpr
setenv = SetEnv
defer :: IExpr -> IExpr
defer = Defer
lam :: IExpr -> IExpr
lam x = pair (defer x) env
-- a form of lambda that does not pull in a surrounding environment
completeLam :: IExpr -> IExpr
completeLam x = pair (defer x) zero
ite :: IExpr -> IExpr -> IExpr -> IExpr
ite i t e = setenv (pair (gate i) (pair e t))
varN :: Int -> IExpr
varN n = pleft (iterate pright env !! n)
-- make sure these patterns are in exact correspondence with the shortcut functions above
pattern FirstArg :: IExpr
pattern FirstArg <- PLeft Env
pattern SecondArg :: IExpr
pattern SecondArg <- PLeft (PRight Env)
pattern ThirdArg :: IExpr
pattern ThirdArg <- PLeft (PRight (PRight Env))
pattern FourthArg :: IExpr
pattern FourthArg <- PLeft (PRight (PRight (PRight Env)))
pattern Lam :: IExpr -> IExpr
pattern Lam x <- Pair (Defer x) Env
pattern App :: IExpr -> IExpr -> IExpr
pattern App c i <- SetEnv (SetEnv (Pair (Defer (Pair (PLeft (PRight Env)) (Pair (PLeft Env) (PRight (PRight Env)))))
(Pair i c)))
pattern TwoArgFun :: IExpr -> IExpr
pattern TwoArgFun c <- Pair (Defer (Pair (Defer c) Env)) Env
pattern ITE :: IExpr -> IExpr -> IExpr -> IExpr
pattern ITE i t e <- SetEnv (Pair (Gate i) (Pair e t))
countApps :: Int -> IExpr -> Maybe Int
countApps x FirstArg = pure x
countApps x (App SecondArg c) = countApps (x + 1) c
countApps _ _ = Nothing
pattern ChurchNum :: Int -> IExpr
pattern ChurchNum x <- TwoArgFun (countApps 0 -> Just x)
pattern ToChurch :: IExpr
pattern ToChurch <-
Lam
(App
(App
FirstArg
(Lam (Lam (Lam (Lam
(ITE
ThirdArg
(App
SecondArg
(App
(App
(App
FourthArg
(PLeft ThirdArg)
)
SecondArg
)
FirstArg
)
)
FirstArg
)
))))
)
(Lam (Lam (Lam FirstArg)))
)
pattern FirstArgA :: ExprA a
pattern FirstArgA <- PLeftA (EnvA _) _
pattern SecondArgA :: ExprA a
pattern SecondArgA <- PLeftA (PRightA (EnvA _) _) _
pattern ThirdArgA :: ExprA a
pattern ThirdArgA <- PLeftA (PRightA (PRightA (EnvA _) _) _) _
pattern FourthArgA :: ExprA a
pattern FourthArgA <- PLeftA (PRightA (PRightA (PRightA (EnvA _) _) _) _) _
pattern AppA :: ExprA a -> ExprA a -> ExprA a
pattern AppA c i <- SetEnvA (SetEnvA (PairA
(DeferA (PairA
(PLeftA (PRightA (EnvA _) _) _)
(PairA (PLeftA (EnvA _) _) (PRightA (PRightA (EnvA _) _) _) _)
_)
_)
(PairA i c _)
_)
_)
_
pattern LamA :: ExprA a -> ExprA a
pattern LamA x <- PairA (DeferA x _) (EnvA _) _
pattern TwoArgFunA :: ExprA a -> a -> a -> ExprA a
pattern TwoArgFunA c ana anb <- PairA (DeferA (PairA (DeferA c ana) (EnvA _) _) anb) (EnvA _) _
pattern ITEA :: ExprA a -> ExprA a -> ExprA a -> ExprA a
pattern ITEA i t e <- SetEnvA (PairA (GateA i _) (PairA e t _) _) _
-- TODO check if these make sense at all. A church type should have two arguments (lamdas), but the inner lambdas
-- for addition/multiplication should be f, f+x rather than m+n
-- no, it does not, in \m n f x -> m f (n f x), m and n are FourthArg and ThirdArg respectively
pattern PlusA :: ExprA a -> ExprA a -> ExprA a
pattern PlusA m n <- LamA (LamA (AppA (AppA m SecondArgA) (AppA (AppA n SecondArgA) FirstArgA)))
pattern MultA :: ExprA a -> ExprA a -> ExprA a
pattern MultA m n <- LamA (AppA m (AppA n FirstArgA))
data DataType
= ZeroType
| ArrType DataType DataType
| PairType DataType DataType -- only used when at least one side of a pair is not ZeroType
deriving (Eq, Show, Ord)
newtype PrettyDataType = PrettyDataType DataType
showInternal at@(ArrType _ _) = concat ["(", show $ PrettyDataType at, ")"]
showInternal t = show . PrettyDataType $ t
instance Show PrettyDataType where
show (PrettyDataType dt) = case dt of
ZeroType -> "D"
(ArrType a b) -> concat [showInternal a, " -> ", showInternal b]
(PairType a b) ->
concat ["{", show $ PrettyDataType a, ",", show $ PrettyDataType b, "}"]
data PartialType
= ZeroTypeP
| AnyType
| TypeVariable Int
| ArrTypeP PartialType PartialType
| PairTypeP PartialType PartialType
deriving (Show, Eq, Ord)
newtype PrettyPartialType = PrettyPartialType PartialType
showInternalP at@(ArrTypeP _ _) = concat ["(", show $ PrettyPartialType at, ")"]
showInternalP t = show . PrettyPartialType $ t
instance Show PrettyPartialType where
show (PrettyPartialType dt) = case dt of
ZeroTypeP -> "Z"
AnyType -> "A"
(ArrTypeP a b) -> concat [showInternalP a, " -> ", showInternalP b]
(PairTypeP a b) ->
concat ["{", show $ PrettyPartialType a, ",", show $ PrettyPartialType b, "}"]
(TypeVariable (-1)) -> "badType"
(TypeVariable x) -> 'v' : show x
instance EndoMapper DataType where
endoMap f ZeroType = f ZeroType
endoMap f (ArrType a b) = f $ ArrType (endoMap f a) (endoMap f b)
endoMap f (PairType a b) = f $ PairType (endoMap f a) (endoMap f b)
instance EndoMapper PartialType where
endoMap f ZeroTypeP = f ZeroTypeP
endoMap f AnyType = f AnyType
endoMap f (TypeVariable i) = f $ TypeVariable i
endoMap f (ArrTypeP a b) = f $ ArrTypeP (endoMap f a) (endoMap f b)
endoMap f (PairTypeP a b) = f $ PairTypeP (endoMap f a) (endoMap f b)
mergePairType :: DataType -> DataType
mergePairType = endoMap f where
f (PairType ZeroType ZeroType) = ZeroType
f x = x
mergePairTypeP :: PartialType -> PartialType
mergePairTypeP = endoMap f where
f (PairTypeP ZeroTypeP ZeroTypeP) = ZeroTypeP
f x = x
newtype PrettyIExpr = PrettyIExpr IExpr
instance Show PrettyIExpr where
show (PrettyIExpr iexpr) = case iexpr of
p@(Pair a b) -> if isNum p
then show $ g2i p
else concat ["{", show (PrettyIExpr a), ",", show (PrettyIExpr b), "}"]
Zero -> "0"
x -> show x
g2i :: IExpr -> Int
g2i Zero = 0
g2i (Pair a b) = 1 + g2i a + g2i b
g2i x = error $ "g2i " ++ show x
i2g :: Int -> IExpr
i2g 0 = Zero
i2g n = Pair (i2g (n - 1)) Zero
ints2g :: [Int] -> IExpr
ints2g = foldr (\i g -> Pair (i2g i) g) Zero
g2Ints :: IExpr -> [Int]
g2Ints Zero = []
g2Ints (Pair n g) = g2i n : g2Ints g
g2Ints x = error $ "g2Ints " ++ show x
s2g :: String -> IExpr
s2g = ints2g . map ord
g2s :: IExpr -> String
g2s = map chr . g2Ints
-- convention is numbers are left-nested pairs with zero on right
isNum :: IExpr -> Bool
isNum Zero = True
isNum (Pair n Zero) = isNum n
isNum _ = False
nextI :: State EIndex EIndex
nextI = state $ \(EIndex n) -> (EIndex n, EIndex (n + 1))
toIndExpr :: IExpr -> State EIndex IndExpr
toIndExpr Zero = ZeroA <$> nextI
toIndExpr (Pair a b) = PairA <$> toIndExpr a <*> toIndExpr b <*> nextI
toIndExpr Env = EnvA <$> nextI
toIndExpr (SetEnv x) = SetEnvA <$> toIndExpr x <*> nextI
toIndExpr (Defer x) = DeferA <$> toIndExpr x <*> nextI
toIndExpr (Abort x) = AbortA <$> toIndExpr x <*> nextI
toIndExpr (Gate x) = GateA <$> toIndExpr x <*> nextI
toIndExpr (PLeft x) = PLeftA <$> toIndExpr x <*> nextI
toIndExpr (PRight x) = PRightA <$> toIndExpr x <*> nextI
toIndExpr (Trace x) = TraceA <$> toIndExpr x <*> nextI
toIndExpr' :: IExpr -> IndExpr
toIndExpr' x = evalState (toIndExpr x) (EIndex 0)
| sfultong/stand-in-language | src/SIL.hs | apache-2.0 | 12,822 | 0 | 30 | 3,601 | 5,224 | 2,624 | 2,600 | 329 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsSceneContextMenuEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QGraphicsSceneContextMenuEvent (
QGraphicsSceneContextMenuEventReason
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CQGraphicsSceneContextMenuEventReason a = CQGraphicsSceneContextMenuEventReason a
type QGraphicsSceneContextMenuEventReason = QEnum(CQGraphicsSceneContextMenuEventReason Int)
ieQGraphicsSceneContextMenuEventReason :: Int -> QGraphicsSceneContextMenuEventReason
ieQGraphicsSceneContextMenuEventReason x = QEnum (CQGraphicsSceneContextMenuEventReason x)
instance QEnumC (CQGraphicsSceneContextMenuEventReason Int) where
qEnum_toInt (QEnum (CQGraphicsSceneContextMenuEventReason x)) = x
qEnum_fromInt x = QEnum (CQGraphicsSceneContextMenuEventReason x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QGraphicsSceneContextMenuEventReason -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
instance QeMouse QGraphicsSceneContextMenuEventReason where
eMouse
= ieQGraphicsSceneContextMenuEventReason $ 0
instance QeKeyboard QGraphicsSceneContextMenuEventReason where
eKeyboard
= ieQGraphicsSceneContextMenuEventReason $ 1
instance QeOther QGraphicsSceneContextMenuEventReason where
eOther
= ieQGraphicsSceneContextMenuEventReason $ 2
| keera-studios/hsQt | Qtc/Enums/Gui/QGraphicsSceneContextMenuEvent.hs | bsd-2-clause | 2,958 | 0 | 18 | 535 | 612 | 310 | 302 | 55 | 1 |
-- 55
import Data.Array((!), (//), listArray)
import Euler(fromDigits, primeSieve, toDigitsBase)
nn = 1000000
genCircular n = map (\x -> fromDigits $ take k $ drop x $ cycle ds) [1..k]
where ds = toDigitsBase 10 n
k = length ds
countCircularPrimes n = length $ filter isCircularPrime primes
where primes = primeSieve n
a = (listArray (2,n) $ repeat False) // [(x,True) | x <- primes]
isCircularPrime p = all (a!) $ genCircular p
main = putStrLn $ show $ countCircularPrimes nn
| higgsd/euler | hs/35.hs | bsd-2-clause | 519 | 0 | 11 | 124 | 218 | 117 | 101 | -1 | -1 |
{-# LANGUAGE Haskell2010 #-}
module OrphanInstancesClass (AClass(..)) where
class AClass a where
aClass :: a -> Int
| haskell/haddock | html-test/src/OrphanInstancesClass.hs | bsd-2-clause | 119 | 0 | 7 | 20 | 32 | 19 | 13 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- | Visualize a collection of images as a three-dimensional volume.
module Web.Lightning.Plots.Volume
(
VolumePlot(..)
, Visualization (..)
, volumePlot
)
where
--------------------------------------------------------------------------------
import Data.Aeson
import Data.Default.Class
import qualified Data.Text as T
import qualified Web.Lightning.Routes as R
import Web.Lightning.Types.Lightning
import Web.Lightning.Types (Img)
import Web.Lightning.Types.Visualization (Visualization (..))
--------------------------------------------------------------------------------
-- | Volume plot parameters
data VolumePlot = VolumePlot { vpImages :: [Img]
-- ^ A collection of images to display. Can be
-- 2 dimensional (grey scale) or 3 dimensional
-- (RGB) lists.
}
deriving (Show, Eq)
instance Default VolumePlot where
def = VolumePlot [ [[[]]] ]
instance ToJSON VolumePlot where
toJSON (VolumePlot imgs) =
object [ "images" .= imgs ]
instance ValidatablePlot VolumePlot where
validatePlot = return
-- | Submits a request to the specified lightning-viz server to create
-- a visualization of a collection of images as a three-dimensional volume.
--
-- <http://lightning-viz.org/visualizations/volume/ Volume Visualization>
volumePlot :: Monad m => T.Text
-- ^ Base URL for lightning-viz server.
-> VolumePlot
-- ^ Volume plot to create
-> LightningT m Visualization
-- ^ Transformer stack with created visualization.
volumePlot bUrl volumePlt = do
viz <- sendPlot "volume" volumePlt R.plot
return $ viz { vizBaseUrl = Just bUrl }
| cmoresid/lightning-haskell | src/Web/Lightning/Plots/Volume.hs | bsd-3-clause | 1,965 | 0 | 10 | 602 | 276 | 166 | 110 | 28 | 1 |
module HKatalog where
import System.Environment
-- | 'main' runs the main program
main :: IO ()
main = getArgs >>= print . haqify . head
haqify :: String -> String
haqify s = "Haq! " ++ s
| txominpelu/hkatalog | HKatalog.hs | bsd-3-clause | 191 | 0 | 7 | 40 | 58 | 32 | 26 | 6 | 1 |
{- |
File paths of interest to Dyre, and related values.
-}
module Config.Dyre.Paths where
import Control.Monad ( filterM )
import Data.List ( isSuffixOf )
import System.Info (os, arch)
import System.FilePath
( (</>), (<.>), takeExtension, splitExtension )
import System.Directory
( doesDirectoryExist
, doesFileExist
, getCurrentDirectory
, getDirectoryContents
, getModificationTime
)
import System.Environment.XDG.BaseDir (getUserCacheDir, getUserConfigDir)
import System.Environment.Executable (getExecutablePath)
import Data.Time
import Config.Dyre.Params
import Config.Dyre.Options
-- | Data type to make it harder to confuse which path is which.
data PathsConfig = PathsConfig
{ runningExecutable :: FilePath
, customExecutable :: FilePath
, configFile :: FilePath
-- ^ Where Dyre looks for the custom configuration file.
, libsDirectory :: FilePath
-- ^ @<configDir>/libs@. This directory gets added to the GHC
-- include path during compilation, so use configurations can be
-- split up into modules. Changes to files under this directory
-- trigger recompilation.
, cacheDirectory :: FilePath
-- ^ Where the custom executable, object and interface files, errors
-- file and other metadata get stored.
}
-- | Determine a file name for the compiler to write to, based on
-- the 'customExecutable' path.
--
outputExecutable :: FilePath -> FilePath
outputExecutable path =
let (base, ext) = splitExtension path
in base <.> "tmp" <.> ext
-- | Return a 'PathsConfig', which records the current binary, the custom
-- binary, the config file, and the cache directory.
getPaths :: Params c r -> IO (FilePath, FilePath, FilePath, FilePath, FilePath)
getPaths params@Params{projectName = pName} = do
thisBinary <- getExecutablePath
debugMode <- getDebug
cwd <- getCurrentDirectory
cacheDir' <- case (debugMode, cacheDir params) of
(True, _ ) -> return $ cwd </> "cache"
(False, Nothing) -> getUserCacheDir pName
(False, Just cd) -> cd
confDir <- case (debugMode, configDir params) of
(True, _ ) -> return cwd
(False, Nothing) -> getUserConfigDir pName
(False, Just cd) -> cd
let
tempBinary =
cacheDir' </> pName ++ "-" ++ os ++ "-" ++ arch <.> takeExtension thisBinary
configFile' = confDir </> pName ++ ".hs"
libsDir = confDir </> "lib"
pure (thisBinary, tempBinary, configFile', cacheDir', libsDir)
getPathsConfig :: Params cfg a -> IO PathsConfig
getPathsConfig params = do
(cur, custom, conf, cache, libs) <- getPaths params
pure $ PathsConfig cur custom conf libs cache
-- | Check if a file exists. If it exists, return Just the modification
-- time. If it doesn't exist, return Nothing.
maybeModTime :: FilePath -> IO (Maybe UTCTime)
maybeModTime path = do
fileExists <- doesFileExist path
if fileExists
then Just <$> getModificationTime path
else return Nothing
checkFilesModified :: PathsConfig -> IO Bool
checkFilesModified paths = do
confTime <- maybeModTime (configFile paths)
libFiles <- findHaskellFiles (libsDirectory paths)
libTimes <- traverse maybeModTime libFiles
thisTime <- maybeModTime (runningExecutable paths)
tempTime <- maybeModTime (customExecutable paths)
pure $
tempTime < confTime -- config newer than custom bin
|| tempTime < thisTime -- main bin newer than custom bin
|| any (tempTime <) libTimes
-- | Recursively find Haskell files (@.hs@, @.lhs@) at the given
-- location.
findHaskellFiles :: FilePath -> IO [FilePath]
findHaskellFiles d = do
exists <- doesDirectoryExist d
if exists
then do
nodes <- getDirectoryContents d
let nodes' = map (d </>) . filter (`notElem` [".", ".."]) $ nodes
files <- filterM isHaskellFile nodes'
dirs <- filterM doesDirectoryExist nodes'
subfiles <- concat <$> traverse findHaskellFiles dirs
pure $ files ++ subfiles
else pure []
where
isHaskellFile f
| any (`isSuffixOf` f) [".hs", ".lhs"] = doesFileExist f
| otherwise = pure False
| willdonnelly/dyre | Config/Dyre/Paths.hs | bsd-3-clause | 4,203 | 0 | 17 | 967 | 970 | 517 | 453 | 82 | 5 |
{-# OPTIONS_HADDOCK hide #-}
module Graphics.Gloss.Internals.Interface.Simulate.State
( State (..)
, stateInit )
where
-- | Simulation state
data State
= State
{ -- | The iteration number we're up to.
stateIteration :: !Integer
-- | How many simulation setps to take for each second of real time
, stateResolution :: !Int
-- | How many seconds worth of simulation we've done so far
, stateSimTime :: !Float }
-- | Initial control state
stateInit :: Int -> State
stateInit resolution
= State
{ stateIteration = 0
, stateResolution = resolution
, stateSimTime = 0 }
| ardumont/snake | deps/gloss/Graphics/Gloss/Internals/Interface/Simulate/State.hs | bsd-3-clause | 785 | 0 | 9 | 316 | 95 | 61 | 34 | 21 | 1 |
{-# LANGUAGE TypeFamilies, ViewPatterns #-}
module Data.Coordinates where
class Coord c where
type Vect c :: *
type Direction c :: *
type Distance c :: *
type instance Vect c = (Direction c, Distance c )
distance :: c -> c -> Vect c
move :: Vect c -> c -> c
newtype Point = Point { unP :: (Int, Int) }
foldn :: Int -> (a -> a) -> a -> a
foldn 0 f a = a
foldn n f a = foldn (n - 1) f (f a)
instance Coord Point where
type Direction (Point) = (Point)
type Distance (Point) = Int
distance (unP -> (x,y)) (unP -> (x', y')) = (Point $ (dx , dy), 1)
where dx = abs $ x - x'
dy = abs $ y - y'
move ((Point p), n) (p') = foldn n f p'
where f (unP -> (x, y)) = Point $ (,) (x + fst p) (y + snd p) | onomatic/sigmund | src/Data/Coordinates.hs | bsd-3-clause | 875 | 0 | 12 | 351 | 380 | 212 | 168 | 21 | 1 |
module SimpleModule.Evaluator
( valueOf
, run
, eval
, evalProgram
) where
import Control.Applicative ((<|>))
import Control.Arrow (second)
import Control.Monad.Except
import Data.Maybe (fromMaybe)
import SimpleModule.Data
import SimpleModule.Parser
import SimpleModule.TypeChecker (typeOfExpression)
type EvaluateResult = Try ExpressedValue
applyForce :: GeneralEnv a -> String -> a
applyForce env var = case apply env var of
Right x -> x
Left _ -> error $ concat [ "Var ", var, " is not in scope." ]
liftMaybe :: LangError -> Maybe a -> Try a
liftMaybe _ (Just x) = return x
liftMaybe y Nothing = throwError y
forceEnvTry :: EnvTry a -> a
forceEnvTry (Left e) = error $ show e
forceEnvTry (Right x) = x
run :: String -> EvaluateResult
run input = parseProgram input >>= evalProgram
liftTypeError :: Either TypeError a -> Try a
liftTypeError (Right x) = return x
liftTypeError (Left err) = throwError (TypeCheckerError err)
eval :: [ModuleDef] -> Expression -> EvaluateResult
eval defs expr = do
liftTypeError (typeOfExpression defs expr)
env <- addModuleDefs defs empty
valueOf expr env
addModuleDefs :: [ModuleDef] -> Environment -> Try Environment
addModuleDefs [] env = return env
addModuleDefs (ModuleDef name iface body : ds) env = do
newEnv <- addModuleBody name body env
pairs <- findModuleIface name iface newEnv
addModuleDefs ds (addNamed name pairs env)
addModuleBody :: String -> ModuleBody -> Environment -> Try Environment
addModuleBody name (ModuleBody defs) = addModuleBody' defs
where
addModuleBody' :: [Definition] -> Environment -> Try Environment
addModuleBody' [] env = return env
addModuleBody' (Definition k e : ds) env = do
v <- valueOf e env
addModuleBody' ds $ extendNamed name k (exprToDeno v) env
findModuleIface :: String -> Interface -> Environment
-> Try [(String, DenotedValue)]
findModuleIface name (Interface decls) env = findIfaces decls []
where
findIfaces :: [Declaration] -> [(String, DenotedValue)]
-> Try [(String, DenotedValue)]
findIfaces [] acc = return $ reverse acc
findIfaces (Declaration k _ : ds) acc =
findIfaces ds ((k, forceEnvTry $ applyNamed env name k) : acc)
evalProgram :: Program -> EvaluateResult
evalProgram (Prog mDefs expr) = eval mDefs expr
valueOf :: Expression -> Environment -> EvaluateResult
valueOf (ConstExpr x) _ = evalConstExpr x
valueOf (VarExpr var) env = evalVarExpr var env
valueOf (LetRecExpr procs recBody) env = evalLetRecExpr procs recBody env
valueOf (BinOpExpr op expr1 expr2) env = evalBinOpExpr op expr1 expr2 env
valueOf (UnaryOpExpr op expr) env = evalUnaryOpExpr op expr env
valueOf (CondExpr pairs) env = evalCondExpr pairs env
valueOf (LetExpr bindings body) env = evalLetExpr bindings body env
valueOf (ProcExpr params body) env = evalProcExpr params body env
valueOf (CallExpr rator rand) env = evalCallExpr rator rand env
valueOf (QualifiedVarExpr m v) env = evalQualifiedVarExpr m v env
evalConstExpr :: ExpressedValue -> EvaluateResult
evalConstExpr = Right
exprToDeno :: ExpressedValue -> DenotedValue
exprToDeno (ExprNum n) = DenoNum n
exprToDeno (ExprBool b) = DenoBool b
exprToDeno (ExprProc p) = DenoProc p
denoToExpr :: DenotedValue -> ExpressedValue
denoToExpr (DenoNum n) = ExprNum n
denoToExpr (DenoBool b) = ExprBool b
denoToExpr (DenoProc p) = ExprProc p
evalVarExpr :: String -> Environment -> EvaluateResult
evalVarExpr var env = return . denoToExpr $ applyForce env var
evalLetRecExpr :: [(Type, String, [(String, Type)], Expression)] -> Expression
-> Environment
-> EvaluateResult
evalLetRecExpr procsSubUnits recBody env =
valueOf recBody $ extendRecMany noTypedProcs env
where
func (_, name, params, body) = (name, fmap fst params, body)
noTypedProcs = fmap func procsSubUnits
binBoolOpMap :: [(BinOp, Bool -> Bool -> Bool)]
binBoolOpMap = []
binNumToNumOpMap :: [(BinOp, Integer -> Integer -> Integer)]
binNumToNumOpMap = [(Add, (+)), (Sub, (-)), (Mul, (*)), (Div, div)]
binNumToBoolOpMap :: [(BinOp, Integer -> Integer -> Bool)]
binNumToBoolOpMap = [(Gt, (>)), (Le, (<)), (Eq, (==))]
unaryBoolOpMap :: [(UnaryOp, Bool -> Bool)]
unaryBoolOpMap = []
unaryNumToNumOpMap :: [(UnaryOp, Integer -> Integer)]
unaryNumToNumOpMap = [(Minus, negate)]
unaryNumToBoolOpMap :: [(UnaryOp, Integer -> Bool)]
unaryNumToBoolOpMap = [(IsZero, (0 ==))]
findOp :: (Eq a, Show a) => a -> [(a, b)] -> b
findOp op lst = fromMaybe err $ lookup op lst
where err = error $ "Unknown operator: " `mappend` show op
binOpConverter :: (ExpressedValue -> Try a)
-> (ExpressedValue -> Try b)
-> (c -> ExpressedValue)
-> (a -> b -> c)
-> (ExpressedValue -> ExpressedValue -> EvaluateResult)
binOpConverter unpack1 unpack2 trans func val1 val2 = do
va <- unpack1 val1
vb <- unpack2 val2
return . trans $ func va vb
binOps :: [(BinOp, ExpressedValue -> ExpressedValue -> EvaluateResult)]
binOps = concat [binNum2Num, binNum2Bool, binBool2Bool]
where
n2nTrans = binOpConverter unpackNum unpackNum ExprNum
binNum2Num = fmap (second n2nTrans) binNumToNumOpMap
n2bTrans = binOpConverter unpackNum unpackNum ExprBool
binNum2Bool = fmap (second n2bTrans) binNumToBoolOpMap
b2bTrans = binOpConverter unpackBool unpackBool ExprBool
binBool2Bool = fmap (second b2bTrans) binBoolOpMap
unaryOpConverter :: (ExpressedValue -> Try a)
-> (b -> ExpressedValue)
-> (a -> b)
-> (ExpressedValue -> EvaluateResult)
unaryOpConverter unpack trans func val = do
va <- unpack val
return . trans $ func va
unaryOps :: [(UnaryOp, ExpressedValue -> EvaluateResult)]
unaryOps = concat [unaryNum2Num, unaryNum2Bool, unaryBool2Bool]
where
n2nTrans = unaryOpConverter unpackNum ExprNum
unaryNum2Num = fmap (second n2nTrans) unaryNumToNumOpMap
n2bTrans = unaryOpConverter unpackNum ExprBool
unaryNum2Bool = fmap (second n2bTrans) unaryNumToBoolOpMap
b2bTrans = unaryOpConverter unpackBool ExprBool
unaryBool2Bool = fmap (second b2bTrans) unaryBoolOpMap
evalBinOpExpr :: BinOp -> Expression -> Expression -> Environment
-> EvaluateResult
evalBinOpExpr op expr1 expr2 env = do
let func = findOp op binOps
v1 <- valueOf expr1 env
v2 <- valueOf expr2 env
func v1 v2
evalUnaryOpExpr :: UnaryOp -> Expression -> Environment
-> EvaluateResult
evalUnaryOpExpr op expr env = do
let func = findOp op unaryOps
v <- valueOf expr env
func v
evalCondExpr :: [(Expression, Expression)] -> Environment -> EvaluateResult
evalCondExpr [] _ = throwError $ DefaultError "No predicate is true."
evalCondExpr ((e1, e2):pairs) env = do
val <- valueOf e1 env
bool <- unpackBool val
if bool then valueOf e2 env else evalCondExpr pairs env
evalLetExpr :: [(String, Expression)] -> Expression -> Environment
-> EvaluateResult
evalLetExpr bindings body env = do
bindVals <- evaledBindings
let bindDenoVals = fmap (second exprToDeno) bindVals
valueOf body $ extendMany bindDenoVals env
where
func maybeBindVals (name, expr) = do
pairs <- maybeBindVals
val <- valueOf expr env
return $ (name, val):pairs
evaledBindings = do
pairs <- foldl func (return []) bindings
return $ reverse pairs
evalLetStarExpr :: [(String, Expression)] -> Expression -> Environment
-> EvaluateResult
evalLetStarExpr [] body env = valueOf body env
evalLetStarExpr ((var, expr):pairs) body env = do
val <- valueOf expr env
evalLetStarExpr pairs body (extend var (exprToDeno val) env)
evalProcExpr :: [(String, Type)] -> Expression -> Environment -> EvaluateResult
evalProcExpr params body env =
return . ExprProc $ Procedure untypedParams body env
where untypedParams = fmap fst params
evalCallExpr :: Expression -> [Expression] -> Environment -> EvaluateResult
evalCallExpr rator rand env = do
rator <- valueOf rator env
proc <- unpackProc rator
args <- maybeArgs
applyProcedure proc args
where
func :: Try [ExpressedValue] -> Try ExpressedValue -> Try [ExpressedValue]
func maybeArgs maybeArg = do
args <- maybeArgs
arg <- maybeArg
return $ arg : args
maybeArgs :: Try [ExpressedValue]
maybeArgs = reverse <$>
foldl func (return []) (fmap (`valueOf` env) rand)
applyProcedure :: Procedure -> [ExpressedValue] -> EvaluateResult
applyProcedure (Procedure params body savedEnv) args = do
pairs <- safeZip params args
applyProcedure' pairs body savedEnv []
applyProcedure' :: [(String, ExpressedValue)] -> Expression -> Environment
-> [String]
-> EvaluateResult
applyProcedure' [] body env _ = valueOf body env
applyProcedure' ((name, val) : pairs) body env names
| name `elem` names =
throwError . DefaultError $ "Parameter name conflict" `mappend` name
| otherwise = let newEnv = extend name (exprToDeno val) env
in applyProcedure' pairs body newEnv (name : names)
safeZip :: [String] -> [ExpressedValue] -> Try [(String, ExpressedValue)]
safeZip names args = if nl == pl
then return $ zip names args
else throwError $ ArgNumMismatch (toInteger nl) args
where (nl, pl) = (length names, length args)
evalQualifiedVarExpr :: String -> String -> Environment -> EvaluateResult
evalQualifiedVarExpr mName vName env =
return . denoToExpr . forceEnvTry $ applyNamed env mName vName
| li-zhirui/EoplLangs | src/SimpleModule/Evaluator.hs | bsd-3-clause | 9,682 | 0 | 14 | 2,125 | 3,285 | 1,689 | 1,596 | 210 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
module Content.Contents
( parserContents
)
where
import Data.OrgMode.Parse.Attoparsec.Content (parseContents)
import Data.OrgMode.Types
import Data.Text (Text)
import Test.Tasty
import Test.Tasty.HUnit
import Util
import Util.Builder
import qualified Data.Text as Text
testDocS :: [Text] -> [Content] -> Assertion
testDocS s expected = expectParse parseContents (Text.unlines s) (Right expected)
parserContents :: TestTree
parserContents = testGroup "Attoparsec orgmode Section Contents"
[ testCase "Parses a Single Paragraph" $
testDocS
["*text *"]
[mark Bold ("text" :: Text)]
, testCase "Parses a HyperLink" $
testDocS
[ "[[https://orgmode.org/manual/Link-format.html][The Org Manual: Link format]]" ]
[ Paragraph
[ HyperLink "https://orgmode.org/manual/Link-format.html" (Just "The Org Manual: Link format") ]
]
, testCase "Parses an italicised HyperLink" $
testDocS
[ "/[[Headline 2][The Org Manual: Link format]]/" ]
[ Paragraph [
Italic [
HyperLink "Headline 2" (Just "The Org Manual: Link format")
]
]
]
, testCase "Parses an italicised HyperLink in an unordered list" $
testDocS
[ " - /[[Headline 2][The Org Manual: Link format]]/" ]
[ UnorderedList [
Item [
Paragraph [
Italic [
HyperLink "Headline 2" (Just "The Org Manual: Link format")
]
]
]
]
]
, testCase "Parses Paragraph and List" $
testDocS
["*text *", " * item1 "]
[mark Bold ("text" :: Text), UnorderedList [toI @Text "item1"]]
, testCase "Parses Paragraph and List with blank line" $
testDocS
["*text *", " ", " * item1"]
[mark Bold ("text" :: Text), UnorderedList [toI @Text "item1"]]
, testCase "Parses List and Paragraph" $
testDocS
[ " * item1", "*text *"]
[UnorderedList [toI @Text "item1"], mark Bold ("text" :: Text)]
, testCase "Parses List and Paragraph with blank line" $
testDocS
[ " * item1", " ", "*text *"]
[UnorderedList [toI @Text "item1"], mark Bold ("text" :: Text)]
]
| digitalmentat/orgmode-parse | test/Content/Contents.hs | bsd-3-clause | 2,477 | 0 | 20 | 834 | 514 | 278 | 236 | 55 | 1 |
module Pipes.Exhaustion (
inexhaustible
) where
import Control.Exception
import Pipes
import Pipes.Core
inexhaustible :: Monad m => Proxy a' a b' b m r -> Proxy a' a b' b m x
inexhaustible p = p *> (throw . AssertionFailed $ "Inexhaustible proxy exhausted.")
| Rotaerk/iircc | src/common/Pipes/Exhaustion.hs | bsd-3-clause | 263 | 0 | 8 | 48 | 89 | 47 | 42 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Config where
import Control.Monad.Except (ExceptT(..))
import Data.Aeson
import qualified Data.Text as TS
import Data.Yaml
import Network.URI (URI, parseURI)
import Web.JWT
data Config = Config { port :: Int
, authDBPath :: FilePath
, logPath :: FilePath
, baseUrl :: URI
, jwtSecret :: Secret
} deriving (Show)
instance FromJSON Config where
parseJSON (Object obj) =
Config <$> obj .: "port"
<*> obj .: "auth-db-path"
<*> obj .: "log-path"
<*> obj .: "base-url"
<*> (secret <$> obj .: "jwt-secret")
parseJSON _ = mempty
instance FromJSON URI where
parseJSON (String str) = maybe mempty pure (parseURI $ TS.unpack str)
parseJSON _ = mempty
loadConfig :: FilePath -> ExceptT ParseException IO Config
loadConfig = ExceptT . decodeFileEither
| savannidgerinel/mead | app/Config.hs | bsd-3-clause | 1,068 | 0 | 14 | 372 | 254 | 143 | 111 | 28 | 1 |
{-# LANGUAGE CPP #-}
#ifdef MainCall
#else
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE CPP #-}
{-@ LIQUID "--higherorder" @-}
{-@ LIQUID "--totality" @-}
{-@ LIQUID "--exactdc" @-}
{-@ LIQUID "--trust-internals" @-}
{-@ infix <+> @-}
{-@ infix <> @-}
import Language.Haskell.Liquid.ProofCombinators
import Prelude hiding ( mempty, mappend, mconcat, map, Monoid
, take, drop
, error, undefined
)
#include "../Data/List/RList.hs"
#endif
{-@ listRightId :: xs:List a -> { append N xs = xs } @-}
listRightId :: List a -> Proof
listRightId xs = append N xs ==. xs *** QED
{-@ listLeftId :: xs:List a -> { append xs N = xs } @-}
listLeftId :: List a -> Proof
listLeftId N
= append N N
==. N
*** QED
listLeftId (C x xs)
= append (C x xs) N
==. C x (append xs N)
==. C x xs ? listLeftId xs
*** QED
{-@ listAssoc :: x:List a -> y:List a -> z:List a
-> {(append x (append y z)) == (append (append x y) z) } @-}
listAssoc :: List a -> List a -> List a -> Proof
listAssoc N y z
= append N (append y z)
==. append y z
==. append (append N y) z
*** QED
listAssoc (C x xs) y z
= append (C x xs) (append y z)
==. C x (append xs (append y z))
==. C x (append (append xs y) z)
? listAssoc xs y z
==. append (C x (append xs y)) z
==. append (append (C x xs) y) z
*** QED
{-@ listTakeDrop ::
i:{Integer | 0 <= i} -> xs:{List a | i <= llen xs}
-> {xs == append (take i xs) (drop i xs)} / [llen xs] @-}
listTakeDrop :: Integer -> List a -> Proof
listTakeDrop i N
= append (take i N) (drop i N)
==. append N N
==. N
*** QED
listTakeDrop i xs | i == 0
= append (take i xs) (drop i xs)
==. append N xs
==. xs ? listLeftId xs
*** QED
listTakeDrop i (C x xs)
= append (take i (C x xs)) (drop i (C x xs))
==. append (x `C` (take (i-1) xs)) (drop (i-1) xs)
==. x `C` (append (take (i-1) xs) (drop (i-1) xs))
==. x `C` xs ? listTakeDrop (i-1) xs
*** QED
-------------------------------------------------------------------------------
-------------- Compatibility with the old names -----------------------------
-------------------------------------------------------------------------------
{-@ appendNil :: xs:List a -> { append xs N = xs } @-}
appendNil :: List a -> Proof
appendNil = listLeftId
{-@ appendAssoc :: x:List a -> y:List a -> z:List a
-> {(append x (append y z)) == (append (append x y) z) } @-}
appendAssoc :: List a -> List a -> List a -> Proof
appendAssoc = listAssoc
| nikivazou/verified_string_matching | src/Proofs/ListMonoidLemmata.hs | bsd-3-clause | 2,882 | 40 | 12 | 822 | 785 | 396 | 389 | 60 | 1 |
--------------------------------------------------------------------------------
-- Copyright © 2011 National Institute of Aerospace / Galois, Inc.
--------------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
module Copilot.Tools.CBMC
( Params (..)
, defaultParams
, genCBMC
, atomPrefix
, sbvPrefix
, appendPrefix
) where
import Copilot.Core
import qualified Copilot.Compile.C99 as C99
import qualified Copilot.Compile.SBV as SBV
import qualified System.IO as I
import Text.PrettyPrint.HughesPJ
--------------------------------------------------------------------------------
data Params = Params
{ numIterations :: Int }
--------------------------------------------------------------------------------
defaultParams :: Params
defaultParams = Params
{ numIterations = 10 }
--------------------------------------------------------------------------------
atomPrefix, sbvPrefix :: Maybe String
atomPrefix = Just "atm"
sbvPrefix = Just "sbv"
appendPrefix :: Maybe String -> String -> String
appendPrefix (Just pre) name = pre ++ "_" ++ name
appendPrefix Nothing name = name
--------------------------------------------------------------------------------
genCBMC :: Params -> Spec -> IO ()
genCBMC params spec =
do
C99.compile (C99.defaultParams { C99.prefix = atomPrefix }) spec
SBV.compile (SBV.defaultParams { SBV.prefix = sbvPrefix }) spec
h <- I.openFile "cbmc_driver.c" I.WriteMode
I.hPutStrLn h (render (driver params spec))
--------------------------------------------------------------------------------
driver :: Params -> Spec -> Doc
driver Params { numIterations = k } spec = vcat
[ text "#include <stdbool.h>"
, text "#include <stdint.h>"
, text "#include <assert.h>"
, include atomPrefix C99.c99DirName C99.c99FileRoot
, include sbvPrefix SBV.sbvDirName "copilot"
, text ""
, declNonDets spec
, text ""
, declExterns spec
, text ""
, sampleExterns spec
, text ""
, verifyObservers spec
, text ""
, text "int main (int argc, char const *argv[])"
, text "{"
, text " int i;"
, text ""
, text " for (i = 0; i < " <> int k <> text "; i++)"
, text " {"
, text " sampleExterns();"
, text $ " " ++ appendPrefix atomPrefix "step();"
, text $ " " ++ appendPrefix sbvPrefix "step();"
, text " verify_observers();"
, text " }"
, text ""
, text " return 0;"
, text "}"
]
where
include prefix dir header = text "#include" <+> doubleQuotes
( text (appendPrefix prefix dir) <> text"/"
<> text (appendPrefix prefix (header ++ ".h"))
)
--------------------------------------------------------------------------------
declNonDets :: Spec -> Doc
declNonDets = vcat . map declNonDet . externVars
where
declNonDet :: ExtVar -> Doc
declNonDet ext@(ExtVar _ t) = typeSpec t <+> nonDetName ext
--------------------------------------------------------------------------------
nonDetName :: ExtVar -> Doc
nonDetName (ExtVar name t) =
text ("nondet_" ++ name ++ "_") <> (typeSpec t) <> text "();"
--------------------------------------------------------------------------------
declExterns :: Spec -> Doc
declExterns = vcat . map declExtern . externVars
where
declExtern :: ExtVar -> Doc
declExtern (ExtVar name t) = typeSpec t <+> text name <> semi
--------------------------------------------------------------------------------
sampleExterns :: Spec -> Doc
sampleExterns spec = vcat
[ text "void sampleExterns()"
, text "{"
, text ""
, nest 2 (vcat $ map sampleExtern (externVars spec))
, text "}"
]
where
sampleExtern :: ExtVar -> Doc
sampleExtern ext@(ExtVar name _) =
text name <+> text "=" <+> nonDetName ext
--------------------------------------------------------------------------------
verifyObservers :: Spec -> Doc
verifyObservers spec = vcat
[ text "void verify_observers()"
, text "{"
, text ""
, nest 2 (vcat $ map verifyObserver (specObservers spec))
, text "}"
]
where
verifyObserver :: Observer -> Doc
verifyObserver (Observer name _ _) =
text "assert(" <> text (appendPrefix atomPrefix name) <+> text "=="
<+> text (appendPrefix sbvPrefix name) <> text ");"
--------------------------------------------------------------------------------
typeSpec :: UType -> Doc
typeSpec UType { uTypeType = t } = text (typeSpec' t)
where
typeSpec' Bool = "bool"
typeSpec' Int8 = "int8_t"
typeSpec' Int16 = "int16_t"
typeSpec' Int32 = "int32_t"
typeSpec' Int64 = "int64_t"
typeSpec' Word8 = "uint8_t"
typeSpec' Word16 = "uint16_t"
typeSpec' Word32 = "uint32_t"
typeSpec' Word64 = "uint64_t"
typeSpec' Float = "float"
typeSpec' Double = "double"
--------------------------------------------------------------------------------
| niswegmann/copilot-cbmc | src/Copilot/Tools/CBMC.hs | bsd-3-clause | 4,825 | 0 | 15 | 856 | 1,204 | 624 | 580 | 109 | 11 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
import BreakthroughGame
import AgentGeneric
import GenericGame
import qualified Data.Text as T
import Data.List (tail)
-- boardRepr :: Text
-- boardRepr b = T.pack $ reprToRow $ boardToDense b
gameRepr g = T.pack $ reverse $ tail $ reverse $ tail $ show $ toRepr $ (g :: Breakthrough)
-- This is a handler function for the GET request method on the HomeR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getHomeR :: Handler RepHtml
getHomeR = do
(formWidget, formEnctype) <- generateFormPost sampleForm
let submission = Nothing :: Maybe (FileInfo, Text)
handlerName = "getHomeR" :: Text
defaultLayout $ do
aDomId <- lift newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
postHomeR :: Handler RepHtml
postHomeR = do
((result, formWidget), formEnctype) <- runFormPost sampleForm
let handlerName = "postHomeR" :: Text
submission = case result of
FormSuccess res -> Just res
_ -> Nothing
defaultLayout $ do
aDomId <- lift newIdent
setTitle "Welcome To Yesod!"
$(widgetFile "homepage")
sampleForm :: Form (FileInfo, Text)
sampleForm = renderDivs $ (,)
<$> fileAFormReq "Choose a file"
<*> areq textField "What's on the file?" Nothing
| Tener/deeplearning-thesis | yesod/abaloney/Handler/Home.hs | bsd-3-clause | 1,591 | 0 | 13 | 356 | 332 | 175 | 157 | 33 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.Misc.Auxiliary
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Demonstrates model construction with auxiliary variables. Sometimes we
-- need to introduce a variable in our problem as an existential variable,
-- but it's "internal" to the problem and we do not consider it as part of
-- the solution. Also, in an `allSat` scenario, we may not care for models
-- that only differ in these auxiliaries. SBV allows designating such variables
-- as `isNonModelVar` so we can still use them like any other variable, but without
-- considering them explicitly in model construction.
-----------------------------------------------------------------------------
module Data.SBV.Examples.Misc.Auxiliary where
import Data.SBV
-- | A simple predicate, based on two variables @x@ and @y@, true when
-- @0 <= x <= 1@ and @x - abs y@ is @0@.
problem :: Predicate
problem = do x <- free "x"
y <- free "y"
constrain $ x .>= 0
constrain $ x .<= 1
return $ x - abs y .== (0 :: SInteger)
-- | Generate all satisfying assignments for our problem. We have:
--
-- >>> allModels
-- Solution #1:
-- x = 0 :: Integer
-- y = 0 :: Integer
-- Solution #2:
-- x = 1 :: Integer
-- y = 1 :: Integer
-- Solution #3:
-- x = 1 :: Integer
-- y = -1 :: Integer
-- Found 3 different solutions.
--
-- Note that solutions @2@ and @3@ share the value @x = 1@, since there are
-- multiple values of @y@ that make this particular choice of @x@ satisfy our constraint.
allModels :: IO AllSatResult
allModels = allSat problem
-- | Generate all satisfying assignments, but we first tell SBV that @y@ should not be considered
-- as a model problem, i.e., it's auxiliary. We have:
--
-- >>> modelsWithYAux
-- Solution #1:
-- x = 0 :: Integer
-- Solution #2:
-- x = 1 :: Integer
-- Found 2 different solutions.
--
-- Note that we now have only two solutions, one for each unique value of @x@ that satisfy our
-- constraint.
modelsWithYAux :: IO AllSatResult
modelsWithYAux = allSatWith z3{isNonModelVar = (`elem` ["y"])} problem
| josefs/sbv | Data/SBV/Examples/Misc/Auxiliary.hs | bsd-3-clause | 2,257 | 0 | 9 | 465 | 187 | 121 | 66 | 12 | 1 |
module Network.DGS.Status.Imports
(
module Data.List
, module Data.Monoid
, module Network.DGS.Atto
, module Network.DGS.Bulletin
, module Network.DGS.Game
, module Network.DGS.Message
, module Network.DGS.Misc
, module Network.DGS.Monad
, module Network.DGS.Time
, module Network.DGS.User
, UTCTime
, Color
, RuleSetGo
) where
import Data.List
import Data.Monoid
import Data.SGF.Types
import Data.Time
import Network.DGS.Atto hiding (takeWhile, take, dropWhile, drop)
import Network.DGS.Bulletin
import Network.DGS.Game hiding (Game(..))
import Network.DGS.Message
import Network.DGS.Misc
import Network.DGS.Monad
import Network.DGS.Time
import Network.DGS.User hiding (User(..), current)
| dmwit/dgs | Network/DGS/Status/Imports.hs | bsd-3-clause | 708 | 6 | 6 | 92 | 200 | 135 | 65 | 27 | 0 |
module Shared.ParserTools
( sepEndBy
, sepEndBy1
) where
import Control.Applicative
import Data.Attoparsec.Text
sepEndBy :: Alternative f => f a -> f b -> f [a]
sepEndBy p sep = sepBy p sep <* optional sep
sepEndBy1 :: Alternative m => m a -> m sep -> m [a]
sepEndBy1 p sep = (:) <$> p <*> ((sep *> sepEndBy p sep) <|> pure [])
| Rydgel/advent-of-code-2016 | src/Shared/ParserTools.hs | bsd-3-clause | 363 | 0 | 10 | 99 | 155 | 79 | 76 | 9 | 1 |
module Fay.Exts where
import qualified Language.Haskell.Exts.Annotated as A
type X = A.SrcSpanInfo
type Alt = A.Alt X
type BangType = A.BangType X
type ClassDecl = A.ClassDecl X
type Decl = A.Decl X
type DeclHead = A.DeclHead X
type Ex = A.Exp X
type Exp = A.Exp X
type ExportSpec = A.ExportSpec X
type FieldDecl = A.FieldDecl X
type FieldUpdate = A.FieldUpdate X
type GadtDecl = A.GadtDecl X
type GuardedAlts = A.GuardedAlts X
type GuardedRhs = A.GuardedRhs X
type ImportDecl = A.ImportDecl X
type ImportSpec = A.ImportSpec X
type Literal = A.Literal X
type Match = A.Match X
type Module = A.Module X
type ModuleName = A.ModuleName X
type ModulePragma = A.ModulePragma X
type Name = A.Name X
type Pat = A.Pat X
type PatField = A.PatField X
type QName = A.QName X
type QOp = A.QOp X
type QualConDecl = A.QualConDecl X
type QualStmt = A.QualStmt X
type Rhs = A.Rhs X
type SpecialCon = A.SpecialCon X
type SrcLoc = A.SrcLoc
type Stmt = A.Stmt X
type TyVarBind = A.TyVarBind X
type Type = A.Type X
moduleName :: A.SrcInfo a => A.Module a -> A.ModuleName a
moduleName (A.Module _ (Just (A.ModuleHead _ n _ _)) _ _ _) = n
moduleName (A.Module a Nothing _ _ _) = A.ModuleName a "Main"
moduleName m = error $ "moduleName: " ++ A.prettyPrint m
moduleExports :: A.Module X -> Maybe (A.ExportSpecList X)
moduleExports (A.Module _ (Just (A.ModuleHead _ _ _ e)) _ _ _) = e
moduleExports (A.Module _ Nothing _ _ _) = Nothing
moduleExports m = error $ "moduleExports: " ++ A.prettyPrint m
moduleNameString :: A.ModuleName t -> String
moduleNameString (A.ModuleName _ n) = n
mkIdent :: String -> A.Name A.SrcSpanInfo
mkIdent = A.Ident noI
noI :: A.SrcSpanInfo
noI = A.noInfoSpan (A.mkSrcSpan A.noLoc A.noLoc)
convertFieldDecl :: A.FieldDecl a -> ([A.Name a], A.BangType a)
convertFieldDecl (A.FieldDecl _ ns b) = (ns, b)
fieldDeclNames :: A.FieldDecl a -> [A.Name a]
fieldDeclNames (A.FieldDecl _ ns _) = ns
declHeadName :: A.DeclHead a -> A.Name a
declHeadName d = case d of
A.DHead _ n _ -> n
A.DHInfix _ _ n _ -> n
A.DHParen _ h -> declHeadName h
| fpco/fay | src/Fay/Exts.hs | bsd-3-clause | 2,092 | 0 | 12 | 413 | 891 | 464 | 427 | 59 | 3 |
module Main where
import Data.Semigroup
import Data.Version (showVersion)
import Options.Applicative
import qualified Paths_surface as Library (version)
import Surface.Command
command :: Parser Command
command
= flag' Interactive (long "interactive" <> short 'i' <> help "Launch the interactive REPL.")
<|> flag Run Debug (long "debug" <> short 'd' <> help "Print debugging information.")
<*> strArgument (metavar "FILE" <> help "The program to run.")
arguments :: ParserInfo Command
arguments = info
(version <*> helper <*> Main.command)
(fullDesc
<> progDesc "Surface is a small experiment in proof refinement–style typechecking and evaluation of dependently-typed languages."
<> header "surface - a dependently typed language with nothing much to say for itself")
main :: IO ()
main = execParser arguments >>= runCommand
versionString :: String
versionString = "Surface version " <> showVersion Library.version
version :: Parser (a -> a)
version = infoOption versionString (long "version" <> short 'V' <> help "Output version info.")
| robrix/surface | app/Main.hs | bsd-3-clause | 1,063 | 0 | 11 | 170 | 263 | 134 | 129 | 23 | 1 |
-------------------------------------------------------------------------
-- Main
-------------------------------------------------------------------------
{-
text2text converts a nested combination of typed text fragments to 1 typed output. A text fragment is delimited by '@@[<type>' and '@@]',
Text is processed in the following steps:
- parse/analyse the chunk structure to find out the types of chunks
- parse individual chunks according to their <type>
- this gives a representation in a common Text format
- which is then output into the requested representation.
The idea is to have the following formats supported, all in a restricted form appropriate for documentation and (relatively) easy mutual transformation
- doclatex: documentation LaTeX
- twiki:
- texinfo:
- html:
Currently supported/implemented:
- input : doclatex
- output: doclatex, twiki
-}
module Main where
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Maybe
import Data.Char
import System.Environment
import System.Exit
import System.Console.GetOpt
import System.IO
import UHC.Util.FPath
import Common
import Text
import Text.Trf.UniformContent
import Text.Parser
import Plugin
-- for plugin: generation of output
import qualified Text.To.DocLaTeX as O_DocLaTeX
import qualified Text.To.TWiki as O_TWiki
import qualified Text.To.Html as O_Html
-- for plugin: parsing input
import qualified Text.Parser.DocLaTeX as P_DocLaTeX
-------------------------------------------------------------------------
-- main
-------------------------------------------------------------------------
main :: IO ()
main
= do { args <- getArgs
; let oo@(o,n,errs) = getOpt Permute cmdLineOpts args
opts = foldr ($) defaultOpts o
; if optHelp opts
then putStrLn (usageInfo "Usage: text2text [options] [file|-]\n\noptions:" cmdLineOpts)
else if null errs
then let (f,frest) = if null n then (emptyFPath,[]) else if head n == "-" then (emptyFPath,tail n) else (mkFPath (head n),tail n)
in doCompile f opts
else putStr (head errs)
}
readT2TFile :: FPath -> Opts -> IO AGItf
readT2TFile fp opts
= do { (fp',fh) <- fpathOpenOrStdin fp
; txt <- hGetContents fh
; let toks = scan t2tScanOpts defaultScState infpStart [ScInput_Uninterpreted txt]
-- ; putStrLn (show toks)
; let (pres,perrs) = parseToResMsgs pAGItf toks
; if null perrs
then return pres
else do { mapM_ (hPutStrLn stderr . show) perrs
; exitFailure
}
}
-------------------------------------------------------------------------
-- Plugins
-------------------------------------------------------------------------
pluginMp :: PluginMp
pluginMp
= Map.fromList
[ ( TextType_DocLaTeX
, defaultPlugin
{ plgHasParserTextItems = True
, plgParseTextItems2 = P_DocLaTeX.pItf
, plgScanOptsMp = P_DocLaTeX.doclatexScanOptsMp
, plgScanInitState = defaultScState { scstateType = ScTpContent TextType_DocLaTeX }
, plgToOutDoc = Just O_DocLaTeX.textToOutDoc
}
)
, ( TextType_TWiki
, defaultPlugin
{ plgToOutDoc = Just O_TWiki.textToOutDoc
}
)
, ( TextType_Html
, defaultPlugin
{ plgToOutDoc = Just O_Html.textToOutDoc
}
)
]
-------------------------------------------------------------------------
-- Cmdline opts
-------------------------------------------------------------------------
cmdLineOpts
= [ Option "" [s] (NoArg (\o -> o {optGenFor = t})) ("generate " ++ s) | (s,t) <- Map.toList texttypeMp
]
++
[ Option "" ["help"] (NoArg oHelp)
"output this help"
, Option "" ["gen-header-numbering"] (OptArg oGenHdrNr "yes|no")
"generate header numbering, default=no"
{-
, Option "h" ["hs"] (NoArg oHS)
"generate code for haskell, default=no"
, Option "l" ["latex"] (NoArg oLaTeX)
"generate code for latex, default=no"
, Option "" ["preamble"] (OptArg oPreamble "yes|no")
"include preamble (marked by version=0), default=yes"
, Option "" ["line"] (OptArg oLinePragmas "yes|no")
"insert #LINE pragmas, default=no"
, Option "p" ["plain"] (NoArg oPlain)
"generate plain code, default=no"
, Option "" ["index"] (NoArg oIndex)
"combined with latex, generate index entries, default=no"
, Option "" ["gen"] (ReqArg oGenReqm "all|<nr>|(<nr> <aspect>*) (to be obsolete, renamed to --gen-reqm)")
"generate for version, default=none"
, Option "g" ["gen-reqm"] (ReqArg oGenReqm "all|<nr>|(<nr> <aspect>*)")
"generate for version, default=none"
, Option "" ["compiler"] (ReqArg oCompiler "<compiler version>")
"Version of the GHC compiler, i.e. 6.6"
, Option "" ["hidedest"] (ReqArg oHideDest "here|appx=<file>")
"destination of text marked as 'hide', default=here"
, Option "" ["order"] (ReqArg oVariantOrder "<order-spec> (to be obsolete, renamed to --variant-order)")
"variant order"
, Option "" ["variant-order"] (ReqArg oVariantOrder "<order-spec>")
"variant order"
, Option "b" ["base"] (ReqArg oBase "<name>")
"base name, default=derived from filename"
, Option "" ["xref-except"] (ReqArg oXRefExcept "<filename>")
"file with list of strings not to be cross ref'd"
, Option "" ["dep"] (NoArg oDep)
"output dependencies"
, Option "" ["depnameprefix"] (OptArg oDepNamePrefix "<name>")
"Prefix of generated makefile vars."
, Option "" ["depsrcvar"] (OptArg oDepSrcVar "<name>")
"Source base-directory"
, Option "" ["depdstvar"] (OptArg oDepDstVar "<name>")
"Destination base-directory"
, Option "" ["depmainvar"] (OptArg oDepMainVar "<name>")
"Varname for the list of main files"
, Option "" ["depdpdsvar"] (OptArg oDepDpdsVar "<name>")
"Varname for the list of dependencies"
, Option "" ["deporigdpdsvar"] (OptArg oDepOrigDpdsVar "<name>")
"Varname for the list of original dependencies"
, Option "" ["depbase"] (OptArg oDepBaseDir "<dir>")
"Root directory for the dependency generation"
, Option "" ["depign"] (OptArg oDepIgn "(<file> )*")
"Totally ignored dependencies"
, Option "" ["depterm"] (OptArg oDepTerm "(<file> => <dep>+ ,)*")
"Dependency ignore list (or terminals)"
, Option "" ["lhs2tex"] (OptArg oLhs2tex "yes|no")
"wrap chunks in lhs2tex's code environment, default=yes"
, Option "" ["agmodheader"] (OptArg oAGModHeader "yes|no")
"generate AG MODULE headers instead of Haskell module headers"
, Option "" ["def"] (ReqArg oDef "key:value")
"define key/value pair, alternate form: key=value"
-}
]
where oDocLaTeX o = o {optGenFor = TextType_DocLaTeX}
oHelp o = o {optHelp = True}
oGenHdrNr ms o = yesno (\f o -> o {optGenHeaderNumbering = f}) ms o
{-
oHS o = o {optHS = True}
oPreamble ms o = yesno (\f o -> o {optPreamble = f}) ms o
oLinePragmas ms o = yesno (\f o -> o {optLinePragmas = f}) ms o
oLaTeX o = o {optLaTeX = True}
oPlain o = o {optPlain = True}
oIndex o = o {optIndex = True}
oCompiler s o = o {optCompiler = map read (words (map (\c -> if c == '.' then ' ' else c) s))}
oLhs2tex ms o = yesno' ChWrapCode ChWrapPlain (\f o -> o {optWrapLhs2tex = f}) ms o
oBase s o = o {optBaseName = Just s}
oVariantOrder s o = o {optVariantRefOrder = parseAndGetRes pVariantRefOrder s}
oXRefExcept s o = o {optMbXRefExcept = Just s}
oGenReqm s o = case dropWhile isSpace s of
"all" -> o {optGenReqm = VReqmAll}
(c:_) | isDigit c -> o {optGenReqm = parseAndGetRes pVariantReqmRef s}
| c == '(' -> o {optGenReqm = parseAndGetRes pVariantReqm s}
_ -> o {optGenReqm = VReqmAll}
oHideDest s o = case s of
"here" -> o
('a':'p':'p':'x':'=':f) -> o {optChDest = (ChHide,f)}
_ -> o
oHelp o = o {optHelp = True}
oDep o = o {optGenDeps = True}
oDepNamePrefix ms o = o { optDepNamePrefix = maybe "FILE_" id ms }
oDepSrcVar ms o = o { optDepSrcVar = maybe "SRC_VAR" id ms }
oDepDstVar ms o = o { optDepDstVar = maybe "DST_VAR" id ms }
oDepMainVar ms o = o { optDepMainVar = maybe "FILES" id ms }
oDepDpdsVar ms o = o { optDepDpdsVar = maybe "DPDS" id ms }
oDepOrigDpdsVar ms o = o { optDepOrigDpdsVar = maybe "ORIG_DPDS" id ms }
oDepBaseDir ms o = o { optDepBaseDir = maybe "./" id ms }
oDepTerm ms o = o { optDepTerm = maybe Map.empty (Map.fromList . parseDeps) ms }
oDepIgn ms o = o { optDepIgn = maybe Set.empty (Set.fromList . words) ms }
oAGModHeader ms o = yesno (\f o -> o {optAGModHeader = f}) ms o
oDef s o = case break (\c -> c == ':' || c == '=') s of
(k,(_:v)) -> o {optDefs = Map.insert k v (optDefs o)}
_ -> o
-}
yesno' y n updO ms o
= case ms of
Just "yes" -> updO y o
Just "no" -> updO n o
_ -> o
yesno = yesno' True False
{-
parseDeps "" = []
parseDeps (',' : rest) = parseDeps rest
parseDeps s
= let (s',rest) = break (==',') s
in parseDep s' : parseDeps rest
parseDep s
= let (term,_:deps) = break (=='>') s
in (term, words deps)
-}
-------------------------------------------------------------------------
-- The actual work
-------------------------------------------------------------------------
doCompile :: FPath -> Opts -> IO ()
doCompile f opts
= do { pres <- readT2TFile f opts
; let (pres2,errs2) = textTrfUniformContent opts pluginMp pres
; mapM_ (hPutOutLn stderr . out) errs2
; case Map.lookup (optGenFor opts) pluginMp of
Just plg | isJust mbToOut
-> putOut $ fromJust mbToOut opts pres2
where mbToOut = plgToOutDoc plg
_ -> hPutOutLn stderr ("no output generator for " +++ show (optGenFor opts))
}
| atzedijkstra/uhc-doc | src/text2text/Text2Text.hs | bsd-3-clause | 11,348 | 0 | 18 | 3,729 | 1,018 | 561 | 457 | 82 | 5 |
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, OverloadedStrings, GADTs #-}
module SqlConnection where
import Control.Monad.Trans.Resource (runResourceT, ResourceT)
import Data.Text.Encoding (encodeUtf8)
import Web.Scotty
import Database.Persist
import Database.Persist.TH
import Database.Persist.Postgresql
import Data.Monoid ((<>))
runDb :: SqlPersist (ResourceT IO) a -> IO a
runDb query = do
let connStr = foldr (\(k,v) t -> t <> (encodeUtf8 $ k <> "=" <> v <> " ")) "" params
runResourceT . withPostgresqlConn connStr
| chengzh2008/hpffp | src/ch19-ApplyingStructure/sqlConnection.hs | bsd-3-clause | 539 | 0 | 18 | 74 | 161 | 91 | 70 | 13 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
{-# OPTIONS_GHC -fwarn-incomplete-uni-patterns #-}
module Day13 where
import Test.Hspec
import Data.Bits
import Control.Monad (guard)
import qualified Data.Set as Set
import Utils
-- Input DSL
-- utils
isWall :: Int -> (Int, Int) -> Bool
isWall key (x, y) = let res = x * x + 3 * x + 2 * x * y + y + y * y
res' = res + key
c = popCount res'
in odd c
type Pos = (Int, Int)
drawWall key = unlines $ do
y <- [0 .. 6]
return $ do
x <- [0 .. 9]
return $ if isWall key (x, y)
then '#'
else '.'
stepFunction :: Int -> Pos -> [Pos]
stepFunction key (x, y) = filter (not . isWall key) $ do
(dx, dy) <- [(-1, 0), (1, 0), (0, 1), (0, -1)]
let x' = x + dx
y' = y + dy
guard $ x' >= 0 && y' >= 0
guard $ x' /= x || y' /= y
return (x', y')
-- FIRST problem
day key = let (_, _, d) = bfs sc (1, 1) steps
in d
where sc todos _ _ = (31, 39) `Set.member` todos
steps = stepFunction key
-- SECOND problem
day' key = let (a, b, _) = bfs sc (1, 1) steps
in length a + length b
where sc _ _ depth = depth == 50
steps = stepFunction key
-- tests and data
content = 1352 :: Int
-- 8h35
-- 9h
-- Yeah, virtual leaderboard ;)
-- comment out and add tests
test = hspec $ it "works" $ do
isWall 10 (3, 5) `shouldBe` True
isWall 10 (6, 5) `shouldBe` False
drawWall 10 `shouldBe` "\
\.#.####.##\n\
\..#..#...#\n\
\#....##...\n\
\###.#.###.\n\
\.##..#..#.\n\
\..##....#.\n\
\#...##.###\n"
day content `shouldBe` 90
day' content `shouldBe` 135
| guibou/AdventOfCode2016 | src/Day13.hs | bsd-3-clause | 1,748 | 0 | 17 | 574 | 662 | 361 | 301 | 45 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
module TopicAbstractMachine where
import Language.Haskell.TH.Lift
import Text.PrettyPrint.HughesPJ
type TopicName = String
type LineNumber = Int
data Position = S1 | S2 | S3 | S4 | S5 | S6
| Sa | Sb | Sc | Sd | Se | Sf
deriving (Eq, Show)
newtype Program = Program {unProgram :: [(LineNumber, Instruction)] }
deriving (Eq, Show)
type LabelName = String
data Instruction = Jump Opcode LabelName
| Label LabelName
| Integer Integer
| Identifier LabelName
| String String
| ForeignCall String
| Bool Bool
| Double Double
| Opcode Opcode
| BlockCode LabelName Program
| AnnotatedInstruction StackEffect StackEffect Instruction
deriving (Eq, Show)
eraseAnnotation :: Instruction -> Instruction
eraseAnnotation (AnnotatedInstruction _ _ p) = p
eraseAnnotation x = x
annotateInstruction :: Instruction -> Instruction
annotateInstruction x@(Jump opc lbl) = let (i,o) = annotateOpcode opc
in annInstruction i o x
annotateInstruction x@(Opcode opc) = let (i,o) = annotateOpcode opc
in annInstruction i o x
annInstruction :: StackEffect -> StackEffect -> Instruction -> Instruction
annInstruction = AnnotatedInstruction
annotateOpcode :: Opcode -> (StackEffect,StackEffect)
annotateOpcode Nop = (EmptyStack, EmptyStack)
annotateOpcode If = (
SE S1 TBool "a" :>
SE S2 (TOr TCode TSymbol) "b" :>
SE S3 (TOr TCode TSymbol) "c",
EmptyStack
)
annotateOpcode Unless = annotateOpcode If
annotateOpcode Apply = (SE S1 TCode "a", EmptyStack)
annotateOpcode Call = (SE S1 TSymbol "a", EmptyStack)
annotateOpcode Return = (EmptyStack, EmptyStack)
annotateOpcode Jmp = (EmptyStack, EmptyStack)
annotateOpcode SkipZero = (SE S1 TInteger "a", SE S1 TInteger "a")
annotateOpcode SkipNotZero = (SE S1 TInteger "a", SE S1 TInteger "a")
annotateOpcode JumpNotZero = (SE S1 TInteger "a", SE S1 TInteger "a")
annotateOpcode JumpZero = (SE S1 TInteger "a", SE S1 TInteger "a")
annotateOpcode And = (SE S1 TLogical "a" :> SE S2 TLogical "a", SE Sa TLogical "a")
annotateOpcode Or = (SE S1 TLogical "a" :> SE S2 TLogical "a", SE Sa TLogical "a")
annotateOpcode Xor = (SE S1 TLogical "a" :> SE S2 TLogical "a", SE Sa TLogical "a")
annotateOpcode Not = (SE S1 (TOr TNumeric TLogical) "a", SE Sa (TOr TNumeric TLogical) "a")
annotateOpcode Add = (SE S1 TNumeric "a" :> SE S2 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Sub = (SE S1 TNumeric "a" :> SE S2 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Mul = (SE S1 TNumeric "a" :> SE S2 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Exp = (SE S1 TNumeric "a" :> SE S2 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Abs = (SE S1 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Sgn = (SE S1 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Dec = (SE S1 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Inc = (SE S1 TNumeric "a", SE Sa TNumeric "a")
annotateOpcode Eq = (SE S1 TAny "a" :> SE S2 TAny "a", SE Sa TBool "b")
annotateOpcode Dup = (
SE S1 TAny "a" :> SE S2 TAny "b",
SE S1 TAny "a" :> SE S1 TAny "a" :> SE S2 TAny "b"
)
annotateOpcode Over = (
tany S1 "a" :> tany S2 "b",
tany S2 "b" :> tany S1 "a" :> tany S2 "b"
)
annotateOpcode Swp = (
tany S1 "a" :> tany S2 "b",
tany S2 "b" :> tany S1 "a"
)
annotateOpcode Under = (
tany S1 "a" :> tany S2 "b",
tany S1 "a" :> tany S2 "b" :> tany S1 "a"
)
annotateOpcode Pop = (
tany S1 "a",
EmptyStack
)
annotateOpcode Rot3 = (
tany S1 "a" :> tany S2 "b" :> tany S3 "c",
tany S2 "b" :> tany S3 "c" :> tany S1 "a"
)
annotateOpcode Rot4 = (
tany S1 "a" :> tany S2 "b" :> tany S3 "c" :> tany S4 "d",
tany S2 "b" :> tany S3 "c" :> tany S4 "d" :> tany S1 "a"
)
annotateOpcode Rot5 = (
tany S1 "a" :> tany S2 "b" :> tany S3 "c" :> tany S4 "d" :> tany S5 "e",
tany S2 "b" :> tany S3 "c" :> tany S4 "d" :> tany S5 "e" :> tany S1 "a"
)
annotateOpcode Lod = (
SE S1 TInteger "a",
SE Sa TAny "b" :> SE S1 TInteger "a"
)
annotateOpcode Stor = (
SE S1 TAny "b" :> SE S1 TInteger "a",
EmptyStack
)
annotateOpcode Exit = (EmptyStack, EmptyStack)
tany n q = SE n TAny q
data StackEffect = SE Position Type Quantifier
| StackEffect :> StackEffect
| EmptyStack
deriving (Eq)
instance Show StackEffect where
show se = show $ text "---" $$ printStackEffect se $$ text "---"
instance Show (StackEffect,StackEffect) where
show (se,sb) = show $ listStackEffect True se `exzip` listStackEffect False sb
exzip :: [Doc] -> [Doc] -> Doc
exzip (x:xs) (y:ys) = x <+> text "->" <> sepa <+> ( y) $$ exzip xs ys
exzip [] (y:ys) = mempty <+> text "->" <> sepa <+> ( y) $$ exzip [] ys
exzip (y:ys) [] = y <+> text "->" <> sepa <+> (mempty) $$ exzip [] ys
exzip [] [] = mempty
sepa = text (extendText 10 " ")
extendText n (x:xs) = x : extendText (n - 1) xs
extendText 0 xs = xs
extendText n [] = replicate n ' '
listStackEffect :: Bool -> StackEffect -> [Doc]
listStackEffect _ EmptyStack = []
listStackEffect b (x :> y) = listStackEffect b x ++ listStackEffect b y
listStackEffect True (SE pos tpe quant) = [ text (extendText 1 quant) <+> char ':' <+> text (extendText 0 $ show (pos)) <+> char '(' <+> text ( extendText 0 (show tpe)) <+> text ( extendText 10 ")")]
listStackEffect False (SE pos tpe quant) = [ text quant <+> char ':' <+> text (show (pos)) <+> char '(' <+> text (show tpe) <+> text ")"]
printStackEffect :: StackEffect -> Doc
printStackEffect EmptyStack = text "---" $$ text "---"
printStackEffect (x :> y) = printStackEffect x $$ printStackEffect y
printStackEffect (SE pos tpe quant) = text quant <+> char ':' <+> text (show (pos)) <+> char '(' <+> text (show tpe) <+> text ")"
type Quantifier = String
data Type = TAny
| TNumeric
| TLogical
| TBool
| TInteger
| TDouble
| TSymbol
| TCode
| TBottom
| TOr Type Type
deriving (Eq, Show)
lower TAny = [TNumeric, TSymbol, TCode, TLogical]
type a :$ b = a b
infixr 1 :$
data Opcode =
If -- If s1, then s2 else s2
| Unless -- Unless s1, then s3 else s2
-- * Nop
| Nop
-- * Block Code calling
| Apply
-- * Function oriented
| Call -- call s1 with s2, s3 .. -> r1
| Return -- return from call
-- * Flow oriented
| Jmp -- Unconditional jump
| SkipZero -- skip next instruction if s1 == zero
| SkipNotZero -- skip next instruction if s1 == zero
| JumpZero -- Jump to label if s1 is zero
| JumpNotZero -- Jump to label if s1 is not zero
-- * Logical operators
| And -- And s1 s2 -> s1
| Or --
| Xor
| Not
-- * Numeric operations
-- All work like:
-- op s1 s2 -> r1
| Add
| Sub
| Mul
| Exp
-- * Mon ops
| Abs
| Sgn
| Dec
| Inc
-- * Value oriented
| Eq
-- * Stack manipulation
| Dup -- duplicate s1, s1 s2 -> s1 s1 s2
| Over -- pull s2 over s1, s1 s2 -> s2 s1 s2
| Swp -- swap s1 and s2 -> s1 s2 -> s2 s1
| Under -- put s1 under s2, s1 s2 -> s1 s2 s1
| Pop -- pop s1, s1 s2 -> s2
| Rot3 -- rot s1 s2 s3 -> s2 s3 s1
| Rot4 -- rot s1 s2 s3 s4 -> s2 s3 s4 s1
| Rot5 -- etc
| Drop -- drop(s1) -> drop s1 from the stack TODO drop should be dropped
-- * Meta stack manipulation
| SOn-- Flips the stack mode bit, if flipped on, the stack of stacks can be manipulated
| SOff -- Flips the stack mode bit, if flipped on, the stack of stacks can be manipulated
| Cst -- Create a stack
-- * Memory manipulation
| Lod -- Load from s1 and push result
| Stor -- Store s2 to s1
-- * Flow termination
| Exit -- Exit
deriving (Show, Eq, Ord)
data Line where
Line :: TopicName -> Maybe FilePath -> Maybe Program -> Line
Comment :: String -> Line
deriving Show
-- $(deriveLiftMany [''Line,''Program,''Instruction,''Opcode])
| edgarklerks/dotfiles | .xmonad/TopicAbstractMachine.hs | bsd-2-clause | 9,081 | 1 | 15 | 2,924 | 2,718 | 1,423 | 1,295 | 190 | 1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
-- Foreign Function Interface (FFI) and will usually be imported via
-- the "Foreign" module.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr
(
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
-- ** Low-level operations
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IOBase
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign pointer, and
-- associates a finaliser with the reference. The finaliser will be executed
-- after the last reference to the foreign object is dropped. Note that there
-- is no guarantee on how soon the finaliser is executed after the last
-- reference was dropped; this depends on the details of the Haskell storage
-- manager. The only guarantee is that the finaliser runs before the program
-- terminates.
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
-- ^This is a way to look at the pointer living inside a
-- foreign object. This function takes a function which is
-- applied to that pointer. The resulting 'IO' action is then
-- executed. The foreign object is kept alive at least during
-- the whole action, even if it is not used directly
-- inside. Note that it is not safe to return the pointer from
-- the action and use it after the action completes. All uses
-- of the pointer should be inside the
-- 'withForeignPtr' bracket. The reason for
-- this unsafeness is the same as for
-- 'unsafeForeignPtrToPtr' below: the finalizer
-- may run earlier than expected, because the compiler can only
-- track usage of the 'ForeignPtr' object, not
-- a 'Ptr' object made from it.
--
-- This function is normally used for marshalling data to
-- or from the object pointed to by the
-- 'ForeignPtr', using the operations from the
-- 'Storable' class.
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
-- | This variant of 'newForeignPtr' adds a finalizer that expects an
-- environment in addition to the finalized pointer. The environment
-- that will be passed to the finalizer is fixed by the second argument to
-- 'newForeignPtrEnv'.
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifdef __GLASGOW_HASKELL__
type FinalizerEnvPtr env a = FunPtr (Ptr env -> Ptr a -> IO ())
-- | like 'addForeignPtrFinalizerEnv' but allows the finalizer to be
-- passed an additional environment parameter to be passed to the
-- finalizer. The environment passed to the finalizer is fixed by the
-- second argument to 'addForeignPtrFinalizerEnv'
addForeignPtrFinalizerEnv ::
FinalizerEnvPtr env a -> Ptr env -> ForeignPtr a -> IO ()
addForeignPtrFinalizerEnv finalizer env fptr =
addForeignPtrConcFinalizer fptr
(mkFinalizerEnv finalizer env (unsafeForeignPtrToPtr fptr))
foreign import ccall "dynamic"
mkFinalizerEnv :: FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO ()
#endif
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray0',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
| alekar/hugs | packages/base/Foreign/ForeignPtr.hs | bsd-3-clause | 6,599 | 10 | 12 | 1,171 | 948 | 520 | 428 | 49 | 1 |
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module TcErrors(
reportUnsolved, reportAllUnsolved, warnAllUnsolved,
warnDefaulting,
solverDepthErrorTcS
) where
#include "HsVersions.h"
import TcRnTypes
import TcRnMonad
import TcMType
import TcType
import RnEnv( unknownNameSuggestions )
import Type
import TyCoRep
import Kind
import Unify ( tcMatchTys )
import Module
import FamInst
import FamInstEnv ( flattenTys )
import Inst
import InstEnv
import TyCon
import Class
import DataCon
import TcEvidence
import HsExpr ( UnboundVar(..) )
import HsBinds ( PatSynBind(..) )
import Name
import RdrName ( lookupGlobalRdrEnv, lookupGRE_Name, GlobalRdrEnv
, mkRdrUnqual, isLocalGRE, greSrcSpan )
import PrelNames ( typeableClassName, hasKey, ptrRepLiftedDataConKey
, ptrRepUnliftedDataConKey )
import Id
import Var
import VarSet
import VarEnv
import NameSet
import Bag
import ErrUtils ( ErrMsg, errDoc, pprLocErrMsg )
import BasicTypes
import ConLike ( ConLike(..) )
import Util
import FastString
import Outputable
import SrcLoc
import DynFlags
import StaticFlags ( opt_PprStyle_Debug )
import ListSetOps ( equivClasses )
import Maybes
import qualified GHC.LanguageExtensions as LangExt
import FV ( fvVarList, unionFV )
import Control.Monad ( when )
import Data.List ( partition, mapAccumL, nub, sortBy, unfoldr )
import qualified Data.Set as Set
#if __GLASGOW_HASKELL__ > 710
import Data.Semigroup ( Semigroup )
import qualified Data.Semigroup as Semigroup
#endif
{-
************************************************************************
* *
\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`.
-}
-- | Report unsolved goals as errors or warnings. We may also turn some into
-- deferred run-time errors if `-fdefer-type-errors` is on.
reportUnsolved :: WantedConstraints -> TcM (Bag EvBind)
reportUnsolved wanted
= do { binds_var <- newTcEvBinds
; defer_errors <- goptM Opt_DeferTypeErrors
; warn_errors <- woptM Opt_WarnDeferredTypeErrors -- implement #10283
; let type_errors | not defer_errors = TypeError
| warn_errors = TypeWarn
| otherwise = TypeDefer
; defer_holes <- goptM Opt_DeferTypedHoles
; warn_holes <- woptM Opt_WarnTypedHoles
; let expr_holes | not defer_holes = HoleError
| warn_holes = HoleWarn
| otherwise = HoleDefer
; partial_sigs <- xoptM LangExt.PartialTypeSignatures
; warn_partial_sigs <- woptM Opt_WarnPartialTypeSignatures
; let type_holes | not partial_sigs = HoleError
| warn_partial_sigs = HoleWarn
| otherwise = HoleDefer
; report_unsolved (Just binds_var) False type_errors expr_holes type_holes wanted
; getTcEvBinds binds_var }
-- | Report *all* unsolved goals as errors, even if -fdefer-type-errors is on
-- However, do not make any evidence bindings, because we don't
-- have any convenient place to put them.
-- See Note [Deferring coercion errors to runtime]
-- Used by solveEqualities for kind equalities
-- (see Note [Fail fast on kind errors] in TcSimplify]
-- and for simplifyDefault.
reportAllUnsolved :: WantedConstraints -> TcM ()
reportAllUnsolved wanted
= report_unsolved Nothing False TypeError HoleError HoleError wanted
-- | Report all unsolved goals as warnings (but without deferring any errors to
-- run-time). See Note [Safe Haskell Overlapping Instances Implementation] in
-- TcSimplify
warnAllUnsolved :: WantedConstraints -> TcM ()
warnAllUnsolved wanted
= report_unsolved Nothing True TypeWarn HoleWarn HoleWarn wanted
-- | Report unsolved goals as errors or warnings.
report_unsolved :: Maybe EvBindsVar -- cec_binds
-> Bool -- Errors as warnings
-> TypeErrorChoice -- Deferred type errors
-> HoleChoice -- Expression holes
-> HoleChoice -- Type holes
-> WantedConstraints -> TcM ()
report_unsolved mb_binds_var err_as_warn type_errors expr_holes type_holes wanted
| isEmptyWC wanted
= return ()
| otherwise
= do { traceTc "reportUnsolved (before zonking and tidying)" (ppr wanted)
; wanted <- zonkWC wanted -- Zonk to reveal all information
; env0 <- tcInitTidyEnv
-- If we are deferring we are going to need /all/ evidence around,
-- including the evidence produced by unflattening (zonkWC)
; let tidy_env = tidyFreeTyCoVars env0 free_tvs
free_tvs = tyCoVarsOfWCList wanted
; traceTc "reportUnsolved (after zonking and tidying):" $
vcat [ pprTvBndrs free_tvs
, ppr wanted ]
; warn_redundant <- woptM Opt_WarnRedundantConstraints
; let err_ctxt = CEC { cec_encl = []
, cec_tidy = tidy_env
, cec_defer_type_errors = type_errors
, cec_errors_as_warns = err_as_warn
, cec_expr_holes = expr_holes
, cec_type_holes = type_holes
, cec_suppress = False -- See Note [Suppressing error messages]
, cec_warn_redundant = warn_redundant
, cec_binds = mb_binds_var }
; tc_lvl <- getTcLevel
; reportWanteds err_ctxt tc_lvl wanted }
--------------------------------------------
-- Internal functions
--------------------------------------------
-- | An error Report collects messages categorised by their importance.
-- See Note [Error report] for details.
data Report
= Report { report_important :: [SDoc]
, report_relevant_bindings :: [SDoc]
}
{- Note [Error report]
The idea is that error msgs are divided into three parts: the main msg, the
context block (\"In the second argument of ...\"), and the relevant bindings
block, which are displayed in that order, with a mark to divide them. The
idea is that the main msg ('report_important') varies depending on the error
in question, but context and relevant bindings are always the same, which
should simplify visual parsing.
The context is added when the the Report is passed off to 'mkErrorReport'.
Unfortunately, unlike the context, the relevant bindings are added in
multiple places so they have to be in the Report.
-}
#if __GLASGOW_HASKELL__ > 710
instance Semigroup Report where
Report a1 b1 <> Report a2 b2 = Report (a1 ++ a2) (b1 ++ b2)
#endif
instance Monoid Report where
mempty = Report [] []
mappend (Report a1 b1) (Report a2 b2) = Report (a1 ++ a2) (b1 ++ b2)
-- | Put a doc into the important msgs block.
important :: SDoc -> Report
important doc = mempty { report_important = [doc] }
-- | Put a doc into the relevant bindings block.
relevant_bindings :: SDoc -> Report
relevant_bindings doc = mempty { report_relevant_bindings = [doc] }
data TypeErrorChoice -- What to do for type errors found by the type checker
= TypeError -- A type error aborts compilation with an error message
| TypeWarn -- A type error is deferred to runtime, plus a compile-time warning
| TypeDefer -- A type error is deferred to runtime; no error or warning at compile time
data HoleChoice
= HoleError -- A hole is a compile-time error
| HoleWarn -- Defer to runtime, emit a compile-time warning
| HoleDefer -- Defer to runtime, no warning
instance Outputable HoleChoice where
ppr HoleError = text "HoleError"
ppr HoleWarn = text "HoleWarn"
ppr HoleDefer = text "HoleDefer"
instance Outputable TypeErrorChoice where
ppr TypeError = text "TypeError"
ppr TypeWarn = text "TypeWarn"
ppr TypeDefer = text "TypeDefer"
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
-- Nothing <=> Report all errors, including holes
-- Do not add any evidence bindings, because
-- we have no convenient place to put them
-- See TcErrors.reportAllUnsolved
-- Just ev <=> make some errors (depending on cec_defer)
-- into warnings, and emit evidence bindings
-- into 'ev' for unsolved constraints
, cec_errors_as_warns :: Bool -- Turn all errors into warnings
-- (except for Holes, which are
-- controlled by cec_type_holes and
-- cec_expr_holes)
, cec_defer_type_errors :: TypeErrorChoice -- Defer type errors until runtime
-- Irrelevant if cec_binds = Nothing
, cec_expr_holes :: HoleChoice -- Holes in expressions
, cec_type_holes :: HoleChoice -- Holes in types
, cec_warn_redundant :: Bool -- True <=> -Wredundant-constraints
, 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 = m_evb
, ic_status = status, ic_info = info
, ic_env = tcl_env, ic_tclvl = tc_lvl })
| BracketSkol <- info
, not insoluble
= return () -- For Template Haskell brackets report only
-- 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
= do { reportWanteds ctxt' tc_lvl wanted
; traceTc "reportImplic" (ppr implic)
; when (cec_warn_redundant ctxt) $
warnRedundantConstraints ctxt' tcl_env info' dead_givens }
where
insoluble = isInsolubleStatus status
(env1, tvs') = mapAccumL tidyTyCoVarBndr (cec_tidy ctxt) tvs
info' = tidySkolemInfo env1 info
implic' = implic { ic_skols = tvs'
, ic_given = map (tidyEvVar env1) given
, ic_info = info' }
ctxt' = ctxt { cec_tidy = env1
, cec_encl = implic' : cec_encl ctxt
, cec_suppress = insoluble || cec_suppress ctxt
-- Suppress inessential errors if there
-- are are insolubles anywhere in the
-- tree rooted here, or we've come across
-- a suppress-worthy constraint higher up (Trac #11541)
, cec_binds = cec_binds ctxt *> m_evb }
-- If cec_binds ctxt is Nothing, that means
-- we're reporting *all* errors. Don't change
-- that behavior just because we're going into
-- an implication.
dead_givens = case status of
IC_Solved { ics_dead = dead } -> dead
_ -> []
warnRedundantConstraints :: ReportErrCtxt -> TcLclEnv -> SkolemInfo -> [EvVar] -> TcM ()
warnRedundantConstraints ctxt env info ev_vars
| null redundant_evs
= return ()
| SigSkol {} <- info
= setLclEnv env $ -- We want to add "In the type signature for f"
-- to the error context, which is a bit tiresome
addErrCtxt (text "In" <+> ppr info) $
do { env <- getLclEnv
; msg <- mkErrorReport ctxt env (important doc)
; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
| otherwise -- But for InstSkol there already *is* a surrounding
-- "In the instance declaration for Eq [a]" context
-- and we don't want to say it twice. Seems a bit ad-hoc
= do { msg <- mkErrorReport ctxt env (important doc)
; reportWarning (Reason Opt_WarnRedundantConstraints) msg }
where
doc = text "Redundant constraint" <> plural redundant_evs <> colon
<+> pprEvVarTheta redundant_evs
redundant_evs = case info of -- See Note [Redundant constraints in instance decls]
InstSkol -> filterOut improving ev_vars
_ -> ev_vars
improving ev_var = any isImprovementPred $
transSuperClasses (idType ev_var)
{- Note [Redundant constraints in instance decls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For instance declarations, we don't report unused givens if
they can give rise to improvement. Example (Trac #10100):
class Add a b ab | a b -> ab, a ab -> b
instance Add Zero b b
instance Add a b ab => Add (Succ a) b (Succ ab)
The context (Add a b ab) for the instance is clearly unused in terms
of evidence, since the dictionary has no feilds. But it is still
needed! With the context, a wanted constraint
Add (Succ Zero) beta (Succ Zero)
we will reduce to (Add Zero beta Zero), and thence we get beta := Zero.
But without the context we won't find beta := Zero.
This only matters in instance declarations..
-}
reportWanteds :: ReportErrCtxt -> TcLevel -> WantedConstraints -> TcM ()
reportWanteds ctxt tc_lvl (WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
= do { traceTc "reportWanteds" (vcat [ text "Simples =" <+> ppr simples
, text "Suppress =" <+> ppr (cec_suppress ctxt)])
; let tidy_cts = bagToList (mapBag (tidyCt env) (insols `unionBags` simples))
-- First deal with things that are utterly wrong
-- Like Int ~ Bool (incl nullary TyCons)
-- or Int ~ t a (AppTy on one side)
-- These ones are not suppressed by the incoming context
; let ctxt_for_insols = ctxt { cec_suppress = False }
; (ctxt1, cts1) <- tryReporters ctxt_for_insols report1 tidy_cts
-- Now all the other constraints. We suppress errors here if
-- any of the first batch failed, or if the enclosing context
-- says to suppress
; let ctxt2 = ctxt { cec_suppress = cec_suppress ctxt || cec_suppress ctxt1 }
; (_, leftovers) <- tryReporters ctxt2 report2 cts1
; MASSERT2( null leftovers, ppr leftovers )
-- 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 ctxt2) 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
env = cec_tidy ctxt
-- report1: ones that should *not* be suppresed by
-- an insoluble somewhere else in the tree
-- It's crucial that anything that is considered insoluble
-- (see TcRnTypes.trulyInsoluble) is caught here, otherwise
-- we might suppress its error message, and proceed on past
-- type checking to get a Lint error later
report1 = [ ("custom_error", is_user_type_error,
True, mkUserTypeErrorReporter)
, ("insoluble1", is_given_eq, True, mkGroupReporter mkEqErr)
, ("insoluble2", utterly_wrong, True, mkGroupReporter mkEqErr)
, ("skolem eq1", very_wrong, True, mkSkolReporter)
, ("skolem eq2", skolem_eq, True, mkSkolReporter)
, ("non-tv eq", non_tv_eq, True, mkSkolReporter)
, ("Out of scope", is_out_of_scope, True, mkHoleReporter)
, ("Holes", is_hole, False, mkHoleReporter)
-- The only remaining equalities are alpha ~ ty,
-- where alpha is untouchable; and representational equalities
, ("Other eqs", is_equality, False, mkGroupReporter mkEqErr) ]
-- report2: we suppress these if there are insolubles elsewhere in the tree
report2 = [ ("Implicit params", is_ip, False, mkGroupReporter mkIPErr)
, ("Irreds", is_irred, False, mkGroupReporter mkIrredErr)
, ("Dicts", is_dict, False, mkGroupReporter mkDictErr) ]
-- rigid_nom_eq, rigid_nom_tv_eq,
is_hole, is_dict,
is_equality, is_ip, is_irred :: Ct -> PredTree -> Bool
is_given_eq ct pred
| EqPred {} <- pred = arisesFromGivens ct
| otherwise = False
-- I think all given residuals are equalities
-- Things like (Int ~N Bool)
utterly_wrong _ (EqPred NomEq ty1 ty2) = isRigidTy ty1 && isRigidTy ty2
utterly_wrong _ _ = False
-- Things like (a ~N Int)
very_wrong _ (EqPred NomEq ty1 ty2) = isSkolemTy tc_lvl ty1 && isRigidTy ty2
very_wrong _ _ = False
-- Things like (a ~N b) or (a ~N F Bool)
skolem_eq _ (EqPred NomEq ty1 _) = isSkolemTy tc_lvl ty1
skolem_eq _ _ = False
-- Things like (F a ~N Int)
non_tv_eq _ (EqPred NomEq ty1 _) = not (isTyVarTy ty1)
non_tv_eq _ _ = False
-- rigid_nom_eq _ pred = isRigidEqPred tc_lvl pred
--
-- rigid_nom_tv_eq _ pred
-- | EqPred _ ty1 _ <- pred = isRigidEqPred tc_lvl pred && isTyVarTy ty1
-- | otherwise = False
is_out_of_scope ct _ = isOutOfScopeCt ct
is_hole ct _ = isHoleCt ct
is_user_type_error ct _ = isUserTypeErrorCt ct
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
---------------
isSkolemTy :: TcLevel -> Type -> Bool
-- The type is a skolem tyvar
isSkolemTy tc_lvl ty
| Just tv <- getTyVar_maybe ty
= isSkolemTyVar tv
|| (isSigTyVar tv && isTouchableMetaTyVar tc_lvl tv)
-- The last case is for touchable SigTvs
-- we postpone untouchables to a latter test (too obscure)
| otherwise
= False
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
mkSkolReporter :: Reporter
-- Suppress duplicates with either the same LHS, or same location
mkSkolReporter ctxt cts
= mapM_ (reportGroup mkEqErr ctxt) (group cts)
where
group [] = []
group (ct:cts) = (ct : yeses) : group noes
where
(yeses, noes) = partition (group_with ct) cts
group_with ct1 ct2
| EQ <- cmp_loc ct1 ct2 = True
| eq_lhs_type ct1 ct2 = True
| otherwise = False
mkHoleReporter :: Reporter
-- Reports errors one at a time
mkHoleReporter ctxt
= mapM_ $ \ct -> do { err <- mkHoleError ctxt ct
; maybeReportHoleError ctxt ct err
; maybeAddDeferredHoleBinding ctxt err ct }
mkUserTypeErrorReporter :: Reporter
mkUserTypeErrorReporter ctxt
= mapM_ $ \ct -> do { err <- mkUserTypeError ctxt ct
; maybeReportError ctxt err }
mkUserTypeError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkUserTypeError ctxt ct = mkErrorMsgFromCt ctxt ct
$ important
$ pprUserTypeErrorTy
$ case getUserTypeErrorMsg ct of
Just msg -> msg
Nothing -> pprPanic "mkUserTypeError" (ppr 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)
eq_lhs_type :: Ct -> Ct -> Bool
eq_lhs_type ct1 ct2
= case (classifyPredType (ctPred ct1), classifyPredType (ctPred ct2)) of
(EqPred eq_rel1 ty1 _, EqPred eq_rel2 ty2 _) ->
(eq_rel1 == eq_rel2) && (ty1 `eqType` ty2)
_ -> pprPanic "mkSkolReporter" (ppr ct1 $$ ppr ct2)
cmp_loc :: Ct -> Ct -> Ordering
cmp_loc ct1 ct2 = ctLocSpan (ctLoc ct1) `compare` ctLocSpan (ctLoc ct2)
reportGroup :: (ReportErrCtxt -> [Ct] -> TcM ErrMsg) -> ReportErrCtxt
-> [Ct] -> TcM ()
reportGroup mk_err ctxt cts =
case partition isMonadFailInstanceMissing cts of
-- Only warn about missing MonadFail constraint when
-- there are no other missing contstraints!
(monadFailCts, []) ->
do { err <- mk_err ctxt monadFailCts
; reportWarning (Reason Opt_WarnMissingMonadFailInstances) err }
(_, cts') -> do { err <- mk_err ctxt cts'
; maybeReportError ctxt err
-- But see Note [Always warn with -fdefer-type-errors]
; traceTc "reportGroup" (ppr cts')
; mapM_ (addDeferredBinding ctxt err) cts' }
-- Add deferred bindings for all
-- Redundant if we are going to abort compilation,
-- but that's hard to know for sure, and if we don't
-- abort, we need bindings for all (e.g. Trac #12156)
where
isMonadFailInstanceMissing ct =
case ctLocOrigin (ctLoc ct) of
FailablePattern _pat -> True
_otherwise -> False
maybeReportHoleError :: ReportErrCtxt -> Ct -> ErrMsg -> TcM ()
maybeReportHoleError ctxt ct 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.
| isTypeHoleCt ct
= -- For partial type signatures, generate warnings only, and do that
-- only if -fwarn_partial_type_signatures is on
case cec_type_holes ctxt of
HoleError -> reportError err
HoleWarn -> reportWarning (Reason Opt_WarnPartialTypeSignatures) err
HoleDefer -> return ()
-- Otherwise this is a typed hole in an expression
| otherwise
= -- If deferring, report a warning only if -Wtyped-holds is on
case cec_expr_holes ctxt of
HoleError -> reportError err
HoleWarn -> reportWarning (Reason Opt_WarnTypedHoles) err
HoleDefer -> return ()
maybeReportError :: ReportErrCtxt -> ErrMsg -> TcM ()
-- Report the error and/or make a deferred binding for it
maybeReportError ctxt err
| cec_suppress ctxt -- Some worse error has occurred;
= return () -- so suppress this error/warning
| cec_errors_as_warns ctxt
= reportWarning NoReason err
| otherwise
= case cec_defer_type_errors ctxt of
TypeDefer -> return ()
TypeWarn -> reportWarning (Reason Opt_WarnDeferredTypeErrors) err
TypeError -> reportError err
addDeferredBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
-- See Note [Deferring coercion errors to runtime]
addDeferredBinding ctxt err ct
| CtWanted { ctev_pred = pred, ctev_dest = dest } <- 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)"
err_tm = EvDelayedError pred err_fs
; case dest of
EvVarDest evar
-> addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
HoleDest hole
-> do { -- See Note [Deferred errors for coercion holes]
evar <- newEvVar pred
; addTcEvBind ev_binds_var $ mkWantedEvBind evar err_tm
; fillCoercionHole hole (mkTcCoVarCo evar) }}
| otherwise -- Do not set any evidence for Given/Derived
= return ()
maybeAddDeferredHoleBinding :: ReportErrCtxt -> ErrMsg -> Ct -> TcM ()
maybeAddDeferredHoleBinding ctxt err ct
| isExprHoleCt ct
= addDeferredBinding ctxt err ct -- Only add bindings for holes in expressions
| otherwise -- not for holes in partial type signatures
= return ()
tryReporters :: ReportErrCtxt -> [ReporterSpec] -> [Ct] -> TcM (ReportErrCtxt, [Ct])
-- Use the first reporter in the list whose predicate says True
tryReporters ctxt reporters cts
= do { traceTc "tryReporters {" (ppr cts)
; (ctxt', cts') <- go ctxt reporters cts
; traceTc "tryReporters }" (ppr cts')
; return (ctxt', cts') }
where
go ctxt [] cts
= return (ctxt, cts)
go ctxt (r : rs) cts
= do { (ctxt', cts') <- tryReporter ctxt r cts
; go ctxt' rs cts' }
-- Carry on with the rest, because we must make
-- deferred bindings for them if we have -fdefer-type-errors
-- But suppress their error messages
tryReporter :: ReportErrCtxt -> ReporterSpec -> [Ct] -> TcM (ReportErrCtxt, [Ct])
tryReporter ctxt (str, keep_me, suppress_after, reporter) cts
| null yeses = return (ctxt, cts)
| otherwise = do { traceTc "tryReporter{ " (text str <+> ppr yeses)
; reporter ctxt yeses
; let ctxt' = ctxt { cec_suppress = suppress_after || cec_suppress ctxt }
; traceTc "tryReporter end }" (text str <+> ppr (cec_suppress ctxt) <+> ppr suppress_after)
; return (ctxt', nos) }
where
(yeses, nos) = partition (\ct -> keep_me ct (classifyPredType (ctPred ct))) cts
pprArising :: CtOrigin -> SDoc
-- Used for the main, top-level error message
-- We've done special processing for TypeEq, KindEq, Given
pprArising (TypeEqOrigin {}) = empty
pprArising (KindEqOrigin {}) = empty
pprArising (GivenOrigin {}) = empty
pprArising orig = pprCtOrigin orig
-- 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 (pprCtLoc (ctLoc ct'))
mkErrorMsgFromCt :: ReportErrCtxt -> Ct -> Report -> TcM ErrMsg
mkErrorMsgFromCt ctxt ct report
= mkErrorReport ctxt (ctLocEnv (ctLoc ct)) report
mkErrorReport :: ReportErrCtxt -> TcLclEnv -> Report -> TcM ErrMsg
mkErrorReport ctxt tcl_env (Report important relevant_bindings)
= do { context <- mkErrInfo (cec_tidy ctxt) (tcl_ctxt tcl_env)
; mkErrDocAt (RealSrcSpan (tcl_loc tcl_env))
(errDoc important [context] relevant_bindings)
}
type UserGiven = Implication
getUserGivens :: ReportErrCtxt -> [UserGiven]
-- One item for each enclosing implication
getUserGivens (CEC {cec_encl = implics}) = getUserGivensFromImplics implics
getUserGivensFromImplics :: [Implication] -> [UserGiven]
getUserGivensFromImplics implics
= reverse (filterOut (null . ic_given) implics)
{-
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.
With #10283, you can now opt out of deferred type error warnings.
Note [Deferred errors for coercion holes]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we need to defer a type error where the destination for the evidence
is a coercion hole. We can't just put the error in the hole, because we can't
make an erroneous coercion. (Remember that coercions are erased for runtime.)
Instead, we invent a new EvVar, bind it to an error and then make a coercion
from that EvVar, filling the hole with that coercion. Because coercions'
types are unlifted, the error is guaranteed to be hit before we get to the
coercion.
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, ct1) <- relevantBindings True ctxt ct1
; let orig = ctOrigin ct1
msg = couldNotDeduce (getUserGivens ctxt) (map ctPred cts, orig)
; mkErrorMsgFromCt ctxt ct1 $
important msg `mappend` relevant_bindings binds_msg }
where
(ct1:_) = cts
----------------
mkHoleError :: ReportErrCtxt -> Ct -> TcM ErrMsg
mkHoleError _ctxt ct@(CHoleCan { cc_hole = ExprHole (OutOfScope occ rdr_env0) })
-- Out-of-scope variables, like 'a', where 'a' isn't bound; suggest possible
-- in-scope variables in the message, and note inaccessible exact matches
= do { dflags <- getDynFlags
; imp_info <- getImports
; let suggs_msg = unknownNameSuggestions dflags rdr_env0
(tcl_rdr lcl_env) imp_info rdr
; rdr_env <- getGlobalRdrEnv
; splice_locs <- getTopLevelSpliceLocs
; let match_msgs = mk_match_msgs rdr_env splice_locs
; mkErrDocAt (RealSrcSpan err_loc) $
errDoc [out_of_scope_msg] [] (match_msgs ++ [suggs_msg]) }
where
rdr = mkRdrUnqual occ
ct_loc = ctLoc ct
lcl_env = ctLocEnv ct_loc
err_loc = tcl_loc lcl_env
hole_ty = ctEvPred (ctEvidence ct)
boring_type = isTyVarTy hole_ty
out_of_scope_msg -- Print v :: ty only if the type has structure
| boring_type = hang herald 2 (ppr occ)
| otherwise = hang herald 2 (pp_with_type occ hole_ty)
herald | isDataOcc occ = text "Data constructor not in scope:"
| otherwise = text "Variable not in scope:"
-- Indicate if the out-of-scope variable exactly (and unambiguously) matches
-- a top-level binding in a later inter-splice group; see Note [OutOfScope
-- exact matches]
mk_match_msgs rdr_env splice_locs
= let gres = filter isLocalGRE (lookupGlobalRdrEnv rdr_env occ)
in case gres of
[gre]
| RealSrcSpan bind_loc <- greSrcSpan gre
-- Find splice between the unbound variable and the match; use
-- lookupLE, not lookupLT, since match could be in the splice
, Just th_loc <- Set.lookupLE bind_loc splice_locs
, err_loc < th_loc
-> [mk_bind_scope_msg bind_loc th_loc]
_ -> []
mk_bind_scope_msg bind_loc th_loc
| is_th_bind
= hang (quotes (ppr occ) <+> parens (text "splice on" <+> th_rng))
2 (text "is not in scope before line" <+> int th_start_ln)
| otherwise
= hang (quotes (ppr occ) <+> bind_rng <+> text "is not in scope")
2 (text "before the splice on" <+> th_rng)
where
bind_rng = parens (text "line" <+> int bind_ln)
th_rng
| th_start_ln == th_end_ln = single
| otherwise = multi
single = text "line" <+> int th_start_ln
multi = text "lines" <+> int th_start_ln <> text "-" <> int th_end_ln
bind_ln = srcSpanStartLine bind_loc
th_start_ln = srcSpanStartLine th_loc
th_end_ln = srcSpanEndLine th_loc
is_th_bind = th_loc `containsSpan` bind_loc
mkHoleError ctxt ct@(CHoleCan { cc_hole = hole })
-- Explicit holes, like "_" or "_f"
= do { (ctxt, binds_msg, ct) <- relevantBindings False ctxt ct
-- The 'False' means "don't filter the bindings"; see Trac #8191
; mkErrorMsgFromCt ctxt ct $
important hole_msg `mappend` relevant_bindings binds_msg }
where
occ = holeOcc hole
hole_ty = ctEvPred (ctEvidence ct)
tyvars = tyCoVarsOfTypeList hole_ty
hole_msg = case hole of
ExprHole {} -> vcat [ hang (text "Found hole:")
2 (pp_with_type occ hole_ty)
, tyvars_msg, expr_hole_hint ]
TypeHole {} -> vcat [ hang (text "Found type wildcard" <+>
quotes (ppr occ))
2 (text "standing for" <+>
quotes (pprType hole_ty))
, tyvars_msg, type_hole_hint ]
tyvars_msg = ppUnless (null tyvars) $
text "Where:" <+> vcat (map loc_msg tyvars)
type_hole_hint
| HoleError <- cec_type_holes ctxt
= text "To use the inferred type, enable PartialTypeSignatures"
| otherwise
= empty
expr_hole_hint -- Give hint for, say, f x = _x
| lengthFS (occNameFS occ) > 1 -- Don't give this hint for plain "_"
= text "Or perhaps" <+> quotes (ppr occ)
<+> text "is mis-spelled, or not in scope"
| otherwise
= empty
loc_msg tv
| isTyVar tv
= case tcTyVarDetails tv of
SkolemTv {} -> pprSkol (cec_encl ctxt) tv
MetaTv {} -> quotes (ppr tv) <+> text "is an ambiguous type variable"
det -> pprTcTyVarDetails det
| otherwise
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PrintExplicitCoercions dflags
then quotes (ppr tv) <+> text "is a coercion variable"
else empty
mkHoleError _ ct = pprPanic "mkHoleError" (ppr ct)
pp_with_type :: OccName -> Type -> SDoc
pp_with_type occ ty = hang (pprPrefixOcc occ) 2 (dcolon <+> pprType ty)
----------------
mkIPErr :: ReportErrCtxt -> [Ct] -> TcM ErrMsg
mkIPErr ctxt cts
= do { (ctxt, binds_msg, ct1) <- relevantBindings True ctxt ct1
; let orig = ctOrigin ct1
preds = map ctPred cts
givens = getUserGivens ctxt
msg | null givens
= addArising orig $
sep [ text "Unbound implicit parameter" <> plural cts
, nest 2 (pprTheta preds) ]
| otherwise
= couldNotDeduce givens (preds, orig)
; mkErrorMsgFromCt ctxt ct1 $
important msg `mappend` relevant_bindings binds_msg }
where
(ct1:_) = cts
{-
Note [OutOfScope exact matches]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When constructing an out-of-scope error message, we not only generate a list of
possible in-scope alternatives but also search for an exact, unambiguous match
in a later inter-splice group. If we find such a match, we report its presence
(and indirectly, its scope) in the message. For example, if a module A contains
the following declarations,
foo :: Int
foo = x
$(return []) -- Empty top-level splice
x :: Int
x = 23
we will issue an error similar to
A.hs:6:7: error:
• Variable not in scope: x :: Int
• ‘x’ (line 11) is not in scope before the splice on line 8
By providing information about the match, we hope to clarify why declaring a
variable after a top-level splice but using it before the splice generates an
out-of-scope error (a situation which is often confusing to Haskell newcomers).
Note that if we find multiple exact matches to the out-of-scope variable
(hereafter referred to as x), we report nothing. Such matches can only be
duplicate record fields, as the presence of any other duplicate top-level
declarations would have already halted compilation. But if these record fields
are declared in a later inter-splice group, then so too are their corresponding
types. Thus, these types must not occur in the inter-splice group containing x
(any unknown types would have already been reported), and so the matches to the
record fields are most likely coincidental.
One oddity of the exact match portion of the error message is that we specify
where the match to x is NOT in scope. Why not simply state where the match IS
in scope? It most cases, this would be just as easy and perhaps a little
clearer for the user. But now consider the following example:
{-# LANGUAGE TemplateHaskell #-}
module A where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
foo = x
$(do -------------------------------------------------
ds <- [d| ok1 = x
|]
addTopDecls ds
return [])
bar = $(do
ds <- [d| x = 23
ok2 = x
|]
addTopDecls ds
litE $ stringL "hello")
$(return []) -----------------------------------------
ok3 = x
Here, x is out-of-scope in the declaration of foo, and so we report
A.hs:8:7: error:
• Variable not in scope: x
• ‘x’ (line 16) is not in scope before the splice on lines 10-14
If we instead reported where x IS in scope, we would have to state that it is in
scope after the second top-level splice as well as among all the top-level
declarations added by both calls to addTopDecls. But doing so would not only
add complexity to the code but also overwhelm the user with unneeded
information.
The logic which determines where x is not in scope is straightforward: it simply
finds the last top-level splice which occurs after x but before (or at) the
match to x (assuming such a splice exists). In most cases, the check that the
splice occurs after x acts only as a sanity check. For example, when the match
to x is a non-TH top-level declaration and a splice S occurs before the match,
then x must precede S; otherwise, it would be in scope. But when dealing with
addTopDecls, this check serves a practical purpose. Consider the following
declarations:
$(do
ds <- [d| ok = x
x = 23
|]
addTopDecls ds
return [])
foo = x
In this case, x is not in scope in the declaration for foo. Since x occurs
AFTER the splice containing the match, the logic does not find any splices after
x but before or at its match, and so we report nothing about x's scope. If we
had not checked whether x occurs before the splice, we would have instead
reported that x is not in scope before the splice. While correct, such an error
message is more likely to confuse than to enlighten.
-}
{-
************************************************************************
* *
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.
Note [Error messages for untouchables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (Trac #9109)
data G a where { GBool :: G Bool }
foo x = case x of GBool -> True
Here we can't solve (t ~ Bool), where t is the untouchable result
meta-var 't', because of the (a ~ Bool) from the pattern match.
So we infer the type
f :: forall a t. G a -> t
making the meta-var 't' into a skolem. So when we come to report
the unsolved (t ~ Bool), t won't look like an untouchable meta-var
any more. So we don't assert that it is.
-}
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
mkEqErr1 ctxt ct
| arisesFromGivens ct
= do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
; let (given_loc, given_msg) = mk_given (ctLoc ct) (cec_encl ctxt)
; dflags <- getDynFlags
; let report = important given_msg `mappend` relevant_bindings binds_msg
; mkEqErr_help dflags ctxt report
(setCtLoc ct given_loc) -- Note [Inaccessible code]
Nothing ty1 ty2 }
| otherwise -- Wanted or derived
= do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
; rdr_env <- getGlobalRdrEnv
; fam_envs <- tcGetFamInstEnvs
; exp_syns <- goptM Opt_PrintExpandedSynonyms
; let (keep_going, is_oriented, wanted_msg)
= mk_wanted_extra (ctLoc ct) exp_syns
coercible_msg = case ctEqRel ct of
NomEq -> empty
ReprEq -> mkCoercibleExplanation rdr_env fam_envs ty1 ty2
; dflags <- getDynFlags
; traceTc "mkEqErr1" (ppr ct $$ pprCtOrigin (ctOrigin ct))
; let report = mconcat [important wanted_msg, important coercible_msg,
relevant_bindings binds_msg]
; if keep_going
then mkEqErr_help dflags ctxt report ct is_oriented ty1 ty2
else mkErrorMsgFromCt ctxt ct report }
where
(ty1, ty2) = getEqPredTys (ctPred ct)
mk_given :: CtLoc -> [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 [] = (loc, empty)
mk_given loc (implic : _) = (setCtLocEnv loc (ic_env implic)
, hang (text "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 :: CtLoc -> Bool -> (Bool, Maybe SwapFlag, SDoc)
mk_wanted_extra loc expandSyns
= case ctLocOrigin loc of
orig@TypeEqOrigin {} -> mkExpectedActualMsg ty1 ty2 orig
t_or_k expandSyns
where
t_or_k = ctLocTypeOrKind_maybe loc
KindEqOrigin cty1 mb_cty2 sub_o sub_t_or_k
-> (True, Nothing, msg1 $$ msg2)
where
sub_what = case sub_t_or_k of Just KindLevel -> text "kinds"
_ -> text "types"
msg1 = sdocWithDynFlags $ \dflags ->
case mb_cty2 of
Just cty2
| gopt Opt_PrintExplicitCoercions dflags
|| not (cty1 `pickyEqType` cty2)
-> hang (text "When matching" <+> sub_what)
2 (vcat [ ppr cty1 <+> dcolon <+>
ppr (typeKind cty1)
, ppr cty2 <+> dcolon <+>
ppr (typeKind cty2) ])
_ -> text "When matching the kind of" <+> quotes (ppr cty1)
msg2 = case sub_o of
TypeEqOrigin {}
| Just cty2 <- mb_cty2 ->
thdOf3 (mkExpectedActualMsg cty1 cty2 sub_o sub_t_or_k
expandSyns)
_ -> empty
_ -> (True, 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
, isNothing (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
-- SLPJ Jun 15: I could not convince myself that these hints were really
-- useful. Maybe they are, but I think we need more work to make them
-- actually helpful.
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
| isBuiltInSyntax (tyConName tc) -- don't print roles for (->), etc.
= Nothing
| otherwise
= Just $ hsep $ [text "type role", ppr tc] ++ map ppr roles
where
roles = tyConRoles tc
-}
mkEqErr_help :: DynFlags -> ReportErrCtxt -> Report
-> Ct
-> Maybe SwapFlag -- Nothing <=> not sure
-> TcType -> TcType -> TcM ErrMsg
mkEqErr_help dflags ctxt report ct oriented ty1 ty2
| Just tv1 <- tcGetTyVar_maybe ty1 = mkTyVarEqErr dflags ctxt report ct oriented tv1 ty2
| Just tv2 <- tcGetTyVar_maybe ty2 = mkTyVarEqErr dflags ctxt report ct swapped tv2 ty1
| otherwise = reportEqErr ctxt report ct oriented ty1 ty2
where
swapped = fmap flipSwap oriented
reportEqErr :: ReportErrCtxt -> Report
-> Ct
-> Maybe SwapFlag -- Nothing <=> not sure
-> TcType -> TcType -> TcM ErrMsg
reportEqErr ctxt report ct oriented ty1 ty2
= mkErrorMsgFromCt ctxt ct (mconcat [misMatch, report, eqInfo])
where misMatch = important $ misMatchOrCND ctxt ct oriented ty1 ty2
eqInfo = important $ mkEqInfoMsg ct ty1 ty2
mkTyVarEqErr :: DynFlags -> ReportErrCtxt -> Report -> Ct
-> Maybe SwapFlag -> TcTyVar -> TcType -> TcM ErrMsg
-- tv1 and ty2 are already tidied
mkTyVarEqErr dflags ctxt report 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)
= mkErrorMsgFromCt ctxt ct $ mconcat
[ important $ misMatchOrCND ctxt ct oriented ty1 ty2
, important $ extraTyVarInfo ctxt tv1 ty2
, report
]
-- 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
| OC_Occurs <- occ_check_expand
, ctEqRel ct == NomEq || isTyVarUnderDatatype tv1 ty2
-- See Note [Occurs check error] in TcCanonical
= do { let occCheckMsg = important $ addArising (ctOrigin ct) $
hang (text "Occurs check: cannot construct the infinite" <+> what <> colon)
2 (sep [ppr ty1, char '~', ppr ty2])
extra2 = important $ mkEqInfoMsg ct ty1 ty2
interesting_tyvars
= filter (not . isEmptyVarSet . tyCoVarsOfType . tyVarKind) $
filter isTyVar $
fvVarList $
tyCoFVsOfType ty1 `unionFV` tyCoFVsOfType ty2
extra3 = relevant_bindings $
ppWhen (not (null interesting_tyvars)) $
hang (text "Type variable kinds:") 2 $
vcat (map (tyvar_binding . tidyTyVarOcc (cec_tidy ctxt))
interesting_tyvars)
tyvar_binding tv = ppr tv <+> dcolon <+> ppr (tyVarKind tv)
; mkErrorMsgFromCt ctxt ct $ mconcat [occCheckMsg, extra2, extra3, report] }
| OC_Forall <- occ_check_expand
= do { let msg = vcat [ text "Cannot instantiate unification variable"
<+> quotes (ppr tv1)
, hang (text "with a" <+> what <+> text "involving foralls:") 2 (ppr ty2)
, nest 2 (text "GHC doesn't yet support impredicative polymorphism") ]
-- Unlike the other reports, this discards the old 'report_important'
-- instead of augmenting it. This is because the details are not likely
-- to be helpful since this is just an unimplemented feature.
; mkErrorMsgFromCt ctxt ct $ report { report_important = [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
= mkErrorMsgFromCt ctxt ct $ mconcat
[ important $ misMatchMsg ct oriented ty1 ty2
, important $ extraTyVarInfo ctxt tv1 ty2
, report
]
-- 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` (tyCoVarsOfType ty2)) skols
, not (null esc_skols)
= do { let msg = important $ misMatchMsg ct oriented ty1 ty2
esc_doc = sep [ text "because" <+> what <+> text "variable" <> plural esc_skols
<+> pprQuotedList esc_skols
, text "would escape" <+>
if isSingleton esc_skols then text "its scope"
else text "their scope" ]
tv_extra = important $
vcat [ nest 2 $ esc_doc
, sep [ (if isSingleton esc_skols
then text "This (rigid, skolem)" <+>
what <+> text "variable is"
else text "These (rigid, skolem)" <+>
what <+> text "variables are")
<+> text "bound by"
, nest 2 $ ppr skol_info
, nest 2 $ text "at" <+> ppr (tcl_loc env) ] ]
; mkErrorMsgFromCt ctxt ct (mconcat [msg, tv_extra, report]) }
-- Nastiest case: attempt to unify an untouchable variable
-- See Note [Error messages for untouchables]
| (implic:_) <- cec_encl ctxt -- Get the innermost context
, Implic { ic_env = env, ic_given = given
, ic_tclvl = lvl, ic_info = skol_info } <- implic
= ASSERT2( isTcTyVar tv1 && not (isTouchableMetaTyVar lvl tv1)
, ppr tv1 ) -- See Note [Error messages for untouchables]
do { let msg = important $ misMatchMsg ct oriented ty1 ty2
tclvl_extra = important $
nest 2 $
sep [ quotes (ppr tv1) <+> text "is untouchable"
, nest 2 $ text "inside the constraints:" <+> pprEvVarTheta given
, nest 2 $ text "bound by" <+> ppr skol_info
, nest 2 $ text "at" <+> ppr (tcl_loc env) ]
tv_extra = important $ extraTyVarInfo ctxt tv1 ty2
add_sig = important $ suggestAddSig ctxt ty1 ty2
; mkErrorMsgFromCt ctxt ct $ mconcat
[msg, tclvl_extra, tv_extra, add_sig, report] }
| otherwise
= reportEqErr ctxt report 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
ty1 = mkTyVarTy tv1
what = case ctLocTypeOrKind_maybe (ctLoc ct) of
Just KindLevel -> text "kind"
_ -> text "type"
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]
-- (c) warning about -fprint-explicit-kinds if that might be helpful
mkEqInfoMsg ct ty1 ty2
= tyfun_msg $$ ambig_msg $$ invis_msg
where
mb_fun1 = isTyFun_maybe ty1
mb_fun2 = isTyFun_maybe ty2
ambig_msg | isJust mb_fun1 || isJust mb_fun2
= snd (mkAmbigMsg False ct)
| otherwise = empty
-- better to check the exp/act types in the CtOrigin than the actual
-- mismatched types for suggestion about -fprint-explicit-kinds
(act_ty, exp_ty) = case ctOrigin ct of
TypeEqOrigin { uo_actual = act
, uo_expected = Check exp } -> (act, exp)
_ -> (ty1, ty2)
invis_msg | Just vis <- tcEqTypeVis act_ty exp_ty
, not vis
= ppSuggestExplicitKinds
| otherwise
= empty
tyfun_msg | Just tc1 <- mb_fun1
, Just tc2 <- mb_fun2
, tc1 == tc2
= text "NB:" <+> quotes (ppr tc1)
<+> text "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 ||
(isRigidTy ty1 && isRigidTy ty2) ||
isGivenCt ct
-- If the equality is unconditionally insoluble
-- or there is no context, don't report the context
= misMatchMsg ct oriented ty1 ty2
| otherwise
= couldNotDeduce givens ([eq_pred], orig)
where
ev = ctEvidence ct
eq_pred = ctEvPred ev
orig = ctEvOrigin ev
givens = [ given | given <- getUserGivens ctxt, not (ic_no_eqs given)]
-- Keep only UserGivens that have some equalities
couldNotDeduce :: [UserGiven] -> (ThetaType, CtOrigin) -> SDoc
couldNotDeduce givens (wanteds, orig)
= vcat [ addArising orig (text "Could not deduce:" <+> pprTheta wanteds)
, vcat (pp_givens givens)]
pp_givens :: [UserGiven] -> [SDoc]
pp_givens givens
= case givens of
[] -> []
(g:gs) -> ppr_given (text "from the context:") g
: map (ppr_given (text "or from:")) gs
where
ppr_given herald (Implic { ic_given = gs, ic_info = skol_info
, ic_env = env })
= hang (herald <+> pprEvVarTheta gs)
2 (sep [ text "bound by" <+> ppr skol_info
, text "at" <+> ppr (tcl_loc env) ])
extraTyVarInfo :: ReportErrCtxt -> TcTyVar -> TcType -> SDoc
-- Add on extra info about skolem constants
-- NB: The types themselves are already tidied
extraTyVarInfo ctxt tv1 ty2
= ASSERT2( isTcTyVar tv1, ppr tv1 )
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
| let pp_tv = quotes (ppr tv)
= case tcTyVarDetails tv of
SkolemTv {} -> pprSkol implics tv
FlatSkol {} -> pp_tv <+> text "is a flattening type variable"
RuntimeUnk {} -> pp_tv <+> text "is an interactive-debugger skolem"
MetaTv {} -> empty
suggestAddSig :: ReportErrCtxt -> TcType -> TcType -> SDoc
-- See Note [Suggest adding a type signature]
suggestAddSig ctxt ty1 ty2
| null inferred_bndrs
= empty
| [bndr] <- inferred_bndrs
= text "Possible fix: add a type signature for" <+> quotes (ppr bndr)
| otherwise
= text "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
, isSkolemTyVar tv
, InferSkol prs <- ic_info (getSkolemInfo (cec_encl ctxt) tv)
= map fst prs
| otherwise
= []
--------------------
misMatchMsg :: Ct -> Maybe SwapFlag -> TcType -> TcType -> SDoc
-- Types are already tidy
-- If oriented then ty1 is actual, ty2 is expected
misMatchMsg ct oriented ty1 ty2
| Just NotSwapped <- oriented
= misMatchMsg ct (Just IsSwapped) ty2 ty1
-- These next two cases are when we're about to report, e.g., that
-- 'PtrRepLifted doesn't match 'VoidRep. Much better just to say
-- lifted vs. unlifted
| Just (tc1, []) <- splitTyConApp_maybe ty1
, tc1 `hasKey` ptrRepLiftedDataConKey
= lifted_vs_unlifted
| Just (tc2, []) <- splitTyConApp_maybe ty2
, tc2 `hasKey` ptrRepLiftedDataConKey
= lifted_vs_unlifted
| Just (tc1, []) <- splitTyConApp_maybe ty1
, Just (tc2, []) <- splitTyConApp_maybe ty2
, (tc1 `hasKey` ptrRepLiftedDataConKey && tc2 `hasKey` ptrRepUnliftedDataConKey)
|| (tc1 `hasKey` ptrRepUnliftedDataConKey && tc2 `hasKey` ptrRepLiftedDataConKey)
= lifted_vs_unlifted
| otherwise -- So now we have Nothing or (Just IsSwapped)
-- For some reason we treat Nothing like IsSwapped
= addArising orig $
sep [ text herald1 <+> quotes (ppr ty1)
, nest padding $
text herald2 <+> quotes (ppr ty2)
, sameOccExtra ty2 ty1 ]
where
herald1 = conc [ "Couldn't match"
, if is_repr then "representation of" else ""
, if is_oriented then "expected" else ""
, what ]
herald2 = conc [ "with"
, if is_repr then "that of" else ""
, if is_oriented then ("actual " ++ what) else "" ]
padding = length herald1 - length herald2
is_repr = case ctEqRel ct of { ReprEq -> True; NomEq -> False }
is_oriented = isJust oriented
orig = ctOrigin ct
what = case ctLocTypeOrKind_maybe (ctLoc ct) of
Just KindLevel -> "kind"
_ -> "type"
conc :: [String] -> String
conc = foldr1 add_space
add_space :: String -> String -> String
add_space s1 s2 | null s1 = s2
| null s2 = s1
| otherwise = s1 ++ (' ' : s2)
lifted_vs_unlifted
= addArising orig $
text "Couldn't match a lifted type with an unlifted type"
mkExpectedActualMsg :: Type -> Type -> CtOrigin -> Maybe TypeOrKind -> Bool
-> (Bool, Maybe SwapFlag, SDoc)
-- NotSwapped means (actual, expected), IsSwapped is the reverse
-- First return val is whether or not to print a herald above this msg
mkExpectedActualMsg ty1 ty2 (TypeEqOrigin { uo_actual = act
, uo_expected = Check exp
, uo_thing = maybe_thing })
m_level printExpanded
| KindLevel <- level, occurs_check_error = (True, Nothing, empty)
| isUnliftedTypeKind act, isLiftedTypeKind exp = (False, Nothing, msg2)
| isLiftedTypeKind act, isUnliftedTypeKind exp = (False, Nothing, msg3)
| isLiftedTypeKind exp && not (isConstraintKind exp)
= (False, Nothing, msg4)
| Just msg <- num_args_msg = (False, Nothing, msg $$ msg1)
| KindLevel <- level, Just th <- maybe_thing = (False, Nothing, msg5 th)
| act `pickyEqType` ty1, exp `pickyEqType` ty2 = (True, Just NotSwapped, empty)
| exp `pickyEqType` ty1, act `pickyEqType` ty2 = (True, Just IsSwapped, empty)
| otherwise = (True, Nothing, msg1)
where
level = m_level `orElse` TypeLevel
occurs_check_error
| Just act_tv <- tcGetTyVar_maybe act
, act_tv `elemVarSet` tyCoVarsOfType exp
= True
| Just exp_tv <- tcGetTyVar_maybe exp
, exp_tv `elemVarSet` tyCoVarsOfType act
= True
| otherwise
= False
sort = case level of
TypeLevel -> text "type"
KindLevel -> text "kind"
msg1 = case level of
KindLevel
| Just th <- maybe_thing
-> msg5 th
_ | not (act `pickyEqType` exp)
-> vcat [ text "Expected" <+> sort <> colon <+> ppr exp
, text " Actual" <+> sort <> colon <+> ppr act
, if printExpanded then expandedTys else empty ]
| otherwise
-> empty
thing_msg = case maybe_thing of
Just thing -> \_ -> quotes (ppr thing) <+> text "is"
Nothing -> \vowel -> text "got a" <>
if vowel then char 'n' else empty
msg2 = sep [ text "Expecting a lifted type, but"
, thing_msg True, text "unlifted" ]
msg3 = sep [ text "Expecting an unlifted type, but"
, thing_msg False, text "lifted" ]
msg4 = maybe_num_args_msg $$
sep [ text "Expected a type, but"
, maybe (text "found something with kind")
(\thing -> quotes (ppr thing) <+> text "has kind")
maybe_thing
, quotes (ppr act) ]
msg5 th = hang (text "Expected" <+> kind_desc <> comma)
2 (text "but" <+> quotes (ppr th) <+> text "has kind" <+>
quotes (ppr act))
where
kind_desc | isConstraintKind exp = text "a constraint"
| otherwise = text "kind" <+> quotes (ppr exp)
num_args_msg = case level of
TypeLevel -> Nothing
KindLevel
-> let n_act = count_args act
n_exp = count_args exp in
case n_act - n_exp of
n | n /= 0
, Just thing <- maybe_thing
, case errorThingNumArgs_maybe thing of
Nothing -> n > 0
Just num_act_args -> num_act_args >= -n
-- don't report to strip off args that aren't there
-> Just $ text "Expecting" <+> speakN (abs n) <+>
more_or_fewer <+> quotes (ppr thing)
where
more_or_fewer
| n < 0 = text "fewer arguments to"
| n == 1 = text "more argument to"
| otherwise = text "more arguments to" -- n > 1
_ -> Nothing
maybe_num_args_msg = case num_args_msg of
Nothing -> empty
Just m -> m
count_args ty = count isVisibleBinder $ fst $ splitPiTys ty
expandedTys =
ppUnless (expTy1 `pickyEqType` exp && expTy2 `pickyEqType` act) $ vcat
[ text "Type synonyms expanded:"
, text "Expected type:" <+> ppr expTy1
, text " Actual type:" <+> ppr expTy2
]
(expTy1, expTy2) = expandSynonymsToMatch exp act
mkExpectedActualMsg _ _ _ _ _ = panic "mkExpectedAcutalMsg"
{-
Note [Expanding type synonyms to make types similar]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In type error messages, if -fprint-expanded-types is used, we want to expand
type synonyms to make expected and found types as similar as possible, but we
shouldn't expand types too much to make type messages even more verbose and
harder to understand. The whole point here is to make the difference in expected
and found types clearer.
`expandSynonymsToMatch` does this, it takes two types, and expands type synonyms
only as much as necessary. Given two types t1 and t2:
* If they're already same, it just returns the types.
* If they're in form `C1 t1_1 .. t1_n` and `C2 t2_1 .. t2_m` (C1 and C2 are
type constructors), it expands C1 and C2 if they're different type synonyms.
Then it recursively does the same thing on expanded types. If C1 and C2 are
same, then it applies the same procedure to arguments of C1 and arguments of
C2 to make them as similar as possible.
Most important thing here is to keep number of synonym expansions at
minimum. For example, if t1 is `T (T3, T5, Int)` and t2 is `T (T5, T3,
Bool)` where T5 = T4, T4 = T3, ..., T1 = X, it returns `T (T3, T3, Int)` and
`T (T3, T3, Bool)`.
* Otherwise types don't have same shapes and so the difference is clearly
visible. It doesn't do any expansions and show these types.
Note that we only expand top-layer type synonyms. Only when top-layer
constructors are the same we start expanding inner type synonyms.
Suppose top-layer type synonyms of t1 and t2 can expand N and M times,
respectively. If their type-synonym-expanded forms will meet at some point (i.e.
will have same shapes according to `sameShapes` function), it's possible to find
where they meet in O(N+M) top-layer type synonym expansions and O(min(N,M))
comparisons. We first collect all the top-layer expansions of t1 and t2 in two
lists, then drop the prefix of the longer list so that they have same lengths.
Then we search through both lists in parallel, and return the first pair of
types that have same shapes. Inner types of these two types with same shapes
are then expanded using the same algorithm.
In case they don't meet, we return the last pair of types in the lists, which
has top-layer type synonyms completely expanded. (in this case the inner types
are not expanded at all, as the current form already shows the type error)
-}
-- | Expand type synonyms in given types only enough to make them as similar as
-- possible. Returned types are the same in terms of used type synonyms.
--
-- To expand all synonyms, see 'Type.expandTypeSynonyms'.
--
-- See `ExpandSynsFail` tests in tests testsuite/tests/typecheck/should_fail for
-- some examples of how this should work.
expandSynonymsToMatch :: Type -> Type -> (Type, Type)
expandSynonymsToMatch ty1 ty2 = (ty1_ret, ty2_ret)
where
(ty1_ret, ty2_ret) = go ty1 ty2
-- | Returns (type synonym expanded version of first type,
-- type synonym expanded version of second type)
go :: Type -> Type -> (Type, Type)
go t1 t2
| t1 `pickyEqType` t2 =
-- Types are same, nothing to do
(t1, t2)
go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2 =
-- Type constructors are same. They may be synonyms, but we don't
-- expand further.
let (tys1', tys2') =
unzip (zipWith (\ty1 ty2 -> go ty1 ty2) tys1 tys2)
in (TyConApp tc1 tys1', TyConApp tc2 tys2')
go (AppTy t1_1 t1_2) (AppTy t2_1 t2_2) =
let (t1_1', t2_1') = go t1_1 t2_1
(t1_2', t2_2') = go t1_2 t2_2
in (mkAppTy t1_1' t1_2', mkAppTy t2_1' t2_2')
go (FunTy t1_1 t1_2) (FunTy t2_1 t2_2) =
let (t1_1', t2_1') = go t1_1 t2_1
(t1_2', t2_2') = go t1_2 t2_2
in (mkFunTy t1_1' t1_2', mkFunTy t2_1' t2_2')
go (ForAllTy b1 t1) (ForAllTy b2 t2) =
-- NOTE: We may have a bug here, but we just can't reproduce it easily.
-- See D1016 comments for details and our attempts at producing a test
-- case. Short version: We probably need RnEnv2 to really get this right.
let (t1', t2') = go t1 t2
in (ForAllTy b1 t1', ForAllTy b2 t2')
go (CastTy ty1 _) ty2 = go ty1 ty2
go ty1 (CastTy ty2 _) = go ty1 ty2
go t1 t2 =
-- See Note [Expanding type synonyms to make types similar] for how this
-- works
let
t1_exp_tys = t1 : tyExpansions t1
t2_exp_tys = t2 : tyExpansions t2
t1_exps = length t1_exp_tys
t2_exps = length t2_exp_tys
dif = abs (t1_exps - t2_exps)
in
followExpansions $
zipEqual "expandSynonymsToMatch.go"
(if t1_exps > t2_exps then drop dif t1_exp_tys else t1_exp_tys)
(if t2_exps > t1_exps then drop dif t2_exp_tys else t2_exp_tys)
-- | Expand the top layer type synonyms repeatedly, collect expansions in a
-- list. The list does not include the original type.
--
-- Example, if you have:
--
-- type T10 = T9
-- type T9 = T8
-- ...
-- type T0 = Int
--
-- `tyExpansions T10` returns [T9, T8, T7, ... Int]
--
-- This only expands the top layer, so if you have:
--
-- type M a = Maybe a
--
-- `tyExpansions (M T10)` returns [Maybe T10] (T10 is not expanded)
tyExpansions :: Type -> [Type]
tyExpansions = unfoldr (\t -> (\x -> (x, x)) `fmap` coreView t)
-- | Drop the type pairs until types in a pair look alike (i.e. the outer
-- constructors are the same).
followExpansions :: [(Type, Type)] -> (Type, Type)
followExpansions [] = pprPanic "followExpansions" empty
followExpansions [(t1, t2)]
| sameShapes t1 t2 = go t1 t2 -- expand subtrees
| otherwise = (t1, t2) -- the difference is already visible
followExpansions ((t1, t2) : tss)
-- Traverse subtrees when the outer shapes are the same
| sameShapes t1 t2 = go t1 t2
-- Otherwise follow the expansions until they look alike
| otherwise = followExpansions tss
sameShapes :: Type -> Type -> Bool
sameShapes AppTy{} AppTy{} = True
sameShapes (TyConApp tc1 _) (TyConApp tc2 _) = tc1 == tc2
sameShapes (FunTy {}) (FunTy {}) = True
sameShapes (ForAllTy {}) (ForAllTy {}) = True
sameShapes (CastTy ty1 _) ty2 = sameShapes ty1 ty2
sameShapes ty1 (CastTy ty2 _) = sameShapes ty1 ty2
sameShapes _ _ = False
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 = moduleUnitId (nameModule n1) == moduleUnitId (nameModule n2)
, n1 /= n2 -- Different Names
, same_occ -- but same OccName
= text "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) <+> text "is defined at")
2 (ppr loc)
| otherwise -- Imported things have an UnhelpfulSrcSpan
= hang (quotes (ppr nm))
2 (sep [ text "is defined in" <+> quotes (ppr (moduleName mod))
, ppUnless (same_pkg || pkg == mainUnitId) $
nest 4 $ text "in package" <+> quotes (ppr pkg) ])
where
pkg = moduleUnitId 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 deferred error of (a ~ [a]). So in the deferred unsolved constraint
'a' is now a skolem, but not one bound by the programmer in the context!
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 = map (lookup_cls_inst inst_envs) min_cts
(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))
; mkErrorMsgFromCt ctxt ct1 (important err) }
where
no_givens = null (getUserGivens ctxt)
is_no_inst (ct, (matches, unifiers, _))
= no_givens
&& null matches
&& (null unifiers || all (not . isAmbiguousTyVar) (tyCoVarsOfCtList ct))
lookup_cls_inst inst_envs ct
-- Note [Flattening in error message generation]
= (ct, lookupInstEnv True inst_envs clas (flattenTys emptyInScopeSet tys))
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 (eqType (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@(CEC {cec_encl = implics}) (ct, (matches, unifiers, unsafe_overlapped))
| null matches -- No matches but perhaps several unifiers
= do { (ctxt, binds_msg, ct) <- relevantBindings True ctxt ct
; candidate_insts <- get_candidate_instances
; return (ctxt, cannot_resolve_msg ct candidate_insts binds_msg) }
| null unsafe_overlapped -- Some matches => overlap errors
= return (ctxt, overlap_msg)
| otherwise
= return (ctxt, safe_haskell_msg)
where
orig = ctOrigin ct
pred = ctPred ct
(clas, tys) = getClassPredTys pred
ispecs = [ispec | (ispec, _) <- matches]
unsafe_ispecs = [ispec | (ispec, _) <- unsafe_overlapped]
useful_givens = discardProvCtxtGivens orig (getUserGivensFromImplics implics)
-- useful_givens are the enclosing implications with non-empty givens,
-- modulo the horrid discardProvCtxtGivens
get_candidate_instances :: TcM [ClsInst]
-- See Note [Report candidate instances]
get_candidate_instances
| [ty] <- tys -- Only try for single-parameter classes
= do { instEnvs <- tcGetInstEnvs
; return (filter (is_candidate_inst ty)
(classInstances instEnvs clas)) }
| otherwise = return []
is_candidate_inst ty inst -- See Note [Report candidate instances]
| [other_ty] <- is_tys inst
, Just (tc1, _) <- tcSplitTyConApp_maybe ty
, Just (tc2, _) <- tcSplitTyConApp_maybe other_ty
= let n1 = tyConName tc1
n2 = tyConName tc2
different_names = n1 /= n2
same_occ_names = nameOccName n1 == nameOccName n2
in different_names && same_occ_names
| otherwise = False
cannot_resolve_msg :: Ct -> [ClsInst] -> SDoc -> SDoc
cannot_resolve_msg ct candidate_insts binds_msg
= vcat [ no_inst_msg
, nest 2 extra_note
, vcat (pp_givens useful_givens)
, mb_patsyn_prov `orElse` empty
, ppWhen (has_ambig_tvs && not (null unifiers && null useful_givens))
(vcat [ ppUnless lead_with_ambig ambig_msg, binds_msg, potential_msg ])
, ppWhen (isNothing mb_patsyn_prov) $
-- Don't suggest fixes for the provided context of a pattern
-- synonym; the right fix is to bind more in the pattern
show_fixes (ctxtFixes has_ambig_tvs pred implics
++ drv_fixes)
, ppWhen (not (null candidate_insts))
(hang (text "There are instances for similar types:")
2 (vcat (map ppr candidate_insts))) ]
-- See Note [Report candidate instances]
where
orig = ctOrigin ct
-- See Note [Highlighting ambiguous type variables]
lead_with_ambig = has_ambig_tvs && not (any isRuntimeUnkSkol ambig_tvs)
&& not (null unifiers) && null useful_givens
(has_ambig_tvs, ambig_msg) = mkAmbigMsg lead_with_ambig ct
ambig_tvs = uncurry (++) (getAmbigTkvs ct)
no_inst_msg
| lead_with_ambig
= ambig_msg <+> pprArising orig
$$ text "prevents the constraint" <+> quotes (pprParendType pred)
<+> text "from being solved."
| null useful_givens
= addArising orig $ text "No instance for"
<+> pprParendType pred
| otherwise
= addArising orig $ text "Could not deduce"
<+> pprParendType pred
potential_msg
= ppWhen (not (null unifiers) && want_potential orig) $
sdocWithDynFlags $ \dflags ->
getPprStyle $ \sty ->
pprPotentials dflags sty potential_hdr unifiers
potential_hdr
= vcat [ ppWhen lead_with_ambig $
text "Probable fix: use a type annotation to specify what"
<+> pprQuotedList ambig_tvs <+> text "should be."
, text "These potential instance" <> plural unifiers
<+> text "exist:"]
mb_patsyn_prov :: Maybe SDoc
mb_patsyn_prov
| not lead_with_ambig
, ProvCtxtOrigin PSB{ psb_def = L _ pat } <- orig
= Just (vcat [ text "In other words, a successful match on the pattern"
, nest 2 $ ppr pat
, text "does not provide the constraint" <+> pprParendType pred ])
| otherwise = Nothing
-- 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
extra_note | any isFunTy (filterOutInvisibleTypes (classTyCon clas) tys)
= text "(maybe you haven't applied a function to enough arguments?)"
| className clas == typeableClassName -- Avoid mysterious "No instance for (Typeable T)
, [_,ty] <- tys -- Look for (Typeable (k->*) (T k))
, Just (tc,_) <- tcSplitTyConApp_maybe ty
, not (isTypeFamilyTyCon tc)
= hang (text "GHC can't yet do polykinded")
2 (text "Typeable" <+>
parens (ppr ty <+> dcolon <+> ppr (typeKind ty)))
| otherwise
= empty
drv_fixes = case orig of
DerivOrigin -> [drv_fix]
DerivOriginDC {} -> [drv_fix]
DerivOriginCoerce {} -> [drv_fix]
_ -> []
drv_fix = hang (text "use a standalone 'deriving instance' declaration,")
2 (text "so you can specify the instance context yourself")
-- Normal overlap error
overlap_msg
= ASSERT( not (null matches) )
vcat [ addArising orig (text "Overlapping instances for"
<+> pprType (mkClassPred clas tys))
, ppUnless (null matching_givens) $
sep [text "Matching givens (or their superclasses):"
, nest 2 (vcat matching_givens)]
, sdocWithDynFlags $ \dflags ->
getPprStyle $ \sty ->
pprPotentials dflags sty (text "Matching instances:") $
ispecs ++ 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 [ text "There exists a (perhaps superclass) match:"
, nest 2 (vcat (pp_givens useful_givens))]
, ppWhen (isSingleton matches) $
parens (vcat [ text "The choice depends on the instantiation of" <+>
quotes (pprWithCommas ppr (tyCoVarsOfTypesList tys))
, ppWhen (null (matching_givens)) $
vcat [ text "To pick the first instance above, use IncoherentInstances"
, text "when compiling the other instance declarations"]
])]
matching_givens = mapMaybe matchable useful_givens
matchable (Implic { ic_given = evvars, ic_info = skol_info, ic_env = env })
= case ev_vars_matching of
[] -> Nothing
_ -> Just $ hang (pprTheta ev_vars_matching)
2 (sep [ text "bound by" <+> ppr skol_info
, text "at" <+> ppr (tcl_loc env) ])
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 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 && not (null unsafe_ispecs) )
vcat [ addArising orig (text "Unsafe overlapping instances for"
<+> pprType (mkClassPred clas tys))
, sep [text "The matching instance is:",
nest 2 (pprInstance $ head ispecs)]
, vcat [ text "It is compiled in a Safe module and as such can only"
, text "overlap instances from the same module, however it"
, text "overlaps the following instances from different" <+>
text "modules:"
, nest 2 (vcat [pprInstances $ unsafe_ispecs])
]
]
ctxtFixes :: Bool -> PredType -> [Implication] -> [SDoc]
ctxtFixes has_ambig_tvs pred implics
| not has_ambig_tvs
, isTyVarClassPred pred
, (skol:skols) <- usefulContext implics pred
, let what | null skols
, SigSkol (PatSynCtxt {}) _ <- skol
= text "\"required\""
| otherwise
= empty
= [sep [ text "add" <+> pprParendType pred
<+> text "to the" <+> what <+> text "context of"
, nest 2 $ ppr_skol skol $$
vcat [ text "or" <+> ppr_skol skol
| skol <- skols ] ] ]
| otherwise = []
where
ppr_skol (PatSkol (RealDataCon dc) _) = text "the data constructor" <+> quotes (ppr dc)
ppr_skol (PatSkol (PatSynCon ps) _) = text "the pattern synonym" <+> quotes (ppr ps)
ppr_skol skol_info = ppr skol_info
discardProvCtxtGivens :: CtOrigin -> [UserGiven] -> [UserGiven]
discardProvCtxtGivens orig givens -- See Note [discardProvCtxtGivens]
| ProvCtxtOrigin (PSB {psb_id = L _ name}) <- orig
= filterOut (discard name) givens
| otherwise
= givens
where
discard n (Implic { ic_info = SigSkol (PatSynCtxt n') _ }) = n == n'
discard _ _ = False
usefulContext :: [Implication] -> PredType -> [SkolemInfo]
-- usefulContext picks out the implications whose context
-- the programmer might plausibly augment to solve 'pred'
usefulContext implics pred
= go implics
where
pred_tvs = tyCoVarsOfType pred
go [] = []
go (ic : ics)
| implausible ic = rest
| otherwise = ic_info ic : rest
where
-- Stop when the context binds a variable free in the predicate
rest | any (`elemVarSet` pred_tvs) (ic_skols ic) = []
| otherwise = go ics
implausible ic
| null (ic_skols ic) = True
| implausible_info (ic_info ic) = True
| otherwise = False
implausible_info (SigSkol (InfSigCtxt {}) _) = True
implausible_info _ = False
-- Do not suggest adding constraints to an *inferred* type signature
{- Note [Report candidate instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have an unsolved (Num Int), where `Int` is not the Prelude Int,
but comes from some other module, then it may be helpful to point out
that there are some similarly named instances elsewhere. So we get
something like
No instance for (Num Int) arising from the literal ‘3’
There are instances for similar types:
instance Num GHC.Types.Int -- Defined in ‘GHC.Num’
Discussion in Trac #9611.
Note [Highlighting ambiguous type variables]
~-------------------------------------------
When we encounter ambiguous type variables (i.e. type variables
that remain metavariables after type inference), we need a few more
conditions before we can reason that *ambiguity* prevents constraints
from being solved:
- We can't have any givens, as encountering a typeclass error
with given constraints just means we couldn't deduce
a solution satisfying those constraints and as such couldn't
bind the type variable to a known type.
- If we don't have any unifiers, we don't even have potential
instances from which an ambiguity could arise.
- Lastly, I don't want to mess with error reporting for
unknown runtime types so we just fall back to the old message there.
Once these conditions are satisfied, we can safely say that ambiguity prevents
the constraint from being solved.
Note [discardProvCtxtGivens]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
In most situations we call all enclosing implications "useful". There is one
exception, and that is when the constraint that causes the error is from the
"provided" context of a pattern synonym declaration:
pattern Pat :: (Num a, Eq a) => Show a => a -> Maybe a
-- required => provided => type
pattern Pat x <- (Just x, 4)
When checking the pattern RHS we must check that it does actually bind all
the claimed "provided" constraints; in this case, does the pattern (Just x, 4)
bind the (Show a) constraint. Answer: no!
But the implication we generate for this will look like
forall a. (Num a, Eq a) => [W] Show a
because when checking the pattern we must make the required
constraints available, since they are needed to match the pattern (in
this case the literal '4' needs (Num a, Eq a)).
BUT we don't want to suggest adding (Show a) to the "required" constraints
of the pattern synonym, thus:
pattern Pat :: (Num a, Eq a, Show a) => Show a => a -> Maybe a
It would then typecheck but it's silly. We want the /pattern/ to bind
the alleged "provided" constraints, Show a.
So we suppress that Implication in discardProvCtxtGivens. It's
painfully ad-hoc but the truth is that adding it to the "required"
constraints would work. Suprressing it solves two problems. First,
we never tell the user that we could not deduce a "provided"
constraint from the "required" context. Second, we never give a
possible fix that suggests to add a "provided" constraint to the
"required" context.
For example, without this distinction the above code gives a bad error
message (showing both problems):
error: Could not deduce (Show a) ... from the context: (Eq a)
... Possible fix: add (Show a) to the context of
the signature for pattern synonym `Pat' ...
-}
show_fixes :: [SDoc] -> SDoc
show_fixes [] = empty
show_fixes (f:fs) = sep [ text "Possible fix:"
, nest 2 (vcat (f : map (text "or" <+>) fs))]
pprPotentials :: DynFlags -> PprStyle -> SDoc -> [ClsInst] -> SDoc
-- See Note [Displaying potential instances]
pprPotentials dflags sty herald insts
| null insts
= empty
| null show_these
= hang herald
2 (vcat [ not_in_scope_msg empty
, flag_hint ])
| otherwise
= hang herald
2 (vcat [ pprInstances show_these
, ppWhen (n_in_scope_hidden > 0) $
text "...plus"
<+> speakNOf n_in_scope_hidden (text "other")
, not_in_scope_msg (text "...plus")
, flag_hint ])
where
n_show = 3 :: Int
show_potentials = gopt Opt_PrintPotentialInstances dflags
(in_scope, not_in_scope) = partition inst_in_scope insts
sorted = sortBy fuzzyClsInstCmp in_scope
show_these | show_potentials = sorted
| otherwise = take n_show sorted
n_in_scope_hidden = length sorted - length show_these
-- "in scope" means that all the type constructors
-- are lexically in scope; these instances are likely
-- to be more useful
inst_in_scope :: ClsInst -> Bool
inst_in_scope cls_inst = nameSetAll name_in_scope $
orphNamesOfTypes (is_tys cls_inst)
name_in_scope name
| isBuiltInSyntax name
= True -- E.g. (->)
| Just mod <- nameModule_maybe name
= qual_in_scope (qualName sty mod (nameOccName name))
| otherwise
= True
qual_in_scope :: QualifyName -> Bool
qual_in_scope NameUnqual = True
qual_in_scope (NameQual {}) = True
qual_in_scope _ = False
not_in_scope_msg herald
| null not_in_scope
= empty
| otherwise
= hang (herald <+> speakNOf (length not_in_scope) (text "instance")
<+> text "involving out-of-scope types")
2 (ppWhen show_potentials (pprInstances not_in_scope))
flag_hint = ppUnless (show_potentials || length show_these == length insts) $
text "(use -fprint-potential-instances to see them all)"
{- Note [Displaying potential instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When showing a list of instances for
- overlapping instances (show ones that match)
- no such instance (show ones that could match)
we want to give it a bit of structure. Here's the plan
* Say that an instance is "in scope" if all of the
type constructors it mentions are lexically in scope.
These are the ones most likely to be useful to the programmer.
* Show at most n_show in-scope instances,
and summarise the rest ("plus 3 others")
* Summarise the not-in-scope instances ("plus 4 not in scope")
* Add the flag -fshow-potential-instances which replaces the
summary with the full list
-}
{-
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 [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 :: Bool -- True when message has to be at beginning of sentence
-> Ct -> (Bool, SDoc)
mkAmbigMsg prepend_msg ct
| null ambig_kvs && null ambig_tvs = (False, empty)
| otherwise = (True, msg)
where
(ambig_kvs, ambig_tvs) = getAmbigTkvs ct
msg | any isRuntimeUnkSkol ambig_kvs -- See Note [Runtime skolems]
|| any isRuntimeUnkSkol ambig_tvs
= vcat [ text "Cannot resolve unknown runtime type"
<> plural ambig_tvs <+> pprQuotedList ambig_tvs
, text "Use :print or :force to determine these types"]
| not (null ambig_tvs)
= pp_ambig (text "type") ambig_tvs
| otherwise -- All ambiguous kind variabes; suggest -fprint-explicit-kinds
-- See Note [Suggest -fprint-explicit-kinds]
= vcat [ pp_ambig (text "kind") ambig_kvs
, ppSuggestExplicitKinds ]
pp_ambig what tkvs
| prepend_msg -- "Ambiguous type variable 't0'"
= text "Ambiguous" <+> what <+> text "variable"
<> plural tkvs <+> pprQuotedList tkvs
| otherwise -- "The type variable 't0' is ambiguous"
= text "The" <+> what <+> text "variable" <> plural tkvs
<+> pprQuotedList tkvs <+> is_or_are tkvs <+> text "ambiguous"
is_or_are [_] = text "is"
is_or_are _ = text "are"
pprSkol :: [Implication] -> TcTyVar -> SDoc
pprSkol implics tv
= case skol_info of
UnkSkol -> quotes (ppr tv) <+> text "is an unknown type variable"
SigSkol ctxt ty -> ppr_rigid (pprSigSkolInfo ctxt
(mkSpecForAllTys skol_tvs ty))
_ -> ppr_rigid (pprSkolInfo skol_info)
where
Implic { ic_skols = skol_tvs, ic_info = skol_info }
= getSkolemInfo implics tv
ppr_rigid pp_info
= hang (quotes (ppr tv) <+> text "is a rigid type variable bound by")
2 (sep [ pp_info
, text "at" <+> ppr (getSrcSpan tv) ])
getAmbigTkvs :: Ct -> ([Var],[Var])
getAmbigTkvs ct
= partition (`elemVarSet` dep_tkv_set) ambig_tkvs
where
tkvs = tyCoVarsOfCtList ct
ambig_tkvs = filter isAmbiguousTyVar tkvs
dep_tkv_set = tyCoVarsOfTypes (map tyVarKind tkvs)
getSkolemInfo :: [Implication] -> TcTyVar -> Implication
-- 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 = 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, Ct)
-- Also returns the zonked and tidied CtOrigin of the constraint
relevantBindings want_filtering ctxt ct
= do { dflags <- getDynFlags
; (env1, tidy_orig) <- zonkTidyOrigin (cec_tidy ctxt) (ctLocOrigin loc)
; let ct_tvs = tyCoVarsOfCt 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 tidy_orig of
KindEqOrigin t1 m_t2 _ _ -> tyCoVarsOfTypes $
t1 : maybeToList m_t2
_ -> emptyVarSet
; traceTc "relevantBindings" $
vcat [ ppr ct
, pprCtOrigin (ctLocOrigin loc)
, ppr ct_tvs
, pprWithCommas id [ ppr id <+> dcolon <+> ppr (idType id)
| TcIdBndr id _ <- tcl_bndrs lcl_env ]
, pprWithCommas id
[ ppr id | TcIdBndr_ExpType id _ _ <- tcl_bndrs lcl_env ] ]
; (tidy_env', docs, discards)
<- go env1 ct_tvs (maxRelevantBinds dflags)
emptyVarSet [] False
(tcl_bndrs lcl_env)
-- tcl_bndrs has the innermost bindings first,
-- which are probably the most relevant ones
; let doc = ppUnless (null docs) $
hang (text "Relevant bindings include")
2 (vcat docs $$ ppWhen discards discardMsg)
-- Put a zonked, tidied CtOrigin into the Ct
loc' = setCtLocOrigin loc tidy_orig
ct' = setCtLoc ct loc'
ctxt' = ctxt { cec_tidy = tidy_env' }
; return (ctxt', doc, ct') }
where
ev = ctEvidence ct
loc = ctEvLoc ev
lcl_env = ctLocEnv loc
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 -> TcTyVarSet -> 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 ct_tvs n_left tvs_seen docs discards (tc_bndr : tc_bndrs)
= case tc_bndr of
TcIdBndr id top_lvl -> go2 (idName id) (idType id) top_lvl
TcIdBndr_ExpType name et top_lvl ->
do { mb_ty <- readExpType_maybe et
-- et really should be filled in by now. But there's a chance
-- it hasn't, if, say, we're reporting a kind error en route to
-- checking a term. See test indexed-types/should_fail/T8129
; ty <- case mb_ty of
Just ty -> return ty
Nothing -> do { traceTc "Defaulting an ExpType in relevantBindings"
(ppr et)
; expTypeToType et }
; go2 name ty top_lvl }
where
go2 id_name id_type top_lvl
= do { (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env id_type
; traceTc "relevantBindings 1" (ppr id_name <+> dcolon <+> ppr tidy_ty)
; let id_tvs = tyCoVarsOfType tidy_ty
doc = sep [ pprPrefixOcc id_name <+> dcolon <+> ppr tidy_ty
, nest 2 (parens (text "bound at"
<+> ppr (getSrcLoc id_name)))]
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 ct_tvs 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 ct_tvs 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 ct_tvs n_left tvs_seen docs True tc_bndrs
-- Keep this binding, decrement fuel
else go tidy_env' ct_tvs (dec_max n_left) new_seen (doc:docs) discards tc_bndrs }
discardMsg :: SDoc
discardMsg = text "(Some bindings suppressed;" <+>
text "use -fmax-relevant-binds=N or -fno-max-relevant-binds)"
-----------------------
warnDefaulting :: [Ct] -> Type -> TcM ()
warnDefaulting wanteds default_ty
= do { warn_default <- woptM Opt_WarnTypeDefaults
; env0 <- tcInitTidyEnv
; let tidy_env = tidyFreeTyCoVars env0 $
tyCoVarsOfCtsList (listToBag wanteds)
tidy_wanteds = map (tidyCt tidy_env) wanteds
(loc, ppr_wanteds) = pprWithArising tidy_wanteds
warn_msg =
hang (hsep [ text "Defaulting the following"
, text "constraint" <> plural tidy_wanteds
, text "to type"
, quotes (ppr default_ty) ])
2
ppr_wanteds
; setCtLocM loc $ warnTc (Reason Opt_WarnTypeDefaults) 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 :: CtLoc -> TcType -> TcM a
solverDepthErrorTcS loc ty
= setCtLocM loc $
do { ty <- zonkTcType ty
; env0 <- tcInitTidyEnv
; let tidy_env = tidyFreeTyCoVars env0 (tyCoVarsOfTypeList ty)
tidy_ty = tidyType tidy_env ty
msg
= vcat [ text "Reduction stack overflow; size =" <+> ppr depth
, hang (text "When simplifying the following type:")
2 (ppr tidy_ty)
, note ]
; failWithTcM (tidy_env, msg) }
where
depth = ctLocDepth loc
note = vcat
[ text "Use -freduction-depth=0 to disable this check"
, text "(any upper bound you could choose might fail unpredictably with"
, text " minor updates to GHC, so disabling the check is recommended if"
, text " you're sure that type checking should terminate)" ]
| sgillespie/ghc | compiler/typecheck/TcErrors.hs | bsd-3-clause | 112,072 | 1 | 25 | 34,531 | 20,030 | 10,204 | 9,826 | -1 | -1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr.Imp
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
-- Foreign Function Interface (FFI) and will usually be imported via
-- the "Foreign" module.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr.Imp
(
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
, FinalizerEnvPtr
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
, withForeignPtr
, finalizeForeignPtr
-- ** Low-level operations
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, plusForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
import Foreign.Storable ( Storable(sizeOf) )
import GHC.Base
import GHC.Num
import GHC.ForeignPtr
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign pointer, and
-- associates a finalizer with the reference. The finalizer will be
-- executed after the last reference to the foreign object is dropped.
-- There is no guarantee of promptness, however the finalizer will be
-- executed before the program exits.
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
-- ^This is a way to look at the pointer living inside a
-- foreign object. This function takes a function which is
-- applied to that pointer. The resulting 'IO' action is then
-- executed. The foreign object is kept alive at least during
-- the whole action, even if it is not used directly
-- inside. Note that it is not safe to return the pointer from
-- the action and use it after the action completes. All uses
-- of the pointer should be inside the
-- 'withForeignPtr' bracket. The reason for
-- this unsafeness is the same as for
-- 'unsafeForeignPtrToPtr' below: the finalizer
-- may run earlier than expected, because the compiler can only
-- track usage of the 'ForeignPtr' object, not
-- a 'Ptr' object made from it.
--
-- This function is normally used for marshalling data to
-- or from the object pointed to by the
-- 'ForeignPtr', using the operations from the
-- 'Storable' class.
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
-- | This variant of 'newForeignPtr' adds a finalizer that expects an
-- environment in addition to the finalized pointer. The environment
-- that will be passed to the finalizer is fixed by the second argument to
-- 'newForeignPtrEnv'.
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray0',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
| rahulmutt/ghcvm | libraries/base/Foreign/ForeignPtr/Imp.hs | bsd-3-clause | 4,500 | 0 | 12 | 947 | 492 | 275 | 217 | 50 | 1 |
--
-- Lorem ipsum dolor sit. Amet perferendis metus feugiat. Suspendisse massa egestas quam.
-- Morbi vivamus dolor nisl mauris ultricies molestie lacus. Proin ad nullam id integer.
--
{-
Eget orci rutrum vel. Elit nullam amet integer. Fusce tellus ut massa. Maecenas risus dictum risus.
Augue aliquam molestie id. Commodo ultricies pede massa fusce ullamcorper dapibus dui.
Maecenas elementum duis porttitor facilisis lectus eleifend nec. Arcu et pellentesque
tellus non tristique suscipit nec. Tempor iaculis orci nec enim ac.
-}
{-# LANGUAGE QuasiQuotes #-}
import Data.String.Here
main = do
putStrLn "Sed etiam a suspendisse. \"Aliquam nulla erat risus.\""
putStrLn [here| Sed etiam a suspendisse. "Aliquam nulla erat risus." |]
| beni55/cgrep | test/test.hs | gpl-2.0 | 776 | 0 | 7 | 153 | 34 | 21 | 13 | 5 | 1 |
-- | This module declares functions and data types for
-- JAR meta-information classes, such as MANIFEST.MF etc.
module Java.META
(module Java.META.Types,
module Java.META.Parser,
module Java.META.Spec,
Manifest (..),
ManifestEntry (..))
where
import qualified Data.Map as M
import Data.Map ((!))
import Java.META.Types
import Java.META.Parser
import Java.META.Spec
-- | JAR MANIFEST.MF
data Manifest = Manifest {
manifestVersion :: String,
createdBy :: String,
sealed :: Bool,
signatureVersion :: Maybe String,
classPath :: [String],
mainClass :: Maybe String,
manifestEntries :: [ManifestEntry]}
deriving (Eq, Show)
-- | Manifest entry
data ManifestEntry = ManifestEntry {
meName :: String,
meSealed :: Bool,
meContentType :: Maybe String,
meBean :: Bool }
deriving (Eq, Show)
instance MetaSpec Manifest where
loadFirstSection s = Manifest {
manifestVersion = s ! "Manifest-Version",
createdBy = s ! "Created-By",
sealed = case M.lookup "Sealed" s of
Nothing -> False
Just str -> string2bool str,
signatureVersion = M.lookup "Signature-Version" s,
classPath = case M.lookup "Class-Path" s of
Nothing -> []
Just str -> words str,
mainClass = M.lookup "Main-Class" s,
manifestEntries = []}
loadOtherSection m s = m {manifestEntries = manifestEntries m ++ [entry]}
where
entry = ManifestEntry {
meName = s ! "Name",
meSealed = case M.lookup "Sealed" s of
Nothing -> sealed m
Just str -> string2bool str,
meContentType = M.lookup "Content-Type" s,
meBean = case M.lookup "Java-Bean" s of
Nothing -> False
Just str -> string2bool str }
storeMeta m = first: map store (manifestEntries m)
where
first = M.fromList $ [
("Manifest-Version", manifestVersion m),
("Created-By", createdBy m)] ++
lookupList "Signature-Version" (signatureVersion m) ++
lookupList "Main-Class" (mainClass m) ++
case classPath m of
[] -> []
list -> [("Class-Path", unwords list)]
store e = M.fromList $ [
("Name", meName e),
("Sealed", bool2string $ meSealed e)] ++
lookupList "Content-Type" (meContentType e) ++
if meBean e
then [("Java-Bean", "true")]
else []
| ledyba/hs-java | Java/META.hs | lgpl-3.0 | 2,523 | 0 | 13 | 788 | 695 | 387 | 308 | 65 | 0 |
module DeadModule where
deadFun1 x y
= [x,y]
| forste/haReFork | StrategyLib-4.0-beta/examples/haskell/testsuite/DeadModule.hs | bsd-3-clause | 49 | 0 | 5 | 12 | 20 | 12 | 8 | 3 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
-- |
module Stack.Types.Package where
import Control.DeepSeq
import Control.Exception hiding (try,catch)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger (MonadLogger)
import Control.Monad.Reader
import Data.Binary
import Data.Binary.VersionTagged
import qualified Data.ByteString as S
import Data.Data
import Data.Function
import Data.List
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Distribution.InstalledPackageInfo (PError)
import Distribution.ModuleName (ModuleName)
import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier)
import Distribution.PackageDescription (TestSuiteInterface)
import Distribution.System (Platform (..))
import Distribution.Text (display)
import GHC.Generics
import Path as FL
import Prelude
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.GhcPkgId
import Stack.Types.PackageName
import Stack.Types.PackageIdentifier
import Stack.Types.Version
-- | All exceptions thrown by the library.
data PackageException
= PackageInvalidCabalFile (Maybe (Path Abs File)) PError
| PackageNoCabalFileFound (Path Abs Dir)
| PackageMultipleCabalFilesFound (Path Abs Dir) [Path Abs File]
| MismatchedCabalName (Path Abs File) PackageName
deriving Typeable
instance Exception PackageException
instance Show PackageException where
show (PackageInvalidCabalFile mfile err) =
"Unable to parse cabal file" ++
(case mfile of
Nothing -> ""
Just file -> ' ' : toFilePath file) ++
": " ++
show err
show (PackageNoCabalFileFound dir) =
"No .cabal file found in directory " ++
toFilePath dir
show (PackageMultipleCabalFilesFound dir files) =
"Multiple .cabal files found in directory " ++
toFilePath dir ++
": " ++
intercalate ", " (map (toFilePath . filename) files)
show (MismatchedCabalName fp name) = concat
[ "cabal file path "
, toFilePath fp
, " does not match the package name it defines.\n"
, "Please rename the file to: "
, packageNameString name
, ".cabal\n"
, "For more information, see: https://github.com/commercialhaskell/stack/issues/317"
]
-- | Some package info.
data Package =
Package {packageName :: !PackageName -- ^ Name of the package.
,packageVersion :: !Version -- ^ Version of the package
,packageFiles :: !GetPackageFiles -- ^ Get all files of the package.
,packageDeps :: !(Map PackageName VersionRange) -- ^ Packages that the package depends on.
,packageTools :: ![Dependency] -- ^ A build tool name.
,packageAllDeps :: !(Set PackageName) -- ^ Original dependencies (not sieved).
,packageFlags :: !(Map FlagName Bool) -- ^ Flags used on package.
,packageHasLibrary :: !Bool -- ^ does the package have a buildable library stanza?
,packageTests :: !(Map Text TestSuiteInterface) -- ^ names and interfaces of test suites
,packageBenchmarks :: !(Set Text) -- ^ names of benchmarks
,packageExes :: !(Set Text) -- ^ names of executables
,packageOpts :: !GetPackageOpts -- ^ Args to pass to GHC.
,packageHasExposedModules :: !Bool -- ^ Does the package have exposed modules?
,packageSimpleType :: !Bool -- ^ Does the package of build-type: Simple
,packageDefinedFlags :: !(Set FlagName) -- ^ All flags defined in the .cabal file
}
deriving (Show,Typeable)
-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageOpts = GetPackageOpts
{ getPackageOpts :: forall env m. (MonadIO m,HasEnvConfig env, HasPlatform env, MonadThrow m, MonadReader env m, MonadLogger m, MonadCatch m)
=> SourceMap
-> InstalledMap
-> [PackageName]
-> [PackageName]
-> Path Abs File
-> m (Map NamedComponent (Set ModuleName)
,Map NamedComponent (Set DotCabalPath)
,Map NamedComponent BuildInfoOpts)
}
instance Show GetPackageOpts where
show _ = "<GetPackageOpts>"
-- | GHC options based on cabal information and ghc-options.
data BuildInfoOpts = BuildInfoOpts
{ bioOpts :: [String]
, bioOneWordOpts :: [String]
, bioPackageFlags :: [String]
-- ^ These options can safely have 'nubOrd' applied to them, as
-- there are no multi-word options (see
-- https://github.com/commercialhaskell/stack/issues/1255)
, bioCabalMacros :: Maybe (Path Abs File)
} deriving Show
-- | Files to get for a cabal package.
data CabalFileType
= AllFiles
| Modules
-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageFiles = GetPackageFiles
{ getPackageFiles :: forall m env. (MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m, MonadReader env m, HasPlatform env, HasEnvConfig env)
=> Path Abs File
-> m (Map NamedComponent (Set ModuleName)
,Map NamedComponent (Set DotCabalPath)
,Set (Path Abs File)
,[PackageWarning])
}
instance Show GetPackageFiles where
show _ = "<GetPackageFiles>"
-- | Warning generated when reading a package
data PackageWarning
= UnlistedModulesWarning (Path Abs File) (Maybe String) [ModuleName]
-- ^ Modules found that are not listed in cabal file
instance Show PackageWarning where
show (UnlistedModulesWarning cabalfp component [unlistedModule]) =
concat
[ "module not listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component (add to other-modules): "
, display unlistedModule]
show (UnlistedModulesWarning cabalfp component unlistedModules) =
concat
[ "modules not listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component (add to other-modules):\n "
, intercalate "\n " (map display unlistedModules)]
-- | Package build configuration
data PackageConfig =
PackageConfig {packageConfigEnableTests :: !Bool -- ^ Are tests enabled?
,packageConfigEnableBenchmarks :: !Bool -- ^ Are benchmarks enabled?
,packageConfigFlags :: !(Map FlagName Bool) -- ^ Package config flags.
,packageConfigCompilerVersion :: !CompilerVersion -- ^ GHC version
,packageConfigPlatform :: !Platform -- ^ host platform
}
deriving (Show,Typeable)
-- | Compares the package name.
instance Ord Package where
compare = on compare packageName
-- | Compares the package name.
instance Eq Package where
(==) = on (==) packageName
type SourceMap = Map PackageName PackageSource
-- | Where the package's source is located: local directory or package index
data PackageSource
= PSLocal LocalPackage
| PSUpstream Version InstallLocation (Map FlagName Bool)
-- ^ Upstream packages could be installed in either local or snapshot
-- databases; this is what 'InstallLocation' specifies.
deriving Show
instance PackageInstallInfo PackageSource where
piiVersion (PSLocal lp) = packageVersion $ lpPackage lp
piiVersion (PSUpstream v _ _) = v
piiLocation (PSLocal _) = Local
piiLocation (PSUpstream _ loc _) = loc
-- | Datatype which tells how which version of a package to install and where
-- to install it into
class PackageInstallInfo a where
piiVersion :: a -> Version
piiLocation :: a -> InstallLocation
-- | Information on a locally available package of source code
data LocalPackage = LocalPackage
{ lpPackage :: !Package
-- ^ The @Package@ info itself, after resolution with package flags,
-- with tests and benchmarks disabled
, lpComponents :: !(Set NamedComponent)
-- ^ Components to build, not including the library component.
, lpUnbuildable :: !(Set NamedComponent)
-- ^ Components explicitly requested for build, that are marked
-- "buildable: false".
, lpWanted :: !Bool
-- ^ Whether this package is wanted as a target.
, lpTestDeps :: !(Map PackageName VersionRange)
-- ^ Used for determining if we can use --enable-tests in a normal build.
, lpBenchDeps :: !(Map PackageName VersionRange)
-- ^ Used for determining if we can use --enable-benchmarks in a normal
-- build.
, lpTestBench :: !(Maybe Package)
-- ^ This stores the 'Package' with tests and benchmarks enabled, if
-- either is asked for by the user.
, lpDir :: !(Path Abs Dir)
-- ^ Directory of the package.
, lpCabalFile :: !(Path Abs File)
-- ^ The .cabal file
, lpDirtyFiles :: !(Maybe (Set FilePath))
-- ^ Nothing == not dirty, Just == dirty. Note that the Set may be empty if
-- we forced the build to treat packages as dirty. Also, the Set may not
-- include all modified files.
, lpNewBuildCache :: !(Map FilePath FileCacheInfo)
-- ^ current state of the files
, lpFiles :: !(Set (Path Abs File))
-- ^ all files used by this package
}
deriving Show
-- | A single, fully resolved component of a package
data NamedComponent
= CLib
| CExe !Text
| CTest !Text
| CBench !Text
deriving (Show, Eq, Ord)
renderComponent :: NamedComponent -> S.ByteString
renderComponent CLib = "lib"
renderComponent (CExe x) = "exe:" <> encodeUtf8 x
renderComponent (CTest x) = "test:" <> encodeUtf8 x
renderComponent (CBench x) = "bench:" <> encodeUtf8 x
renderPkgComponents :: [(PackageName, NamedComponent)] -> Text
renderPkgComponents = T.intercalate " " . map renderPkgComponent
renderPkgComponent :: (PackageName, NamedComponent) -> Text
renderPkgComponent (pkg, comp) = packageNameText pkg <> ":" <> decodeUtf8 (renderComponent comp)
exeComponents :: Set NamedComponent -> Set Text
exeComponents = Set.fromList . mapMaybe mExeName . Set.toList
where
mExeName (CExe name) = Just name
mExeName _ = Nothing
testComponents :: Set NamedComponent -> Set Text
testComponents = Set.fromList . mapMaybe mTestName . Set.toList
where
mTestName (CTest name) = Just name
mTestName _ = Nothing
benchComponents :: Set NamedComponent -> Set Text
benchComponents = Set.fromList . mapMaybe mBenchName . Set.toList
where
mBenchName (CBench name) = Just name
mBenchName _ = Nothing
isCLib :: NamedComponent -> Bool
isCLib CLib{} = True
isCLib _ = False
isCExe :: NamedComponent -> Bool
isCExe CExe{} = True
isCExe _ = False
isCTest :: NamedComponent -> Bool
isCTest CTest{} = True
isCTest _ = False
isCBench :: NamedComponent -> Bool
isCBench CBench{} = True
isCBench _ = False
-- | A location to install a package into, either snapshot or local
data InstallLocation = Snap | Local
deriving (Show, Eq)
instance Monoid InstallLocation where
mempty = Snap
mappend Local _ = Local
mappend _ Local = Local
mappend Snap Snap = Snap
data InstalledPackageLocation = InstalledTo InstallLocation | ExtraGlobal
deriving (Show, Eq)
data FileCacheInfo = FileCacheInfo
{ fciModTime :: !ModTime
, fciSize :: !Word64
, fciHash :: !S.ByteString
}
deriving (Generic, Show)
instance Binary FileCacheInfo
instance HasStructuralInfo FileCacheInfo
instance NFData FileCacheInfo
-- | Used for storage and comparison.
newtype ModTime = ModTime (Integer,Rational)
deriving (Ord,Show,Generic,Eq,NFData,Binary)
instance HasStructuralInfo ModTime
instance HasSemanticVersion ModTime
-- | A descriptor from a .cabal file indicating one of the following:
--
-- exposed-modules: Foo
-- other-modules: Foo
-- or
-- main-is: Foo.hs
--
data DotCabalDescriptor
= DotCabalModule !ModuleName
| DotCabalMain !FilePath
| DotCabalFile !FilePath
| DotCabalCFile !FilePath
deriving (Eq,Ord,Show)
-- | Maybe get the module name from the .cabal descriptor.
dotCabalModule :: DotCabalDescriptor -> Maybe ModuleName
dotCabalModule (DotCabalModule m) = Just m
dotCabalModule _ = Nothing
-- | Maybe get the main name from the .cabal descriptor.
dotCabalMain :: DotCabalDescriptor -> Maybe FilePath
dotCabalMain (DotCabalMain m) = Just m
dotCabalMain _ = Nothing
-- | A path resolved from the .cabal file, which is either main-is or
-- an exposed/internal/referenced module.
data DotCabalPath
= DotCabalModulePath !(Path Abs File)
| DotCabalMainPath !(Path Abs File)
| DotCabalFilePath !(Path Abs File)
| DotCabalCFilePath !(Path Abs File)
deriving (Eq,Ord,Show)
-- | Get the module path.
dotCabalModulePath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalModulePath (DotCabalModulePath fp) = Just fp
dotCabalModulePath _ = Nothing
-- | Get the main path.
dotCabalMainPath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalMainPath (DotCabalMainPath fp) = Just fp
dotCabalMainPath _ = Nothing
-- | Get the c file path.
dotCabalCFilePath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalCFilePath (DotCabalCFilePath fp) = Just fp
dotCabalCFilePath _ = Nothing
-- | Get the path.
dotCabalGetPath :: DotCabalPath -> Path Abs File
dotCabalGetPath dcp =
case dcp of
DotCabalModulePath fp -> fp
DotCabalMainPath fp -> fp
DotCabalFilePath fp -> fp
DotCabalCFilePath fp -> fp
type InstalledMap = Map PackageName (InstallLocation, Installed)
data Installed = Library PackageIdentifier GhcPkgId | Executable PackageIdentifier
deriving (Show, Eq, Ord)
-- | Get the installed Version.
installedVersion :: Installed -> Version
installedVersion (Library (PackageIdentifier _ v) _) = v
installedVersion (Executable (PackageIdentifier _ v)) = v
| harendra-kumar/stack | src/Stack/Types/Package.hs | bsd-3-clause | 15,066 | 0 | 18 | 3,934 | 3,022 | 1,648 | 1,374 | 371 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.