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 RecordWildCards, DeriveDataTypeable, TupleSections, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-cse #-}
{-# LANGUAGE OverloadedStrings #-}
-- | The application entry point
module Nauvad (main) where
import Control.Exception
import System.IO.Error
import Control.Monad.Extra
import Data.List.Extra
import Data.Maybe
import Data.Tuple.Extra
import Session
import System.Console.CmdArgs
import System.Directory.Extra
import System.Exit
import System.FilePath
import System.IO
import Language.Haskell.Ghcid.Util
import Language.Haskell.Ghcid.Types
import Wait
import Data.Functor
import Prelude
---
import Data.Monoid
import qualified Data.Aeson as A
import Data.Text (Text)
import qualified Data.Text as T
import Data.String
import Data.Time.Clock
import qualified Data.ByteString.Char8 as BS8
import Data.Typeable
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Monad.Writer
import System.Process
import Network.PortFinder (findPort)
import qualified Network.WebSockets as WS
import Network.WebSockets.Snap
import qualified Snap.Core as Snap
import Snap.Http.Server (ConfigLog(..), httpServe, setStartupHook, setPort, setAccessLog, setErrorLog)
import Snap.Util.FileServe (serveDirectory)
import Snap.Blaze (blaze)
import Nauva.Handle
import Nauva.View
import Nauva.Product.Nauva.Element.Message (messageEl, MessageProps(..), MessageSeverity(..))
import Nauva.Product.Nauva.Element.Terminal (terminalEl, TerminalProps(..))
import Settings
{-
# State Change Triggers (SCT)
- SCT-1: client opens websocket connection
- SCT-2: reading from the client websocket connection fails
- SCT-3: writing to the client websocket connection fails
- SCT-4: reading from the backend websocket connection fails
- SCT-5: writing to the backend websocket connection fails
- SCT-6: ghcid session has started the test command
- SCT-7: ghcid test command has exited
-}
--
data State = State
{ _clientConnection :: Maybe (WS.Connection, ThreadId)
-- ^ The connection between NauvaD and the client (browser). This
-- connection is usually created once and is open for the whole nauvad
-- lifetime.
, _backendConnection :: Maybe (WS.Connection, ThreadId)
-- The connection to the backend server. Is killed and re-established
-- everytime the ghcid session restarts the process.
, _backendPort :: Maybe Int
-- The port number allocated for the backend. Everytime the backend
-- is recompiled and restarted a new port is allocated so that the
-- backend can immediately bind to it.
, _sessionOutput :: [Text]
-- ^ The raw output from the current run (reload) of the GHCi session.
-- This is what we show in the client.
, _sessionMessages :: [Load]
-- ^ These are the internal messages produced by the current session.
-- If the session was not loaded successfully, these are the messages
-- which are sent to the client, nicely formatted.
}
data NauvaD = NauvaD
{ opts :: Options
-- ^ The commandline options
, stateVar :: TVar State
-- ^ The mutable state owned and managed by nauvad itself.
, session :: Session
-- ^ The underlying ghci session.
, waiter :: Waiter
-- ^ For file watching.
}
sendToClient :: TVar State -> NVDMessage -> IO ()
sendToClient stateVar msg = do
mbClientConnection <- _clientConnection <$> atomically (readTVar stateVar)
case mbClientConnection of
Nothing -> pure ()
Just (conn, _) -> (WS.sendPing conn ("ping" :: Text) >> WS.sendTextData conn (A.encode msg)) `catch`
\(_ :: IOException) -> shutdownClientConnection stateVar -- SCT-3
appendLine :: TVar State -> Text -> IO ()
appendLine stateVar line =
atomically $ modifyTVar' stateVar $ \s ->
s { _sessionOutput = _sessionOutput s <> [line] }
registerClientConnection :: TVar State -> (WS.Connection, ThreadId) -> IO ()
registerClientConnection stateVar clientConnection =
atomically $ modifyTVar' stateVar $ \s ->
s { _clientConnection = Just clientConnection }
shutdownClientConnection :: TVar State -> IO ()
shutdownClientConnection stateVar = do
mbClientConnection <- atomically $ do
state <- readTVar stateVar
modifyTVar' stateVar $ \s -> s { _clientConnection = Nothing }
pure $ _clientConnection state
case mbClientConnection of
Nothing -> pure ()
Just (_, threadId) -> killThread threadId
registerBackendConnection :: TVar State -> (WS.Connection, ThreadId) -> IO ()
registerBackendConnection stateVar backendConnection =
atomically $ modifyTVar' stateVar $ \s ->
s { _backendConnection = Just backendConnection }
shutdownBackendConnection :: TVar State -> IO ()
shutdownBackendConnection stateVar = do
mbBackendConnection <- atomically $ do
state <- readTVar stateVar
modifyTVar' stateVar $ \s -> s { _backendConnection = Nothing }
pure $ _backendConnection state
case mbBackendConnection of
Nothing -> pure ()
Just (_, threadId) -> killThread threadId
connectToBackend :: TVar State -> Int -> IO ()
connectToBackend stateVar portNumber = void $ forkIO $ go `catches`
[ Handler $ \(_ :: IOException) -> do -- SCT-4
-- Immediately retry to establish the connection to the backend.
currentBackendPort <- _backendPort <$> atomically (readTVar stateVar)
if currentBackendPort == Just portNumber
then connectToBackend stateVar portNumber
else pure ()
, Handler $ warnSomeException "connectToBackend"
]
where
go = WS.runClient "127.0.0.1" portNumber "/_nauva" $ \conn -> do
shutdownBackendConnection stateVar
threadId <- myThreadId
registerBackendConnection stateVar (conn, threadId)
forever $ do
datum <- WS.receiveData conn
case A.eitherDecode datum of
Right ("spine" :: Text, v :: A.Value, headElements :: A.Value) -> do
sendToClient stateVar $ NVDMSpineRaw v headElements
Right ("location", v, _) -> do
sendToClient stateVar $ NVDMLocationRaw v
_ -> do
putStrLn "Failed to decode message"
print datum
-- SCT-1
handleClient :: TVar State -> WS.PendingConnection -> IO ()
handleClient stateVar pendingConnection = do
conn <- WS.acceptRequest pendingConnection
WS.forkPingThread conn 5
threadId <- myThreadId
registerClientConnection stateVar (conn, threadId)
pump conn `catches`
[ Handler $ \(_ :: IOException) ->
shutdownClientConnection stateVar -- SCT-2
, Handler $ warnSomeException "handleClient/pump"
]
where
pump conn = forever $ do
d <- WS.receiveData conn
sendMessage d
sendMessage :: Text -> IO ()
sendMessage d = do
mbBackendConnection <- _backendConnection <$> atomically (readTVar stateVar)
case mbBackendConnection of
Nothing -> pure ()
Just (conn, _) -> (WS.sendPing conn ("ping" :: Text) >> WS.sendTextData conn d) `catches`
[ Handler $ \(_ :: IOException) ->
shutdownBackendConnection stateVar -- SCT-5
, Handler $ warnSomeException "handleClient/sendMessage"
]
warnSomeException :: String -> SomeException -> IO ()
warnSomeException f (SomeException e) = do
let rep = typeOf e
tyCon = typeRepTyCon rep
putStrLn $ "## " ++ f ++ " Exception: Type " ++ show rep ++ " from module " ++ tyConModule tyCon ++ " from package " ++ tyConPackage tyCon
echo :: TVar State -> Stream -> String -> IO ()
echo stateVar _ s = do
appendLine stateVar (T.pack s)
strs <- _sessionOutput <$> atomically (readTVar stateVar)
spine <- atomically $ do
(inst, _effects) <- runWriterT $ instantiate (Path []) $ div_
[style_ rootStyle]
[terminalEl TerminalProps { terminalLines = strs }]
toSpine inst
when (length strs `mod` 10 == 0) (threadDelay 100000)
sendToClient stateVar $ NVDMSpine spine
pure ()
where
rootStyle = mkStyle $ do
backgroundColor "#050f14"
position absolute
top "0"
left "0"
bottom "0"
right "0"
-- | Command line options
data Options = Options
{command :: String
,arguments :: [String]
,test :: [String]
,warnings :: Bool
,reload :: [FilePath]
,restart :: [FilePath]
,directory :: FilePath
}
deriving (Data,Typeable,Show)
options :: Mode (CmdArgs Options)
options = cmdArgsMode $ Options
{command = "" &= typ "COMMAND" &= help "Command to run (defaults to ghci or cabal repl)"
,arguments = [] &= args &= typ "MODULE"
,test = [] &= name "T" &= typ "EXPR" &= help "Command to run after successful loading"
,warnings = False &= name "W" &= help "Allow tests to run even with warnings"
,restart = [] &= typ "PATH" &= help "Restart the command when the given file or directory contents change (defaults to .ghci and any .cabal file)"
,reload = [] &= typ "PATH" &= help "Reload when the given file or directory contents change (defaults to none)"
,directory = "." &= typDir &= name "C" &= help "Set the current directory"
} &= verbosity &=
program "nauvad" &= summary ("Auto reloading GHCi daemon")
{-
What happens on various command lines:
Hlint with no .ghci file:
- cabal repl - prompt with Language.Haskell.HLint loaded
- cabal exec ghci Sample.hs - prompt with Sample.hs loaded
- ghci - prompt with nothing loaded
- ghci Sample.hs - prompt with Sample.hs loaded
- stack ghci - prompt with all libraries and Main loaded
Hlint with a .ghci file:
- cabal repl - loads everything twice, prompt with Language.Haskell.HLint loaded
- cabal exec ghci Sample.hs - loads everything first, then prompt with Sample.hs loaded
- ghci - prompt with everything
- ghci Sample.hs - loads everything first, then prompt with Sample.hs loaded
- stack ghci - loads everything first, then prompt with libraries and Main loaded
Warnings:
- cabal repl won't pull in any C files (e.g. hoogle)
- cabal exec ghci won't work with modules that import an autogen Paths module
As a result, we prefer to give users full control with a .ghci file, if available
-}
autoOptions :: Options -> IO Options
autoOptions o@Options{..}
| command /= "" = return $ f [command] []
| otherwise = do
files <- getDirectoryContents "."
-- use unsafePerformIO to get nicer pattern matching for logic (read-only operations)
let isStack dir = flip catchIOError (const $ return False) $
doesFileExist (dir </> "stack.yaml") &&^ doesDirectoryExist (dir </> ".stack-work")
stack <- isStack "." ||^ isStack ".." -- stack file might be parent, see #62
let cabal = filter ((==) ".cabal" . takeExtension) files
let opts = ["-fno-code" | null test]
return $ case () of
_ | stack ->
let flags = if null arguments then
"stack ghci --test" :
["--no-load" | ".ghci" `elem` files] ++
map ("--ghci-options=" ++) opts
else
"stack exec --test -- ghci" : opts
in f flags $ "stack.yaml":cabal
| ".ghci" `elem` files -> f ("ghci":opts) [".ghci"]
| cabal /= [] -> f (if arguments == [] then "cabal repl":map ("--ghc-options=" ++) opts else "cabal exec -- ghci":opts) cabal
| otherwise -> f ("ghci":opts) []
where
f c r = o{command = unwords $ c ++ map escape arguments, arguments = [], restart = restart ++ r}
-- in practice we're not expecting many arguments to have anything funky in them
escape x | ' ' `elem` x = "\"" ++ x ++ "\""
| otherwise = x
main :: IO ()
main = do
-- The internal state of NauvaD: WebSocket connections, backend port,
-- compiler output etc. This 'TVar' is modified by various parts
-- and threads of NauvaD.
stateVar <- newTVarIO State
{ _clientConnection = Nothing
, _backendConnection = Nothing
, _backendPort = Nothing
, _sessionOutput = []
, _sessionMessages = []
}
-- The port of the HTTP/WebSocket server, where clients will connect to.
-- We immediately create a HTTP server on that port.
serverPort <- fromIntegral <$> findPort 8000
-- Start the server in a separate thread. The 'withAsync' function
-- ensures that the server thread is killed when the application exits.
withAsync (httpServer serverPort stateVar) $ \_ -> do
putStrLn ""
putStrLn ""
putStrLn (">>> Server running on http://localhost:" <> show serverPort)
putStrLn ""
putStrLn ""
withSession $ \session -> do
-- On certain Cygwin terminals stdout defaults to BlockBuffering
hSetBuffering stdout LineBuffering
hSetBuffering stderr NoBuffering
opts <- cmdArgsRun options
withCurrentDirectory (directory opts) $ do
opts <- autoOptions opts
opts <- return $ opts{restart = nubOrd $ restart opts, reload = nubOrd $ reload opts}
withWaiterNotify $ \waiter ->
handle (\(UnexpectedExit cmd _) -> putStrLn $ "Command \"" ++ cmd ++ "\" exited unexpectedly") $
runGhcid $ NauvaD opts stateVar session waiter
httpServer :: Int -> TVar State -> IO ()
httpServer port stateVar = do
staticApp <- mkStaticSettings
httpServe config $ foldl1 (<|>)
[ Snap.path "_nauva" (runWebSocketsSnap (handleClient stateVar))
-- Static files required by nauvad itself.
, staticApp
-- public dir of the product
, serveDirectory "../../public"
-- index.html
, blaze $ index port
]
where
config =
setStartupHook startupHook .
setPort port .
setAccessLog (ConfigIoLog BS8.putStrLn) .
setErrorLog (ConfigIoLog BS8.putStrLn) $
mempty
startupHook _ = do
callProcess "open" ["http://localhost:" <> show port <> "/"]
pure ()
index :: Int -> H.Html
index port = H.docTypeHtml $ do
H.head $ do
H.script $ fromString $ "NAUVA_PORT = " <> show port
H.body $ do
H.div H.! A.id "root" $ ""
H.script H.! A.src "/nauvad.js" $ ""
runGhcid :: NauvaD -> IO ()
runGhcid nd@NauvaD{..} = do
let Options{..} = opts
-- Collect the time stamps of files which shall cause us to restart the whole
-- session (instead of merely reload it).
restartTimes <- mapM getModTime restart
fire nd restartTimes (sessionStart session (echo stateVar) command)
-- | Called when the session has finished loading (compiling). The function is given
-- a list of 'Load' messages, and a list of files (modules) that have been loaded.
fire :: NauvaD -> [Maybe UTCTime] -> IO ([Load], [FilePath]) -> IO ()
fire nd@NauvaD{..} restartTimes m = do
let Options{..} = opts
nextWait <- waitFiles waiter
-- Signal to the client that we're (re-)loading the GHCi session, do
-- the actual work, and once it's done store the output messages in
-- the state.
sendToClient stateVar NVDMLoading
atomically $ modifyTVar' stateVar $ \s -> s { _sessionMessages = [], _sessionOutput = [] }
(messages, loaded) <- m
atomically $ modifyTVar' stateVar $ \s -> s { _sessionMessages = messages }
-- Now we have three options going forward:
--
-- 1. Loading the session failed completely (eg. due to a syntax error in the cabal file).
-- 2. The session loaded some modules but there were fatal errors or warnings.
-- 3. Everything ok.
--
-- In the first two cases, we present the user with a nice error message. In the third case
-- we can start the dev server and connect to it.
let (countErrors, countWarnings) = both sum $ unzip [if loadSeverity == Error then (1,0) else (0,1) | m@Message{..} <- messages, loadMessage /= []]
let renderMessages = countErrors /= 0 || (countWarnings /= 0 && not warnings)
case (null loaded, renderMessages) of
-- CASE-1
(True, _) -> do
putStrLn "No files loaded, nothing to wait for. Fix the last error and restart."
reason <- nextWait $ restart ++ reload ++ loaded
pure ()
-- CARSE-2
(_, True) -> do
let msgs = [m | m@Message{..} <- messages, loadMessage /= []]
let children = flip map msgs $ \Message{..} ->
messageEl MessageProps
{ filePath = T.pack loadFile
, messages = map T.pack loadMessage
, severity = case loadSeverity of
Warning -> MSWarning
Error -> MSError
}
spine <- atomically $ do
(inst, _effects) <- runWriterT $ instantiate (Path []) $ div_
[style_ $ mkStyle (backgroundColor "black" >> overflow "auto" >> padding "2rem" >> position absolute >> top "0" >> left "0" >> bottom "0" >> right "0")]
children
toSpine inst
sendToClient stateVar $ NVDMSpine spine
reason <- nextWait $ restart ++ reload ++ loaded
pure ()
-- CASE-3
(_, _) -> do
sendToClient stateVar NVDMGood
-- Allocate a fresh port for the backend server.
backendPort <- fromIntegral <$> findPort 9000
atomically $ modifyTVar' stateVar $ \s -> s { _backendPort = Just backendPort }
sessionExecAsync session (intercalate "\n" test ++ " " ++ show backendPort) $ \stderr ->
hFlush stdout -- may not have been a terminating newline from test output
-- SCT-6
connectToBackend stateVar backendPort
-- The following line will suspend the application until one of the given files change.
reason <- nextWait $ restart ++ reload ++ loaded
atomically $ modifyTVar' stateVar $ \s -> s { _backendPort = Nothing }
shutdownBackendConnection stateVar
-- When we arrive here it's because one of the files we've been watching
-- has changed. Determine if we can reload the session or if we have to
-- do a full restart, and do so.
restartTimes2 <- mapM getModTime restart
if restartTimes == restartTimes2 then
fire nd restartTimes2 (sessionReload session (echo stateVar))
else
fire nd restartTimes2 (sessionStart session (echo stateVar) command)
|
wereHamster/nauva
|
pkg/hs/nauvad/src/Nauvad.hs
|
mit
| 19,299
| 0
| 30
| 5,428
| 4,332
| 2,225
| 2,107
| 309
| 6
|
module SetOrd (Set(..),emptySet,isEmpty,inSet,subSet,insertSet,
deleteSet,powerSet,takeSet,(!!!),list2set,unionSet)
where
import Data.List (sort)
{-- Sets implemented as ordered lists without duplicates --}
newtype Set a = Set [a] deriving (Eq,Ord)
instance (Show a) => Show (Set a) where
showsPrec _ (Set s) str = showSet s str
showSet [] str = showString "{}" str
showSet (x:xs) str = showChar '{' ( shows x ( showl xs str))
where showl [] str = showChar '}' str
showl (x:xs) str = showChar ',' (shows x (showl xs str))
emptySet :: Set a
emptySet = Set []
isEmpty :: Set a -> Bool
isEmpty (Set []) = True
isEmpty _ = False
inSet :: (Ord a) => a -> Set a -> Bool
inSet x (Set s) = elem x (takeWhile (<= x) s)
subSet :: (Ord a) => Set a -> Set a -> Bool
subSet (Set []) _ = True
subSet (Set (x:xs)) set = (inSet x set) && subSet (Set xs) set
insertSet :: (Ord a) => a -> Set a -> Set a
insertSet x (Set s) = Set (insertList x s)
insertList x [] = [x]
insertList x ys@(y:ys') = case compare x y of
GT -> y : insertList x ys'
EQ -> ys
_ -> x : ys
deleteSet :: Ord a => a -> Set a -> Set a
deleteSet x (Set s) = Set (deleteList x s)
deleteList x [] = []
deleteList x ys@(y:ys') = case compare x y of
GT -> y : deleteList x ys'
EQ -> ys'
_ -> ys
list2set :: Ord a => [a] -> Set a
list2set [] = Set []
list2set (x:xs) = insertSet x (list2set xs)
-- list2set xs = Set (foldr insertList [] xs)
powerSet :: Ord a => Set a -> Set (Set a)
powerSet (Set xs) =
Set (sort (map (\xs -> (list2set xs)) (powerList xs)))
powerList :: [a] -> [[a]]
powerList [] = [[]]
powerList (x:xs) = (powerList xs)
++ (map (x:) (powerList xs))
takeSet :: Eq a => Int -> Set a -> Set a
takeSet n (Set xs) = Set (take n xs)
infixl 9 !!!
(!!!) :: Eq a => Set a -> Int -> a
(Set xs) !!! n = xs !! n
unionSet :: (Ord a) => Set a -> Set a -> Set a
unionSet (Set []) set2 = set2
unionSet (Set (x:xs)) set2 =
insertSet x (unionSet (Set xs) set2)
|
stgm/prac-testing
|
week4/SetOrd.hs
|
mit
| 2,266
| 0
| 13
| 760
| 1,111
| 569
| 542
| 53
| 3
|
import qualified Test.Tasty
import Test.Tasty.Hspec
main :: IO ()
main = do
test <- testSpec "cosmos" spec
Test.Tasty.defaultMain test
spec :: Spec
spec = parallel $ do
it "is trivially true" $ do
True `shouldBe` True
|
mlitchard/cosmos
|
test-suite/TestSuite.hs
|
mit
| 239
| 0
| 11
| 57
| 82
| 42
| 40
| 10
| 1
|
{-# htermination maxFM :: Ord a => FiniteMap [a] b -> Maybe [a] #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_maxFM_4.hs
|
mit
| 85
| 0
| 3
| 16
| 5
| 3
| 2
| 1
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Rest where
import Network.HTTP.Conduit
import Control.Applicative
import Network.HTTP.Types
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy.Char8 as LC8
import Data.String (fromString)
import Data.Digest.Pure.SHA
import Data.Time.Format
import Data.Time.Clock
import System.Locale
import Data.Char
import qualified Data.Yaml as Y
import Data.Aeson
import Control.Monad (mzero)
data SortOrder = Asc | Desc
instance Show SortOrder where
show Asc = "asc"
show Desc = "desc"
data Config = Config { apiSecret :: String, apiKey :: String, clientId :: String }
instance FromJSON Config where
parseJSON (Object obj) = Config <$>
((obj .: "production") >>= (.: "apiSecret")) <*>
((obj .: "production") >>= (.: "apiKey")) <*>
((obj .: "production") >>= (.: "clientId"))
parseJSON _ = mzero
baseUrl :: String
baseUrl = "https://www.bitstamp.net/api"
post :: String -> [(C8.ByteString, C8.ByteString)] -> IO (Response LC8.ByteString)
post endpoint qParams = do
nonce <- getNonce
Just config <- getConfigData
let apiSecret' = apiSecret config
let clientId' = clientId config
let apiKey' = apiKey config
let signature = map toUpper $ showDigest $ hmacSha256 (fromString apiSecret')
(fromString $ nonce ++ clientId' ++ apiKey')
let authParams = [(fromString "key", fromString apiKey'),
(fromString "nonce", fromString nonce),
(fromString "signature", fromString signature)]
request <- parseUrl $ baseUrl ++ endpoint
withManager $ httpLbs $ urlEncodedBody (authParams ++ qParams) $ request { method = methodPost }
where
getNonce :: IO String
getNonce = getCurrentTime >>= return . formatTime defaultTimeLocale "%s"
get :: String -> [(C8.ByteString, Maybe C8.ByteString)] -> IO (Response LC8.ByteString)
get endpoint qParams = do
request <- parseUrl endpoint
withManager $ httpLbs request { method = methodGet, queryString = renderQuery True qParams }
getConfigData :: IO (Maybe Config)
getConfigData = Y.decodeFile "src/config.yml" :: IO (Maybe Config)
|
GildedHonour/BitstampApi
|
src/Rest.hs
|
mit
| 2,182
| 0
| 15
| 440
| 671
| 363
| 308
| 51
| 1
|
module Shuffle where
import System.Random
import qualified Data.List as L
randomGens :: StdGen -> Int -> [StdGen]
randomGens gen n = take n $ iterate (\gen -> fst $ split gen) gen
shuffleList :: StdGen -> [a] -> [a]
shuffleList gen list = map fst orderedPairs
where orderedPairs = L.sortBy num pairs
pairs = zip list rands
rands = take (length list) $ randoms gen :: [Int]
num (ax,anum) (bx,bnum)
| anum > bnum = GT
| anum < bnum = LT
| anum == bnum = EQ
-- See
-- http://stackoverflow.com/questions/14692059/how-to-shuffle-a-list-in-haskell
-- except that it doesn't work :-)
shuffle :: StdGen -> [a] -> [a]
shuffle g xs = shuffle' (randoms g) xs
shuffle' :: [Int] -> [a] -> [a]
shuffle' (i:is) xs = let (firsts, rest) = splitAt (i `mod` length xs) xs
in (last firsts) : shuffle' is (init firsts ++ rest)
l1 = [1..6]
l2 = [100..110]
l3 = [50..60]
l = [l1, l2, l3]
{- now do something like:
gen <- getStdGen
gens = randomGens $ length l
zipWith shuffleList gens l
-}
|
tjunier/mlgsc
|
src/Shuffle.hs
|
mit
| 1,123
| 0
| 12
| 334
| 400
| 216
| 184
| 23
| 1
|
-- | Bindings for the Slack incoming webhook API.
module Slack
( SlackMessage(..)
, SlackAttachment(..)
, SlackField(..)
) where
import Data.Aeson (toJSON)
import Data.Aeson.TH (deriveJSON)
import Data.Default (Default(..))
import Data.Text (Text)
import Network.Wreq.Types (Postable(..))
import Rules (slackOptions)
-- | A field in a message attachment.
data SlackField = SlackField
{ fieldTitle :: Text
, fieldValue :: Text
, fieldShort :: Bool
} deriving (Show, Eq)
deriveJSON slackOptions ''SlackField
-- | A Slack message attachment.
data SlackAttachment = SlackAttachment
{ attachmentFallback :: Text
, attachmentColor :: Maybe Text
, attachmentPretext :: Maybe Text
, attachmentAuthorName :: Maybe Text
, attachmentAuthorLink :: Maybe Text
, attachmentAuthorIcon :: Maybe Text
, attachmentTitle :: Text
, attachmentTitleLink :: Maybe Text
, attachmentText :: Maybe Text
, attachmentFields :: [SlackField]
, attachmentMrkdwnIn :: [Text]
} deriving (Show, Eq)
deriveJSON slackOptions ''SlackAttachment
instance Default SlackAttachment where
def = SlackAttachment
{ attachmentFallback = ""
, attachmentColor = Nothing
, attachmentPretext = Nothing
, attachmentAuthorName = Nothing
, attachmentAuthorLink = Nothing
, attachmentAuthorIcon = Nothing
, attachmentTitle = ""
, attachmentTitleLink = Nothing
, attachmentText = Nothing
, attachmentFields = []
, attachmentMrkdwnIn = []
}
-- | A Slack message.
data SlackMessage = SlackMessage
{ messageText :: Maybe Text
, messageUsername :: Maybe Text
, messageIconEmoji :: Maybe Text
, messageChannel :: Maybe Text
, messageAttachments :: [SlackAttachment]
} deriving (Show, Eq)
deriveJSON slackOptions ''SlackMessage
instance Default SlackMessage where
def = SlackMessage
{ messageText = Nothing
, messageUsername = Nothing
, messageIconEmoji = Nothing
, messageChannel = Nothing
, messageAttachments = []
}
instance Postable SlackMessage where
postPayload = postPayload . toJSON
|
fusionapp/catcher-in-the-rye
|
src/Slack.hs
|
mit
| 2,143
| 0
| 9
| 478
| 494
| 296
| 198
| -1
| -1
|
{-|
Empty image: Dark side of the moon
From: Heikki Salo / heikki.ao.salo@iki.fi
CC0 1.0
-}
import CV.Image
import CVWeb
image get = empty (500,500)
|
deggis/CV-web
|
web/demos/empty.hs
|
mit
| 153
| 0
| 6
| 29
| 27
| 15
| 12
| 3
| 1
|
{-| DCC command parsing and encoding module.
Use the 'CtcpCommand' type class to convert between 'CTCPByteString's
and typed values.
Try converting a 'CTCPByteString' to a 'DccSend' value:
> fromCtcp ctcpMessage :: Either String DccSend
Encoding a 'DccSend' value to a 'CTCPByteString':
> toCtcp (Send fileName ip port (Just fileSize))
-}
module Network.IRC.DCC (
-- * DCC command parsing and encoding
CtcpCommand(..)
-- * DCC command types
-- ** Messaging commands (DCC CHAT)
, DccChat(..)
, DccClose(..)
-- ** File Transfer commands (DCC SEND)
, DccSend(..)
, DccResume(..)
, DccAccept(..)
, acceptedPosition
, DccSendReverseClient(..)
-- *** Constructors from other commands
, resumeFromSend
-- *** Protocol variant checks
, matchesSend
-- ** Helper Types
, Path(..)
, fromPath
, PathType(..)
, FileOffset
, Token(..)
) where
import Network.IRC.DCC.Internal
-- | Try resuming a file offer
resumeFromSend :: DccSend -> FileOffset -> DccResume
resumeFromSend (Send path' _ port _) pos =
Resume path' port pos
resumeFromSend (SendReverseServer path' _ _ token') pos =
ResumeReverse path' pos token'
-- | Check if a 'DccSend' and a 'DccAccept' command are part of the same negotiation.
matchesSend :: DccAccept -> DccSend -> Bool
matchesSend (Accept pathA portA _) (Send pathS _ portS _) =
pathS == pathA && portS == portA
matchesSend (AcceptReverse pathA _ tokenA) (SendReverseServer pathS _ _ tokenS) =
pathS == pathA && tokenS == tokenA
matchesSend _ _ = False
|
JanGe/irc-dcc
|
src/Network/IRC/DCC.hs
|
mit
| 1,569
| 0
| 7
| 334
| 293
| 172
| 121
| 28
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module QMatrix (
MeasureKind(..),
QMatrix, QCMatrix,
kronecker, identity, matrix, zero, hadamard,
pauliX, pauliZ, pauliY,swap, swapSqrt, phaseShift, measure,
(<->), (<|>)
) where
import Complex
import Data.Matrix hiding (identity, matrix, zero, (<->), (<|>))
import qualified Data.Matrix
data MeasureKind = UL | BR
class (Num a, Num (m a)) => QMatrix m a where
-- |kronecker is the Kronecker product
kronecker :: m a -> m a -> m a
matrix :: Int -> Int -> (Int -> Int -> a) -> m a
(<->) :: m a -> m a -> m a
(<|>) :: m a -> m a -> m a
zero :: Int -> Int -> m a
zero r c = matrix r c $ \_ _ -> 0
identity :: Int -> m a
identity n = matrix n n $ \r c -> if r == c then 1 else 0
-- |hadamard is the matrix for the Hadamard gate
hadamard :: Floating a => m a
hadamard = matrix 2 2 hadamardMatrix where
hadamardMatrix 2 2 = -1 / sqrt 2
hadamardMatrix _ _ = 1 / sqrt 2
-- |pauliX is the Pauli X matrix (Not)
pauliX :: m a
pauliX = matrix 2 2 pauliXMatrix where
pauliXMatrix 1 2 = 1
pauliXMatrix 2 1 = 1
pauliXMatrix _ _ = 0
-- |pauliZ is the Pauli Z matrix
pauliZ :: m a
pauliZ = matrix 2 2 pauliZMatrix where
pauliZMatrix 1 1 = 1
pauliZMatrix 2 2 = -1
pauliZMatrix _ _ = 0
-- |swap is a matrix that swaps two qubits
swap :: m a
swap = matrix 4 4 swapMatrix where
swapMatrix 1 1 = 1
swapMatrix 2 3 = 1
swapMatrix 3 2 = 1
swapMatrix 4 4 = 1
swapMatrix _ _ = 0
-- |measure is the measure matrix
-- measure UL is [1, 0; 0, 0] whereas measure BR is [0, 0; 0, 1]
measure :: MeasureKind -> m a
measure k =
let
gen UL 1 1 = 1
gen BR 2 2 = 1
gen _ _ _ = 0
in
matrix 2 2 (gen k)
class (Fractional a, Floating a, QMatrix m (Complex a)) => QCMatrix m a where
-- |swapSqrt is the gate_W, the square root of the swap matrix
swapSqrt :: m (Complex a)
swapSqrt = matrix 4 4 swapSqrtMatrix where
swapSqrtMatrix 1 1 = 1
swapSqrtMatrix 2 2 = (1 + ii) / 2
swapSqrtMatrix 2 3 = (1 - ii) / 2
swapSqrtMatrix 3 2 = (1 - ii) / 2
swapSqrtMatrix 3 3 = (1 + ii) / 2
swapSqrtMatrix 4 4 = 1
swapSqrtMatrix _ _ = 0
-- |pauliY is the Pauli Y matrix
pauliY :: m (Complex a)
pauliY = matrix 2 2 pauliYMatrix where
pauliYMatrix 1 2 = -ii
pauliYMatrix 2 1 = ii
pauliYMatrix _ _ = 0
phaseShift :: a -> m (Complex a)
phaseShift phi = matrix 2 2 phaseShiftMatrix where
phaseShiftMatrix 1 1 = 1
phaseShiftMatrix 2 2 = exp $ ii * (phi :+ 0)
phaseShiftMatrix _ _ = 0
instance Num a => QMatrix Matrix a where
kronecker a b =
let
ra = nrows a
rb = nrows b
ca = ncols a
cb = ncols b
gen (r, c) = ae * be where
ae = a ! (ar, ac)
ar = 1 + (r - 1) `div` rb
ac = 1 + (c - 1) `div` cb
be = b ! (br, bc)
br = 1 + (r - 1) `mod` rb
bc = 1 + (c - 1) `mod` cb
in
Data.Matrix.matrix (ra * rb) (ca * cb) gen
identity = Data.Matrix.identity
zero = Data.Matrix.zero
matrix r c f = Data.Matrix.matrix r c (uncurry f)
(<->) = (Data.Matrix.<->)
(<|>) = (Data.Matrix.<|>)
instance (Fractional a, Floating a) => QCMatrix Matrix a where
|
miniBill/entangle
|
src/lib/QMatrix.hs
|
mit
| 3,664
| 0
| 15
| 1,339
| 1,306
| 699
| 607
| 91
| 0
|
{-
This file is part of the Haskell package thetvdb. It is subject to the
license terms in the LICENSE file found in the top-level directory of
this distribution and at git://pmade.com/thetvdb/LICENSE. No part of
themoviedb package, including this file, may be copied, modified,
propagated, or distributed except according to the terms contained in
the LICENSE file.
-}
module Network.API.TheTVDB.Types.Series (Series(..)) where
import Data.Text (Text())
import Network.API.TheTVDB.Types.API (UniqueID)
import Network.API.TheTVDB.Types.Season (Season)
data Series = Series
{ seriesID :: UniqueID
, seriesIMDB :: Text
, seriesName :: Text
, seriesOverview :: Text
, seriesPosterURL :: Maybe Text
, seasonList :: [Season]
} deriving (Eq, Show)
|
pjones/thetvdb
|
Network/API/TheTVDB/Types/Series.hs
|
mit
| 783
| 0
| 9
| 145
| 120
| 78
| 42
| 12
| 0
|
import Test.Hspec
-- Problem 20
-- Remove the K'th element from a list.
removeAt :: Int -> [a] -> (a,[a])
removeAt i (x:xs) | i > 1 = (xz,x:yz)
| otherwise = (x,xs)
where (xz,yz) = removeAt (i-1) xs
main :: IO()
main = hspec $
describe "99-exercises.20 = Remove the K'th element from a list" $
it "should remove the k'th element of a list an return a pair" $
removeAt 2 "abcd" `shouldBe` ('b',"acd")
|
baldore/haskell-99-exercises
|
20.hs
|
mit
| 438
| 0
| 9
| 114
| 161
| 87
| 74
| 10
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html
module Stratosphere.Resources.RedshiftClusterSecurityGroup where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.Tag
-- | Full data type definition for RedshiftClusterSecurityGroup. See
-- 'redshiftClusterSecurityGroup' for a more convenient constructor.
data RedshiftClusterSecurityGroup =
RedshiftClusterSecurityGroup
{ _redshiftClusterSecurityGroupDescription :: Val Text
, _redshiftClusterSecurityGroupTags :: Maybe [Tag]
} deriving (Show, Eq)
instance ToResourceProperties RedshiftClusterSecurityGroup where
toResourceProperties RedshiftClusterSecurityGroup{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::Redshift::ClusterSecurityGroup"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("Description",) . toJSON) _redshiftClusterSecurityGroupDescription
, fmap (("Tags",) . toJSON) _redshiftClusterSecurityGroupTags
]
}
-- | Constructor for 'RedshiftClusterSecurityGroup' containing required fields
-- as arguments.
redshiftClusterSecurityGroup
:: Val Text -- ^ 'rcsegDescription'
-> RedshiftClusterSecurityGroup
redshiftClusterSecurityGroup descriptionarg =
RedshiftClusterSecurityGroup
{ _redshiftClusterSecurityGroupDescription = descriptionarg
, _redshiftClusterSecurityGroupTags = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html#cfn-redshift-clustersecuritygroup-description
rcsegDescription :: Lens' RedshiftClusterSecurityGroup (Val Text)
rcsegDescription = lens _redshiftClusterSecurityGroupDescription (\s a -> s { _redshiftClusterSecurityGroupDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html#cfn-redshift-clustersecuritygroup-tags
rcsegTags :: Lens' RedshiftClusterSecurityGroup (Maybe [Tag])
rcsegTags = lens _redshiftClusterSecurityGroupTags (\s a -> s { _redshiftClusterSecurityGroupTags = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/RedshiftClusterSecurityGroup.hs
|
mit
| 2,255
| 0
| 15
| 248
| 279
| 162
| 117
| 31
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -Wall #-}
import Data.Monoid (mappend)
import Hakyll
import System.FilePath
import qualified System.Exit
import qualified System.Process as Process
import Text.Pandoc()
main :: IO ()
main = hakyll $ do
match "images/*" $ do
route idRoute
compile copyFileCompiler
match "css/*" $ do
route idRoute
compile compressCssCompiler
match (fromList ["about.rst"
, "contact.markdown"
, "cv_ru.markdown"]) $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- CV as PDF
match "cv_ru.markdown" $ version "pdf" $ do
route $ setExtension ".pdf"
compile $ do getResourceBody >>= xelatex
match "posts/*" $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" postCtx
>>= loadAndApplyTemplate "templates/default.html" postCtx
>>= relativizeUrls
create ["archive.html"] $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let archiveCtx =
listField "posts" postCtx (return posts) `mappend`
constField "title" "Заметки" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/archive.html" archiveCtx
>>= loadAndApplyTemplate "templates/default.html" archiveCtx
>>= relativizeUrls
match "index.html" $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let indexCtx =
listField "posts" postCtx (return posts) `mappend`
defaultContext
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
match "templates/*" $ compile templateBodyCompiler
postCtx :: Context String
postCtx =
dateField "date" "%B %e, %Y" `mappend`
defaultContext
xelatex :: Item String -> Compiler (Item TmpFile)
xelatex item = do
TmpFile mdPath <- newTmpFile "tmp.md"
let pdfPath = replaceExtension mdPath "pdf"
unsafeCompiler $ do
writeFile mdPath $ itemBody item
exitCode <- Process.system $ unwords ["pandoc", mdPath
, "--pdf-engine=xelatex" , "-V", "mainfont=\"Liberation Serif\""
, "-V", "geometry:left=3cm,top=2cm,bottom=2cm,right=2cm", "-o", pdfPath]
case exitCode of
System.Exit.ExitSuccess -> return ()
_ -> error "Can't convert markdown to pdf."
makeItem $ TmpFile pdfPath
|
vkorepanov/vkorepanov.github.io
|
hakyll_generator/site.hs
|
mit
| 2,960
| 0
| 21
| 975
| 643
| 301
| 342
| 73
| 2
|
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
import Data.Char (toLower)
import Data.List (sort, nub)
isPangram :: String -> Bool
isPangram = (== letters) . nub . sort . filter (`elem` letters) .map toLower
where letters = "abcdefghijklmnopqrstuvwxyz"
main :: IO ()
main = do
ip <- getContents
let result = isPangram ip
putStrLn $ if result == True then "pangram" else "not pangram"
|
cbrghostrider/Hacking
|
HackerRank/Algorithms/Strings/pangrams.hs
|
mit
| 760
| 1
| 10
| 127
| 134
| 75
| 59
| 10
| 2
|
module STG.PrettyPrint (ppStg) where
import Data.List
import Text.Printf
import STG.AST
ppStg :: Program -> String
ppStg = pp
class PrettyPrint a where
pp :: a -> String
instance PrettyPrint Program where
pp (Program bs) = unlines $ map pp bs
instance PrettyPrint Binding where
pp (Binding var lambda) = printf "%s = %s" var $ pp lambda
instance PrettyPrint Lambda where
pp (Lambda free update vars expr) = printf "{%s} \\%s {%s} -> %s" (intercalate "," free) (pp update) (intercalate "," vars) (pp expr)
instance PrettyPrint UpdateFlag where
pp U = "u"
pp N = "n"
instance PrettyPrint Expr where
pp (Let bs expr) = printf "let {%s} in %s" (intercalate "; " $ map pp bs) (pp expr)
pp (LetRec bs expr) = printf "let rec {%s} in %s" (intercalate "; " $ map pp bs) (pp expr)
pp (Case expr alts) = printf "case %s of { %s }" (pp expr) (pp alts)
pp (Ap var atoms) = printf "%s {%s}" var (intercalate "," $ map pp atoms)
pp (Constr tag atoms) = printf "Pack{%d%s}" tag (concat $ map (\a -> ", " ++ pp a) atoms)
pp (Prim prim atoms) = printf "%s {%s}" (pp prim) (intercalate "," $ map pp atoms)
pp (Literal lit) = show lit
instance PrettyPrint Prim where
pp PrimAdd = "AddInt#"
pp PrimMul = "MulInt#"
instance PrettyPrint Atom where
pp (AtomVar x) = x
pp (AtomLit x) = show x
instance PrettyPrint Alts where
pp (Algebraic aalts def) = intercalate "; " (map pp aalts) ++ "; " ++ pp def
pp (Primitive palts def) = intercalate "; " (map pp palts) ++ "; " ++ pp def
instance PrettyPrint DefAlt where
pp (DefBinding name expr) = printf "%s -> %s" name $ pp expr
pp (Default expr) = printf "DEFAULT -> %s" $ pp expr
instance PrettyPrint AAlt where
pp (AAlt tag binders expr) = printf "<%d> %s -> %s" tag (intercalate " " binders) $ pp expr
instance PrettyPrint PAlt where
pp (PAlt lit expr) = printf "%d -> %s" lit $ pp expr
|
tcsavage/lazy-compiler
|
src/STG/PrettyPrint.hs
|
mit
| 1,919
| 0
| 13
| 451
| 791
| 386
| 405
| 41
| 1
|
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses, DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances, DeriveDataTypeable #-}
module Petri.Remote where
import Petri.Type
import Petri.Step
import Petri.Roll
import Petri.Dot
import Petri.Property
import Autolib.Reader
import Autolib.ToDoc
import Autolib.Dot.Dotty ( peng )
import Data.Typeable
import Data.List ( minimumBy, maximumBy )
import Data.Ord ( comparing )
import qualified Data.Set as S
import qualified Data.Map as M
import Challenger.Partial
import Autolib.Reporter
import Autolib.Size
import Autolib.Hash
import Inter.Types
import Inter.Quiz
data Petri_Deadlock_Remote = Petri_Deadlock_Remote
deriving ( Typeable )
instance OrderScore Petri_Deadlock_Remote where
scoringOrder _ = Decreasing
$(derives [makeReader, makeToDoc] [''Petri_Deadlock_Remote])
instance ( Ord s, Ord t, Hash s, Hash t, Size t
, ToDoc s, ToDoc t , Reader s, Reader t
) =>
Measure Petri_Deadlock_Remote [ Property] ( Net s t, [ t ] ) where
measure _ props ( n, ts ) = fromIntegral $ length ts
instance Partial Petri_Deadlock_Remote [ Property ]
( Net Place Transition, [ Transition ] ) where
report _ props = do
inform $ vcat
[ text "Gesucht ist ein Petri-Netz mit den Eigenschaften"
</> toDoc props
, text "für das die kürzeste Schaltfolge zu einem Deadlock"
, text "möglichst lang ist."
, text "Eine solche Schaltfolge ist ebenfalls anzugeben."
]
initial _ props =
( fst Petri.Type.example
, S.toList $ transitions $ fst Petri.Type.example
)
partial _ props ( n, ts ) = do
validates ( Default : props ) n
inform $ text "Netz mit Startzustand:"
peng n
out <- silent $ executes n ts
inform $ vcat
[ text "Nach Ausführung von" <+> toDoc ts
, text "wird dieser Zustand erreicht:" </> toDoc out
]
peng $ n { start = out }
assert ( null $ successors n out )
$ text "dieser Zustand hat keine Nachfolger?"
total _ props ( n, ts ) = do
let infos = do
( k, ds ) <- zip [ 0 .. length ts - 1 ] $ deadlocks n
guard $ not $ null ds
return $ fsep
[ text "Weglänge:", toDoc k
, text "Anzahl toter Zustände:", toDoc ( length ds )
]
if ( null infos )
then inform $ text "Es gibt keinen kürzeren Weg zu einem Deadlock."
else reject $ text "Es gibt kürzere Wege zu Deadlocks:" </>
vcat ( take 2 infos )
make_fixed :: Make
make_fixed = direct Petri_Deadlock_Remote
[ Max_Num_Places 5
, Max_Initial_Tokens 1
, Max_Edge_Multiplicity 1
, Capacity Unbounded
]
|
Erdwolf/autotool-bonn
|
src/Petri/Remote.hs
|
gpl-2.0
| 2,987
| 0
| 18
| 966
| 754
| 392
| 362
| 72
| 1
|
-- | Save video from an attached webcam to compressed video on disk
-- while also showing it on-screen.
import HOpenCV.OpenCV
import HOpenCV.HighImage
import HOpenCV.HCxCore
import HOpenCV.HVideo
import System.Exit (exitSuccess)
main :: IO ()
main = do cam <- createCameraCaptureCV 0
writeImg <- createVideoWriterCV "foo.avi" (toFourCC "XVID") 10 (CvSize 640 480)
namedWindow "Video Test" autoSize
let kb 27 = exitSuccess
kb _ = go
go = do frame <- queryFrameCV cam
showImage "Video Test" frame
i <- writeFrameCV writeImg frame
--print i
r <- waitKey 1
case r of
(Return r') -> kb r'
(Raise s) -> go
go
releaseVideoWriter writeImg
release_capture cam
|
juanmab37/HOpenCV-0.5.0.1
|
src/examples/VideoWriter.hs
|
gpl-2.0
| 929
| 0
| 16
| 381
| 211
| 99
| 112
| 21
| 3
|
{-
This file is part of artgen.
Foobar is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Foobar is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) 2015 Chad Dettmering
Authors:
Chad Dettmering chad.dettmering@gmail.com
-}
module Chainer.HistogramMap where
import qualified Chainer.Histogram as Histogram
import qualified Data.Map.Strict as Map
-- Maps an element to its successor histogram, where a successor histogram
-- is the histogram of the element that follows the current element.
type HistogramMap a = Map.Map a (Histogram.Histogram a)
{-
- Creates an empty HistogramMap
-}
emptyHM :: HistogramMap a
emptyHM = Map.empty :: Map.Map a (Histogram.Histogram a)
{-
- Creates a HistogramMap from a list
-}
fromListHM :: Ord a => [a] -> HistogramMap a
fromListHM [] = emptyHM
fromListHM (x:[]) = emptyHM
fromListHM (x:y:z) = adjustOrInsertHM (\h -> Histogram.addH y h) x (fromListHM (y:z))
{-
- Merges 2 HistogramMaps together
-}
mergeHM :: Ord a => HistogramMap a -> HistogramMap a -> HistogramMap a
mergeHM histogram1 histogram2 = Map.unionWith (\element1 element2 -> Histogram.mergeH element1 element2) histogram1 histogram2
{-
- Inserts element into the HistogramMap if it doesn't exist, otherwise adjusts
- the value of element by applying f to it.
-}
adjustOrInsertHM :: Ord k => (Histogram.Histogram k -> Histogram.Histogram k) -> k -> HistogramMap k -> HistogramMap k
adjustOrInsertHM f element histogram = case (Map.lookup element histogram) of
Just found -> Map.adjust f element histogram
Nothing -> Map.insert element (f Histogram.emptyH) histogram
{-
- Gets the Histogram for the key, otherwise returns an empty
- Histogram if key doesn't exist.
-}
histogram :: Ord a => a -> HistogramMap a -> Histogram.Histogram a
histogram key histogram = case (Map.lookup key histogram) of
Just found -> found
Nothing -> Histogram.emptyH
|
cdettmering/artgen
|
Chainer/HistogramMap.hs
|
gpl-3.0
| 2,498
| 0
| 11
| 532
| 437
| 225
| 212
| 20
| 2
|
-- Exercise 2.5
module Ex2_5 (Tree(E, T), complete, create) where
data Tree a = E | T (Tree a) a (Tree a) deriving Show
-- Exercise 2.5 (a)
--
-- complete
-- A function that returns a binary tree of depth d, with the given element x
-- stored at every node. Since the left and right sub-trees at every node are
-- identical, they are represented by the same tree.
complete _ 0 = E
complete x d =
let subTree = complete x (d - 1)
in T subTree x subTree
-- Exercise 2.5 (b)
--
-- A function create that returns a binary tree of size n, with the given
-- element x stored at every node. The tree will be as balanced as possible;
-- at any node, the left and right sub-trees differ in size by at most 1.
-- The create function is implemented using mutual recursion with a function
-- create2, which returns a pair of trees, with the second of the trees having a
-- size one greater than the first.
-- create2 create x m
--
-- Mutually recursive helper for create. Returns two trees, of sizes m and m+1.
-- Arguments:
-- create: function that returns a single tree with a specified number of elements.
-- x: element to put at every node in created trees.
-- m: size of the smaller of the two trees that will be returned.
create2 _ x 0 = (E, T E x E)
create2 create x m =
let bigTree = create x (div (m + 1) 2)
smallTree = create x (div (m - 1) 2)
in
if mod m 2 == 0 then (T smallTree x bigTree, T bigTree x bigTree)
else (T smallTree x smallTree, T smallTree x bigTree)
create _ 0 = E
create x n =
let (smallTree, bigTree) = create2 create x (div (n - 1) 2)
in
if mod n 2 == 0 then (T smallTree x bigTree)
else (T smallTree x smallTree)
|
fishbee/pfds-haskell
|
chapter2/Ex2_5.hs
|
gpl-3.0
| 1,674
| 0
| 13
| 379
| 372
| 204
| 168
| 19
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DeregisterImage
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deregisters the specified AMI. After you deregister an AMI, it can't be used
-- to launch new instances.
--
-- This command does not delete the AMI.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeregisterImage.html>
module Network.AWS.EC2.DeregisterImage
(
-- * Request
DeregisterImage
-- ** Request constructor
, deregisterImage
-- ** Request lenses
, diDryRun
, diImageId
-- * Response
, DeregisterImageResponse
-- ** Response constructor
, deregisterImageResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DeregisterImage = DeregisterImage
{ _diDryRun :: Maybe Bool
, _diImageId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'DeregisterImage' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'diDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'diImageId' @::@ 'Text'
--
deregisterImage :: Text -- ^ 'diImageId'
-> DeregisterImage
deregisterImage p1 = DeregisterImage
{ _diImageId = p1
, _diDryRun = Nothing
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
diDryRun :: Lens' DeregisterImage (Maybe Bool)
diDryRun = lens _diDryRun (\s a -> s { _diDryRun = a })
-- | The ID of the AMI.
diImageId :: Lens' DeregisterImage Text
diImageId = lens _diImageId (\s a -> s { _diImageId = a })
data DeregisterImageResponse = DeregisterImageResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeregisterImageResponse' constructor.
deregisterImageResponse :: DeregisterImageResponse
deregisterImageResponse = DeregisterImageResponse
instance ToPath DeregisterImage where
toPath = const "/"
instance ToQuery DeregisterImage where
toQuery DeregisterImage{..} = mconcat
[ "DryRun" =? _diDryRun
, "ImageId" =? _diImageId
]
instance ToHeaders DeregisterImage
instance AWSRequest DeregisterImage where
type Sv DeregisterImage = EC2
type Rs DeregisterImage = DeregisterImageResponse
request = post "DeregisterImage"
response = nullResponse DeregisterImageResponse
|
romanb/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/DeregisterImage.hs
|
mpl-2.0
| 3,411
| 0
| 9
| 744
| 400
| 245
| 155
| 51
| 1
|
module PrimeNumbers where
primes :: [Int]
primes = sieve [2 ..]
where
sieve (p : xs) = p : sieve [ x | x <- xs, x `mod` p > 0 ]
--
getPrimes :: Int -> [Int]
getPrimes n = take n primes
|
ice1000/OI-codes
|
codewars/101-200/get-n-first-prime-numbers.hs
|
agpl-3.0
| 193
| 0
| 12
| 52
| 99
| 55
| 44
| 6
| 1
|
module SignAnalysis where
import GLuanalysis.AG.ControlFlow
import GLua.AG.Token
import GLua.Lexer
import GLua.TokenTypes
import GLua.Parser
import GLua.AG.PrettyPrint
import Data.Graph.Inductive.Graph hiding (empty)
import Data.Graph.Inductive.PatriciaTree
import Graphviz
import GLua.AG.AST
import qualified Data.Map as M
import Data.Maybe
import Data.Char
import qualified Data.List as L
import System.FilePath
import System.Environment
import System.IO
import System.Exit
import Debug.Trace
import Control.Monad
import GLua.TokenTypes
import MonotoneFramework
type SignAn = M.Map Token SignType
data SignType = I [IntType] | B [Bool] | Bottom | Top
deriving (Show,Eq)
data IntType = N | Z | P
deriving (Show,Eq,Ord)
-- | Monotone framework instance of sign analysis
signFramework :: MF SignAn
signFramework = MF {joinOp=M.unionWith signJoin,joinOpReturn=M.unionWith signJoinOver,iota=M.empty,bottom=M.empty,consistent=signConsist,transfer=signAss,transferReturn= \ a (NReturn b) c d -> synchReturn b c d ,outfun=outF}
-- | Embellished Monotone framework instance of sign analysis
mEmbellishedFramework :: MF EmbellishedSign
mEmbellishedFramework = MF {joinOp=sJoin,joinOpReturn=sJoinR,iota=sIota,bottom=sBottom,consistent=sConsistent,transfer=sTransfer,transferReturn=sTransferReturn,outfun=sOutFun}
type EmbellishedSign = M.Map [Node] SignAn
sJoin :: EmbellishedSign -> EmbellishedSign -> EmbellishedSign
sJoin = M.unionWith (M.unionWith signJoin)
sJoinR :: EmbellishedSign -> EmbellishedSign -> EmbellishedSign
sJoinR = M.unionWith (M.unionWith signJoinOver)
sIota :: EmbellishedSign
sIota = M.fromList [([],M.empty)]
sBottom :: EmbellishedSign
sBottom = M.fromList [([],M.empty)]
sConsistent :: EmbellishedSign -> EmbellishedSign -> EdgeLabel -> Bool
sConsistent x y l = all M.null $ map snd $ M.toList $ M.unionWith (\a b -> if signConsist a b l then M.empty else M.union a b) x y
sTransfer :: NodeThing -> EmbellishedSign -> EmbellishedSign
sTransfer nod r = M.map (signAss nod) r
sTransferReturn :: NodeThing -> NodeThing -> EmbellishedSign -> EmbellishedSign -> EmbellishedSign
sTransferReturn a (NReturn b) c d = M.unionWith (\e f -> synchReturn b e f) c d
sOutFun :: Node -> EmbellishedSign -> AnalysisGraph -> [AEdge]
sOutFun l' reach (gr,_) = out gr l'
-- | Join function to merge signs, this is monotone.
signJoin :: SignType -> SignType -> SignType
signJoin (I d) (I e) = I (L.union e d )
signJoin (B d) (B e) = B (L.union e d)
signJoin Top _ = Top
signJoin _ Top = Top
signJoin Bottom Bottom = Bottom
signJoin a b = a -- error ("mixing ints and bools" ++ show a ++ show b)
-- | Join function to merge signs from a return.
signJoinOver :: SignType -> SignType -> SignType
signJoinOver (I d) (I e) = I (d)
signJoinOver (B d) (B e) = B (d)
signJoinOver Top _ = Top
signJoinOver _ Top = Top
signJoinOver Bottom Bottom = Bottom
signJoinOver a b = a -- error ("mixing ints and bools" ++ show a ++ show b)
-- | Consistence function
signConsist :: SignAn -> SignAn -> EdgeLabel -> Bool
signConsist a b c = keyDiff a b
-- | Function to check differences in keys, such that (x,I [P]) and (y,I [P]) are marked as different
keyDiff :: (Ord k,Show k) => M.Map k SignType -> M.Map k SignType -> Bool
keyDiff a b = let l = M.toList a
k = map (\(x,y) -> case M.lookup x b of
(Just z) -> if containedIn z y then Nothing else Just x
Nothing -> Just x) l
m = catMaybes k
in null m
-- | Function to see if the values of associated keys are consistent
containedIn Top kek = True
containedIn kek Top = True
containedIn Bottom Bottom = False
containedIn (B a) (B b) = and $ map (\x -> elem x a) b
containedIn (I a) (I b) = and $ map (\x -> elem x a) b
containedIn a b = False
-- | Function to map a node to a sign.
signAss :: NodeThing -> SignAn -> SignAn
signAss (NStat a) b = let ass = filter (\(x,y) -> y /= Bottom) $ catMaybes $ getAss a b
in inserts ass b
where inserts ((x,y):xs) c = inserts xs (M.insert x y c)
inserts [] c = c
signAss (NReturn _) b = b
signAss (ExprCallExit _) ts = ts
signAss (ExprCallEntry _ _) ts = ts
signAss (UnknownFunction s) ts =ts
signAss (UnknownFunctionExpr s) ts =ts
signAss x _ = error $ show x
-- | Function that gets all the assignments from a statement
getAss :: MStat -> SignAn -> [Maybe (Token, SignType)]
getAss s a= case s of
(MStat p (Def v)) -> let defs = map fst v
vals = map snd v
vals' = map (\(MExpr _ e) -> calcAss e a) . catMaybes $ vals
defs' = map (\(PFVar (MToken _ g) _) -> g) defs
in map Just $ zipWith (,) defs' vals'
(MStat p (LocDef v)) -> let defs = map fst v
vals = map snd v
vals' = map (\(MExpr _ e) -> calcAss e a) . catMaybes $ vals
defs' = map (\(PFVar (MToken _ g) _) -> g) defs
in map Just $ zipWith (,) defs' vals'
_ -> [Nothing]
-- | Function that merges returned assignments and current assignments.
synchReturn (AReturn _ [MExpr _ e]) a b = let val = calcAss e b
in M.fromList $ map (\(x,c) -> (x,val)) $(M.toList a)
-- | Function that calculates the out-edges that should be visited
outF :: Node -> SignAn -> AnalysisGraph -> [AEdge]
outF l' a (gr,_) =
let nodething = fromJust $ lab gr l' :: NodeThing
outs = out gr l'
isConditional = case nodething of
(NStat (MStat _ d)) -> case d of
(AIf (MExpr _ c) _ _ _) -> Just c
(AWhile (MExpr _ c) _) -> Just c
(ARepeat _ (MExpr _ c) ) -> Just c
_ -> Nothing
_ -> Nothing
in case isConditional of
Nothing ->outs
Just c -> case calcAss c a of
(B [True]) -> filter (\(x,y,z) -> filterEdges z True ) outs
(B [False]) -> filter (\(x,y,z) -> filterEdges z False ) outs
Top -> outs
(B [True,False]) -> outs
_ -> [] -- outs
-- | Function that considers edges associated with functions.
filterEdges (Intra g ) f = g == f
filterEdges (Inter _) f = f
filterEdges (ExprInter g ) f = f
-- | Function which calculates the sign of an expression.
calcAss :: Expr -> SignAn -> SignType
calcAss e s =
case e of
ANil -> Bottom
AFalse -> B [False]
ATrue -> B [True]
ANumber n -> if (read n :: Int) > 0 then I [P] else if (read n :: Int) == 0 then I [Z] else I [N]
AString (MToken _ st) -> Bottom -- fromJust $ M.lookup st s
AVarArg -> Bottom
AnonymousFunc p b -> Bottom
APrefixExpr (PFVar (MToken _ g) _) -> case M.lookup g s of
(Just a) -> a
Nothing -> Top -- error ("Lookup of " ++ show g ++ " failed, env: " ++ show s)
ATableConstructor fs -> Bottom
BinOpExpr op (MExpr _ l) (MExpr _ r) ->
if (calcAss l s == Top || calcAss r s == Top) then Top else
case op of
APlus -> let first = case (calcAss l s) of
(I f) -> f
_ -> []
second = case (calcAss r s) of
(I f) -> f
_ -> []
in
if elem N first || elem N second
then if elem P first || elem P second
then I [N,Z,P]
else I [N]
else if elem Z first || elem Z second
then if elem P first || elem P second
then I [P]
else I [Z]
else I [P]
BinMinus -> let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if elem N first || elem N second
then if elem P first || elem P second
then I [N,Z,P]
else I [N,Z]
else if elem Z first || elem Z second
then if elem P first || elem P second
then I [P,N,Z]
else I [Z]
else I [P,N,Z]
AMultiply ->
let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if elem N first || elem N second
then if elem P first || elem P second
then if first == [Z] || second == [Z]
then I [Z]
else if elem Z first || elem Z second
then I [N,Z]
else I [N]
else I [N]
else if elem Z first || elem Z second
then if elem P first || elem P second
then if first == [Z] || second == [Z]
then I [Z]
else if elem Z first || elem Z second
then I [P,Z]
else I [P]
else I [Z]
else I [Z]
ADivide ->
let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if first == [Z] then I [Z] else
if elem N first || elem N second
then if elem Z first || elem Z second
then if elem P first || elem P second
then I [P,Z,N]
else I [N]
else I [P]
else if elem Z first || elem Z second
then if elem P first || elem P second
then I [Z,P]
else I [Z]
else I [P]
AModulus ->
let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if first == [Z] then I [Z] else I second
APower ->
let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if elem N first || elem N second
then if elem Z first || elem Z second
then I [N,P,Z]
else I [P,N]
else if elem Z first || elem Z second
then I [P,Z]
else I [P]
AConcatenate -> Bottom
ALT -> let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if (first == [N] && not (elem Z second) )||( first == [Z] && second == [P] )then B [True] else B [True,False]
ALEQ -> let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if (first == [N]) || (elem Z first && (not $ elem N second) && not (elem P first)) || ( elem P first && elem P second) then B [True] else B [True,False]
AGT -> let first = case (calcAss l s) of
(I f) -> f
_ -> []
second = case (calcAss r s) of
(I f) -> f
_ -> []
in
if first == [] || second == [] then Bottom else
if null [x | x <- first, y <- second, x >= y]
then B [False]
else if null [x | x <- first, y <- second, x <= y]
then B [True]
else B [True,False]
AGEQ -> let (I first) = (calcAss l s)
(I second) = (calcAss r s)
in if (first == [P]) || (elem Z first && not (elem P second) && not( elem N first)) || ( elem N first && elem N second) then B [True] else B [True,False]
AEq -> let first = (calcAss l s)
second = (calcAss r s)
in case first of
(I _) -> signJoin first second
(B f) -> case second of
(B g) -> if f == [True] && g == [True] || f ==[False] && g == [False] then B [True] else B[True,False]
_ -> Bottom
ANEq -> let first = (calcAss l s)
second = (calcAss r s)
in case first of
(I _) -> signJoin first second
(B f) -> case second of
(B g) -> if f == [True] && g == [True] || f ==[False] && g == [False] then B [False] else B[True,False] -- not totally accurate
_ -> Bottom
AAnd -> let first = (calcAss l s)
second = (calcAss r s)
in case first of
(I _) -> Bottom
(B f) -> case second of
(B g) -> if not (elem False f ) && not (elem False g) then B [True] else if f ==[False] && g ==[False] then B[False] else B[True,False]
_ -> Bottom
AOr -> let first = (calcAss l s)
second = (calcAss r s)
in case first of
(I _) -> Bottom
(B f) -> case second of
(B g) -> if f == [True] || g == [True] then B [True] else if not (elem True f) || not (elem True g) then B[False] else B[True,False]
_ -> Bottom
UnOpExpr op (MExpr _ r) -> if (calcAss r s == Top) then Top else
case op of
UnMinus -> let (I f) = calcAss r s
in I (map unSignI f)
ANot -> let (B f) = calcAss r s
in B $ map not f
AHash -> Bottom
_ -> error "ayy"
-- | Function that flips the sign of an IntType, used in negation.
unSignI :: IntType -> IntType
unSignI Z = Z
unSignI N = P
unSignI P = N
|
FPtje/LuaAnalysis
|
analysis/src/SignAnalysis.hs
|
lgpl-2.1
| 18,643
| 9
| 24
| 10,267
| 5,108
| 2,673
| 2,435
| 280
| 83
|
module Madness where
import Data.Monoid
type Verb = String
type Adjective = String
type Adverb = String
type Noun = String
type Exclamation = String
madlibbin' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbin' e adv noun adj =
e <> "! he said " <>
adv <> " as he jumped into his car " <>
noun <> " and drove off with his " <>
adj <> " wife."
madlibbinBetter' :: Exclamation
-> Adverb
-> Noun
-> Adjective
-> String
madlibbinBetter' e adv noun adj = mconcat
[ e, "! he said ", adv, " as he jummped into his car ", noun, " and drove off with his ", adj, " wife."]
|
dmp1ce/Haskell-Programming-Exercises
|
Chapter 15/Madness.hs
|
unlicense
| 705
| 0
| 11
| 244
| 164
| 93
| 71
| 24
| 1
|
module EKG.A256417 (a256417) where
import EKG.A064413 (a064413)
import Helpers.Primes (isPrime)
a256417 :: Int -> Integer
a256417 n
| isPrime $ a064413 n = a064413 n * 2
| thricePrime $ a064413 n = a064413 n * 2 `div` 3
| otherwise = a064413 n where
thricePrime k = k `mod` 3 == 0 && isPrime (k `div` 3)
|
peterokagey/haskellOEIS
|
src/EKG/A256417.hs
|
apache-2.0
| 333
| 0
| 10
| 87
| 145
| 75
| 70
| 9
| 1
|
{-
Copyright 2016, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
module Camfort.Specification.Stencils.Synthesis
( formatSpec
, formatSpecNoComment
, offsetToIx
) where
import Data.List
import Camfort.Specification.Stencils.Syntax
import Camfort.Analysis.Annotations
import qualified Language.Fortran.AST as F
import qualified Language.Fortran.Analysis as FA
import qualified Language.Fortran.Util.Position as FU
import Language.Fortran.Util.Position
-- Format inferred specifications
formatSpec :: F.MetaInfo -> Int -> Char
-> (FU.SrcSpan, Either [([Variable], Specification)] (String,Variable))
-> String
formatSpec mi indent marker (span, Right (evalInfo, name)) = buildCommentText mi indent $
marker : " "
++ evalInfo
++ (if name /= "" then " :: " ++ name else "") ++ "\n"
formatSpec _ _ _ (_, Left []) = ""
formatSpec mi indent marker (span, Left specs) =
(intercalate "\n" $ map (\s -> buildCommentText mi indent (marker : " " ++ doSpec s)) specs)
where
commaSep = intercalate ", "
doSpec (arrayVar, spec) =
show (fixSpec spec) ++ " :: " ++ commaSep arrayVar
fixSpec s = s
-- | Format inferred specifications, but do not format as a comment.
formatSpecNoComment ::
(FU.SrcSpan, Either [([Variable], Specification)] (String,Variable))
-> String
formatSpecNoComment (span, Right (evalInfo, name)) =
show span ++ " " ++ evalInfo ++ (if name /= "" then " :: " ++ name else "") ++ "\n"
formatSpecNoComment (_, Left []) = ""
formatSpecNoComment (span, Left specs) =
intercalate "\n" . map (\s -> show span ++ " " ++ doSpec s) $ specs
where
commaSep = intercalate ", "
doSpec (arrayVar, spec) =
show (fixSpec spec) ++ " :: " ++ commaSep arrayVar
fixSpec s = s
------------------------
a = (head $ FA.initAnalysis [unitAnnotation]) { FA.insLabel = Just 0 }
s = SrcSpan (Position 0 0 0) (Position 0 0 0)
-- Make indexing expression for variable 'v' from an offset.
-- essentially inverse to `ixToOffset` in StencilSpecification
offsetToIx :: F.Name -> Int -> F.Index (FA.Analysis A)
offsetToIx v o
| o == absoluteRep
= F.IxSingle a s Nothing (F.ExpValue a s (F.ValInteger "0"))
| o == 0 = F.IxSingle a s Nothing (F.ExpValue a s (F.ValVariable v))
| o > 0 = F.IxSingle a s Nothing (F.ExpBinary a s F.Addition
(F.ExpValue a s (F.ValVariable v))
(F.ExpValue a s (F.ValInteger $ show o)))
| otherwise = F.IxSingle a s Nothing (F.ExpBinary a s F.Subtraction
(F.ExpValue a s (F.ValVariable v))
(F.ExpValue a s (F.ValInteger $ show (abs o))))
|
mrd/camfort
|
src/Camfort/Specification/Stencils/Synthesis.hs
|
apache-2.0
| 3,411
| 0
| 15
| 853
| 936
| 499
| 437
| 52
| 2
|
-- Copyright (c) 2013-2015 PivotCloud, Inc.
--
-- Aws.Kinesis.Commands.PutRecord
--
-- Please feel free to contact us at licensing@pivotmail.com with any
-- contributions, additions, or other feedback; we would love to hear from
-- you.
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may
-- not use this file except in compliance with the License. You may obtain a
-- copy of the License at http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations
-- under the License.
-- |
-- Module: Aws.Kinesis.Commands.PutRecord
-- Copyright: Copyright (c) 2013-2015 PivotCloud, Inc.
-- license: Apache License, Version 2.0
-- Maintainer: Lars Kuhtz <lars@alephcloud.com>
-- Stability: experimental
--
-- /API Version: 2013-12-02/
--
-- This operation puts a data record into an Amazon Kinesis stream from a
-- producer. This operation must be called to send data from the producer into
-- the Amazon Kinesis stream for real-time ingestion and subsequent processing.
-- The PutRecord operation requires the name of the stream that captures,
-- stores, and transports the data; a partition key; and the data blob itself.
-- The data blob could be a segment from a log file, geographic/location data,
-- website clickstream data, or any other data type.
--
-- The partition key is used to distribute data across shards. Amazon Kinesis
-- segregates the data records that belong to a data stream into multiple
-- shards, using the partition key associated with each data record to
-- determine which shard a given data record belongs to.
--
-- Partition keys are Unicode strings, with a maximum length limit of 256
-- bytes. An MD5 hash function is used to map partition keys to 128-bit integer
-- values and to map associated data records to shards using the hash key
-- ranges of the shards. You can override hashing the partition key to
-- determine the shard by explicitly specifying a hash value using the
-- ExplicitHashKey parameter. For more information, see the Amazon Kinesis
-- Developer Guide.
--
-- PutRecord returns the shard ID of where the data record was placed and the
-- sequence number that was assigned to the data record.
--
-- Sequence numbers generally increase over time. To guarantee strictly
-- increasing ordering, use the SequenceNumberForOrdering parameter. For more
-- information, see the Amazon Kinesis Developer Guide.
--
-- If a PutRecord request cannot be processed because of insufficient
-- provisioned throughput on the shard involved in the request, PutRecord
-- throws ProvisionedThroughputExceededException.
--
-- Data records are accessible for only 24 hours from the time that they are
-- added to an Amazon Kinesis stream.
--
-- <http://docs.aws.amazon.com/kinesis/2013-12-02/APIReference/API_PutRecord.html>
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Aws.Kinesis.Commands.PutRecord
( PutRecord(..)
, PutRecordResponse(..)
, PutRecordExceptions(..)
) where
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 1
#endif
import Aws.Core
import Aws.Kinesis.Types
import Aws.Kinesis.Core
#if ! MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.DeepSeq
import Data.Aeson
import Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Base64 as B64
import qualified Data.Text.Encoding as T
import Data.Typeable
import GHC.Generics
putRecordAction :: KinesisAction
putRecordAction = KinesisPutRecord
data PutRecord = PutRecord
{ putRecordData :: !B.ByteString
-- ^ The data blob to put into the record. The maximum size of the data
-- blob is 50 kilobytes (KB)
, putRecordExplicitHashKey :: !(Maybe PartitionHash)
-- ^ The hash value used to explicitly determine the shard the data record
-- is assigned to by overriding the partition key hash.
--
-- FIXME the specification is rather vague about the precise encoding
-- of this value. The default is to compute it as an MD5 hash of
-- the partition key. The API reference describes it as an Int128.
-- However, it is not clear how the result of the hash function is
-- encoded (big-endian or small endian, word size?) and how it is
-- serialized to text, which is the type in the JSON serialization.
, putRecordPartitionKey :: !PartitionKey
-- ^ Determines which shard in the stream the data record is assigned to.
, putRecordSequenceNumberForOrdering :: !(Maybe SequenceNumber)
-- ^ Guarantees strictly increasing sequence numbers, for puts from the
-- same client and to the same partition key. Usage: set the
-- SequenceNumberForOrdering of record n to the sequence number of record
-- n-1 (as returned in the PutRecordResult when putting record n-1). If
-- this parameter is not set, records will be coarsely ordered based on
-- arrival time.
, putRecordStreamName :: !StreamName
-- ^ The name of the stream to put the data record into.
}
deriving (Show, Read, Eq, Ord, Typeable, Generic)
instance NFData PutRecord
instance ToJSON PutRecord where
toJSON PutRecord{..} = object
[ "Data" .= T.decodeUtf8 (B64.encode putRecordData)
, "ExplicitHashKey" .= putRecordExplicitHashKey
, "PartitionKey" .= putRecordPartitionKey
, "SequenceNumberForOrdering" .= putRecordSequenceNumberForOrdering
, "StreamName" .= putRecordStreamName
]
data PutRecordResponse = PutRecordResponse
{ putRecordResSequenceNumber :: !SequenceNumber
-- ^ The sequence number identifier that was assigned to the put data
-- record. The sequence number for the record is unique across all records
-- in the stream. A sequence number is the identifier associated with every
-- record put into the stream.
, putRecordResShardId :: !ShardId
-- ^ The shard ID of the shard where the data record was placed.
}
deriving (Show, Read, Eq, Ord, Typeable, Generic)
instance NFData PutRecordResponse
instance FromJSON PutRecordResponse where
parseJSON = withObject "PutRecordResponse" $ \o -> PutRecordResponse
<$> o .: "SequenceNumber"
<*> o .: "ShardId"
instance ResponseConsumer r PutRecordResponse where
type ResponseMetadata PutRecordResponse = KinesisMetadata
responseConsumer _ = kinesisResponseConsumer
instance SignQuery PutRecord where
type ServiceConfiguration PutRecord = KinesisConfiguration
signQuery cmd = kinesisSignQuery KinesisQuery
{ kinesisQueryAction = putRecordAction
, kinesisQueryBody = Just $ LB.toStrict $ encode cmd
}
instance Transaction PutRecord PutRecordResponse
instance AsMemoryResponse PutRecordResponse where
type MemoryResponse PutRecordResponse = PutRecordResponse
loadToMemory = return
-- -------------------------------------------------------------------------- --
-- Exceptions
--
-- Currently not used for requests. It's included for future usage
-- and as reference.
data PutRecordExceptions
= PutRecordInvalidArgumentException
-- ^ /Code 400/
| PutRecordProvisionedThroughputExceededException
-- ^ /Code 400/
| PutRecordResourceNotFoundException
-- ^ /Code 400/
deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable, Generic)
instance NFData PutRecordExceptions
|
alephcloud/hs-aws-kinesis
|
src/Aws/Kinesis/Commands/PutRecord.hs
|
apache-2.0
| 7,767
| 0
| 12
| 1,384
| 655
| 413
| 242
| 81
| 1
|
{-| Implementation of the Ganeti Query2 common objects.
-}
{-
Copyright (C) 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Query.Common
( NoDataRuntime(..)
, rsNoData
, rsUnavail
, rsNormal
, rsMaybeNoData
, rsMaybeUnavail
, rsErrorNoData
, rsErrorMaybeUnavail
, rsUnknown
, missingRuntime
, rpcErrorToStatus
, timeStampFields
, uuidFields
, serialFields
, tagsFields
, dictFieldGetter
, buildNdParamField
, buildBeParamField
, buildHvParamField
, getDefaultHypervisorSpec
, getHvParamsFromCluster
, aliasFields
) where
import Control.Monad (guard)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Text.JSON (JSON, showJSON)
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.Config
import Ganeti.Errors
import Ganeti.JSON
import Ganeti.Objects
import Ganeti.Rpc
import Ganeti.Query.Language
import Ganeti.Query.Types
import Ganeti.Types
-- | The runtime used by queries which retrieve no live data.
data NoDataRuntime = NoDataRuntime
-- * Generic functions
-- | Conversion from 'VType' to 'FieldType'.
vTypeToQFT :: VType -> FieldType
vTypeToQFT VTypeString = QFTOther
vTypeToQFT VTypeMaybeString = QFTOther
vTypeToQFT VTypeBool = QFTBool
vTypeToQFT VTypeSize = QFTUnit
vTypeToQFT VTypeInt = QFTNumber
vTypeToQFT VTypeFloat = QFTNumberFloat
-- * Result helpers
-- | Helper for a result with no data.
rsNoData :: ResultEntry
rsNoData = ResultEntry RSNoData Nothing
-- | Helper for result for an entity which supports no such field.
rsUnavail :: ResultEntry
rsUnavail = ResultEntry RSUnavail Nothing
-- | Helper to declare a normal result.
rsNormal :: (JSON a) => a -> ResultEntry
rsNormal a = ResultEntry RSNormal $ Just (showJSON a)
-- | Helper to declare a result from a 'Maybe' (the item might be
-- missing, in which case we return no data). Note that there's some
-- ambiguity here: in some cases, we mean 'RSNoData', but in other
-- 'RSUnavail'; this is easy to solve in simple cases, but not in
-- nested dicts. If you want to return 'RSUnavail' in case of 'Nothing'
-- use the function 'rsMaybeUnavail'.
rsMaybeNoData :: (JSON a) => Maybe a -> ResultEntry
rsMaybeNoData = maybe rsNoData rsNormal
-- | Helper to declare a result from a 'ErrorResult' (an error happened
-- while retrieving the data from a config, or there was no data).
-- This function should be used if an error signals there was no data.
rsErrorNoData :: (JSON a) => ErrorResult a -> ResultEntry
rsErrorNoData res = case res of
Ok x -> rsNormal x
Bad _ -> rsNoData
-- | Helper to declare a result from a 'Maybe'. This version returns
-- a 'RSUnavail' in case of 'Nothing'. It should be used for optional
-- fields that are not set. For cases where 'Nothing' means that there
-- was an error, consider using 'rsMaybe' instead.
rsMaybeUnavail :: (JSON a) => Maybe a -> ResultEntry
rsMaybeUnavail = maybe rsUnavail rsNormal
-- | Helper to declare a result from 'ErrorResult Maybe'. This version
-- should be used if an error signals there was no data and at the same
-- time when we have optional fields that may not be setted (i.e. we
-- want to return a 'RSUnavail' in case of 'Nothing').
rsErrorMaybeUnavail :: (JSON a) => ErrorResult (Maybe a) -> ResultEntry
rsErrorMaybeUnavail res =
case res of
Ok x -> rsMaybeUnavail x
Bad _ -> rsNoData
-- | Helper for unknown field result.
rsUnknown :: ResultEntry
rsUnknown = ResultEntry RSUnknown Nothing
-- | Helper for a missing runtime parameter.
missingRuntime :: FieldGetter a b
missingRuntime = FieldRuntime (\_ _ -> ResultEntry RSNoData Nothing)
-- * Error conversion
-- | Convert RpcError to ResultStatus
rpcErrorToStatus :: RpcError -> ResultStatus
rpcErrorToStatus OfflineNodeError = RSOffline
rpcErrorToStatus _ = RSNoData
-- * Common fields
-- | The list of timestamp fields.
timeStampFields :: (TimeStampObject a) => FieldList a b
timeStampFields =
[ (FieldDefinition "ctime" "CTime" QFTTimestamp "Creation timestamp",
FieldSimple (rsNormal . TimeAsDoubleJSON . cTimeOf), QffNormal)
, (FieldDefinition "mtime" "MTime" QFTTimestamp "Modification timestamp",
FieldSimple (rsNormal . TimeAsDoubleJSON . mTimeOf), QffNormal)
]
-- | The list of UUID fields.
uuidFields :: (UuidObject a) => String -> FieldList a b
uuidFields name =
[ (FieldDefinition "uuid" "UUID" QFTText (name ++ " UUID"),
FieldSimple (rsNormal . uuidOf), QffNormal) ]
-- | The list of serial number fields.
serialFields :: (SerialNoObject a) => String -> FieldList a b
serialFields name =
[ (FieldDefinition "serial_no" "SerialNo" QFTNumber
(name ++ " object serial number, incremented on each modification"),
FieldSimple (rsNormal . serialOf), QffNormal) ]
-- | The list of tag fields.
tagsFields :: (TagsObject a) => FieldList a b
tagsFields =
[ (FieldDefinition "tags" "Tags" QFTOther "Tags",
FieldSimple (rsNormal . tagsOf), QffNormal) ]
-- * Generic parameter functions
-- | Returns a field from a (possibly missing) 'DictObject'. This is
-- used by parameter dictionaries, usually. Note that we have two
-- levels of maybe: the top level dict might be missing, or one key in
-- the dictionary might be.
dictFieldGetter :: (DictObject a) => String -> Maybe a -> ResultEntry
dictFieldGetter k = maybe rsNoData (rsMaybeNoData . lookup k . toDict)
-- | Ndparams optimised lookup map.
ndParamTypes :: Map.Map String FieldType
ndParamTypes = Map.map vTypeToQFT C.ndsParameterTypes
-- | Ndparams title map.
ndParamTitles :: Map.Map String FieldTitle
ndParamTitles = C.ndsParameterTitles
-- | Ndparam getter builder: given a field, it returns a FieldConfig
-- getter, that is a function that takes the config and the object and
-- returns the Ndparam field specified when the getter was built.
ndParamGetter :: (NdParamObject a) =>
String -- ^ The field we're building the getter for
-> ConfigData -> a -> ResultEntry
ndParamGetter field config =
dictFieldGetter field . getNdParamsOf config
-- | Builds the ndparam fields for an object.
buildNdParamField :: (NdParamObject a) => String -> FieldData a b
buildNdParamField =
buildParamField "ndp" "node" ndParamTitles ndParamTypes ndParamGetter
-- | Beparams optimised lookup map.
beParamTypes :: Map.Map String FieldType
beParamTypes = Map.map vTypeToQFT C.besParameterTypes
-- | Builds the beparam fields for an object.
buildBeParamField :: (String -> ConfigData -> a -> ResultEntry)
-> String
-> FieldData a b
buildBeParamField =
buildParamField "be" "backend" C.besParameterTitles beParamTypes
-- | Hvparams optimised lookup map.
hvParamTypes :: Map.Map String FieldType
hvParamTypes = Map.map vTypeToQFT C.hvsParameterTypes
-- | Builds the beparam fields for an object.
buildHvParamField :: (String -> ConfigData -> a -> ResultEntry)
-> String
-> FieldData a b
buildHvParamField =
buildParamField "hv" "hypervisor" C.hvsParameterTitles hvParamTypes
-- | Builds a param field for a certain getter class
buildParamField :: String -- ^ Prefix
-> String -- ^ Parameter group name
-> Map.Map String String -- ^ Parameter title map
-> Map.Map String FieldType -- ^ Parameter type map
-> (String -> ConfigData -> a -> ResultEntry)
-> String -- ^ The parameter name
-> FieldData a b
buildParamField prefix paramGroupName titleMap typeMap getter field =
let full_name = prefix ++ "/" ++ field
title = fromMaybe full_name $ field `Map.lookup` titleMap
qft = fromMaybe QFTOther $ field `Map.lookup` typeMap
desc = "The \"" ++ field ++ "\" " ++ paramGroupName ++ " parameter"
in ( FieldDefinition full_name title qft desc
, FieldConfig (getter field), QffNormal
)
-- | Looks up the default hypervisor and its hvparams
getDefaultHypervisorSpec :: ConfigData -> (Hypervisor, HvParams)
getDefaultHypervisorSpec cfg = (hv, getHvParamsFromCluster cfg hv)
where hv = getDefaultHypervisor cfg
-- | Looks up the cluster's hvparams of the given hypervisor
getHvParamsFromCluster :: ConfigData -> Hypervisor -> HvParams
getHvParamsFromCluster cfg hv =
fromMaybe (GenericContainer Map.empty) .
Map.lookup (hypervisorToRaw hv) .
fromContainer . clusterHvparams $ configCluster cfg
-- | Given an alias list and a field list, copies field definitions under a
-- new field name. Aliases should be tested - see the test module
-- 'Test.Ganeti.Query.Aliases'!
aliasFields :: [(FieldName, FieldName)] -> FieldList a b -> FieldList a b
aliasFields aliases fieldList = fieldList ++ do
alias <- aliases
(FieldDefinition name d1 d2 d3, v1, v2) <- fieldList
guard (snd alias == name)
return (FieldDefinition (fst alias) d1 d2 d3, v1, v2)
|
ganeti-github-testing/ganeti-test-1
|
src/Ganeti/Query/Common.hs
|
bsd-2-clause
| 10,090
| 0
| 13
| 1,907
| 1,661
| 907
| 754
| 146
| 2
|
module Infinity.Plugins.System where
import Infinity.Plugins
data System = System
deriving (Eq,Show)
instance Plugin System () where
pinit _ = ()
cmds _ = ["help","version","list"]
help _ "help" = "@help <cmd>, provides help for a command"
help _ "version" = "Gives version information"
help _ "list" = "Lists all commands"
exec _ _ "version" _ = return ((),ver)
exec _ _ "help" Nothing = return ((),"Need command...")
exec _ _ "help" (Just x) = pRunHelp x >>= \x' -> return ((),x')
exec _ _ "list" _ = pListHelp >>= \x -> return ((),unlines x)
|
thoughtpolice/infinity
|
src/Infinity/Plugins/System.hs
|
bsd-3-clause
| 624
| 0
| 10
| 172
| 229
| 121
| 108
| -1
| -1
|
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.III.K4cf5dd973ae4 (III(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
import qualified Test.ZM.ADT.Int8.Kb3a2642b4a84
import qualified Test.ZM.ADT.Int16.K3dac6bd4fa9c
import qualified Test.ZM.ADT.Int64.Kfb94cb4d4ede
import qualified Test.ZM.ADT.IEEE_754_binary32.Kb53bec846608
import qualified Test.ZM.ADT.IEEE_754_binary64.Kcba9596b4657
import qualified Test.ZM.ADT.Int.K102a3bb904e3
data III = III {w8 :: Test.ZM.ADT.Int8.Kb3a2642b4a84.Int8,
w16 :: Test.ZM.ADT.Int16.K3dac6bd4fa9c.Int16,
w :: Test.ZM.ADT.Int64.Kfb94cb4d4ede.Int64,
i8 :: Test.ZM.ADT.Int8.Kb3a2642b4a84.Int8,
i :: Test.ZM.ADT.Int64.Kfb94cb4d4ede.Int64,
f :: Test.ZM.ADT.IEEE_754_binary32.Kb53bec846608.IEEE_754_binary32,
d :: Test.ZM.ADT.IEEE_754_binary64.Kcba9596b4657.IEEE_754_binary64,
ii :: Test.ZM.ADT.Int.K102a3bb904e3.Int}
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance Data.Model.Model III
|
tittoassini/typed
|
test/Test/ZM/ADT/III/K4cf5dd973ae4.hs
|
bsd-3-clause
| 1,206
| 0
| 9
| 211
| 254
| 178
| 76
| 23
| 0
|
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Test.IO.Mafia.Chaos where
import Control.Exception (IOException)
import Control.Monad.Catch (MonadCatch(..), MonadMask(..), bracket, handle)
import Control.Monad.Trans.Bifunctor (firstT)
import Control.Monad.Trans.Either (EitherT, runEitherT)
import Control.Monad.Trans.Either (hoistEither)
import Hedgehog.Corpus (muppets, viruses)
import Test.Mafia.IO (testIO)
import Data.Char (toUpper)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Mafia.Catch (bracketEitherT')
import Mafia.Git
import Mafia.IO
import Mafia.P
import Mafia.Path
import Mafia.Process (Hush(..), Pass(..))
import Mafia.Process (ProcessError, ProcessResult, Argument)
import Mafia.Process (call_, callFrom)
import System.IO (IO, print)
import Test.QuickCheck (Arbitrary(..), Gen, Property, Testable(..))
import Test.QuickCheck (forAllProperties)
import qualified Test.QuickCheck as QC
------------------------------------------------------------------------
data ChaosError =
GitError GitError
| ProcessError ProcessError
| ExpectedBuildFailure
deriving (Show)
type PackageName = Text
type SubmoduleName = Text
data Repo = Repo {
repoFocusPackage :: PackageDeps
, repoOtherPackages :: Map PackageName PackageDeps
} deriving (Eq, Ord, Show)
data PackageDeps = PackageDeps {
depSubmodules :: Set SubmoduleName
, depLocalPackages :: Set PackageName
} deriving (Eq, Ord, Show)
newtype Actions = Actions { unActions :: [Action] }
deriving (Eq, Ord, Show)
data Profiling =
NoProfiling
| Profiling
deriving (Eq, Ord, Show)
data Action =
Clean
| Lock
| Unlock
| Build Profiling
| AddLocal PackageName PackageName
| AddSubmodule SubmoduleName PackageName
| RemoveLocal PackageName
| RemoveSubmodule SubmoduleName
-- Sidestep = temporarily move out the way, try to build, then move back to
-- the valid location. Useful to test that caching works even across invalid
-- source states.
| SidestepLocal PackageName
| SidestepSubmodule SubmoduleName
deriving (Eq, Ord, Show)
repoSubmodules :: Repo -> Set SubmoduleName
repoSubmodules (Repo focus others) =
let fs = depSubmodules focus
os = Set.unions (fmap depSubmodules (Map.elems others)) in
Set.union fs os
emptyRepo :: Repo
emptyRepo = Repo emptyPackageDeps Map.empty
emptyPackageDeps :: PackageDeps
emptyPackageDeps = PackageDeps Set.empty Set.empty
fromTestRun :: [(Action, Repo)] -> [Action]
fromTestRun = fmap fst
fromActions :: [Action] -> Maybe [(Action, Repo)]
fromActions = fromActions' emptyRepo
fromActions' :: Repo -> [Action] -> Maybe [(Action, Repo)]
fromActions' _ [] = Just []
fromActions' repo (a : as) = do
repo' <- applyAction a repo
xs <- fromActions' repo' as
pure $ (a, repo') : xs
finalRepo :: [(Action, Repo)] -> Repo
finalRepo = \case
[] -> emptyRepo
((_, repo):[]) -> repo
(_:xs) -> finalRepo xs
------------------------------------------------------------------------
instance Arbitrary Actions where
arbitrary =
fmap (Actions . fromTestRun) . QC.sized $ \n -> do
k <- QC.choose (0, n)
genTestRun k
shrink (Actions as) = Actions <$> do
as' <- QC.shrinkList shrinkAction as
case fromActions as' of
Nothing -> pure []
Just _ -> pure as'
shrinkAction :: Action -> [Action]
shrinkAction = \case
AddLocal dep pkg
| pkg /= focusPackageName -> [AddLocal dep focusPackageName]
| otherwise -> []
AddSubmodule dep pkg
| pkg /= focusPackageName -> [AddSubmodule dep focusPackageName]
| otherwise -> []
Clean -> []
Lock -> []
Unlock -> []
Build NoProfiling -> []
Build Profiling -> [Build NoProfiling]
RemoveLocal _ -> []
RemoveSubmodule _ -> []
SidestepLocal _ -> []
SidestepSubmodule _ -> []
genTestRun :: Int -> Gen [(Action, Repo)]
genTestRun n
| n <= 0 = pure []
| otherwise = do
testRun <- genTestRun (n - 1)
let repo = finalRepo testRun
action <- genAction (finalRepo testRun)
pure . fromMaybe testRun
. fmap (\r -> testRun <> [(action, r)])
$ applyAction action repo
genAction :: Repo -> Gen Action
genAction repo@(Repo _ others) = do
profiling <- QC.elements [NoProfiling, Profiling]
mbLocalPackageNames <- oneOfSet localPackageNames
mbSubmoduleNames <- oneOfSet submoduleNames
let removableLocals = Map.keysSet others
availableLocals = Set.insert focusPackageName
. maybe id Set.delete mbLocalPackageNames
$ removableLocals
mbRemovableLocals <- oneOfSet removableLocals
mbAvailableLocals <- oneOfSet availableLocals
mbRemovableSubmodules <- oneOfSet (repoSubmodules repo)
QC.elements $ catMaybes [
pure Clean
, pure Lock
, pure Unlock
, pure (Build profiling)
, AddLocal <$> mbLocalPackageNames <*> mbAvailableLocals
, AddSubmodule <$> mbSubmoduleNames <*> mbAvailableLocals
, RemoveLocal <$> mbRemovableLocals
, RemoveSubmodule <$> mbRemovableSubmodules
, SidestepLocal <$> mbRemovableLocals
, SidestepSubmodule <$> mbRemovableSubmodules
]
focusPackageName :: PackageName
focusPackageName = "chaos-focus"
localPackageNames :: Set PackageName
localPackageNames = Set.fromList (("chaos-" <>) . T.replace " " "-" <$> viruses)
submoduleNames :: Set SubmoduleName
submoduleNames = Set.fromList (T.replace " " "-" <$> muppets)
oneOfSet :: Set a -> Gen (Maybe a)
oneOfSet xs
| Set.null xs = pure Nothing
| otherwise = Just <$> QC.elements (Set.toList xs)
applyAction :: Action -> Repo -> Maybe Repo
applyAction action =
let mustModify f g repo = if g repo == repo
then Nothing
else Just (f (repo, g repo))
in case action of
Clean -> Just . id
Lock -> Just . id
Unlock -> Just . id
Build _ -> Just . id
AddLocal dep pkg -> mustModify snd (addLocal dep pkg)
AddSubmodule dep pkg -> mustModify snd (addSubmodule dep pkg)
RemoveLocal dep -> mustModify snd (removeLocal dep)
RemoveSubmodule dep -> mustModify snd (removeSubmodule dep)
SidestepLocal dep -> mustModify fst (removeLocal dep)
SidestepSubmodule dep -> mustModify fst (removeSubmodule dep)
addLocal :: PackageName -> PackageName -> Repo -> Repo
addLocal dep pkg repo@(Repo f os)
| pkgIsFocus = Repo (addLocal' dep f) os'
| isCircular = repo
| pkgExists = Repo f (Map.adjust (addLocal' dep) pkg os')
| otherwise = repo
where
pkgIsFocus = pkg == focusPackageName
isCircular = Set.member pkg depDeps
pkgExists = Map.member pkg os
depDeps = fromMaybe Set.empty (recursiveLocals repo <$> Map.lookup dep os')
os' = Map.insertWith (\_ old -> old) dep emptyPackageDeps os
addLocal' :: PackageName -> PackageDeps -> PackageDeps
addLocal' dep (PackageDeps ss ls) =
PackageDeps ss (Set.insert dep ls)
addSubmodule :: SubmoduleName -> PackageName -> Repo -> Repo
addSubmodule dep pkg (Repo f os) =
if pkg == focusPackageName
then Repo (addSubmodule' dep f) os
else Repo f (Map.adjust (addSubmodule' dep) pkg os)
addSubmodule' :: SubmoduleName -> PackageDeps -> PackageDeps
addSubmodule' dep (PackageDeps ss ls) =
PackageDeps (Set.insert dep ss) ls
recursiveLocals :: Repo -> PackageDeps -> Set PackageName
recursiveLocals repo@(Repo _ os) (PackageDeps _ ls) =
let lookup name = fromMaybe Set.empty (recursiveLocals repo <$> Map.lookup name os) in
Set.union (unionMap lookup ls) ls
recursiveSubmodules :: Repo -> PackageDeps -> Set SubmoduleName
recursiveSubmodules repo@(Repo _ os) (PackageDeps ss ls) =
let lookup name = fromMaybe Set.empty (recursiveSubmodules repo <$> Map.lookup name os) in
Set.union (unionMap lookup ls) ss
unionMap :: Ord b => (a -> Set b) -> Set a -> Set b
unionMap f = Set.foldl (\xs x -> xs `Set.union` f x) Set.empty
removeLocal :: PackageName -> Repo -> Repo
removeLocal dep (Repo f os) =
let rm = Map.map (removeLocal' dep) . Map.delete dep in
Repo (removeLocal' dep f) (rm os)
removeLocal' :: PackageName -> PackageDeps -> PackageDeps
removeLocal' dep (PackageDeps ss ls) =
PackageDeps ss (Set.delete dep ls)
removeSubmodule :: SubmoduleName -> Repo -> Repo
removeSubmodule dep (Repo f os) =
let rm = Map.map (removeSubmodule' dep) . Map.delete dep in
Repo (removeSubmodule' dep f) (rm os)
removeSubmodule' :: SubmoduleName -> PackageDeps -> PackageDeps
removeSubmodule' dep (PackageDeps ss ls) =
PackageDeps (Set.delete dep ss) ls
------------------------------------------------------------------------
bracketDirectory :: IO a -> IO a
bracketDirectory io = bracket getCurrentDirectory setCurrentDirectory (const io)
withTempDirectory :: Testable a => (Directory -> EitherT ChaosError IO a) -> Property
withTempDirectory io = testIO . bracketDirectory $ do
result <- runEitherT $ withSystemTempDirectory "mafia.chaos" io
case result of
Left err -> return (QC.counterexample (show err) False)
Right x -> return (property x)
hush :: (MonadIO m, MonadCatch m) => a -> m a -> m a
hush def = handle $ \(_ :: IOException) -> return def
------------------------------------------------------------------------
writeRepo :: (MonadIO m, MonadCatch m) => Directory -> Repo -> m ()
writeRepo dir repo@(Repo focus others) = do
writePackage dir repo focusPackageName focus
mapM_ (\(name, pkg) -> writePackage dir repo name pkg) (Map.toList others)
writePackage :: (MonadIO m, MonadCatch m) => Directory -> Repo -> PackageName -> PackageDeps -> m ()
writePackage dir repo name pd@(PackageDeps ss ls) = do
let deps = Set.toList (Set.union ss ls)
locals = Set.toList (recursiveLocals repo pd)
writeProject (dir </> name) name deps locals
writeProject :: (MonadIO m, MonadCatch m) => Directory -> Text -> [Text] -> [Text] -> m ()
writeProject dir name deps locals = do
let modName = dromedary name
cabalFile = dir </> name <> ".cabal"
subsFile = dir </> name <> ".submodules"
hsFile = dir </> "src" </> modName <> ".hs"
writeFile cabalFile (cabalText name deps)
writeFile hsFile ("module " <> modName <> " where\n")
if null locals
then removeFile subsFile `catch` \(_ :: IOException) -> return ()
else writeFile subsFile (T.unlines locals)
writeFile :: MonadIO m => Path -> Text -> m ()
writeFile path txt = do
createDirectoryIfMissing True (takeDirectory path)
writeUtf8 path txt
dromedary :: Text -> Text
dromedary = mconcat . fmap upcase . T.splitOn "-"
where
upcase xs | T.null xs = xs
| otherwise = T.singleton (toUpper (T.head xs)) <> T.tail xs
cabalText :: Text -> [Text] -> Text
cabalText name deps = T.unlines [
"name: acme-" <> name
, "version: 0.0.1"
, "license: AllRightsReserved"
, "author: Mafia Chaos"
, "maintainer: Mafia Chaos"
, "synopsis: synopsis"
, "category: Development"
, "cabal-version: >= 1.8"
, "build-type: Simple"
, "description: description"
, ""
, "library"
, " hs-source-dirs: src"
, " build-depends:"
, " base >= 3 && < 5"
, " , transformers >= 0.4 && < 6"
] <> T.unlines (fmap (" , acme-" <>) deps)
------------------------------------------------------------------------
git :: (MonadCatch m, MonadIO m, Functor m, ProcessResult a)
=> Directory -> Argument -> [Argument] -> EitherT ChaosError m a
git dir cmd args =
callFrom ProcessError dir "git" ([cmd] <> args)
createGitHub :: (MonadCatch m, MonadIO m, Functor m) => Path -> EitherT ChaosError m ()
createGitHub dir =
forM_ submoduleNames $ \name -> do
let subDir = dir </> name
createDirectoryIfMissing True subDir
Hush <- git subDir "init" []
Hush <- git subDir "config" ["user.name", "Doris"]
Hush <- git subDir "config" ["user.email", "doris@megacorp.com"]
writeProject subDir name [] []
Hush <- git subDir "add" ["-A"]
Hush <- git subDir "commit" ["-m", "created project"]
return ()
submoduleExists :: Directory -> EitherT ChaosError IO Bool
submoduleExists sub = do
subs <- fmap subName <$> firstT GitError getSubmodules
return (sub `elem` subs)
gitAddSubmodule :: Directory -> Directory -> Path -> EitherT ChaosError IO ()
gitAddSubmodule github repoDir dep = do
let subDir = "lib" </> dep
exists <- submoduleExists subDir
unless exists $ do
Pass <- git repoDir "submodule" ["add", github </> dep, subDir]
Pass <- git repoDir "commit" ["-m", "added " <> dep]
return ()
gitRemoveSubmodule :: Directory -> Path -> EitherT ChaosError IO ()
gitRemoveSubmodule repoDir dep = do
let subDir = "lib" </> dep
exists <- submoduleExists subDir
when exists $ do
Pass <- git repoDir "rm" ["--cached", subDir]
Pass <- git repoDir "commit" ["-m", "removed " <> dep]
return ()
------------------------------------------------------------------------
prop_chaos (Actions actions) =
withTempDirectory $ \temp -> do
liftIO (print actions)
mafia <- (</> "dist/build/mafia/mafia") <$> getCurrentDirectory
let githubDir = temp </> "github"
repoDir = temp </> "repo"
homeDir = temp </> "home"
focusDir = repoDir </> focusPackageName
createGitHub githubDir
createDirectoryIfMissing False repoDir
createDirectoryIfMissing False focusDir
createDirectoryIfMissing False homeDir
withEnv "MAFIA_HOME" homeDir $ do
Pass <- git repoDir "init" []
Pass <- git repoDir "config" ["user.name", "Doris"]
Pass <- git repoDir "config" ["user.email", "doris@megacorp.com"]
setCurrentDirectory focusDir
writeRepo repoDir emptyRepo
case fromActions actions of
Nothing -> do
return (QC.counterexample "Invalid set of actions" (property False))
Just testRun -> do
forM_ testRun $ \(action, repo) -> do
runAction mafia githubDir repoDir repo action
return (property True)
withEnv :: (MonadMask m, MonadIO m) => Text -> Text -> EitherT e m b -> EitherT e m b
withEnv key new io =
let acquire = do
old <- lookupEnv key
setEnv key new
return old
release = \case
Nothing -> unsetEnv key
Just old -> setEnv key old
in bracketEitherT' acquire release (const io)
runAction :: File -> Directory -> Directory -> Repo -> Action -> EitherT ChaosError IO ()
runAction mafia github repoDir repo@(Repo focus _) = \case
Clean -> do
liftIO . T.putStrLn $ "$ mafia clean"
call_ ProcessError mafia ["clean"]
Lock -> do
liftIO . T.putStrLn $ "$ mafia lock"
call_ ProcessError mafia ["lock"]
Unlock -> do
liftIO . T.putStrLn $ "$ mafia unlock"
call_ ProcessError mafia ["unlock"]
Build prof -> do
liftIO . T.putStrLn $ "$ mafia " <> T.intercalate " " (["build"] <> profilingArgs prof)
expectBuildSuccess mafia prof
AddLocal dep pkg -> do
putAdd (dep <> " -> " <> pkg)
writeRepo repoDir repo
AddSubmodule dep pkg -> do
putAdd ("lib" </> dep <> " -> " <> pkg)
gitAddSubmodule github repoDir dep
writeRepo repoDir repo
RemoveLocal dep -> do
putRemove dep
removeDirectoryRecursive (repoDir </> dep)
writeRepo repoDir repo
RemoveSubmodule dep -> do
putRemove ("lib" </> dep)
gitRemoveSubmodule repoDir dep
writeRepo repoDir repo
SidestepLocal dep -> do
putSidestep dep
removeDirectoryRecursive (repoDir </> dep)
if Set.member dep (recursiveLocals repo focus)
then expectBuildFailure mafia NoProfiling
else expectBuildSuccess mafia NoProfiling
writeRepo repoDir repo
SidestepSubmodule dep -> do
putSidestep ("lib" </> dep)
gitRemoveSubmodule repoDir dep
if Set.member dep (recursiveSubmodules repo focus)
then expectBuildFailure mafia NoProfiling
else expectBuildSuccess mafia NoProfiling
gitAddSubmodule github repoDir dep
expectBuildSuccess :: File -> Profiling -> EitherT ChaosError IO ()
expectBuildSuccess mafia prof =
call_ ProcessError mafia $ ["build"] <> profilingArgs prof
expectBuildFailure :: File -> Profiling -> EitherT ChaosError IO ()
expectBuildFailure mafia prof = do
result <- liftIO . runEitherT . call_ id mafia $ ["build"] <> profilingArgs prof
hoistEither $ case result of
Left _ -> Right ()
Right () -> Left ExpectedBuildFailure
profilingArgs :: Profiling -> [Argument]
profilingArgs = \case
NoProfiling -> []
Profiling -> ["--profiling"]
putAdd :: MonadIO m => Text -> m ()
putAdd x = liftIO (T.putStrLn ("+ " <> x))
putRemove :: MonadIO m => Text -> m ()
putRemove x = liftIO (T.putStrLn ("- " <> x))
putSidestep :: MonadIO m => Text -> m ()
putSidestep x = liftIO (T.putStrLn ("~ " <> x))
------------------------------------------------------------------------
return []
tests = $forAllProperties $ QC.quickCheckWithResult (QC.stdArgs {QC.maxSuccess = 10})
|
ambiata/mafia
|
test/Test/IO/Mafia/Chaos.hs
|
bsd-3-clause
| 17,781
| 0
| 21
| 4,182
| 5,725
| 2,862
| 2,863
| 416
| 12
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings,
GADTs, FlexibleContexts, MultiParamTypeClasses, GeneralizedNewtypeDeriving,
RankNTypes, NamedFieldPuns #-}
-- | Global sqlite database shared by all projects.
-- Warning: this is currently only accessible from __outside__ a Docker container.
module Stack.Docker.GlobalDB
(updateDockerImageLastUsed
,getDockerImagesLastUsed
,pruneDockerImagesLastUsed
,DockerImageLastUsed
,DockerImageProjectId
,getDockerImageExe
,setDockerImageExe
,DockerImageExeId)
where
import Control.Monad.Logger (NoLoggingT)
import Stack.Prelude
import Data.List (sortBy, isInfixOf, stripPrefix)
import Data.List.Extra (stripSuffix)
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import Data.Time.Clock (UTCTime,getCurrentTime)
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import Path (parent, (<.>))
import Path.IO (ensureDir)
import Stack.Types.Config
import Stack.Types.Docker
import System.FileLock (withFileLock, SharedExclusive(Exclusive))
share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistLowerCase|
DockerImageProject
imageHash String
projectPath FilePath
lastUsedTime UTCTime
DockerImageProjectPathKey imageHash projectPath
deriving Show
DockerImageExe
imageHash String
exePath FilePath
exeTimestamp UTCTime
compatible Bool
DockerImageExeUnique imageHash exePath exeTimestamp
deriving Show
|]
-- | Update last used time and project for a Docker image hash.
updateDockerImageLastUsed :: Config -> String -> FilePath -> IO ()
updateDockerImageLastUsed config imageId projectPath =
do curTime <- getCurrentTime
_ <- withGlobalDB config (upsert (DockerImageProject imageId projectPath curTime) [])
return ()
-- | Get a list of Docker image hashes and when they were last used.
getDockerImagesLastUsed :: Config -> IO [DockerImageLastUsed]
getDockerImagesLastUsed config =
do imageProjects <- withGlobalDB config (selectList [] [Asc DockerImageProjectLastUsedTime])
return (sortBy (flip sortImage)
(Map.toDescList (Map.fromListWith (++)
(map mapImageProject imageProjects))))
where
mapImageProject (Entity _ imageProject) =
(dockerImageProjectImageHash imageProject
,[(dockerImageProjectLastUsedTime imageProject
,dockerImageProjectProjectPath imageProject)])
sortImage (_,(a,_):_) (_,(b,_):_) = compare a b
sortImage _ _ = EQ
-- | Given a list of all existing Docker images, remove any that no longer exist from
-- the database.
pruneDockerImagesLastUsed :: Config -> [String] -> IO ()
pruneDockerImagesLastUsed config existingHashes =
withGlobalDB config go
where
go = do
l <- selectList [] []
forM_ l (\(Entity k DockerImageProject{dockerImageProjectImageHash = h}) ->
when (h `notElem` existingHashes) $ delete k)
-- | Get the record of whether an executable is compatible with a Docker image
getDockerImageExe :: Config -> String -> FilePath -> UTCTime -> IO (Maybe Bool)
getDockerImageExe config imageId exePath exeTimestamp =
withGlobalDB config $ do
mentity <- getBy (DockerImageExeUnique imageId exePath exeTimestamp)
return (fmap (dockerImageExeCompatible . entityVal) mentity)
-- | Seet the record of whether an executable is compatible with a Docker image
setDockerImageExe :: Config -> String -> FilePath -> UTCTime -> Bool -> IO ()
setDockerImageExe config imageId exePath exeTimestamp compatible =
withGlobalDB config $
do _ <- upsert (DockerImageExe imageId exePath exeTimestamp compatible) []
return ()
-- | Run an action with the global database. This performs any needed migrations as well.
withGlobalDB :: forall a. Config -> SqlPersistT (NoLoggingT (ResourceT IO)) a -> IO a
withGlobalDB config action =
do let db = dockerDatabasePath (configDocker config)
dbLock <- db <.> "lock"
ensureDir (parent db)
withFileLock (toFilePath dbLock) Exclusive (\_fl -> runSqlite (T.pack (toFilePath db))
(do _ <- runMigrationSilent migrateTables
action))
`catch` \ex -> do
let str = show ex
str' = fromMaybe str $ stripPrefix "user error (" $
fromMaybe str $ stripSuffix ")" str
if "ErrorReadOnly" `isInfixOf` str
then throwString $ str' ++
" This likely indicates that your DB file, " ++
toFilePath db ++ ", has incorrect permissions or ownership."
else throwIO (ex :: IOException)
-- | Date and project path where Docker image hash last used.
type DockerImageLastUsed = (String, [(UTCTime, FilePath)])
|
MichielDerhaeg/stack
|
src/Stack/Docker/GlobalDB.hs
|
bsd-3-clause
| 5,115
| 1
| 17
| 1,283
| 1,051
| 557
| 494
| 81
| 2
|
{-# OPTIONS_GHC -Wall #-}
module Type.Constrain.Expression where
import Control.Applicative ((<$>))
import Control.Arrow (second)
import qualified Control.Monad as Monad
import qualified Data.List as List
import qualified Data.Map as Map
import qualified AST.Expression.General as E
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Literal as Lit
import qualified AST.Pattern as P
import qualified AST.Type as ST
import qualified AST.Variable as V
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Type as Error
import qualified Reporting.Region as R
import qualified Type.Constrain.Literal as Literal
import qualified Type.Constrain.Pattern as Pattern
import qualified Type.Environment as Env
import qualified Type.Fragment as Fragment
import Type.Type hiding (Descriptor(..))
constrain
:: Env.Environment
-> Canonical.Expr
-> Type
-> IO TypeConstraint
constrain env annotatedExpr@(A.A region expression) tipe =
let list t = Env.get env Env.types "List" <| t
(<?) = CInstance region
in
case expression of
E.Literal lit ->
Literal.constrain env region lit tipe
E.GLShader _uid _src gltipe ->
exists $ \attr ->
exists $ \unif ->
let
shaderTipe a u v =
Env.get env Env.types "WebGL.Shader" <| a <| u <| v
glTipe =
Env.get env Env.types . Lit.glTipeName
makeRec accessor baseRec =
let decls = accessor gltipe
in
if Map.size decls == 0
then baseRec
else record (Map.map (\t -> [glTipe t]) decls) baseRec
attribute = makeRec Lit.attribute attr
uniform = makeRec Lit.uniform unif
varying = makeRec Lit.varying (termN EmptyRecord1)
in
return (CEqual Error.Shader region tipe (shaderTipe attribute uniform varying))
E.Var var ->
let name = V.toString var
in
return (if name == E.saveEnvName then CSaveEnv else name <? tipe)
E.Range lowExpr highExpr ->
existsNumber $ \n ->
do lowCon <- constrain env lowExpr n
highCon <- constrain env highExpr n
return $ CAnd
[ lowCon
, highCon
, CEqual Error.Range region (list n) tipe
]
E.ExplicitList exprs ->
constrainList env region exprs tipe
E.Binop op leftExpr rightExpr ->
constrainBinop env region op leftExpr rightExpr tipe
E.Lambda pattern body ->
exists $ \argType ->
exists $ \resType ->
do fragment <- Pattern.constrain env pattern argType
bodyCon <- constrain env body resType
let con =
ex (Fragment.vars fragment)
(CLet [monoscheme (Fragment.typeEnv fragment)]
(Fragment.typeConstraint fragment /\ bodyCon)
)
return $ con /\ CEqual Error.Lambda region tipe (argType ==> resType)
E.App _ _ ->
let
(f:args) = E.collectApps annotatedExpr
in
constrainApp env region f args tipe
E.MultiIf branches finally ->
constrainIf env region branches finally tipe
E.Case expr branches ->
constrainCase env region expr branches tipe
E.Data name exprs ->
do vars <- Monad.forM exprs $ \_ -> variable Flexible
let pairs = zip exprs (map varN vars)
(ctipe, cs) <- Monad.foldM step (tipe, CTrue) (reverse pairs)
return $ ex vars (cs /\ name <? ctipe)
where
step (t,c) (e,x) =
do c' <- constrain env e x
return (x ==> t, c /\ c')
E.Access expr label ->
exists $ \t ->
constrain env expr (record (Map.singleton label [tipe]) t)
E.Remove expr label ->
exists $ \t ->
constrain env expr (record (Map.singleton label [t]) tipe)
E.Insert expr label value ->
exists $ \valueType ->
exists $ \recordType ->
do valueCon <- constrain env value valueType
recordCon <- constrain env expr recordType
let newRecordType =
record (Map.singleton label [valueType]) recordType
return $ CAnd
[ valueCon
, recordCon
, CEqual Error.Record region tipe newRecordType
]
E.Modify expr fields ->
exists $ \t ->
do oldVars <- Monad.forM fields $ \_ -> variable Flexible
let oldFields = ST.fieldMap (zip (map fst fields) (map varN oldVars))
cOld <- ex oldVars <$> constrain env expr (record oldFields t)
newVars <- Monad.forM fields $ \_ -> variable Flexible
let newFields = ST.fieldMap (zip (map fst fields) (map varN newVars))
let cNew = CEqual Error.Record region tipe (record newFields t)
cs <- Monad.zipWithM (constrain env) (map snd fields) (map varN newVars)
return $ cOld /\ ex newVars (CAnd (cNew : cs))
E.Record fields ->
do vars <- Monad.forM fields (\_ -> variable Flexible)
fieldCons <-
Monad.zipWithM
(constrain env)
(map snd fields)
(map varN vars)
let fields' = ST.fieldMap (zip (map fst fields) (map varN vars))
let recordType = record fields' (termN EmptyRecord1)
return (ex vars (CAnd (fieldCons ++ [CEqual Error.Record region tipe recordType])))
E.Let defs body ->
do bodyCon <- constrain env body tipe
(Info schemes rqs fqs headers c2 c1) <-
Monad.foldM
(constrainDef env)
(Info [] [] [] Map.empty CTrue CTrue)
(concatMap expandPattern defs)
let letScheme =
[ Scheme rqs fqs (CLet [monoscheme headers] c2) headers ]
return $ CLet schemes (CLet letScheme (c1 /\ bodyCon))
E.Port impl ->
case impl of
E.In _ _ ->
return CTrue
E.Out _ expr _ ->
constrain env expr tipe
E.Task _ expr _ ->
constrain env expr tipe
E.Crash _ ->
return CTrue
-- CONSTRAIN APP
constrainApp
:: Env.Environment
-> R.Region
-> Canonical.Expr
-> [Canonical.Expr]
-> Type
-> IO TypeConstraint
constrainApp env region f args tipe =
do funcVar <- variable Flexible
funcCon <- constrain env f (varN funcVar)
(vars, argCons, numberOfArgsCons, argMatchCons, _, returnVar) <-
argConstraints env maybeName region (length args) funcVar 1 args
let returnCon =
CEqual (Error.Function maybeName) region (varN returnVar) tipe
return $ ex (funcVar : vars) $
CAnd (funcCon : argCons ++ numberOfArgsCons ++ argMatchCons ++ [returnCon])
where
maybeName =
case f of
A.A _ (E.Var canonicalName) ->
Just canonicalName
_ ->
Nothing
argConstraints
:: Env.Environment
-> Maybe V.Canonical
-> R.Region
-> Int
-> Variable
-> Int
-> [Canonical.Expr]
-> IO ([Variable], [TypeConstraint], [TypeConstraint], [TypeConstraint], Maybe R.Region, Variable)
argConstraints env name region totalArgs overallVar index args =
case args of
[] ->
return ([], [], [], [], Nothing, overallVar)
expr@(A.A subregion _) : rest ->
do argVar <- variable Flexible
argCon <- constrain env expr (varN argVar)
argIndexVar <- variable Flexible
localReturnVar <- variable Flexible
(vars, argConRest, numberOfArgsRest, argMatchRest, restRegion, returnVar) <-
argConstraints env name region totalArgs localReturnVar (index + 1) rest
let arityRegion =
maybe subregion (R.merge subregion) restRegion
let numberOfArgsCon =
CEqual
(Error.FunctionArity name (index - 1) totalArgs arityRegion)
region
(varN argIndexVar ==> varN localReturnVar)
(varN overallVar)
let argMatchCon =
CEqual
(Error.UnexpectedArg name index subregion)
region
(varN argIndexVar)
(varN argVar)
return
( argVar : argIndexVar : localReturnVar : vars
, argCon : argConRest
, numberOfArgsCon : numberOfArgsRest
, argMatchCon : argMatchRest
, Just arityRegion
, returnVar
)
-- CONSTRAIN BINOP
constrainBinop
:: Env.Environment
-> R.Region
-> V.Canonical
-> Canonical.Expr
-> Canonical.Expr
-> Type
-> IO TypeConstraint
constrainBinop env region op leftExpr@(A.A leftRegion _) rightExpr@(A.A rightRegion _) tipe =
do leftVar <- variable Flexible
rightVar <- variable Flexible
leftCon <- constrain env leftExpr (varN leftVar)
rightCon <- constrain env rightExpr (varN rightVar)
leftVar' <- variable Flexible
rightVar' <- variable Flexible
answerVar <- variable Flexible
let opType = varN leftVar' ==> varN rightVar' ==> varN answerVar
return $
ex [leftVar,rightVar,leftVar',rightVar',answerVar] $ CAnd $
[ leftCon
, rightCon
, CInstance region (V.toString op) opType
, CEqual (Error.BinopLeft op leftRegion) region (varN leftVar') (varN leftVar)
, CEqual (Error.BinopRight op rightRegion) region (varN rightVar') (varN rightVar)
, CEqual (Error.Binop op) region tipe (varN answerVar)
]
-- CONSTRAIN LISTS
constrainList
:: Env.Environment
-> R.Region
-> [Canonical.Expr]
-> Type
-> IO TypeConstraint
constrainList env region exprs tipe =
do (exprInfo, exprCons) <-
unzip <$> mapM elementConstraint exprs
(vars, cons) <- pairCons region Error.ListElement varToCon exprInfo
return $ ex vars (CAnd (exprCons ++ cons))
where
elementConstraint expr@(A.A region' _) =
do var <- variable Flexible
con <- constrain env expr (varN var)
return ( (var, region'), con )
varToCon var =
CEqual Error.List region tipe (Env.get env Env.types "List" <| varN var)
-- CONSTRAIN IF EXPRESSIONS
constrainIf
:: Env.Environment
-> R.Region
-> [(Canonical.Expr, Canonical.Expr)]
-> Canonical.Expr
-> Type
-> IO TypeConstraint
constrainIf env region branches finally tipe =
do let (conditions, branchExprs) =
second (++ [finally]) (unzip branches)
(condVars, condCons) <-
unzip <$> mapM constrainCondition conditions
(branchInfo, branchExprCons) <-
unzip <$> mapM constrainBranch branchExprs
(vars,cons) <- branchCons branchInfo
return $ ex (condVars ++ vars) (CAnd (condCons ++ branchExprCons ++ cons))
where
bool =
Env.get env Env.types "Bool"
constrainCondition condition@(A.A condRegion _) =
do condVar <- variable Flexible
condCon <- constrain env condition (varN condVar)
let boolCon = CEqual Error.IfCondition condRegion (varN condVar) bool
return (condVar, CAnd [ condCon, boolCon ])
constrainBranch expr@(A.A branchRegion _) =
do branchVar <- variable Flexible
exprCon <- constrain env expr (varN branchVar)
return
( (branchVar, branchRegion)
, exprCon
)
branchCons branchInfo =
case branchInfo of
[(thenVar, _), (elseVar, _)] ->
return
( [thenVar,elseVar]
, [ CEqual Error.IfBranches region (varN thenVar) (varN elseVar)
, varToCon thenVar
]
)
_ ->
pairCons region Error.MultiIfBranch varToCon branchInfo
varToCon var =
CEqual Error.If region (varN var) tipe
-- CONSTRAIN CASE EXPRESSIONS
constrainCase
:: Env.Environment
-> R.Region
-> Canonical.Expr
-> [(P.CanonicalPattern, Canonical.Expr)]
-> Type
-> IO TypeConstraint
constrainCase env region expr branches tipe =
do exprVar <- variable Flexible
exprCon <- constrain env expr (varN exprVar)
(branchInfo, branchExprCons) <-
unzip <$> mapM (branch (varN exprVar)) branches
(vars, cons) <- pairCons region Error.CaseBranch varToCon branchInfo
return $ ex (exprVar : vars) (CAnd (exprCon : branchExprCons ++ cons))
where
branch patternType (pattern, branchExpr@(A.A branchRegion _)) =
do branchVar <- variable Flexible
fragment <- Pattern.constrain env pattern patternType
branchCon <- constrain env branchExpr (varN branchVar)
return
( (branchVar, branchRegion)
, CLet [Fragment.toScheme fragment] branchCon
)
varToCon var =
CEqual Error.Case region tipe (varN var)
-- COLLECT PAIRS
data Pair = Pair
{ _index :: Int
, _var1 :: Variable
, _var2 :: Variable
, _region :: R.Region
}
pairCons
:: R.Region
-> (Int -> R.Region -> Error.Hint)
-> (Variable -> TypeConstraint)
-> [(Variable, R.Region)]
-> IO ([Variable], [TypeConstraint])
pairCons region pairHint varToCon items =
let
pairToCon (Pair index var1 var2 subregion) =
CEqual (pairHint index subregion) region (varN var1) (varN var2)
in
case collectPairs 2 items of
Nothing ->
do var <- variable Flexible
return ([var], [varToCon var])
Just (pairs, var) ->
return (map fst items, map pairToCon pairs ++ [varToCon var])
collectPairs :: Int -> [(Variable, R.Region)] -> Maybe ([Pair], Variable)
collectPairs index items =
case items of
[] ->
Nothing
(var,_) : [] ->
Just ([], var)
(var,_) : rest@((var',region) : _) ->
do (pairs, summaryVar) <- collectPairs (index+1) rest
return (Pair index var var' region : pairs, summaryVar)
-- EXPAND PATTERNS
expandPattern :: Canonical.Def -> [Canonical.Def]
expandPattern def@(Canonical.Definition lpattern expr maybeType) =
let (A.A patternRegion pattern) = lpattern
in
case pattern of
P.Var _ ->
[def]
_ ->
mainDef : map toDef vars
where
vars = P.boundVarList lpattern
combinedName = "$" ++ concat vars
pvar name =
A.A patternRegion (P.Var name)
localVar name =
A.A patternRegion (E.localVar name)
mainDef = Canonical.Definition (pvar combinedName) expr maybeType
toDef name =
let extract =
E.Case (localVar combinedName) [(lpattern, localVar name)]
in
Canonical.Definition (pvar name) (A.A patternRegion extract) Nothing
-- CONSTRAIN DEFINITIONS
data Info = Info
{ iSchemes :: [TypeScheme]
, iRigid :: [Variable]
, iFlex :: [Variable]
, iHeaders :: Map.Map String (A.Located Type)
, iC2 :: TypeConstraint
, iC1 :: TypeConstraint
}
constrainDef :: Env.Environment -> Info -> Canonical.Def -> IO Info
constrainDef env info (Canonical.Definition (A.A patternRegion pattern) expr maybeTipe) =
let qs = [] -- should come from the def, but I'm not sure what would live there...
in
case (pattern, maybeTipe) of
(P.Var name, Just (A.A typeRegion tipe)) ->
constrainAnnotatedDef env info qs patternRegion typeRegion name expr tipe
(P.Var name, Nothing) ->
constrainUnannotatedDef env info qs patternRegion name expr
_ -> error ("problem in constrainDef with " ++ show pattern)
constrainAnnotatedDef
:: Env.Environment
-> Info
-> [String]
-> R.Region
-> R.Region
-> String
-> Canonical.Expr
-> ST.Canonical
-> IO Info
constrainAnnotatedDef env info qs patternRegion typeRegion name expr tipe =
do -- Some mistake may be happening here. Currently, qs is always [].
rigidVars <- Monad.forM qs (\_ -> variable Rigid)
flexiVars <- Monad.forM qs (\_ -> variable Flexible)
let inserts = zipWith (\arg typ -> Map.insert arg (varN typ)) qs flexiVars
let env' = env { Env.value = List.foldl' (\x f -> f x) (Env.value env) inserts }
(vars, typ) <- Env.instantiateType env tipe Map.empty
let scheme =
Scheme
{ rigidQuantifiers = []
, flexibleQuantifiers = flexiVars ++ vars
, constraint = CTrue
, header = Map.singleton name (A.A patternRegion typ)
}
var <- variable Flexible
defCon <- constrain env' expr (varN var)
let annCon =
CEqual (Error.BadTypeAnnotation name) typeRegion typ (varN var)
return $ info
{ iSchemes = scheme : iSchemes info
, iC1 = iC1 info /\ ex [var] (defCon /\ fl rigidVars annCon)
}
constrainUnannotatedDef
:: Env.Environment
-> Info
-> [String]
-> R.Region
-> String
-> Canonical.Expr
-> IO Info
constrainUnannotatedDef env info qs patternRegion name expr =
do -- Some mistake may be happening here. Currently, qs is always [].
rigidVars <- Monad.forM qs (\_ -> variable Rigid)
v <- variable Flexible
let tipe = varN v
let inserts = zipWith (\arg typ -> Map.insert arg (varN typ)) qs rigidVars
let env' = env { Env.value = List.foldl' (\x f -> f x) (Env.value env) inserts }
con <- constrain env' expr tipe
return $ info
{ iRigid = rigidVars ++ iRigid info
, iFlex = v : iFlex info
, iHeaders = Map.insert name (A.A patternRegion tipe) (iHeaders info)
, iC2 = con /\ iC2 info
}
|
johnpmayer/elm-compiler
|
src/Type/Constrain/Expression.hs
|
bsd-3-clause
| 18,345
| 110
| 34
| 6,137
| 4,475
| 2,468
| 2,007
| 432
| 23
|
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
-- Module : lexString
-- Copyright : (c) 2010 David M. Rosenberg
-- License : BSD3
--
-- Maintainer : David Rosenberg <rosenbergdm@uchicago.edu>
-- Stability : experimental
-- Portability : portable
-- Created : 06/10/10
--
-- Description :
-- DESCRIPTION HERE.
-----------------------------------------------------------------------------
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Combinator
import Text.Parsec.Char
import Text.Parsec.Prim
dblQuotedString :: (Text.Parsec.Prim.Stream s m Char) => Text.Parsec.Prim.ParsecT s u m String
dblQuotedString = do
capture <- (between (char '"') (char '"') (many $ choice [char '\\' >> char '"', noneOf "\""]))
return $ capture
singQuotedString :: (Text.Parsec.Prim.Stream s m Char) => Text.Parsec.Prim.ParsecT s u m String
singQuotedString = do
capture <- (between (char '\'') (char '\'') (many $ choice [char '\\' >> char '\'', noneOf "'"]))
return $ capture
quotedString :: (Text.Parsec.Prim.Stream s m Char) => Text.Parsec.Prim.ParsecT s u m String
quotedString = try dblQuotedString
<|> singQuotedString
|
rosenbergdm/language-r
|
src/Language/R/backup/lexString.hs
|
bsd-3-clause
| 1,235
| 0
| 15
| 196
| 301
| 167
| 134
| 17
| 1
|
{-------------------------------------------------------------------------------
Computes BOW similarity scores over a list of word pairs.
Generates additional files with data about vector
dimensions and weights for the two word vectors and their
intersection.
(c) 2014 Jan Snajder <jan.snajder@fer.hr>
TODO: add output management via command args
code cleanup
-------------------------------------------------------------------------------}
{-# LANGUAGE DoAndIfThenElse #-}
import Control.Applicative
import Control.Monad
import Control.Monad.Trans
import Data.Function
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Ord
import Data.Word (Word64)
import qualified Data.Text as T
import qualified DSem.Vector as V
import DSem.VectorSpace.Bow as Bow
import System.Console.ParseArgs
import System.Environment
import System.Exit
import System.IO
import Text.Printf
data WordSim = WordSim
{ cosine :: Double
, norm1 :: Double
, norm2 :: Double
, norm12 :: Double
, dotProd :: Double
, dimShared :: Word64
, entropy1 :: Double
, entropy2 :: Double
, jsDiv :: Double
, jaccard :: Double
, v1 :: [ (Bow.Target, V.Weight) ]
, v2 :: [ (Bow.Target, V.Weight) ]
, v12 :: [ (Bow.Target, V.Weight) ] }
nullWordSim = WordSim (-1) 0 0 0 0 0 0 0 0 0 [] [] []
wordSim :: String -> String -> BowM (Maybe WordSim)
wordSim w1 w2 = do
v1 <- Bow.getTargetVector w1
v2 <- Bow.getTargetVector w2
case (v1,v2) of
(Just v1,Just v2) -> do
v1' <- vectorDims v1
v2' <- vectorDims v2
let v12 = V.pmul v1 v2
v12' <- vectorDims v12
return . Just $ WordSim
{ cosine = {-max 0 . min 1 $-} V.cosine v1 v2
, norm1 = V.norm2 v1
, norm2 = V.norm2 v2
, dotProd = sum $ V.nonzeroWeights v12
, norm12 = V.norm2 v12
, entropy1 = V.entropy v1
, entropy2 = V.entropy v2
, dimShared = V.dimShared v1 v2
, jsDiv = V.jsDivergence v1 v2
, jaccard = V.jaccardIndex v1 v2
, v1 = v1'
, v2 = v2'
, v12 = v12' }
_ -> return Nothing
phraseSim :: String -> String -> String -> BowM (Maybe WordSim)
phraseSim sep p1 p2 =
maximumBy (compare `on` (cosine <$>)) <$>
sequence [wordSim w1 w2 | w1 <- split p1, w2 <- split p2]
where split = splitOn sep
arg =
[ Arg 0 (Just 'p') (Just "vector-profiles") Nothing
"output vector profiles (instead of plain similarities)"
, Arg 1 (Just 'h') (Just "header") Nothing
"output header with field descriptions"
, Arg 2 (Just 'r') (Just "remove-words") Nothing
"remove word pairs from output"
, Arg 3 (Just 'm') (Just "multiwords") Nothing
"compute multiword phrase similarity as max word cosine similarity"
, Arg 4 (Just 'w') (Just "word-separator")
(argDataDefaulted "string" ArgtypeString "-")
"separator for words in a phrase (default=\"-\")"
, Arg 5 (Just 'c') (Just "contexts")
(argDataOptional "filename" ArgtypeString)
"BoW contexts (only required for --vector-profiles)"
, Arg 6 (Just 'd') (Just "dimensions")
(argDataDefaulted "integer" ArgtypeString "50")
"number of vector profile dimensions (default=50)"
, Arg 7 Nothing Nothing (argDataRequired "bow" ArgtypeString)
"BoW matrix filename"
, Arg 8 Nothing Nothing (argDataRequired "pairs" ArgtypeString)
"list of word pairs" ]
header = "w1\tw2\tcos(v1,v2)\tnorm2(v1)\tnorm2(v2)\t\tnorm2(v1*v2)\t\
\dimShared(v1,v2)\tentropy(v1)\tentropy(v2)\tjsDivergence(v1,v2)\t\
\jaccard(v1,v2)"
main = do
args <- parseArgsIO ArgsComplete arg
let matrix = fromJust $ getArg args 7
pairs = fromJust $ getArg args 8
sep = fromJust $ getArg args 4
sim = if gotArg args 3 then phraseSim sep else wordSim
ps <- let parse (w1:w2:_) = (w1, w2)
parse _ = error "no parse"
in map (parse . words) . lines <$> readFile pairs
if not $ gotArg args 0 then do
m <- Bow.readMatrix matrix
when (gotArg args 1) $ putStrLn header
Bow.runModelIO m $ do
forM_ ps $ \(w1,w2) -> do
s <- fromMaybe nullWordSim <$> sim w1 w2
when (not $ gotArg args 2) . liftIO . putStr $ printf "%s\t%s\t" w1 w2
liftIO . putStrLn $ printf "%f\t%f\t%f\t%f\t%d\t%f\t%f\t%f\t%f"
(cosine s) (norm1 s) (norm2 s) (dotProd s) (dimShared s)
(entropy1 s) (entropy2 s) (jsDiv s) (jaccard s)
else do
when (not $ gotArg args 5) $ usageError args "no contexts file provided"
let contexts = fromJust $ getArg args 5
dims = read $ fromJust $ getArg args 6
m <- Bow.readModel matrix contexts
Bow.runModelIO m $ do
forM_ (zip [1..] ps) $ \(i,(w1,w2)) -> do
s <- fromMaybe nullWordSim <$> sim w1 w2
liftIO . putStrLn $
printf "(%04d) w1 = %s, w2 = %s, cos(v1,v2) = %.4f, \
\norm2(v1) = %.2f, norm2(v2) = %.2f, norm2(v1*v2) = %.2f, \
\dot(v1,v2) = %.2f, dimShared(v1,v2) = %d, \
\entropy(v1) = %.2f, entropy(v2) = %.2f, \
\jsDivergence(v1,v2) = %.2f, jaccard(v1,v2) = %.2f\n\n"
(i::Int) w1 w2 (cosine s) (norm1 s) (norm2 s) (norm12 s)
(dotProd s) (dimShared s) (entropy1 s) (entropy2 s)
(jsDiv s) (jaccard s) ++
printVectorDims dims s
printVectorDims :: Int -> WordSim -> String
printVectorDims k s = unlines $ zipWith3 f xs1 xs2 xs12
where xs1 = top k (v1 s)
xs2 = top k (v2 s)
xs12 = top k (v12 s) ++ repeat (T.pack "",0)
top k = map r . take k . filter ((/=0).snd) .
sortBy (flip $ comparing snd)
f (t1,w1) (t2,w2) (t12,w12) =
printf "%11.2f %-30s\t%11.2f %-30s\t%11.2f %-30s"
w1 (T.unpack t1) w2 (T.unpack t2) w12 (T.unpack t12)
r (_,0) = (T.pack "",0)
r x = x
-- TODO: move this to Bow module
-- within a Bow monad, you should be able to link dimensions to targets
-- provide a getVector variant that does that
-- and/or a context aware vector type
-- maybe change distributional vector to such a type!
-- returns vector contexts sorted in descending order by weights
vectorDims :: V.Vector v => v -> BowM [(Bow.Target,V.Weight)]
vectorDims v = do
ts <- Bow.getContexts
let ws = V.toList v
return $ zip ts ws
|
jsnajder/dsem
|
src/bow-sim.hs
|
bsd-3-clause
| 6,367
| 7
| 24
| 1,688
| 1,921
| 988
| 933
| -1
| -1
|
module Main where
import PropertyTest
import UnitTest
import Test.Framework.Runners.Console (defaultMain)
main = defaultMain $ [UnitTest.tests, PropertyTest.tests]
|
grievejia/njuscript
|
test/Main.hs
|
bsd-3-clause
| 165
| 0
| 7
| 17
| 41
| 26
| 15
| 5
| 1
|
{-# LANGUAGE ViewPatterns #-}
-- | FIXME: Currently there is an exception allowing us to identify
-- finalizers that are called through function pointers if the
-- function pointer is global and has an initializer.
--
-- This needs to be generalized to cover things that are initialized
-- once in the library code with a finalizer. This will be a lower-level
-- analysis that answers the query:
--
-- > initializedOnce :: Value -> Maybe Value
--
-- where the returned value is the single initializer that was sourced
-- within the library. This can be the current simple analysis for
-- globals with initializers. Others will be analyzed in terms of
-- access paths (e.g., Field X of Type Y is initialized once with
-- value Z).
--
-- Linear scan for all stores, recording their access path. Also look
-- at all globals (globals can be treated separately). If an access
-- path gets more than one entry, stop tracking it. Only record
-- stores where the value is some global entity.
--
-- Run this analysis after or before constructing the call graph and
-- initialize the whole-program summary with it. It doesn't need to
-- be computed bottom up as part of the call graph traversal.
module Foreign.Inference.Analysis.IndirectCallResolver (
IndirectCallSummary,
identifyIndirectCallTargets,
indirectCallInitializers,
indirectCallTargets
) where
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashMap.Strict as HM
import Data.HashSet ( HashSet )
import qualified Data.HashSet as HS
import Data.Maybe ( fromMaybe )
import Data.Monoid
import LLVM.Analysis
import LLVM.Analysis.ClassHierarchy
import LLVM.Analysis.PointsTo
import LLVM.Analysis.PointsTo.Andersen
-- import Text.Printf
-- import Debug.Trace
-- debug = flip trace
-- | This isn't a true points-to analysis because it is an
-- under-approximation. However, that is sufficient for this library.
instance PointsToAnalysis IndirectCallSummary where
mayAlias _ _ _ = True
pointsTo = indirectCallInitializers
resolveIndirectCall = indirectCallTargets
data IndirectCallSummary =
ICS { summaryTargets :: Andersen
, resolverCHA :: CHA
, globalInits :: HashMap (Type, Int) (HashSet Value)
}
-- If i is a Load of a global with an initializer (or a GEP of a
-- global with a complex initializer), just use the initializer to
-- determine the points-to set. Obviously this isn't general.
--
-- Eventually, this should call down to a real (field-based) points-to
-- analysis for other values.
indirectCallInitializers :: IndirectCallSummary -> Value -> [Value]
indirectCallInitializers ics v =
case valueContent' v of
FunctionC f -> [toValue f]
ExternalFunctionC ef -> [toValue ef]
InstructionC li@LoadInst { loadAddress = (valueContent' ->
InstructionC GetElementPtrInst { getElementPtrValue = base
, getElementPtrIndices = [ (valueContent -> ConstantC ConstantInt { constantIntValue = 0 })
, (valueContent -> ConstantC ConstantInt { constantIntValue = (fromIntegral -> ix) })
]
})} -> fromMaybe (lookupInst li) $ do
let baseTy = valueType base
globInits <- HM.lookup (baseTy, ix) (globalInits ics)
return $ HS.toList globInits ++ lookupInst li
-- Here, walk the initializer if it isn't a simple integer
-- constant We discard the first index because while the global
-- variable is a pointer type, the initializer is not (because all
-- globals get an extra indirection as r-values)
InstructionC li@LoadInst { loadAddress = (valueContent' ->
ConstantC ConstantValue { constantInstruction = (valueContent' ->
InstructionC GetElementPtrInst { getElementPtrValue = (valueContent' ->
GlobalVariableC GlobalVariable { globalVariableInitializer = Just i })
, getElementPtrIndices = (valueContent -> ConstantC ConstantInt { constantIntValue = 0 }) :ixs
})})} ->
maybe (lookupInst li) (:[]) $ resolveInitializer i ixs
InstructionC li@LoadInst { loadAddress = (valueContent' ->
GlobalVariableC GlobalVariable { globalVariableInitializer = Just i })} ->
case valueContent' i of
-- All globals have some kind of initializer; if it is a zero
-- or constant (non-function) initializer, just ignore it and
-- use the more complex fallback.
ConstantC _ -> lookupInst li
_ -> [i]
InstructionC li@LoadInst { } ->
lookupInst li
InstructionC i -> lookupInst i
_ -> []
where
lookupInst i = pointsTo (summaryTargets ics) (toValue i)
resolveInitializer :: Value -> [Value] -> Maybe Value
resolveInitializer v [] = return (stripBitcasts v)
resolveInitializer v (ix:ixs) = do
intVal <- fromConstantInt ix
case valueContent v of
ConstantC ConstantArray { constantArrayValues = vs } ->
if length vs <= intVal then Nothing else resolveInitializer (vs !! intVal) ixs
ConstantC ConstantStruct { constantStructValues = vs } ->
if length vs <= intVal then Nothing else resolveInitializer (vs !! intVal) ixs
_ -> Nothing
fromConstantInt :: Value -> Maybe Int
fromConstantInt v =
case valueContent v of
ConstantC ConstantInt { constantIntValue = iv } ->
return $ fromIntegral iv
_ -> Nothing
-- | Resolve the targets of an indirect call instruction. This works
-- with both C++ virtual function dispatch and some other common
-- function pointer call patterns. It is unsound and incomplete.
indirectCallTargets :: IndirectCallSummary -> Instruction -> [Value]
indirectCallTargets ics i =
-- If this is a virtual function call (C++), use the virtual
-- function resolver. Otherwise, fall back to the normal function
-- pointer analysis.
maybe fptrTargets (fmap toValue) vfuncTargets
where
vfuncTargets = resolveVirtualCallee (resolverCHA ics) i
fptrTargets =
case i of
CallInst { callFunction = f } ->
indirectCallInitializers ics f
InvokeInst { invokeFunction = f } ->
indirectCallInitializers ics f
_ -> []
-- | Run the initializer analysis: a cheap pass to identify a subset
-- of possible function pointers that object fields can point to.
identifyIndirectCallTargets :: Module -> IndirectCallSummary
identifyIndirectCallTargets m =
ICS (runPointsToAnalysisWith ignoreNonFptr m) (runCHA m) gis
where
ignoreNonFptr = ignoreNonFptrType . valueType
ignoreNonFptrType t =
case t of
TypeFunction _ _ _ -> False
TypePointer t' _ -> ignoreNonFptrType t'
_ -> True
gis = foldr extractGlobalFieldInits mempty (moduleGlobalVariables m)
-- FIXME: One day push this hack down into the andersen analysis.
extractGlobalFieldInits :: GlobalVariable -> HashMap (Type, Int) (HashSet Value) -> HashMap (Type, Int) (HashSet Value)
extractGlobalFieldInits gv acc = fromMaybe acc $ do
ConstantC ConstantStruct { constantStructValues = vs } <- globalVariableInitializer gv
return $ foldr (addFieldInit (valueType gv)) acc (zip [0..] vs)
where
addFieldInit t (ix, v) =
HM.insertWith HS.union (t, ix) (HS.singleton v)
-- Find all initializers of function types to global fields. Make a map
-- of (struct type, field no) -> {initializers}
|
travitch/foreign-inference
|
src/Foreign/Inference/Analysis/IndirectCallResolver.hs
|
bsd-3-clause
| 7,426
| 0
| 31
| 1,691
| 1,353
| 726
| 627
| 97
| 9
|
module Bayesian.Variable(
Domain,
Variable,
VariableSet,
VariableInstantiation,
VariableInstantiationSet,
createVariable,
instantiateVariable,
instantiatedVariable,
instantiation,
variableLabel,
variableSize,
variableSetSize,
variableInstantiations,
variableSetAllInstantiations
) where
import Data.List
import Bayesian.CheckedError
-- | Synonym for a set of Strings.
type Domain = [String]
-- | Synonym for a set of Variables.
type VariableSet = [Variable]
-- | Synonym for a set of Variables Instantiations.
type VariableInstantiationSet = [VariableInstantiation]
-- | Discrete variable on a network.
data Variable = V {
variableLabel :: String,
variableDomain :: Domain
} deriving (Eq, Ord)
instance Show Variable where
show = variableLabel
-- | Instantiated variable.
data VariableInstantiation = I {
instantiatedVariable :: Variable,
instantiation :: String
} deriving (Eq, Ord)
instance Show VariableInstantiation where
show vi =
show (instantiatedVariable vi) ++ "=" ++ instantiation vi
-- | Creates a variable, given its label and domain values.
createVariable :: String -> Domain -> Variable
createVariable label domain = V label (nub domain)
-- | Creates a variable instantiantion, given the variable and the corresponding value.
instantiateVariable :: String -> Variable -> Checked VariableInstantiation
instantiateVariable value variable =
if value `elem` variableDomain variable then
Right $ I variable value
else
Left InvalidVariableInstantiation
-- | Get the set of valid instantiations for a given variable.
variableInstantiations :: Variable -> VariableInstantiationSet
variableInstantiations v = map (I v) $ variableDomain v
-- | Gets the variable domain size (the number of valid instantiations)
variableSize :: Variable -> Int
variableSize = length.variableDomain
-- | Gets the size of a variable set, which is the product of all variables sizes.
variableSetSize :: VariableSet -> Int
variableSetSize = foldr ((*) .variableSize) 1
variableSetAllInstantiations :: [Variable] -> [Domain]
variableSetAllInstantiations = mapM variableDomain
|
sebassimoes/haskell-bayesian
|
src/Bayesian/Variable.hs
|
bsd-3-clause
| 2,125
| 1
| 10
| 338
| 400
| 228
| 172
| 48
| 2
|
-- ^Uses NetCore to implement a Network Address Translator
--
-- Does not work on networks with loops.
module NAT where
import Control.Concurrent
import Control.Monad (forever)
import Frenetic.NetCore
import Frenetic.NetCore.Types
-- import Frenetic.EthernetAddress
import qualified Data.Map as Map
import Data.Word
import Data.Bits
-- Shorthand for hard-coded IP addresses
addr :: (Word8, Word8, Word8, Word8) -> Word32
addr (a, b, c, d) =
let a' = fromIntegral a
b' = fromIntegral b
c' = fromIntegral c
d' = fromIntegral d
in shift a' 24 .|. shift b' 16 .|. shift c' 8 .|. d'
-- MAC address of the gateway box
gateMAC = ethernetAddress 0x00 0x00 0x00 0x00 0x00 0x11
-- Fake "NAT" IP address
fakeIP = ipAddress 10 0 0 101
-- Internal IP traffic
private = NwDst (IPAddressPrefix (IPAddress 0x0a000000) 24)
-- ARP traffic
arp = DlTyp 0x0806
-- Traffic directed to the gateway
toGateway = DlDst gateMAC
-- Port to gateway
gatePort = 3
-- Traffic arriving from the gateway
fromGateway = IngressPort gatePort
-- Returns a pair of two channels: the first is a channel of unique packets
-- (unique tuples of MAC address, location, and source TCP port) that have
-- been sent to the gateway. The second is a channel of policies that
-- implement the packet query---as new tuples are recognized, the policy is
-- refined to exclude more of the same packet.
pktsByLocation :: IO (Chan LocPacket, Chan Policy)
pktsByLocation = do
uniqPktChan <- newChan
polChan <- newChan
(pktChan, act) <- getPkts
let loop :: Map.Map (IPAddress, Port) (EthernetAddress, Predicate) -> IO ()
loop locs = do
(loc, pkt) <- readChan pktChan
let srcMac = pktDlSrc pkt
let srcIp = pktNwSrc pkt
let srcTp = pktTpSrc pkt
case (srcIp, srcTp) of
(Just srcIp, Just srcTp) -> do
case Map.lookup (srcIp, srcTp) locs of
Just (srcMac',_) | srcMac == srcMac' -> do
-- Not a new location, nothing to do.
loop locs
otherwise -> do
-- Either a new outgoing stream or a new MAC address associated
-- with an existing IP (we're kind of simulating ARP here...)
let pred = DlSrc srcMac <&&> NwSrc (IPAddressPrefix srcIp 32)
<&&> TpSrcPort srcTp
let locs' = Map.insert (srcIp, srcTp) (srcMac, pred) locs
writeChan uniqPktChan (loc, pkt)
writeChan polChan $
(DlDst gateMAC) <&&>
(Not (prOr (map snd (Map.elems locs')))) ==> act
loop locs'
otherwise -> loop locs
-- Initially, inspect all packets destined for the gateway.
writeChan polChan (DlDst gateMAC ==> act)
forkIO (loop Map.empty)
return (uniqPktChan, polChan)
-- Implement NAT logic here.
--
-- This version of a NAT simply maps internal (IP, Port) pairs to
-- a unique externap port. We implement this with modification actions
-- on the switch:
--
-- 1: Internal -> External. If dlDst = 0x1, then the packet is bound
-- for the outside world. Replace dlDst with 0x11, nwSrc with fakeIP,
-- and tpSrc with the mapping from (srcIP, tpSrc).
--
-- 2: External -> Internal. Packets arriving on port 3 (i.e. from the
-- outside world) will have dstIP = fakeIP and dstPort = map(srcIP, tpSrc).
-- Replace with the proper IP, port, and MAC.
installHosts :: Chan LocPacket -> IO (Chan Policy)
installHosts pktChan = do
polChan <- newChan
-- Map (SrcIP, SrcPort) to an external port coupled with two policies;
-- for outgoing and incoming packets, respectively.
let loop :: Map.Map (IPAddress, Port) (Port, Policy) -> Port -> IO ()
loop locs pNum = do
(Loc _ inSwitchPort, pkt) <- readChan pktChan
-- Extract the internal source information from the packet.
let srcMac = pktDlSrc pkt
let srcIp = pktNwSrc pkt
let srcTp = pktTpSrc pkt
-- Ignore this packet if the source IP or port aren't set.
case (srcIp, srcTp) of
(Just srcIp, Just srcTp) -> do
-- Map (srcIp, srcTp) to a unique external port, picking a new one if
-- one doesn't already exist.
let (extPort, pNum) = case Map.lookup (srcIp, srcTp) locs of {
Just (ePort, _) -> (ePort, pNum);
Nothing -> (pNum, pNum + 1) }
-- Create the policy that rewrites the internal source on outgoing packets.
let outMod = (modNwSrc fakeIP) {modifyTpSrc = Just extPort}
let outPol = DlSrc srcMac
<&&> DlDst gateMAC
<&&> NwSrc (IPAddressPrefix srcIp 32)
<&&> TpSrcPort srcTp
==> modify [(gatePort, outMod)]
let outPol = DlDst gateMAC ==> forward [gatePort]
-- Create the policy that replaces the internal source on incoming packets.
let inMod = (modNwDst srcIp) {modifyTpDst = Just srcTp, modifyDlSrc = Just srcMac}
let inPol = NwDst (IPAddressPrefix srcIp 32)
<&&> TpDstPort extPort
==> modify [(inSwitchPort, inMod)]
-- Update the map.
let locs' = Map.insert (srcIp, srcTp) (extPort, inPol <+> outPol) locs
-- Push the new policy.
let newPol = foldr1 (<+>) $ map (\(_,(_,pol))->pol) $ Map.toList locs'
writeChan polChan newPol
loop locs' pNum
otherwise -> loop locs pNum
writeChan polChan $ (DlDst gateMAC ==> forward [gatePort]) <+> (NwDst (IPAddressPrefix fakeIP 32) ==> dropPkt)
forkIO (loop Map.empty 1)
return polChan
nonNATPolicy :: Policy
nonNATPolicy =
-- ARP
((arp ==> allPorts unmodified) <+>
-- Internal traffic
(private ==> allPorts unmodified)) <%>
-- Restricted to traffic not destined for the gateway
(Not $ DlDst gateMAC)
nat :: IO (Chan Policy)
nat = do
(uniqPktsChan, queryPolChan) <- pktsByLocation
fwdPolChan <- installHosts uniqPktsChan
bothPolsChan <- both queryPolChan fwdPolChan
polChan <- newChan
forkIO $ forever $ do
(queryPol, fwdPol) <- readChan bothPolsChan
writeChan polChan (nonNATPolicy <+> fwdPol <+> queryPol)
return polChan
main addr = do
putStrLn "I am the NAT!"
polChan <- nat
pktChan <- newChan
-- dynController polChan pktChan
(qchan, q) <- getPkts
let loop = do
packet <- readChan qchan
print packet
let badPolicy = (IngressPort 1 ==> forward [2]) <+>
(IngressPort 2 ==> forward [1]) <+>
(Any ==> q)
forkIO $ forever $ loop
controller addr badPolicy
|
frenetic-lang/netcore-1.0
|
examples/NAT.hs
|
bsd-3-clause
| 6,746
| 0
| 32
| 1,967
| 1,628
| 827
| 801
| -1
| -1
|
module ProveEverywhere.Parser (parsePrompt) where
import Control.Applicative
import Data.Text (Text)
import qualified Data.Text as T
import Text.Parser.Char
import Text.Parser.Combinators
import Text.Parser.Token
import Text.Parsec (parse, ParseError)
import Text.Parsec.Text (Parser)
import ProveEverywhere.Types
parsePrompt :: Text -> Either ParseError CoqtopState
parsePrompt = parse prompt "prompt"
-- | Prompt parser
prompt :: Parser CoqtopState
prompt = do
skipMany $ noneOf "<" -- this may ignore important error messages
between (symbol "<prompt>") (symbol "</prompt>") internal
internal :: Parser CoqtopState
internal = do
current <- token theorem
_ <- symbol "<"
wholeState <- natural
stack <- token theoremStack
theoremState <- natural
_ <- symbol "<"
return CoqtopState
{ promptCurrentTheorem = current
, promptWholeStateNumber = wholeState
, promptTheoremStack = stack
, promptTheoremStateNumber = theoremState
}
-- | Parser for theorem name
theorem :: Parser Text
theorem = T.pack <$> some (alphaNum <|> oneOf "_'")
-- | Parses |theorem1|theorem2| ... |theoremn| and return list of theorem names
theoremStack :: Parser [Text]
theoremStack = between (char '|') (char '|') $ sepBy' theorem (char '|')
where
sepBy' p sep = sepBy1' p sep <|> pure []
sepBy1' p sep = (:) <$> p <*> many (try (sep *> p))
|
prove-everywhere/server
|
src/ProveEverywhere/Parser.hs
|
bsd-3-clause
| 1,405
| 0
| 12
| 281
| 395
| 208
| 187
| 35
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Parser.GeomStaticMesh where
import Data.Attoparsec.Text
import Control.Applicative (liftA3)
import Data.Char (isSpace)
import Data.Array.IArray (listArray)
import Types.GeomStaticMesh
import Parser.Util
-- The following parsers parse the corresponding
-- fields in the GeomStaticMesh plugin
vertices :: Parser Vertices
vertices = string "vertices=" *> arrayVector
faces :: Parser Faces
faces = string "faces=" *> listInt
normals :: Parser Normals
normals = string "normals=" *> arrayNormal
faceNormals :: Parser FaceNormals
faceNormals = string "faceNormals=" *> listInt
mapChannels :: Parser MapChannels
mapChannels = string "map_channels=" *>
(listOf "List" $ do
_ <- string "List"
parens $
liftA3 (,,) decimal
(comma *> listVector)
(comma *> listInt))
edgeVisibility :: Parser EdgeVisibility
edgeVisibility = string "edge_visibility=" *> listInt
faceMtlIDs :: Parser FaceMtlIDs
faceMtlIDs = string "face_mtlIDs=" *> listInt
smoothDerivs :: Parser SmoothDerivs
smoothDerivs = string "smooth_derivs=" *> listOf "List" decimal
dynamicGeometry :: Parser DynamicGeometry
dynamicGeometry = string "dynamic_geometry=" *> fmap (== (1::Int)) decimal
geomStaticMesh :: Parser GeomStaticMesh
geomStaticMesh = do
_ <- string "GeomStaticMesh "
name <- takeTill isSpace
skipSpace
braces $
GeomStaticMesh name <$>
field (listArray (1, 0) []) vertices <*>
field [] faces <*>
field (listArray (1, 0) []) normals <*>
field [] faceNormals <*>
field [] mapChannels <*>
field [] edgeVisibility <*>
field [] faceMtlIDs <*>
field [] smoothDerivs <*>
field False dynamicGeometry
|
leohaskell/parseVRS
|
src/Parser/GeomStaticMesh.hs
|
bsd-3-clause
| 1,741
| 0
| 19
| 352
| 481
| 244
| 237
| 48
| 1
|
module Main (
main
) where
import qualified Cgs (main)
main :: IO ()
main = Cgs.main
|
thomaseding/cgs
|
src/Main.hs
|
bsd-3-clause
| 95
| 0
| 6
| 27
| 35
| 21
| 14
| 5
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module PeerReview.SubmissionRepo.Testing
( repo
) where
import PeerReview.Types
repo :: SubmissionRepo
repo = SubmissionRepo byId forTask forUser getAll
testSubs :: [Submission]
testSubs =
[ Submission "1" "user1" "task1"
, Submission "2" "user2" "task1"
, Submission "3" "user2" "task2"
]
byId :: SubmissionID -> IO (Maybe SubmissionDetails)
byId _ = return $ Just (SubmissionDetails "1" "2" ["3"] "wat")
forTask :: TaskID -> IO [Submission]
forTask _ = return []
forUser :: UserID -> IO [Submission]
forUser uid = return $ filter (\ s -> uid == sSender s) testSubs
getAll :: IO [Submission]
getAll = return testSubs
|
keveri/peer-review-service
|
test/PeerReview/SubmissionRepo/Testing.hs
|
bsd-3-clause
| 695
| 0
| 10
| 142
| 222
| 117
| 105
| 19
| 1
|
{-|
Module : Riff.Prelude
Description : Custom Prelude
Copyright : (c) 2019 Steven Meunier
License : BSD-style (see the file LICENSE)
Welcome to your custom Prelude
Export here everything that should always be in your library scope
For more info on what is exported by Protolude check:
https://github.com/sdiehl/protolude/blob/master/Symbols.md
-}
module Riff.Prelude
( module Exports
, id
, String
)
where
import Protolude as Exports
import Data.Function ( id )
type String = [Char]
|
solaryeti/riff
|
src/Riff/Prelude.hs
|
bsd-3-clause
| 562
| 0
| 5
| 151
| 43
| 29
| 14
| 7
| 0
|
module Main where
import Lib
main :: IO ()
main = writeFile "/tmp/ipotenuse.txt" . show . triplesLessThan $ 10^7
|
meditans/ipotenusa
|
app/Main.hs
|
bsd-3-clause
| 115
| 0
| 9
| 21
| 41
| 22
| 19
| 4
| 1
|
module Main where
import WYAScheme.Parser
main :: IO ()
main = putStrLn "Stub"
|
timcowlishaw/write_yourself_a_scheme
|
src/Main.hs
|
bsd-3-clause
| 85
| 0
| 6
| 19
| 27
| 15
| 12
| 4
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ViewPatterns #-}
module Mapnik.Bindings.VectorTile.Datasource where
import Mapnik.Bindings.VectorTile.Types
import Mapnik.Bindings.Types (Datasource(..), mapnikCtx)
import qualified Mapnik.Bindings.Datasource as Datasource
import Mapnik.Bindings.Util (decodeUtf8Keys)
import Mapnik.Bindings (MapnikError)
import qualified Mapnik.Bindings.Cpp as C
import Control.Exception
import Data.IORef
import Data.ByteString (packCStringLen)
import Foreign.Ptr
import Foreign.Storable
import Foreign.C.Types
import Foreign.C.String
import Data.Text (Text)
C.context mapnikCtx
C.include "hs_vector_tile_datasource.hpp"
C.using "namespace mapnik"
C.using "namespace mapnik::vector_tile_impl"
type LayerName = Text
-- | Loads a 'Datasource' for features withing an 'XYZ' tileindex for each
-- layer in a 'MVTile'
layerDatasources
:: MVTile
-> XYZ
-> IO (Either MapnikError [(LayerName, Datasource)])
layerDatasources (MVTile pbf) xyz = try $ do
ref <- newIORef []
let cb :: CString -> CInt -> Ptr Datasource -> IO ()
cb name len p = do ds <- Datasource.unsafeNew (flip poke p)
name' <- packCStringLen (name, fromIntegral len)
modifyIORef' ref ((name',ds):)
[C.catchBlock|
auto const buf = std::make_shared<std::string>($bs-ptr:pbf, $bs-len:pbf);
protozero::pbf_reader tile(*buf);
while (tile.next(3)) { // Iterate all layers (msgid=3)
protozero::pbf_reader layer = tile.get_message();
auto ds = std::make_shared<hs_tile_datasource_pbf>(
buf, layer, $(uint64_t x), $(uint64_t y), $(uint64_t z)
);
auto const& name = ds->get_name();
$fun:(void(*cb)(char *,int, datasource_ptr*))(
const_cast<char*>(name.data()), name.size(), new datasource_ptr(ds)
);
}
|]
reverse <$> (decodeUtf8Keys "layerDatasources" =<< readIORef ref)
where XYZ (fromIntegral->x) (fromIntegral->y) (fromIntegral->z) = xyz
|
albertov/hs-mapnik
|
vectortile/src/Mapnik/Bindings/VectorTile/Datasource.hs
|
bsd-3-clause
| 2,122
| 0
| 16
| 478
| 395
| 217
| 178
| 36
| 1
|
<ESC>:set shiftwidth=8<CR>amain = do
print "hello"
|
itchyny/vim-haskell-indent
|
test/do/main_do_sw8.in.hs
|
mit
| 51
| 5
| 9
| 6
| 36
| 15
| 21
| -1
| -1
|
{-- snippet all --}
-- posixtime.hs
import System.Posix.Files
import System.Time
import System.Posix.Types
-- | Given a path, returns (atime, mtime, ctime)
getTimes :: FilePath -> IO (ClockTime, ClockTime, ClockTime)
getTimes fp =
do stat <- getFileStatus fp
return (toct (accessTime stat),
toct (modificationTime stat),
toct (statusChangeTime stat))
-- | Convert an EpochTime to a ClockTime
toct :: EpochTime -> ClockTime
toct et =
TOD (truncate (toRational et)) 0
{-- /snippet all --}
|
binesiyu/ifl
|
examples/ch20/posixtime.hs
|
mit
| 536
| 0
| 11
| 121
| 138
| 73
| 65
| 12
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : Artem Chirkin
-- License : MIT
--
-- Maintainer : Artem Chirkin
-- Stability : experimental
--
-- An executable for sending and receiving simple Luci messages.
--
-----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Aeson as JSON
import qualified Data.Text as Text
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BSLC
import Control.Concurrent.QSem
import Luci.Connect
import Luci.Connect.Base
import Luci.Messages
import System.Environment (getArgs)
import Data.List (stripPrefix)
import Data.Maybe (isNothing)
import Control.Monad (when)
import Data.Conduit
main :: IO ()
main = do
args <- getArgs
let sets = setSettings args RunSettings
{ host = "127.0.1.1"
, port = 7654
, logLevel = LevelInfo
, command = Nothing
}
when (isNothing $ command sets) $
putStrLn "Luci-console app. Usage:\n\
\luci-console [args..]\n\
\Parameters:\n\
\\tport=x - choose port (default: 7654)\n\
\\thost=a.b.c.d - choose host (default: 127.0.1.1)\n\
\\tloglevel=lvl - choose logging level (default: info)\n\
\\t possible levels: debug, info, warn, error\n\
\\t-c '<command>' - send a single JSON message to Luci and disconnect\n\
\\nType JSON message headers and press enter to send them."
runLuciProgram () (logLevel sets) $ luciChannels (port sets)
(Just $ host sets)
(case command sets of
Nothing -> return (awaitForever logResponse, source)
Just msg -> singleAction msg
)
return ()
where
logResponse (MessageHeader h, _) = liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
source = do
val <- fmap eitherDecodeStrict' . liftIO $ BS.getLine
case val of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, [])
source
setSettings [] s = s
setSettings (par:xs) s = case stripPrefix "port=" par of
Just n -> setSettings xs s{port = read n}
Nothing -> case stripPrefix "host=" par of
Just h -> setSettings xs s{host = BSC.pack h}
Nothing -> case stripPrefix "loglevel=" par of
Just "debug" -> setSettings xs s{logLevel = LevelDebug}
Just "info" -> setSettings xs s{logLevel = LevelInfo}
Just "warn" -> setSettings xs s{logLevel = LevelWarn}
Just "warning" -> setSettings xs s{logLevel = LevelWarn}
Just "error" -> setSettings xs s{logLevel = LevelError}
Just h -> setSettings xs s{logLevel = LevelOther $ Text.pack h}
Nothing -> if "-c" == par
then s{command = Just . BSC.pack $ unwords xs}
else setSettings xs s
singleAction :: ByteString -> LuciProgram () (Sink LuciMessage (LuciProgram ()) (), Source (LuciProgram ()) LuciMessage)
singleAction msg = do
sem <- liftIO $ newQSem 0
return (waitResults sem,source sem)
where
waitResults sem = do
m <- await
case m of
Nothing -> liftIO $ putStrLn "channel closed"
Just lm@(h,_) -> do
liftIO $ do
putStr "[Server Message] "
BSLC.putStrLn $ encode h
case parseMessage lm of
JSON.Success MsgResult{} -> liftIO (signalQSem sem)
JSON.Success MsgError{} -> liftIO (signalQSem sem)
_ -> waitResults sem
source sem = case eitherDecodeStrict' msg of
Left err -> liftIO $ putStrLn err
Right h -> yield (h, []) >> liftIO (waitQSem sem)
data RunSettings = RunSettings
{ host :: ByteString
, port :: Int
, logLevel :: LogLevel
, command :: Maybe ByteString
}
|
achirkin/qua-kit
|
libs/hs/luci-connect/examples/LuciConsole.hs
|
mit
| 4,261
| 0
| 21
| 1,349
| 1,073
| 550
| 523
| 81
| 13
|
{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-unused-do-bind #-}
module HaObj where
import Control.Monad
import Data.List (partition,unzip7)
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
import System.IO (hGetContents, IOMode (..),withFile)
import Text.Parsec
--TODO switch to arrays/vectors
data V3 = V3 !Float !Float !Float deriving (Eq,Read,Show)
--TODO incomplete, at least need to add texture maps
data Material = Material { mNs :: !Float --specular exponent
, mKa :: !V3 --ambient color
, mKd :: !V3 --diffuse color
, mKs :: !V3 --specular color
, mNi :: !Float --optical density (refraction)
, mD :: !Float --dissolved (halo factor)
, mIllum :: !Int --illumination model
} deriving (Eq,Read,Show)
data Mesh = Mesh { mVertices :: [V3]
, mNormals :: [V3]
, mTextures :: [V3]
, mParamSpaceVs :: [V3]
, mFaces :: [(Material,[Face])]
, mSmoothFaces :: [(Material,[Face])]
, mLines :: [(Int,Int)]
} deriving (Eq,Read,Show)
--material index and vertices
data Face = Face [FaceV] deriving (Eq,Read,Show)
data FaceV = FaceV { fvVertex :: !Int
, fvTexture :: !Int
, fvNormal :: !Int
} deriving (Eq,Show,Read)
makeScene :: [(String, Material)]
-> [(String,[V3],[V3],[V3],[V3],[(String,Int,[Face])],[(Int,Int)])]
-> Mesh
makeScene mtls0 objs0 =
let mtls = M.fromList mtls0
(_,vs,ns,ts,pss,mfaces,ls) = unzip7 objs0
mfaces' = map (\(m,s,fs) -> (findMaterial mtls m,s,fs)) (concat mfaces)
(notSmooth,smooth) = partition (\(_,s,_) -> s == 0) mfaces'
notSmooth' = map dropMid notSmooth
smooth' = map dropMid smooth
in Mesh (concat vs) (concat ns) (concat ts) (concat pss) notSmooth' smooth' (concat ls)
findMaterial :: (Ord a, Show a) => Map a b -> a -> b
findMaterial dict m = fromMaybe (error (show m ++ " not found")) (M.lookup m dict)
dropMid :: (a,b,c) -> (a,c)
dropMid (a,_,c) = (a,c)
{- parses .obj files -}
parseObj fname = (fmap . fmap) (uncurry makeScene) (parseObj' fname)
{- if you don't want to use the types -}
parseObj' fname = withFile fname ReadMode (\h -> do
input <- hGetContents h
case runParser readObj () fname input of
Left e -> return $ Left e
Right (mtllib,meshes) -> withFile mtllib ReadMode (\h2 -> do
mtlInput <- hGetContents h2
case runParser readMtl () mtllib mtlInput of
Left e -> return $ Left e
Right mtls -> return $ Right (mtls,meshes)))
readObj = do
skipMany ignorable
mtllib <- string "mtllib" >> spaces >> manyTill anyChar endOfLine
meshes <- manyTill (skipMany ignorable >> mesh) eof
return (mtllib,meshes)
mesh = do
char 'o'
spaces
name <- manyTill anyChar endOfLine
vs <- many (try vertex)
ts <- many (try texture)
ns <- many (try normal)
pss <- many (try parameterSpace)
mfaces <- many materialAndFaces
ls <- many (try line)
return (name,vs,ns,ts,pss,mfaces,ls)
vertex = char 'v' >> spaces >> parseV3
normal = string "vn" >> spaces >> parseV3
texture = string "vt" >> spaces >> parseV3'
line = do
string "l"
v1 <- spaces >> uint
v2 <- spaces >> uint
endOfLine
return (v1,v2)
parameterSpace = string "vp" >> spaces >> parseV3''
materialAndFaces = do
mtl <- string "usemtl" >> spaces >> manyTill anyChar endOfLine
s <- try (string "s" >> spaces >> (try (string "off" >> return 0) <|> uint))
<|> return 0
faces <- skipMany endOfLine >> many1 ngonFace
return (mtl, s, faces)
ngonFace = do
char 'f'
spaces
vs <- sepEndBy faceEl spaces
return (Face vs)
faceEl = do
v <- uint
vt <- try (char '/' >> uint) <|>
return (-1)
vn <- try (char '/' >> uint) <|>
try (char '/' >> char '/' >> uint) <|>
return (-1)
return (FaceV v vt vn)
vertexPair = do
v1 <- uint
v2 <- char '/' >> uint
return (v1,v2)
readMtl = do
skipMany ignorable
manyTill (do skipMany ignorable
m <- material
skipMany ignorable
return m) eof
comments = char '#' >> manyTill anyToken endOfLine >> return ()
ignorable = comments <|> void endOfLine
material = do
string "newmtl"
spaces
name <- manyTill anyChar endOfLine
ns <- parseNs
endOfLine
ka <- parseKa
kd <- parseKd
ks <- parseKs
ni <- try parseNi <* endOfLine <|> return 1.0
--endOfLine
d <- parseD
endOfLine
illum <- parseIllum
return (name,Material ns ka kd ks ni d illum)
parseNs = string "Ns" >> spaces >> float
parseKa = string "Ka" >> spaces >> parseV3
parseKd = string "Kd" >> spaces >> parseV3
parseKs = string "Ks" >> spaces >> parseV3
parseNi = string "Ni" >> spaces >> float
parseD = string "d" >> spaces >> float
parseIllum = string "illum" >> spaces >> uint
parseV3 = do
xs <- sepEndBy float spaces
case xs of
(r:g:b:[]) -> return (V3 r g b)
_ -> fail "unexpected number of floats"
parseV3' = do
xs <- sepEndBy float spaces
case xs of
(u:v:[]) -> return (V3 u v 0)
(u:v:w:[]) -> return (V3 u v w)
_ -> fail "unexpected number of floats"
parseV3'' = do
xs <- sepEndBy float spaces
case xs of
(u:[]) -> return (V3 u 0 0)
(u:v:[]) -> return (V3 u v 0)
(u:v:w:[]) -> return (V3 u v w)
_ -> fail "unexpected number of floats"
(<++>) a b = (++) <$> a <*> b
(<:>) a b = (:) <$> a <*> b
number = many1 digit
plus = char '+' *> number
minus = char '-' <:> number
integer = plus <|> minus <|> number
uint = let rd = read :: String -> Int in rd <$> number
float = fmap rd $ integer <++> decimal <++> exponent
where rd = read :: String -> Float
decimal = option "" $ char '.' <:> number
exponent = option "" $ oneOf "eE" <:> integer
|
jrraymond/haobj
|
src/HaObj.hs
|
mit
| 6,053
| 0
| 23
| 1,742
| 2,415
| 1,234
| 1,181
| 189
| 4
|
{-- snippet odd --}
isOdd n = mod n 2 == 1
{-- /snippet odd --}
|
binesiyu/ifl
|
examples/ch02/RoundToEven.hs
|
mit
| 64
| 0
| 6
| 16
| 20
| 10
| 10
| 1
| 1
|
module Interpreter (
Interpreter
, eval
, withInterpreter
) where
import System.IO
import System.Process
import System.Exit
import Control.Monad(when)
import Control.Exception (bracket)
import Data.Char
import Data.List
import GHC.Paths (ghc)
-- | Truly random marker, used to separate expressions.
--
-- IMPORTANT: This module relies upon the fact that this marker is unique. It
-- has been obtained from random.org. Do not expect this module to work
-- properly, if you reuse it for any purpose!
marker :: String
marker = show "dcbd2a1e20ae519a1c7714df2859f1890581d57fac96ba3f499412b2f5c928a1"
data Interpreter = Interpreter {
hIn :: Handle
, hOut :: Handle
, process :: ProcessHandle
}
newInterpreter :: [String] -> IO Interpreter
newInterpreter flags = do
(Just stdin_, Just stdout_, Nothing, processHandle ) <- createProcess $ (proc ghc myFlags) {std_in = CreatePipe, std_out = CreatePipe, std_err = UseHandle stdout}
setMode stdin_
setMode stdout_
return Interpreter {hIn = stdin_, hOut = stdout_, process = processHandle}
where
myFlags = ["-v0", "--interactive", "-ignore-dot-ghci"] ++ flags
setMode handle = do
hSetBinaryMode handle False
hSetBuffering handle LineBuffering
hSetEncoding handle utf8
-- | Run an interpreter session.
--
-- Example:
--
-- >>> withInterpreter [] $ \i -> eval i "23 + 42"
-- "65\n"
withInterpreter
:: [String] -- ^ List of flags, passed to GHC
-> (Interpreter -> IO a) -- ^ Action to run
-> IO a -- ^ Result of action
withInterpreter flags = bracket (newInterpreter flags) closeInterpreter
closeInterpreter :: Interpreter -> IO ()
closeInterpreter repl = do
hClose $ hIn repl
-- It is crucial not to close `hOut` before calling `waitForProcess`,
-- otherwise ghci may not cleanly terminate on SIGINT (ctrl-c) and hang
-- around consuming 100% CPU. This happens when ghci tries to print
-- something to stdout in its signal handler (e.g. when it is blocked in
-- threadDelay it writes "Interrupted." on SIGINT).
e <- waitForProcess $ process repl
hClose $ hOut repl
when (e /= ExitSuccess) $ error $ "Interpreter exited with an error: " ++ show e
return ()
putExpression :: Interpreter -> String -> IO ()
putExpression repl e = do
hPutStrLn stdin_ $ filterExpression e
hPutStrLn stdin_ marker
hFlush stdin_
return ()
where
stdin_ = hIn repl
-- | Fail on unterminated multiline commands.
--
-- Examples:
--
-- >>> filterExpression ""
-- ""
--
-- >>> filterExpression "foobar"
-- "foobar"
--
-- >>> filterExpression ":{"
-- "*** Exception: unterminated multiline command
--
-- >>> filterExpression " :{ "
-- "*** Exception: unterminated multiline command
--
-- >>> filterExpression " :{ \nfoobar"
-- "*** Exception: unterminated multiline command
--
-- >>> filterExpression " :{ \nfoobar \n :} "
-- " :{ \nfoobar \n :} "
--
filterExpression :: String -> String
filterExpression e =
case lines e of
[] -> e
l -> if firstLine == ":{" && lastLine /= ":}" then fail_ else e
where
firstLine = strip $ head l
lastLine = strip $ last l
fail_ = error "unterminated multiline command"
where
strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse
getResult :: Interpreter -> IO String
getResult repl = do
line <- hGetLine stdout_
if isSuffixOf marker line
then
return $ stripMarker line
else do
result <- getResult repl
return $ line ++ '\n' : result
where
stdout_ = hOut repl
stripMarker l = take (length l - length marker) l
-- | Evaluate an expresion
eval
:: Interpreter
-> String -- Expression
-> IO String -- Result
eval repl expr = do
putExpression repl expr
getResult repl
|
sakari/doctest-haskell
|
src/Interpreter.hs
|
mit
| 3,808
| 0
| 12
| 844
| 820
| 432
| 388
| 75
| 3
|
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Qi.Util.DDB where
import Control.Lens hiding (view, (.=))
import Data.Aeson
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as SHM
import Data.Text (Text)
import qualified Data.Text as T
import Network.AWS.DynamoDB (AttributeValue, attributeValue, avN, avS)
import Protolude
class FromAttrs a where
parseAttrs
:: HashMap Text AttributeValue
-> Result a
class ToAttrs a where
toAttrs
:: a
-> HashMap Text AttributeValue
parseStringAttr
:: Text
-> HashMap Text AttributeValue
-> Result Text
parseStringAttr attrName hm =
maybe
(Error $ "could not parse attribute: " ++ T.unpack attrName)
return
$ (^.avS) =<< SHM.lookup attrName hm
parseNumberAttr
:: Text
-> HashMap Text AttributeValue
-> Result Int
parseNumberAttr attrName hm =
maybe
(Error $ "could not parse attribute: " ++ T.unpack attrName)
return
$ ((readMaybe . toS) <=< (^.avN)) =<< SHM.lookup attrName hm
stringAttr
:: Text
-> AttributeValue
stringAttr s = attributeValue & avS .~ Just s
numberAttr
:: Int
-> AttributeValue
numberAttr n = attributeValue & avN .~ Just (T.pack $ show n)
|
qmuli/qmuli
|
library/Qi/Util/DDB.hs
|
mit
| 1,320
| 0
| 11
| 339
| 364
| 197
| 167
| 45
| 1
|
module System.Process.Utils
( withProcess
) where
import qualified Control.Exception as E
import System.IO (Handle, hClose)
import System.Process
import Lamdu.Prelude
withProcess ::
CreateProcess ->
((Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO a) ->
IO a
withProcess createProc =
E.bracket
(createProcess createProc)
(E.uninterruptibleMask_ . close)
where
close (_, mStdout, mStderr, handle) =
do
_ <- [mStdout, mStderr] & traverse . traverse %%~ hClose
terminateProcess handle
waitForProcess handle
|
lamdu/lamdu
|
src/System/Process/Utils.hs
|
gpl-3.0
| 648
| 0
| 13
| 195
| 179
| 97
| 82
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.S3.UploadPart
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Uploads a part in a multipart upload.
--
-- Note: After you initiate multipart upload and upload one or more parts, you
-- must either complete or abort multipart upload in order to stop getting
-- charged for storage of the uploaded parts. Only after you either complete or
-- abort multipart upload, Amazon S3 frees up the parts storage and stops
-- charging you for the parts storage.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/UploadPart.html>
module Network.AWS.S3.UploadPart
(
-- * Request
UploadPart
-- ** Request constructor
, uploadPart
-- ** Request lenses
, upBody
, upBucket
, upContentLength
, upContentMD5
, upKey
, upPartNumber
, upRequestPayer
, upSSECustomerAlgorithm
, upSSECustomerKey
, upSSECustomerKeyMD5
, upUploadId
-- * Response
, UploadPartResponse
-- ** Response constructor
, uploadPartResponse
-- ** Response lenses
, uprETag
, uprRequestCharged
, uprSSECustomerAlgorithm
, uprSSECustomerKeyMD5
, uprSSEKMSKeyId
, uprServerSideEncryption
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
data UploadPart = UploadPart
{ _upBody :: RqBody
, _upBucket :: Text
, _upContentLength :: Maybe Int
, _upContentMD5 :: Maybe Text
, _upKey :: Text
, _upPartNumber :: Int
, _upRequestPayer :: Maybe RequestPayer
, _upSSECustomerAlgorithm :: Maybe Text
, _upSSECustomerKey :: Maybe (Sensitive Text)
, _upSSECustomerKeyMD5 :: Maybe Text
, _upUploadId :: Text
} deriving (Show)
-- | 'UploadPart' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'upBody' @::@ 'RqBody'
--
-- * 'upBucket' @::@ 'Text'
--
-- * 'upContentLength' @::@ 'Maybe' 'Int'
--
-- * 'upContentMD5' @::@ 'Maybe' 'Text'
--
-- * 'upKey' @::@ 'Text'
--
-- * 'upPartNumber' @::@ 'Int'
--
-- * 'upRequestPayer' @::@ 'Maybe' 'RequestPayer'
--
-- * 'upSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'upSSECustomerKey' @::@ 'Maybe' 'Text'
--
-- * 'upSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'upUploadId' @::@ 'Text'
--
uploadPart :: RqBody -- ^ 'upBody'
-> Text -- ^ 'upBucket'
-> Text -- ^ 'upKey'
-> Int -- ^ 'upPartNumber'
-> Text -- ^ 'upUploadId'
-> UploadPart
uploadPart p1 p2 p3 p4 p5 = UploadPart
{ _upBody = p1
, _upBucket = p2
, _upKey = p3
, _upPartNumber = p4
, _upUploadId = p5
, _upContentLength = Nothing
, _upContentMD5 = Nothing
, _upSSECustomerAlgorithm = Nothing
, _upSSECustomerKey = Nothing
, _upSSECustomerKeyMD5 = Nothing
, _upRequestPayer = Nothing
}
upBody :: Lens' UploadPart RqBody
upBody = lens _upBody (\s a -> s { _upBody = a })
upBucket :: Lens' UploadPart Text
upBucket = lens _upBucket (\s a -> s { _upBucket = a })
-- | Size of the body in bytes. This parameter is useful when the size of the body
-- cannot be determined automatically.
upContentLength :: Lens' UploadPart (Maybe Int)
upContentLength = lens _upContentLength (\s a -> s { _upContentLength = a })
upContentMD5 :: Lens' UploadPart (Maybe Text)
upContentMD5 = lens _upContentMD5 (\s a -> s { _upContentMD5 = a })
upKey :: Lens' UploadPart Text
upKey = lens _upKey (\s a -> s { _upKey = a })
-- | Part number of part being uploaded.
upPartNumber :: Lens' UploadPart Int
upPartNumber = lens _upPartNumber (\s a -> s { _upPartNumber = a })
upRequestPayer :: Lens' UploadPart (Maybe RequestPayer)
upRequestPayer = lens _upRequestPayer (\s a -> s { _upRequestPayer = a })
-- | Specifies the algorithm to use to when encrypting the object (e.g., AES256,
-- aws:kms).
upSSECustomerAlgorithm :: Lens' UploadPart (Maybe Text)
upSSECustomerAlgorithm =
lens _upSSECustomerAlgorithm (\s a -> s { _upSSECustomerAlgorithm = a })
-- | Specifies the customer-provided encryption key for Amazon S3 to use in
-- encrypting data. This value is used to store the object and then it is
-- discarded; Amazon does not store the encryption key. The key must be
-- appropriate for use with the algorithm specified in the
-- x-amz-server-side-encryption-customer-algorithm header. This must be the
-- same encryption key specified in the initiate multipart upload request.
upSSECustomerKey :: Lens' UploadPart (Maybe Text)
upSSECustomerKey = lens _upSSECustomerKey (\s a -> s { _upSSECustomerKey = a }) . mapping _Sensitive
-- | Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321.
-- Amazon S3 uses this header for a message integrity check to ensure the
-- encryption key was transmitted without error.
upSSECustomerKeyMD5 :: Lens' UploadPart (Maybe Text)
upSSECustomerKeyMD5 =
lens _upSSECustomerKeyMD5 (\s a -> s { _upSSECustomerKeyMD5 = a })
-- | Upload ID identifying the multipart upload whose part is being uploaded.
upUploadId :: Lens' UploadPart Text
upUploadId = lens _upUploadId (\s a -> s { _upUploadId = a })
data UploadPartResponse = UploadPartResponse
{ _uprETag :: Maybe Text
, _uprRequestCharged :: Maybe RequestCharged
, _uprSSECustomerAlgorithm :: Maybe Text
, _uprSSECustomerKeyMD5 :: Maybe Text
, _uprSSEKMSKeyId :: Maybe (Sensitive Text)
, _uprServerSideEncryption :: Maybe ServerSideEncryption
} deriving (Eq, Read, Show)
-- | 'UploadPartResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'uprETag' @::@ 'Maybe' 'Text'
--
-- * 'uprRequestCharged' @::@ 'Maybe' 'RequestCharged'
--
-- * 'uprSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'uprSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'uprSSEKMSKeyId' @::@ 'Maybe' 'Text'
--
-- * 'uprServerSideEncryption' @::@ 'Maybe' 'ServerSideEncryption'
--
uploadPartResponse :: UploadPartResponse
uploadPartResponse = UploadPartResponse
{ _uprServerSideEncryption = Nothing
, _uprETag = Nothing
, _uprSSECustomerAlgorithm = Nothing
, _uprSSECustomerKeyMD5 = Nothing
, _uprSSEKMSKeyId = Nothing
, _uprRequestCharged = Nothing
}
-- | Entity tag for the uploaded object.
uprETag :: Lens' UploadPartResponse (Maybe Text)
uprETag = lens _uprETag (\s a -> s { _uprETag = a })
uprRequestCharged :: Lens' UploadPartResponse (Maybe RequestCharged)
uprRequestCharged =
lens _uprRequestCharged (\s a -> s { _uprRequestCharged = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header confirming the encryption
-- algorithm used.
uprSSECustomerAlgorithm :: Lens' UploadPartResponse (Maybe Text)
uprSSECustomerAlgorithm =
lens _uprSSECustomerAlgorithm (\s a -> s { _uprSSECustomerAlgorithm = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header to provide round trip
-- message integrity verification of the customer-provided encryption key.
uprSSECustomerKeyMD5 :: Lens' UploadPartResponse (Maybe Text)
uprSSECustomerKeyMD5 =
lens _uprSSECustomerKeyMD5 (\s a -> s { _uprSSECustomerKeyMD5 = a })
-- | If present, specifies the ID of the AWS Key Management Service (KMS) master
-- encryption key that was used for the object.
uprSSEKMSKeyId :: Lens' UploadPartResponse (Maybe Text)
uprSSEKMSKeyId = lens _uprSSEKMSKeyId (\s a -> s { _uprSSEKMSKeyId = a }) . mapping _Sensitive
-- | The Server-side encryption algorithm used when storing this object in S3
-- (e.g., AES256, aws:kms).
uprServerSideEncryption :: Lens' UploadPartResponse (Maybe ServerSideEncryption)
uprServerSideEncryption =
lens _uprServerSideEncryption (\s a -> s { _uprServerSideEncryption = a })
instance ToPath UploadPart where
toPath UploadPart{..} = mconcat
[ "/"
, toText _upBucket
, "/"
, toText _upKey
]
instance ToQuery UploadPart where
toQuery UploadPart{..} = mconcat
[ "partNumber" =? _upPartNumber
, "uploadId" =? _upUploadId
]
instance ToHeaders UploadPart where
toHeaders UploadPart{..} = mconcat
[ "Content-Length" =: _upContentLength
, "Content-MD5" =: _upContentMD5
, "x-amz-server-side-encryption-customer-algorithm" =: _upSSECustomerAlgorithm
, "x-amz-server-side-encryption-customer-key" =: _upSSECustomerKey
, "x-amz-server-side-encryption-customer-key-MD5" =: _upSSECustomerKeyMD5
, "x-amz-request-payer" =: _upRequestPayer
]
instance ToBody UploadPart where
toBody = toBody . _upBody
instance AWSRequest UploadPart where
type Sv UploadPart = S3
type Rs UploadPart = UploadPartResponse
request = stream PUT
response = headerResponse $ \h -> UploadPartResponse
<$> h ~:? "ETag"
<*> h ~:? "x-amz-request-charged"
<*> h ~:? "x-amz-server-side-encryption-customer-algorithm"
<*> h ~:? "x-amz-server-side-encryption-customer-key-MD5"
<*> h ~:? "x-amz-server-side-encryption-aws-kms-key-id"
<*> h ~:? "x-amz-server-side-encryption"
|
romanb/amazonka
|
amazonka-s3/gen/Network/AWS/S3/UploadPart.hs
|
mpl-2.0
| 10,455
| 0
| 19
| 2,471
| 1,549
| 917
| 632
| 155
| 1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : DiagramTextItem.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:47
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module DiagramScene.DiagramTextItem(
QdiagramTextItem(..)
,dtItemChange
,dtFocusOutEvent
,dtMouseDoubleClickEvent
,editorLostFocus
) where
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core
import Qtc.Classes.Gui
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Core
import Qtc.ClassTypes.Gui
import Qtc.Core.Base
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
import Qtc.Enums.Core.Qt
import Qtc.Gui.QGraphicsItem
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Gui.QGraphicsTextItem
import Qtc.Gui.QGraphicsTextItem_h
import Qtc.Gui.QGraphicsScene
import Qtc.Gui.QGraphicsSceneMouseEvent
import Qtc.Gui.QTextCursor
import Data.IORef
import DiagramScene.DiagramTextItemType
import DiagramScene.DiagramSceneType
class QqDiagramTextItem x1 where
qDiagramTextItem :: x1 -> IO QDiagramTextItem
instance QqDiagramTextItem () where
qDiagramTextItem () = qSubClass $ qGraphicsTextItem ()
instance QqDiagramTextItem (QGraphicsItem a) where
qDiagramTextItem (x1) = qSubClass $ qGraphicsTextItem (x1)
instance QqDiagramTextItem (QGraphicsItem a, QGraphicsScene b) where
qDiagramTextItem (x1, x2) = qSubClass $ qGraphicsTextItem (x1, x2)
class QdiagramTextItem x1 where
diagramTextItem :: x1 -> IO QDiagramTextItem
instance QdiagramTextItem (()) where
diagramTextItem ()
= do
dtio <- qDiagramTextItem ()
diagramTextItem_s dtio
instance QdiagramTextItem (QGraphicsItem a) where
diagramTextItem (x1)
= do
dtio <- qDiagramTextItem x1
diagramTextItem_s dtio
instance QdiagramTextItem (QGraphicsItem a, QGraphicsScene b) where
diagramTextItem (x1, x2)
= do
dtio <- qDiagramTextItem (x1, x2)
diagramTextItem_s dtio
diagramTextItem_s :: QDiagramTextItem -> IO QDiagramTextItem
diagramTextItem_s dtio
= do
setHandler dtio "(int)type()" diagramTextItemtype
setHandler dtio "(QVariant)itemChange(QGraphicsItem::GraphicsItemChange,const QVariant&)" dtItemChange
setHandler dtio "focusOutEvent(QFocusEvent*)" dtFocusOutEvent
setHandler dtio "mouseDoubleClickEvent(QGraphicsSceneMouseEvent*)" dtMouseDoubleClickEvent
setFlags dtio $ fItemIsMovable + fItemIsSelectable
return dtio
dtItemChange :: QDiagramTextItem -> GraphicsItemChange -> QVariant () -> IO (QVariant ())
dtItemChange ti ic vr
= do
if (qEnum_toInt ic == 14)
then emitSignal ti "selectedChange(QGraphicsTextItem*)" ti
else return ()
return vr
dtFocusOutEvent :: QDiagramTextItem -> QFocusEvent () -> IO ()
dtFocusOutEvent ti fe
= do
setTextInteractionFlags ti fNoTextInteraction
emitSignal ti "lostFocus(QGraphicsTextItem*)" ti
focusOutEvent_h ti fe
dtMouseDoubleClickEvent :: QDiagramTextItem -> QGraphicsSceneMouseEvent () -> IO ()
dtMouseDoubleClickEvent ti ge
= do
cf <- textInteractionFlags ti ()
if (cf == fNoTextInteraction)
then setTextInteractionFlags ti fTextEditorInteraction
else return ()
mouseDoubleClickEvent_h ti ge
editorLostFocus :: QDiagramScene -> QDiagramTextItem -> IO ()
editorLostFocus sn ti
= do
cr <- textCursor ti ()
clearSelection cr ()
setTextCursor ti cr
tt <- toPlainText ti ()
if (length tt == 0)
then
do
removeItem sn ti
qGraphicsTextItem_deleteLater ti
else
return ()
|
uduki/hsQt
|
examples/DiagramScene/DiagramTextItem.hs
|
bsd-2-clause
| 3,719
| 0
| 11
| 613
| 874
| 443
| 431
| 96
| 2
|
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Choose.IOBase
-- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
module Data.Choose.IOBase
where
import Control.Monad
import Control.Monad.ST
import Data.Choose.Base
-- | A mutable combination that can be manipulated in the 'IO' monad.
newtype IOChoose = IOChoose (STChoose RealWorld) deriving Eq
newIOChoose :: Int -> Int -> IO (IOChoose)
newIOChoose n k = liftM IOChoose $ stToIO (newSTChoose n k)
{-# INLINE newIOChoose #-}
newIOChoose_ :: Int -> Int -> IO (IOChoose)
newIOChoose_ n k = liftM IOChoose $ stToIO (newSTChoose_ n k)
{-# INLINE newIOChoose_ #-}
getPossibleIOChoose :: IOChoose -> IO Int
getPossibleIOChoose (IOChoose c) = stToIO $ getPossibleSTChoose c
{-# INLINE getPossibleIOChoose #-}
possibleIOChoose :: IOChoose -> Int
possibleIOChoose (IOChoose c) = possibleSTChoose c
{-# INLINE possibleIOChoose #-}
getSizeIOChoose :: IOChoose -> IO Int
getSizeIOChoose (IOChoose c) = stToIO $ getSizeSTChoose c
{-# INLINE getSizeIOChoose #-}
sizeIOChoose :: IOChoose -> Int
sizeIOChoose (IOChoose c) = sizeSTChoose c
{-# INLINE sizeIOChoose #-}
unsafeGetElemIOChoose :: IOChoose -> Int -> IO Int
unsafeGetElemIOChoose (IOChoose c) i = stToIO $ unsafeGetElemSTChoose c i
{-# INLINE unsafeGetElemIOChoose #-}
unsafeSetElemIOChoose :: IOChoose -> Int -> Int -> IO ()
unsafeSetElemIOChoose (IOChoose c) i x = stToIO $ unsafeSetElemSTChoose c i x
{-# INLINE unsafeSetElemIOChoose #-}
getElemsIOChoose :: IOChoose -> IO [Int]
getElemsIOChoose (IOChoose c) = stToIO $ getElemsSTChoose c
{-# INLINE getElemsIOChoose #-}
setElemsIOChoose :: IOChoose -> [Int] -> IO ()
setElemsIOChoose (IOChoose c) is = stToIO $ setElemsSTChoose c is
{-# INLINE setElemsIOChoose #-}
unsafeFreezeIOChoose :: IOChoose -> IO Choose
unsafeFreezeIOChoose (IOChoose c) = stToIO $ unsafeFreezeSTChoose c
{-# INLINE unsafeFreezeIOChoose #-}
unsafeThawIOChoose :: Choose -> IO (IOChoose)
unsafeThawIOChoose c = liftM IOChoose $ stToIO (unsafeThawSTChoose c)
{-# INLINE unsafeThawIOChoose #-}
|
patperry/permutation
|
lib/Data/Choose/IOBase.hs
|
bsd-3-clause
| 2,251
| 0
| 9
| 338
| 521
| 273
| 248
| 42
| 1
|
verticalSlice :: Chord (Voice a) -> Voice (Chord a)
-- Natural transformation?
reactiveSwithPoints :: Reactive a -> [Time]
splitReactive :: Time -> Reactive a -> Reactive a
splitReactives :: [Reactive a] -> [Reactive a]
Before export to notation formats, generate a full hierarchical representation
of the (visual) score. Something like:
Score
StaffGroup/Staff x Bar
BarVoice
BeatGroup
Beat = (HLine begin/end, Beam)
Chord = (Tremolo, Harmonic, Articulation, Dynamic, IsGrace)
Note = (VLine begin/end, Tie begin/end, Color, NHType, NHSize)
|
FranklinChen/music-score
|
sketch/old/HierachicalTS.hs
|
bsd-3-clause
| 601
| 6
| 8
| 138
| 221
| 113
| 108
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
module Git.CommonTests
(
main
, test
) where
import qualified Test.HUnit as H
import Git.Common
import Test.QuickCheck hiding ((.&.))
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit
import Data.Bits
import Data.Word
main :: IO ()
main = defaultMain [test]
test_isMsbSet = H.assertBool
"isMsbSet should be true if the most significant bit is set"
(isMsbSet (128::Word8))
test_isMsbNotSet = H.assertBool
"isMsbSet should be false if the most significant bit is not set"
(not $ isMsbSet (127::Word8))
test_pktLineEmpty = H.assertEqual
"Empty pktline should be 0004"
"0004"
(pktLine "")
test_pktLineNotEmpty = H.assertEqual
"Should be prefixed with valid length (in hex)"
"0032want 40bcec379e1cde8d3a3e841e7f218cd84448cec5\n"
(pktLine "want 40bcec379e1cde8d3a3e841e7f218cd84448cec5\n")
test_pktLineDone = H.assertEqual
"Done packet"
"0008done"
(pktLine "done")
test_pktLineDoneLn = H.assertEqual
"Done packet"
"0009done\n"
(pktLine "done\n")
test_toHex = H.assertEqual
"210 should be in hex"
"d2"
(toHex 210)
test :: Test
test = testGroup "Common"
[
testProperty "prop_isMsbSet" prop_isMsbSet
,testCase "isMsbSet/1" test_isMsbSet
,testCase "isMsbSet/2" test_isMsbNotSet
,testCase "test_pktLineEmpty/1" test_pktLineEmpty
,testCase "test_pktLineNotEmpty/1" test_pktLineNotEmpty
,testCase "test_pktLineDone/1" test_pktLineDone
,testCase "test_pktLineDoneLn/1" test_pktLineDoneLn
,testCase "test_toHex/1" test_toHex
]
prop_isMsbSet :: Int -> Bool
prop_isMsbSet x = testBit x 7 == isMsbSet x
|
fcharlie/hgit
|
tests/src/Git/CommonTests.hs
|
bsd-3-clause
| 1,770
| 0
| 9
| 336
| 367
| 200
| 167
| 54
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
module Test.Foundation.Collection
( testCollection
, fromListP
, toListP
) where
import qualified Prelude
import Imports
import Foundation
import Foundation.Collection
import Test.Data.List
-- | internal helper to convert a list of element into a collection
--
fromListP :: (IsList c, Item c ~ Element c) => Proxy c -> [Element c] -> c
fromListP p = \x -> asProxyTypeOf (fromList x) p
-- | internal helper to convert a given Collection into a list of its element
--
toListP :: (IsList c, Item c ~ Element c) => Proxy c -> c -> [Element c]
toListP p x = toList (asProxyTypeOf x p)
-- | test property equality for the given Collection
--
-- This does to enforce
testEquality :: ( Show e
, Eq e, Eq a
, Element a ~ e
, IsList a, Item a ~ Element a
)
=> Proxy a
-> Gen e
-> TestTree
testEquality proxy genElement = testGroup "equality"
[ testProperty "x == x" $ withElements $ \l -> let col = fromListP proxy l in col == col
, testProperty "x == y" $ with2Elements $ \(l1, l2) ->
(fromListP proxy l1 == fromListP proxy l2) == (l1 == l2)
]
where
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
testOrdering :: ( Show e
, Ord a, Ord e
, Element a ~ e
, IsList a, Item a ~ Element a
)
=> Proxy a
-> Gen e
-> TestTree
testOrdering proxy genElement = testGroup "ordering"
[ testProperty "x `compare` y" $ with2Elements $ \(l1, l2) ->
(fromListP proxy l1 `compare` fromListP proxy l2) == (l1 `compare` l2)
]
where
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
testIsList :: ( Show e
, Eq e, Eq a
, Element a ~ e
, IsList a, Item a ~ Element a
)
=> Proxy a
-> Gen e
-> TestTree
testIsList proxy genElement = testGroup "IsList"
[ testProperty "fromList . toList == id" $ withElements $ \l -> (toList $ fromListP proxy l) === l
]
where
withElements f = forAll (generateListOfElement genElement) f
-- | group of all the property a given collection should have
--
-- > splitAt == (take, drop)
--
-- > revSplitAt == (revTake, revDrop)
--
-- > c == [Element c]
--
testSequentialProperties :: (Show a, Sequential a, Eq a, e ~ Item a) => Proxy a -> Gen e -> TestTree
testSequentialProperties proxy genElement = testGroup "Properties"
[ testProperty "splitAt == (take, drop)" $ withCollection2 $ \(col, n) ->
splitAt n col == (take n col, drop n col)
, testProperty "revSplitAt == (revTake, revDrop)" $ withCollection2 $ \(col, n) ->
revSplitAt n col == (revTake n col, revDrop n col)
]
where
withCollection2 f = forAll ((,) <$> (fromListP proxy <$> generateListOfElement genElement) <*> (CountOf <$> arbitrary)) f
testMonoid :: ( Show a, Show e
, Eq a, Eq e
, Monoid a
, Element a ~ e, IsList a, Item a ~ Element a
)
=> Proxy a
-> Gen e
-> TestTree
testMonoid proxy genElement = testGroup "Monoid"
[ testProperty "mempty <> x == x" $ withElements $ \l -> let col = fromListP proxy l in (col <> mempty) === col
, testProperty "x <> mempty == x" $ withElements $ \l -> let col = fromListP proxy l in (mempty <> col) === col
, testProperty "x1 <> x2 == x1|x2" $ with2Elements $ \(l1,l2) ->
(fromListP proxy l1 <> fromListP proxy l2) === fromListP proxy (l1 <> l2)
, testProperty "mconcat [map fromList [e]] = fromList (concat [e])" $ withNElements $ \l ->
mconcat (fmap (fromListP proxy) l) === fromListP proxy (mconcat l)
]
where
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
withNElements f = forAll (generateListOfElementMaxN 5 (generateListOfElement genElement)) f
testCollection :: ( Sequential a
, Show a, Show (Element a)
, Eq (Element a)
, Ord a, Ord (Item a)
)
=> String
-> Proxy a
-> Gen (Element a)
-> TestTree
testCollection name proxy genElement = testGroup name
[ testEquality proxy genElement
, testOrdering proxy genElement
, testIsList proxy genElement
, testMonoid proxy genElement
, testCollectionOps proxy genElement
, testSequentialOps proxy genElement
]
fromListNonEmptyP :: Collection a => Proxy a -> NonEmpty [Element a] -> NonEmpty a
fromListNonEmptyP proxy = nonEmpty_ . fromListP proxy . getNonEmpty
testCollectionOps :: ( Collection a
, Show a, Show (Element a)
, Eq (Element a)
, Ord a, Ord (Item a)
)
=> Proxy a
-> Gen (Element a)
-> TestTree
testCollectionOps proxy genElement = testGroup "Collection"
[ testProperty "length" $ withElements $ \l -> (length $ fromListP proxy l) === length l
, testProperty "elem" $ withListAndElement $ \(l,e) -> elem e (fromListP proxy l) == elem e l
, testProperty "notElem" $ withListAndElement $ \(l,e) -> notElem e (fromListP proxy l) == notElem e l
, testProperty "minimum" $ withNonEmptyElements $ \els -> minimum (fromListNonEmptyP proxy els) === minimum els
, testProperty "maximum" $ withNonEmptyElements $ \els -> maximum (fromListNonEmptyP proxy els) === maximum els
, testProperty "all" $ withListAndElement $ \(l, e) ->
all (/= e) (fromListP proxy l) == all (/= e) l &&
all (== e) (fromListP proxy l) == all (== e) l
, testProperty "any" $ withListAndElement $ \(l, e) ->
any (/= e) (fromListP proxy l) == any (/= e) l &&
any (== e) (fromListP proxy l) == any (== e) l
]
where
withElements f = forAll (generateListOfElement genElement) f
withListAndElement = forAll ((,) <$> generateListOfElement genElement <*> genElement)
withNonEmptyElements f = forAll (generateNonEmptyListOfElement 80 genElement) f
testSplitOn :: ( Sequential a
, Show a, Show (Element a)
, Eq (Element a)
, Eq a, Ord a, Ord (Item a), Show a
)
=> Proxy a -> (Element a -> Bool) -> a
-> TestTree
testSplitOn _ predicate col = testCase "splitOn (const True) mempty == [mempty]" $
assertEq' (splitOn predicate col) [col]
testSequentialOps :: ( Sequential a
, Show a, Show (Element a)
, Eq (Element a)
, Eq a, Ord a, Ord (Item a), Show a
)
=> Proxy a
-> Gen (Element a)
-> TestTree
testSequentialOps proxy genElement = testGroup "Sequential"
[ testProperty "take" $ withElements2 $ \(l, n) -> toList (take n $ fromListP proxy l) === (take n) l
, testProperty "drop" $ withElements2 $ \(l, n) -> toList (drop n $ fromListP proxy l) === (drop n) l
, testProperty "splitAt" $ withElements2 $ \(l, n) -> toList2 (splitAt n $ fromListP proxy l) === (splitAt n) l
, testProperty "revTake" $ withElements2 $ \(l, n) -> toList (revTake n $ fromListP proxy l) === (revTake n) l
, testProperty "revDrop" $ withElements2 $ \(l, n) -> toList (revDrop n $ fromListP proxy l) === (revDrop n) l
, testProperty "revSplitAt" $ withElements2 $ \(l, n) -> toList2 (revSplitAt n $ fromListP proxy l) === (revSplitAt n) l
, testProperty "break" $ withElements2E $ \(l, c) -> toList2 (break (== c) $ fromListP proxy l) === (break (== c)) l
, testProperty "breakEnd" $ withElements2E $ \(l, c) -> toList2 (breakEnd (== c) $ fromListP proxy l) === (breakEnd (== c)) l
, testProperty "breakElem" $ withElements2E $ \(l, c) -> toList2 (breakElem c $ fromListP proxy l) === (breakElem c) l
, testProperty "span" $ withElements2E $ \(l, c) -> toList2 (span (== c) $ fromListP proxy l) === (span (== c)) l
, testProperty "filter" $ withElements2E $ \(l, c) -> toList (filter (== c) $ fromListP proxy l) === (filter (== c)) l
, testProperty "partition" $ withElements2E $ \(l, c) -> toList2 (partition (== c) $ fromListP proxy l) === (partition (== c)) l
, testProperty "snoc" $ withElements2E $ \(l, c) -> toList (snoc (fromListP proxy l) c) === (l <> [c])
, testProperty "cons" $ withElements2E $ \(l, c) -> toList (cons c (fromListP proxy l)) === (c : l)
, testProperty "unsnoc" $ withElements $ \l -> fmap toListFirst (unsnoc (fromListP proxy l)) === unsnoc l
, testProperty "uncons" $ withElements $ \l -> fmap toListSecond (uncons (fromListP proxy l)) === uncons l
, testProperty "head" $ withNonEmptyElements $ \els -> head (fromListNonEmptyP proxy els) === head els
, testProperty "last" $ withNonEmptyElements $ \els -> last (fromListNonEmptyP proxy els) === last els
, testProperty "tail" $ withNonEmptyElements $ \els -> toList (tail $ fromListNonEmptyP proxy els) === tail els
, testProperty "init" $ withNonEmptyElements $ \els -> toList (init $ fromListNonEmptyP proxy els) === init els
, testProperty "splitOn" $ withElements2E $ \(l, ch) ->
fmap toList (splitOn (== ch) (fromListP proxy l)) === splitOn (== ch) l
, testSplitOn proxy (const True) mempty
, testProperty "intercalate c (splitOn (c ==) col) == col" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) c) === c
, testProperty "intercalate c (splitOn (c ==) (col ++ [c]) == (col ++ [c])" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) $ snoc c ch) === (snoc c ch)
, testProperty "intercalate c (splitOn (c ==) (col ++ [c,c]) == (col ++ [c,c])" $ withElements2E $ \(c, ch) ->
intercalate [ch] (splitOn (== ch) $ snoc (snoc c ch) ch) === (snoc (snoc c ch) ch)
, testProperty "intersperse" $ withElements2E $ \(l, c) ->
toList (intersperse c (fromListP proxy l)) === intersperse c l
, testProperty "intercalate" $ withElements2E $ \(l, c) ->
let ls = Prelude.replicate 5 l
cs = Prelude.replicate 5 c
in toList (intercalate (fromListP proxy cs) (fromListP proxy <$> ls)) === intercalate cs ls
, testProperty "sortBy" $ withElements $ \l ->
(sortBy compare $ fromListP proxy l) === fromListP proxy (sortBy compare l)
, testProperty "reverse" $ withElements $ \l ->
(reverse $ fromListP proxy l) === fromListP proxy (reverse l)
-- stress slicing
, testProperty "take . take" $ withElements3 $ \(l, n1, n2) -> toList (take n2 $ take n1 $ fromListP proxy l) === (take n2 $ take n1 l)
, testProperty "drop . take" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ take n1 $ fromListP proxy l) === (drop n2 $ take n1 l)
, testProperty "drop . drop" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ drop n1 $ fromListP proxy l) === (drop n2 $ drop n1 l)
, testProperty "drop . take" $ withElements3 $ \(l, n1, n2) -> toList (drop n2 $ take n1 $ fromListP proxy l) === (drop n2 $ take n1 l)
, testProperty "second take . splitAt" $ withElements3 $ \(l, n1, n2) ->
(toList2 $ (second (take n1) . splitAt n2) $ fromListP proxy l) === (second (take n1) . splitAt n2) l
, testSequentialProperties proxy genElement
, testGroup "isSuffixOf"
[ testProperty "collection + sub" $ withElements2 $ \(l1, n) ->
let c1 = fromListP proxy l1 in isSuffixOf (revTake n c1) c1 === isSuffixOf (revTake n l1) l1
, testProperty "2 collections" $ with2Elements $ \(l1, l2) -> isSuffixOf (fromListP proxy l1) (fromListP proxy l2) === isSuffixOf l1 l2
, testProperty "collection + empty" $ withElements $ \l1 ->
isSuffixOf (fromListP proxy []) (fromListP proxy l1) === isSuffixOf [] l1
]
, testGroup "isPrefixOf"
[ testProperty "collection + sub" $ withElements2 $ \(l1, n) ->
let c1 = fromListP proxy l1 in isPrefixOf (take n c1) c1 === isPrefixOf (take n l1) l1
, testProperty "2 collections" $ with2Elements $ \(l1, l2) -> isPrefixOf (fromListP proxy l1) (fromListP proxy l2) === isPrefixOf l1 l2
, testProperty "collection + empty" $ withElements $ \l1 ->
isPrefixOf (fromListP proxy []) (fromListP proxy l1) === isPrefixOf [] l1
]
, testGroup "isInfixOf"
[ testProperty "b isInfixOf 'a b c'" $ with3Elements $ \(a, b, c) ->
isInfixOf (toCol b) (toCol a <> toCol b <> toCol c)
, testProperty "the reverse is typically not an infix" $ withElements $ \a' ->
let a = toCol a'; rev = reverse a in isInfixOf rev a === (a == rev)
]
]
{-
, testProperty "imap" $ \(CharMap (LUString u) i) ->
(imap (addChar i) (fromList u) :: String) `assertEq` fromList (Prelude.map (addChar i) u)
]
-}
where
toCol = fromListP proxy
toList2 (x,y) = (toList x, toList y)
toListFirst (x,y) = (toList x, y)
toListSecond (x,y) = (x, toList y)
withElements f = forAll (generateListOfElement genElement) f
with2Elements f = forAll ((,) <$> generateListOfElement genElement <*> generateListOfElement genElement) f
with3Elements f = forAll ((,,) <$> generateListOfElement genElement <*> generateListOfElement genElement <*> generateListOfElement genElement) f
withElements2 f = forAll ((,) <$> generateListOfElement genElement <*> (CountOf <$> arbitrary)) f
withElements3 f = forAll ((,,) <$> generateListOfElement genElement <*> (CountOf <$> arbitrary) <*> (CountOf <$> arbitrary)) f
withElements2E f = forAll ((,) <$> generateListOfElement genElement <*> genElement) f
withNonEmptyElements f = forAll (generateNonEmptyListOfElement 80 genElement) f
|
vincenthz/hs-foundation
|
foundation/tests/Test/Foundation/Collection.hs
|
bsd-3-clause
| 14,234
| 0
| 17
| 3,826
| 5,121
| 2,598
| 2,523
| 205
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- | News page view.
module HL.View.News where
import HL.View
import HL.View.Template
-- | News view.
newsV :: Html () -> FromLucid App
newsV inner =
template []
"News"
(\_ ->
container_
(do row_ (span12_ [class_ "col-sm-12"] (do h1_ "News"))
inner))
|
gbaz/hl
|
src/HL/View/News.hs
|
bsd-3-clause
| 399
| 0
| 18
| 127
| 102
| 54
| 48
| 13
| 1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012-2014
--
-- License : BSD-style
--
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : non-portable (TF,GNTD)
--
-- Provides meta-data attribution for composer, lyricist etc.
--
-------------------------------------------------------------------------------------
module Music.Score.Meta.Attribution (
-- * Attribution type
Attribution,
attribution,
attributions,
getAttribution,
-- ** Adding attribution to scores
attribute,
attributeDuring,
composer,
composerDuring,
lyricist,
lyricistDuring,
arranger,
arrangerDuring,
-- ** Extracting attribution
withAttribution,
withAttribution',
) where
import Control.Lens (view)
import Control.Monad.Plus
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Data.Typeable
import Music.Pitch.Literal
import Music.Score.Meta
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Internal.Util
import Music.Time
import Music.Time.Reactive
-- |
-- An attributions is a simple map from keys to values used to gather information such as
-- composer, lyricist, orchestrator, performer, etc.
--
-- Attribution is a 'Semigroup', and compose by choosing the leftmost value in each
-- category. For example
--
-- > attribution "composer" "H" <> attribution "composer" "S" <> attribution "lyricist" "S"
-- > ===> attributions [("composer","H"),("lyricist","S")]
--
-- Any kind of attribution can be added, and backends may recognize or ignore categories as they
-- see fit. The following categories are normally recognized:
--
-- > composer
-- > lyricist
-- > arranger
-- > performer
-- > dedication
-- > year
-- > copyright
-- > information
--
newtype Attribution = Attribution (Map String (Option (Last String)))
deriving (Typeable, Monoid, Semigroup)
instance Show Attribution where
show (Attribution a) = "attributions " ++ show (Map.toList (fmap (fromJust . fmap getLast . getOption) $ a))
-- | Make an 'Attribution' from keys and values.
attributions :: [(String, String)] -> Attribution
attributions = Attribution . fmap (Option . Just . Last) . Map.fromList
-- | Make an 'Attribution' a single key and value.
attribution :: String -> String -> Attribution
attribution k v = Attribution . fmap (Option . Just . Last) $ Map.singleton k v
-- | Extract an the given attributions value. Semantic function.
getAttribution :: Attribution -> String -> Maybe String
getAttribution (Attribution a) k = join $ k `Map.lookup` (fmap (fmap getLast . getOption) $ a)
-- | Set the given attribution in the given score.
attribute :: (HasMeta a, HasPosition a) => Attribution -> a -> a
attribute a x = attributeDuring (_era x) a x
-- | Set the given attribution in the given part of a score.
attributeDuring :: (HasMeta a) => Span -> Attribution -> a -> a
attributeDuring s a = addMetaNote (view event (s, a))
-- | Set composer of the given score.
composer :: (HasMeta a, HasPosition a) => String -> a -> a
composer t x = composerDuring (_era x) t x
-- | Set composer of the given part of a score.
composerDuring :: HasMeta a => Span -> String -> a -> a
composerDuring s x = attributeDuring s ("composer" `attribution` x)
-- | Set lyricist of the given score.
lyricist :: (HasMeta a, HasPosition a) => String -> a -> a
lyricist t x = lyricistDuring (_era x) t x
-- | Set lyricist of the given part of a score.
lyricistDuring :: HasMeta a => Span -> String -> a -> a
lyricistDuring s x = attributeDuring s ("lyricist" `attribution` x)
-- | Set arranger of the given score.
arranger :: (HasMeta a, HasPosition a) => String -> a -> a
arranger t x = arrangerDuring (_era x) t x
-- | Set arranger of the given part of a score.
arrangerDuring :: HasMeta a => Span -> String -> a -> a
arrangerDuring s x = attributeDuring s ("arranger" `attribution` x)
-- | Extract attribution values of the given category from a score.
withAttribution :: String -> (String -> Score a -> Score a) -> Score a -> Score a
withAttribution name f = withAttribution' (fromMaybe id . fmap f . flip getAttribution name)
-- | Extract all attribution values from a score.
withAttribution' :: (Attribution -> Score a -> Score a) -> Score a -> Score a
withAttribution' = withMetaAtStart
|
music-suite/music-score
|
src/Music/Score/Meta/Attribution.hs
|
bsd-3-clause
| 5,522
| 0
| 16
| 1,336
| 1,057
| 602
| 455
| 78
| 1
|
{-# OPTIONS_GHC -cpp #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Setup
-- Copyright : Isaac Jones 2003-2004
--
-- Maintainer : Isaac Jones <ijones@syntaxpolice.org>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Data types and parser for the standard command-line
-- setup. Will also return commands it doesn't know about.
{- All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 Distribution.Setup (--parseArgs,
module Distribution.Compiler,
Action(..),
ConfigFlags(..), emptyConfigFlags, configureArgs,
CopyFlags(..), CopyDest(..),
InstallFlags(..), emptyInstallFlags,
HaddockFlags(..), emptyHaddockFlags,
BuildFlags(..), CleanFlags(..), PFEFlags(..),
RegisterFlags(..), emptyRegisterFlags,
SDistFlags(..),
MaybeUserFlag(..), userOverride,
--optionHelpString,
#ifdef DEBUG
hunitTests,
#endif
parseGlobalArgs, defaultCompilerFlavor,
parseConfigureArgs, parseBuildArgs, parseCleanArgs,
parseHaddockArgs, parseProgramaticaArgs, parseTestArgs,
parseInstallArgs, parseSDistArgs, parseRegisterArgs,
parseUnregisterArgs, parseCopyArgs,
reqPathArg, reqDirArg
) where
-- Misc:
#ifdef DEBUG
import HUnit (Test(..))
#endif
import Distribution.Compiler (CompilerFlavor(..), Compiler(..))
import Distribution.Simple.Utils (die)
import Distribution.Program(ProgramConfiguration(..),
userSpecifyPath, userSpecifyArgs)
import Data.List(find)
import Distribution.Compat.Map (keys)
import Distribution.GetOpt
import Distribution.Compat.FilePath (platformPath)
import System.Exit
import System.Environment
-- type CommandLineOpts = (Action,
-- [String]) -- The un-parsed remainder
data Action = ConfigCmd ConfigFlags -- config
| BuildCmd -- build
| CleanCmd -- clean
| CopyCmd CopyDest -- copy (--destdir flag)
| HaddockCmd -- haddock
| ProgramaticaCmd -- pfesetup
| InstallCmd -- install (install-prefix)
| SDistCmd -- sdist
| TestCmd -- test
| RegisterCmd -- register
| UnregisterCmd -- unregister
| HelpCmd -- help
-- | NoCmd -- error case, help case.
-- | TestCmd 1.0?
-- | BDist -- 1.0
-- | CleanCmd -- clean
-- | NoCmd -- error case?
-- ------------------------------------------------------------
-- * Flag-related types
-- ------------------------------------------------------------
-- | Flags to @configure@ command
data ConfigFlags = ConfigFlags {
configPrograms :: ProgramConfiguration, -- ^All programs that cabal may run
configHcFlavor :: Maybe CompilerFlavor,
configHcPath :: Maybe FilePath, -- ^given compiler location
configHcPkg :: Maybe FilePath, -- ^given hc-pkg location
configHappy :: Maybe FilePath, -- ^Happy path
configAlex :: Maybe FilePath, -- ^Alex path
configHsc2hs :: Maybe FilePath, -- ^Hsc2hs path
configC2hs :: Maybe FilePath, -- ^C2hs path
configCpphs :: Maybe FilePath, -- ^Cpphs path
configGreencard:: Maybe FilePath, -- ^GreenCard path
configVanillaLib :: Bool, -- ^Enable vanilla library
configProfLib :: Bool, -- ^Enable profiling in the library
configProfExe :: Bool, -- ^Enable profiling in the executables.
configPrefix :: Maybe FilePath,
-- ^installation prefix
configBinDir :: Maybe FilePath,
-- ^installation dir for binaries,
configLibDir :: Maybe FilePath,
-- ^installation dir for object code libraries,
configLibSubDir :: Maybe FilePath,
-- ^subdirectory of libdir in which libs are installed
configLibExecDir :: Maybe FilePath,
-- ^installation dir for program executables,
configDataDir :: Maybe FilePath,
-- ^installation dir for read-only arch-independent data,
configDataSubDir :: Maybe FilePath,
-- ^subdirectory of datadir in which data files are installed
configVerbose :: Int, -- ^verbosity level
configUser :: Bool, -- ^--user flag?
configGHCiLib :: Bool, -- ^Enable compiling library for GHCi
configSplitObjs :: Bool -- ^Enable -split-objs with GHC
}
emptyConfigFlags :: ProgramConfiguration -> ConfigFlags
emptyConfigFlags progConf = ConfigFlags {
configPrograms = progConf,
configHcFlavor = defaultCompilerFlavor,
configHcPath = Nothing,
configHcPkg = Nothing,
-- configHaddock = EmptyLocation,
configHappy = Nothing,
configAlex = Nothing,
configHsc2hs = Nothing,
configC2hs = Nothing,
configVanillaLib = True,
configProfLib = False,
configProfExe = False,
configCpphs = Nothing,
configGreencard= Nothing,
configPrefix = Nothing,
configBinDir = Nothing,
configLibDir = Nothing,
configLibSubDir = Nothing,
configLibExecDir = Nothing,
configDataDir = Nothing,
configDataSubDir = Nothing,
configVerbose = 0,
configUser = False,
configGHCiLib = True,
configSplitObjs = False -- takes longer, so turn off by default
}
-- | Flags to @copy@: (destdir, copy-prefix (backwards compat), verbose)
data CopyFlags = CopyFlags {copyDest :: CopyDest
,copyVerbose :: Int}
data CopyDest
= NoCopyDest
| CopyTo FilePath
| CopyPrefix FilePath -- DEPRECATED
deriving (Eq, Show)
data MaybeUserFlag = MaybeUserNone -- ^no --user OR --global flag.
| MaybeUserUser -- ^--user flag
| MaybeUserGlobal -- ^--global flag
-- |A 'MaybeUserFlag' overrides the default --user setting
userOverride :: MaybeUserFlag -> Bool -> Bool
MaybeUserUser `userOverride` _ = True
MaybeUserGlobal `userOverride` _ = False
_ `userOverride` r = r
-- | Flags to @install@: (user package, verbose)
data InstallFlags = InstallFlags {installUserFlags::MaybeUserFlag
,installVerbose :: Int}
emptyInstallFlags :: InstallFlags
emptyInstallFlags = InstallFlags{ installUserFlags=MaybeUserNone,
installVerbose=0 }
-- | Flags to @sdist@: (snapshot, verbose)
data SDistFlags = SDistFlags {sDistSnapshot::Bool
,sDistVerbose:: Int}
-- | Flags to @register@ and @unregister@: (user package, gen-script,
-- in-place, verbose)
data RegisterFlags = RegisterFlags {regUser::MaybeUserFlag
,regGenScript::Bool
,regInPlace::Bool
,regWithHcPkg::Maybe FilePath
,regVerbose::Int}
emptyRegisterFlags :: RegisterFlags
emptyRegisterFlags = RegisterFlags { regUser=MaybeUserNone,
regGenScript=False,
regInPlace=False,
regWithHcPkg=Nothing,
regVerbose=0 }
data HaddockFlags = HaddockFlags {haddockHoogle :: Bool
,haddockVerbose :: Int}
emptyHaddockFlags :: HaddockFlags
emptyHaddockFlags = HaddockFlags {haddockHoogle = False, haddockVerbose = 0}
-- Following only have verbose flags, but for consistency and
-- extensibility we make them into a type.
data BuildFlags = BuildFlags {buildVerbose :: Int}
data CleanFlags = CleanFlags {cleanVerbose :: Int}
data PFEFlags = PFEFlags {pfeVerbose :: Int}
-- |Most of these flags are for Configure, but InstPrefix is for Copy.
data Flag a = GhcFlag | NhcFlag | HugsFlag | JhcFlag
| WithCompiler FilePath | WithHcPkg FilePath
| WithHappy FilePath | WithAlex FilePath
| WithHsc2hs FilePath | WithC2hs FilePath | WithCpphs FilePath
| WithGreencard FilePath
| WithVanillaLib | WithoutVanillaLib
| WithProfLib | WithoutProfLib
| WithProfExe | WithoutProfExe
| WithGHCiLib | WithoutGHCiLib
| WithSplitObjs | WithoutSplitObjs
| Prefix FilePath
| BinDir FilePath
| LibDir FilePath
| LibSubDir FilePath
| LibExecDir FilePath
| DataDir FilePath
| DataSubDir FilePath
| ProgramArgs String String -- program name, arguments
| WithProgram String FilePath -- program name, location
-- For install, register, and unregister:
| UserFlag | GlobalFlag
-- for register & unregister
| GenScriptFlag
| InPlaceFlag
-- For copy:
| InstPrefix FilePath
| DestDir FilePath
-- For sdist:
| Snapshot
-- For haddock:
| HaddockHoogle
-- For everyone:
| HelpFlag
| Verbose Int
-- | Version?
| Lift a
deriving (Show, Eq)
-- ------------------------------------------------------------
-- * Mostly parsing functions
-- ------------------------------------------------------------
defaultCompilerFlavor :: Maybe CompilerFlavor
defaultCompilerFlavor =
#if defined(__GLASGOW_HASKELL__)
Just GHC
#elif defined(__NHC__)
Just NHC
#elif defined(__JHC__)
Just JHC
#elif defined(__HUGS__)
Just Hugs
#else
Nothing
#endif
-- | Arguments to pass to a @configure@ script, e.g. generated by
-- @autoconf@.
configureArgs :: ConfigFlags -> [String]
configureArgs flags
= hc_flag ++
optFlag "with-hc-pkg" configHcPkg ++
optFlag "prefix" configPrefix ++
optFlag "bindir" configBinDir ++
optFlag "libdir" configLibDir ++
optFlag "libexecdir" configLibExecDir ++
optFlag "datadir" configDataDir
where
hc_flag = case (configHcFlavor flags, configHcPath flags) of
(_, Just hc_path) -> ["--with-hc=" ++ hc_path]
(Just hc, Nothing) -> ["--with-hc=" ++ showHC hc]
(Nothing,Nothing) -> []
optFlag name config_field = case config_field flags of
Just p -> ["--" ++ name ++ "=" ++ p]
Nothing -> []
showHC GHC = "ghc"
showHC NHC = "nhc98"
showHC JHC = "jhc"
showHC Hugs = "hugs"
showHC c = "unknown compiler: " ++ (show c)
cmd_help :: OptDescr (Flag a)
cmd_help = Option "h?" ["help"] (NoArg HelpFlag) "Show this help text"
cmd_verbose :: OptDescr (Flag a)
cmd_verbose = Option "v" ["verbose"] (OptArg verboseFlag "n") "Control verbosity (n is 0--5, normal verbosity level is 1, -v alone is equivalent to -v3)"
where
verboseFlag mb_s = Verbose (maybe 3 read mb_s)
cmd_with_hc_pkg :: OptDescr (Flag a)
cmd_with_hc_pkg = Option "" ["with-hc-pkg"] (reqPathArg WithHcPkg)
"give the path to the package tool"
-- Do we have any other interesting global flags?
globalOptions :: [OptDescr (Flag a)]
globalOptions = [
cmd_help
]
liftCustomOpts :: [OptDescr a] -> [OptDescr (Flag a)]
liftCustomOpts flags = [ Option shopt lopt (f adesc) help
| Option shopt lopt adesc help <- flags ]
where f (NoArg x) = NoArg (Lift x)
f (ReqArg g s) = ReqArg (Lift . g) s
f (OptArg g s) = OptArg (Lift . g) s
data Cmd a = Cmd {
cmdName :: String,
cmdHelp :: String, -- Short description
cmdDescription :: String, -- Long description
cmdOptions :: [OptDescr (Flag a)],
cmdAction :: Action
}
commandList :: ProgramConfiguration -> [Cmd a]
commandList progConf = [(configureCmd progConf), buildCmd, cleanCmd, installCmd,
copyCmd, sdistCmd, testCmd, haddockCmd, programaticaCmd,
registerCmd, unregisterCmd]
lookupCommand :: String -> [Cmd a] -> Maybe (Cmd a)
lookupCommand name = find ((==name) . cmdName)
printGlobalHelp :: ProgramConfiguration -> IO ()
printGlobalHelp progConf =
do pname <- getProgName
let syntax_line = "Usage: " ++ pname ++ " [GLOBAL FLAGS]\n or: " ++ pname ++ " COMMAND [FLAGS]\n\nGlobal flags:"
putStrLn (usageInfo syntax_line globalOptions)
putStrLn "Commands:"
let maxlen = maximum [ length (cmdName cmd) | cmd <- (commandList progConf) ]
sequence_ [ do putStr " "
putStr (align maxlen (cmdName cmd))
putStr " "
putStrLn (cmdHelp cmd)
| cmd <- (commandList progConf) ]
putStrLn $ "\nFor more information about a command, try '" ++ pname ++ " COMMAND --help'."
where align n str = str ++ replicate (n - length str) ' '
printCmdHelp :: Cmd a -> [OptDescr a] -> IO ()
printCmdHelp cmd opts = do pname <- getProgName
let syntax_line = "Usage: " ++ pname ++ " " ++ cmdName cmd ++ " [FLAGS]\n\nFlags for " ++ cmdName cmd ++ ":"
putStrLn (usageInfo syntax_line (cmdOptions cmd ++ liftCustomOpts opts))
putStr (cmdDescription cmd)
getCmdOpt :: Cmd a -> [OptDescr a] -> [String] -> ([Flag a], [String], [String])
getCmdOpt cmd opts s = let (a,_,c,d) = getOpt' Permute (cmdOptions cmd ++ liftCustomOpts opts) s
in (a,c,d)
-- We don't want to use elem, because that imposes Eq a
hasHelpFlag :: [Flag a] -> Bool
hasHelpFlag flags = not . null $ [ () | HelpFlag <- flags ]
parseGlobalArgs :: ProgramConfiguration -> [String] -> IO (Action,[String])
parseGlobalArgs progConf args =
case getOpt' RequireOrder globalOptions args of
(flags, _, _, []) | hasHelpFlag flags -> do
(printGlobalHelp progConf)
exitWith ExitSuccess
(_, cname:cargs, extra_args, []) -> do
case lookupCommand cname (commandList progConf) of
Just cmd -> return (cmdAction cmd, extra_args ++ cargs)
Nothing -> die $ "Unrecognised command: " ++ cname ++ " (try --help)"
(_, [], _, []) -> die $ "No command given (try --help)"
(_, _, _, errs) -> putErrors errs
configureCmd :: ProgramConfiguration -> Cmd a
configureCmd progConf = Cmd {
cmdName = "configure",
cmdHelp = "Prepare to build the package.",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help, cmd_verbose,
Option "g" ["ghc"] (NoArg GhcFlag) "compile with GHC",
Option "n" ["nhc"] (NoArg NhcFlag) "compile with NHC",
Option "" ["jhc"] (NoArg JhcFlag) "compile with JHC",
Option "" ["hugs"] (NoArg HugsFlag) "compile with hugs",
Option "w" ["with-compiler"] (reqPathArg WithCompiler)
"give the path to a particular compiler",
cmd_with_hc_pkg,
Option "" ["prefix"] (reqDirArg Prefix)
"bake this prefix in preparation of installation",
Option "" ["bindir"] (reqDirArg BinDir)
"installation directory for executables",
Option "" ["libdir"] (reqDirArg LibDir)
"installation directory for libraries",
Option "" ["libsubdir"] (reqDirArg LibSubDir)
"subdirectory of libdir in which libs are installed",
Option "" ["libexecdir"] (reqDirArg LibExecDir)
"installation directory for program executables",
Option "" ["datadir"] (reqDirArg DataDir)
"installation directory for read-only data",
Option "" ["datasubdir"] (reqDirArg DataSubDir)
"subdirectory of datadir in which data files are installed",
Option "" ["with-happy"] (reqPathArg WithHappy)
"give the path to happy",
Option "" ["with-alex"] (reqPathArg WithAlex)
"give the path to alex",
Option "" ["with-hsc2hs"] (reqPathArg WithHsc2hs)
"give the path to hsc2hs",
Option "" ["with-c2hs"] (reqPathArg WithC2hs)
"give the path to c2hs",
Option "" ["with-cpphs"] (reqPathArg WithCpphs)
"give the path to cpphs",
Option "" ["with-greencard"] (reqPathArg WithGreencard)
"give the path to greencard",
Option "" ["enable-library-vanilla"] (NoArg WithVanillaLib)
"Enable vanilla libraries",
Option "" ["disable-library-vanilla"] (NoArg WithoutVanillaLib)
"Disable vanilla libraries",
Option "p" ["enable-library-profiling"] (NoArg WithProfLib)
"Enable library profiling",
Option "" ["disable-library-profiling"] (NoArg WithoutProfLib)
"Disable library profiling",
Option "" ["enable-executable-profiling"] (NoArg WithProfExe)
"Enable executable profiling",
Option "" ["disable-executable-profiling"] (NoArg WithoutProfExe)
"Disable executable profiling",
Option "" ["enable-library-for-ghci"] (NoArg WithGHCiLib)
"compile library for use with GHCi",
Option "" ["disable-library-for-ghci"] (NoArg WithoutGHCiLib)
"do not compile libraries for GHCi",
Option "" ["enable-split-objs"] (NoArg WithSplitObjs)
"split library into smaller objects to reduce binary sizes (GHC 6.6+)",
Option "" ["disable-split-objs"] (NoArg WithoutSplitObjs)
"split library into smaller objects to reduce binary sizes (GHC 6.6+)",
Option "" ["user"] (NoArg UserFlag)
"allow dependencies to be satisfied from the user package database. also implies install --user",
Option "" ["global"] (NoArg GlobalFlag)
"(default) dependencies must be satisfied from the global package database"
]
{-
FIX: Instead of using ++ here, we might add extra arguments. That
way, we can condense the help out put to something like
--with-{haddock,happy,alex,etc}
FIX: shouldn't use default. Look in hooks?.
-}
++ (withProgramOptions progConf)
++ (programArgsOptions progConf),
cmdAction = ConfigCmd (emptyConfigFlags progConf)
}
programArgsOptions :: ProgramConfiguration -> [OptDescr (Flag a)]
programArgsOptions (ProgramConfiguration conf) = map f (keys conf)
where f name = Option "" [name ++ "-args"] (reqPathArg (ProgramArgs name))
("give the args to " ++ name)
withProgramOptions :: ProgramConfiguration -> [OptDescr (Flag a)]
withProgramOptions (ProgramConfiguration conf) = map f (keys conf)
where f name = Option "" ["with-" ++ name] (reqPathArg (WithProgram name))
("give the path to " ++ name)
reqPathArg :: (FilePath -> a) -> ArgDescr a
reqPathArg constr = ReqArg (constr . platformPath) "PATH"
reqDirArg :: (FilePath -> a) -> ArgDescr a
reqDirArg constr = ReqArg (constr . platformPath) "DIR"
parseConfigureArgs :: ProgramConfiguration -> ConfigFlags -> [String] -> [OptDescr a] ->
IO (ConfigFlags, [a], [String])
parseConfigureArgs progConf = parseArgs (configureCmd progConf) updateCfg
where updateCfg t GhcFlag = t { configHcFlavor = Just GHC }
updateCfg t NhcFlag = t { configHcFlavor = Just NHC }
updateCfg t JhcFlag = t { configHcFlavor = Just JHC }
updateCfg t HugsFlag = t { configHcFlavor = Just Hugs }
updateCfg t (WithCompiler path) = t { configHcPath = Just path }
updateCfg t (WithHcPkg path) = t { configHcPkg = Just path }
updateCfg t (WithHappy path) = t { configHappy = Just path }
updateCfg t (WithAlex path) = t { configAlex = Just path }
updateCfg t (WithHsc2hs path) = t { configHsc2hs = Just path }
updateCfg t (WithC2hs path) = t { configC2hs = Just path }
updateCfg t (WithCpphs path) = t { configCpphs = Just path }
updateCfg t (WithGreencard path) = t { configGreencard= Just path }
updateCfg t (ProgramArgs name args) = t { configPrograms = (userSpecifyArgs
name
args (configPrograms t))}
updateCfg t (WithProgram name path) = t { configPrograms = (userSpecifyPath
name
path (configPrograms t))}
updateCfg t WithVanillaLib = t { configVanillaLib = True }
updateCfg t WithoutVanillaLib = t { configVanillaLib = False, configGHCiLib = False }
updateCfg t WithProfLib = t { configProfLib = True }
updateCfg t WithoutProfLib = t { configProfLib = False }
updateCfg t WithProfExe = t { configProfExe = True }
updateCfg t WithoutProfExe = t { configProfExe = False }
updateCfg t WithGHCiLib = t { configGHCiLib = True }
updateCfg t WithoutGHCiLib = t { configGHCiLib = False }
updateCfg t (Prefix path) = t { configPrefix = Just path }
updateCfg t (BinDir path) = t { configBinDir = Just path }
updateCfg t (LibDir path) = t { configLibDir = Just path }
updateCfg t (LibSubDir path) = t { configLibSubDir= Just path }
updateCfg t (LibExecDir path) = t { configLibExecDir = Just path }
updateCfg t (DataDir path) = t { configDataDir = Just path }
updateCfg t (DataSubDir path) = t { configDataSubDir = Just path }
updateCfg t (Verbose n) = t { configVerbose = n }
updateCfg t UserFlag = t { configUser = True }
updateCfg t GlobalFlag = t { configUser = False }
updateCfg t WithSplitObjs = t { configSplitObjs = True }
updateCfg t WithoutSplitObjs = t { configSplitObjs = False }
updateCfg t (Lift _) = t
updateCfg t _ = error $ "Unexpected flag!"
buildCmd :: Cmd a
buildCmd = Cmd {
cmdName = "build",
cmdHelp = "Make this package ready for installation.",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help, cmd_verbose],
cmdAction = BuildCmd
}
parseBuildArgs :: [String] -> [OptDescr a] -> IO (BuildFlags, [a], [String])
parseBuildArgs = parseNoArgs buildCmd BuildFlags
haddockCmd :: Cmd a
haddockCmd = Cmd {
cmdName = "haddock",
cmdHelp = "Generate Haddock HTML code from Exposed-Modules.",
cmdDescription = "Requires cpphs and haddock.",
cmdOptions = [cmd_help, cmd_verbose,
Option "" ["hoogle"] (NoArg HaddockHoogle) "Generate a hoogle database"],
cmdAction = HaddockCmd
}
parseHaddockArgs :: HaddockFlags -> [String] -> [OptDescr a] -> IO (HaddockFlags, [a], [String])
parseHaddockArgs = parseArgs haddockCmd updateCfg
where updateCfg (HaddockFlags hoogle verbose) fl = case fl of
HaddockHoogle -> HaddockFlags True verbose
Verbose n -> HaddockFlags hoogle n
_ -> error "Unexpected flag!"
programaticaCmd :: Cmd a
programaticaCmd = Cmd {
cmdName = "pfe",
cmdHelp = "Generate Programatica Project.",
cmdDescription = "",
cmdOptions = [cmd_help, cmd_verbose],
cmdAction = ProgramaticaCmd
}
parseProgramaticaArgs :: [String] -> [OptDescr a] -> IO (PFEFlags, [a], [String])
parseProgramaticaArgs = parseNoArgs programaticaCmd PFEFlags
cleanCmd :: Cmd a
cleanCmd = Cmd {
cmdName = "clean",
cmdHelp = "Clean up after a build.",
cmdDescription = "Removes .hi, .o, preprocessed sources, etc.\n", -- Multi-line!
cmdOptions = [cmd_help, cmd_verbose],
cmdAction = CleanCmd
}
parseCleanArgs :: [String] -> [OptDescr a] -> IO (CleanFlags, [a], [String])
parseCleanArgs = parseNoArgs cleanCmd CleanFlags
installCmd :: Cmd a
installCmd = Cmd {
cmdName = "install",
cmdHelp = "Copy the files into the install locations. Run register.",
cmdDescription = "Unlike the copy command, install calls the register command.\nIf you want to install into a location that is not what was\nspecified in the configure step, use the copy command.\n",
cmdOptions = [cmd_help, cmd_verbose,
Option "" ["install-prefix"] (reqDirArg InstPrefix)
"[DEPRECATED, use copy]",
Option "" ["user"] (NoArg UserFlag)
"upon registration, register this package in the user's local package database",
Option "" ["global"] (NoArg GlobalFlag)
"(default; override with configure) upon registration, register this package in the system-wide package database"
],
cmdAction = InstallCmd
}
copyCmd :: Cmd a
copyCmd = Cmd {
cmdName = "copy",
cmdHelp = "Copy the files into the install locations.",
cmdDescription = "Does not call register, and allows a prefix at install time\nWithout the --destdir flag, configure determines location.\n",
cmdOptions = [cmd_help, cmd_verbose,
Option "" ["destdir"] (reqDirArg DestDir)
"directory to copy files to, prepended to installation directories",
Option "" ["copy-prefix"] (reqDirArg InstPrefix)
"[DEPRECATED, directory to copy files to instead of prefix]"
],
cmdAction = CopyCmd NoCopyDest
}
parseCopyArgs :: CopyFlags -> [String] -> [OptDescr a] ->
IO (CopyFlags, [a], [String])
parseCopyArgs = parseArgs copyCmd updateCfg
where updateCfg (CopyFlags copydest verbose) fl = case fl of
InstPrefix path -> (CopyFlags (CopyPrefix path) verbose)
DestDir path -> (CopyFlags (CopyTo path) verbose)
Verbose n -> (CopyFlags copydest n)
_ -> error $ "Unexpected flag!"
parseInstallArgs :: InstallFlags -> [String] -> [OptDescr a] ->
IO (InstallFlags, [a], [String])
parseInstallArgs = parseArgs installCmd updateCfg
where updateCfg (InstallFlags uFlag verbose) fl = case fl of
InstPrefix _ -> error "--install-prefix is obsolete. Use copy command instead."
UserFlag -> (InstallFlags MaybeUserUser verbose)
GlobalFlag -> (InstallFlags MaybeUserGlobal verbose)
Verbose n -> (InstallFlags uFlag n)
_ -> error $ "Unexpected flag!"
sdistCmd :: Cmd a
sdistCmd = Cmd {
cmdName = "sdist",
cmdHelp = "Generate a source distribution file (.tar.gz or .zip).",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help,cmd_verbose,
Option "" ["snapshot"] (NoArg Snapshot)
"Produce a snapshot source distribution"
],
cmdAction = SDistCmd
}
parseSDistArgs :: [String] -> [OptDescr a] -> IO (SDistFlags, [a], [String])
parseSDistArgs = parseArgs sdistCmd updateCfg (SDistFlags False 0)
where updateCfg (SDistFlags snapshot verbose) fl = case fl of
Snapshot -> (SDistFlags True verbose)
Verbose n -> (SDistFlags snapshot n)
_ -> error $ "Unexpected flag!"
testCmd :: Cmd a
testCmd = Cmd {
cmdName = "test",
cmdHelp = "Run the test suite, if any (configure with UserHooks).",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help,cmd_verbose],
cmdAction = TestCmd
}
parseTestArgs :: [String] -> [OptDescr a] -> IO (Int, [a], [String])
parseTestArgs = parseNoArgs testCmd id
registerCmd :: Cmd a
registerCmd = Cmd {
cmdName = "register",
cmdHelp = "Register this package with the compiler.",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help, cmd_verbose,
Option "" ["user"] (NoArg UserFlag)
"upon registration, register this package in the user's local package database",
Option "" ["global"] (NoArg GlobalFlag)
"(default) upon registration, register this package in the system-wide package database",
Option "" ["inplace"] (NoArg InPlaceFlag)
"register the package in the build location, so it can be used without being installed",
Option "" ["gen-script"] (NoArg GenScriptFlag)
"Instead of performing the register command, generate a script to register later",
cmd_with_hc_pkg
],
cmdAction = RegisterCmd
}
parseRegisterArgs :: RegisterFlags -> [String] -> [OptDescr a] ->
IO (RegisterFlags, [a], [String])
parseRegisterArgs = parseArgs registerCmd updateCfg
where updateCfg reg fl = case fl of
UserFlag -> reg { regUser=MaybeUserUser }
GlobalFlag -> reg { regUser=MaybeUserGlobal }
Verbose n -> reg { regVerbose=n }
GenScriptFlag -> reg { regGenScript=True }
InPlaceFlag -> reg { regInPlace=True }
WithHcPkg f -> reg { regWithHcPkg=Just f }
_ -> error $ "Unexpected flag!"
unregisterCmd :: Cmd a
unregisterCmd = Cmd {
cmdName = "unregister",
cmdHelp = "Unregister this package with the compiler.",
cmdDescription = "", -- This can be a multi-line description
cmdOptions = [cmd_help, cmd_verbose,
Option "" ["user"] (NoArg UserFlag)
"unregister this package in the user's local package database",
Option "" ["global"] (NoArg GlobalFlag)
"(default) unregister this package in the system-wide package database",
Option "" ["gen-script"] (NoArg GenScriptFlag)
"Instead of performing the unregister command, generate a script to unregister later"
],
cmdAction = UnregisterCmd
}
parseUnregisterArgs :: RegisterFlags -> [String] -> [OptDescr a] ->
IO (RegisterFlags, [a], [String])
parseUnregisterArgs = parseRegisterArgs
-- |Helper function for commands with no arguments except for verbose
-- and help.
parseNoArgs :: (Cmd a)
-> (Int -> b) -- Constructor to make this type.
-> [String] -> [OptDescr a]-> IO (b, [a], [String])
parseNoArgs cmd c = parseArgs cmd updateCfg (c 0)
where
updateCfg _ (Verbose n) = c n
updateCfg _ _ = error "Unexpected flag!"
-- |Helper function for commands with more options.
parseArgs :: Cmd a -> (cfg -> Flag a -> cfg) -> cfg ->
[String] -> [OptDescr a] -> IO (cfg, [a], [String])
parseArgs cmd updateCfg cfg args customOpts =
case getCmdOpt cmd customOpts args of
(flags, _, []) | hasHelpFlag flags -> do
printCmdHelp cmd customOpts
exitWith ExitSuccess
(flags, args', []) ->
let flags' = filter (not.isLift) flags in
return (foldl updateCfg cfg flags', unliftFlags flags, args')
(_, _, errs) -> putErrors errs
where
isLift (Lift _) = True
isLift _ = False
unliftFlags :: [Flag a] -> [a]
unliftFlags flags = [ fl | Lift fl <- flags ]
putErrors :: [String] -> IO a
putErrors errs = die $ "Errors:" ++ concat ['\n':err | err <- errs]
#ifdef DEBUG
hunitTests :: [Test]
hunitTests = []
-- The test cases kinda have to be rewritten from the ground up... :/
--hunitTests =
-- let m = [("ghc", GHC), ("nhc", NHC), ("hugs", Hugs)]
-- (flags, commands', unkFlags, ers)
-- = getOpt Permute options ["configure", "foobar", "--prefix=/foo", "--ghc", "--nhc", "--hugs", "--with-compiler=/comp", "--unknown1", "--unknown2", "--install-prefix=/foo", "--user", "--global"]
-- in [TestLabel "very basic option parsing" $ TestList [
-- "getOpt flags" ~: "failed" ~:
-- [Prefix "/foo", GhcFlag, NhcFlag, HugsFlag,
-- WithCompiler "/comp", InstPrefix "/foo", UserFlag, GlobalFlag]
-- ~=? flags,
-- "getOpt commands" ~: "failed" ~: ["configure", "foobar"] ~=? commands',
-- "getOpt unknown opts" ~: "failed" ~:
-- ["--unknown1", "--unknown2"] ~=? unkFlags,
-- "getOpt errors" ~: "failed" ~: [] ~=? ers],
--
-- TestLabel "test location of various compilers" $ TestList
-- ["configure parsing for prefix and compiler flag" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Nothing, Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name, "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "find the package tool" $ TestList
-- ["configure parsing for prefix comp flag, withcompiler" ~: "failed" ~:
-- (Right (ConfigCmd (Just comp, Just "/foo/comp", Just "/usr/local"), []))
-- ~=? (parseArgs ["--prefix=/usr/local", "--"++name,
-- "--with-compiler=/foo/comp", "configure"])
-- | (name, comp) <- m],
--
-- TestLabel "simpler commands" $ TestList
-- [flag ~: "failed" ~: (Right (flagCmd, [])) ~=? (parseArgs [flag])
-- | (flag, flagCmd) <- [("build", BuildCmd),
-- ("install", InstallCmd Nothing False),
-- ("sdist", SDistCmd),
-- ("register", RegisterCmd False)]
-- ]
-- ]
#endif
{- Testing ideas:
* IO to look for hugs and hugs-pkg (which hugs, etc)
* quickCheck to test permutations of arguments
* what other options can we over-ride with a command-line flag?
-}
|
alekar/hugs
|
packages/Cabal/Distribution/Setup.hs
|
bsd-3-clause
| 35,936
| 122
| 15
| 10,928
| 7,058
| 3,931
| 3,127
| 542
| 36
|
module Oracles.Flag (
Flag (..), flag, crossCompiling, platformSupportsSharedLibs,
ghcWithSMP, ghcWithNativeCodeGen, supportsSplitObjects
) where
import Hadrian.Oracles.TextFile
import Base
import Oracles.Setting
data Flag = ArSupportsAtFile
| CrossCompiling
| GccIsClang
| GhcUnregisterised
| LeadingUnderscore
| SolarisBrokenShld
| SplitObjectsBroken
| WithLibdw
| HaveLibMingwEx
| UseSystemFfi
-- Note, if a flag is set to empty string we treat it as set to NO. This seems
-- fragile, but some flags do behave like this, e.g. GccIsClang.
flag :: Flag -> Action Bool
flag f = do
let key = case f of
ArSupportsAtFile -> "ar-supports-at-file"
CrossCompiling -> "cross-compiling"
GccIsClang -> "gcc-is-clang"
GhcUnregisterised -> "ghc-unregisterised"
LeadingUnderscore -> "leading-underscore"
SolarisBrokenShld -> "solaris-broken-shld"
SplitObjectsBroken -> "split-objects-broken"
WithLibdw -> "with-libdw"
HaveLibMingwEx -> "have-lib-mingw-ex"
UseSystemFfi -> "use-system-ffi"
value <- lookupValueOrError configFile key
when (value `notElem` ["YES", "NO", ""]) . error $ "Configuration flag "
++ quote (key ++ " = " ++ value) ++ " cannot be parsed."
return $ value == "YES"
crossCompiling :: Action Bool
crossCompiling = flag CrossCompiling
platformSupportsSharedLibs :: Action Bool
platformSupportsSharedLibs = do
badPlatform <- anyTargetPlatform [ "powerpc-unknown-linux"
, "x86_64-unknown-mingw32"
, "i386-unknown-mingw32" ]
solaris <- anyTargetPlatform [ "i386-unknown-solaris2" ]
solarisBroken <- flag SolarisBrokenShld
return $ not (badPlatform || solaris && solarisBroken)
ghcWithSMP :: Action Bool
ghcWithSMP = do
goodArch <- anyTargetArch ["i386", "x86_64", "sparc", "powerpc", "arm"]
ghcUnreg <- flag GhcUnregisterised
return $ goodArch && not ghcUnreg
ghcWithNativeCodeGen :: Action Bool
ghcWithNativeCodeGen = do
goodArch <- anyTargetArch ["i386", "x86_64", "sparc", "powerpc"]
badOs <- anyTargetOs ["ios", "aix"]
ghcUnreg <- flag GhcUnregisterised
return $ goodArch && not badOs && not ghcUnreg
supportsSplitObjects :: Action Bool
supportsSplitObjects = do
broken <- flag SplitObjectsBroken
ghcUnreg <- flag GhcUnregisterised
goodArch <- anyTargetArch [ "i386", "x86_64", "powerpc", "sparc" ]
goodOs <- anyTargetOs [ "mingw32", "cygwin32", "linux", "darwin", "solaris2"
, "freebsd", "dragonfly", "netbsd", "openbsd" ]
return $ not broken && not ghcUnreg && goodArch && goodOs
|
bgamari/shaking-up-ghc
|
src/Oracles/Flag.hs
|
bsd-3-clause
| 2,865
| 0
| 14
| 779
| 606
| 316
| 290
| 62
| 10
|
module Network.HaskellNet.IMAP
( connectIMAP, connectIMAPPort, connectStream
-- * IMAP commands
-- ** any state commands
, noop, capability, logout
-- ** not authenticated state commands
, login, authenticate
-- ** autenticated state commands
, select, examine, create, delete, rename
, subscribe, unsubscribe
, list, lsub, status, append
-- ** selected state commands
, check, close, expunge
, search, store, copy
, idle
-- * fetch commands
, fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot
, fetchFlags, fetchR, fetchByString, fetchByStringR
-- * other types
, Flag(..), Attribute(..), MailboxStatus(..)
, SearchQuery(..), FlagsQuery(..)
, A.AuthType(..)
)
where
import Network
import Network.HaskellNet.BSStream
import Network.HaskellNet.IMAP.Connection
import Network.HaskellNet.IMAP.Types
import Network.HaskellNet.IMAP.Parsers
import qualified Network.HaskellNet.Auth as A
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Control.Applicative ((<$>))
import Control.Monad
import System.Time
import Data.Maybe
import Data.List hiding (delete)
import Data.Char
import Text.Packrat.Parse (Result)
-- suffixed by `s'
data SearchQuery = ALLs
| FLAG Flag
| UNFLAG Flag
| BCCs String
| BEFOREs CalendarTime
| BODYs String
| CCs String
| FROMs String
| HEADERs String String
| LARGERs Integer
| NEWs
| NOTs SearchQuery
| OLDs
| ONs CalendarTime
| ORs SearchQuery SearchQuery
| SENTBEFOREs CalendarTime
| SENTONs CalendarTime
| SENTSINCEs CalendarTime
| SINCEs CalendarTime
| SMALLERs Integer
| SUBJECTs String
| TEXTs String
| TOs String
| UIDs [UID]
instance Show SearchQuery where
showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q
where app_prec = 10
showQuery ALLs = "ALL"
showQuery (FLAG f) = showFlag f
showQuery (UNFLAG f) = "UN" ++ showFlag f
showQuery (BCCs addr) = "BCC " ++ addr
showQuery (BEFOREs t) = "BEFORE " ++ dateToStringIMAP t
showQuery (BODYs s) = "BODY " ++ s
showQuery (CCs addr) = "CC " ++ addr
showQuery (FROMs addr) = "FROM " ++ addr
showQuery (HEADERs f v) = "HEADER " ++ f ++ " " ++ v
showQuery (LARGERs siz) = "LARGER {" ++ show siz ++ "}"
showQuery NEWs = "NEW"
showQuery (NOTs qry) = "NOT " ++ show qry
showQuery OLDs = "OLD"
showQuery (ONs t) = "ON " ++ dateToStringIMAP t
showQuery (ORs q1 q2) = "OR " ++ show q1 ++ " " ++ show q2
showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t
showQuery (SENTONs t) = "SENTON " ++ dateToStringIMAP t
showQuery (SENTSINCEs t) = "SENTSINCE " ++ dateToStringIMAP t
showQuery (SINCEs t) = "SINCE " ++ dateToStringIMAP t
showQuery (SMALLERs siz) = "SMALLER {" ++ show siz ++ "}"
showQuery (SUBJECTs s) = "SUBJECT " ++ s
showQuery (TEXTs s) = "TEXT " ++ s
showQuery (TOs addr) = "TO " ++ addr
showQuery (UIDs uids) = concat $ intersperse "," $
map show uids
showFlag Seen = "SEEN"
showFlag Answered = "ANSWERED"
showFlag Flagged = "FLAGGED"
showFlag Deleted = "DELETED"
showFlag Draft = "DRAFT"
showFlag Recent = "RECENT"
showFlag (Keyword s) = "KEYWORD " ++ s
data FlagsQuery = ReplaceFlags [Flag]
| PlusFlags [Flag]
| MinusFlags [Flag]
----------------------------------------------------------------------
-- establish connection
connectIMAPPort :: String -> PortNumber -> IO IMAPConnection
connectIMAPPort hostname port =
handleToStream <$> connectTo hostname (PortNumber port)
>>= connectStream
connectIMAP :: String -> IO IMAPConnection
connectIMAP hostname = connectIMAPPort hostname 143
connectStream :: BSStream -> IO IMAPConnection
connectStream s =
do msg <- bsGetLine s
unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $
fail "cannot connect to the server"
newConnection s
----------------------------------------------------------------------
-- normal send commands
sendCommand' :: IMAPConnection -> String -> IO (ByteString, Int)
sendCommand' c cmdstr = do
(_, num) <- withNextCommandNum c $ \num -> bsPutCrLf (stream c) $
BS.pack $ show6 num ++ " " ++ cmdstr
resp <- getResponse (stream c)
return (resp, num)
show6 :: (Ord a, Num a, Show a) => a -> String
show6 n | n > 100000 = show n
| n > 10000 = '0' : show n
| n > 1000 = "00" ++ show n
| n > 100 = "000" ++ show n
| n > 10 = "0000" ++ show n
| otherwise = "00000" ++ show n
sendCommand :: IMAPConnection -> String
-> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v))
-> IO v
sendCommand imapc cmdstr pFunc =
do (buf, num) <- sendCommand' imapc cmdstr
let (resp, mboxUp, value) = eval pFunc (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate imapc mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
getResponse :: BSStream -> IO ByteString
getResponse s = unlinesCRLF <$> getLs
where unlinesCRLF = BS.concat . concatMap (:[crlfStr])
getLs =
do l <- strip <$> bsGetLine s
case () of
_ | isLiteral l -> do l' <- getLiteral l (getLitLen l)
ls <- getLs
return (l' : ls)
| isTagged l -> (l:) <$> getLs
| otherwise -> return [l]
getLiteral l len =
do lit <- bsGet s len
l2 <- strip <$> bsGetLine s
let l' = BS.concat [l, crlfStr, lit, l2]
if isLiteral l2
then getLiteral l' (getLitLen l2)
else return l'
crlfStr = BS.pack "\r\n"
isLiteral l = BS.last l == '}' &&
BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{'
getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init
isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' '
mboxUpdate :: IMAPConnection -> MboxUpdate -> IO ()
mboxUpdate conn (MboxUpdate exists' recent') = do
when (isJust exists') $
modifyMailboxInfo conn $ \mbox -> mbox { _exists = fromJust exists' }
when (isJust recent') $
modifyMailboxInfo conn $ \mbox -> mbox { _recent = fromJust recent' }
----------------------------------------------------------------------
-- IMAP commands
--
idle :: IMAPConnection -> Int -> IO ()
idle conn timeout =
do
(buf',num) <- sendCommand' conn "IDLE"
buf <-
if BS.take 2 buf' == BS.pack "+ "
then do
_ <- bsWaitForInput (stream conn) timeout
bsPutCrLf (stream conn) $ BS.pack "DONE"
getResponse $ stream conn
else
return buf'
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
noop :: IMAPConnection -> IO ()
noop conn = sendCommand conn "NOOP" pNone
capability :: IMAPConnection -> IO [String]
capability conn = sendCommand conn "CAPABILITY" pCapability
logout :: IMAPConnection -> IO ()
logout c = do bsPutCrLf (stream c) $ BS.pack "a0001 LOGOUT"
bsClose (stream c)
login :: IMAPConnection -> A.UserName -> A.Password -> IO ()
login conn username password = sendCommand conn ("LOGIN " ++ (escapeLogin username) ++ " " ++ (escapeLogin password))
pNone
authenticate :: IMAPConnection -> A.AuthType
-> A.UserName -> A.Password -> IO ()
authenticate conn A.LOGIN username password =
do (_, num) <- sendCommand' conn "AUTHENTICATE LOGIN"
bsPutCrLf (stream conn) $ BS.pack userB64
bsGetLine (stream conn)
bsPutCrLf (stream conn) $ BS.pack passB64
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
where (userB64, passB64) = A.login username password
authenticate conn at username password =
do (c, num) <- sendCommand' conn $ "AUTHENTICATE " ++ show at
let challenge =
if BS.take 2 c == BS.pack "+ "
then A.b64Decode $ BS.unpack $ head $
dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c
else ""
bsPutCrLf (stream conn) $ BS.pack $
A.auth at challenge username password
buf <- getResponse $ stream conn
let (resp, mboxUp, value) = eval pNone (show6 num) buf
case resp of
OK _ _ -> do mboxUpdate conn $ mboxUp
return value
NO _ msg -> fail ("NO: " ++ msg)
BAD _ msg -> fail ("BAD: " ++ msg)
PREAUTH _ msg -> fail ("preauth: " ++ msg)
_select :: String -> IMAPConnection -> String -> IO ()
_select cmd conn mboxName =
do mbox' <- sendCommand conn (cmd ++ quoted mboxName) pSelect
setMailboxInfo conn $ mbox' { _mailbox = mboxName }
where
quoted s = "\"" ++ s ++ "\""
select :: IMAPConnection -> MailboxName -> IO ()
select = _select "SELECT "
examine :: IMAPConnection -> MailboxName -> IO ()
examine = _select "EXAMINE "
create :: IMAPConnection -> MailboxName -> IO ()
create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone
delete :: IMAPConnection -> MailboxName -> IO ()
delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone
rename :: IMAPConnection -> MailboxName -> MailboxName -> IO ()
rename conn mboxorg mboxnew =
sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone
subscribe :: IMAPConnection -> MailboxName -> IO ()
subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone
unsubscribe :: IMAPConnection -> MailboxName -> IO ()
unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone
list :: IMAPConnection -> IO [([Attribute], MailboxName)]
list conn = (map (\(a, _, m) -> (a, m))) <$> listFull conn "\"\"" "*"
lsub :: IMAPConnection -> IO [([Attribute], MailboxName)]
lsub conn = (map (\(a, _, m) -> (a, m))) <$> lsubFull conn "\"\"" "*"
listFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList
lsubFull :: IMAPConnection -> String -> String
-> IO [([Attribute], String, MailboxName)]
lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub
status :: IMAPConnection -> MailboxName -> [MailboxStatus]
-> IO [(MailboxStatus, Integer)]
status conn mbox stats =
let cmd = "STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")"
in sendCommand conn cmd pStatus
append :: IMAPConnection -> MailboxName -> ByteString -> IO ()
append conn mbox mailData = appendFull conn mbox mailData [] Nothing
appendFull :: IMAPConnection -> MailboxName -> ByteString
-> [Flag] -> Maybe CalendarTime -> IO ()
appendFull conn mbox mailData flags' time =
do (buf, num) <- sendCommand' conn
(unwords ["APPEND", mbox
, fstr, tstr, "{" ++ show len ++ "}"])
unless (BS.null buf || (BS.head buf /= '+')) $
fail "illegal server response"
mapM_ (bsPutCrLf $ stream conn) mailLines
buf2 <- getResponse $ stream conn
let (resp, mboxUp, ()) = eval pNone (show6 num) buf2
case resp of
OK _ _ -> mboxUpdate conn mboxUp
NO _ msg -> fail ("NO: "++msg)
BAD _ msg -> fail ("BAD: "++msg)
PREAUTH _ msg -> fail ("PREAUTH: "++msg)
where mailLines = BS.lines mailData
len = sum $ map ((2+) . BS.length) mailLines
tstr = maybe "" show time
fstr = unwords $ map show flags'
check :: IMAPConnection -> IO ()
check conn = sendCommand conn "CHECK" pNone
close :: IMAPConnection -> IO ()
close conn =
do sendCommand conn "CLOSE" pNone
setMailboxInfo conn emptyMboxInfo
expunge :: IMAPConnection -> IO [Integer]
expunge conn = sendCommand conn "EXPUNGE" pExpunge
search :: IMAPConnection -> [SearchQuery] -> IO [UID]
search conn queries = searchCharset conn "" queries
searchCharset :: IMAPConnection -> Charset -> [SearchQuery]
-> IO [UID]
searchCharset conn charset queries =
sendCommand conn ("UID SEARCH "
++ (if not . null $ charset
then charset ++ " "
else "")
++ unwords (map show queries)) pSearch
fetch :: IMAPConnection -> UID -> IO ByteString
fetch conn uid =
do lst <- fetchByString conn uid "BODY[]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[]" lst
fetchHeader :: IMAPConnection -> UID -> IO ByteString
fetchHeader conn uid =
do lst <- fetchByString conn uid "BODY[HEADER]"
return $ maybe BS.empty BS.pack $ lookup' "BODY[HEADER]" lst
fetchSize :: IMAPConnection -> UID -> IO Int
fetchSize conn uid =
do lst <- fetchByString conn uid "RFC822.SIZE"
return $ maybe 0 read $ lookup' "RFC822.SIZE" lst
fetchHeaderFields :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFields conn uid hs =
do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]")
return $ maybe BS.empty BS.pack $
lookup' ("BODY[HEADER.FIELDS "++unwords hs++"]") lst
fetchHeaderFieldsNot :: IMAPConnection
-> UID -> [String] -> IO ByteString
fetchHeaderFieldsNot conn uid hs =
do let fetchCmd = "BODY[HEADER.FIELDS.NOT "++unwords hs++"]"
lst <- fetchByString conn uid fetchCmd
return $ maybe BS.empty BS.pack $ lookup' fetchCmd lst
fetchFlags :: IMAPConnection -> UID -> IO [Flag]
fetchFlags conn uid =
do lst <- fetchByString conn uid "FLAGS"
return $ getFlags $ lookup' "FLAGS" lst
where getFlags Nothing = []
getFlags (Just s) = eval' dvFlags "" s
fetchR :: IMAPConnection -> (UID, UID)
-> IO [(UID, ByteString)]
fetchR conn r =
do lst <- fetchByStringR conn r "BODY[]"
return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $
lookup' "BODY[]" vs)) lst
fetchByString :: IMAPConnection -> UID -> String
-> IO [(String, String)]
fetchByString conn uid command =
do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id
return $ snd $ head lst
fetchByStringR :: IMAPConnection -> (UID, UID) -> String
-> IO [(UID, [(String, String)])]
fetchByStringR conn (s, e) command =
fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc
where proc (n, ps) =
(maybe (toEnum (fromIntegral n)) read (lookup' "UID" ps), ps)
fetchCommand :: IMAPConnection -> String
-> ((Integer, [(String, String)]) -> b) -> IO [b]
fetchCommand conn command proc =
(map proc) <$> sendCommand conn command pFetch
storeFull :: IMAPConnection -> String -> FlagsQuery -> Bool
-> IO [(UID, [Flag])]
storeFull conn uidstr query isSilent =
fetchCommand conn ("UID STORE " ++ uidstr ++ " " ++ flgs query) procStore
where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")"
toFStr s fstrs' =
s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs'
flgs (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs
flgs (PlusFlags fs) = toFStr "+FLAGS" $ fstrs fs
flgs (MinusFlags fs) = toFStr "-FLAGS" $ fstrs fs
procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read
(lookup' "UID" ps)
,maybe [] (eval' dvFlags "") (lookup' "FLAG" ps))
store :: IMAPConnection -> UID -> FlagsQuery -> IO ()
store conn i q = storeFull conn (show i) q True >> return ()
copyFull :: IMAPConnection -> String -> String -> IO ()
copyFull conn uidStr mbox =
sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone
copy :: IMAPConnection -> UID -> MailboxName -> IO ()
copy conn uid mbox = copyFull conn (show uid) mbox
----------------------------------------------------------------------
-- auxialiary functions
dateToStringIMAP :: CalendarTime -> String
dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date
, showMonth $ ctMonth date
, show $ ctYear date]
where show2 n | n < 10 = '0' : show n
| otherwise = show n
showMonth January = "Jan"
showMonth February = "Feb"
showMonth March = "Mar"
showMonth April = "Apr"
showMonth May = "May"
showMonth June = "Jun"
showMonth July = "Jul"
showMonth August = "Aug"
showMonth September = "Sep"
showMonth October = "Oct"
showMonth November = "Nov"
showMonth December = "Dec"
strip :: ByteString -> ByteString
strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace
crlf :: BS.ByteString
crlf = BS.pack "\r\n"
bsPutCrLf :: BSStream -> ByteString -> IO ()
bsPutCrLf h s = bsPut h s >> bsPut h crlf >> bsFlush h
lookup' :: String -> [(String, b)] -> Maybe b
lookup' _ [] = Nothing
lookup' q ((k,v):xs) | q == lastWord k = return v
| otherwise = lookup' q xs
where
lastWord = last . words
-- TODO: This is just a first trial solution for this stack overflow question:
-- http://stackoverflow.com/questions/26183675/error-when-fetching-subject-from-email-using-haskellnets-imap
-- It must be reviewed. References: rfc3501#6.2.3, rfc2683#3.4.2.
-- This function was tested against the password: `~1!2@3#4$5%6^7&8*9(0)-_=+[{]}\|;:'",<.>/? (with spaces in the laterals).
escapeLogin :: String -> String
escapeLogin x = "\"" ++ replaceSpecialChars x ++ "\""
where
replaceSpecialChars "" = ""
replaceSpecialChars (c:cs) = escapeChar c ++ replaceSpecialChars cs
escapeChar '"' = "\\\""
escapeChar '\\' = "\\\\"
escapeChar '{' = "\\{"
escapeChar '}' = "\\}"
escapeChar s = [s]
|
lemol/HaskellNet
|
src/Network/HaskellNet/IMAP.hs
|
bsd-3-clause
| 19,783
| 0
| 18
| 6,361
| 6,369
| 3,205
| 3,164
| 403
| 12
|
-- | Provides a simple main function which runs all the tests
--
module Main
( main
) where
import Test.Framework (defaultMain)
import qualified Tests.Buffer as Buffer
import qualified Tests.Properties as Properties
import qualified Tests.Regressions as Regressions
import qualified Tests.Marshal as Marshal
main :: IO ()
main = defaultMain [Buffer.tests, Properties.tests, Regressions.tests, Marshal.tests]
|
ghcjs/ghcjs-base
|
test/Tests.hs
|
mit
| 419
| 0
| 7
| 64
| 91
| 59
| 32
| 9
| 1
|
{- | Module : $Header$
- Description : Implementation of generic data structures and functions
- Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : hausmann@dfki.de
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the generic algorithm for checking
- satisfiability/provability of several types of modal logics.
-}
{-# LANGUAGE ExistentialQuantification, MultiParamTypeClasses,
FunctionalDependencies, FlexibleInstances,
FlexibleContexts, UndecidableInstances #-}
module GMP.Logics.Generic where
import Data.List
import Data.Ratio
import Data.Maybe
import Text.ParserCombinators.Parsec
import Debug.Trace
import Control.Monad.ST
{- ------------------------------------------------------------------------------
basic data types
------------------------------------------------------------------------------ -}
-- Formulae
data Formula a = F | T | And (Formula a) (Formula a) | Or (Formula a) (Formula a) |
Neg (Formula a) | Atom Int | Mod a deriving (Eq, Ord, Show)
{- ------------------------------------------------------------------------------
List of (possibly heterogenous) premises:
a list of premises may contain sequents with different types...
------------------------------------------------------------------------------ -}
-- A sequent is a list of formulae
data Sequent = forall a b c . (Feature a (b c), Eq (a (b c))) => Sequent [Formula (a (b c))]
-- A list of premises is a list of a list of sequent
type Premises = [[[Sequent]]]
data ModalOperator = Sqr | Ang | None
deriving Eq
{- ------------------------------------------------------------------------------
feature type-class
the feature type-class carries the matching function...
------------------------------------------------------------------------------ -}
class Feature a b where
-- basic methods
fMatch :: [Bool] -> [Formula (a b)] -> Premises
fPretty :: a b -> String
fFeatureFromSignature :: a b -> [Formula e] -> a e
fFeatureFromFormula :: Formula (a b) -> [Formula e] -> a e
fStripFeature :: a b -> [Formula b]
fDisj2Conj :: Formula (a b) -> Formula (a b)
fNegNorm :: Formula (a b) -> Formula (a b)
fStripFormula :: Formula (a b) -> a b
fStripFormula phi = case phi of
T -> fFeatureFromFormula phi []
F -> fFeatureFromFormula phi []
And psi xi -> fStripFormula psi
Or psi xi -> fStripFormula psi
Neg psi -> fStripFormula psi
Mod sig -> sig
-- parsing methods
fNext :: a b -> b
fParser :: a b -> Parser ([Formula e] -> a e)
fSeparator :: a b -> String
-- preproving methods
fDepth :: a b -> Int
fPreProve :: [Formula (a b)] -> Int -> [[Formula (a b)]] -> [[Formula (a b)]]
fPreProve seq i ecs = []
fMatchOptimised :: [Bool] -> [Formula (a b)] -> [[Formula (a b)]] -> Premises
fMatchOptimised flags seq ecs = fMatch flags seq
-- state monad stuff
fGetCache :: a b -> [Formula (a b)]
fGetCache sig = evalState get []
fPutCache :: a b -> [Formula (a b)] -> (GMPState [Formula (a b)]) ()
fPutCache sig = put
newtype GMPState s a = GMPState { runState :: s -> (a, s) }
evalState :: GMPState b a -> b -> a
evalState m s = fst (runState m s)
instance Monad (GMPState s) where
return a = GMPState $ \ s -> (a, s)
(GMPState x) >>= f = GMPState $ \ s -> let (v, s') = x s in runState (f v) s'
class MonadState m s | m -> s where
get :: m s
put :: s -> m ()
instance MonadState (GMPState s) s where
get = GMPState $ \ s -> (s, s)
put s = GMPState $ const ((), s)
{- ------------------------------------------------------------------------------
nonempty-features are a subclass of features
they have more default-functions than normal features though
------------------------------------------------------------------------------ -}
class (SigFeature b c d, Eq (c d)) => NonEmptyFeature a b c d where
nefMatch :: [Bool] -> [Formula (a (b (c d)))] -> Premises
nefPretty :: a (b (c d)) -> String
nefFeatureFromSignature :: a (b (c d)) -> [Formula e] -> a e
nefFeatureFromFormula :: Formula (a (b (c d))) -> [Formula e] -> a e
nefStripFeature :: a (b (c d)) -> [Formula (b (c d))]
nefDisj2Conj :: Formula (a (b (c d))) -> Formula (a (b (c d)))
nefDisj2Conj = genfDisj2Conj
nefNegNorm :: Formula (a (b (c d))) -> Formula (a (b (c d)))
nefNegNorm = genfNegNorm
nefNext :: a (b (c d)) -> b (c d)
nefNext = genfNext
nefDepth :: a (b (c d)) -> Int
nefDepth = genfDepth
nefParser :: a (b (c d)) -> Parser ([Formula e] -> a e)
nefParser sig = return (nefFeatureFromSignature sig)
nefSeparator :: a (b (c d)) -> String
nefSeparator sig = ","
instance (NonEmptyFeature a b c d, Eq (c d)) => Feature a (b (c d)) where
fMatch = nefMatch
fDisj2Conj = nefDisj2Conj
fNegNorm = nefNegNorm
fDepth = nefDepth
fNext = nefNext
fPretty = nefPretty
fFeatureFromSignature = nefFeatureFromSignature
fFeatureFromFormula = nefFeatureFromFormula
fStripFeature = nefStripFeature
fParser = nefParser
fSeparator = nefSeparator
{- ------------------------------------------------------------------------------
sigfeature type-class
the sigfeature type-class ensures correct order of features...
------------------------------------------------------------------------------ -}
class (Feature a (b c), Feature b c, Eq c) => SigFeature a b c where
-- basic methods
sMatch :: (Eq c) => [Bool] -> [Formula (a (b c))] -> Premises
sDisj2Conj :: Formula (a (b c)) -> Formula (a (b c))
sNegNorm :: Formula (a (b c)) -> Formula (a (b c))
sPretty :: a (b c) -> String
-- parsing methods
sParser :: a (b c) -> Parser ([Formula e] -> a e)
sParser = fParser
sNextSig :: a (b c) -> b c
sNextSig = fNext
pGoOn :: a (b c) -> ModalOperator -> Parser (Formula (b c))
-- preproving methods
sDepth :: Formula (a (b c)) -> Int
{- ------------------------------------------------------------------------------
nonempty-sigfeatures are a subclass of sigfeatures
they have more default-functions than normal sigfeatures though
------------------------------------------------------------------------------ -}
class (SigFeature b c d, Eq d, Feature a (b (c d)), Feature b (c d), Eq (c d)) => NonEmptySigFeature a b c d where
neMatch :: (Eq (c d)) => [Bool] -> [Formula (a (b (c d)))] -> Premises
neMatch = fMatch
neGoOn :: a (b (c d)) -> ModalOperator -> Parser (Formula (b (c d)))
neDisj2Conj :: Formula (a (b (c d))) -> Formula (a (b (c d)))
neDisj2Conj = fDisj2Conj
neNegNorm :: Formula (a (b (c d))) -> Formula (a (b (c d)))
neNegNorm = fNegNorm
neDepth :: Formula (a (b (c d))) -> Int
neDepth = genSDepth
nePretty :: a (b (c d)) -> String
nePretty sig = "{NonEmpty} " ++ fPretty sig
instance (NonEmptySigFeature a b c d, Eq (c d)) => SigFeature a b (c d) where
sMatch = neMatch
pGoOn = neGoOn
sDisj2Conj = neDisj2Conj
sNegNorm = neNegNorm
sDepth = neDepth
sPretty = nePretty
{- ------------------------------------------------------------------------------
Generic functions for Features
------------------------------------------------------------------------------ -}
genfDepth :: (Feature a (b (c d)), SigFeature b c d) => a (b (c d)) -> Int
genfDepth sig = case fStripFeature sig of
[phi] -> sDepth phi
genfNext :: (Feature a (b (c d)), SigFeature b c d) => a (b (c d)) -> b (c d)
genfNext sig = case fStripFeature sig of
[] -> fStripFormula F
phis -> fStripFormula (head phis)
genfDisj2Conj :: (Feature a (b (c d)), SigFeature b c d) => Formula (a (b (c d))) -> Formula (a (b (c d)))
genfDisj2Conj phi = Mod (fFeatureFromFormula phi (map disj2conj (fStripFeature (fStripFormula phi))))
genfNegNorm :: (Feature a (b (c d)), SigFeature b c d) => Formula (a (b (c d))) -> Formula (a (b (c d)))
genfNegNorm phi = Mod (fFeatureFromFormula phi (map negNorm (fStripFeature (fStripFormula phi))))
genfPretty :: (Feature a (b (c d)), SigFeature b c d) => a (b (c d)) -> String -> String
genfPretty d s = case fStripFeature d of
[] -> s ++ " nothing contained!"
(e : []) -> s ++ pretty e
e -> s ++ show (map pretty e)
{- ------------------------------------------------------------------------------
Generic functions for SigFeatures
------------------------------------------------------------------------------ -}
-- generic matching for sigfeatures (uses matching function of underlaying feature)
genSMatch :: (SigFeature a b (c d), SigFeature b c d, Eq d) => [Bool] -> [Formula (a (b (c d)))] -> Premises
genSMatch = fMatch
-- the depth of modal nesting of a list of formulae
ldepth :: (SigFeature a b c) => [Formula (a (b c))] -> Int
ldepth seq = maximum (map genSDepth seq)
-- generic depth of modal nesting of a formula
genSDepth :: (SigFeature a b c) => Formula (a (b c)) -> Int
genSDepth F = 0
genSDepth T = 0
genSDepth (Atom i) = 0
genSDepth (Neg phi) = genSDepth phi
genSDepth (And phi psi) = max (genSDepth phi) (genSDepth psi)
genSDepth (Or phi psi) = max (genSDepth phi) (genSDepth psi)
genSDepth (Mod xs) = 1 + fDepth xs
{- generic function to return all top-level modal arguments of phi
genSGetArgs :: (SigFeature a, Feature b, Eq e) => Formula (a (b (c (d e)))) -> [Formula (c (d e))]
genSGetArgs phi = case phi of
T -> []
F -> []
(Atom i) -> []
(Neg psi) -> sGetArgs psi
(And xi yi) -> sGetArgs xi ++ sGetArgs yi
(Or xi yi) -> sGetArgs xi ++ sGetArgs yi
(Mod sig) -> fStripFeat (sNextSig sig) -}
{- generic function to return all top-level modal arguments of phi
genHGetArgs :: (SigFeature a, Feature b, Eq e) => Formula (a (b (c (d e)))) -> [Formula (c (d e))] :*: HNil
genHGetArgs phi = case phi of
T -> [] .*. HNil
F -> [] .*. HNil
(Atom i) -> [] .*. HNil
(Neg psi) -> hGetArgs psi
(And xi yi) -> (hHead (hGetArgs xi) ++ hHead (hGetArgs yi)) .*. HNil
(Or xi yi) -> (hHead (hGetArgs xi) ++ hHead (hGetArgs yi)) .*. HNil
(Mod sig) -> fStripFeat (sNextSig sig) .*. HNil -}
{- generic function to return the list of all arguments of modality that
have nesting depth at most i
genSGetPrems :: (SigFeature a, Feature b, SigFeature c, Feature d, Eq e) =>
Int -> Formula (a (b (c (d e)))) -> [Sequent]
genSGetPrems i phi = if (sDepth phi) <= i then
let args = (sGetArgs phi)
in (Sequent args) : concatMap (sGetPrems i) (args)
else
let args = (sGetArgs phi)
in concatMap (sGetPrems i) (args) -}
{- ------------------------------------------------------------------------------
generic functions for preproving
------------------------------------------------------------------------------ -}
{- given a formula, a number i(=0) and a list of classes, compute the list of
preproving classes for the formula.
genSPreProve :: (SigFeature a, Feature b, SigFeature c, Feature d, Eq g) =>
Formula (a (b (c (d (e (f g)))))) -> Int -> [[Sequent]] -> [[Sequent]]
genSPreProve phi i seqs = let eq = (genClasses (merge (collapse (sGetPrems i phi)) seqs))
in if (i == (sDepth phi)-1) then eq
else eq ++ (genSPreProve phi (i+1) eq) -}
{- not done yet ([[1]:A, [2]:B, [3]:C, [4]:A] -> [[1,4]:A, [2]:B, [3:C]]):
collapse :: [Sequent] -> [Sequent]
collapse ((Sequent phis):seqs) = (Sequent phis):seqs -}
{- not done yet ([[1]:ABC, [2]:CDE],[[[3]:ABC,[4]:ABC],[[5]:CDE,[6]:CDE]] -> [([1],[[3],[4]]):ABC, ([2],[[5],[6]]):CDE]):
merge :: [Sequent] -> [[Sequent]] -> [DoubleSequent]
merge [] [] = [] -}
{- given a list of pairs of sequents of the same type (the pair consisting of
the formulas which are to be treated and a list of already known classes),
return the list of the list of classes for each pair.
genClasses :: [DoubleSequent] -> [[Sequent]]
genClasses [] = []
genClasses (DoubleSequent (xis,eqs):seqs) = (classes (sFilter xis) eqs) : (genClasses seqs) -}
{- give preproving classes of a list list of formulas using the knowledge about
classes ppcs.
classes :: (SigFeature a, Feature b, Eq e) => [Formula (a (b (c (d e))))] -> [[Formula (a (b (c (d e))))]] -> [Sequent]
classes [] ppcs = []
classes (phi:phis) ppcs = let ppc = nub (phi:(ppClass phi phis ppcs))
in (Sequent ppc) : (classes ((phi:phis) \\ ppc) (ppc:ppcs)) -}
{- given a formula phi and a list of formulae, return the list of all formulae
that are in the same class as phi (using the knowledge ppcs).
ppClass :: (SigFeature a, Feature b, Eq e) => Formula (a (b (c (d e)))) -> [Formula (a (b (c (d e))))] ->
[[Formula (a (b (c (d e))))]] -> [Formula (a (b (c (d e))))]
ppClass phi [] ppcs = []
ppClass phi (psi:phis) ppcs = if (sCompute phi psi ppcs) then psi:(ppClass phi phis ppcs)
else (ppClass phi phis ppcs) -}
{- check whether the two input formulae are equivalent. If they are already in
the same preproving class, it is not necessary to prove their equivalence.
equiv :: (SigFeature a, Feature b, Eq e) => Formula (a (b (c (d e)))) -> Formula (a (b (c (d e)))) -> [[Formula (a (b (c (d e))))]] -> Bool
equiv phi psi ppc = -- trace (" <Trying to show equivalence:> "
-- ++ show (pretty phi) ++ " = " ++ show (pretty psi)) $
(any (\eqcls -> ((phi `elem` eqcls) && (psi `elem` eqcls))) ppc) ||
provable (And (Neg (And (Neg psi) phi)) (Neg (And (Neg phi) psi))) -}
{- ------------------------------------------------------------------------------
generic functions of (sig)features
------------------------------------------------------------------------------ -}
-- generic finishing feature
instance Feature a () where
fMatch flags seq = trace "\n <Matching not possible, no more layers>" [[]]
fDisj2Conj phi = F
fNegNorm phi = F
fPretty e = " nothing contained!"
fDepth phi = 0
fFeatureFromSignature = error $ "fFeatureFromSignature not implemented for" ++
" instance Feature a ()"
fFeatureFromFormula = error $ "fFeatureFromFormula not implemented for" ++
" instance Feature a ()"
fStripFeature = error $ "fStripFeature not implemented for" ++
" instance Feature a ()"
fNext = error "fNext not implemented for instance Feature a ()"
fParser = error "fParser not implemented for instance Feature a ()"
fSeparator = error "fSeparator not implemented for instance Feature a ()"
-- generic finishing feature
instance Feature a (b ()) where
fMatch flags seq = trace "\n <Matching not possible, no more layers>" [[]]
fDisj2Conj phi = F
fNegNorm phi = F
fPretty e = " nothing Contained!"
fDepth phi = 0
fFeatureFromSignature = error $ "fFeatureFromSignature not implemented for" ++
" instance Feature a (b ())"
fFeatureFromFormula = error $ "fFeatureFromFormula not implemented for" ++
" instance Feature a (b ())"
fStripFeature = error $ "fStripFeature not implemented for" ++
" instance Feature a (b ())"
fNext = error "fNext not implemented for instance Feature a (b ())"
fParser = error "fParser not implemented for instance Feature a (b ())"
fSeparator = error "fSeparator not implemented for instance Feature a (b ())"
-- generic finishing sigfeature
instance SigFeature a b () where
sMatch flags seq = trace "\n <Matching not possible, no more layers>" [[]]
sDisj2Conj phi = F
sNegNorm phi = F
sPretty sig = "{Last SigFeature} " ++ fPretty sig
sDepth phi = 0
pGoOn sig flag = trace ("finishing: " ++ sPretty sig) $ return F
{- ------------------------------------------------------------------------------
preparsing functions
------------------------------------------------------------------------------ -}
{- | Preparsing replaces all disjunctions by conjunctions and normalizes negations -
This is the form that the sequent calculus expects -}
preparse :: (SigFeature a b (c d), SigFeature b c d) => Formula (a (b (c d))) -> Formula (a (b (c d)))
preparse f = negNorm $ disj2conj f
disj2conj :: (SigFeature a b c) => Formula (a (b c)) -> Formula (a (b c))
disj2conj w = case w of
(And x y) -> let a = disj2conj x
b = disj2conj y
in And a b
(Or x y) -> let a = disj2conj x
b = disj2conj y
in Neg (And (Neg a) (Neg b))
(Neg x) -> let a = disj2conj x
in Neg a
(Mod phi) -> sDisj2Conj (Mod phi)
x -> x
negNorm :: (SigFeature a b c) => Formula (a (b c)) -> Formula (a (b c))
negNorm w = case w of
(Neg (Neg x)) -> negNorm x
(Neg x) -> neg $ negNorm x
(Mod phi) -> sNegNorm (Mod phi)
(And x y) -> let a = negNorm x
b = negNorm y
in And a b
x -> x -- there is no need for discussing "Or"
{- ------------------------------------------------------------------------------
some auxiliary functions which are used by several features
------------------------------------------------------------------------------ -}
-- generate the powerlist of a list
powerList :: [a] -> [[a]]
powerList [] = [[]]
powerList (x : xs) = powerList xs ++ map (x :) (powerList xs)
-- Remove all formulas from a container that are not positive modal literals
keep_poslits :: [Formula (a b)] -> [Formula (a b)]
keep_poslits = filter (\ phi -> case phi of Mod _ -> True; _ -> False)
-- Remove all formulas from a container that are not negative modal literals
keep_neglits :: [Formula (a b)] -> [Formula (a b)]
keep_neglits = filter (\ phi -> case phi of Neg (Mod _) -> True; _ -> False)
{- Get list [0..(length xs)-1]
Needed for 'normal-forms' of G, P -}
to_inds :: [a] -> [Int]
to_inds [] = []
to_inds xs = [0 .. length xs - 1]
{- Get the elements of a list that are indexed by the first parameter list
Needed for 'normal-forms' of G, P -}
img :: Eq (a (b c)) => [Int] -> [Formula (a (b c))] -> [Formula (a (b c))]
img inds xs = map (xs !!) inds
imgInt :: [Int] -> [Int] -> [Int]
imgInt inds xs = map (xs !!) inds
andify :: Eq (a (b c)) => [Formula (a (b c))] -> Formula (a (b c))
andify [] = F
andify (phi : []) = phi
andify (phi : phis) = And phi (andify phis)
{- ------------------------------------------------------------------------------
remove empty sequents from a list of sequents
------------------------------------------------------------------------------ -}
{- emptifys :: [Sequent] -> [Sequent]
emptifys seqs = case seqs of
[] -> []
((Sequent x):xs) -> case x of
[] -> emptifys xs
phis -> (Sequent x) : emptifys xs -}
{- emptifyss :: [[Sequent]] -> [[Sequent]]
emptifyss seqs = case seqs of
[] -> []
(x:xs) -> emptifys x : emptifyss xs -}
{- emptify :: Premises -> Premises
emptify prems = trace ("emptying "++ show (map (map (map pretty_seq)) prems))$
case prems of
[] -> []
(x:xs) -> emptifyss x : emptify xs -}
emptifys :: [Sequent] -> [Sequent]
emptifys [] = []
emptifys (s : seqs) = case s of
Sequent [] -> emptifys seqs
Sequent (x : xs) -> s : emptifys seqs
emptify :: Premises -> Premises
emptify = map (map emptifys)
{- ------------------------------------------------------------------------------
basic sequent functions
------------------------------------------------------------------------------ -}
-- expand applies all sequent rules that do not branch
expand :: [Formula (a b)] -> [Formula (a b)]
expand [] = []
expand (Neg (Neg phi) : as) = expand (phi : as)
expand (Neg (And phi psi) : as) = expand (Neg phi : Neg psi : as)
expand (a : as) = a : expand as
neg :: (SigFeature a b c) => Formula (a (b c)) -> Formula (a (b c))
neg = Neg
{- ------------------------------------------------------------------------------
pretty printing functions
------------------------------------------------------------------------------ -}
-- pretty print formula
pretty :: (Feature a (b c)) => Formula (a (b c)) -> String
pretty F = "F"; pretty T = "T";
pretty (Atom k) = "Atom" ++ show k;
pretty (Or (Neg x) y) = "(" ++ pretty x ++ ") --> (" ++ pretty y ++ ")"
pretty (Neg x) = '!' : pretty x
pretty (Or x y) = "(" ++ pretty x ++ ") OR (" ++ pretty y ++ ")"
pretty (And x y) = "(" ++ pretty x ++ ") AND (" ++ pretty y ++ ")"
pretty (Mod a) = fPretty a
-- pretty print sequent
pretty_seq :: Sequent -> String
pretty_seq (Sequent seq) = pretty_list seq
-- pretty print list of formulae
pretty_list :: (Feature a (b c)) => [Formula (a (b c))] -> String
pretty_list [] = "[]"
pretty_list (x : xs) = case xs of
[] -> pretty x
(y : ys) -> pretty x ++ " , " ++ pretty_list xs
-- pretty print list of sequents
pretty_slist :: [Sequent] -> String
pretty_slist [] = ""
pretty_slist (x : xs) = case xs of
[] -> pretty_seq x
(y : ys) -> pretty_seq x ++ " , " ++ pretty_slist xs
-- pretty print a list of lists of sequents
prettyll :: [[Sequent]] -> String
prettyll [] = ""
prettyll (x : xs) = case x of
[] -> "[[]]"
(y : ys) -> case ys of
[] -> "[" ++ pretty_seq y ++ "]" ++ prettyll xs
(z : zs) -> "[" ++ pretty_seq y ++ "," ++ pretty_slist ys ++ "]" ++ prettyll xs
-- pretty print a list of lists of lists of sequents
prettylll :: [[[Sequent]]] -> String
prettylll [] = ""
prettylll (x : xs) = case x of
[] -> "[[]]"
(y : ys) -> case ys of
[] -> "[" ++ pretty_slist y ++ "]" ++ prettylll xs
(z : zs) -> "[" ++ pretty_slist y ++ "," ++ prettyll ys ++ "]" ++ prettylll xs
{- ------------------------------------------------------------------------------
'polymorphic equality' type-class:
every feature is preserving the comparability of sequents...
------------------------------------------------------------------------------ -}
-- not needed?
{- instance Eq a => Eq (b a)
class PolyEq f
where g :: a -> f a
instance Feature a b => PolyEq a
instance (Eq a, PolyEq f) => Eq (f a) -}
{- class Eq2 f
class PolyEq2 f
where dzdu :: a -> f a
instance SigFeature a b c => PolyEq2 a
instance (Eq2 a, PolyEq2 f) => Eq2 (f a)
instance Eq2 a => Eq a -}
|
keithodulaigh/Hets
|
GMP/GMP-CoLoSS/GMP/Logics/Generic.hs
|
gpl-2.0
| 22,633
| 0
| 17
| 5,287
| 5,776
| 2,953
| 2,823
| 270
| 5
|
-- (c) 2007 Andy Gill
module HpcFlags where
import System.Console.GetOpt
import qualified Data.Set as Set
import Data.Char
import Trace.Hpc.Tix
import Trace.Hpc.Mix
import System.Exit
data Flags = Flags
{ outputFile :: String
, includeMods :: Set.Set String
, excludeMods :: Set.Set String
, hpcDir :: String
, srcDirs :: [String]
, destDir :: String
, perModule :: Bool
, decList :: Bool
, xmlOutput :: Bool
, funTotals :: Bool
, altHighlight :: Bool
, combineFun :: CombineFun -- tick-wise combine
, postFun :: PostFun --
, mergeModule :: MergeFun -- module-wise merge
}
default_flags :: Flags
default_flags = Flags
{ outputFile = "-"
, includeMods = Set.empty
, excludeMods = Set.empty
, hpcDir = ".hpc"
, srcDirs = []
, destDir = "."
, perModule = False
, decList = False
, xmlOutput = False
, funTotals = False
, altHighlight = False
, combineFun = ADD
, postFun = ID
, mergeModule = INTERSECTION
}
-- We do this after reading flags, because the defaults
-- depends on if specific flags we used.
default_final_flags :: Flags -> Flags
default_final_flags flags = flags
{ srcDirs = if null (srcDirs flags)
then ["."]
else srcDirs flags
}
type FlagOptSeq = [OptDescr (Flags -> Flags)] -> [OptDescr (Flags -> Flags)]
noArg :: String -> String -> (Flags -> Flags) -> FlagOptSeq
noArg flag detail fn = (:) $ Option [] [flag] (NoArg $ fn) detail
anArg :: String -> String -> String -> (String -> Flags -> Flags) -> FlagOptSeq
anArg flag detail argtype fn = (:) $ Option [] [flag] (ReqArg fn argtype) detail
infoArg :: String -> FlagOptSeq
infoArg info = (:) $ Option [] [] (NoArg $ id) info
excludeOpt, includeOpt, hpcDirOpt, srcDirOpt, destDirOpt, outputOpt,
perModuleOpt, decListOpt, xmlOutputOpt, funTotalsOpt,
altHighlightOpt, combineFunOpt, combineFunOptInfo, mapFunOpt,
mapFunOptInfo, unionModuleOpt :: FlagOptSeq
excludeOpt = anArg "exclude" "exclude MODULE and/or PACKAGE" "[PACKAGE:][MODULE]"
$ \ a f -> f { excludeMods = a `Set.insert` excludeMods f }
includeOpt = anArg "include" "include MODULE and/or PACKAGE" "[PACKAGE:][MODULE]"
$ \ a f -> f { includeMods = a `Set.insert` includeMods f }
hpcDirOpt = anArg "hpcdir" "sub-directory that contains .mix files" "DIR"
(\ a f -> f { hpcDir = a })
. infoArg "default .hpc [rarely used]"
srcDirOpt = anArg "srcdir" "path to source directory of .hs files" "DIR"
(\ a f -> f { srcDirs = srcDirs f ++ [a] })
. infoArg "multi-use of srcdir possible"
destDirOpt = anArg "destdir" "path to write output to" "DIR"
$ \ a f -> f { destDir = a }
outputOpt = anArg "output" "output FILE" "FILE" $ \ a f -> f { outputFile = a }
-- markup
perModuleOpt = noArg "per-module" "show module level detail" $ \ f -> f { perModule = True }
decListOpt = noArg "decl-list" "show unused decls" $ \ f -> f { decList = True }
xmlOutputOpt = noArg "xml-output" "show output in XML" $ \ f -> f { xmlOutput = True }
funTotalsOpt = noArg "fun-entry-count" "show top-level function entry counts"
$ \ f -> f { funTotals = True }
altHighlightOpt
= noArg "highlight-covered" "highlight covered code, rather that code gaps"
$ \ f -> f { altHighlight = True }
combineFunOpt = anArg "function"
"combine .tix files with join function, default = ADD" "FUNCTION"
$ \ a f -> case reads (map toUpper a) of
[(c,"")] -> f { combineFun = c }
_ -> error $ "no such combine function : " ++ a
combineFunOptInfo = infoArg
$ "FUNCTION = " ++ foldr1 (\ a b -> a ++ " | " ++ b) (map fst foldFuns)
mapFunOpt = anArg "function"
"apply function to .tix files, default = ID" "FUNCTION"
$ \ a f -> case reads (map toUpper a) of
[(c,"")] -> f { postFun = c }
_ -> error $ "no such combine function : " ++ a
mapFunOptInfo = infoArg
$ "FUNCTION = " ++ foldr1 (\ a b -> a ++ " | " ++ b) (map fst postFuns)
unionModuleOpt = noArg "union"
"use the union of the module namespace (default is intersection)"
$ \ f -> f { mergeModule = UNION }
-------------------------------------------------------------------------------
readMixWithFlags :: Flags -> Either String TixModule -> IO Mix
readMixWithFlags flags modu = readMix [ dir ++ "/" ++ hpcDir flags
| dir <- srcDirs flags
] modu
-------------------------------------------------------------------------------
command_usage :: Plugin -> IO ()
command_usage plugin =
putStrLn $
"Usage: hpc " ++ (name plugin) ++ " " ++
(usage plugin) ++
"\n" ++ summary plugin ++ "\n" ++
if null (options plugin [])
then ""
else usageInfo "\n\nOptions:\n" (options plugin [])
hpcError :: Plugin -> String -> IO a
hpcError plugin msg = do
putStrLn $ "Error: " ++ msg
command_usage plugin
exitFailure
-------------------------------------------------------------------------------
data Plugin = Plugin { name :: String
, usage :: String
, options :: FlagOptSeq
, summary :: String
, implementation :: Flags -> [String] -> IO ()
, init_flags :: Flags
, final_flags :: Flags -> Flags
}
------------------------------------------------------------------------------
-- filterModules takes a list of candidate modules,
-- and
-- * excludes the excluded modules
-- * includes the rest if there are no explicity included modules
-- * otherwise, accepts just the included modules.
allowModule :: Flags -> String -> Bool
allowModule flags full_mod
| full_mod' `Set.member` excludeMods flags = False
| pkg_name `Set.member` excludeMods flags = False
| mod_name `Set.member` excludeMods flags = False
| Set.null (includeMods flags) = True
| full_mod' `Set.member` includeMods flags = True
| pkg_name `Set.member` includeMods flags = True
| mod_name `Set.member` includeMods flags = True
| otherwise = False
where
full_mod' = pkg_name ++ mod_name
-- pkg name always ends with '/', main
(pkg_name,mod_name) =
case span (/= '/') full_mod of
(p,'/':m) -> (p ++ ":",m)
(m,[]) -> (":",m)
_ -> error "impossible case in allowModule"
filterTix :: Flags -> Tix -> Tix
filterTix flags (Tix tixs) =
Tix $ filter (allowModule flags . tixModuleName) tixs
------------------------------------------------------------------------------
-- HpcCombine specifics
data CombineFun = ADD | DIFF | SUB
deriving (Eq,Show, Read, Enum)
theCombineFun :: CombineFun -> Integer -> Integer -> Integer
theCombineFun fn = case fn of
ADD -> \ l r -> l + r
SUB -> \ l r -> max 0 (l - r)
DIFF -> \ g b -> if g > 0 then 0 else min 1 b
foldFuns :: [ (String,CombineFun) ]
foldFuns = [ (show comb,comb)
| comb <- [ADD .. SUB]
]
data PostFun = ID | INV | ZERO
deriving (Eq,Show, Read, Enum)
thePostFun :: PostFun -> Integer -> Integer
thePostFun ID x = x
thePostFun INV 0 = 1
thePostFun INV _ = 0
thePostFun ZERO _ = 0
postFuns :: [(String, PostFun)]
postFuns = [ (show pos,pos)
| pos <- [ID .. ZERO]
]
data MergeFun = INTERSECTION | UNION
deriving (Eq,Show, Read, Enum)
theMergeFun :: (Ord a) => MergeFun -> Set.Set a -> Set.Set a -> Set.Set a
theMergeFun INTERSECTION = Set.intersection
theMergeFun UNION = Set.union
mergeFuns :: [(String, MergeFun)]
mergeFuns = [ (show pos,pos)
| pos <- [INTERSECTION,UNION]
]
|
nomeata/ghc
|
utils/hpc/HpcFlags.hs
|
bsd-3-clause
| 8,099
| 83
| 15
| 2,385
| 2,261
| 1,269
| 992
| 164
| 4
|
{-# LANGUAGE QuasiQuotes #-}
module Main where
import Graphics.Vty
import qualified BenchImageFuzz
import qualified BenchNoDiffOpt
import qualified BenchRenderChar
import qualified BenchVerticalScroll
import Control.Monad
import Data.Maybe
import Data.List
import System.Environment
import System.Posix.Process
import Verify
main = do
args <- getArgs
let benches = [ ("no-diff-opt-0", BenchNoDiffOpt.bench0)
, ("render-char-0", BenchRenderChar.bench0)
, ("render-char-1", BenchRenderChar.bench1)
, ("vertical-scroll-0", BenchVerticalScroll.bench0)
, ("image-fuzz-0", BenchImageFuzz.bench0) ]
help = forM_ benches $ \(b,_) -> putStrLn $ "--" ++ b
case args of
["--help"] -> help
["-h" ] -> help
_ -> do
let args' = if args /= []
then map (drop 2) args
else map fst benches
-- drop the dash-dash "--"
results <- forM args' $ \bName -> do
case lookup bName benches of
Just b -> bench bName b
Nothing -> fail $ "No benchmark named " ++ bName
print results
return ()
bench bName b = do
putStrLn $ "starting " ++ bName
Bench bDataGen bProc <- b
bData <- bDataGen
startTimes <- bData `deepseq` getProcessTimes
bProc bData
endTimes <- getProcessTimes
let ut = userTime endTimes - userTime startTimes
st = systemTime endTimes - systemTime startTimes
putStrLn $ "user time: " ++ show ut
putStrLn $ "system time: " ++ show st
return (bName, ut, st)
|
jtdaugherty/vty
|
test/benchmark.hs
|
bsd-3-clause
| 1,688
| 0
| 21
| 551
| 449
| 232
| 217
| 46
| 5
|
{-# LANGUAGE OverloadedStrings, CPP #-}
module Tests.FFIFuns where
import Haste
import Haste.Foreign
#ifdef __HASTE__
test3 :: (Maybe Int -> Maybe String -> Bool -> IO String) -> IO String
test3 = ffi "(function(f) {return (f(null, 'str', true));})"
test1 :: (Int -> IO Int) -> IO ()
test1 = ffi "(function(f) {console.log(f(42));})"
test0 :: IO Int -> IO Int
test0 = ffi "(function(f) {return f()+1;})"
testNothing :: IO () -> IO (Maybe Int, Maybe Int)
testNothing = ffi "(function(f) {return [17, null];})"
runTest = do
test0 (return 42) >>= writeLog . show
res <- test3 (\a b c -> return $ show a ++ show (fmap reverse b) ++ show c)
writeLog res
test1 (\x -> writeLog ("Got: " ++ show x) >> return 9)
testNothing (writeLog "this should never happen") >>= writeLog . show
#else
runTest = do
putStrLn $ show (43 :: Int)
putStrLn $ show (Nothing :: Maybe Int) ++
show (fmap reverse (Just ("str" :: String))) ++
show True
putStrLn $ "Got: 42"
putStrLn $ show (9 :: Int)
putStrLn $ show (Just (17 :: Int), Nothing :: Maybe Int)
#endif
|
joelburget/haste-compiler
|
Tests/FFIFuns.hs
|
bsd-3-clause
| 1,088
| 0
| 15
| 239
| 290
| 142
| 148
| 12
| 1
|
-- Checks that using the "by" clause in a transform requires a function parameter
{-# OPTIONS_GHC -XTransformListComp #-}
module ShouldFail where
import Data.List(take)
z = [x | x <- [1..10], then take 5 by x]
|
frantisekfarka/ghc-dsi
|
testsuite/tests/typecheck/should_fail/tcfail194.hs
|
bsd-3-clause
| 215
| 0
| 8
| 40
| 50
| 29
| 21
| 4
| 1
|
-- !! function types in deriving Eq things
-- From a bug report by Dave Harrison <D.A.Harrison@newcastle.ac.uk>
module ShouldFail where
type Process a = Pid -> Time -> Message a -> ( MessList a,
Continuation a)
data Continuation a = Do (Process a) deriving Eq
type ProcList a = [ (Pid, Status, Process a) ]
data Status = Active | Passive | Busy Integer | Terminated
deriving Eq
data Message a = Create (Process a) | Created Pid | Activate Pid |
Passivate Pid | Terminate Pid | Wait Pid Time |
Query Pid a | Data Pid a | Event |
Output Pid String
deriving Eq
type MessList a = [ Message a ]
type Pid = Integer
type Time = Integer
|
sgillespie/ghc
|
testsuite/tests/typecheck/should_fail/tcfail046.hs
|
bsd-3-clause
| 828
| 0
| 9
| 322
| 197
| 118
| 79
| 15
| 0
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Futhark.Optimise.InPlaceLowering.LowerIntoStm
( lowerUpdateGPU,
lowerUpdate,
LowerUpdate,
DesiredUpdate (..),
)
where
import Control.Monad
import Control.Monad.Writer
import Data.Either
import Data.List (find, unzip4)
import Data.Maybe (isNothing, mapMaybe)
import Futhark.Analysis.PrimExp.Convert
import Futhark.Construct
import Futhark.IR.Aliases
import Futhark.IR.GPU
import Futhark.Optimise.InPlaceLowering.SubstituteIndices
data DesiredUpdate dec = DesiredUpdate
{ -- | Name of result.
updateName :: VName,
-- | Type of result.
updateType :: dec,
updateCerts :: Certs,
updateSource :: VName,
updateIndices :: Slice SubExp,
updateValue :: VName
}
deriving (Show)
instance Functor DesiredUpdate where
f `fmap` u = u {updateType = f $ updateType u}
updateHasValue :: VName -> DesiredUpdate dec -> Bool
updateHasValue name = (name ==) . updateValue
type LowerUpdate rep m =
Scope (Aliases rep) ->
Stm (Aliases rep) ->
[DesiredUpdate (LetDec (Aliases rep))] ->
Maybe (m [Stm (Aliases rep)])
lowerUpdate ::
( MonadFreshNames m,
Buildable rep,
LetDec rep ~ Type,
CanBeAliased (Op rep)
) =>
LowerUpdate rep m
lowerUpdate scope (Let pat aux (DoLoop merge form body)) updates = do
canDo <- lowerUpdateIntoLoop scope updates pat merge form body
Just $ do
(prestms, poststms, pat', merge', body') <- canDo
return $
prestms
++ [ certify (stmAuxCerts aux) $
mkLet pat' $ DoLoop merge' form body'
]
++ poststms
lowerUpdate
_
(Let pat aux (BasicOp (SubExp (Var v))))
[DesiredUpdate bindee_nm bindee_dec cs src (Slice is) val]
| patNames pat == [src] =
let is' = fullSlice (typeOf bindee_dec) is
in Just . pure $
[ certify (stmAuxCerts aux <> cs) $
mkLet [Ident bindee_nm $ typeOf bindee_dec] $
BasicOp $ Update Unsafe v is' $ Var val
]
lowerUpdate _ _ _ =
Nothing
lowerUpdateGPU :: MonadFreshNames m => LowerUpdate GPU m
lowerUpdateGPU
scope
(Let pat aux (Op (SegOp (SegMap lvl space ts kbody))))
updates
| all ((`elem` patNames pat) . updateValue) updates,
not source_used_in_kbody = do
mk <- lowerUpdatesIntoSegMap scope pat updates space kbody
Just $ do
(pat', kbody', poststms) <- mk
let cs = stmAuxCerts aux <> foldMap updateCerts updates
return $
certify cs (Let pat' aux $ Op $ SegOp $ SegMap lvl space ts kbody') :
stmsToList poststms
where
-- This check is a bit more conservative than ideal. In a perfect
-- world, we would allow indexing a[i,j] if the update is also
-- to exactly a[i,j], as that will not create cross-iteration
-- dependencies. (Although the type checker wouldn't be able to
-- permit this anyway.)
source_used_in_kbody =
mconcat (map (`lookupAliases` scope) (namesToList (freeIn kbody)))
`namesIntersect` mconcat (map ((`lookupAliases` scope) . updateSource) updates)
lowerUpdateGPU scope stm updates = lowerUpdate scope stm updates
lowerUpdatesIntoSegMap ::
MonadFreshNames m =>
Scope (Aliases GPU) ->
Pat (Aliases GPU) ->
[DesiredUpdate (LetDec (Aliases GPU))] ->
SegSpace ->
KernelBody (Aliases GPU) ->
Maybe
( m
( Pat (Aliases GPU),
KernelBody (Aliases GPU),
Stms (Aliases GPU)
)
)
lowerUpdatesIntoSegMap scope pat updates kspace kbody = do
-- The updates are all-or-nothing. Being more liberal would require
-- changes to the in-place-lowering pass itself.
mk <- zipWithM onRet (patElems pat) (kernelBodyResult kbody)
return $ do
(pes, bodystms, krets, poststms) <- unzip4 <$> sequence mk
return
( Pat pes,
kbody
{ kernelBodyStms = kernelBodyStms kbody <> mconcat bodystms,
kernelBodyResult = krets
},
mconcat poststms
)
where
(gtids, _dims) = unzip $ unSegSpace kspace
onRet (PatElem v v_dec) ret
| Just (DesiredUpdate bindee_nm bindee_dec _cs src slice _val) <-
find ((== v) . updateValue) updates = do
Returns _ cs se <- Just ret
-- The slice we're writing per thread must fully cover the
-- underlying dimensions.
guard $
let (dims', slice') =
unzip . drop (length gtids) . filter (isNothing . dimFix . snd) $
zip (arrayDims (typeOf bindee_dec)) (unSlice slice)
in isFullSlice (Shape dims') (Slice slice')
Just $ do
(slice', bodystms) <-
flip runBuilderT scope $
traverse (toSubExp "index") $
fixSlice (fmap pe64 slice) $ map (pe64 . Var) gtids
let res_dims = take (length slice') $ arrayDims $ snd bindee_dec
ret' = WriteReturns cs (Shape res_dims) src [(Slice $ map DimFix slice', se)]
v_aliased <- newName v
return
( PatElem bindee_nm bindee_dec,
bodystms,
ret',
stmsFromList
[ mkLet [Ident v_aliased $ typeOf v_dec] $ BasicOp $ Index bindee_nm slice,
mkLet [Ident v $ typeOf v_dec] $ BasicOp $ Copy v_aliased
]
)
onRet pe ret =
Just $ return (pe, mempty, ret, mempty)
lowerUpdateIntoLoop ::
( Buildable rep,
BuilderOps rep,
Aliased rep,
LetDec rep ~ (als, Type),
MonadFreshNames m
) =>
Scope rep ->
[DesiredUpdate (LetDec rep)] ->
Pat rep ->
[(FParam rep, SubExp)] ->
LoopForm rep ->
Body rep ->
Maybe
( m
( [Stm rep],
[Stm rep],
[Ident],
[(FParam rep, SubExp)],
Body rep
)
)
lowerUpdateIntoLoop scope updates pat val form body = do
-- Algorithm:
--
-- 0) Map each result of the loop body to a corresponding in-place
-- update, if one exists.
--
-- 1) Create new merge variables corresponding to the arrays being
-- updated; extend the pattern and the @res@ list with these,
-- and remove the parts of the result list that have a
-- corresponding in-place update.
--
-- (The creation of the new merge variable identifiers is
-- actually done at the same time as step (0)).
--
-- 2) Create in-place updates at the end of the loop body.
--
-- 3) Create index expressions that read back the values written
-- in (2). If the merge parameter corresponding to this value
-- is unique, also @copy@ this value.
--
-- 4) Update the result of the loop body to properly pass the new
-- arrays and indexed elements to the next iteration of the
-- loop.
--
-- We also check that the merge parameters we work with have
-- loop-invariant shapes.
-- Safety condition (8).
forM_ (zip val $ bodyAliases body) $ \((p, _), als) ->
guard $ not $ paramName p `nameIn` als
mk_in_place_map <- summariseLoop scope updates usedInBody resmap val
Just $ do
in_place_map <- mk_in_place_map
(val', prestms, poststms) <- mkMerges in_place_map
let valpat = mkResAndPat in_place_map
idxsubsts = indexSubstitutions in_place_map
(idxsubsts', newstms) <- substituteIndices idxsubsts $ bodyStms body
(body_res, res_stms) <- manipulateResult in_place_map idxsubsts'
let body' = mkBody (newstms <> res_stms) body_res
return (prestms, poststms, valpat, val', body')
where
usedInBody =
mconcat $ map (`lookupAliases` scope) $ namesToList $ freeIn body <> freeIn form
resmap = zip (bodyResult body) $ patIdents pat
mkMerges ::
(MonadFreshNames m, Buildable rep) =>
[LoopResultSummary (als, Type)] ->
m ([(Param DeclType, SubExp)], [Stm rep], [Stm rep])
mkMerges summaries = do
((origmerge, extramerge), (prestms, poststms)) <-
runWriterT $ partitionEithers <$> mapM mkMerge summaries
return (origmerge ++ extramerge, prestms, poststms)
mkMerge summary
| Just (update, mergename, mergedec) <- relatedUpdate summary = do
source <- newVName "modified_source"
let source_t = snd $ updateType update
elmident =
Ident
(updateValue update)
(source_t `setArrayDims` sliceDims (updateIndices update))
tell
( [ mkLet [Ident source source_t] . BasicOp $
Update
Unsafe
(updateSource update)
(fullSlice source_t $ unSlice $ updateIndices update)
$ snd $ mergeParam summary
],
[ mkLet [elmident] . BasicOp $
Index
(updateName update)
(fullSlice source_t $ unSlice $ updateIndices update)
]
)
return $
Right
( Param mempty mergename (toDecl (typeOf mergedec) Unique),
Var source
)
| otherwise = return $ Left $ mergeParam summary
mkResAndPat summaries =
let (origpat, extrapat) = partitionEithers $ map mkResAndPat' summaries
in origpat ++ extrapat
mkResAndPat' summary
| Just (update, _, _) <- relatedUpdate summary =
Right (Ident (updateName update) (snd $ updateType update))
| otherwise =
Left (inPatAs summary)
summariseLoop ::
( Aliased rep,
MonadFreshNames m
) =>
Scope rep ->
[DesiredUpdate (als, Type)] ->
Names ->
[(SubExpRes, Ident)] ->
[(Param DeclType, SubExp)] ->
Maybe (m [LoopResultSummary (als, Type)])
summariseLoop scope updates usedInBody resmap merge =
sequence <$> zipWithM summariseLoopResult resmap merge
where
summariseLoopResult (se, v) (fparam, mergeinit)
| Just update <- find (updateHasValue $ identName v) updates =
-- Safety condition (7)
if usedInBody `namesIntersect` lookupAliases (updateSource update) scope
then Nothing
else
if hasLoopInvariantShape fparam
then Just $ do
lowered_array <- newVName "lowered_array"
return
LoopResultSummary
{ resultSubExp = se,
inPatAs = v,
mergeParam = (fparam, mergeinit),
relatedUpdate =
Just
( update,
lowered_array,
updateType update
)
}
else Nothing
summariseLoopResult _ _ =
Nothing -- XXX: conservative; but this entire pass is going away.
hasLoopInvariantShape = all loopInvariant . arrayDims . paramType
merge_param_names = map (paramName . fst) merge
loopInvariant (Var v) = v `notElem` merge_param_names
loopInvariant Constant {} = True
data LoopResultSummary dec = LoopResultSummary
{ resultSubExp :: SubExpRes,
inPatAs :: Ident,
mergeParam :: (Param DeclType, SubExp),
relatedUpdate :: Maybe (DesiredUpdate dec, VName, dec)
}
deriving (Show)
indexSubstitutions :: Typed dec => [LoopResultSummary dec] -> IndexSubstitutions
indexSubstitutions = mapMaybe getSubstitution
where
getSubstitution res = do
(DesiredUpdate _ _ cs _ is _, nm, dec) <- relatedUpdate res
let name = paramName $ fst $ mergeParam res
return (name, (cs, nm, typeOf dec, is))
manipulateResult ::
(Buildable rep, MonadFreshNames m) =>
[LoopResultSummary (LetDec rep)] ->
IndexSubstitutions ->
m (Result, Stms rep)
manipulateResult summaries substs = do
let (orig_ses, updated_ses) = partitionEithers $ map unchangedRes summaries
(subst_ses, res_stms) <- runWriterT $ zipWithM substRes updated_ses substs
pure (orig_ses ++ subst_ses, stmsFromList res_stms)
where
unchangedRes summary =
case relatedUpdate summary of
Nothing -> Left $ resultSubExp summary
Just _ -> Right $ resultSubExp summary
substRes (SubExpRes res_cs (Var res_v)) (subst_v, (_, nm, _, _))
| res_v == subst_v =
pure $ SubExpRes res_cs $ Var nm
substRes (SubExpRes res_cs res_se) (_, (cs, nm, dec, Slice is)) = do
v' <- newIdent' (++ "_updated") $ Ident nm $ typeOf dec
tell
[ certify (res_cs <> cs) . mkLet [v'] . BasicOp $
Update Unsafe nm (fullSlice (typeOf dec) is) res_se
]
pure $ varRes $ identName v'
|
HIPERFIT/futhark
|
src/Futhark/Optimise/InPlaceLowering/LowerIntoStm.hs
|
isc
| 12,524
| 0
| 22
| 3,741
| 3,591
| 1,846
| 1,745
| 272
| 5
|
module Wobsurv.Util.HTTP.Model where
import BasePrelude
import qualified Data.ByteString as ByteString
type BS =
ByteString.ByteString
type Version =
(Word, Word)
-- * Headers
-------------------------
data Header =
ConnectionHeader ConnectionHeader |
ContentLengthHeader ContentLengthHeader |
ContentTypeHeader ContentTypeHeader |
KeepAliveHeader KeepAliveHeader
deriving (Show, Read, Eq, Ord, Typeable, Generic)
-- | Specifies whether to keep the connection alive.
type ConnectionHeader =
Bool
-- | A length of the content in octets.
type ContentLengthHeader =
Word
-- | A MIME type of content and possibly a charset
type ContentTypeHeader =
(BS, Maybe Charset)
-- | A timeout in seconds and possibly a maximum amount of requests.
type KeepAliveHeader =
(Word, Maybe Word)
data Charset =
UTF8
deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable, Generic)
-- * Methods
-------------------------
data StandardMethod =
Options | Get | Head | Post | Put | Delete | Trace | Connect
deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable, Generic)
type Method =
Either StandardMethod BS
-- * Statuses
-------------------------
type Status =
(Word, BS)
ok :: Status = (200, "OK")
badRequest :: Status = (400, "Bad Request")
unauthorized :: Status = (401, "Unauthorized")
forbidden :: Status = (403, "Forbidden")
notFound :: Status = (404, "Not Found")
methodNotAllowed :: Status = (405, "Method Not Allowed")
requestTimeOut :: Status = (408, "Request Time-out")
entityTooLarge :: Status = (413, "Entity Too Large")
requestURITooLarge :: Status = (414, "Request-URI Too Large")
notImplemented :: Status = (501, "Not Implemented")
serviceUnavailable :: Status = (503, "Service Unavailable")
httpVersionNotSupported :: Status = (505, "HTTP Version not supported")
-- * URI
-------------------------
data URI =
AbsoluteURI !Scheme !Authority !(Maybe Port) !RelativeURI |
SchemeRelativeURI !Authority !(Maybe Port) !RelativeURI |
RelativeURI !RelativeURI
deriving (Show, Read, Eq, Ord, Typeable, Generic)
type RelativeURI =
(Maybe RelativePath, Maybe Query, Maybe Fragment)
type Authority =
Either Domain IP
data Scheme =
HTTP | HTTPS
deriving (Show, Read, Eq, Ord, Enum, Bounded, Typeable, Generic)
type Domain =
BS
type IP =
BS
type Port =
Int
type RelativePath =
BS
type Query =
BS
type Fragment =
BS
|
nikita-volkov/wobsurv
|
library/Wobsurv/Util/HTTP/Model.hs
|
mit
| 2,532
| 0
| 9
| 569
| 656
| 376
| 280
| -1
| -1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Module-level code generation.
module Orchid.Codegen.Module
( ModuleState
, msOptimizeTailRecursion
, LLVM
, ToLLVM
, toLLVM
, execLLVM
, mkModuleState
, declareFunction
, addFuncDef
, addGlobalVariable
, declareClass
, startClassDef
, makeFuncPrivate
, finishClassDef
) where
import Control.Lens (at, ix, makeLenses, makeLensesFor,
set, use, view, (%=), (&), (.=),
(.~), (<>=), (^.), _Just)
import Control.Monad (when)
import Control.Monad.Except (ExceptT, MonadError (throwError),
runExceptT)
import Control.Monad.State (MonadState, State, runState)
import Data.Foldable (foldlM)
import Data.List (find, findIndex)
import qualified Data.Map as M
import Data.Maybe (fromJust, isJust)
import qualified Data.Set as S
import Data.String.Conversions (convertString)
import Data.Text (Text)
import qualified LLVM.General.AST as AST
import LLVM.General.AST.AddrSpace (AddrSpace (AddrSpace))
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Global as G
import Serokell.Util (format')
import Orchid.Codegen.Body (ToBody (toBody), createBlocks,
execBodyGen)
import qualified Orchid.Codegen.Body as B
import Orchid.Codegen.Common (ClassVariable, ClassesMap,
FunctionData (FunctionData),
FunctionsMap,
HasClasses (classesLens),
VariableData (..), VariablesMap,
cdAllVMethods, cdOurVMethods,
cdVariables, classAndParents,
compareTypesSmart, cvInitializer,
cvName, cvType, fdArgTypes,
fdRetType, lookupClassType,
mangleClassMethodName, mkClassData,
orchidTypeToLLVM, thisPtrName,
throwCodegenError, vTableName,
vTableType, vTableTypeName)
import Orchid.Codegen.Constant (ToConstant (toConstant))
import Orchid.Codegen.Type (Type (..))
import Orchid.Error (CodegenException)
-------------------------------------------------------------------------------
-- Module Level
-------------------------------------------------------------------------------
$(makeLensesFor [("moduleDefinitions", "mDefinitions")] ''AST.Module)
-- | ModuleState is a state of the whole module.
data ModuleState = ModuleState
{ _msFunctions :: !FunctionsMap -- ^ Global functions
-- defined within
-- module
, _msPrivateFunctions :: !(S.Set Text) -- ^ Which functions are private
, _msClasses :: !ClassesMap -- ^ Classes defined
-- within module
, _msVariables :: !VariablesMap -- ^ Global variables
-- defined within
-- module
, _msClass :: !(Maybe Text) -- ^ Active class
, _msModule :: !AST.Module -- ^ LLVM Module
, _msOptimizeTailRecursion :: !Bool -- ^ Whether tail
-- recursion should
-- be optimized
} deriving (Show)
$(makeLenses ''ModuleState)
instance HasClasses ModuleState where
classesLens = msClasses
-- | LLVM is a Monad intended to be used for module code generation.
newtype LLVM a = LLVM
{ getLLVM :: ExceptT CodegenException (State ModuleState) a
} deriving (Functor,Applicative,Monad,MonadState ModuleState,MonadError CodegenException)
class ToLLVM a where
toLLVM :: a -> LLVM ()
-- | Execute LLVM Monad to produce a generated module.
execLLVM :: ModuleState -> LLVM a -> Either CodegenException AST.Module
execLLVM m = f . flip runState m . runExceptT . getLLVM
where
f (Left e,_) = Left e
f (_,s') = Right $ s' ^. msModule
-- | Make initial module state with given name and some predefined
-- functions and variables.
mkModuleState
:: Text
-> Bool
-> AST.Module
-> FunctionsMap
-> ClassesMap
-> VariablesMap
-> ModuleState
mkModuleState moduleName optimizeTailRecursion preludeModule preludeFunctions preludeClasses preludeVariables =
ModuleState
{ _msFunctions = preludeFunctions
, _msPrivateFunctions = S.empty
, _msClasses = preludeClasses
, _msVariables = preludeVariables
, _msClass = Nothing
, _msModule = preludeModule
{ AST.moduleName = convertString moduleName
}
, _msOptimizeTailRecursion = optimizeTailRecursion
}
declareFunction :: Type -> Text -> [(Type, Text)] -> LLVM ()
declareFunction retType funcName args =
msFunctions . at funcName .= Just funcData
where
funcData =
FunctionData
{ fdRetType = retType
, fdArgTypes = map fst args
}
addDefn :: AST.Definition -> LLVM ()
addDefn d = msModule . mDefinitions <>= [d]
-- | Add function with given return type, name, arguments and suite to
-- module taking active class into account.
addFuncDef :: B.ToBody a r => Type -> Text -> [(Type, Text)] -> a -> LLVM ()
addFuncDef retType funcName args suite = do
maybe globalCase classCase =<< use msClass
where
globalCase = addFuncDefDo retType funcName args bodyGlobal
bodyGlobal = do
mapM_ storeArgument args
() <$ B.addEmptyBlock B.tailRecBlockName
() <$ B.br B.tailRecBlockName
B.setBlock B.tailRecBlockName
B.toBody suite
storeArgument (argType,argName) = do
addr <- B.alloca argType
B.store addr $
( argType
, AST.LocalReference
(orchidTypeToLLVM argType)
(convertString argName))
B.addVariable argName argType addr
classCase className = do
classType <- lookupClassType className
let thisArg = (TPointer classType, thisPtrName)
mangledFuncName = mangleClassMethodName className funcName
addFuncDefDo retType mangledFuncName (thisArg : args) $
bodyClass classType
bodyClass classType = do
let thisType = TPointer classType
B.addVariable thisPtrName classType $
( thisType
, AST.LocalReference (orchidTypeToLLVM thisType) thisPtrName)
mapM_ storeArgument args
B.toBody suite
addFuncDefDo
:: (B.ToBody a r)
=> Type -> Text -> [(Type, Text)] -> a -> LLVM ()
addFuncDefDo retType funcName args suite = do
msFunctions . at funcName .= Just funcData
funcs <- use msFunctions
privFuncs <- use msPrivateFunctions
classes <- use msClasses
vars <- use msVariables
activeClass <- use msClass
optimizeTailRec <- use msOptimizeTailRecursion
case bodyEither funcs privFuncs classes vars activeClass optimizeTailRec of
Left e -> throwError e
Right body -> do
addDefn $ AST.GlobalDefinition $
G.functionDefaults
{ G.name = funcName'
, G.parameters = parameters
, G.returnType = orchidTypeToLLVM retType
, G.basicBlocks = body
}
where
funcName' = convertString funcName
funcData =
FunctionData
{ fdRetType = retType
, fdArgTypes = map fst args
}
bodyEither funcs privFuncs classes vars activeClass optimizeTailRec =
execBodyGen
funcs
privFuncs
classes
vars
funcName
activeClass
optimizeTailRec
(toBody suite) >>=
createBlocks
parameters =
( [G.Parameter (orchidTypeToLLVM t) (convertString n) [] | (t,n) <-
args]
, False)
-- | This function adds global variable with given type
-- and name to module.
addGlobalVariable
:: (ToConstant a)
=> Type -> Text -> a -> LLVM ()
addGlobalVariable varType varName varExpr = addToGlobal =<< toConstant varExpr
where
varName' = convertString varName
varType' = orchidTypeToLLVM varType
varData =
VariableData
{ vdType = varType
, vdPtrOperand = (AST.ConstantOperand $ C.GlobalReference varType' $
varName')
}
addToGlobal value = do
addDefn $ AST.GlobalDefinition $
G.globalVariableDefaults
{ G.name = varName'
, G.type' = varType'
, G.initializer = Just value
}
msVariables . at varName .= Just varData
declareClass :: Text
-> Maybe Text
-> [ClassVariable]
-> [(Text, Type)]
-> LLVM ()
declareClass className parent members virtualMethods = do
insertDummyClassData className parent
parents <- tail <$> classAndParents (Just className)
defineVTable className parents virtualMethods
parentVars <-
mapM
(\n ->
use $ msClasses . at n . _Just . cdVariables)
parents
msClasses . at className %= fmap (set cdVariables (concat parentVars))
existingMembers <- use variablesLens
mapM_ addClassVarSafe members
let allMembers = existingMembers ++ members
addTypeDefinition allMembers
addConstructor allMembers
where
variablesLens = msClasses . at className . _Just . cdVariables
vTableType' =
AST.NamedTypeReference $ convertString $ vTableTypeName className
vTablePtrType' = AST.PointerType vTableType' $ AddrSpace 0
addTypeDefinition =
addDefn . AST.TypeDefinition (convertString className) . Just .
AST.StructureType False .
(vTablePtrType' :) .
map (orchidTypeToLLVM . view cvType)
addConstructor variables =
addFuncDefDo
(TClass className $ map (view cvType) variables)
className
[] $
constructorBody variables
constructorBody variables = do
let operand =
AST.ConstantOperand .
C.Struct (Just . convertString $ className) False .
(C.GlobalReference
vTableType'
(convertString $ vTableName className) :) .
map (view cvInitializer) $
variables
B.ret . Just $ operand
addClassVarSafe classVar = do
alreadyAdded <-
isJust . find ((== classVar ^. cvName) . view cvName) <$>
use variablesLens
when alreadyAdded $ throwCodegenError $
format'
"variable {} is defined in class {} more than once"
(classVar ^. cvName, className)
msClasses . at className . _Just . cdVariables <>= [classVar]
checkNestedClass :: LLVM ()
checkNestedClass = do
cls <- use msClass
when (isJust cls) $
throwCodegenError "class definition can't appear inside another class"
-- A little bit hacky solution to make classAndParents function work.
insertDummyClassData :: Text -> Maybe Text -> LLVM()
insertDummyClassData className parent =
msClasses %= M.insert className (mkClassData [] parent [] [])
data ExtendedVirtualMethod = ExtendedVirtualMethod
{ evmClass :: !Text
, evmName :: !Text
, evmType :: !Type
} deriving (Show)
defineVTable :: Text -> [Text] -> [(Text, Type)] -> LLVM ()
defineVTable className parents virtualMethods = do
parentVirtualMethods <-
mapM
(\n ->
map (uncurry (ExtendedVirtualMethod n)) <$>
use (msClasses . at n . _Just . cdOurVMethods))
parents
let ourVirtualMethods =
map
((\(mName,mType) ->
ExtendedVirtualMethod className mName $ TPointer $
addThisPtrType className mType))
virtualMethods
jointVirtualMethods <-
joinVirtualMethods parentVirtualMethods ourVirtualMethods
let setVMethods lens methods =
msClasses . at className %=
fmap
(set lens $
map
(\ExtendedVirtualMethod{..} ->
(evmName, evmType))
methods)
setVMethods cdOurVMethods ourVirtualMethods
setVMethods cdAllVMethods jointVirtualMethods
cd <- fromJust <$> use (msClasses . at className)
addVTableTypeDefinition jointVirtualMethods
addVTable cd jointVirtualMethods
where
realVTableType jointVirtualMethods =
AST.StructureType False . map (orchidTypeToLLVM . evmType) $
jointVirtualMethods
addVTableTypeDefinition =
addDefn . AST.TypeDefinition (convertString $ vTableTypeName className) .
Just .
realVTableType
addVTable cd jointVirtualMethods =
addDefn . AST.GlobalDefinition $
G.globalVariableDefaults
{ G.name = convertString $ vTableName className
, G.type' = orchidTypeToLLVM $ vTableType className cd
, G.initializer = Just .
C.Struct (Just . convertString . vTableTypeName $ className) False .
map virtualMethodConstant $
jointVirtualMethods
}
virtualMethodConstant ExtendedVirtualMethod{..} =
C.GlobalReference
(orchidTypeToLLVM evmType)
(convertString $ mangleClassMethodName evmClass evmName)
addThisPtrType methodClass (TFunction retType argTypes) =
TFunction retType $ TPointer (TClass methodClass []) : argTypes
addThisPtrType _ _ = error "addThisPtrType: not TFunction"
joinVirtualMethods
:: [[ExtendedVirtualMethod]]
-> [ExtendedVirtualMethod]
-> LLVM [ExtendedVirtualMethod]
joinVirtualMethods parentMethods ourMethods =
foldlM step [] (concat (reverse parentMethods) ++ ourMethods)
where
step
:: [ExtendedVirtualMethod]
-> ExtendedVirtualMethod
-> LLVM [ExtendedVirtualMethod]
step l evm =
case findIndex ((evmName evm ==) . evmName) l of
Nothing -> pure $ l ++ [evm]
Just i -> do
let tExpected = evmType (l !! i)
tFound = evmType evm
typeMismatch <- not <$> compareTypesSmart tExpected tFound
when typeMismatch $
throwCodegenError $
format'
"Virtual method type mismatch (found {}, expected {})"
(tFound, tExpected)
return $ (l & ix i .~ evm)
startClassDef :: Text -> LLVM ()
startClassDef className = do
checkNestedClass
msClass .= Just className
-- | Make function in active class private.
makeFuncPrivate :: Text -> LLVM ()
makeFuncPrivate funcName =
maybe (throwCodegenError outsideClassMsg) impl =<< use msClass
where
outsideClassMsg =
"internal error: attempt to make function private outside class"
impl clsName =
msPrivateFunctions %= S.insert (mangleClassMethodName clsName funcName)
finishClassDef :: LLVM ()
finishClassDef = maybe reportError (const $ msClass .= Nothing) =<< use msClass
where
reportError =
throwCodegenError
"internal error: attempt to finish definition of class outside of class"
|
gromakovsky/Orchid
|
src/Orchid/Codegen/Module.hs
|
mit
| 16,445
| 0
| 19
| 5,707
| 3,559
| 1,865
| 1,694
| -1
| -1
|
{-# LANGUAGE RankNTypes #-}
module Main where
import Graphics.UI.SDL as SDL
( Surface
, SurfaceFlag(Fullscreen)
, Rect(Rect)
, SDLKey(SDLK_BACKSPACE, SDLK_ESCAPE, SDLK_RETURN, SDLK_SPACE, SDLK_m)
, Keysym(Keysym)
, InitFlag(InitEverything)
, Event(KeyUp)
, Pixel(Pixel)
, setCaption
, setVideoMode
, getVideoSurface
, getVideoInfo
, flip
, fillRect
, blitSurface
, videoInfoWidth
, videoInfoHeight
, surfaceGetWidth
, surfaceGetHeight
, freeSurface
, quit
, init
, waitEventBlocking
)
import Graphics.UI.SDL.Image ( load )
import Graphics.UI.SDL.Rotozoomer ( zoom )
import Control.Monad ( unless )
import Data.IORef ( IORef, newIORef, readIORef, writeIORef )
import System.Exit ( exitSuccess )
import Recogs.Util.Config ( getConfig )
import Recogs.Util.RandomList ( shuffle )
import Recogs.Data ( Game(..)
, Dimension
, Coord
, Config( configCols
, configFS
, configHeight
, configImages
, configRows
, configWidth)
)
main :: IO ()
main = do
SDL.init [InitEverything]
conf <- getConfig
config <- createAdjustedWindow "Recogs" conf
coords <- shuffle $ coordinates config
game <- initGame config coords
gameRef <- newIORef game
display gameRef
eventLoop gameRef
eventLoop :: IORef Game -> IO ()
eventLoop game = SDL.waitEventBlocking >>= handleEvent game
handleEvent :: IORef Game -> Event -> IO ()
handleEvent _ (SDL.KeyUp (Keysym SDLK_ESCAPE _ _)) = exit
handleEvent game (SDL.KeyUp (Keysym k _ _)) = handleKey game k >> eventLoop game
handleEvent game _ = eventLoop game
handleKey :: IORef Game -> SDLKey -> IO ()
handleKey game SDLK_SPACE = doNextStep game (subtract 1)
handleKey game SDLK_BACKSPACE = doNextStep game (+1)
handleKey game SDLK_RETURN = revealOrStartNext game
handleKey game SDLK_m = reshuffle game
handleKey _ _ = return ()
getSurfaceDimension :: Surface -> Dimension
getSurfaceDimension s = (surfaceGetWidth s, surfaceGetHeight s)
getScaleFactor :: Dimension -> Dimension -> Double
getScaleFactor (w1, h1) (w2, h2) = min (divide w2 w1) (divide h2 h1)
where divide a b = fromIntegral a / fromIntegral b
getOffset :: Dimension -> Dimension -> Dimension
getOffset (w1, h1) (w2, h2) = (offset w1 w2, offset h1 h2)
where offset :: Int -> Int -> Int
offset x y | x == y = 0
| otherwise = abs $ (x - y) `div` 2
getOffsetRect :: Dimension -> Dimension -> Maybe Rect
getOffsetRect a b
| a == b = Nothing
| otherwise = Just $ Rect x y 0 0
where (x, y) = getOffset a b
rangeCheck :: Ord a => a -> a -> a -> a
rangeCheck lowerBound upperBound n
| n < lowerBound = lowerBound
| n > upperBound = upperBound
| otherwise = n
maxSteps :: Config -> Int
maxSteps c = configRows c * configCols c
coordinates :: Config -> [Coord]
coordinates config = [(r, c)| r <- [0..(rows - 1)], c <- [0..(cols - 1)]]
where rows = configRows config
cols = configCols config
scaleImage :: Surface -> Double -> IO Surface
scaleImage s d = zoom s d d True
calculateBlockDimension :: Dimension -> Int -> Int -> Dimension
calculateBlockDimension (w, h) r c = ((w `div` c) + 1, (h `div` r) + 1)
calculateImageData :: Surface -> Config -> IO (Surface, Dimension, Dimension)
calculateImageData image config = do
screen <- getVideoSurface
let sf = getScaleFactor imageDimension screenDimension
imageDimension = getSurfaceDimension image
screenDimension = getSurfaceDimension screen
scaledImage <- scaleImage image sf
freeSurface image
let offset = getOffset scaledImageDimension screenDimension
scaledImageDimension = getSurfaceDimension scaledImage
blockDimension = calculateBlockDimension scaledImageDimension (configRows config) (configCols config)
return (scaledImage, blockDimension, offset)
initImageData :: Config -> IO (Surface, Dimension, Dimension)
initImageData config = do
image <- load $ head $ configImages config
calculateImageData image config
initGame :: Config -> [Coord] -> IO Game
initGame config coords = do
(image, blockDimension, offset) <- initImageData config
return Game { getConf = config
, getCoords = coords
, getStep = 0
, getImage = image
, getBlockDimension = blockDimension
, getBaseOffset = offset
, getFileNr = 0
}
doNextStep :: IORef Game -> (Int -> Int) -> IO ()
doNextStep gameRef f = do
game <- readIORef gameRef
let lastStep = getStep game
upperBound = maxSteps $ getConf game
nextStep = rangeCheck 0 upperBound $ f lastStep
unless (nextStep == lastStep) $ do
writeIORef gameRef game {getStep = nextStep}
display gameRef
nextRound :: IORef Game -> IO ()
nextRound gameRef = do
game <- readIORef gameRef
let fileNr = getFileNr game
config = getConf game
imgFiles = configImages config
if fileNr == length imgFiles - 1
then exitSuccess
else do
let nextFileNr = fileNr + 1
coords <- shuffle $ coordinates config
image <- load $ configImages config !! nextFileNr
(scaledImage, blockDimension, offset) <- calculateImageData image config
freeSurface image
clearScreen
writeIORef gameRef game { getCoords = coords
, getFileNr = nextFileNr
, getStep = maxSteps config
, getImage = scaledImage
, getBlockDimension = blockDimension
, getBaseOffset = offset
}
reshuffle :: IORef Game -> IO ()
reshuffle gameRef = do
game <- readIORef gameRef
coords <- shuffle $ coordinates $ getConf game
writeIORef gameRef game {getCoords = coords}
display gameRef
revealOrStartNext :: IORef Game -> IO ()
revealOrStartNext gameRef = do
game <- readIORef gameRef
if getStep game == 0
then nextRound gameRef
else doNextStep gameRef (*0)
clearScreen :: IO ()
clearScreen = do
screen <- getVideoSurface
_ <- fillRect screen (Just (Rect 0 0 (surfaceGetWidth screen) (surfaceGetHeight screen))) (Pixel 0x000000)
SDL.flip screen
display :: IORef Game -> IO ()
display gameRef = do
game <- readIORef gameRef
screen <- getVideoSurface
let step = getStep game
image = getImage game
coords = getCoords game
blockDimension = getBlockDimension game
offset = getBaseOffset game
_ <- showImage image screen
mapM_ (drawSegment screen blockDimension offset) $ take step coords
SDL.flip screen
showImage :: Surface -> Surface -> IO Bool
showImage surface screen = blitSurface surface Nothing screen $ getOffsetRect (getSurfaceDimension surface) (getSurfaceDimension screen)
drawSegment :: Surface -> Dimension -> Dimension -> Coord -> IO ()
drawSegment screen blockDimension (xOffset, yOffset) (row, col) = do
let (width, height) = blockDimension
x = (col * width) + xOffset
y = (row * height) + yOffset
_ <- fillRect screen (Just (Rect x y width height)) (Pixel 0x000000)
return ()
createAdjustedWindow :: String -> Config -> IO Config
createAdjustedWindow title config
| configFS config = do
info <- getVideoInfo
let w = videoInfoWidth info
h = videoInfoHeight info
_ <- setVideoMode w h 32 [Fullscreen]
return config { configWidth = w
, configHeight = h
}
| otherwise = do
let w = fromIntegral $ configWidth config
h = fromIntegral $ configHeight config
_ <- setVideoMode w h 32 []
_ <- SDL.setCaption title title
return config
exit :: IO ()
exit = do
SDL.quit
print "done..."
|
FlashKorten/recogs
|
src/Recogs.hs
|
mit
| 8,542
| 0
| 14
| 2,767
| 2,547
| 1,297
| 1,250
| 207
| 2
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -ddump-splices #-}
module Solar.Asteroid.Core.Valuable.Basics where
-- base
import Prelude(String,(.),Either(..),Bool(..),Double,Float,Integer,Char)
import Data.Int
import Data.Word
-- text
import qualified Data.Text as T
-- bytestring
import qualified Data.ByteString as B
-- local
import Solar.Asteroid.Core.Valuable.Class
import Solar.Asteroid.Core.Valuable.Derive
simpleDeriveValuable ''Int
simpleDeriveValuable ''Int8
simpleDeriveValuable ''Int16
simpleDeriveValuable ''Int32
simpleDeriveValuable ''Int64
simpleDeriveValuable ''Integer
simpleDeriveValuable ''Char
simpleDeriveValuable ''Double
simpleDeriveValuable ''Float
simpleDeriveValuable ''Word8
simpleDeriveValuable ''Word16
simpleDeriveValuable ''Word32
simpleDeriveValuable ''Word64
useSerializeInstance ''B.ByteString
deriveTextFromBinary ''B.ByteString ''String
deriveAesonFromText ''B.ByteString
instance ValuableStr B.ByteString where
useSerializeInstance ''String
useAesonInstance ''String
instance TextValuable String String where
encodeAsText = T.pack
decodeFromText = Right . T.unpack
instance ValuableStr String where
useSerializeInstance ''Bool
useAesonInstance ''Bool
deriveTextFromAeson ''Bool
instance ValuableStr Bool where
|
Cordite-Studios/asteroid-core
|
src/Solar/Asteroid/Core/Valuable/Basics.hs
|
mit
| 1,454
| 0
| 7
| 146
| 333
| 171
| 162
| 41
| 0
|
module Split (
stupidSlicer,
split,
toDocument
)
where
import SplitUtil
|
axelGschaider/ttofu
|
src/Split.hs
|
mit
| 78
| 0
| 4
| 16
| 18
| 12
| 6
| 5
| 0
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
module Model where
import ClassyPrelude.Yesod
import Database.Persist.Quasi
import qualified Glot.Language as Language
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlSettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
|
prasmussen/glot-www
|
Model.hs
|
mit
| 601
| 0
| 8
| 77
| 61
| 38
| 23
| -1
| -1
|
-- Copyright © 2013 Julian Blake Kongslie <jblake@omgwallhack.org>
-- Licensed under the MIT license.
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans #-}
module Maze
where
import Control.Applicative
import Control.DeepSeq
import Control.Monad.Random
import Control.Monad.State.Strict
import Data.Array
import Data.List
import Data.Maybe
import System.Random.Shuffle
import Block
instance (MonadRandom m) => MonadRandom (StateT s m) where
getRandom = lift getRandom
getRandoms = lift getRandoms
getRandomR = lift . getRandomR
getRandomRs = lift . getRandomRs
east :: (Int, Int) -> (Int, Int)
east (x,y) = (x+1,y)
north :: (Int, Int) -> (Int, Int)
north (x,y) = (x,y-1)
south :: (Int, Int) -> (Int, Int)
south (x,y) = (x,y+1)
west :: (Int, Int) -> (Int, Int)
west (x,y) = (x-1,y)
buildMaze :: (Eq c, Functor m, Monad m, NFData c, Ord c) => Array (Int, Int) (Maybe (Block c)) -> ((Int, Int) -> Side -> [c]) -> [Block c] -> RandT StdGen m (Maybe (Map c))
buildMaze initMap colorM bs = unpartial <$> execStateT (buildCell 0 $ indices initMap) initMap
where
getColor s p = case colorM p s of
[] -> do
if inRange (bounds initMap) p
then do
m <- get
case m ! p of
Just b -> return $ \b' -> sideColors b ! s == [] || sideColors b' ! (opposite s) == [] || or [ c == c' | c <- sideColors b ! s, c' <- sideColors b' ! (opposite s) ]
Nothing -> return $ const True
else return $ const True
cs -> return $ \b' -> sideColors b' ! (opposite s) == [] || or [ c == c' | c <- cs, c' <- sideColors b' ! (opposite s) ]
killCell p x = do
m <- get
if inRange (bounds m) p
then case initMap ! p of
Just _ -> x
Nothing -> case m ! p of
Just _ -> put $ force $ m // [(p, Nothing)]
Nothing -> x
else x
buildCell _ [] = return ()
buildCell n (p:q) = do
done <- gets $ \a -> not (inRange (bounds a) p) || isJust (a ! p)
if done
then buildCell n q
else do
let q' = if n == (0::Int) then force $ nub q else q
eastColor <- getColor West $ east p
northColor <- getColor South $ north p
southColor <- getColor North $ south p
westColor <- getColor East $ west p
bs' <- shuffleM $ filter eastColor $ filter northColor $ filter southColor $ filter westColor bs
if p /= (fst $ bounds initMap) && length bs' == length bs
then buildCell n q'
else case bs' of
[] -> do
modify $ \m -> force $ m // [(p, Nothing)]
kills <- shuffleM [east, north, south, west]
foldr (\d x -> killCell (d p) x) (return ()) kills
buildCell ((n+1) `mod` 100) $ p : east p : north p : south p : west p : q'
(b:_) -> do
modify $ \m -> force $ m // [(p, Just b)]
buildCell ((n+1) `mod` 100) $ q' ++ [east p, north p, south p, west p]
|
jblake/pokemap
|
src/Maze.hs
|
mit
| 3,071
| 0
| 28
| 990
| 1,361
| 701
| 660
| 69
| 12
|
module GHCJS.DOM.VTTRegion (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/VTTRegion.hs
|
mit
| 39
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
import Data.List (foldl')
import Data.Char (digitToInt)
the_sequence =
[ "37107287533902102798797998220837590246510135740250"
, "46376937677490009712648124896970078050417018260538"
, "74324986199524741059474233309513058123726617309629"
, "91942213363574161572522430563301811072406154908250"
, "23067588207539346171171980310421047513778063246676"
, "89261670696623633820136378418383684178734361726757"
, "28112879812849979408065481931592621691275889832738"
, "44274228917432520321923589422876796487670272189318"
, "47451445736001306439091167216856844588711603153276"
, "70386486105843025439939619828917593665686757934951"
, "62176457141856560629502157223196586755079324193331"
, "64906352462741904929101432445813822663347944758178"
, "92575867718337217661963751590579239728245598838407"
, "58203565325359399008402633568948830189458628227828"
, "80181199384826282014278194139940567587151170094390"
, "35398664372827112653829987240784473053190104293586"
, "86515506006295864861532075273371959191420517255829"
, "71693888707715466499115593487603532921714970056938"
, "54370070576826684624621495650076471787294438377604"
, "53282654108756828443191190634694037855217779295145"
, "36123272525000296071075082563815656710885258350721"
, "45876576172410976447339110607218265236877223636045"
, "17423706905851860660448207621209813287860733969412"
, "81142660418086830619328460811191061556940512689692"
, "51934325451728388641918047049293215058642563049483"
, "62467221648435076201727918039944693004732956340691"
, "15732444386908125794514089057706229429197107928209"
, "55037687525678773091862540744969844508330393682126"
, "18336384825330154686196124348767681297534375946515"
, "80386287592878490201521685554828717201219257766954"
, "78182833757993103614740356856449095527097864797581"
, "16726320100436897842553539920931837441497806860984"
, "48403098129077791799088218795327364475675590848030"
, "87086987551392711854517078544161852424320693150332"
, "59959406895756536782107074926966537676326235447210"
, "69793950679652694742597709739166693763042633987085"
, "41052684708299085211399427365734116182760315001271"
, "65378607361501080857009149939512557028198746004375"
, "35829035317434717326932123578154982629742552737307"
, "94953759765105305946966067683156574377167401875275"
, "88902802571733229619176668713819931811048770190271"
, "25267680276078003013678680992525463401061632866526"
, "36270218540497705585629946580636237993140746255962"
, "24074486908231174977792365466257246923322810917141"
, "91430288197103288597806669760892938638285025333403"
, "34413065578016127815921815005561868836468420090470"
, "23053081172816430487623791969842487255036638784583"
, "11487696932154902810424020138335124462181441773470"
, "63783299490636259666498587618221225225512486764533"
, "67720186971698544312419572409913959008952310058822"
, "95548255300263520781532296796249481641953868218774"
, "76085327132285723110424803456124867697064507995236"
, "37774242535411291684276865538926205024910326572967"
, "23701913275725675285653248258265463092207058596522"
, "29798860272258331913126375147341994889534765745501"
, "18495701454879288984856827726077713721403798879715"
, "38298203783031473527721580348144513491373226651381"
, "34829543829199918180278916522431027392251122869539"
, "40957953066405232632538044100059654939159879593635"
, "29746152185502371307642255121183693803580388584903"
, "41698116222072977186158236678424689157993532961922"
, "62467957194401269043877107275048102390895523597457"
, "23189706772547915061505504953922979530901129967519"
, "86188088225875314529584099251203829009407770775672"
, "11306739708304724483816533873502340845647058077308"
, "82959174767140363198008187129011875491310547126581"
, "97623331044818386269515456334926366572897563400500"
, "42846280183517070527831839425882145521227251250327"
, "55121603546981200581762165212827652751691296897789"
, "32238195734329339946437501907836945765883352399886"
, "75506164965184775180738168837861091527357929701337"
, "62177842752192623401942399639168044983993173312731"
, "32924185707147349566916674687634660915035914677504"
, "99518671430235219628894890102423325116913619626622"
, "73267460800591547471830798392868535206946944540724"
, "76841822524674417161514036427982273348055556214818"
, "97142617910342598647204516893989422179826088076852"
, "87783646182799346313767754307809363333018982642090"
, "10848802521674670883215120185883543223812876952786"
, "71329612474782464538636993009049310363619763878039"
, "62184073572399794223406235393808339651327408011116"
, "66627891981488087797941876876144230030984490851411"
, "60661826293682836764744779239180335110989069790714"
, "85786944089552990653640447425576083659976645795096"
, "66024396409905389607120198219976047599490197230297"
, "64913982680032973156037120041377903785566085089252"
, "16730939319872750275468906903707539413042652315011"
, "94809377245048795150954100921645863754710598436791"
, "78639167021187492431995700641917969777599028300699"
, "15368713711936614952811305876380278410754449733078"
, "40789923115535562561142322423255033685442488917353"
, "44889911501440648020369068063960672322193204149535"
, "41503128880339536053299340368006977710650566631954"
, "81234880673210146739058568557934581403627822703280"
, "82616570773948327592232845941706525094512325230608"
, "22918802058777319719839450180888072429661980811197"
, "77158542502016545090413245809786882778948721859617"
, "72107838435069186155435662884062257473692284509516"
, "20849603980134001723930671666823555245252804609722"
, "53503534226472524250874054075591789781264330331690"
]
main = print $ take 10 $ show $ foldl' (\acc n -> acc + read n) 0 the_sequence
|
dpieroux/euler
|
0/0013.hs
|
mit
| 6,057
| 0
| 10
| 633
| 370
| 237
| 133
| 104
| 1
|
module TestGlob where
import Control.Monad
import Debug.Trace
import Data.Bits
import Data.Char
import Data.List
import Text.Printf
import System.FilePath
import System.Directory
import System.Random
import Glob
-- TODO:
-- * Test non-standard abstract syntax (GlobSeq's nested, unit GlobSeq's, what happens with empty string literals)
-- * Update pureTests to do matching itself somehow... so we get concise output
-- * Start a first pass at file system tests.
--
------------------------------------------------
------------------------------------------------
-- SYNTAX TESTS parseGlob/ppGlob --
------------------------------------------------
------------------------------------------------
syntaxTests = mapM_ testSyntax [
oky ("abcd",GlobLit 1 "abcd")
, oky ("\\\\abcd",GlobLit 1 "\\abcd")
, oky ("{a{b,c}d}e",GlobSeq 1 [GlobAlt 1 "1" [GlobSeq 2 [GlobLit 2 "a",GlobAlt 3 "2" [GlobLit 4 "b",GlobLit 6 "c"],GlobLit 8 "d"]],GlobLit 10 "e"])
, oky ("ab/cd", GlobSeq 1 [GlobLit 1 "ab",GlobSep 3,GlobLit 4 "cd"])
, oky ("a$var{b,c}d", GlobSeq 1 [GlobLit 1 "a",GlobAlt 2 "var" [GlobLit 7 "b",GlobLit 9 "c"],GlobLit 11 "d"])
, oky ("$\"var (\\\"quoted\\\")\"{b,c}",GlobAlt 1 "\"var (\"quoted\")\"" [GlobLit 19 "b",GlobLit 21 "c"])
, oky ("ab{c,d}ef",GlobSeq 1 [GlobLit 1 "ab",
GlobAlt 3 "1" [GlobLit 4 "c",GlobLit 6 "d"],
GlobLit 8 "ef"])
, oky ("{a,b}",GlobAlt 1 "1" [GlobLit 2 "a",GlobLit 4 "b"])
, oky ("ab/{c,d}/ef", GlobSeq 1 [GlobLit 1 "ab",
GlobSep 3, GlobAlt 4 "1" [GlobLit 5 "c",GlobLit 7 "d"],
GlobSep 9, GlobLit 10 "ef"])
, oky ("a*b?c", GlobSeq 1 [GlobLit 1 "a",GlobAnyStr 2 "1",
GlobLit 3 "b",GlobAnyChr 4 "2",GlobLit 5 "c"])
, oky ("{aa,b*b}",GlobAlt 1 "1"
[GlobLit 2 "aa",GlobSeq 5
[GlobLit 5 "b",
GlobAnyStr 6 "2",
GlobLit 7 "b"]])
, oky ("{aaa/bb}", GlobAlt 1 "1" [GlobSeq 2 [GlobLit 2 "aaa",GlobSep 5,GlobLit 6 "bb"]])
-- ERRORS
, err ("","1. empty glob expression")
, err ("ab,cd","3. ',' outside of alternation")
, err ("$1{a,b}","2. simple variables must start with alphabetic character")
, err ("abc{unmatched","4. could not find matching '}'")
, err ("foo$var", "8. variables must annotate variable expressions")
, err ("foo$\"var\"bar", "10. variables must annotate variable expressions")
, err ("$\"\\\"{a,b}","2. unclosed quoted variable")
, err ("a{x,y}*$v?{a,b\\}..","11. could not find matching '}'")
]
where oky (s,r) = (s,Right r)
err (s,e) = (s,Left e)
testSyntax :: (String,Either String GlobExpr) -> IO ()
testSyntax (str,eeg) = do
-- print (str,eeg)
putStr $ printf "%-36s " (show str++":")
let ind = unlines . map (" "++) . lines
s = case parseGlob str of
Left err ->
case eeg of
Left rerr
| rerr `isInfixOf` err -> "ok (err good)"
| otherwise -> "FAILED: error message wrong:\n" ++ ind err
Right r -> "FAILED: parse failed: " ++ err
Right exp
| ppGlob exp /= str -> "FAILED: ppGlob mismatches: "++ppGlob exp
| otherwise ->
case eeg of
Left _ -> "FAILED: parse should have failed: "++show exp
Right ref
| exp == ref -> "ok"
| otherwise -> "FAILED: parsed value mismatch: "++show exp
putStrLn s
------------------------------------------------
------------------------------------------------
-- PURE TESTS expandGlob --
------------------------------------------------
------------------------------------------------
pureTests = sequence
[litTest1, litTest2,
altTest1, altTest2, altTest3, altTest4, altTest5,
strTest1, strTest2,
chrTest1,
cmbTest1]
-- ab - literal composition
litTest1 = runPureTestE (GlobSeq 1 [GlobLit 1 "a", GlobLit 4 "b"]) litVals1
litVals1 = ["", "a", "b", "aa","ab", "abs"]
-- ab - with embedded sequences
litTest2 = runPureTestE (GlobSeq 0 [GlobSeq 1 [GlobSeq 0 [GlobLit 1 "a"], GlobSeq 0 [GlobLit 4 "b"]]]) litVals1
litTest3 = runPureTestS "a/b" ["","a","a/b","a/bs","a/b/s"]
-- {a,b}x - prefix alternation
altTest1 = runPureTestE (GlobSeq 1 [
GlobAlt 1 "1" [GlobLit 2 "a", GlobLit 4 "b"],
GlobLit 6 "x"])
["","a","ax","axs","ay","bx"]
-- a{x,y} - suffix alternation
altTest2 = runPureTestE (GlobSeq 1 [
GlobLit 1 "a",
GlobAlt 2 "1" [GlobLit 3 "x", GlobLit 5 "y"]]) ["","a","ax","axs","ay","b"]
-- {a,b}x{c,d} - multiple variables
altTest3 = runPureTestE (GlobSeq 1 [
GlobAlt 1 "1" [GlobLit 2 "a", GlobLit 4 "b"],
GlobLit 6 "x",
GlobAlt 8 "2" [GlobLit 2 "c", GlobLit 4 "d"]]) altVals3
altVals3 = ["","a","ax","bx","axc","axd","axds","axx","bxd","bxa","bxds"]
-- {a,b}x{c,d} - multiple variables with sequences embedded
altTest4 = runPureTestE (GlobSeq 1 [
GlobSeq 1 [GlobAlt 1 "1" [GlobLit 2 "a", GlobSeq 4 [GlobLit 4 "b"]]],
GlobSeq 6 [GlobLit 6 "x"],
GlobSeq 8 [GlobAlt 8 "2" [GlobLit 10 "c", GlobLit 12 "d"]]]) altVals3
-- a{x,y{z,w}} - nested expressions
altTest5 = runPureTestE (GlobSeq 1 [
GlobLit 1 "a",
GlobAlt 2 "1" [
GlobLit 3 "x",
GlobSeq 5 [GlobLit 5 "y",GlobAlt 6 "2" [GlobLit 7 "z",GlobLit 9 "w"]]]])
["","a","ax","axs","ay","ayz","ayw","ayzs"]
-- * - any string
strTest1 = runPureTestE (GlobSeq 1 [GlobAnyStr 1 "1"])
["","a","ab","cd","ab/cd"]
-- ** - any string combination
strTest2 = runPureTestE (GlobSeq 1 [GlobAnyStr 1 "1", GlobAnyStr 2 "2"])
["","a","abc"]
-- ? - any char
chrTest1 = runPureTestE (GlobSeq 1 [GlobAnyChr 1 "1"])
["","a","ab"]
-- ?a?
chrTest2 = runPureTestE (GlobSeq 1 [GlobAnyChr 1 "1",GlobLit 2 "b",GlobAnyChr 3 "2"])
["","a","ab","abc","abcd"]
-- "{a?*,b*}s" - combination of all constructs
cmbTest1 = runPureTestE (GlobSeq 1 [GlobAlt 1 "1" [GlobSeq 2 [GlobLit 2 "a",GlobAnyChr 3 "2",GlobAnyStr 4 "3"],GlobSeq 6 [GlobLit 6 "b",GlobAnyStr 7 "4"]],GlobLit 1 "s"])
["",
"axaas/t", -- yes
"axs/t", -- no (nothing for * after the a?)
"axyyyys/t", -- yes (x yyyy
"bzzz", -- no s after alt
"bzzzs" -- yes
]
runPureTestE :: GlobExpr -> [String] -> IO ()
runPureTestE g xs = runPureTest (Right g) xs
runPureTestS :: String -> [String] -> IO ()
runPureTestS s xs = runPureTest (Left s) xs
runPureTest :: Either String GlobExpr -> [String] -> IO ()
runPureTest eg vals = do
case eg of
Left str -> case parseGlob str of
Left err -> putStrLn $ str ++ ": FAILED: " ++ err
Right g -> runPureTest (Right g) vals
Right g -> do
putStr $ show (ppGlob g) ++ ": "
let res = concatMap (expandGlob g) vals
putStrLn $ show g
putStrLn $ " inp: " ++ show vals
putStrLn $ " res: " ++ show res
forM_ vals $ \v -> do
putStr $ printf " %-16s " (show v)
let fs = filter (\(defs,val,sfx) -> v == val ++ sfx) res
if null fs then putStrLn "no match" else do
forM_ (zip ("" : repeat " ") fs) $ \(indent,(defs,val,sfx)) -> do
putStrLn $ indent ++
printf "%-8s" val ++ " " ++ printf "%-16s " (show defs) ++
if null sfx then "" else " with suffix " ++ show sfx
------------------------------------------------
------------------------------------------------
-- PATH TESTS expandGlobPath --
------------------------------------------------
------------------------------------------------
pathTests = sequence [pathTest1,pathTest2,pathTest3]
pathTest1 = runPathTest "testdir" "top/*"
[([("1","b_y")],"top/b_y"),
([("1","b_x")],"top/b_x"),
([("1","a_y")],"top/a_y"),
([("1","a_x")],"top/a_x")]
pathTest2 = runPathTest "testdir/top" "{a,b}_{x,y}"
[([("1","b"),("2","y")],"b_y"),
([("1","b"),("2","x")],"b_x"),
([("1","a"),("2","y")],"a_y"),
([("1","a"),("2","x")],"a_x")]
pathTest3 = runPathTest "testdir" "*/{a,b}_{x,y}/*/dat"
[([("1","top"),("2","b"),("3","y"),("4","foo")],"top/b_y/foo/dat"),
([("1","top"),("2","b"),("3","y"),("4","baz")],"top/b_y/baz/dat"),
([("1","top"),("2","b"),("3","y"),("4","bar")],"top/b_y/bar/dat"),
([("1","top"),("2","b"),("3","x"),("4","qux")],"top/b_x/qux/dat"),
([("1","top"),("2","b"),("3","x"),("4","foo")],"top/b_x/foo/dat"),
([("1","top"),("2","b"),("3","x"),("4","baz")],"top/b_x/baz/dat"),
([("1","top"),("2","b"),("3","x"),("4","bar")],"top/b_x/bar/dat"),
([("1","top"),("2","a"),("3","y"),("4","qux")],"top/a_y/qux/dat"),
([("1","top"),("2","a"),("3","y"),("4","foo")],"top/a_y/foo/dat"),
([("1","top"),("2","a"),("3","y"),("4","baz")],"top/a_y/baz/dat"),
([("1","top"),("2","a"),("3","y"),("4","bar")],"top/a_y/bar/dat"),
([("1","top"),("2","a"),("3","x"),("4","qux")],"top/a_x/qux/dat"),
([("1","top"),("2","a"),("3","x"),("4","foo")],"top/a_x/foo/dat"),
([("1","top"),("2","a"),("3","x"),("4","baz")],"top/a_x/baz/dat"),
([("1","top"),("2","a"),("3","x"),("4","bar")],"top/a_x/bar/dat")]
runPathTest :: FilePath -> String -> [(VarDefs,String)] -> IO ()
runPathTest testDirRoot expr rpaths = do
putStr $ expr ++ ": "
case parseGlob expr of
Left err -> putStrLn $ ": FAILED: parse error: " ++ err
Right ge -> do
putStrLn $ show ge
ps <- expandGlobPath ge testDirRoot
putStr $ " - under dir " ++ testDirRoot ++ " this gives "
putStrLn $ show (length ps) ++ " matches"
forM_ ps $ \(vs,p) -> do
putStr $ " * " ++ show (vs,p) ++ ": "
if (vs,p) `elem` rpaths then putStr "ok"
else putStr "ERROR: unexpected entry"
putStrLn ""
let missing = rpaths \\ ps
when (not (null missing)) $ do
putStrLn "ERROR: the following are missing"
mapM_ (\(vs,p) -> putStrLn $ " * " ++ show (vs,p)) missing
makePathTestTree = do
let getDatLine f = do
let hash f = foldl1' xor (map ord f) `mod` 10
rs <- sequence (replicate 5 (randomRIO (1,10)))
let vs = map ((hash f)+) rs
return $ intercalate " " (map (printf "%6d") vs) ++ "\n"
mkFile f = do
n <- randomRIO (1,7) :: IO Int
ls <- sequence (replicate n (getDatLine f))
createDirectoryIfMissing True (takeDirectory f)
putStrLn $ f ++ ":\n" ++ concat ls
writeFile f ("#" ++ f ++ "\n" ++ concat ls)
files = ["testdir/top/" ++ a_b : "_" ++ x_y : "/" ++ fbbq ++ "/dat" |
a_b <- "ab",
x_y <- "xy",
fbbq <- ["foo","bar","baz","qux"],
a_b /= 'b' || x_y /= 'y' || (fbbq /= "baz" && fbbq /= "qux")]
mapM_ mkFile files
let badFile = "testdir/top/b_y/baz/dat"
partialBadFile = "testdir/top/b_x/baz/dat"
putStrLn $ "adding bad line to: " ++ partialBadFile
appendFile partialBadFile "malformed line in otherwise good file"
putStrLn $ "creating bad file: " ++ badFile
createDirectoryIfMissing True (takeDirectory badFile)
writeFile badFile "malformed file data"
{-
test e = expandGlobPath e "testdir"
ge0 = GlobSeq 1 [ -- top/a_x
GlobLit 1 "top", GlobSep 4, GlobLit 1 "a_x"]
ge1 = GlobSeq 1 [ -- top/*
GlobLit 1 "top", GlobSep 4,
GlobAnyStr 5 "1"]
ge2 = GlobSeq 1 [ -- top/?*
GlobLit 1 "top", GlobSep 4,
GlobAnyChr 5 "1", GlobAnyStr 6 "2"]
gt = GlobSeq 1 [
GlobLit 1 "top", GlobSep 4,
GlobAnyStr 5 "1", GlobSep 6,
GlobSeq 7 [GlobAlt 7 "2" [GlobLit 8 "a",GlobLit 10 "b"],GlobLit 7 "_",GlobAlt 13 "3" [GlobLit 14 "x",GlobLit 16 "y"]], GlobSep 18,
GlobLit 19 "dat"]
-}
|
trbauer/globexpr
|
Test/TestGlob.hs
|
mit
| 11,622
| 0
| 27
| 2,690
| 4,131
| 2,261
| 1,870
| 205
| 5
|
-- |
-- Module : Backtrace.Typechecker
-- Copyright : © 2019 Elias Castegren and Kiko Fernandez-Reyes
-- License : MIT
--
-- Stability : experimental
-- Portability : portable
--
-- This module includes everything you need to get started type checking
-- a program. To build the Abstract Syntax Tree (AST), please import and build
-- the AST from "Backtrace.AST".
--
-- The main entry point to the type checker is the combinator 'tcProgram', which
-- takes an AST and returns either an error, or the typed program.
-- For example, for the following program (using a made up syntax):
--
-- >
-- > class C
-- > val f: Foo
-- >
--
-- should be parsed and generate this AST:
--
-- > testClass1 =
-- > ClassDef {cname = "C"
-- > ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}]
-- > ,methods = []}
-- >
--
-- To type check the AST, run the 'tcProgram' combinator as follows:
--
-- > tcProgram testClass1
--
{-# LANGUAGE NamedFieldPuns, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, RankNTypes, ConstrainedClassMethods #-}
module Backtrace.Typechecker where
import Data.Map as Map hiding (foldl, map)
import Data.List as List
import Data.Maybe (fromJust)
import Data.Either (fromLeft)
import Text.Printf (printf)
import Control.Monad
import Control.Monad.Reader
import Control.Monad.Except
import Backtrace.AST
-- * Type checking monad
-- |The type checking monad. The type checking monad is the stacking
-- of the 'Reader' and 'Exception' monads.
type TypecheckM a = forall m. (MonadReader Env m, MonadError TCError m) => m a
-- * Type checking errors
-- | Declaration of type checking errors.
data TCError = TCError Error Backtrace
-- |Data declaration of available errors. Value constructors are used
-- to create statically known errors. For example:
--
-- > UnknownClassError (Name c)
--
-- creates a 'UnknownClassError'. This error should be created whenever there
-- is a class whose declaration is unknown or inexistent.
data Error =
UnknownClassError Name -- ^ Reference of a class that does not exists
| UnknownFieldError Name -- ^ Reference of a field that does not exists
| UnknownMethodError Name -- ^ Reference of a method that does not exists
| UnboundVariableError Name -- ^ Unbound variable
-- | Type mismatch error, the first @Type@ refers to the formal type argument,
-- the second @Type@ refers to the actual type argument.
| TypeMismatchError Type Type
-- | Immutable field error, used when someone violates immutability
| ImmutableFieldError Expr
-- | Error to indicate that a one cannot assign a value to expression @Expr@
| NonLValError Expr
-- | Error indicating that the return type cannot be @Null@
| PrimitiveNullError Type
-- | Used to indicate that @Type@ is not of a class type
| NonClassTypeError Type
-- | Expecting a function (arrow) type but got another type instead.
| NonArrowTypeError Type
-- | Tried to call a constructor outside of instantiation
| ConstructorCallError Type
-- | Cannot infer type of @Expr@
| UninferrableError Expr
-- |Returns a type checking monad, containing the error @err@.
-- A common example throughout the code is the following:
--
-- > tcError $ UnknownClassError c
--
-- The code above throws an error because the class @c@ was not
-- found in the environment 'Env'.
tcError :: Error -> TypecheckM a
tcError err = do
bt <- asks bt
throwError $ TCError err bt
instance Show TCError where
show (TCError err bt) =
" *** Error during typechecking *** \n" ++
show err ++ "\n" ++ show bt
instance Show Error where
show (UnknownClassError c) = printf "Unknown class '%s'" c
show (UnknownFieldError f) = printf "Unknown field '%s'" f
show (UnknownMethodError m) = printf "Unknown method '%s'" m
show (UnboundVariableError x) = printf "Unbound variable '%s'" x
show (TypeMismatchError actual expected) =
printf "Type '%s' does not match expected type '%s'"
(show actual) (show expected)
show (ImmutableFieldError e) =
printf "Cannot write to immutable field '%s'" (show e)
show (NonLValError e) =
printf "Cannot assign to expression '%s'" (show e)
show (PrimitiveNullError t) =
printf "Type '%s' cannot be null" (show t)
show (NonClassTypeError t) =
printf "Expected class type, got '%s'" (show t)
show (NonArrowTypeError t) =
printf "Expected function type, got '%s'" (show t)
show (ConstructorCallError t) =
printf "Tried to call constructor of class '%s' outside of instantiation"
(show t)
show (UninferrableError e) =
printf "Cannot infer the type of '%s'" (show e)
-- * Type checking combinators
-- | Environment. The 'Env' is used during type checking, and is updated as
-- the type checker runs. Most likely, one uses the 'Reader' monad to hide details
-- of how the environment is updated, via the common 'local' function.
data Env =
Env {ctable :: Map Name ClassDef
,vartable :: Map Name Type
,bt :: Backtrace
,constructor :: Bool}
-- | Conditionally update the environment to track if we are in a
-- constructor method.
setConstructor :: Name -> Env -> Env
setConstructor m env = env{constructor = isConstructorName m}
-- | Generates an empty environment.
emptyEnv :: Env
emptyEnv = Env {ctable = Map.empty
,vartable = Map.empty
,bt = emptyBt
,constructor = False}
-- | Helper function to lookup a class given a 'Name' and an 'Env'. Usually
-- it relies on the 'Reader' monad, so that passing the 'Env' can be omitted.
-- For example:
--
-- > findClass :: Type -> TypecheckM ClassDef
-- > findClass ty@(ClassType c) = do
-- > cls <- asks $ lookupClass c
-- > case cls of
-- > Just cdef -> return cdef
-- > Nothing -> tcError $ UnknownClassError c
-- > findClass ty = tcError $ NonClassTypeError ty
--
-- In this function ('findClass'), the 'Reader' function 'asks' injects
-- the 'Reader' monad as the last argument. More details in the paper.
lookupClass :: Name -> Env -> Maybe ClassDef
lookupClass c Env{ctable} = Map.lookup c ctable
-- | Look up a variable by its 'Name' in the 'Env', returning an option type
-- indicating whether the variable was found or not.
lookupVar :: Name -> Env -> Maybe Type
lookupVar x Env{vartable} = Map.lookup x vartable
-- | Find a class declaration by its 'Type'
findClass :: Type -> TypecheckM ClassDef
findClass ty@(ClassType c) = do
cls <- asks $ lookupClass c
case cls of
Just cdef -> return cdef
Nothing -> tcError $ UnknownClassError c
findClass ty = tcError $ NonClassTypeError ty
-- | Find a method declaration by its 'Type' and method name @m@
findMethod :: Type -> Name -> TypecheckM MethodDef
findMethod ty m = do
ClassDef{methods} <- findClass ty
case List.find ((== m) . mname) methods of
Just mdef -> return mdef
Nothing -> tcError $ UnknownMethodError m
-- | Find a field declaration by its 'Type' (@ty@) and field name @f@
findField :: Type -> Name -> TypecheckM FieldDef
findField ty f = do
ClassDef{fields} <- findClass ty
case List.find ((== f) . fname) fields of
Just fdef -> return fdef
Nothing -> tcError $ UnknownFieldError f
-- | Find a variable in the environment by its name @x@
findVar :: Name -> TypecheckM Type
findVar x = do
result <- asks $ lookupVar x
case result of
Just t -> return t
Nothing -> tcError $ UnboundVariableError x
-- | Generates an environment (symbol's table) from a 'Program',
genEnv :: Program -> Env
genEnv (Program cls) = foldl generateEnv emptyEnv cls
where
generateEnv :: Env -> ClassDef -> Env
generateEnv env cls = Env {ctable = Map.insert (cname cls) cls (ctable env)
,vartable = vartable env
,bt = emptyBt
,constructor = False}
-- | Add a variable name and its type to the environment 'Env'.
addVariable :: Name -> Type -> Env -> Env
addVariable x t env@Env{vartable} =
env{vartable = Map.insert x t vartable}
-- | Add a list of parameters, 'Param', to the environment.
addParameters :: [Param] -> Env -> Env
addParameters params env = foldl addParameter env params
where
addParameter env (Param name ty) = addVariable name ty env
-- | Main entry point of the type checker. This function type checks an AST
-- returning either an error or a well-typed program. For instance,
-- assuming the following made up language:
-- >
-- > class C
-- > val f: Foo
-- >
--
-- it should be parsed to generate the following AST:
--
-- > testClass1 =
-- > ClassDef {cname = "C"
-- > ,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}]
-- > ,methods = []}
-- >
--
-- To type check the AST, run the 'tcProgram' combinator as follows:
--
-- > tcProgram testClass1
--
-- which either returns an error or the resulting typed AST.
--
tcProgram :: Program -> Either TCError Program
tcProgram p = do
let env = genEnv p
exceptM = runReaderT (doTypecheck p) env
runExcept exceptM
-- | The type class defines how to type check an AST node.
class Typecheckable a where
-- | Type check the well-formedness of an AST node.
doTypecheck :: a -> TypecheckM a
-- | Type check an AST node, updating the environment's backtrace.
typecheck :: (Backtraceable a) => a -> TypecheckM a
typecheck x = local pushBT $ doTypecheck x
where
pushBT env@Env{bt} = env{bt = push x bt}
-- Type checking the well-formedness of types
instance Typecheckable Type where
doTypecheck (ClassType c) = do
_ <- findClass (ClassType c)
return $ ClassType c
doTypecheck IntType = return IntType
doTypecheck BoolType = return BoolType
doTypecheck UnitType = return UnitType
doTypecheck (Arrow ts t) = do
ts' <- mapM typecheck ts
t' <- typecheck t
return $ Arrow ts' t'
instance Typecheckable Program where
doTypecheck (Program cls) = Program <$> mapM typecheck cls
instance Typecheckable ClassDef where
doTypecheck cdef@ClassDef{cname, fields, methods} = do
let withThisAdded = local $ addVariable thisName (ClassType cname)
fields' <- withThisAdded $ mapM typecheck fields
methods' <- withThisAdded $ mapM typecheck methods
return $ cdef {fields = fields'
,methods = methods'}
instance Typecheckable FieldDef where
doTypecheck fdef@FieldDef{ftype} = do
ftype' <- typecheck ftype
return fdef{ftype = ftype'}
instance Typecheckable Param where
doTypecheck param@(Param {ptype}) = do
ptype' <- typecheck ptype
return param{ptype = ptype'}
instance Typecheckable MethodDef where
doTypecheck mdef@(MethodDef {mname, mparams, mbody, mtype}) = do
-- typecheck the well-formedness of types of method parameters
mparams' <- mapM typecheck mparams
mtype' <- typecheck mtype
-- extend environment with method parameters and typecheck body
mbody' <- local (addParameters mparams .
setConstructor mname) $ hasType mbody mtype'
return $ mdef {mparams = mparams'
,mtype = mtype'
,mbody = mbody'}
instance Typecheckable Expr where
doTypecheck e@(BoolLit {}) = return $ setType BoolType e
doTypecheck e@(IntLit {}) = return $ setType IntType e
doTypecheck e@(Lambda {params, body}) = do
params' <- mapM typecheck params
body' <- local (addParameters params) $ typecheck body
let parameterTypes = map ptype params'
bodyType = getType body'
funType = Arrow parameterTypes bodyType
return $ setType funType e{params = params'
,body = body'}
doTypecheck e@(VarAccess {name}) = do
ty <- findVar name
return $ setType ty e
doTypecheck e@(FieldAccess {target, name}) = do
target' <- typecheck target
let targetType = getType target'
FieldDef {ftype} <- findField targetType name
return $ setType ftype e{target = target'}
doTypecheck e@(Assignment {lhs, rhs}) = do
unless (isLVal lhs) $
tcError $ NonLValError lhs
lhs' <- typecheck lhs
let lType = getType lhs'
rhs' <- hasType rhs lType
let rType = getType rhs'
checkMutability lhs'
return $ setType UnitType e{lhs = lhs'
,rhs = rhs'}
where
checkMutability e@FieldAccess{target, name} = do
field <- findField (getType target) name
inConstructor <- asks constructor
unless (isVarField field ||
inConstructor && isThisAccess target) $
tcError $ ImmutableFieldError e
checkMutability _ = return ()
doTypecheck e@(New {ty, args}) = do
ty' <- typecheck ty
MethodDef {mparams} <- findMethod ty' "init"
let paramTypes = map ptype mparams
args' <- zipWithM hasType args paramTypes
return $ setType ty' $ e{ty = ty'
,args = args'}
doTypecheck e@(MethodCall {target, name, args}) = do
target' <- typecheck target
let targetType = getType target'
MethodDef {mparams, mtype} <- findMethod targetType name
when (isConstructorName name) $
tcError $ ConstructorCallError targetType
let paramTypes = map ptype mparams
args' <- zipWithM hasType args paramTypes
return $ setType mtype $ e{target = target'
,args = args'}
doTypecheck e@(FunctionCall {target, args}) = do
target' <- typecheck target
let targetType = getType target'
unless (isArrowType targetType) $
tcError $ NonArrowTypeError targetType
let paramTypes = tparams targetType
resultType = tresult targetType
args' <- zipWithM hasType args paramTypes
return $ setType resultType e{target = target'
,args = args'}
doTypecheck e@(BinOp {op, lhs, rhs}) = do
lhs' <- hasType lhs IntType
rhs' <- hasType rhs IntType
return $ setType IntType e{lhs = lhs'
,rhs = rhs'}
doTypecheck e@(Cast {body, ty}) = do
ty' <- typecheck ty
body' <- hasType body ty'
return $ setType ty' e{body = body'
,ty = ty'}
doTypecheck e@(If {cond, thn, els}) = do
cond' <- hasType cond BoolType
thn' <- typecheck thn
let thnType = getType thn'
els' <- hasType els thnType
return $ setType thnType e{cond = cond'
,thn = thn'
,els = els'}
doTypecheck e@(Let {name, val, body}) = do
val' <- typecheck val
let ty = getType val'
body' <- local (addVariable name ty) $ typecheck body
let bodyType = getType body'
return $ setType bodyType e{val = val'
,body = body'}
doTypecheck e =
tcError $ UninferrableError e
-- | This combinator is used whenever a certain type is expected. This function
-- is quite important. Here follows an example:
--
-- > doTypecheck mdef@(MethodDef {mparams, mbody, mtype}) = do
-- > -- typecheck the well-formedness of types of method parameters
-- > mparams' <- mapM typecheck mparams
-- > mtype' <- typecheck mtype
-- >
-- > -- extend environment with method parameters and typecheck body
-- > mbody' <- local (addParameters mparams) $ hasType mbody mtype'
-- > ...
--
-- in the last line, because we are type checking a method declaration,
-- it is statically known what should be the return type of the function body. In these
-- cases, one should use the 'hasType' combinator.
--
hasType :: Expr -> Type -> TypecheckM Expr
hasType e@Null{} expected = do
unless (isClassType expected) $
tcError $ PrimitiveNullError expected
return $ setType expected e
hasType e expected = do
e' <- typecheck e
let eType = getType e'
unless (eType == expected) $
tcError $ TypeMismatchError eType expected
return $ setType expected e'
-- | Test programs of a class with a single field.
-- This program is the AST equivalent of the following syntax:
--
-- > class C
-- > val f: Foo
-- >
--
testClass1 =
ClassDef {cname = "C"
,fields = [FieldDef {fmod = Val, fname = "f", ftype = ClassType "Foo"}]
,methods = []}
-- | Test program with a class, field, method, and variable access. The class @Bar@
-- does not exist in the environment. The variable access is unbound.
--
-- This program is the AST equivalent of the following syntax:
--
-- > class D
-- > val g: Bar
-- > def m(): Int
-- > x
--
testClass2 =
ClassDef {cname = "D"
,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "Bar"}]
,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]}
-- | Test program with a two classes, field, method, and variable access. The class
-- declaration are duplicated.
--
-- This program is the AST equivalent of the following syntax:
--
-- > class D
-- > val g: Bar
-- > def m(): Int
-- > x
-- >
-- > class D
-- > val g: Bar
-- > def m(): Int
-- > x
--
testClass3 =
[ClassDef {cname = "D"
,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "D"}]
,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]},
ClassDef {cname = "D"
,fields = [FieldDef {fmod = Val, fname = "g", ftype = ClassType "D"}]
,methods = [MethodDef {mname = "m", mparams = [], mtype = IntType, mbody = VarAccess Nothing "x"}]}]
--testProgram :: Program 'Parsed 'Parsed
testProgram = Program [testClass1, testClass2]
testValidProgram = Program testClass3
-- | Test suite that runs 'testProgram'.
testSuite = do
putStrLn $ "\n************************************************"
putStrLn $ "3. Add backtrace information.\n" ++
"Showing a program with 3 errors:\n" ++
"- type checker only catches one error\n" ++
"- support for backtrace\n"
putStrLn "Output:"
putStrLn ""
putStrLn $ show $ fromLeft undefined (tcProgram testProgram)
putStrLn ""
putStrLn $ "************************************************"
|
kikofernandez/kikofernandez.github.io
|
files/monadic-typechecker/typechecker/src/Backtrace/Typechecker.hs
|
mit
| 18,040
| 0
| 16
| 4,326
| 3,973
| 2,090
| 1,883
| 287
| 2
|
-- |Haskollider.Server defines all the types and functionals relavent to communicating with a running scsynth instances
module Haskollider.Server where
import Haskollider.NetAddr
import Haskollider.Engine
import Haskollider.Node
import Haskollider.Util
import Haskollider.Buffer
import qualified Haskollider.Bus as Bus
import Sound.OSC
import Control.Monad.State
import Control.Concurrent
import Data.Maybe
import Data.Time
import Data.List
import System.Process
import System.IO
import System.Posix.Env
-- |Protocol to use for Osc communication with scsynth. Udp is the default for server communication.
data Protocol = Tcp | Udp deriving (Eq, Show)
-- |ServerType, distinguishes between an internal server or local host scsynth instance. LocalHost by default
data ServerType = LocalHost | InternalServer deriving(Eq, Show)
-- |ServerProcess is just binds together the various handles returned from createProcess
data ServerProcess = ServerProcess { stdIn :: Handle, stdOut :: Handle, stdErr :: Handle, process :: ProcessHandle }
-- |ServerProcess instance of show, it simply displays a booted status.
instance Show ServerProcess where
show (ServerProcess _ _ _ _) = "ServerProcess: Booted"
-- |ServerOptions, a group of options passed to the server on creation.
data ServerOptions = ServerOptions {
sNumAudioBusChannels :: Int,
sNumControlBusChannels :: Int,
sMaxLogins :: Int,
sMaxNodes :: Int,
sNumInputBusChannels :: Int,
sNumOutputBusChannels :: Int,
sNumBuffers :: Int,
sMaxSynthDefs :: Int,
sProtocol :: Protocol,
sBufLength :: Int,
sNumRGens :: Int,
sMaxWireBufs :: Int,
sPreferredSampleRate :: Int,
sLoadGraphDefs :: Bool,
sVerbosity :: Int,
sRendezvous :: Bool,
sRemoteControlVolume :: Bool,
sMemoryLocking :: Bool,
sPreferredHardwareBufferFrameSize :: Int,
sRealTimeMemorySize :: Int,
sBlockSize :: Int,
sPortNum :: Int,
sNumPrivateAudioBusChannels :: Int
} deriving (Show)
{-|
A default collection of ServerOptions for quick use and reference.
If you want to target specific arguments start here and change via record syntax.
-}
defaultServerOptions :: ServerOptions
defaultServerOptions = ServerOptions {
sNumAudioBusChannels = 128,
sNumControlBusChannels = 4096,
sMaxLogins = 64,
sMaxNodes = 1024,
sNumInputBusChannels = 8,
sNumOutputBusChannels = 8,
sNumBuffers = 1024,
sMaxSynthDefs = 2048,
sProtocol = Udp,
sBufLength = 64,
sNumRGens = 64,
sMaxWireBufs = 64,
sPreferredSampleRate = 44100,
sLoadGraphDefs = True,
sVerbosity = 0,
sRendezvous = False,
sRemoteControlVolume = False,
sMemoryLocking = False,
sPreferredHardwareBufferFrameSize = 512,
sRealTimeMemorySize = 81920, -- Increased
sBlockSize = 512,
sPortNum = 67110, -- Don't use the default SuperCollider scsynth port to prevent clashes
sNumPrivateAudioBusChannels = 112
}
-- |Server, the main type used to instantiate and communicate with an scsynth instance
data Server = Server {
serverName :: String,
serverOptions :: ServerOptions,
serverNetAddr :: NetAddr,
serverClientID :: Int,
serverRunning :: Bool,
serverBootNotifyFirst :: Bool,
serverLatency :: Double,
serverDumpMode :: Int,
serverNotify :: Bool,
serverNotified :: Bool,
serverNumUgens :: Int,
serverNumSynths :: Int,
serverAlive :: Bool,
serverAliveThreadPeriod :: Double,
serverRecHeaderFormat :: String,
serverRecSampleFormat :: String,
serverRecChannels :: Int,
currentNodeID :: Int,
controlBusAllocator :: PowerOfTwoAllocator,
audioBusAllocator :: PowerOfTwoAllocator,
bufferAllocator :: PowerOfTwoAllocator,
rootNode :: Group,
defaultGroup :: Group,
recordBuf :: Maybe Buffer,
recordNode :: Maybe Synth,
serverCmd :: String,
serverProcess :: Maybe ServerProcess
} deriving (Show)
-- |A Server with typical values.
defaultServer :: Server
defaultServer = Server {
serverName = "Local Host",
serverOptions = defaultServerOptions,
serverNetAddr = newNetAddr "127.0.0.1" (sPortNum defaultServerOptions),
serverClientID = 0,
serverRunning = False,
serverBootNotifyFirst = False,
serverLatency = 0.2,
serverDumpMode = 0,
serverNotify = True,
serverNotified = False,
serverNumUgens = 0,
serverNumSynths = 0,
serverAlive = False,
serverAliveThreadPeriod = 0.7,
serverRecHeaderFormat = "wav",
serverRecSampleFormat = "float",
serverRecChannels = 2,
currentNodeID = initialNodeID,
controlBusAllocator = newPowerOfTwoAllocator (sNumControlBusChannels defaultServerOptions),
audioBusAllocator = newPowerOfTwoAllocator (sNumAudioBusChannels defaultServerOptions),
bufferAllocator = newPowerOfTwoAllocator (sNumBuffers defaultServerOptions),
rootNode = newGroup rootNodeID, -- If you've already started scsynth from Supercollider these will be created by default
defaultGroup = newGroup defaultGroupID,
recordBuf = Nothing,
recordNode = Nothing,
serverCmd = "scsynth",
serverProcess = Nothing
}
data ServerCommand = None | Notify| Status | Quit | Cmd | D_recv | D_load | D_loadDir | D_freeAll | S_new | N_trace | N_free | N_run | N_cmd | N_map |
N_set | N_setn | N_fill | N_before | N_after | U_cmd | G_new | G_head | G_tail | G_freeAll | C_set | C_setn | C_fill | B_alloc |
B_allocRead | B_read | B_write | B_free | B_close | B_zero | B_set | B_setn | B_fill | B_gen | DumpOSC | C_get | C_getn | B_get |
B_getn | S_get | S_getn | N_query | B_query | N_mapn | S_noid | G_deepFree | ClearSched | Sync | D_free | B_allocReadChannel |
B_readChannel | G_dumpTree | G_queryTree | Error | S_newargs | N_mapa | N_mapan | N_order | NUMBER_OF_COMMANDS deriving (Show, Eq, Ord, Enum)
-------------------------------------------------------------------------------
-- Internal functions, don't need to use these unless you have a good reason
-------------------------------------------------------------------------------
-- |Helper function to find the first private bus
firstPrivateBus :: ServerOptions -> Int
firstPrivateBus o = (sNumOutputBusChannels o) + (sNumOutputBusChannels o)
-- |Converts ServerOptions to a list of command line Arguments for scsynth
optionsToCmdString :: ServerOptions -> [String]
optionsToCmdString options = udpP ++ numAudio ++ numControl ++ numInput ++ numOutput ++ blockS ++ hardBufSize ++
sRate ++ nBuffers ++ mNodes ++ mSDefs ++ rtMem ++ wBuf ++ logins
where
udpP = ["-u ", (show $ sPortNum options)]
numAudio = ["-a ", (show $ sNumAudioBusChannels options)]
numControl = ["-c ", (show $ sNumControlBusChannels options)]
numInput = ["-i ", (show $ sNumInputBusChannels options)]
numOutput = ["-o ", (show $ sNumOutputBusChannels options)]
blockS = ["-z ", (show $ sBlockSize options)]
hardBufSize = ["-Z ", (show $ sPreferredHardwareBufferFrameSize options)]
sRate = ["-S ", (show $ sPreferredSampleRate options)]
nBuffers = ["-b ", (show $ sNumBuffers options)]
mNodes = ["-n ", (show $ sMaxNodes options)]
mSDefs = ["-d ", (show $ sMaxSynthDefs options)]
rtMem = ["-m ", (show $ sRealTimeMemorySize options)]
wBuf = ["-w ", (show $ sMaxWireBufs options)]
logins = ["-l ", (show $ sMaxLogins options)]
-- |Helper function for sending OSC messages to scsynth
sendMsg :: Server -> Message -> IO ()
sendMsg s m = sendNetAddrMsg (serverNetAddr s) m
-- |Helper function for sending OSC bundles to scsynth
sendBundle :: Server -> Bundle -> IO ()
sendBundle s b = sendNetAddrBundle (serverNetAddr s) b
-- |Increments the server's node counter, returning a node id.
nextNodeID :: StateT Server IO NodeID
nextNodeID = do
server <- get
put (server { currentNodeID = newID server})
return $ newID server
where newID s = allocNodeID (currentNodeID s)
-- |Allocates n number of control buses on the server
allocControlBus :: Int -> StateT Server IO (Maybe Int)
allocControlBus n = do
server <- get
put (server { controlBusAllocator = snd $ cb server })
return . fst $ cb server
where cb s = allocPTBlock (controlBusAllocator s) n
-- |Frees a control bus, identified by number
freeControlBus :: Int -> StateT Server IO ()
freeControlBus n = do
server <- get
put (server { controlBusAllocator = fc server })
return ()
where fc s = freePTBlock (controlBusAllocator s) n
-- |Allocates n number of audio buses on the server
allocAudioBus :: Int -> StateT Server IO (Maybe Int)
allocAudioBus n = do
server <- get
put (server { audioBusAllocator = snd $ ab server })
return . fst $ ab server
where ab s = allocPTBlock (audioBusAllocator s) n
-- |Frees an audio bus, identified by number
freeAudioBus :: Int -> StateT Server IO ()
freeAudioBus n = do
server <- get
put (server { audioBusAllocator = fa server })
return ()
where fa s = freePTBlock (audioBusAllocator s) n
-- |Allocates n number of buffers on the server
allocBuffer :: Int -> StateT Server IO (Maybe Int)
allocBuffer n = do
server <- get
put (server { bufferAllocator = snd $ bb server })
return . fst $ bb server
where bb s = allocPTBlock (bufferAllocator s) n
-- |Frees a buffer, identified by number
freeBuffer :: Int -> StateT Server IO ()
freeBuffer n = do
server <- get
put (server { bufferAllocator = fb server })
return ()
where fb s = freePTBlock (bufferAllocator s) n
-- |Create the default group on the scsynth server. This is useful if you're starting it from the cml or otherwise not from sclang.
sendDefaultGroup :: Server -> IO ()
sendDefaultGroup server = sendMsg server $ Message "/g_new" [int32 defaultGroupID, int32 (fromEnum AddToHead), int32 rootNodeID]
-- |Process the stdout and stderr from the running scsynth instance
scprocessOut :: ServerProcess -> StateT Server IO (ThreadId)
scprocessOut scProcess = do
server <- get
lift . forkIO $ outFunc server
where outFunc server = do
outContents <- hGetContents $ stdOut scProcess
errContents <- hGetContents $ stdErr scProcess
if(isInfixOf "SuperCollider 3 server ready." outContents)
then do
sendMsg server notify
sendDefaultGroup server
return ()
else return ()
putStrLn outContents
putStrLn errContents
return ()
-- |A simple Osc Message that when sent will ask scsynth to quit
quitMsg :: Message
quitMsg = Message "/quit" []
-------------------------------------------------------------------------
-- Below is the standard interface for using the Haskollider library.
-------------------------------------------------------------------------
-- |Helper function, just wraps up the get and lift for slightly more streamlined sending. Used for things like set and free
send :: Message -> StateT Server IO ()
send m = do
s <- get
lift (sendMsg s m)
-- |Takes a newBus function, allocates a bus, and returns a Bus object
sendBus :: Bus.Rate -> (Int -> Bus.Bus) -> StateT Server IO (Maybe Bus.Bus)
sendBus r f = do (allocBus 1) >>= (\i -> return (bus i))
where
allocBus = if r == Bus.Audio then (allocAudioBus) else (allocControlBus)
bus (Just i) = Just $ f i
bus Nothing = Nothing
{-|
sendNew is a helper function for simplifying new node message sending to scsynth. It takes a function (NodeId to Node a), increments the node id
in the server, and returns the created Node. Eg sendNew $ newSynth "mySynth" [("arg1", value)] ... or also: sendNew $ newGroup
-}
sendNew :: ScSendable a => (Int -> a) -> StateT Server IO a
sendNew f = do nextNodeID >>= (\i -> let n = f i in do (send $ newMsg n); return n)
-- |A Synth type based wrapper for sendNew
sendSynth :: (Int -> Synth) -> StateT Server IO Synth
sendSynth = sendNew
-- |A Group type based wrapper for sendNew
sendGroup :: (Int -> Group) -> StateT Server IO Group
sendGroup = sendNew
{-|
Similar to sendNew, this takes a curried function (returned by various Buffer module functions) and returns a Buffer
When executed a buffer is allocated on the server, passed functions takes that number and returns a function which is sent to the server
-}
sendBuffer :: (Int -> Buffer) -> StateT Server IO (Maybe Buffer)
sendBuffer f = do (allocBuffer 1) >>= (\i -> let b = buf i in do sendBuf b; return b)
where
buf (Just i) = Just $ f i
buf Nothing = Nothing
sendBuf (Just b) = send $ newMsg b
sendBuf Nothing = do lift $ print "No more buffer numbers -- free some buffers before allocating more."; return ()
-- |Requests scsynth to load a directory of compiled synth definitions
loadDirectory :: String -> StateT Server IO ()
loadDirectory dir = send $ Message "/d_loadDir" [string dir]
-- |Begin recording, this just uses the current working directory and a generated filename based on the current time.
record :: StateT Server IO ()
record = do
prepareForRecording
server <- get
if isNothing (recordNode server)
then do
rNode <- sendSynth $ synthTail (rootNode server) "server-record" [("bufnum", fromIntegral . bufnum . fromJust $ recordBuf server)]
server' <- get
put (server' { recordNode = Just rNode })
else send $ run (fromJust $ recordNode server) True
-- |Pauses the current recording, if any.
pauseRecording :: StateT Server IO ()
pauseRecording = do
server <- get
if isJust (recordNode server)
then send $ run (fromJust $ recordNode server) False
else lift $ print "Warning: Not recording"
-- |Stops and finalized the current recording, if any.
stopRecording :: StateT Server IO ()
stopRecording = do
server <- get
if isJust (recordNode server)
then do
send $ freeNode (fromJust $ recordNode server)
send $ close (fromJust $ recordBuf server)
send $ freeBuf (fromJust $ recordBuf server)
put (server { recordNode = Nothing, recordBuf = Nothing })
else lift $ print "Warning: Not recording"
-- |A helper function for created the necessary node and buffer for record. Not necessary to call this before recording.
prepareForRecording :: StateT Server IO ()
prepareForRecording = do
server <- get
if isJust (recordBuf server) then return () else do
rBuf <- sendBuffer $ alloc 65536 (serverRecChannels server)
now <- lift getCurrentTime
case rBuf of
Nothing -> return ()
Just buf -> do
lift $ putStrLn ("prepareForRecording path: " ++ newPath)
send $ write buf newPath (serverRecHeaderFormat server) (serverRecSampleFormat server) 0 0 True
where newPath = filter (/=' ') ("SC_" ++ (show now) ++ "." ++ (serverRecHeaderFormat server))
put (server { recordBuf = rBuf })
-- |Boots the server, spawning a child scsynth process and established pipes for stdout and sterr
boot :: StateT Server IO ()
boot = do
lift $ putEnv "SC_JACK_DEFAULT_INPUTS=system"
lift $ putEnv "SC_JACK_DEFAULT_OUTPUTS=system"
-- automatically start jack when booting the server
-- can still be overridden with JACK_NO_START_SERVER
lift $ putEnv "JACK_START_SERVER=true"
server <- get
(mstin, mstout, msterr, pHandle) <- lift $
createProcess (System.Process.proc "scsynth" (optionsToCmdString $ serverOptions server)) { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
let stList = [mstin, mstout, msterr]
if (any (isNothing) stList)
then do
lift $ putStrLn "NOTHING!"
return ()
else case stList of
[Just stin, Just stout, Just sterr] -> let
scProcess = ServerProcess stin stout sterr pHandle
in do
put (server { serverProcess = Just scProcess, serverRunning = True })
scprocessOut scProcess
return ()
-- |Quits the child scsynth process
quit :: StateT Server IO ()
quit = do
send quitMsg
server <- get
case (serverProcess server) of
Nothing -> return ()
Just scProcess -> do
lift . hClose $ stdIn scProcess
lift . hClose $ stdOut scProcess
lift . hClose $ stdErr scProcess
lift $ waitForProcess (process scProcess)
put (server { serverRunning = False })
return ()
-- |A notify message, when notified scsynth will start sending update messages to sender regarding running synths, ugens, etc.
notify :: Message
notify = Message "/notify" [int32 1]
{-|
Test code for Haskollider. First start SC and boot the server. Next, you'll need a Synth named "TestSine"; Something like this:
SynthDef.new("TestSine", {
arg freq = 440, amp = 0.2;
var env = EnvGen.ar(Env.perc(0, 0.5), doneAction: 2);
Out.ar(0, SinOsc.ar(freq, 0 , env * amp).dup);
}).store;
Next, make sure you have Haskollider compiled and installed (cabal build && cabal install). Finally, open up ghci and run
:m Haskollider.Server
testSC
-}
testSC :: IO ()
testSC = let
server = defaultServer
synth f = sendSynth $ newSynth "TestSine" [("freq", fromIntegral f)]
synths fundamental n = do
synth $ fundamental * (mod n 8 + 1)
synth $ fundamental * (mod n 7 + 1)
lift $ threadDelay 100000
if n < 200
then synths fundamental (n + 1)
else return()
in evalStateT (synths 80 1) server
{-|
More test code for Haskollider. First start SC and boot the server. Next, you'll need a Synth named "TestSine2"; Something like this:
SynthDef.new("TestSine2", {
arg freq = 440, amp = 0.2, gate = 1;
var env = EnvGen.ar(Env.asr(0, 1, 0.5), gate: gate, doneAction: 2);
Out.ar(0, SinOsc.ar(freq, 0 , env * amp).dup);
}).store;
Next, make sure you have Haskollider compiled and installed (cabal build && cabal install). Finally, open up ghci and run
:m Haskollider.Server
testSC2
-}
testSC2 :: IO ()
testSC2 = let
server = defaultServer
synth f = sendSynth $ newSynth "TestSine2" [("freq", f)]
runSynths = do
synth1 <- synth 160.0
synth2 <- synth 160.0
synths synth1 synth2 80 1
synths :: Synth -> Synth -> Double -> Int -> StateT Server IO ()
synths synth1 synth2 fundamental n = do
send $ set synth1 "freq" (fundamental * fromIntegral (mod n 9 + 1))
send $ set synth2 "freq" (fundamental * fromIntegral (mod n 7 + 1))
lift $ threadDelay 100000
if n < 1000
then synths synth1 synth2 fundamental (n + 4)
else do
send $ set synth1 "gate" 0
send $ set synth2 "gate" 0
in evalStateT (runSynths) server
{-|
Server Process control test. Using the boot/quit functions we don't have to start SuperCollider outside of the program.
This assumes you're on a unixy system with supercollider installed and with scsynth in your path.
Also, for recording to work you need to have a "server-record" synth def like such compiled:
SynthDef("server-record", { arg bufnum;
DiskOut.ar(bufnum, In.ar(0, recChannels))
}).store;
-}
testSC3 :: IO ()
testSC3 = evalStateT (runSC) server
where
server = defaultServer
synth f = sendSynth $ newSynth "TestSine" [("freq", fromIntegral f)]
synths fundamental n = do
synth $ fundamental * (mod n 8 + 1)
synth $ fundamental * (mod n 7 + 1)
lift $ threadDelay 100000
if n < 200
then synths fundamental (n + 1)
else return()
runSC :: StateT Server IO ()
runSC = do
boot
lift $ threadDelay 1000000
record
synths 80 1
stopRecording
quit
|
ChadMcKinney/Haskollider
|
src/Haskollider/Server.hs
|
gpl-2.0
| 18,617
| 250
| 21
| 3,406
| 4,921
| 2,607
| 2,314
| 366
| 3
|
module Handler.Einsendung where
import Import
import Handler.EinsendungAnlegen (getAufgabeInstanz, getCrc, getDefaultParam)
import Handler.AufgabeKonfiguration (checkKonfiguration)
import Handler.Statistik (tdRadioField)
import Data.Text.Lazy (toStrict)
import Network.HTTP.Types (temporaryRedirect307)
import System.IO (readFile)
import System.Directory
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Control.Punkt (bepunkteStudentDB)
import qualified Control.Stud_Aufg.DB as EinsendungDB
import qualified Control.Stud_Aufg.Typ as Einsendung
import qualified Control.Types as T
import Operate.Bank (bank)
import qualified Operate.Param as P
import qualified Operate.Store as Store (Type (Input, Instant), location)
import Operate.Types (signed_task_config)
import Types.Signed (Signed (signature))
import qualified Util.Datei as D
getEinsendungR :: AufgabeId -> StudentId -> Handler Html
getEinsendungR = postEinsendungR
postEinsendungR :: AufgabeId -> StudentId -> Handler Html
postEinsendungR aufgabeId studentId = do
meinsendung <- liftIO $ fmap listToMaybe $ EinsendungDB.get_snr_anr (T.SNr $ keyToInt studentId) $ T.ANr $ keyToInt aufgabeId
aufgabe <- runDB $ get404 aufgabeId
student <- runDB $ get404 studentId
istTutor <- runDB $ not . null <$> selectList [TutorStudentId ==. studentId, TutorVorlesungId ==. aufgabeVorlesungId aufgabe] []
einsendung <- liftIO $ maybe (EinsendungDB.put_blank (T.SNr $ keyToInt studentId) (T.ANr $ keyToInt aufgabeId)) return meinsendung
mbewertung <- liftIO $ sequence $ fmap preEscapedToHtml . readFile . T.toString <$> Einsendung.report einsendung
((formResult, formWidget), formEnctype) <- runFormPost $ bewertungBearbeitenForm mbewertung
case formResult of
FormSuccess (mneueBewertung, mneuerWert) -> do
let param = getDefaultParam student studentId aufgabe aufgabeId
continue = case mneuerWert of
Just T.Pending -> True
_ -> isJust mneueBewertung
if continue
then do
msg <- lift $ liftIO $ bank param {
P.report = mneueBewertung,
P.mresult = mplus mneuerWert (Einsendung.result einsendung) -- Warum input und instant nicht setzen?
}
setMessage $ toHtml $ pack msg
else setMessageI MsgEinsendungBewertungNotwendig
_ -> return ()
input <- fixInput student studentId aufgabe aufgabeId einsendung
instant <- fixInstant student studentId aufgabe aufgabeId einsendung
-- INFO: Logging entfernt ("Super.view")
maufgabenstellung <- liftIO $ sequence $ fmap (fmap preEscapedToHtml . readFile . T.toString) instant
-- INFO: Logging entfernt ("Super.view")
meinsendung' <- liftIO $ sequence $ fmap (readFile . T.toString) input
defaultLayout $
$(widgetFile "einsendung")
bewertungBearbeitenForm :: Maybe Html -> Form (Maybe Html, Maybe T.Wert)
bewertungBearbeitenForm mbewertung =
identifyForm "bewertung" $ renderBootstrap3 BootstrapBasicForm $ (,)
<$> aopt htmlField (addAttrs $ bfs MsgBewertungBearbeiten) (Just mbewertung)
<*> areq (tdRadioField $ optionsPairs optionen) (bfs MsgEinsendungBewertung) {fsAttrs = []} (Just Nothing)
<* bootstrapSubmit (BootstrapSubmit MsgEinsendungBewerten "btn-success" [])
where
addAttrs field = field {
fsAttrs = ("rows", pack . show $ 2 + maybe 0 (length . lines . toStrict . renderHtml) mbewertung) : fsAttrs field
}
optionen :: [(AutotoolMessage, Maybe T.Wert)]
optionen = [(MsgBehalten, Nothing), (MsgNein, Just T.No), (MsgAusstehend, Just T.Pending)] ++ fmap (\ i -> (MsgTextToMsg (pack $ show i), Just $ T.Ok i)) [1..10]
fixInput :: Student -> StudentId -> Aufgabe -> AufgabeId -> Einsendung.Stud_Aufg -> Handler (Maybe T.File)
fixInput student studentId aufgabe aufgabeId einsendung = case Einsendung.input einsendung of
Just file -> return $ Just file
Nothing -> liftIO $ do
-- fix location of previous einsendung
let p = getDefaultParam student studentId aufgabe aufgabeId
d = Store.location Store.Input
p "latest" False
file <- D.home d
ex <- doesFileExist file
if ex
then do
-- nur infile-location einschreiben
let inf = T.fromCGI file
bepunkteStudentDB
(P.ident p) (P.anr p)
Nothing
Nothing (P.highscore p)
(Just inf)
Nothing
return $ Just inf
else return Nothing
fixInstant :: Student -> StudentId -> Aufgabe -> AufgabeId -> Einsendung.Stud_Aufg -> Handler (Maybe T.File)
fixInstant student studentId aufgabe aufgabeId einschreibung = case Einsendung.instant einschreibung of
Just file -> return $ Just file
Nothing -> do
-- transitional:
-- (try to) re-generate previous instance
aufgabe' <- updateSignatur aufgabe aufgabeId
(_, _, _, aufgabenstellung) <-
getAufgabeInstanz
(aufgabeServer aufgabe')
(signed_task_config $ entityToAufgabe aufgabeId aufgabe')
(getCrc (T.VNr $ keyToInt $ aufgabeVorlesungId aufgabe) (Just $ T.ANr $ keyToInt aufgabeId) (T.MNr $ unpack $ studentMatrikelNummer student))
let p = getDefaultParam student studentId aufgabe' aufgabeId
d = Store.location Store.Instant
p "latest" False
file <- liftIO $ D.schreiben d $ show aufgabenstellung
let inst = T.fromCGI file
liftIO $ bepunkteStudentDB
(P.ident p) (P.anr p)
(Just inst)
Nothing (P.highscore p)
Nothing
Nothing
return $ Just inst
updateSignatur :: Aufgabe -> AufgabeId -> Handler Aufgabe
updateSignatur aufgabe aufgabeId =
if aufgabeSignatur aufgabe == "missing"
then do
esigned <-
checkKonfiguration
(aufgabeServer aufgabe)
(aufgabeTyp aufgabe)
(aufgabeKonfiguration aufgabe)
case esigned of
Left fehler -> do
setMessage fehler
redirectWith temporaryRedirect307 $ VorlesungR $ aufgabeVorlesungId aufgabe
Right signed -> do
aufgabe'' <- runDB $ updateGet aufgabeId [AufgabeSignatur =. pack (signature signed)]
setMessageI MsgAufgabeSignaturUpdate
return aufgabe''
else return aufgabe
|
marcellussiegburg/autotool
|
yesod/Handler/Einsendung.hs
|
gpl-2.0
| 6,148
| 0
| 23
| 1,298
| 1,817
| 917
| 900
| -1
| -1
|
{- |
Module : $Header$
Description : auxiliary functions on terms and formulas
Copyright : (c) Mingyi Liu and Till Mossakowski and Uni Bremen 2004-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : xinga@informatik.uni-bremen.de
Stability : provisional
Portability : portable
Auxiliary functions on terms and formulas
-}
module CASL.CCC.TermFormula where
import CASL.AS_Basic_CASL
import CASL.Overload(leqF)
import CASL.Sign(OpMap, Sign(sortRel), toOP_TYPE, toOpType)
import Common.Id(Token(tokStr), Id(Id), Range, GetRange(..), nullRange)
import Common.Utils(nubOrd)
import qualified Common.Lib.MapSet as MapSet
import qualified Common.Lib.Rel as Rel
import Control.Monad(liftM)
import qualified Data.Map as Map
import qualified Data.Set as Set
-- | the sorted term is always ignored
term :: TERM f -> TERM f
term t = case t of
Sorted_term t' _ _ -> term t'
_ -> t
-- | the quantifier of term is always ignored
quanti :: FORMULA f -> FORMULA f
quanti f = case f of
Quantification _ _ f' _ -> quanti f'
_ -> f
-- | check whether it exist a (unique)existent quantification
isExQuanti :: FORMULA f -> Bool
isExQuanti f =
case f of
Quantification Existential _ _ _ -> True
Quantification Unique_existential _ _ _ -> True
Quantification _ _ f' _ -> isExQuanti f'
Implication f1 f2 _ _ -> isExQuanti f1 || isExQuanti f2
Equivalence f1 f2 _ -> isExQuanti f1 || isExQuanti f2
Negation f' _ -> isExQuanti f'
_ -> False
-- | get the constraint from a sort generated axiom
constraintOfAxiom :: FORMULA f -> [Constraint]
constraintOfAxiom f =
case f of
Sort_gen_ax constrs _ -> constrs
_ -> []
-- | determine whether a formula is a sort generation constraint
isSortGen :: FORMULA a -> Bool
isSortGen (Sort_gen_ax _ _) = True
isSortGen _ = False
-- | check whether it contains a membership formula
isMembership :: FORMULA f -> Bool
isMembership f =
case f of
Quantification _ _ f' _ -> isMembership f'
Conjunction fs _ -> any isMembership fs
Disjunction fs _ -> any isMembership fs
Negation f' _ -> isMembership f'
Implication f1 f2 _ _ -> isMembership f1 || isMembership f2
Equivalence f1 f2 _ -> isMembership f1 || isMembership f2
Membership _ _ _ -> True
_ -> False
-- | check whether a sort is free generated
isFreeGenSort :: SORT -> [FORMULA f] -> Maybe Bool
isFreeGenSort _ [] = Nothing
isFreeGenSort s (f:fs) =
case f of
Sort_gen_ax csts isFree | any ((== s) . newSort) csts -> Just isFree
_ -> isFreeGenSort s fs
-- | check whether it is the domain of a partial function
isDomain :: FORMULA f -> Bool
isDomain f = case (quanti f) of
Equivalence (Definedness _ _) f' _ -> not (containDef f')
Definedness _ _ -> True
_ -> False
-- | check whether it contains a definedness formula
containDef :: FORMULA f -> Bool
containDef f = case f of
Quantification _ _ f' _ -> containDef f'
Conjunction fs _ -> any containDef fs
Disjunction fs _ -> any containDef fs
Implication f1 f2 _ _ -> containDef f1 || containDef f2
Equivalence f1 f2 _ -> containDef f1 || containDef f2
Negation f' _ -> containDef f'
Definedness _ _ -> True
_ -> False
-- | check whether it contains a negation
containNeg :: FORMULA f -> Bool
containNeg f = case f of
Quantification _ _ f' _ -> containNeg f'
Implication _ f' _ _ -> containNeg f'
Equivalence f' _ _ -> containNeg f'
Negation _ _ -> True
_ -> False
-- | check whether it contains a definedness formula in correct form
correctDef :: FORMULA f -> Bool
correctDef f = case (quanti f) of
Implication _ (Definedness _ _) _ _ -> False
Implication (Definedness _ _) _ _ _ -> True
Equivalence (Definedness _ _) f' _ -> not (containDef f')
Negation (Definedness _ _) _ -> True
Definedness _ _ -> True
_ -> False
-- | extract all partial function symbols, their domains are defined
domainOpSymbs :: [FORMULA f] -> [OP_SYMB]
domainOpSymbs fs = concatMap domOpS fs
where domOpS f = case (quanti f) of
Equivalence (Definedness t _) _ _ -> [opSymbOfTerm t]
_ -> []
-- | check whether a formula gives the domain of a partial function
domainOs :: FORMULA f -> OP_SYMB -> Bool
domainOs f os = case (quanti f) of
Equivalence (Definedness t _) _ _ -> opSymbOfTerm t == os
_ -> False
-- | extract the domain-list of partial functions
domainList :: [FORMULA f] -> [(TERM f,FORMULA f)]
domainList fs = concatMap dm fs
where dm f = case (quanti f) of
Equivalence (Definedness t _) f' _ -> [(t,f')]
_ -> []
-- | check whether it is a application term
isApp :: TERM t -> Bool
isApp t = case t of
Application _ _ _ -> True
Sorted_term t' _ _ -> isApp t'
Cast t' _ _ -> isApp t'
_ -> False
-- | check whether it is a Variable
isVar :: TERM t -> Bool
isVar t = case t of
Qual_var _ _ _ -> True
Sorted_term t' _ _ -> isVar t'
Cast t' _ _ -> isVar t'
_ -> False
-- | extract the operation symbol from a term
opSymbOfTerm :: TERM f -> OP_SYMB
opSymbOfTerm t = case term t of
Application os _ _ -> os
Sorted_term t' _ _ -> opSymbOfTerm t'
Conditional t' _ _ _ -> opSymbOfTerm t'
_ -> error "CASL.CCC.TermFormula.<opSymbOfTerm>"
-- | extract all variables of a term
varOfTerm :: Ord f => TERM f -> [TERM f]
varOfTerm t = case t of
Qual_var _ _ _ -> [t]
Sorted_term t' _ _ -> varOfTerm t'
Application _ ts _ -> if null ts then []
else nubOrd $ concatMap varOfTerm ts
_ -> []
-- | extract all arguments of a term
arguOfTerm :: TERM f-> [TERM f]
arguOfTerm t = case t of
Qual_var _ _ _ -> [t]
Application _ ts _ -> ts
Sorted_term t' _ _ -> arguOfTerm t'
_ -> []
-- | extract all arguments of a predication
arguOfPred :: FORMULA f -> [TERM f]
arguOfPred f = case quanti f of
Negation f1 _ -> arguOfPred f1
Predication _ ts _ -> ts
_ -> []
-- | extract all variables of a axiom
varOfAxiom :: FORMULA f -> [VAR]
varOfAxiom f =
case f of
Quantification Universal v_d _ _ ->
concatMap (\(Var_decl vs _ _)-> vs) v_d
Quantification Existential v_d _ _ ->
concatMap (\(Var_decl vs _ _)-> vs) v_d
Quantification Unique_existential v_d _ _ ->
concatMap (\(Var_decl vs _ _)-> vs) v_d
_ -> []
-- | extract the predication symbols from a axiom
predSymbsOfAxiom :: (FORMULA f) -> [PRED_SYMB]
predSymbsOfAxiom f =
case f of
Quantification _ _ f' _ -> predSymbsOfAxiom f'
Conjunction fs _ -> concatMap predSymbsOfAxiom fs
Disjunction fs _ -> concatMap predSymbsOfAxiom fs
Implication f1 f2 _ _ -> predSymbsOfAxiom f1 ++ predSymbsOfAxiom f2
Equivalence f1 f2 _ -> predSymbsOfAxiom f1 ++ predSymbsOfAxiom f2
Negation f' _ -> predSymbsOfAxiom f'
Predication p_s _ _ -> [p_s]
_ -> []
-- | check whether it is a partial axiom
partialAxiom :: FORMULA f -> Bool
partialAxiom f =
case (opTypAxiom f) of
Just False -> True
_ -> False
-- | create the obligation of subsort
infoSubsort :: [SORT] -> FORMULA f -> [FORMULA f]
infoSubsort sts f =
case f of
Quantification Universal v (Equivalence (Membership _ s _) f1 _) _ ->
[Quantification Existential v f1 nullRange | notElem s sts]
_ -> []
-- | extract the leading symbol from a formula
leadingSym :: FORMULA f -> Maybe (Either OP_SYMB PRED_SYMB)
leadingSym = liftM extractLeadingSymb . leadingTermPredication
-- | extract the leading symbol with the range from a formula
leadingSymPos :: GetRange f => FORMULA f
-> (Maybe (Either OP_SYMB PRED_SYMB), Range)
leadingSymPos f = leading (f,False,False,False)
where
leading (f1,b1,b2,b3) = case (f1,b1,b2,b3) of
((Quantification _ _ f' _),_,_,_) ->
leading (f',b1,b2,b3)
((Negation f' _),_,_,False) ->
leading (f',b1,b2,True)
((Implication _ f' _ _),False,False,False) ->
leading (f',True,False,False)
((Equivalence f' _ _),_,False,False) ->
leading (f',b1,True,False)
((Definedness t _),_,_,_) ->
case (term t) of
Application opS _ p -> (Just (Left opS), p)
_ -> (Nothing,(getRange f1))
((Predication predS _ _),_,_,_) ->
((Just (Right predS)),(getRange f1))
((Strong_equation t _ _),_,False,False) ->
case (term t) of
Application opS _ p -> (Just (Left opS), p)
_ -> (Nothing,(getRange f1))
((Existl_equation t _ _),_,False,False) ->
case (term t) of
Application opS _ p -> (Just (Left opS), p)
_ -> (Nothing,(getRange f1))
_ -> (Nothing,(getRange f1))
-- | extract the leading term or predication from a formula
leadingTermPredication :: FORMULA f -> Maybe (Either (TERM f) (FORMULA f))
leadingTermPredication f = leading (f,False,False,False)
where
leading (f1,b1,b2,b3) = case (f1,b1,b2,b3) of
((Quantification _ _ f' _),_,_,_) ->
leading (f',b1,b2,b3)
((Negation f' _),_,_,False) ->
leading (f',b1,b2,True)
((Implication _ f' _ _),False,False,False) ->
leading (f',True,False,False)
((Equivalence f' _ _),_,False,False) ->
leading (f',b1,True,False)
((Definedness t _),_,_,_) ->
case (term t) of
Application _ _ _ -> return (Left (term t))
_ -> Nothing
((Predication p ts ps),_,_,_) ->
return (Right (Predication p ts ps))
((Strong_equation t _ _),_,False,False) ->
case (term t) of
Application _ _ _ -> return (Left (term t))
_ -> Nothing
((Existl_equation t _ _),_,False,False) ->
case (term t) of
Application _ _ _ -> return (Left (term t))
_ -> Nothing
_ -> Nothing
-- | extract the leading symbol from a term or a formula
extractLeadingSymb :: Either (TERM f) (FORMULA f) -> Either OP_SYMB PRED_SYMB
extractLeadingSymb lead =
case lead of
Left (Application os _ _) -> Left os
Right (Predication p _ _) -> Right p
_ -> error "CASL.CCC.TermFormula<extractLeadingSymb>"
-- | leadingTerm is total operation : Just True,
-- leadingTerm is partial operation : Just False,
-- others : Nothing.
opTypAxiom :: FORMULA f -> Maybe Bool
opTypAxiom f =
case (leadingSym f) of
Just (Left (Op_name _)) -> Nothing
Just (Left (Qual_op_name _ (Op_type Total _ _ _) _)) -> Just True
Just (Left (Qual_op_name _ (Op_type Partial _ _ _) _)) -> Just False
_ -> Nothing
-- | extract the overloaded constructors
constructorOverload :: Sign f e -> OpMap -> [OP_SYMB] -> [OP_SYMB]
constructorOverload s opm os = concatMap cons_Overload os
where cons_Overload o =
case o of
Op_name _ -> [o]
Qual_op_name on1 ot _ ->
concatMap (cons on1 ot) $ Set.toList $ MapSet.lookup on1 opm
cons on opt1 opt2 = [Qual_op_name on (toOP_TYPE opt2) nullRange |
leqF s (toOpType opt1) opt2]
-- | check whether the operation symbol is a constructor
isCons :: Sign f e -> [OP_SYMB] -> OP_SYMB -> Bool
isCons s cons os =
if null cons
then False
else is_Cons (head cons) os || isCons s (tail cons) os
where is_Cons (Op_name _) _ = False
is_Cons _ (Op_name _) = False
is_Cons (Qual_op_name on1 ot1 _) (Qual_op_name on2 ot2 _)
| on1 /= on2 = False
| not $ isSupersort s (res_OP_TYPE ot2) (res_OP_TYPE ot1) = False
| otherwise = isSupersortS s (args_OP_TYPE ot2) (args_OP_TYPE ot1)
-- | check whether a sort is the others super sort
isSupersort :: Sign f e -> SORT -> SORT -> Bool
isSupersort sig s1 s2 = elem s1 slist
where sM = Rel.toMap $ sortRel sig
slist = case Map.lookup s2 sM of
Nothing -> [s2]
Just sts -> Set.toList $ Set.insert s2 sts
-- | check whether all sorts of a set are another sets super sort
isSupersortS :: Sign f e -> [SORT] -> [SORT] -> Bool
isSupersortS sig s1 s2
| length s1 /= length s2 = False
| otherwise = supS s1 s2
where supS [] [] = True
supS sts1 sts2 = isSupersort sig (head sts1) (head sts2) &&
supS (tail sts1) (tail sts2)
-- | translate id to string
idStr :: Id -> String
idStr (Id ts _ _) = concatMap tokStr ts
-- | replaces variables by terms in a term
substitute :: Eq f => [(TERM f,TERM f)] -> TERM f -> TERM f
substitute subs t =
case t of
t'@(Qual_var _ _ _) ->
subst subs t'
Application os ts r ->
Application os (map (substitute subs) ts) r
Sorted_term te s r ->
Sorted_term (substitute subs te) s r
Cast te s r ->
Cast (substitute subs te) s r
Conditional t1 f t2 r ->
Conditional (substitute subs t1) (substiF subs f) (substitute subs t2) r
Mixfix_term ts ->
Mixfix_term (map (substitute subs) ts)
Mixfix_parenthesized ts r ->
Mixfix_parenthesized (map (substitute subs) ts) r
Mixfix_bracketed ts r ->
Mixfix_bracketed (map (substitute subs) ts) r
Mixfix_braced ts r ->
Mixfix_braced (map (substitute subs) ts) r
_ -> t
where subst [] tt = tt
subst (x:xs) tt = if tt == snd x then fst x
else subst xs tt
-- | replaces variables by terms in a formula
substiF :: Eq f => [(TERM f,TERM f)] -> FORMULA f -> FORMULA f
substiF subs f =
case f of
Quantification q v f' r -> Quantification q v (substiF subs f') r
Conjunction fs r -> Conjunction (map (substiF subs) fs) r
Disjunction fs r -> Disjunction (map (substiF subs) fs) r
Implication f1 f2 b r -> Implication (substiF subs f1) (substiF subs f2) b r
Equivalence f1 f2 r -> Equivalence (substiF subs f1) (substiF subs f2) r
Negation f' r -> Negation (substiF subs f') r
Predication ps ts r -> Predication ps (map (substitute subs) ts) r
Existl_equation t1 t2 r ->
Existl_equation (substitute subs t1) (substitute subs t2) r
Strong_equation t1 t2 r ->
Strong_equation (substitute subs t1) (substitute subs t2) r
Membership t s r -> Membership (substitute subs t) s r
Mixfix_formula t -> Mixfix_formula (substitute subs t)
_ -> f
-- | check whether two terms are the terms of same application symbol
sameOpsApp :: TERM f -> TERM f -> Bool
sameOpsApp app1 app2 = case (term app1) of
Application ops1 _ _ ->
case (term app2) of
Application ops2 _ _ -> ops1==ops2
_ -> False
_ -> False
-- | get the axiom range of a term
axiomRangeforTerm :: (GetRange f, Eq f) => [FORMULA f] -> TERM f -> Range
axiomRangeforTerm [] _ = nullRange
axiomRangeforTerm fs t =
case leadingTermPredication (head fs) of
Just (Left tt) -> if tt == t
then getRange $ quanti $ head fs
else axiomRangeforTerm (tail fs) t
_ -> axiomRangeforTerm (tail fs) t
-- | get the sort of a variable declaration
sortOfVarD :: VAR_DECL -> SORT
sortOfVarD (Var_decl _ s _) = s
-- | get or create a variable declaration for a formula
varDeclOfF :: Ord f => FORMULA f -> [VAR_DECL]
varDeclOfF f =
case f of
Quantification _ vds _ _ -> vds
Conjunction fs _ -> concatVD $ nubOrd $ concatMap varDeclOfF fs
Disjunction fs _ -> concatVD $ nubOrd $ concatMap varDeclOfF fs
Implication f1 f2 _ _ -> concatVD $ nubOrd $ varDeclOfF f1 ++
varDeclOfF f2
Equivalence f1 f2 _ -> concatVD $ nubOrd $ varDeclOfF f1 ++
varDeclOfF f2
Negation f' _ -> varDeclOfF f'
Predication _ ts _ -> varD $ nubOrd $ concatMap varOfTerm ts
Definedness t _ -> varD $ varOfTerm t
Existl_equation t1 t2 _ -> varD $ nubOrd $ varOfTerm t1 ++ varOfTerm t2
Strong_equation t1 t2 _ -> varD $ nubOrd $ varOfTerm t1 ++ varOfTerm t2
_ -> []
where varD [] = []
varD vars@(v:vs) =
case v of
Qual_var _ s r ->
Var_decl (nubOrd $ map varOfV $
filter (\ v' -> sortOfV v' == s) vars) s r:
varD (filter (\ v' -> sortOfV v' /= s) vs)
_ -> error "CASL.CCC.TermFormula<varD>"
concatVD [] = []
concatVD vd@((Var_decl _ s r):vds) =
Var_decl (nubOrd $ concatMap vOfVD $
filter (\ v' -> sortOfVarD v' == s) vd) s r:
concatVD (filter (\ v' -> sortOfVarD v' /= s) vds)
vOfVD (Var_decl vs _ _) = vs
sortOfV (Qual_var _ s _) = s
sortOfV _ = error "CASL.CCC.TermFormula<sortOfV>"
varOfV (Qual_var v _ _) = v
varOfV _ = error "CASL.CCC.TermFormula<varOfV>"
|
nevrenato/Hets_Fork
|
CASL/CCC/TermFormula.hs
|
gpl-2.0
| 19,224
| 0
| 18
| 7,148
| 6,133
| 3,065
| 3,068
| 362
| 16
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Utils.GHCUtils
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : Jutaro <jutaro@leksah.org>
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Utils.GHCUtils (
inGhcIO
, getInstalledPackageInfos
, findFittingPackages
, myParseModule
, myParseHeader
) where
import Distribution.Simple (withinRange,PackageIdentifier(..),Dependency(..))
#if MIN_VERSION_ghc(7,10,0)
import PackageConfig (sourcePackageIdString)
import Distribution.Text (simpleParse)
import Data.Maybe (fromJust)
#else
import qualified Distribution.InstalledPackageInfo as IPI (sourcePackageId)
#endif
import GHC
import DriverPipeline(preprocess)
import StringBuffer (StringBuffer(..),hGetStringBuffer)
import FastString (mkFastString)
import Lexer (mkPState,ParseResult(..),getMessages,unP)
import Outputable (ppr)
#if MIN_VERSION_ghc(7,2,0)
#if MIN_VERSION_ghc(7,6,0)
import Bag (unitBag)
#else
import ErrUtils (printBagOfWarnings)
#endif
import ErrUtils (dumpIfSet_dyn,printBagOfErrors,errorsFound,mkPlainErrMsg,showPass,ErrMsg(..))
import Control.Monad (unless)
#else
import ErrUtils (dumpIfSet_dyn,printErrorsAndWarnings,mkPlainErrMsg,showPass,ErrMsg(..))
#endif
import PackageConfig (PackageConfig)
import Data.Foldable (maximumBy)
import qualified Parser as P (parseModule,parseHeader)
import HscStats (ppSourceStats)
#if MIN_VERSION_ghc(7,2,0)
#if !MIN_VERSION_ghc(7,7,0)
import GhcMonad (Ghc(..))
#endif
import SrcLoc (mkRealSrcLoc)
#else
import HscTypes (Ghc(..))
#endif
import IDE.Utils.FileUtils (getSysLibDir)
#if MIN_VERSION_ghc(7,7,0)
import DynFlags (DumpFlag(..), gopt_set, PkgConfRef(..))
#else
import DynFlags (dopt_set, PkgConfRef(..))
#endif
import System.Log.Logger(debugM)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Text (Text)
import qualified Data.Text as T (pack, unpack)
import Data.Monoid ((<>))
import Data.Function (on)
#if !MIN_VERSION_ghc(7,7,0)
-- this should not be repeated here, why is it necessary?
instance MonadIO Ghc where
liftIO ioA = Ghc $ \_ -> ioA
#endif
#if MIN_VERSION_ghc(7,7,0)
inGhcIO :: FilePath -> [Text] -> [GeneralFlag] -> [FilePath] -> (DynFlags -> Ghc a) -> IO a
#else
inGhcIO :: FilePath -> [Text] -> [DynFlag] -> [FilePath] -> (DynFlags -> Ghc a) -> IO a
#endif
inGhcIO libDir flags' udynFlags dbs ghcAct = do
debugM "leksah-server" $ "inGhcIO called with: " ++ show flags'
-- (restFlags, _) <- parseStaticFlags (map noLoc flags')
runGhc (Just libDir) $ do
dynflags <- getSessionDynFlags
#if MIN_VERSION_ghc(7,7,0)
let dynflags' = foldl gopt_set dynflags udynFlags
#else
let dynflags' = foldl dopt_set dynflags udynFlags
#endif
let dynflags'' = dynflags' {
hscTarget = HscNothing,
ghcMode = CompManager,
ghcLink = NoLink,
extraPkgConfs = (map PkgConfFile dbs++) . extraPkgConfs dynflags'
}
dynflags''' <- parseGhcFlags dynflags'' (map (noLoc . T.unpack) flags') flags'
res <- defaultCleanupHandler dynflags''' $ do
setSessionDynFlags dynflags'''
getSessionDynFlags >>= ghcAct
unload
return res
where
parseGhcFlags :: DynFlags -> [Located String]
-> [Text] -> Ghc DynFlags
parseGhcFlags dynflags flags_ _origFlags = do
(dynflags', rest, _) <- parseDynamicFlags dynflags flags_
if not (null rest)
then do
liftIO $ debugM "leksah-server" ("No dynamic GHC options: " ++ unwords (map unLoc rest))
return dynflags'
else return dynflags'
-- | Unload whatever is currently loaded.
unload :: Ghc ()
unload = do
setTargets []
load LoadAllTargets
return ()
getInstalledPackageInfos :: Ghc [PackageConfig]
getInstalledPackageInfos = do
dflags1 <- getSessionDynFlags
#if !MIN_VERSION_ghc(7,6,0)
setSessionDynFlags $ dopt_set dflags1 Opt_ReadUserPackageConf
#endif
case pkgDatabase dflags1 of
Nothing -> return []
Just fm -> return fm
findFittingPackages :: [Dependency] -> Ghc [PackageIdentifier]
findFittingPackages dependencyList = do
knownPackages <- getInstalledPackageInfos
#if MIN_VERSION_ghc(7,10,0)
let packages = map (fromJust . simpleParse . sourcePackageIdString) knownPackages
#else
let packages = map IPI.sourcePackageId knownPackages
#endif
return (concatMap (fittingKnown packages) dependencyList)
where
fittingKnown packages (Dependency dname versionRange) =
let filtered = filter (\ (PackageIdentifier name version) ->
name == dname && withinRange version versionRange)
packages
in if length filtered > 1
then [maximumBy (compare `on` pkgVersion) filtered]
else filtered
---------------------------------------------------------------------
-- | Parser function copied here, because it is not exported
myParseModule :: DynFlags -> FilePath -> Maybe StringBuffer
-> IO (Either ErrMsg (Located (HsModule RdrName)))
myParseModule dflags src_filename maybe_src_buf
= -------------------------- Parser ----------------
showPass dflags "Parser" >>
{-# SCC "Parser" #-} do
-- sometimes we already have the buffer in memory, perhaps
-- because we needed to parse the imports out of it, or get the
-- module name.
buf' <- case maybe_src_buf of
Just b -> return b
Nothing -> hGetStringBuffer src_filename
#if MIN_VERSION_ghc(7,2,0)
let loc = mkRealSrcLoc (mkFastString src_filename) 1 0
#else
let loc = mkSrcLoc (mkFastString src_filename) 1 0
#endif
case unP P.parseModule (mkPState dflags buf' loc) of {
#if MIN_VERSION_ghc(7,6,0)
PFailed span' err -> do {
let {errMsg = mkPlainErrMsg dflags span' err};
printBagOfErrors dflags (unitBag errMsg);
return (Left errMsg);
};
#else
PFailed span' err -> return (Left (mkPlainErrMsg span' err));
#endif
POk pst rdr_module -> do {
#if MIN_VERSION_ghc(7,2,0)
let {ms@(warnings, errors) = getMessages pst};
printBagOfErrors dflags errors;
#if MIN_VERSION_ghc(7,6,0)
unless (errorsFound dflags ms) $ printBagOfErrors dflags warnings;
#else
unless (errorsFound dflags ms) $ printBagOfWarnings dflags warnings;
#endif
#else
let {ms = getMessages pst};
printErrorsAndWarnings dflags ms;
#endif
-- when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
(ppSourceStats False rdr_module) ;
return (Right rdr_module)
-- ToDo: free the string buffer later.
}}
myParseHeader :: FilePath -> String -> [Text] -> IO (Either Text (DynFlags, HsModule RdrName))
myParseHeader fp _str opts = do
libDir <- getSysLibDir
inGhcIO libDir (opts++["-cpp"]) [] [] $ \ _dynFlags -> do
session <- getSession
#if MIN_VERSION_ghc(7,2,0)
(dynFlags',fp') <- liftIO $ preprocess session (fp,Nothing)
#else
(dynFlags',fp') <- preprocess session (fp,Nothing)
#endif
liftIO $ do
stringBuffer <- hGetStringBuffer fp'
parseResult <- myParseModuleHeader dynFlags' fp (Just stringBuffer)
case parseResult of
Right (L _ mod') -> return (Right (dynFlags', mod'))
Left errMsg -> do
let str = "Failed to parse " <> T.pack (show errMsg)
return (Left str)
---------------------------------------------------------------------
-- | Parser function copied here, because it is not exported
myParseModuleHeader :: DynFlags -> FilePath -> Maybe StringBuffer
-> IO (Either ErrMsg (Located (HsModule RdrName)))
myParseModuleHeader dflags src_filename maybe_src_buf
= -------------------------- Parser ----------------
showPass dflags "Parser" >>
{-# SCC "Parser" #-} do
-- sometimes we already have the buffer in memory, perhaps
-- because we needed to parse the imports out of it, or get the
-- module name.
buf' <- case maybe_src_buf of
Just b -> return b
Nothing -> hGetStringBuffer src_filename
#if MIN_VERSION_ghc(7,2,0)
let loc = mkRealSrcLoc (mkFastString src_filename) 1 0
#else
let loc = mkSrcLoc (mkFastString src_filename) 1 0
#endif
#if MIN_VERSION_ghc(7,0,1)
case unP P.parseHeader (mkPState dflags buf' loc) of {
#else
case unP P.parseHeader (mkPState buf' loc dflags) of {
#endif
#if MIN_VERSION_ghc(7,6,0)
PFailed span' err -> return (Left (mkPlainErrMsg dflags span' err));
#else
PFailed span' err -> return (Left (mkPlainErrMsg span' err));
#endif
POk pst rdr_module -> do {
#if MIN_VERSION_ghc(7,2,0)
let {ms@(warnings, errors) = getMessages pst};
printBagOfErrors dflags errors;
#if MIN_VERSION_ghc(7,6,0)
unless (errorsFound dflags ms) $ printBagOfErrors dflags warnings;
#else
unless (errorsFound dflags ms) $ printBagOfWarnings dflags warnings;
#endif
#else
let {ms = getMessages pst};
printErrorsAndWarnings dflags ms;
#endif
-- when (errorsFound dflags ms) $ exitWith (ExitFailure 1);
dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr rdr_module) ;
dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics"
(ppSourceStats False rdr_module) ;
return (Right rdr_module)
-- ToDo: free the string buffer later.
}}
|
JPMoresmau/leksah-server
|
src/IDE/Utils/GHCUtils.hs
|
gpl-2.0
| 10,014
| 0
| 25
| 2,280
| 1,990
| 1,072
| 918
| -1
| -1
|
{-| Metadata daemon.
-}
{-
Copyright (C) 2014 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Main (main) where
import qualified Ganeti.Constants as Constants
import Ganeti.Daemon (OptType)
import qualified Ganeti.Daemon as Daemon
import qualified Ganeti.Metad as Metad
import qualified Ganeti.Runtime as Runtime
options :: [OptType]
options =
[ Daemon.oBindAddress
, Daemon.oDebug
, Daemon.oNoDaemonize
, Daemon.oNoUserChecks
, Daemon.oPort Constants.defaultMetadPort
]
main :: IO ()
main =
Daemon.genericMain Runtime.GanetiMetad options
(\_ -> return . Right $ ())
(\_ _ -> return ())
(\opts _ _ -> Metad.start opts)
|
badp/ganeti
|
src/ganeti-metad.hs
|
gpl-2.0
| 1,309
| 0
| 9
| 233
| 176
| 105
| 71
| 19
| 1
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module AntSkull where
import Control.Monad.State hiding (when)
import Control.Monad.Writer hiding (when)
import Data.List (sortBy)
import Data.Function (on)
import Prelude hiding (drop, Left, Right, (&&), (||))
--
-- A nice way to print our functions
--
class PrimitiveInstruction r where
instruction :: String -> Entry -> r
instance PrimitiveInstruction (M ()) where
instruction s n = lift $ writer ((), [(n, s)])
instance (PrimitiveInstruction r, Show a) => PrimitiveInstruction (a -> r) where
instruction s n x = instruction (s ++ " " ++ show x) n
type Entry = Int -- Convention: all entry identifiers start with an underscore
type Cont = Int
type Program = [(Entry, String)]
type M = StateT Int (Writer Program)
-- Allocate an entrypoint for a function
alloc :: M Int
alloc = do
n <- get
modify (+1)
return n
--
-- IO functionality
--
-- Generate the program and sort instructions on line number
run :: M () -> Program
run prog = sortBy (compare `on` fst) (snd $ runWriter (runStateT (alloc >> prog) 0))
-- Print function to IO
debug :: M () -> IO ()
debug prog = mapM_ (putStrLn . snd) (run prog)
--
-- Some datatypes to make life more beautiful
--
data SenseDir = Here | Ahead | LeftAhead | RightAhead deriving Show
data Condition = Friend | Foe | FriendWithFood | FoeWithFood
| Food | Rock | Marker Mark | FoeMarker
| Home | FoeHome deriving Show
data Turn = Left | Right deriving Show
type Mark = Int
--
-- The primitive functions
--
sense :: Entry -> SenseDir -> Cont -> Cont -> Condition -> M ()
sense n = instruction "Sense" n
mark :: Entry -> Mark -> Cont -> M ()
mark n = instruction "Mark" n
unmark :: Entry -> Mark -> Cont -> M ()
unmark n = instruction "Unmark" n
pickup :: Entry -> Cont -> Cont -> M ()
pickup n = instruction "PickUp" n
drop :: Entry -> Cont -> M ()
drop n = instruction "Drop" n
turn :: Entry -> Turn -> Cont -> M ()
turn n = instruction "Turn" n
move :: Entry -> Cont -> Cont -> M ()
move n = instruction "Move" n
rand :: Entry -> Int -> Cont -> Cont -> M ()
rand n = instruction "Flip" n
--
-- Advanced sensing system
--
data Expr = If SenseDir Condition | Not Expr | And Expr Expr | Or Expr Expr
notIf dir cond = Not (If dir cond)
(&&) expr1 expr2 = And expr1 expr2
(||) expr1 expr2 = Or expr1 expr2
when :: Entry -> Expr -> Cont -> Cont -> M ()
when n1 (If dir cond) k1 k2 = sense n1 dir k1 k2 cond
when n1 (Not expr) k1 k2 = when n1 expr k2 k1
when n1 (And expr1 expr2) k1 k2 = do
n2 <- alloc
when n1 expr1 n2 k2
when n2 expr2 k1 k2
when n1 (Or expr1 expr2) k1 k2 = do
n2 <- alloc
when n1 expr1 k1 n2
when n2 expr2 k1 k2
--
-- Our extension functions
--
-- GEEF GLOBALS DOOR ALS PARAMETERS
-- Do a random move (biased to go fairly straight)
randomMove :: Entry -> Cont -> M ()
randomMove _this k = do
_rand <- alloc
_turnR <- alloc
_turnL <- alloc
_move <- alloc
random _this 75 _move _rand
random _rand 50 _turnR _turnL
turn _turnR Right _move
turn _turnL Left _move
move _move k _this
-- Try follow a trail in front, else do a random move
tryFollowTrail :: Entry -> Condition -> Cont -> M ()
tryFollowTrail _this cond k = do
_randomMove <- alloc
followTrail _this cond k _randomMove
randomMove _randomMove k
-- Follow a trail in front, or fail
followTrail :: Entry -> Condition -> Cont -> Cont -> M ()
followTrail _this cond k1 k2 = do
_moveAgain <- alloc
_moveAround <- alloc
-- If the marker is in front of us and we moved there, go to k1
senseAdjMove _this k1 _moveAgain k2 cond
move21 _moveAgain k1 _moveAround
-- If we keep bumping into something, move around
moveAround _moveAround k1 k2
-- Try to pass at the right side
moveAround :: Entry -> Cont -> Cont -> M ()
moveAround _this k1 k2 = do
_moveForwardRight <- alloc
_turnBackRight <- alloc
_turnLeft <- alloc
_moveForwardLeft <- alloc
_turnBackLeft <- alloc
_moveLeftFailed <- alloc
-- Turn right, move forward and turn back left
turn _this Right _moveForwardRight
move _moveForwardRight _turnBackRight _turnLeft
turn2 _turnBackRight Left k1
-- If the move failed, try to pass at the left side
turn2 _turnLeft Left _moveForwardLeft
move _moveForwardLeft _turnBackLeft _moveLeftFailed
turn2 _turnBackLeft Right k1
-- If that failed as well, then turn back and fail for real
turn _moveLeftFailed Right k2
-- Check a condition in all adjacent directions
-- Gets the two state parameters and the condition
senseAdj :: Entry -> Cont -> Cont -> Condition -> M ()
senseAdj _this k1 k2 cond = when _this (If Ahead cond || If RightAhead cond || If LeftAhead cond) k1 k2
-- Check a condition in all adjacent directions, and move to the corresponding place if the condition holds
-- Gets three state parameters (move succes, move fail and condition fail) and the condition
senseAdjMove :: Entry -> Cont -> Cont -> Cont -> Condition -> M ()
senseAdjMove _this k1 k2 k3 cond = do
_or2 <- alloc
_or3 <- alloc
_turnR <- alloc
_turnL <- alloc
_moveA <- alloc
_moveR <- alloc
_moveL <- alloc
when _this (If Ahead cond) _moveA _or2
when _or2 (If RightAhead cond) _turnR _or3
when _or3 (If LeftAhead cond) _turnL k3
move _moveA k1 _or2
turn _turnR Right _moveR
move _moveR k1 _or3
turn _turnL Left _moveL
move _moveL k1 k2
-- Check a condition in all adjacent directions, and move to the corresponding place if the condition holds
-- Gets three state parameters (move succes, move fail and condition fail), the condition and the not-condition
senseAdjMoveAndNot :: Entry -> Cont -> Cont -> Cont -> Condition -> Condition -> M ()
senseAdjMoveAndNot _this k1 k2 k3 cond notCond = do
_or2 <- alloc
_or3 <- alloc
_move <- alloc
_turnR <- alloc
_turnL <- alloc
when _this (If Ahead cond && notIf Ahead notCond) _move _or2
when _or2 (If RightAhead cond && notIf Ahead notCond) _turnR _or3
when _or3 (If LeftAhead cond && notIf Ahead notCond) _turnL k3
turn _turnR Right _move
turn _turnL Left _move
move _move k1 k2
-- Move multiple times
-- Gets the normal move parameters
move7 :: Entry -> Cont -> Cont -> M ()
move7 _this k1 k2 = do
_m2 <- alloc
_m3 <- alloc
_m4 <- alloc
_m5 <- alloc
_m6 <- alloc
_m7 <- alloc
move _this k1 _m2
move _m2 k1 _m3
move _m3 k1 _m4
move _m4 k1 _m5
move _m5 k1 _m6
move _m6 k1 _m7
move _m7 k1 k2
move21 :: Entry -> Cont -> Cont -> M()
move21 _this k1 k2 = do
_m8 <- alloc
_m15 <- alloc
move7 _this k1 _m8
move7 _m8 k1 _m15
move7 _m15 k1 k2
-- Turn multiple times
-- Gets the normal turn parameters: a turn direction {Left, Right} and the state paramweter
turn2 :: Entry -> Turn -> Cont -> M ()
turn2 _this t k = do
_t2 <- alloc
turn _this t _t2
turn _t2 t k
turnAround :: Entry -> Cont -> M ()
turnAround _this k = do
_t2 <- alloc
_t3 <- alloc
turn _this Right _t2
turn _t2 Right _t3
turn _t3 Right k
-- Create a decent randomizer in terms of the Flip randomizer
-- Gets its current line number, the percentage in [0, 100], and the two state parameters
random :: Entry -> Float -> Cont -> Cont -> M ()
random _this 5 k1 k2 = rand _this 20 k1 k2
random _this 10 k1 k2 = rand _this 10 k1 k2
random _this 33 k1 k2 = rand _this 3 k1 k2
random _this 25 k1 k2 = rand _this 4 k1 k2
random _this 50 k1 k2 = rand _this 2 k1 k2
random _this 67 k1 k2 = rand _this 3 k2 k1
random _this 75 k1 k2 = rand _this 4 k2 k1
random _this 90 k1 k2 = rand _this 10 k2 k1
|
Chiel92/ants
|
AntSkull.hs
|
gpl-2.0
| 7,753
| 0
| 12
| 1,942
| 2,537
| 1,243
| 1,294
| 176
| 1
|
#!/usr/bin/env runhaskell
{-|
hledger-print-unique [-f JOURNALFILE | -f-]
Print only journal entries which are unique by description (or
something else). Reads the default or specified journal, or stdin.
|-}
import Data.List
import Data.Ord
import Hledger.Cli
main = do
putStrLn "(-f option not supported)"
opts <- getCliOpts (defCommandMode ["hledger-print-unique"])
withJournalDo opts $
\opts j@Journal{jtxns=ts} -> print' opts j{jtxns=uniquify ts}
where
uniquify = nubBy (\t1 t2 -> thingToCompare t1 == thingToCompare t2) . sortBy (comparing thingToCompare)
thingToCompare = tdescription
-- thingToCompare = tdate
|
kmels/hledger
|
extra/hledger-print-unique.hs
|
gpl-3.0
| 653
| 0
| 12
| 117
| 142
| 73
| 69
| 10
| 1
|
module Type where
class Type a where
showType :: a -> String
|
Kotolegokot/Underlisp
|
src/Type.hs
|
gpl-3.0
| 64
| 0
| 7
| 15
| 22
| 12
| 10
| 3
| 0
|
{-
This source file is a part of the noisefunge programming environment.
Copyright (C) 2015 Rev. Johnny Healey <rev.null@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE FlexibleContexts #-}
module Language.NoiseFunge.Server.Comm (Subscription(..),
Request(..),
Response(..),
withAPIConnection,
Conn,
addProgram,
sendBinary',
requestReset,
streamEvents) where
import Control.Applicative
import Control.Monad
import qualified Control.Monad.State as ST
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Data.Binary
import Data.ByteString.Lazy as BS
import Network.Socket
import Network.Socket.ByteString
import System.Environment
import System.Timeout
import Language.NoiseFunge.Beat
import Language.NoiseFunge.Befunge
import Language.NoiseFunge.Befunge.Process
data Subscription = Stats | Deltas
deriving (Read, Show, Eq, Ord)
instance Binary Subscription where
get = getSub <$> getWord8 where
getSub 0 = Stats
getSub 1 = Deltas
getSub _ = error "Bad Subscription"
put Stats = putWord8 0
put Deltas = putWord8 1
data Request =
Subscribe Subscription (Maybe Beat)
| StartProgram String String String ProgArray
| StopProgram (Maybe Word32) (Maybe String) (Maybe String)
| SendReset
deriving (Show, Eq, Ord)
instance Binary Request where
get = getWord8 >>= getReq where
getReq 0 = Subscribe <$> get <*> get
getReq 1 = StartProgram <$> get <*> get <*> get <*> get
getReq 2 = StopProgram <$> get <*> get <*> get
getReq 3 = return SendReset
getReq _ = error "Bad request"
put (Subscribe s b) =
putWord8 0 >> put s >> put b
put (StartProgram n ib ob a) =
putWord8 1 >> put n >> put ib >> put ob >> put a
put (StopProgram p n r) =
putWord8 2 >> put p >> put n >> put r
put SendReset =
putWord8 3
data Response =
Catchup !Beat !PID ProgArray Delta
| Change !Beat !PID Delta
| Dead !Beat !PID (Maybe String)
| NewProcess !PID
| NextBeat !Beat
| ProcessStats !Beat !BefungeStats
| TickStats !Beat !Word32 !Word32 !Word32 !Word32
| Reset
deriving (Show, Eq, Ord)
instance Binary Response where
get = getWord8 >>= getResp where
getResp 0 = Catchup <$> get <*> get <*> get <*> get
getResp 1 = Change <$> get <*> get <*> get
getResp 2 = Dead <$> get <*> get <*> get
getResp 3 = NewProcess <$> get
getResp 4 = NextBeat <$> get
getResp 5 = ProcessStats <$> get <*> get
getResp 6 = TickStats <$> get <*> get <*> get <*> get <*> get
getResp 7 = return Reset
getResp _ = error "Bad Response"
put (Catchup a b c d) = putWord8 0 >> put a >> put b >> put c >> put d
put (Change a b c) = putWord8 1 >> put a >> put b >> put c
put (Dead a b c) = putWord8 2 >> put a >> put b >> put c
put (NewProcess a) = putWord8 3 >> put a
put (NextBeat a) = putWord8 4 >> put a
put (ProcessStats a b) = putWord8 5 >> put a >> put b
put (TickStats a b c d e) =
putWord8 6 >> put a >> put b >> put c >> put d >> put e
put Reset = putWord8 7
data Conn = Conn Socket SockAddr
withAPIConnection :: (Conn -> IO a) -> IO ()
withAPIConnection fn = do
host <- getEnv "NOISEFUNGE_HOST"
servHost <- getEnv "NOISEFUNGE_SERVER_HOST"
servPort <- getEnv "NOISEFUNGE_SERVER_PORT"
ais <- getAddrInfo Nothing (Just host) Nothing
sais <- getAddrInfo Nothing (Just servHost) (Just servPort)
case (ais, sais) of
([],__) -> error "Invalid NOISEFUNGE_HOST"
(_, []) -> error
"Invalid NOISEFUNGE_SERVER_HOST or NOISEFUNGE_SERVER_PORT"
((ai:_), (sai:_)) -> do
s <- socket (addrFamily ai) Datagram defaultProtocol
bind s (addrAddress ai)
void $ fn (Conn s (addrAddress sai))
runBuffered :: Monad m => ST.StateT [b] m a -> m a
runBuffered bst = ST.evalStateT bst []
sendBinary :: (MonadIO m, Functor m) => Binary b =>
b -> Conn -> ST.StateT [b1] m ()
sendBinary b (Conn s dest) = do
let b' = toStrict $ encode b
void $ liftIO $ sendTo s b' dest
sendBinary' :: Binary b => b -> Conn -> IO ()
sendBinary' b (Conn s dest) = do
let b' = toStrict $ encode b
void $ sendTo s b' dest
waitForBinary :: (Functor m, MonadIO m) => Binary b => Conn ->
Maybe Int -> ST.StateT [b] m (Maybe b)
waitForBinary (Conn s _) timeo = runMaybeT readBinary where
readBinary = readFromBuf <|> readFromSock
readFromBuf = do
buff <- lift $ ST.get
case buff of
[] -> fail "empty"
(x:xs) -> do
ST.put xs
return x
readFromSock = do
(bs, _) <- case timeo of
Just t -> MaybeT . liftIO . timeout t $ recvFrom s 32768
Nothing -> liftIO $ recvFrom s 32768
lift $ decodeAll (fromChunks [bs])
readBinary
decodeAll bs
| BS.null bs = return ()
| otherwise = case (decodeOrFail bs) of
Left (_,_,err) -> fail err
Right (rest,_,a) -> do
decodeAll rest
ST.modify (a:)
addProgram :: Conn -> String -> String -> String -> [String] -> IO PID
addProgram conn name inbuf outbuf arr = do
runBuffered $ do
sendBinary (StartProgram name inbuf outbuf (makeProgArray arr)) conn
Just (NewProcess p) <- waitForBinary conn Nothing
return p
requestReset :: Conn -> IO ()
requestReset conn = runBuffered $ do
sendBinary SendReset conn
streamEvents :: (Functor m, MonadIO m) => [Subscription] -> Conn ->
(Response -> m a) -> m ()
streamEvents subs conn fn = runBuffered $ initialize where
initialize = do
subscribe Nothing
wait
subscribe b = do
forM_ subs $ \sub -> do
sendBinary (Subscribe sub b) conn
wait = waitForBinary conn (Just 1000000) >>= handle
handle Nothing = initialize
handle (Just r@(NextBeat b)) = do
void . lift $ fn r
subscribe (Just b)
wait
handle (Just r) = do
void . lift $ fn r
wait
|
revnull/noisefunge
|
src/Language/NoiseFunge/Server/Comm.hs
|
gpl-3.0
| 7,027
| 0
| 17
| 2,176
| 2,290
| 1,124
| 1,166
| -1
| -1
|
module Main where
import Graphics.Rendering.Chart.Easy
import Data.Time.LocalTime
import BenchmarkHistory
main :: IO ()
main = return ()
|
choener/BenchmarkHistory
|
src/BenchmarkHistogram.hs
|
gpl-3.0
| 144
| 0
| 6
| 24
| 40
| 24
| 16
| 6
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Rasa.Ext.Slate.Internal.Attributes where
import Rasa.Ext
import qualified Yi.Rope as Y
import qualified Graphics.Vty as V
import Data.Bifunctor
import Data.Text (Text, pack)
-- | Convert style from "Rasa.Ext.Style" into 'V.Attr's
convertStyle :: Style -> V.Attr
convertStyle (Style (fg', bg', flair')) = V.Attr
(maybe V.KeepCurrent convertFlair flair')
(maybe V.KeepCurrent convertColor fg')
(maybe V.KeepCurrent convertColor bg')
(maybe V.KeepCurrent convertUrl (Just ""))
-- | Convert flair from "Rasa.Ext.Style" into 'V.Style's
convertFlair :: Flair -> V.MaybeDefault V.Style
convertFlair Standout = V.SetTo V.standout
convertFlair Underline = V.SetTo V.underline
convertFlair ReverseVideo = V.SetTo V.reverseVideo
convertFlair Blink = V.SetTo V.blink
convertFlair Dim = V.SetTo V.dim
convertFlair Bold = V.SetTo V.bold
convertFlair Italic = V.SetTo V.italic
convertFlair DefFlair = V.Default
-- | Convert colors from "Rasa.Ext.Style" into 'V.Color's
convertColor :: Color -> V.MaybeDefault V.Color
convertColor Black = V.SetTo V.black
convertColor Red = V.SetTo V.red
convertColor Green = V.SetTo V.green
convertColor Yellow = V.SetTo V.yellow
convertColor Blue = V.SetTo V.blue
convertColor Magenta = V.SetTo V.magenta
convertColor Cyan = V.SetTo V.cyan
convertColor White = V.SetTo V.white
convertColor DefColor = V.Default
convertUrl :: Text -> V.MaybeDefault Text
convertUrl = V.SetTo
-- | helper to reset to default attributes
reset :: V.Image
reset = V.text' V.defAttr ""
-- | A newtype to define a (not necessarily law abiding) Monoid for 'V.Attr' which acts as we like.
newtype AttrMonoid = AttrMonoid {
getAttr :: V.Attr
}
instance Semigroup AttrMonoid where
AttrMonoid v <> AttrMonoid v' = AttrMonoid $ v <> v'
-- | We want 'mempty' to be 'V.defAttr' instead of 'V.currentAttr' for use in 'combineSpans'.
instance Monoid AttrMonoid where
mempty = AttrMonoid V.defAttr
-- | Apply a list of styles to the given text, resulting in a 'V.Image'.
applyAttrs :: RenderInfo -> V.Image
applyAttrs (RenderInfo txt styles) = textAndStylesToImage mergedSpans (padSpaces <$> Y.lines txt)
where mergedSpans = second getAttr <$> combineSpans (fmap AttrMonoid <$> atts)
-- Newlines aren't rendered; so we replace them with spaces so they're selectable
padSpaces = (`Y.append` " ")
atts = second convertStyle <$> styles
-- | Makes and image from text and styles
textAndStylesToImage :: [(Coord, V.Attr)] -> [Y.YiString] -> V.Image
textAndStylesToImage atts lines' = V.vertCat $ wrapResets . uncurry attrLine <$> pairLines atts lines'
where
wrapResets img = reset V.<|> img V.<|> reset
-- | Applies the list of attrs to the line and returns a 'V.Image'. It assumes that the list
-- contains only 'Coord's on the same line (i.e. row == 0)
--
-- Should be able to clean this up and provide better guarantees if I do a scan
-- over attrs and get each successive mappend of them, then do T.splitAt for
-- each offset, then apply the attr for each section at the begining of each
-- of T.lines within each group. Ugly I know.
attrLine :: [(Coord, V.Attr)] -> Y.YiString -> V.Image
attrLine [] txt = plainText txt
attrLine atts "" = V.text' (mconcat (snd <$> atts)) ""
attrLine ((Coord _ 0, attr):atts) txt = V.text' attr "" V.<|> attrLine atts txt
attrLine atts@((Coord _ col, _):_) txt =
let (prefix, suffix) = Y.splitAt col txt
in plainText prefix V.<|> attrLine (decrCol col atts) suffix
-- | Pairs up lines with their styles.
pairLines :: [(Coord, b)] -> [a] -> [([(Coord, b)], a)]
pairLines _ [] = []
pairLines [] ls = zip (repeat []) ls
pairLines crds@((Coord 0 _, _):_) (l:ls) = (takeWhile isSameRow crds, l) : pairLines (decrRow $ dropWhile isSameRow crds) ls
where isSameRow (Coord 0 _, _) = True
isSameRow _ = False
pairLines crds (l:ls) = ([], l): pairLines (decrRow crds) ls
-- | Decrements the row of all future attrs' location
decrRow :: [(Coord, a)] -> [(Coord, a)]
decrRow = fmap (\(Coord r c, a) -> (Coord (r-1) c, a))
-- | Decrements the column of all future attrs' location by the given amount
decrCol :: Int -> [(Coord, a)] -> [(Coord, a)]
decrCol n = fmap (\(Coord r c, a) -> (Coord r (c-n), a))
-- | Creates a text image without any new attributes.
plainText :: Y.YiString -> V.Image
plainText = V.text' V.currentAttr . Y.toText
|
ChrisPenner/rasa
|
rasa-ext-slate/src/Rasa/Ext/Slate/Internal/Attributes.hs
|
gpl-3.0
| 4,517
| 0
| 11
| 909
| 1,334
| 708
| 626
| 70
| 2
|
module System.Environment.XDG.MimeType where
|
felixsch/xdg
|
src/System/Environment/XDG/MimeType.hs
|
gpl-3.0
| 45
| 0
| 3
| 3
| 8
| 6
| 2
| 1
| 0
|
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, TemplateHaskell #-}
-- | Run a process that evaluates given compiled
module Lamdu.Eval.JS
( Evaluator
, Actions(..), aLoadGlobal, aReadAssocName, aReportUpdatesAvailable, aCompleted
, start, stop
, Dependencies(..), whilePaused
, getResults
) where
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.MVar
import qualified Control.Exception as E
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Monad (unless)
import qualified Data.Aeson as JsonStr
import Data.Aeson.Types ((.:))
import qualified Data.Aeson.Types as Json
import qualified Data.ByteString as SBS
import qualified Data.ByteString.Char8 as Char8
import qualified Data.ByteString.Base16 as Hex
import qualified Data.ByteString.Lazy as LBS
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IORef
import Data.List.Split (chunksOf)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import Data.UUID.Types (UUID)
import qualified Data.UUID.Utils as UUIDUtils
import qualified Data.Vector as Vec
import Data.Word (Word8)
import qualified Lamdu.Builtins.PrimVal as PrimVal
import Lamdu.Calc.Identifier (Identifier(..))
import Lamdu.Calc.Type (Tag(..))
import qualified Lamdu.Calc.Val as V
import Lamdu.Calc.Val.Annotated (Val)
import qualified Lamdu.Data.Definition as Def
import qualified Lamdu.DataFile as DataFile
import qualified Lamdu.Eval.JS.Compiler as Compiler
import Lamdu.Eval.Results (ScopeId(..), EvalResults(..))
import qualified Lamdu.Eval.Results as ER
import Numeric (readHex)
import System.FilePath (splitFileName)
import System.IO (IOMode(..), Handle, hClose, hIsEOF, hPutStrLn, withFile)
import qualified System.NodeJS.Path as NodeJS
import qualified System.Process as Proc
import Prelude.Compat
data Actions srcId = Actions
{ _aLoadGlobal :: V.Var -> IO (Def.Body (Val srcId))
, -- TODO: This is currently not in use but remains here because
-- it *should* be used for readable JS output
_aReadAssocName :: UUID -> IO String
, _aReportUpdatesAvailable :: IO ()
, _aCompleted :: Either E.SomeException (ER.Val srcId) -> IO ()
, _aCopyJSOutputPath :: Maybe FilePath
}
Lens.makeLenses ''Actions
data Dependencies srcId = Dependencies
{ subExprDeps :: Set srcId
, globalDeps :: Set V.Var
}
instance Ord srcId => Monoid (Dependencies srcId) where
mempty = Dependencies mempty mempty
mappend (Dependencies x0 y0) (Dependencies x1 y1) =
Dependencies (x0 <> x1) (y0 <> y1)
data Evaluator srcId = Evaluator
{ stop :: IO ()
, eDeps :: MVar (Dependencies srcId)
, eResultsRef :: IORef (EvalResults srcId)
}
nodeRepl :: FilePath -> FilePath -> Proc.CreateProcess
nodeRepl nodeExePath rtsPath =
(Proc.proc nodeExePath ["--harmony-tailcalls"])
{ Proc.env = Just [("NODE_PATH", rtsPath)]
}
withProcess ::
Proc.CreateProcess ->
((Maybe Handle, Maybe Handle, Maybe Handle, Proc.ProcessHandle) -> IO a) ->
IO a
withProcess createProc =
E.bracket
(Proc.createProcess createProc
{ Proc.std_in = Proc.CreatePipe
, Proc.std_out = Proc.CreatePipe
})
close
where
close (_, mStdout, mStderr, handle) =
do
_ <- [mStdout, mStderr] & Lens.traverse . Lens.traverse %%~ hClose
Proc.terminateProcess handle
parseHexBs :: String -> SBS.ByteString
parseHexBs =
SBS.pack . map (fst . sHead . readHex) . chunksOf 2
where
sHead [] = error "parseHexBs got bad input"
sHead (x:_) = x
parseHexNameBs :: String -> SBS.ByteString
parseHexNameBs ('_':n) = parseHexBs n
parseHexNameBs n = parseHexBs n
parseUUID :: String -> UUID
parseUUID = UUIDUtils.fromSBS16 . parseHexNameBs
parseRecord :: HashMap Text Json.Value -> ER.Val ()
parseRecord obj =
HashMap.toList obj & foldl step (ER.Val () ER.RRecEmpty)
where
step r (k, v) =
ER.RRecExtend V.RecExtend
{ V._recTag = Text.unpack k & parseHexNameBs & Identifier & Tag
, V._recFieldVal = parseResult v
, V._recRest = r
} & ER.Val ()
parseWord8 :: Json.Value -> Word8
parseWord8 (Json.Number x)
| x == fromIntegral i = i
where
i = truncate x
parseWord8 x = error $ "Expected word8, given: " ++ show x
parseBytes :: Json.Value -> ER.Val ()
parseBytes (Json.Array vals) =
Vec.toList vals
<&> parseWord8
& SBS.pack & PrimVal.Bytes & PrimVal.fromKnown & ER.RPrimVal & ER.Val ()
parseBytes _ = error "Bytes with non-array data"
parseInject :: String -> Maybe Json.Value -> ER.Val ()
parseInject tag mData =
ER.RInject V.Inject
{ V._injectTag = parseHexNameBs tag & Identifier & Tag
, V._injectVal =
case mData of
Nothing -> ER.Val () ER.RRecEmpty
Just v -> parseResult v
} & ER.Val ()
parseResult :: Json.Value -> ER.Val ()
parseResult (Json.Number x) =
realToFrac x & PrimVal.Float & PrimVal.fromKnown & ER.RPrimVal & ER.Val ()
parseResult (Json.Object obj) =
case Json.parseMaybe (.: "tag") obj of
Nothing -> parseRecord obj
Just tag
| tag == "bytes" ->
fromMaybe (error "bytes with no data?!") dataField & parseBytes
| tag == "function" -> ER.Val () ER.RFunc
| otherwise -> parseInject tag dataField
where
dataField = Json.parseMaybe (.: "data") obj
parseResult (Json.Array arr) =
Vec.toList arr <&> parseResult & ER.RArray & ER.Val ()
parseResult x = error $ "Unsupported encoded JS output: " ++ show x
addVal ::
Ord srcId =>
(UUID -> srcId) -> Json.Object ->
Map srcId (Map ScopeId (ER.Val ())) ->
Map srcId (Map ScopeId (ER.Val ()))
addVal fromUUID obj =
case Json.parseMaybe (.: "result") obj of
Nothing -> id
Just result ->
Map.alter
(<> Just (Map.singleton (ScopeId scope) (parseResult result)))
(fromUUID (parseUUID exprId))
where
Just scope = Json.parseMaybe (.: "scope") obj
Just exprId = Json.parseMaybe (.: "exprId") obj
newScope ::
Ord srcId =>
(UUID -> srcId) -> Json.Object ->
Map srcId (Map ScopeId [(ScopeId, ER.Val ())]) ->
Map srcId (Map ScopeId [(ScopeId, ER.Val ())])
newScope fromUUID obj =
Map.alter addApply (fromUUID (parseUUID lamId))
where
addApply Nothing = Just apply
addApply (Just x) = Just (Map.unionWith (++) x apply)
apply = Map.singleton (ScopeId parentScope) [(ScopeId scope, arg)]
Just parentScope = Json.parseMaybe (.: "parentScope") obj
Just scope = Json.parseMaybe (.: "scope") obj
Just lamId = Json.parseMaybe (.: "lamId") obj
arg =
case Json.parseMaybe (.: "arg") obj of
Nothing -> error "Scope report missing arg"
Just x -> parseResult x
processEvent ::
Ord srcId => (UUID -> srcId) -> IORef (EvalResults srcId) -> Json.Object -> IO ()
processEvent fromUUID resultsRef obj =
case event of
"Result" ->
atomicModifyIORef' resultsRef
(flip (,) () . (ER.erExprValues %~ addVal fromUUID obj))
"NewScope" ->
atomicModifyIORef' resultsRef
(flip (,) () . (ER.erAppliesOfLam %~ newScope fromUUID obj))
_ -> "Unknown event " ++ event & putStrLn
where
Just event = Json.parseMaybe (.: "event") obj
withCopyJSOutputTo :: Maybe FilePath -> ((String -> IO ()) -> IO a) -> IO a
withCopyJSOutputTo Nothing f = f $ \_js -> return ()
withCopyJSOutputTo (Just path) f =
withFile path WriteMode $ \outputFile -> f (hPutStrLn outputFile)
asyncStart ::
Ord srcId =>
(srcId -> UUID) -> (UUID -> srcId) ->
MVar (Dependencies srcId) -> IORef (EvalResults srcId) ->
Val srcId -> Actions srcId ->
IO ()
asyncStart toUUID fromUUID depsMVar resultsRef val actions =
do
nodeExePath <- NodeJS.path
rtsPath <- DataFile.getPath "js/rts.js" <&> fst . splitFileName
withProcess (nodeRepl nodeExePath rtsPath) $
\(Just stdin, Just stdout, Nothing, handle) ->
withCopyJSOutputTo (actions ^. aCopyJSOutputPath) $ \copyJSOutput ->
do
val
<&> valId
& Compiler.compile Compiler.Actions
{ Compiler.readAssocName = return . Char8.unpack . Hex.encode . UUIDUtils.toSBS16
, Compiler.readGlobal =
\globalId ->
modifyMVar depsMVar $ \oldDeps ->
do
-- This happens inside the modifyMVar so
-- loads are under "lock" and not racy
defBody <- globalId & actions ^. aLoadGlobal
return
( oldDeps <> Dependencies
{ subExprDeps = defBody ^.. Lens.folded . Lens.folded & Set.fromList
, globalDeps = Set.singleton globalId
}
, defBody <&> fmap valId
)
, Compiler.output =
\line ->
do
copyJSOutput line
hPutStrLn stdin line
, Compiler.loggingMode = Compiler.loggingEnabled
}
hClose stdin
let
processLines =
do
isEof <- hIsEOF stdout
unless isEof $
do
line <- SBS.hGetLine stdout
let Just obj = JsonStr.decode (LBS.fromChunks [line])
processEvent fromUUID resultsRef obj
actions ^. aReportUpdatesAvailable
processLines
processLines
_ <- Proc.waitForProcess handle
return ()
where
valId = Compiler.ValId . toUUID
-- | Pause the evaluator, yielding all dependencies of evaluation so
-- far. If any dependency changed, this evaluation is stale.
--
-- Pause must be called for a started/resumed evaluator, and if given
-- an already paused evaluator, will wait for its resumption.
whilePaused :: Evaluator srcId -> (Dependencies srcId -> IO a) -> IO a
whilePaused = withMVar . eDeps
start ::
Ord srcId => (srcId -> UUID) -> (UUID -> srcId) ->
Actions srcId -> Val srcId -> IO (Evaluator srcId)
start toUUID fromUUID actions val =
do
depsMVar <-
newMVar Dependencies
{ globalDeps = Set.empty
, subExprDeps = val ^.. Lens.folded & Set.fromList
}
resultsRef <- newIORef ER.empty
tid <- asyncStart toUUID fromUUID depsMVar resultsRef val actions & forkIO
return Evaluator
{ stop = killThread tid
, eDeps = depsMVar
, eResultsRef = resultsRef
}
getResults :: Evaluator srcId -> IO (EvalResults srcId)
getResults = readIORef . eResultsRef
|
da-x/lamdu
|
Lamdu/Eval/JS.hs
|
gpl-3.0
| 11,624
| 0
| 30
| 3,558
| 3,341
| 1,768
| 1,573
| -1
| -1
|
module FA2Exp
( etnfa2exp
, tnfa2exp
, foldnonrec
)
where
import Set
import FiniteMap
import Stuff
import Options
import TA
import FAtypes
import FAconv
import FA
import Ids
import Syntax
tnfa2exp :: (Show a, Ord a) => Opts -> TNFA a -> Exp
tnfa2exp opts = etnfa2exp opts . tnfa2etnfa opts
-----------------------------------------------------------------------
etnfa2exp :: (Ord a, Show a) => Opts -> ETNFA a -> Exp
etnfa2exp opts (ETNFA cons all starts moves eps) =
let
-- todo: this neither nice nor correct nor in the right place
-- (the user might have overridden the latex format entry)
plus = head [ id | (id, _) <- fids, idname id == "++" ]
expset [] = Coll CSet []
expset [x] = x
expset xs = foldl1 (\ x y -> App plus [x, y]) xs
leadsto = head [ id | (id, _) <- fids, idname id == "->" ]
eall = mapSet var2id all
estarts = expset (map var2exp (setToList starts))
emoves = [ ( var2exp x
, expset ( map sterm2exp (setToList ts)
++ map var2exp (setToList (lookupset eps x))) )
| (x, ts) <- fmToList moves
]
(cstarts, cmoves) =
(chose opts "foldnonrec" (foldnonrec eall) id) $
(chose opts "foldconst" (foldconst eall) id) $
(estarts, emoves)
in if (null cmoves && onoff opts "hidegrammar")
then cstarts
else
App (userfun 2 "grammar") -- todo: wrong place
[ cstarts
, Coll CSet [ App leadsto [ x, y ]
| (x, y) <- cmoves ]
]
---------------------------------------------------------------------------
varset r = mkSet (appids r)
varsets xrs = unionManySets [ varset r | (x, r) <- xrs ]
substMoves name val moves =
[ (x, substExp name val r) | (x, r) <- moves ]
foldconst vars (starts, moves) =
fixpoint (\ (starts, moves) ->
case [ (x, r) | (x, r) <- moves
, isEmptySet (varset r `intersectSet` vars)
] of
[] -> (starts, moves)
(x, r) : _ ->
-- trace ("\nfoldconst " ++ show x ++ " => " ++ show r) $
( substExp x r starts
, substMoves x r [ (y, s) | (y, s) <- moves, y /= x ] ) )
(starts, moves)
------------------------------------------------------------------------
foldnonrec vars (starts, moves) =
fixpoint (\ (starts, moves) ->
case [ (x, r) | (x, r) <- moves
, not (unAppId x `elementOf` varset r)
] of
[] -> (starts, moves)
(x, r) : _ ->
-- trace ("\nfoldnonrec " ++ show x ++ " => " ++ show r) $
( substExp x r starts
, substMoves x r [ (y, s) | (y, s) <- moves, y /= x ] ) )
(starts, moves)
|
jwaldmann/rx
|
src/FA2Exp.hs
|
gpl-3.0
| 2,490
| 49
| 18
| 624
| 1,018
| 552
| 466
| 62
| 4
|
----------------------------------------------------------------------------
-- |
-- Module : $Header$
-- Copyright : (c) Proyecto Theona, 2012-2013
-- (c) Alejandro Gadea, Emmanuel Gunther, Miguel Pagano
-- License : <license>
--
-- Maintainer : miguel.pagano+theona@gmail.com
-- Stability : experimental
-- Portability : portable
--
--
--
----------------------------------------------------------------------------
{-# Language OverloadedStrings #-}
module Fun.FunTheories.FOL(
folTheory
, bool
) where
import qualified Equ.Theories.FOL as EquFOL
import qualified Equ.Theories as EquTh
import Equ.PreExpr
import Equ.Proof (Theorem,Axiom)
import Equ.Types
import Equ.IndTypes (bool)
import Fun.Theory
import Fun.Decl
{- Lógica -}
varP,varQ :: Variable
varP = var "p" (TyAtom ATyBool)
varQ = var "q" (TyAtom ATyBool)
{- or p q = case p of
False -> q
True -> True
-}
folOrExpr :: PreExpr
folOrExpr = Case (Var varP)
[ (Con EquFOL.folFalse, Var varQ)
, (Con EquFOL.folTrue,Con EquFOL.folTrue)
]
folOr :: OpDecl
folOr = OpDecl EquFOL.folOr [varP,varQ] folOrExpr
{- and p q = case n of
False -> Flase
True -> q
-}
folAndExpr :: PreExpr
folAndExpr = Case (Var varP) [ (Con EquFOL.folFalse, Con EquFOL.folFalse)
, (Con EquFOL.folTrue,Con EquFOL.folTrue)
]
folAnd :: OpDecl
folAnd = OpDecl EquFOL.folAnd [varP,varQ] folAndExpr
boolQuantifiers :: [Quantifier]
boolQuantifiers = EquFOL.theoryQuantifiersList
boolAxioms :: [Axiom]
boolAxioms = EquTh.axiomList
boolTheorems :: [Theorem]
boolTheorems = []
folTheory :: Theory
folTheory = Theory {
tname = "Lógica"
, indType = [bool]
, operators = [folOr, folAnd]
, quantifiers = boolQuantifiers
, axioms = boolAxioms
, theorytheorems = boolTheorems
}
|
alexgadea/fun
|
Fun/FunTheories/FOL.hs
|
gpl-3.0
| 2,039
| 0
| 9
| 577
| 400
| 241
| 159
| 40
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.