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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Paths_BottleStory (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName
) where
import Data.Version (Version(..))
import System.Environment (getEnv)
version :: Version
version = Version {versionBranch = [0,0,0], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath
bindir = "/Users/hiromi/Documents/Programming/haskell/yesod/BottleStory/cabal-dev//bin"
libdir = "/Users/hiromi/Documents/Programming/haskell/yesod/BottleStory/cabal-dev//lib/BottleStory-0.0.0/ghc-7.0.3"
datadir = "/Users/hiromi/Documents/Programming/haskell/yesod/BottleStory/cabal-dev//share/BottleStory-0.0.0"
libexecdir = "/Users/hiromi/Documents/Programming/haskell/yesod/BottleStory/cabal-dev//libexec"
getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catch (getEnv "BottleStory_bindir") (\_ -> return bindir)
getLibDir = catch (getEnv "BottleStory_libdir") (\_ -> return libdir)
getDataDir = catch (getEnv "BottleStory_datadir") (\_ -> return datadir)
getLibexecDir = catch (getEnv "BottleStory_libexecdir") (\_ -> return libexecdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| konn/BottleStory | dist/build/autogen/Paths_BottleStory.hs | bsd-2-clause | 1,224 | 0 | 10 | 144 | 280 | 161 | 119 | 22 | 1 |
{-|
Module : Database.Relational.Alter
Description : Definition of ALTER.
Copyright : (c) Alexander Vieth, 2015
Licence : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE AutoDeriveTypeable #-}
module Database.Relational.Alter (
ALTER(..)
) where
data ALTER term alteration = ALTER term alteration
| avieth/Relational | Database/Relational/Alter.hs | bsd-3-clause | 393 | 0 | 6 | 77 | 31 | 21 | 10 | 4 | 0 |
{-|
Module : Game.GoreAndAsh.LambdaCube.Module
Description : Internal implementation of public API of lambda cube game module
Copyright : (c) Anton Gushcha, 2016-2017
Anatoly Nardid, 2016-2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
The module defines implementation of lambda cube game module. You are
interested only in a 'LambdaCubeT' and 'LambdaCubeOptions' types as 'LambdaCubeT'
should be placed in your monad stack to enable 'MonadLambdaCube' API in your
application.
@
type AppStack t = LambdaCubeT t (LoggingT t (TimerT t (GameMonad t)))
newtype AppMonad t a = AppMonad { runAppMonad :: AppStack t a}
deriving (Functor, Applicative, Monad, MonadFix)
@
And you will need some boilerplate code for instance deriving, see
`examples/Example01.hs` for full example.
-}
module Game.GoreAndAsh.LambdaCube.Module(
LambdaCubeOptions(..)
, LambdaCubeT(..)
) where
import Control.Monad.Base
import Control.Monad.Catch
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Control
import Data.IORef
import Data.Map.Strict (Map)
import Data.Monoid
import Data.Proxy
import Data.Sequence (Seq)
import Data.Text (Text)
import LambdaCube.Compiler as LambdaCube
import LambdaCube.GL as LambdaCubeGL
import qualified Data.Map.Strict as M
import qualified Data.Sequence as S
import qualified Data.Text as T
import Game.GoreAndAsh
import Game.GoreAndAsh.LambdaCube.API
-- | Helper to show values in 'Text'
showt :: Show a => a -> Text
showt = T.pack . show
-- | Options that are passed to 'runModule' at application startup.
--
-- [@s@] The nested options of next module in stack. Options are layered the
-- similar way as parts of monad transformers.
data LambdaCubeOptions s = LambdaCubeOptions {
lambdaOptsNext :: s -- ^ Nested options of next game module
}
-- | All info about a LambdaCube pipeline
data PipelineInfo = PipelineInfo {
pipeInfoRenderer :: !GLRenderer
, pipeInfoSchema :: !PipelineSchema
, pipeInfoPipeline :: !Pipeline
}
-- | Internal environment of game module
data LambdaCubeEnv t = LambdaCubeEnv {
-- | Options that were used to create the module.
lambdaEnvOptions :: !(LambdaCubeOptions ())
-- | Holds known pipelines.
, lambdaEnvPipelines :: !(IORef (Map PipelineId PipelineInfo))
-- | Holds known storages and next free id for a new storage
, lambdaEnvStorages :: !(IORef (Int, Map StorageId GLStorage))
-- | Holds sequence of storages that are rendered to screen
, lambdaEnvRenderOrder :: !(IORef (Seq StorageId))
}
-- | Create a new environment for game module
newLambdaCubeEnv :: MonadAppHost t m => LambdaCubeOptions s -> m (LambdaCubeEnv t)
newLambdaCubeEnv opts = do
pipelines <- liftIO $ newIORef mempty
storages <- liftIO $ newIORef (0, mempty)
order <- liftIO $ newIORef mempty
return LambdaCubeEnv {
lambdaEnvOptions = opts { lambdaOptsNext = () }
, lambdaEnvPipelines = pipelines
, lambdaEnvStorages = storages
, lambdaEnvRenderOrder = order
}
-- | Update viewport size of all storages
updateStateViewportSize :: Word -> Word -> LambdaCubeEnv t -> IO ()
updateStateViewportSize w h LambdaCubeEnv{..} = do
m <- snd <$> readIORef lambdaEnvStorages
mapM_ (\s -> LambdaCubeGL.setScreenSize s w h) m
-- | Returns True if given pipeline is already exists
isPipelineRegisteredInternal :: PipelineId -> LambdaCubeEnv t -> IO Bool
isPipelineRegisteredInternal pid LambdaCubeEnv{..} = do
m <- readIORef lambdaEnvPipelines
case M.lookup pid m of
Nothing -> return False
Just _ -> return True
-- | Register new pipeline with renderer in module
registerPipelineInternal :: PipelineId -> Pipeline -> PipelineSchema -> GLRenderer -> LambdaCubeEnv t -> IO ()
registerPipelineInternal i ps pl r LambdaCubeEnv{..} = do
atomicModifyIORef' lambdaEnvPipelines $ (, ()) . M.insert i info
where
info = PipelineInfo {
pipeInfoRenderer = r
, pipeInfoSchema = pl
, pipeInfoPipeline = ps
}
-- | Removes pipeline from state and deletes it, also destroys all storages of the pipeline
unregisterPipelineInternal :: PipelineId -> LambdaCubeEnv t -> IO ()
unregisterPipelineInternal i LambdaCubeEnv{..} = do
pipelines <- readIORef lambdaEnvPipelines
case M.lookup i pipelines of
Nothing -> return ()
Just PipelineInfo{..} -> do
storages <- snd <$> readIORef lambdaEnvStorages
let storagesToDispose = M.filterWithKey (\k _ -> isPipelineStorage i k) storages
mapM_ LambdaCubeGL.disposeStorage $ storagesToDispose
LambdaCubeGL.disposeRenderer pipeInfoRenderer
atomicModifyIORef' lambdaEnvPipelines $ (, ()) . M.delete i
atomicModifyIORef' lambdaEnvStorages $ \(n, m) -> ((n, M.filterWithKey (\k _ -> not $ isPipelineStorage i k) m), ())
-- | Getter of pipeline scheme
getPipelineSchemeInternal :: PipelineId -> LambdaCubeEnv t -> IO (Maybe PipelineSchema)
getPipelineSchemeInternal i LambdaCubeEnv{..} = fmap pipeInfoSchema . M.lookup i <$> readIORef lambdaEnvPipelines
-- | Registering gl storage for given pipeline
registerStorageInternal :: PipelineId -> GLStorage -> LambdaCubeEnv t -> IO StorageId
registerStorageInternal pid storage LambdaCubeEnv{..} = do
let mkId n = StorageId {
storageId = n
, storageScheme = pid
}
atomicModifyIORef lambdaEnvStorages $ \(i, m) -> let i' = mkId i
in ((i + 1, M.insert i' storage m), i')
-- | Remove and deallocate storage
unregisterStorageInternal :: StorageId -> LambdaCubeEnv t -> IO ()
unregisterStorageInternal i LambdaCubeEnv{..} = do
m <- snd <$> readIORef lambdaEnvStorages
case M.lookup i m of
Nothing -> return ()
Just storage -> do
LambdaCubeGL.disposeStorage storage
atomicModifyIORef lambdaEnvStorages $ \(n, storages) -> ((n, M.delete i storages), ())
getRendererInternal :: PipelineId -> LambdaCubeEnv t -> IO (Maybe GLRenderer)
getRendererInternal i LambdaCubeEnv{..} = fmap pipeInfoRenderer . M.lookup i <$> readIORef lambdaEnvPipelines
-- | Find storage in state
getStorageInternal :: StorageId -> LambdaCubeEnv t -> IO (Maybe GLStorage)
getStorageInternal i LambdaCubeEnv{..} = M.lookup i . snd <$> readIORef lambdaEnvStorages
-- | Puts storage at end of rendering queue
renderStorageLastInternal :: StorageId -> LambdaCubeEnv t -> IO ()
renderStorageLastInternal i LambdaCubeEnv{..} = atomicModifyIORef lambdaEnvRenderOrder $ \m ->
(, ()) $ S.filter (/= i) m S.|> i
-- | Puts storage at begining of rendering queue
renderStorageFirstInternal :: StorageId -> LambdaCubeEnv t -> IO ()
renderStorageFirstInternal i LambdaCubeEnv{..} = atomicModifyIORef lambdaEnvRenderOrder $ \m ->
(, ()) $ i S.<| S.filter (/= i) m
-- | Removes storage from rendering queue
stopRenderingInternal :: StorageId -> LambdaCubeEnv t -> IO ()
stopRenderingInternal i LambdaCubeEnv{..} = atomicModifyIORef lambdaEnvRenderOrder $ \m ->
(, ()) $ S.filter (/= i) m
-- | Render all queued storages
renderStorages :: LambdaCubeEnv t -> IO ()
renderStorages e@LambdaCubeEnv{..} = do
renderings <- readIORef lambdaEnvRenderOrder
mapM_ renderStorage renderings
where
renderStorage si = do
ms <- getStorageInternal si e
case ms of
Nothing -> return ()
Just storage -> do
mr <- getRendererInternal (storageScheme si) e
case mr of
Nothing -> return ()
Just renderer -> do
mres <- liftIO $ LambdaCubeGL.setStorage renderer storage
case mres of
Just er -> throwM $! PipeLineIncompatible si (T.pack er)
Nothing -> liftIO $ LambdaCubeGL.renderFrame renderer
-- | Implementation of 'MonadLambdaCube' API.
--
-- [@t@] FRP engine, you could ignore this parameter as it resolved only at main
-- function of your application.
--
-- [@m@] Underlying game modules, next layer in monad stack.
--
-- [@a@] Result of computation.
--
-- How to embed the monad into your app:
--
-- @
-- type AppStack t = LambdaCubeT t (LoggingT t (TimerT t (GameMonad t)))
--
-- newtype AppMonad t a = AppMonad { runAppMonad :: AppStack t a}
-- deriving (Functor, Applicative, Monad, MonadFix)
-- @
--
-- And you will need some boilerplate code for instance deriving, see
-- `examples/Example01.hs` for full example.
--
newtype LambdaCubeT t m a = LambdaCubeT { runLambdaCubeT :: ReaderT (LambdaCubeEnv t) m a }
deriving (Functor, Applicative, Monad, MonadReader (LambdaCubeEnv t), MonadFix
, MonadIO, MonadThrow, MonadCatch, MonadMask, MonadSample t, MonadHold t)
instance {-# OVERLAPPING #-} (MonadAppHost t m, MonadThrow m) => MonadLambdaCube t (LambdaCubeT t m) where
lambdacubeUpdateSize !w !h = do
s <- ask
liftIO $ updateStateViewportSize w h s
{-# INLINE lambdacubeUpdateSize #-}
lambdacubeGetSizeUpdater = return . (\s w h -> updateStateViewportSize w h s) =<< ask
{-# INLINE lambdacubeGetSizeUpdater #-}
lambdacubeAddPipeline !ps !mn !pid !pwr = do
s <- ask
isRegistered <- liftIO $ isPipelineRegisteredInternal pid s
when isRegistered . throwM . PipeLineAlreadyRegistered $! pid
mpd <- liftIO $ LambdaCube.compileMain ps OpenGL33 (T.unpack mn)
case mpd of
Left err -> throwM . PipeLineCompileFailed mn pid $! "compile error:\n" <> showt err
Right pd -> do
let sch = makeSchema pwr
r <- liftIO $ LambdaCubeGL.allocRenderer pd
liftIO $ registerPipelineInternal pid pd sch r s
{-# INLINE lambdacubeAddPipeline #-}
lambdacubeDeletePipeline !i = do
s <- ask
liftIO $ unregisterPipelineInternal i s
{-# INLINE lambdacubeDeletePipeline #-}
lambdacubeCreateStorage !i = do
s <- ask
mscheme <- liftIO $ getPipelineSchemeInternal i s
case mscheme of
Nothing -> throwM . PipeLineNotFound $! i
Just sch -> liftIO $ do
storage <- LambdaCubeGL.allocStorage sch
si <- liftIO $ registerStorageInternal i storage s
return (si, storage)
{-# INLINE lambdacubeCreateStorage #-}
lambdacubeDeleteStorage !i = do
s <- ask
liftIO $ unregisterStorageInternal i s
{-# INLINE lambdacubeDeleteStorage #-}
lambdacubeGetStorage !si = do
s <- ask
ms <- liftIO $ getStorageInternal si s
case ms of
Nothing -> throwM . StorageNotFound $! si
Just storage -> return storage
{-# INLINE lambdacubeGetStorage #-}
lambdacubeRenderStorageLast !si = do
s <- ask
liftIO $ renderStorageLastInternal si s
{-# INLINE lambdacubeRenderStorageLast #-}
lambdacubeRenderStorageFirst !si = do
s <- ask
liftIO $ renderStorageFirstInternal si s
{-# INLINE lambdacubeRenderStorageFirst #-}
lambdacubeStopRendering !si = do
s <- ask
liftIO $ stopRenderingInternal si s
{-# INLINE lambdacubeStopRendering #-}
lambdacubeRender = liftIO . renderStorages =<< ask
{-# INLINE lambdacubeRender #-}
lambdacubeGetRenderer = return . renderStorages =<< ask
{-# INLINE lambdacubeGetRenderer #-}
-- Boilerplate
instance MonadTrans (LambdaCubeT t) where
lift = LambdaCubeT . lift
instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (LambdaCubeT t m) where
newEventWithTrigger = lift . newEventWithTrigger
newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer
instance MonadSubscribeEvent t m => MonadSubscribeEvent t (LambdaCubeT t m) where
subscribeEvent = lift . subscribeEvent
instance MonadAppHost t m => MonadAppHost t (LambdaCubeT t m) where
getFireAsync = lift getFireAsync
getRunAppHost = do
runner <- LambdaCubeT getRunAppHost
return $ \m -> runner $ runLambdaCubeT m
performPostBuild_ = lift . performPostBuild_
liftHostFrame = lift . liftHostFrame
instance MonadTransControl (LambdaCubeT t) where
type StT (LambdaCubeT t) a = StT (ReaderT (LambdaCubeEnv t)) a
liftWith = defaultLiftWith LambdaCubeT runLambdaCubeT
restoreT = defaultRestoreT LambdaCubeT
instance MonadBase b m => MonadBase b (LambdaCubeT t m) where
liftBase = LambdaCubeT . liftBase
instance (MonadBaseControl b m) => MonadBaseControl b (LambdaCubeT t m) where
type StM (LambdaCubeT t m) a = ComposeSt (LambdaCubeT t) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
instance (MonadIO (HostFrame t), GameModule t m) => GameModule t (LambdaCubeT t m) where
type ModuleOptions t (LambdaCubeT t m) = LambdaCubeOptions (ModuleOptions t m)
runModule opts (LambdaCubeT m) = do
s <- newLambdaCubeEnv opts
runModule (lambdaOptsNext opts) $ runReaderT m s
withModule t _ = withModule t (Proxy :: Proxy m)
| Teaspot-Studio/gore-and-ash-lambdacube | src/Game/GoreAndAsh/LambdaCube/Module.hs | bsd-3-clause | 12,602 | 0 | 26 | 2,446 | 3,109 | 1,574 | 1,535 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Trurl
import SimpleParams
import System.Environment
help :: IO ()
help = do
putStrLn "trurl <command> [parameters]"
putStrLn " update -- fetch the updates from repository"
putStrLn " new project <name> <project_template> [parameters] -- create project of specified type with specified name; optionally add parameters"
putStrLn " new project <name> <project_template> -j [parameters_string] -- create project of specified type with specified name; optionally add JSON parameters, wrap it with \"\" or ''"
putStrLn " new file <name> <file_template> [parameters] -- create file from the template with specified string parameters"
putStrLn " new file <name> <file_template> -j [parameters_string] -- create file from the template with specified JSON parameters, wrap it with \"\" or ''"
putStrLn " list -- print all available templates"
putStrLn " help <template> -- print template info"
putStrLn " help -- print this help"
putStrLn " version -- print version"
printVersion :: IO ()
printVersion = putStrLn "0.4.1.x"
main :: IO ()
main = do
args <- getArgs
case args of
[] -> help
["--help"] -> help
["-h"] -> help
["help"] -> help
["help", template] -> helpTemplate template
["update"] -> updateFromRepository
["new", "project", name, project] -> createProject name project "{}"
["new", "project", name, project, "-j", params] -> createProject name project params
["new", "project", name, project, params] -> createProject name project $ simpleParamsToJson params
["new", "file", name, template, "-j" ,params] -> newTemplate name template params
["new", "file", name, template, params] -> newTemplate name template $ simpleParamsToJson params
["list"] -> listTemplates
["version"] -> printVersion
["--version"] -> printVersion
["-v"] -> printVersion
_ -> putStrLn "Unknown command"
| dbushenko/trurl | src/Main.hs | bsd-3-clause | 2,292 | 0 | 11 | 715 | 395 | 204 | 191 | 39 | 16 |
module Builder(test2, test) where
import qualified Data.Sequence.Chunked.Builder as B
import Data.Sequence.Chunked
import Data.Monoid
import qualified Data.Vector.Unboxed as V
instance Unbox Double where
defaultChunkSize _ = 128
test :: Int -> Seq Int
test n = B.toSeq (stupidReplicate n 0)
stupidReplicate :: Int -> Int -> B.Builder Int
stupidReplicate n a = go n where
go 0 = mempty
go n = B.singleton a `mappend` go (n-1)
test2 :: Int -> Seq Int
test2 n = B.toSeq (B.singleton n `mappend` B.singleton n `mappend` B.singleton n)
{-# SPECIALISE snocChunk :: Seq Int -> V.Vector Int -> Seq Int #-}
| reinerp/chunked-sequence | examples/Builder.hs | bsd-3-clause | 612 | 0 | 10 | 111 | 217 | 118 | 99 | 16 | 2 |
import Process
import WhileParser
import qualified Data.Map.Strict as Map
import Text.Parsec (Parsec, runP)
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import Control.Monad.State.Lazy
import Control.Monad
import System.IO
showSymState :: SymState -> String
showSymState (s, _, fl) = "Active variables: " ++ (show s) ++ "Functions: " ++ (show (Map.keys fl))
addFunc :: SymState -> FuncDecl -> SymState
addFunc (s, t, fl) f = (s, t, (Map.insert (getFuncName f) f fl))
type IOState = (SymState, Int, Stmt)
runCycle :: IOState -> IO ()
runCycle (state, lineno, laststmt) = do
str <- getLine
let command = (drop 3 str)
case (take 2 str) of
":f" -> case parse functionDecl "" command of
Left e -> do {
putStrLn $ "Parsing Error: " ++ show(e);
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
Right r -> do {
putStrLn $ "Function will be added to current state";
putStr $ ((show lineno) ++ "> ");
runCycle (addFunc state r, lineno + 1, laststmt)
}
":i" -> case parse whileParser "" command of
Left e -> do {
putStrLn $ "Parsing Error: " ++ show(e);
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
Right r -> let newstate = execState (evalStmt r) state in
do {
putStrLn (showSymState newstate);
putStr $ ((show lineno) ++ "> ");
runCycle (newstate, lineno + 1, r)
}
":p" -> case parse expression "" command of
Left e -> do {
putStrLn $ "Parsing Error: " ++ show(e);
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
Right r -> let result = evalState (evalExpr r) state in
do {
putStrLn $ "Evaluation: " ++ (show result);
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
":t" -> do {
putStrLn $ show laststmt;
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
":q" -> return ()
otherwise -> do {
putStrLn $ "Unknown prefix - [" ++ (take 3 str) ++ "]";
putStr $ ((show lineno) ++ "> ");
runCycle (state, lineno + 1, laststmt)
}
repl :: IO ()
repl = do
putStrLn $ "You are now at REPL Mode. :f to define function, :i to execute code, :p to print variable to screen" ++
":q to quit, :t to print AST of last :i action."
putStr "> "
runCycle (nullSymState, 1, Skip)
| PiffNP/HaskellProject | src/REPL.hs | bsd-3-clause | 5,224 | 0 | 21 | 3,362 | 956 | 504 | 452 | 64 | 9 |
{-- The newtype keyword
The value constructor of a newtype must have exactly one field, and only one value constructor
The newtype keyword in Haskell is made exactly for these cases when we want to just take one type and wrap it in something to present it as another type. In the actual libraries,
ZipList a is defined like this:
newtype ZipList a = ZipList { getZipList :: [a] }
If you use the data keyword to wrap a type, there's some overhead to all that wrapping and unwrapping when your program is running.
But if you use newtype, Haskell knows that you're just using it to wrap an existing type into a new type (hence the name), because you want it to be the same internally but have a different type.
With that in mind, Haskell can get rid of the wrapping and unwrapping once it resolves which value is of what type.
We can also use the deriving keyword with newtype just like we would with data. Because newtype just wraps an existing type.
newtype CharList = CharList { getCharList :: [Char] } deriving (Eq, Show)
In this particular newtype, the value constructor CharList (rihght side of equation) has the following type:
CharList :: [Char] -> CharList
Conversely, the getCharList function, which was generated for us because we used record syntax in our newtype, has this type:
getCharList :: CharList -> [Char]
--}
-- data Person = Person String String Int Float String String deriving (Show)
-- :t Person
-- Person :: String -> String -> Int -> Float -> String -> String -> Person
-- :t firstName
-- firstName :: Person -> String
-- syntax sugar like:
-- firstName :: Person -> String
-- firstName (Person firstname _ _ _ _ _) = firstname
-- phoneNumber :: Person -> String
-- phoneNumber (Person _ _ _ _ number _) = number
-- syntax sugar as:
data Person = Person { firstName :: String
, lastName :: String
, age :: Int
, height :: Float
, phoneNumber :: String
, flavor :: String
} deriving (Show)
{--
With Maybe, we just say instance Functor Maybe where because only type constructors that take exactly one parameter can be made an instance of Functor.
But it seems like there's no way to do something like that with (a,b) so that the type parameter a ends up being the one that changes when we use fmap.
To get around this, we can newtype our tuple in such a way that the second type parameter represents the type of the first component in the tuple:
newtype Pair b a = Pair { getPair :: (a,b) }
:t Pair
Pair :: (a, b) -> Pair b a
instance Functor (Pair c) where
fmap f (Pair (x,y)) = Pair (f x, y)
We pattern match to get the underlying tuple, then we apply the function f to the first component in the tuple and then we use the Pair value constructor to convert the tuple back to our Pair b a.
If we imagine what the type fmap would be if it only worked on our new pairs, it would be:
fmap :: (a -> b) -> Pair c a -> Pair c b
So now, if we convert a tuple into a Pair b a, we can use fmap over it and the function will be mapped over the first component:
ghci> getPair $ fmap (*100) (Pair (2,3))
(200,3)
-- ONLY FIRST ELEM IS FMAPPED
ghci> getPair $ fmap reverse (Pair ("london calling", 3))
("gnillac nodnol",3)
--}
{--
Haskell can represent the values of types defined with newtype just like the original ones, only it has to keep in mind that the their types are now distinct.
This fact means that not only is newtype faster, it's also lazier. Let's take a look at what this means.
The undefined value in Haskell represents an erronous computation. If we try to evaluate it (that is, force Haskell to actually compute it) by printing it to the terminal, Haskell will throw an exception
However, if we make a list that has some undefined values in it but request only the head of the list, which is not undefined, everything will go smoothly because Haskell doesn't really need to evaluate any other elements in a list if we only want to see what the first element is:
head [3,4,5,undefined,2,undefined]
--}
{--
Let's make a function that pattern matches on a CoolBool and returns the value "hello" regardless of whether the Bool inside the CoolBool was True or False:
helloMe :: CoolBool -> String
helloMe (CoolBool _) = "hello"
ghci> helloMe undefined
"*** Exception: Prelude.undefined
Types defined with the data keyword can have "multiple value constructors" (even though CoolBool only has one).
So in order to see if the value given to our function conforms to the (CoolBool _) pattern, Haskell has to evaluate the value just enough to see which value constructor was used when we made the value.
And when we try to evaluate an undefined value, even a little, an exception is thrown.
newtype CoolBool = CoolBool { getCoolBool :: Bool }
ghci> helloMe undefined
"hello"
when we use newtype, Haskell can internally represent the values of the new type in the same way as the original values.
It doesn't have to add another box around them, it just has to be aware of the values being of different types.
And because Haskell knows that types made with the newtype keyword can only have one constructor, it doesn't have to evaluate the value passed to the function to make sure that it conforms to the (CoolBool _) pattern because newtype types can only have one possible value constructor and one field!
--}
{-- type vs. newtype vs. data
The type keyword is for making type synonyms.
type IntList = [Int]
All this does is to allow us to refer to the [Int] type as IntList.
They can be used interchangeably. We don't get an IntList value constructor or anything like that.
The newtype keyword is for taking existing types and wrapping them in new types, mostly so that it's easier to make them instances of certain type classes.
newtype CharList = CharList { getCharList :: [Char] }
We can't use ++ to put together a CharList and a list of type [Char]. We can't even use ++ to put together two CharLists, because ++ works only on lists and the CharList type isn't a list, even though it could be said that it contains one. We can, however, convert two CharLists to lists, ++ them and then convert that back to a CharList.
When we use record syntax in our newtype declarations, we get functions for converting between the new type and the original type: namely the value constructor of our newtype and the function for extracting the value in its field.
The new type also isn't automatically made an instance of the type classes that the original type belongs to, so we have to derive or manually write them.
In practice, you can think of newtype declarations as data declarations that can only have one constructor and one field.
If you catch yourself writing such a data declaration, consider using newtype.
--}
| jamesyang124/haskell-playground | src/Chp112.hs | bsd-3-clause | 6,836 | 0 | 8 | 1,412 | 69 | 49 | 20 | 7 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Lens hiding (elements)
import qualified Data.Binary as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import Data.Int
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import Network.Kafka
import Network.Kafka.Exports
import Network.Kafka.Fields
import Network.Kafka.Producer
import Network.Kafka.Protocol
import Network.Kafka.Primitive.GroupCoordinator
import Network.Kafka.Primitive.Fetch
import Network.Kafka.Primitive.Metadata
import Network.Kafka.Primitive.Offset
import Network.Kafka.Primitive.OffsetCommit
import Network.Kafka.Primitive.OffsetFetch
import Network.Kafka.Primitive.Produce
import Network.Kafka.Types
-- import Network.Kafka.Arbitrary
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import Test.QuickCheck.Arbitrary
import Test.QuickCheck.Gen
import ConnectionTests
instance Arbitrary ErrorCode where
arbitrary = Test.QuickCheck.Gen.elements
[ NoError
, Unknown
, OffsetOutOfRange
, CorruptMessage
, UnknownTopicOrPartition
, InvalidMessageSize
, LeaderNotAvailable
, NotLeaderForPartition
, RequestTimedOut
, BrokerNotAvailable
, ReplicaNotAvailable
, MessageSizeTooLarge
, StaleControllerEpoch
, OffsetMetadataTooLarge
, GroupLoadInProgress
, GroupCoordinatorNotAvailable
, NotCoordinatorForGroup
, InvalidTopic
, RecordListTooLarge
, NotEnoughReplicas
, NotEnoughReplicasAfterAppend
, InvalidRequiredAcks
, IllegalGeneration
, InconsistentGroupProtocol
, InvalidGroupId
, UnknownMemberId
, InvalidSessionTimeout
, RebalanceInProgress
, InvalidCommitOffsetSize
, TopicAuthorizationFailed
, GroupAuthorizationFailed
, ClusterAuthorizationFailed
]
instance Arbitrary Utf8 where
arbitrary = (Utf8 . T.encodeUtf8 . T.pack) <$> listOf arbitrary
instance Arbitrary CoordinatorId where
arbitrary = CoordinatorId <$> arbitrary
instance Arbitrary NodeId where
arbitrary = NodeId <$> arbitrary
instance Arbitrary ConsumerId where
arbitrary = ConsumerId <$> arbitrary
instance Arbitrary GenerationId where
arbitrary = GenerationId <$> arbitrary
instance Arbitrary GroupCoordinatorRequestV0 where
arbitrary = GroupCoordinatorRequestV0 <$> arbitrary
instance Arbitrary GroupCoordinatorResponseV0 where
arbitrary = GroupCoordinatorResponseV0 <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary FetchRequestV0 where
arbitrary = FetchRequestV0 <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary FetchResponseV0 where
arbitrary = FetchResponseV0 <$>
arbitrary
instance Arbitrary TopicFetch where
arbitrary = TopicFetch <$>
arbitrary <*>
arbitrary
instance Arbitrary PartitionFetch where
arbitrary = PartitionFetch <$>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary FetchResult where
arbitrary = FetchResult <$>
arbitrary <*>
arbitrary
instance Arbitrary FetchResultPartitionResults where
arbitrary = FetchResultPartitionResults <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary MessageSetItem where
arbitrary = MessageSetItem <$> arbitrary <*> arbitrary
uncompressedMessageGen :: Gen MessageSetItem
uncompressedMessageGen = MessageSetItem <$> arbitrary <*> (Message (Attributes NoCompression) <$> arbitrary <*> arbitrary)
instance Arbitrary Message where
arbitrary = do
attrs@(Attributes codec) <- arbitrary
case codec of
NoCompression -> Message attrs <$> arbitrary <*> arbitrary
GZip -> gzippedMessage <$> listOf uncompressedMessageGen
Snappy -> error "Not supported yet"
instance Arbitrary Attributes where
arbitrary = Attributes <$> arbitrary
instance Arbitrary CompressionCodec where
-- TODO, support snappy
arbitrary = elements [NoCompression, GZip {-, Snappy -}]
instance Arbitrary a => Arbitrary (V.Vector a) where
arbitrary = V.fromList <$> listOf arbitrary
instance Arbitrary PartitionId where
arbitrary = PartitionId <$> arbitrary
instance Arbitrary Bytes where
arbitrary = (Bytes . BL.pack) <$> listOf arbitrary
instance Arbitrary MetadataRequestV0 where
arbitrary = MetadataRequestV0 <$> arbitrary
instance Arbitrary MetadataResponseV0 where
arbitrary = MetadataResponseV0 <$> arbitrary <*> arbitrary
instance Arbitrary Broker where
arbitrary = Broker <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary TopicMetadata where
arbitrary = TopicMetadata <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary PartitionMetadata where
arbitrary = PartitionMetadata <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary OffsetRequestV0 where
arbitrary = OffsetRequestV0 <$>
arbitrary <*>
arbitrary
instance Arbitrary OffsetResponseV0 where
arbitrary = OffsetResponseV0 <$> arbitrary
instance Arbitrary TopicPartition where
arbitrary = TopicPartition <$> arbitrary <*> arbitrary
instance Arbitrary PartitionOffsetRequestInfo where
arbitrary = PartitionOffsetRequestInfo <$>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary PartitionOffsetResponseInfo where
arbitrary = PartitionOffsetResponseInfo <$>
arbitrary <*>
arbitrary
instance Arbitrary PartitionOffset where
arbitrary = PartitionOffset <$>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary OffsetCommitRequestV0 where
arbitrary = OffsetCommitRequestV0 <$>
arbitrary <*>
arbitrary
instance Arbitrary OffsetCommitResponseV0 where
arbitrary = OffsetCommitResponseV0 <$> arbitrary
instance Arbitrary OffsetCommitRequestV1 where
arbitrary = OffsetCommitRequestV1 <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary OffsetCommitResponseV1 where
arbitrary = OffsetCommitResponseV1 <$> arbitrary
instance Arbitrary OffsetCommitRequestV2 where
arbitrary = OffsetCommitRequestV2 <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary OffsetCommitResponseV2 where
arbitrary = OffsetCommitResponseV2 <$> arbitrary
instance Arbitrary CommitV0 where
arbitrary = CommitV0 <$> arbitrary <*> arbitrary
instance Arbitrary CommitPartitionV0 where
arbitrary = CommitPartitionV0 <$>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary CommitV1 where
arbitrary = CommitV1 <$> arbitrary <*> arbitrary
instance Arbitrary CommitV2 where
arbitrary = CommitV2 <$> arbitrary <*> arbitrary
instance Arbitrary CommitTopicResult where
arbitrary = CommitTopicResult <$> arbitrary <*> arbitrary
instance Arbitrary CommitPartitionV1 where
arbitrary = CommitPartitionV1 <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary CommitPartitionV2 where
arbitrary = CommitPartitionV2 <$>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary CommitPartitionResult where
arbitrary = CommitPartitionResult <$>
arbitrary <*>
arbitrary
instance Arbitrary OffsetFetchRequestV0 where
arbitrary = OffsetFetchRequestV0 <$>
arbitrary <*>
arbitrary
instance Arbitrary TopicOffset where
arbitrary = TopicOffset <$>
arbitrary <*>
arbitrary
instance Arbitrary OffsetFetchResponseV0 where
arbitrary = OffsetFetchResponseV0 <$> arbitrary
instance Arbitrary TopicOffsetResponse where
arbitrary = TopicOffsetResponse <$>
arbitrary <*>
arbitrary
instance Arbitrary PartitionOffsetFetch where
arbitrary = PartitionOffsetFetch <$>
arbitrary <*>
arbitrary <*>
arbitrary <*>
arbitrary
instance Arbitrary OffsetFetchRequestV1 where
arbitrary = OffsetFetchRequestV1 <$>
arbitrary <*>
arbitrary
instance Arbitrary OffsetFetchResponseV1 where
arbitrary = OffsetFetchResponseV1 <$>
arbitrary
instance Arbitrary (f a) => Arbitrary (Array f a) where
arbitrary = Array <$> arbitrary
instance Arbitrary (f a) => Arbitrary (FixedArray f a) where
arbitrary = FixedArray <$> arbitrary
instance Arbitrary ApiKey where
arbitrary = ApiKey <$> arbitrary
instance Arbitrary ApiVersion where
arbitrary = ApiVersion <$> arbitrary
instance Arbitrary CorrelationId where
arbitrary = CorrelationId <$> arbitrary
instance Arbitrary TopicPublish where
arbitrary = TopicPublish <$> arbitrary <*> arbitrary
instance Arbitrary PublishResult where
arbitrary = PublishResult <$> arbitrary <*> arbitrary
instance Arbitrary PartitionMessages where
arbitrary = PartitionMessages <$> arbitrary <*> arbitrary
instance Arbitrary PublishPartitionResult where
arbitrary = PublishPartitionResult <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary ProduceRequestV0 where
arbitrary = ProduceRequestV0 <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary ProduceResponseV0 where
arbitrary = ProduceResponseV0 <$> arbitrary
-- produceAndConsume :: IO
{-
produceAndConsume = withKafkaConnection "localhost" "9092" $ \conn -> do
let r = req (CorrelationId 0) (Utf8 "sample") $ ProduceRequestV0 1 0 $
V.fromList [ TopicPublish (Utf8 "hs-kafka-test-topic") $
V.fromList
[ PartitionMessages (PartitionId 0) $ MessageSet
[ MessageSetItem 0 $ Message 0 (Attributes NoCompression) (Bytes "") (Bytes "hello")
]
]
]
send conn r
-}
roundTrip' :: B.Binary a => a -> a
roundTrip' = B.decode . B.encode
roundTrip :: (Eq a, B.Binary a, ByteSize a) => a -> Bool
roundTrip x = x == decoded && fromIntegral (byteSize x) == BL.length encoded
where
encoded = B.encode x
decoded = B.decode encoded
supportTypeTests :: TestTree
supportTypeTests = testGroup "Support types"
[ testProperty "PartitionMessages" $ \x -> roundTrip (x :: PartitionMessages)
, testProperty "Array" $ \x -> roundTrip (x :: Array V.Vector Int16)
, testProperty "FixedArray" $ \x -> roundTrip (x :: FixedArray V.Vector Int32)
, testProperty "ErrorCode" $ \x -> roundTrip (x :: ErrorCode)
, testProperty "ApiKey" $ \x -> roundTrip (x :: ApiKey)
, testProperty "ApiVersion" $ \x -> roundTrip (x :: ApiVersion)
, testProperty "CorrelationId" $ \x -> roundTrip (x :: CorrelationId)
, testProperty "CoordinatorId" $ \x -> roundTrip (x :: CoordinatorId)
, testProperty "NodeId" $ \x -> roundTrip (x :: NodeId)
, testProperty "PartitionId" $ \x -> roundTrip (x :: PartitionId)
, testProperty "Utf8" $ \x -> roundTrip (x :: Utf8)
, testProperty "Bytes" $ \x -> roundTrip (x :: Bytes)
, testProperty "Attributes" $ \x -> roundTrip (x :: Attributes)
]
main = defaultMain $ testGroup "Kafka tests"
[ testGroup "Round trip serialization"
[ supportTypeTests
, testGroup "ConsumerMetadata"
[ testProperty "Request V0" $ \x -> roundTrip (x :: GroupCoordinatorRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: GroupCoordinatorResponseV0)
]
, testGroup "Fetch"
[ testProperty "Request V0" $ \x -> roundTrip (x :: FetchRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: FetchResponseV0)
]
, testGroup "Metadata"
[ testProperty "Request V0" $ \x -> roundTrip (x :: MetadataRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: MetadataResponseV0)
]
, testGroup "Offset"
[ testProperty "Request V0" $ \x -> roundTrip (x :: OffsetRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: OffsetResponseV0)
]
, testGroup "OffsetCommit"
[ testProperty "Request V0" $ \x -> roundTrip (x :: OffsetCommitRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: OffsetCommitResponseV0)
, testProperty "Request V1" $ \x -> roundTrip (x :: OffsetCommitRequestV1)
, testProperty "Response V1" $ \x -> roundTrip (x :: OffsetCommitResponseV1)
, testProperty "Request V2" $ \x -> roundTrip (x :: OffsetCommitRequestV2)
, testProperty "Response V2" $ \x -> roundTrip (x :: OffsetCommitResponseV2)
]
, testGroup "OffsetFetch"
[ testProperty "Request V0" $ \x -> roundTrip (x :: OffsetFetchRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: OffsetFetchResponseV0)
, testProperty "Request V1" $ \x -> roundTrip (x :: OffsetFetchRequestV1)
, testProperty "Response V1" $ \x -> roundTrip (x :: OffsetFetchResponseV1)
]
, testGroup "Produce"
[ testProperty "Request V0" $ \x -> roundTrip (x :: ProduceRequestV0)
, testProperty "Response V0" $ \x -> roundTrip (x :: ProduceResponseV0)
]
]
, connectionTests
]
{-
testGroup "Connection"
[ "connection open"
, "connection close"
, "connection queues requests"
, "demand result flushes queue"
]
, testGroup "Basic requests return properly"
[ testCase "groupCoordinator" $ do
k <- localKafka $ groupCoordinator "test-group"
assertEqual "error code" NoError $ k ^. errorCode
{-
, testCase "fetch" $ do
localKafka
, testCase "metadata" $ do
localKafka
, testCase "offset" $ do
localKakfa
, testCase "offsetCommit" $ do
localKafka
, testCase "produce" $ do
localKafka
-}
]
, testGroup "Client" []
, testGroup "Producer" []
, testGroup "Consumer" []
]
-}
| iand675/hs-kafka | test/Main.hs | bsd-3-clause | 14,408 | 0 | 15 | 3,459 | 2,860 | 1,552 | 1,308 | 323 | 1 |
import Data.Bits (setBit, testBit)
robot :: Int -> Int -> Int -> Int
robot _ 3 3 = 1
robot f x y = n + e + s + w
where n | y > 0 && not (testBit f (x+4*(y-1))) = robot (setBit f (x+4*(y-1))) x (y-1)
| otherwise = 0
e | x < 3 && not (testBit f (x+1+4*y)) = robot (setBit f (x+1+4*y)) (x+1) y
| otherwise = 0
s | y < 3 && not (testBit f (x+4*(y+1))) = robot (setBit f (x+4*(y+1))) x (y+1)
| otherwise = 0
w | x > 0 && not (testBit f (x-1+4*y)) = robot (setBit f (x-1+4*y)) (x-1) y
| otherwise = 0
main :: IO ()
main = print $ robot 1 0 0
| nikai3d/ce-challenges | hard/robot_movements.hs | bsd-3-clause | 801 | 0 | 17 | 393 | 471 | 237 | 234 | 14 | 1 |
{-# LANGUAGE PolyKinds, DataKinds, TemplateHaskell, TypeFamilies,
GADTs, TypeOperators, RankNTypes, FlexibleContexts, UndecidableInstances,
FlexibleInstances, ScopedTypeVariables, MultiParamTypeClasses,
OverlappingInstances #-}
module Oxymoron.Scene.Mesh where
import Data.Singletons
import Data.Array.Repa hiding (Any)
import Data.Array.Repa.Repr.ForeignPtr
import Data.Word
import Data.Int
import Graphics.Rendering.OpenGL.Raw
import qualified Oxymoron.Description.Mesh as Desc
import Oxymoron.Description.Attribute
import qualified Oxymoron.Scene.Attribute as A
import Oxymoron.Scene.Attribute (AttributeState(..))
import Oxymoron.Description.Mesh (IndexType(..))
import Oxymoron.Scene.TypeFunctions
import Data.Singletons.Extras
type instance ToUnpacked 'IUnsignedByte = Word8
type instance ToUnpacked 'IUnsignedShort = Word16
type instance ToUnpacked 'IUnsignedInt = Word32
type instance ToUnpacked ('Desc.IndexArray x y) = ToUnpacked x
type IndexArray (a :: Desc.IndexArray ) = MetaVector a
type instance ToUnpacked ('Desc.VertexArray xs) = ToUnpacked xs
type VertexArray (a :: Desc.VertexArray) = MetaVector a
data Mesh :: Desc.Mesh -> * where
Mesh :: IndexArray (Desc.GetIndexArray a)
-> VertexArray (Desc.GetVertexArray a)
-> Mesh a
data ExMesh :: Desc.VertexArray -> * where
ExMesh :: Mesh ('Desc.Mesh ia va) -> ExMesh va
{-
bindAttributes :: VertexArray as 'Bound pr -> pr ()
bindAttributes (BoundVertexArray as vts) = mapM (bindAttribute vts) as
renderMesh :: ExMesh as 'Bound pr -> pr ()
renderMesh (ExMesh (MeshV idx vs)) = do
--break open the vertex array and bind the attributes
bindAttributes vs
--draw the elements
drawElements idx
-}
| jfischoff/oxymoron | src/Oxymoron/Scene/Mesh.hs | bsd-3-clause | 1,747 | 0 | 11 | 288 | 328 | 196 | 132 | 31 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Game.Monsters.MGunnerGlobals where
import Control.Lens (makeLenses)
import Types
makeLenses ''MGunnerGlobals
initialMGunnerGlobals :: MGunnerGlobals
initialMGunnerGlobals =
MGunnerGlobals { _mGunnerSoundPain = 0
, _mGunnerSoundPain2 = 0
, _mGunnerSoundDeath = 0
, _mGunnerSoundIdle = 0
, _mGunnerSoundOpen = 0
, _mGunnerSoundSearch = 0
, _mGunnerSoundSight = 0
}
| ksaveljev/hake-2 | src/Game/Monsters/MGunnerGlobals.hs | bsd-3-clause | 537 | 0 | 6 | 183 | 83 | 52 | 31 | 14 | 1 |
{-# LANGUAGE PackageImports #-}
module Numeric (module M) where
import "base" Numeric as M
| silkapp/base-noprelude | src/Numeric.hs | bsd-3-clause | 96 | 0 | 4 | 18 | 17 | 13 | 4 | 3 | 0 |
{-# LANGUAGE ForeignFunctionInterface, BangPatterns, ScopedTypeVariables, TupleSections
#-}
module Main where
import qualified Data.Vector.Storable as V
import Data.Vector.Storable ((!))
import Bindings.SVM
import Foreign.C.Types
import Foreign.C.String
import Foreign.Ptr
import Foreign.ForeignPtr
import qualified Foreign.Concurrent as C
import Foreign.Marshal.Utils
import Control.Applicative
import System.IO.Unsafe
import Foreign.Storable
import Control.Monad
{-# SPECIALIZE convertDense :: V.Vector Double -> V.Vector C'svm_node #-}
{-# SPECIALIZE convertDense :: V.Vector Float -> V.Vector C'svm_node #-}
convertDense :: (V.Storable a, Real a) => V.Vector a -> V.Vector C'svm_node
convertDense v = V.generate (dim+1) readVal
where
dim = V.length v
readVal !n | n >= dim = C'svm_node (-1) 0
readVal !n = C'svm_node (fromIntegral n) (realToFrac $ v ! n)
withProblem :: [(Double, V.Vector Double)] -> (Ptr C'svm_problem -> IO b) -> IO b
withProblem v op = -- Well. This turned out super ugly. Possibly even wrong.
V.unsafeWith xs $ \ptr_xs ->
V.unsafeWith y $ \ptr_y ->
let optrs = offsetPtrs ptr_xs
in V.unsafeWith optrs $ \ptr_offsets ->
with (C'svm_problem (fromIntegral dim) ptr_y ptr_offsets) op
where
dim = length v
lengths = map (V.length . snd) v
offsetPtrs addr = V.fromList
[addr `plusPtr` (idx * sizeOf (xs ! 0))
| idx <- scanl (+) 0 lengths]
y = V.fromList . map (realToFrac . fst) $ v
xs = V.concat . map (extractSvmNode.snd) $ v
extractSvmNode x = convertDense $ V.generate (V.length x) (x !)
newtype SVM = SVM (ForeignPtr C'svm_model)
modelFinalizer :: Ptr C'svm_model -> IO ()
modelFinalizer = \modelPtr -> do
with modelPtr (c'svm_free_and_destroy_model)
loadSVM :: FilePath -> IO SVM
loadSVM fp = do
ptr <- withCString fp c'svm_load_model
let fin = modelFinalizer ptr
SVM <$> C.newForeignPtr ptr fin
predict :: SVM -> V.Vector Double -> Double
predict (SVM fptr) vec = unsafePerformIO $
withForeignPtr fptr $ \modelPtr ->
let nodes = convertDense vec
in realToFrac <$> V.unsafeWith nodes (c'svm_predict modelPtr)
dummyParameters = C'svm_parameter {
c'svm_parameter'svm_type = c'LINEAR
, c'svm_parameter'kernel_type = c'RBF
, c'svm_parameter'degree = 1
, c'svm_parameter'gamma = 0.01
, c'svm_parameter'coef0 = 0.1
, c'svm_parameter'cache_size = 10
, c'svm_parameter'eps = 0.00001
, c'svm_parameter'C = 0.01
, c'svm_parameter'nr_weight = 0
, c'svm_parameter'weight_label = nullPtr
, c'svm_parameter'weight = nullPtr
, c'svm_parameter'nu = 0.1
, c'svm_parameter'p = 0.1
, c'svm_parameter'shrinking = 0
, c'svm_parameter'probability = 0
}
foreign import ccall "wrapper"
wrapPrintF :: (CString -> IO ()) -> IO (FunPtr (CString -> IO ()))
trainSVM :: [(Double, V.Vector Double)] -> IO SVM
trainSVM dataSet = do
pf <- wrapPrintF (\cstr -> peekCString cstr >>= print . (, ":HS"))
c'svm_set_print_string_function pf
modelPtr <- withProblem dataSet $ \ptr_problem ->
with dummyParameters $ \ptr_parameters ->
c'svm_train ptr_problem ptr_parameters
SVM <$> C.newForeignPtr modelPtr (modelFinalizer modelPtr)
main = do
--mPtr <- withCString "model" c'svm_load_model
svm <- loadSVM "model"
let positiveSample = V.fromList
[0.708333, 1, 1, -0.320755, -0.105023, -1
, 1, -0.419847, -1, -0.225806, 1, -1]
negativeSample = V.fromList
[0.583333 ,-1 ,0.333333 ,-0.603774 ,1 ,-1
,1 ,0.358779 ,-1 ,-0.483871 ,-1 ,1]
let
pos = predict svm positiveSample
neg = predict svm negativeSample
print (pos,neg)
print "Training"
let trainingData = [(-1, V.fromList [0])
,(-1, V.fromList [20])
,(1, V.fromList [21])
,(1, V.fromList [50])
]
svm2 <- trainSVM trainingData
print $ predict svm2 $ V.fromList [0]
print $ predict svm2 $ V.fromList [5]
print $ predict svm2 $ V.fromList [12]
print $ predict svm2 $ V.fromList [40]
| aleator/aleators-bindings-svm | example/SmokeTest.hs | bsd-3-clause | 4,470 | 0 | 17 | 1,284 | 1,341 | 709 | 632 | 99 | 2 |
module Main where
import Lib
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
import Data.Maybe
main :: IO ()
main = do
putStrLn "Excercises from Chapter 22: Reader"
putStrLn "Some examples commented out in main function."
putStrLn "Use 'stack ghci' to start ghci to play around. Enjoy."
-- print $ sequenceA [Just 3, Just 2, Just 1]
-- print $ sequenceA [x, y]
-- print $ sequenceA [xs, ys]
-- print $ summed <$> ((,) <$> xs <*> ys)
-- print $ fmap summed ((,) <$> xs <*> zs)
-- print $ bolt 7
-- print $ fmap bolt z
--
-- print $ sequenceA [(>3), (<8), even] 7
-- print $ foldr (&&) True $ sequA 7
-- print $ sequA $ fromMaybe 0 s'
-- print $ bolt $ fromMaybe 0 ys
| backofhan/HaskellExercises | CH22/app/Main.hs | bsd-3-clause | 739 | 0 | 7 | 167 | 74 | 45 | 29 | 11 | 1 |
module Data.List.Zipper where
import Data.Maybe (listToMaybe)
data Zipper a = Zip ![a] ![a] deriving (Eq,Show)
instance Functor Zipper where
fmap f (Zip ls rs) = Zip (map f ls) (map f rs)
-- | @empty@ is an empty zipper
empty :: Zipper a
empty = Zip [] []
-- | @fromList xs@ returns a zipper containing the elements of xs,
-- focused on the first element.
fromList :: [a] -> Zipper a
fromList = Zip []
-- | @fromListEnd xs@ returns a zipper containing the elements of xs,
-- focused just off the right end of the list.
fromListEnd :: [a] -> Zipper a
fromListEnd as = Zip (reverse as) []
toList :: Zipper a -> [a]
toList (Zip ls rs) = reverse ls ++ rs
-- | @beginp z@ returns @True@ if the zipper is at the start.
beginp :: Zipper a -> Bool
beginp (Zip [] _ ) = True
beginp _ = False
-- | @endp z@ returns @True@ if the zipper is at the end.
-- It is not safe to call @cursor@ on @z@ if @endp z@ returns @True@.
endp :: Zipper a -> Bool
endp (Zip _ []) = True
endp _ = False
-- | @emptyp z@ returns @True@ if the zipper is completely empty.
-- forall z. emptyp z == beginp z && endp z
emptyp :: Zipper a -> Bool
emptyp (Zip [] []) = True
emptyp _ = False
start, end :: Zipper a -> Zipper a
start (Zip ls rs) = Zip [] (reverse ls ++ rs)
end (Zip ls rs) = Zip (reverse rs ++ ls) []
-- | @cursor z@ returns the targeted element in @z@.
--
-- This function is not total, but the invariant is that
-- @endp z == False@ means that you can safely call
-- @cursor z@.
cursor :: Zipper a -> a
cursor (Zip _ (a:_)) = a
cursor (Zip _ []) = error "cursor out of bounds"
-- | @safeCursor@ is like @cursor@ but total.
safeCursor :: Zipper a -> Maybe a
safeCursor (Zip _ rs) = listToMaybe rs
-- | @left z@ returns the zipper with the focus
-- shifted left one element.
left :: Zipper a -> Zipper a
left (Zip (a:ls) rs) = Zip ls (a:rs)
left z = z
-- | @right z@ returns the zipper with the focus
-- shifted right one element; this can move the
-- cursor off the end.
right :: Zipper a -> Zipper a
right (Zip ls (a:rs)) = Zip (a:ls) rs
right z = z
-- | @insert x z@ adds x at the cursor.
insert :: a -> Zipper a -> Zipper a
insert a (Zip ls rs) = Zip ls (a:rs)
-- | @delete z@ removes the element at the cursor (if any).
-- Safe to call on an empty zipper.
-- forall x z. delete (insert x z) == z
delete :: Zipper a -> Zipper a
delete (Zip ls (_:rs)) = Zip ls rs
delete z = z
-- | @push x z@ inserts x into the zipper, and advances
-- the cursor past it.
push :: a -> Zipper a -> Zipper a
push a (Zip ls rs) = Zip (a:ls) rs
-- | @pop z@ removes the element before the cursor (if any).
-- Safe to call on an empty zipper.
-- forall x z. pop (push x z) == z
pop :: Zipper a -> Zipper a
pop (Zip (_:ls) rs) = Zip ls rs
pop z = z
-- | @replace a z@ changes the current element in the zipper
-- to the passed in value. If there is no current element,
-- the zipper is unchanged. If you want to add the element
-- in that case instead, use @insert a (delete z)@.
replace :: a -> Zipper a -> Zipper a
replace a (Zip ls (_:rs)) = Zip ls (a:rs)
replace _ z = z
-- | @reversez z@ returns the zipper with the elements in
-- the reverse order. O(1). The cursor is moved to the
-- previous element, so if the cursor was at the start,
-- it's now off the right end, and if it was off the
-- right end, it's now at the start of the reversed list.
reversez :: Zipper a -> Zipper a
reversez (Zip ls rs) = Zip rs ls
-- | @foldrz f x zip@ calls @f@ with the zipper focused on
-- each element in order, starting with the current.
-- You are guaranteed that f can safely call "cursor" on
-- its argument; the zipper won't be at the end.
foldrz :: (Zipper a -> b -> b) -> b -> Zipper a -> b
foldrz f x = go where
go z
| endp z = x
| otherwise = f z (go $ right z)
-- | @foldlz f x zip@ calls f with the zipper focused on
-- each element in order, starting with the current.
-- You are guaranteed that f can safely call "cursor" on
-- its argument; the zipper won't be at the end.
foldlz :: (b -> Zipper a -> b) -> b -> Zipper a -> b
foldlz f x z
| endp z = x
| otherwise = foldlz f (f x z) (right z)
-- | @foldlz'@ is foldlz with a strict accumulator
foldlz' :: (b -> Zipper a -> b) -> b -> Zipper a -> b
foldlz' f x z
| endp z = x
| otherwise = acc `seq` foldlz' f acc (right z)
where acc = f x z
-- | @extractz@, @extendz@, and @duplicatez@ can be used to
-- implement Copointed and Comonad from category-extras. I didn't
-- add the instances here so as not to introduce a dependency
-- on that package.
extractz :: Zipper a -> a
extractz = cursor
duplicatez :: Zipper a -> Zipper (Zipper a)
duplicatez z@(Zip _ _) = Zip ls' rs' where
rs' = foldrz (:) [] z
ls' = map reversez $
foldrz (\z' xs -> right z' : xs) [] $
reversez z
extendz :: (Zipper a -> b) -> Zipper a -> Zipper b
extendz f z@(Zip _ _) = Zip ls' rs' where
rs' = foldrz (\z' xs -> f z' : xs) [] z
ls' = foldrz (\z' xs -> f (reversez $ right z') : xs) [] $ reversez z
| z0isch/lambda-hive | src/Data/List/Zipper.hs | bsd-3-clause | 5,160 | 0 | 15 | 1,338 | 1,499 | 769 | 730 | 81 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Parser
-- Copyright : (C) 2014 John MacFarlane
-- License : BSD-style (see LICENSE)
--
-- Maintainer : John MacFarlane <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Parser for CSL XML files.
-----------------------------------------------------------------------------
module Text.CSL.Parser (readCSLFile, parseCSL, parseCSL',
parseLocale, localizeCSL)
where
import Prelude
import qualified Control.Exception as E
import Control.Monad (when)
import qualified Data.ByteString.Lazy as L
import Data.Either (lefts, rights)
import qualified Data.Map as M
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Text (Text, unpack)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import System.Directory (getAppUserDataDirectory)
import Text.CSL.Compat.Pandoc (fetchItem)
import Text.CSL.Data (getLocale)
import Text.CSL.Exception
import Text.CSL.Style hiding (parseNames)
import Text.CSL.Util (findFile, toRead, trim)
import Text.Pandoc.Shared (safeRead)
import qualified Text.XML as X
import Text.XML.Cursor
-- | Parse a 'String' into a 'Style' (with default locale).
parseCSL :: Text -> Style
parseCSL = parseCSL' . TL.encodeUtf8 . TL.fromStrict
-- | Parse locale. Raises 'CSLLocaleException' on error.
parseLocale :: Text -> IO Locale
parseLocale locale =
parseLocaleElement . fromDocument . X.parseLBS_ X.def <$> getLocale locale
-- | Merge locale into a CSL style.
localizeCSL :: Maybe Text -> Style -> IO Style
localizeCSL mbLocale s = do
let locale = fromMaybe (styleDefaultLocale s) mbLocale
l <- parseLocale locale
return s { styleLocale = mergeLocales locale l (styleLocale s) }
-- | Read and parse a CSL style file into a localized sytle.
readCSLFile :: Maybe Text -> FilePath -> IO Style
readCSLFile mbLocale src = do
csldir <- getAppUserDataDirectory "csl"
mbSrc <- findFile [".", csldir] src
fetchRes <- fetchItem (fromMaybe src mbSrc)
f <- case fetchRes of
Left err -> E.throwIO err
Right (rawbs, _) -> return $ L.fromChunks [rawbs]
let cur = fromDocument $ X.parseLBS_ X.def f
-- see if it's a dependent style, and if so, try to fetch its parent:
let pickParentCur = get "link" >=> attributeIs (X.Name "rel" Nothing Nothing) "independent-parent"
let parentCur = cur $/ get "info" &/ pickParentCur
let parent' = T.concat $ map (stringAttr "href") parentCur
when (parent' == T.pack src) $
E.throwIO $ DependentStyleHasItselfAsParent src
case parent' of
"" -> localizeCSL mbLocale $ parseCSLCursor cur
y -> do
-- note, we insert locale from the dependent style:
let mbLocale' = case stringAttr "default-locale" cur of
"" -> mbLocale
x -> Just x
readCSLFile mbLocale' (T.unpack y)
parseCSL' :: L.ByteString -> Style
parseCSL' = parseCSLCursor . fromDocument . X.parseLBS_ X.def
parseCSLCursor :: Cursor -> Style
parseCSLCursor cur =
Style{ styleVersion = T.pack version
, styleClass = T.pack class_
, styleInfo = Just info
, styleDefaultLocale = defaultLocale
, styleLocale = locales
, styleAbbrevs = Abbreviations M.empty
, csOptions = filter (\(k,_) -> k `notElem`
["class",
"xmlns",
"version",
"default-locale"]) $ parseOptions cur
, csMacros = macros
, citation = fromMaybe (Citation [] [] Layout{ layFormat = emptyFormatting
, layDelim = ""
, elements = [] }) $ listToMaybe $
cur $/ get "citation" &| parseCitation
, biblio = listToMaybe $ cur $/ get "bibliography" &| parseBiblio
}
where version = unpack . T.concat $ cur $| laxAttribute "version"
class_ = unpack . T.concat $ cur $| laxAttribute "class"
defaultLocale = case cur $| laxAttribute "default-locale" of
(x:_) -> x
[] -> "en-US"
author = case cur $// get "info" &/ get "author" of
(x:_) -> CSAuthor (T.concat $ x $/ get "name" &/ content)
(T.concat $ x $/ get "email" &/ content)
(T.concat $ x $/ get "uri" &/ content)
_ -> CSAuthor "" "" ""
info = CSInfo
{ csiTitle = T.concat $ (cur $/ get "info" &/ get "title" &/ content)
, csiAuthor = author
, csiCategories = [] -- TODO we don't really use this, and the type
-- in Style doesn't match current CSL at all
, csiId = T.concat $ cur $/ get "info" &/ get "id" &/ content
, csiUpdated = T.concat $ cur $/ get "info" &/ get "updated" &/ content
}
locales = cur $/ get "locale" &| parseLocaleElement
macros = cur $/ get "macro" &| parseMacroMap
get :: Text -> Axis
get name =
element (X.Name name (Just "http://purl.org/net/xbiblio/csl") Nothing)
attrWithDefault :: Read a => Text -> a -> Cursor -> a
attrWithDefault t d cur =
fromMaybe d $ safeRead (toRead $ stringAttr t cur)
stringAttr :: Text -> Cursor -> Text
stringAttr t cur =
case node cur of
X.NodeElement e ->
case M.lookup (X.Name t Nothing Nothing) (X.elementAttributes e) of
Just x -> x
Nothing -> ""
_ -> ""
parseCslTerm :: Cursor -> CslTerm
parseCslTerm cur =
let body = trim . T.concat $ cur $/ content
in CT
{ cslTerm = stringAttr "name" cur
, termForm = attrWithDefault "form" Long cur
, termGender = attrWithDefault "gender" Neuter cur
, termGenderForm = attrWithDefault "gender-form" Neuter cur
, termSingular = if T.null body
then T.concat $ cur $/ get "single" &/ content
else body
, termPlural = if T.null body
then T.concat $ cur $/ get "multiple" &/ content
else body
, termMatch = stringAttr "match" cur
}
parseLocaleElement :: Cursor -> Locale
parseLocaleElement cur = Locale
{ localeVersion = T.concat version
, localeLang = T.concat lang
, localeOptions = concat $ cur $/ get "style-options" &| parseOptions
, localeTerms = terms
, localeDate = concat $ cur $/ get "date" &| parseElement
}
where version = cur $| laxAttribute "version"
lang = cur $| laxAttribute "lang"
terms = cur $/ get "terms" &/ get "term" &| parseCslTerm
parseElement :: Cursor -> [Element]
parseElement cur =
case node cur of
X.NodeElement e ->
case X.nameLocalName $ X.elementName e of
"term" -> parseTerm cur
"text" -> parseText cur
"choose" -> parseChoose cur
"group" -> parseGroup cur
"label" -> parseLabel cur
"number" -> parseNumber cur
"substitute" -> parseSubstitute cur
"names" -> parseNames cur
"date" -> parseDate cur
_ -> []
_ -> []
getFormatting :: Cursor -> Formatting
getFormatting cur =
emptyFormatting{
prefix = stringAttr "prefix" cur
, suffix = stringAttr "suffix" cur
, fontFamily = stringAttr "font-family" cur
, fontStyle = stringAttr "font-style" cur
, fontVariant = stringAttr "font-variant" cur
, fontWeight = stringAttr "font-weight" cur
, textDecoration = stringAttr "text-decoration" cur
, verticalAlign = stringAttr "vertical-align" cur
, textCase = stringAttr "text-case" cur
, display = stringAttr "display" cur
, quotes = if attrWithDefault "quotes" False cur
then NativeQuote
else NoQuote
, stripPeriods = attrWithDefault "strip-periods" False cur
, noCase = attrWithDefault "no-case" False cur
, noDecor = attrWithDefault "no-decor" False cur
}
parseDate :: Cursor -> [Element]
parseDate cur = [Date (T.words variable) form format delim parts partsAttr]
where variable = stringAttr "variable" cur
form = case stringAttr "form" cur of
"text" -> TextDate
"numeric" -> NumericDate
_ -> NoFormDate
format = getFormatting cur
delim = stringAttr "delimiter" cur
parts = cur $/ get "date-part" &| parseDatePart form
partsAttr = stringAttr "date-parts" cur
parseDatePart :: DateForm -> Cursor -> DatePart
parseDatePart defaultForm cur =
DatePart { dpName = stringAttr "name" cur
, dpForm = case stringAttr "form" cur of
"" -> case defaultForm of
TextDate -> "long"
NumericDate -> "numeric"
_ -> "long"
x -> x
, dpRangeDelim = case stringAttr "range-delimiter" cur of
"" -> "-"
x -> x
, dpFormatting = getFormatting cur
}
parseNames :: Cursor -> [Element]
parseNames cur = [Names (T.words variable) names formatting delim others]
where variable = stringAttr "variable" cur
formatting = getFormatting cur
delim = stringAttr "delimiter" cur
elts = cur $/ parseName
names = case rights elts of
[] -> [Name NotSet emptyFormatting [] "" []]
xs -> xs
others = lefts elts
parseName :: Cursor -> [Either Element Name]
parseName cur =
case node cur of
X.NodeElement e ->
case X.nameLocalName $ X.elementName e of
"name" -> [Right $ Name (attrWithDefault "form" NotSet cur)
format (nameAttrs e) delim nameParts]
"label" -> [Right $ NameLabel (attrWithDefault "form" Long cur)
format plural]
"et-al" -> [Right $ EtAl format $ stringAttr "term" cur]
_ -> map Left $ parseElement cur
_ -> map Left $ parseElement cur
where format = getFormatting cur
plural = attrWithDefault "plural" Contextual cur
delim = stringAttr "delimiter" cur
nameParts = cur $/ get "name-part" &| parseNamePart
nameAttrs x = [(n, v) |
(X.Name n _ _, v) <- M.toList (X.elementAttributes x),
n `elem` nameAttrKeys]
nameAttrKeys = [ "et-al-min"
, "et-al-use-first"
, "suppress-min"
, "suppress-max"
, "et-al-subsequent-min"
, "et-al-subsequent-use-first"
, "et-al-use-last"
, "delimiter-precedes-et-al"
, "and"
, "delimiter-precedes-last"
, "sort-separator"
, "initialize"
, "initialize-with"
, "name-as-sort-order" ]
parseNamePart :: Cursor -> NamePart
parseNamePart cur = NamePart s format
where format = getFormatting cur
s = stringAttr "name" cur
parseSubstitute :: Cursor -> [Element]
parseSubstitute cur = [Substitute (cur $/ parseElement)]
parseTerm :: Cursor -> [Element]
parseTerm cur =
let termForm' = attrWithDefault "form" Long cur
formatting = getFormatting cur
plural = attrWithDefault "plural" True cur
name = stringAttr "name" cur
in [Term name termForm' formatting plural]
parseText :: Cursor -> [Element]
parseText cur =
let term = stringAttr "term" cur
variable = stringAttr "variable" cur
macro = stringAttr "macro" cur
value = stringAttr "value" cur
delim = stringAttr "delimiter" cur
formatting = getFormatting cur
plural = attrWithDefault "plural" True cur
textForm = attrWithDefault "form" Long cur
in if not (T.null term)
then [Term term textForm formatting plural]
else if not (T.null macro)
then [Macro macro formatting]
else if not (T.null variable)
then [Variable (T.words variable) textForm formatting delim]
else [Const value formatting | not (T.null value)]
parseChoose :: Cursor -> [Element]
parseChoose cur =
let ifPart = cur $/ get "if" &| parseIf
elseIfPart = cur $/ get "else-if" &| parseIf
elsePart = cur $/ get "else" &/ parseElement
in [Choose (head ifPart) elseIfPart elsePart]
parseIf :: Cursor -> IfThen
parseIf cur = IfThen cond mat elts
where cond = Condition {
isType = go "type"
, isSet = go "variable"
, isNumeric = go "is-numeric"
, isUncertainDate = go "is-uncertain-date"
, isPosition = go "position"
, disambiguation = go "disambiguate"
, isLocator = go "locator"
}
mat = attrWithDefault "match" All cur
elts = cur $/ parseElement
go x = T.words $ stringAttr x cur
parseLabel :: Cursor -> [Element]
parseLabel cur = [Label variable form formatting plural]
where variable = stringAttr "variable" cur
form = attrWithDefault "form" Long cur
formatting = getFormatting cur
plural = attrWithDefault "plural" Contextual cur
parseNumber :: Cursor -> [Element]
parseNumber cur = [Number variable numForm formatting]
where variable = stringAttr "variable" cur
numForm = attrWithDefault "form" Numeric cur
formatting = getFormatting cur
parseGroup :: Cursor -> [Element]
parseGroup cur =
let elts = cur $/ parseElement
delim = stringAttr "delimiter" cur
formatting = getFormatting cur
in [Group formatting delim elts]
parseMacroMap :: Cursor -> MacroMap
parseMacroMap cur = (name, elts)
where name = cur $| stringAttr "name"
elts = cur $/ parseElement
parseCitation :: Cursor -> Citation
parseCitation cur = Citation{ citOptions = parseOptions cur
, citSort = concat $ cur $/ get "sort" &| parseSort
, citLayout = case cur $/ get "layout" &| parseLayout of
(x:_) -> x
[] -> Layout
{ layFormat = emptyFormatting
, layDelim = ""
, elements = [] }
}
parseSort :: Cursor -> [Sort]
parseSort cur = concat $ cur $/ get "key" &| parseKey
parseKey :: Cursor -> [Sort]
parseKey cur =
case stringAttr "variable" cur of
"" ->
case stringAttr "macro" cur of
"" -> []
x -> [SortMacro x sorting (attrWithDefault "names-min" 0 cur)
(attrWithDefault "names-use-first" 0 cur)
(stringAttr "names-use-last" cur)]
x -> [SortVariable x sorting]
where sorting = case stringAttr "sort" cur of
"descending" -> Descending ""
_ -> Ascending ""
parseBiblio :: Cursor -> Bibliography
parseBiblio cur =
Bibliography{
bibOptions = parseOptions cur,
bibSort = concat $ cur $/ get "sort" &| parseSort,
bibLayout = case cur $/ get "layout" &| parseLayout of
(x:_) -> x
[] -> Layout
{ layFormat = emptyFormatting
, layDelim = ""
, elements = [] }
}
parseOptions :: Cursor -> [Option]
parseOptions cur =
case node cur of
X.NodeElement e ->
[(n, v) |
(X.Name n _ _, v) <- M.toList (X.elementAttributes e)]
_ -> []
parseLayout :: Cursor -> Layout
parseLayout cur =
Layout
{ layFormat = getFormatting cur
, layDelim = stringAttr "delimiter" cur
, elements = cur $/ parseElement
}
| jgm/pandoc-citeproc | src/Text/CSL/Parser.hs | bsd-3-clause | 17,223 | 0 | 18 | 6,325 | 4,302 | 2,246 | 2,056 | 353 | 11 |
-- Copyright (c) 2016 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}
module IR.Common.Transfer(
Transfer(..)
) where
import Data.Hashable
import Data.Position.DWARFPosition
import IR.Common.Names
import IR.Common.Rename
import IR.Common.RenameType
import Prelude.Extras
import Text.Format
import Text.XML.Expat.Pickle hiding (Node)
import Text.XML.Expat.Tree(NodeG)
-- | Transfers. These represent methods of leaving a basic block.
-- All basic blocks end in a transfer.
data Transfer exp =
-- | A direct jump
Goto {
-- | The jump target.
gotoLabel :: !Label,
-- | The position in source from which this arises.
gotoPos :: !(DWARFPosition Globalname Typename)
}
-- | A (integer) case expression
| Case {
-- | The value being decided upon. Must be an integer value.
caseVal :: exp,
-- | The cases. There must be at least one case.
caseCases :: [(Integer, Label)],
-- | The default case.
caseDefault :: !Label,
-- | The position in source from which this arises.
casePos :: !(DWARFPosition Globalname Typename)
}
-- | A return
| Ret {
-- | The return value, if one exists.
retVal :: Maybe exp,
-- | The position in source from which this arises.
retPos :: !(DWARFPosition Globalname Typename)
}
-- | An unreachable instruction, usually following a call with no
-- return
| Unreachable { unreachablePos :: !(DWARFPosition Globalname Typename) }
instance Eq1 Transfer where
Goto { gotoLabel = label1 } ==# Goto { gotoLabel = label2 } = label1 == label2
Case { caseVal = val1, caseCases = cases1, caseDefault = def1 } ==#
Case { caseVal = val2, caseCases = cases2, caseDefault = def2 } =
val1 == val2 && cases1 == cases2 && def1 == def2
Ret { retVal = ret1 } ==# Ret { retVal = ret2 } = ret1 == ret2
Unreachable _ ==# Unreachable _ = True
_ ==# _ = False
instance Eq exp => Eq (Transfer exp) where
(==) = (==#)
instance Ord1 Transfer where
compare1 Goto { gotoLabel = label1 } Goto { gotoLabel = label2 } =
compare label1 label2
compare1 Goto {} _ = LT
compare1 _ Goto {} = GT
compare1 Case { caseVal = val1, caseCases = cases1, caseDefault = def1 }
Case { caseVal = val2, caseCases = cases2, caseDefault = def2 } =
case compare val1 val2 of
EQ -> case compare def1 def2 of
EQ -> compare cases1 cases2
out -> out
out -> out
compare1 Case {} _ = LT
compare1 _ Case {} = GT
compare1 Ret { retVal = ret1 } Ret { retVal = ret2 } = compare ret1 ret2
compare1 Ret {} _ = LT
compare1 _ Ret {} = GT
compare1 (Unreachable _) (Unreachable _) = EQ
instance Ord exp => Ord (Transfer exp) where
compare = compare1
instance Hashable elem => Hashable (Transfer elem) where
hashWithSalt s Goto { gotoLabel = label } =
s `hashWithSalt` (1 :: Int) `hashWithSalt` label
hashWithSalt s Case { caseVal = val, caseCases = cases, caseDefault = def } =
s `hashWithSalt` (2 :: Int) `hashWithSalt`
val `hashWithSalt` cases `hashWithSalt` def
hashWithSalt s Ret { retVal = val } =
s `hashWithSalt` (3 :: Int) `hashWithSalt` val
hashWithSalt s (Unreachable _) = s `hashWithSalt` (4 :: Int)
instance RenameType Typename exp => RenameType Typename (Transfer exp) where
renameType f tr @ Case { caseVal = val } = tr { caseVal = renameType f val }
renameType f tr @ Ret { retVal = val } = tr { retVal = renameType f val }
renameType _ tr = tr
instance Rename Id exp => Rename Id (Transfer exp) where
rename f tr @ Case { caseVal = val } = tr { caseVal = rename f val }
rename f tr @ Ret { retVal = val } = tr { retVal = rename f val }
rename _ tr = tr
instance Format exp => Format (Transfer exp) where
format Goto { gotoLabel = l } = string "goto" <+> format l
format Case { caseVal = e, caseCases = cases, caseDefault = def } =
let
mapfun (i, l) = format i <> colon <+> format l
casesdoc = list ((string "default" <> colon <+> format def) :
map mapfun cases)
in
string "case" <+> align (format e </> casesdoc)
format Ret { retVal = Just e } = string "ret" <+> format e
format Ret { retVal = Nothing } = string "ret"
format (Unreachable _) = string "Unreachable"
instance FormatM m exp => FormatM m (Transfer exp) where
formatM Goto { gotoLabel = l } = return $! string "goto" <+> format l
formatM Case { caseVal = e, caseCases = cases, caseDefault = def } =
let
mapfun (i, l) = format i <> colon <+> format l
casesdoc = list ((string "default" <> colon <+> format def) :
map mapfun cases)
in do
edoc <- formatM e
return $! string "case" <> align (softbreak <> edoc </> casesdoc)
formatM Ret { retVal = Just e } =
do
edoc <- formatM e
return $! string "ret" <+> edoc
formatM Ret { retVal = Nothing } = return $! string "ret"
formatM (Unreachable _) = return $! string "Unreachable"
gotoPickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text) =>
PU [NodeG [] tag text] (Transfer exp)
gotoPickler =
let
revfunc Goto { gotoLabel = l, gotoPos = pos } = (l, pos)
revfunc _ = error $! "Can't convert"
in
xpWrap (\(l, pos) -> Goto { gotoLabel = l, gotoPos = pos }, revfunc)
(xpElem (gxFromString "Goto") xpickle
(xpElemNodes (gxFromString "pos") xpickle))
casePickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text,
XmlPickler [NodeG [] tag text] exp) =>
PU [NodeG [] tag text] (Transfer exp)
casePickler =
let
revfunc Case { caseVal = val, caseDefault = def,
caseCases = cases, casePos = pos } =
(val, cases, def, pos)
revfunc _ = error $! "Can't convert"
casepickler =
xpElemNodes (gxFromString "cases")
(xpList (xpElemAttrs (gxFromString "case")
(xpPair (xpAttr (gxFromString "val")
xpPrim)
xpickle)))
in
xpWrap (\(val, cases, def, pos) ->
Case { caseVal = val, caseDefault = def,
caseCases = cases, casePos = pos }, revfunc)
(xpElemNodes (gxFromString "Case")
(xp4Tuple (xpElemNodes (gxFromString "val") xpickle)
(xpElemNodes (gxFromString "cases")
casepickler)
(xpElemAttrs (gxFromString "default")
xpickle)
(xpElemNodes (gxFromString "pos") xpickle)))
retPickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text,
XmlPickler [NodeG [] tag text] exp) =>
PU [NodeG [] tag text] (Transfer exp)
retPickler =
let
revfunc Ret { retVal = val, retPos = pos } = (pos, val)
revfunc _ = error $! "Can't convert"
in
xpWrap (\(pos, val) -> Ret { retVal = val, retPos = pos }, revfunc)
(xpElemNodes (gxFromString "Ret")
(xpPair xpickle
(xpOption (xpElemNodes (gxFromString "val")
xpickle))))
unreachablePickler :: (GenericXMLString tag, Show tag,
GenericXMLString text, Show text) =>
PU [NodeG [] tag text] (Transfer exp)
unreachablePickler =
let
revfunc (Unreachable pos) = pos
revfunc _ = error "cannot convert"
in
xpWrap (Unreachable, revfunc)
(xpElemNodes (gxFromString "Unreachable") xpickle)
instance (GenericXMLString tag, Show tag, GenericXMLString text, Show text,
XmlPickler [NodeG [] tag text] exp) =>
XmlPickler [NodeG [] tag text] (Transfer exp) where
xpickle =
let
picker Goto {} = 0
picker Case {} = 1
picker Ret {} = 2
picker Unreachable {} = 3
in
xpAlt picker [gotoPickler, casePickler, retPickler, unreachablePickler]
| emc2/chill | src/IR/Common/Transfer.hs | bsd-3-clause | 9,810 | 4 | 19 | 2,807 | 2,665 | 1,427 | 1,238 | 180 | 2 |
{-# LANGUAGE CPP, RecordWildCards, OverloadedStrings #-}
module OS.Win
( winOsFromConfig
)
where
import Control.Monad ( void, when )
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
import Development.Shake
import Development.Shake.FilePath
#if !MIN_VERSION_Cabal(1,22,0)
import qualified Distribution.InstalledPackageInfo as C
#endif
import qualified Distribution.Package as C
import Dirs
import LocalCommand
import OS.Internal
import OS.Win.WinPaths
import OS.Win.WinRules
import OS.Win.WinUtils
import Paths
import Types
import Utils
winOsFromConfig :: BuildConfig -> OS
winOsFromConfig BuildConfig{..} = os
where
os = OS{..}
HpVersion{..} = bcHpVersion
GhcVersion{..} = bcGhcVersion
osHpPrefix = winHpPrefix
osGhcPrefix = winGhcPrefix
osGhcLocalInstall =
GhcInstallCustom $ winGhcInstall ghcLocalDir
osGhcTargetInstall =
-- Windows installs HP and GHC in a single directory, so creating
-- dependencies on the contents of winGhcTargetDir won't account
-- for the HP pieces. Also, for Windows, the ghc-bindist/local and
-- the GHC installed into the targetDir should be identical.
-- osTargetAction is the right place to do the targetDir snapshot.
GhcInstallCustom $ \bc distDir -> do
void $ winGhcInstall winGhcTargetDir bc distDir
return ghcLocalDir
osPackageTargetDir p = winHpPrefix </> packagePattern p
-- The ghc builds for Windows do not have pre-built .dyn_hi files
-- (Revisit this in future versions)
osDoShared = False
osPackagePostRegister p = do
let confFile = packageTargetConf p
whenM (doesFileExist confFile) $ pkgrootConfFixup os confFile
osPackageInstallAction p = do
putLoud $ "osPackageInstallAction: " ++ show p
-- "install" the packages into winTargetDir.
--
-- This is not "installing"; this is simply "copying"; later on, we
-- check consistency to be sure. Furthermore, the Shake actions
-- are run in parallel, so registering via ghc-pkg at this point
-- can result in failures, as the conf files need to be installed
-- in dependency order, which cannot be expected due
-- to the parallel builds coupled with laziness in Shake actions.
-- These could possibly be resolved by creating a Rule for the
-- ghc-pkg register, but this might hurt the parallel builds.
let confFile = packageTargetConf p
whenM (doesFileExist confFile) $ do
confStr <- liftIO . B.readFile $ confFile
pkgInfo <- parseConfFile confFile (B8.unpack confStr)
let (C.InstalledPackageId pkgid) = C.installedPackageId pkgInfo
-- need the long name of the package
pkgDbConf = winGhcTargetPackageDbDir </> pkgid <.> "conf"
command_ [] "cp" ["-p", confFile, pkgDbConf]
whenM :: (Monad m) => m Bool -> m () -> m ()
whenM mp m = mp >>= \p -> when p m
osTargetAction = do
-- Now, targetDir is actually ready to snapshot (we skipped doing
-- this in osGhcTargetInstall).
void $ getDirectoryFiles "" [targetDir ++ "//*"]
osGhcDbDir = winGhcPackageDbDir
osGhcPkgHtmlFieldExtras = ["--no-expand-pkgroot"]
osPlatformPkgPathMunge base (HaddockPkgLoc p i) =
HaddockPkgLoc (relativeToDir (expandPkgroot p) base) i
osGhcPkgPathMunge base (HaddockPkgLoc p i) =
HaddockPkgLoc (relativeToDir (expandTopdir p) base) i
osPkgHtmlDir pkgid =
expandPkgroot . expandPrefix . expandPkgid . expandDocdir $ htmldir
where
expandPrefix = replace "$prefix" (targetDir </> osHpPrefix)
expandPkgid = replace "$pkgid" (show pkgid)
expandDocdir = replace "$docdir" docdir
-- On Windows, ghc uses $topdir; and when installed, this is
-- <installdir>/lib
expandTopdir = replace "$topdir" (targetDir </> "lib")
-- On Windows, HP conf files use ${pkgroot}; and when installed this is
-- <installdir>/lib
expandPkgroot = replace "${pkgroot}" (targetDir </> "lib")
replace srchT replc = T.unpack . T.replace srchT (T.pack replc) . T.pack
osDocAction = return ()
osProduct = winProductFile bcIncludeExtra hpVersion bcArch
osRules _rel bc = do
winRules
osProduct %> \_ -> do
need $ [dir ghcLocalDir, targetDir, vdir ghcVirtualTarget]
++ winNeeds
copyWinTargetExtras bc
-- Now, it is time to make sure there are no problems with the
-- conf files copied to
localCommand' [] "ghc-pkg"
[ "recache"
, "--package-db=" ++ winGhcTargetPackageDbDir ]
localCommand' [] "ghc-pkg"
[ "check"
, "--package-db=" ++ winGhcTargetPackageDbDir ]
-- Build installer now; makensis must be run in installerPartsDir
command_ [Cwd installerPartsDir] "makensis" [nsisFileName]
osPackageConfigureExtraArgs _ =
[ "--prefix=" ++ toCabalPrefix osHpPrefix
, "--libsubdir=$pkgid"
, "--datasubdir=$pkgid"
, "--docdir=" ++ docdir
]
htmldir = "$docdir/html"
docdir = "$prefix/doc/$pkgid"
| gbaz/haskell-platform | hptool/src/OS/Win.hs | bsd-3-clause | 5,349 | 0 | 17 | 1,416 | 959 | 511 | 448 | 87 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Playable(
Playable(..)
) where
class Playable a where
sound :: a -> (Double,[Double])
instance Playable (Double,[Double]) where
sound = id
| alpheccar/HaskellViewer | Playable.hs | bsd-3-clause | 194 | 6 | 9 | 38 | 69 | 41 | 28 | 7 | 0 |
module GmState where
import Debug.Trace
import Language
import PrettyPrint
import Parser
import Utils
runProg :: String -> String
runProg = showResults . eval . compile . parse
type GmState =
( GmCode
, GmStack
, GmHeap
, GmGlobals
, GmStats
)
type GmCode = [Instruction]
getCode :: GmState -> GmCode
getCode (i, stack, heap, globals, stats) = i
putCode :: GmCode -> GmState -> GmState
putCode i' (i, stack, heap, globals, stats)
= (i', stack, heap, globals, stats)
data Instruction
= Unwind
| Pushglobal Name
| Pushint Int
| Push Int
| Mkap
| Slide Int
deriving (Eq)
type GmStack = [Addr]
getStack :: GmState -> GmStack
getStack (i, stack, heap, globals, stats) = stack
putStack :: GmStack -> GmState -> GmState
putStack stack' (i, stack, heap, globals, stats)
= (i, stack', heap, globals, stats)
type GmHeap = Heap Node
getHeap :: GmState -> GmHeap
getHeap (i, stack, heap, globals, stats) = heap
putHeap :: GmHeap -> GmState -> GmState
putHeap heap' (i, stack, heap, globals, stats)
= (i, stack, heap', globals, stats)
data Node
= NNum Int -- Numbers
| NAp Addr Addr -- Applicatons
| NGlobal Int GmCode -- Globals
type GmGlobals = ASSOC Name Addr
getGlobals :: GmState -> GmGlobals
getGlobals (i, stack, heap, globals, stats) = globals
type GmStats = Int
statInitial :: GmStats
statInitial = 0
statIncSteps :: GmStats -> GmStats
statIncSteps s = s + 1
statGetSteps :: GmStats -> Int
statGetSteps s = s
getStats :: GmState -> GmStats
getStats (i, stack, heap, globals, stats) = stats
putStats :: GmStats -> GmState -> GmState
putStats stats' (i, stack, heap, globals, stats)
= (i, stack, heap, globals, stats')
showResults :: [GmState] -> String
showResults = undefined
compile :: CoreProgram -> GmState
compile = undefined
eval :: GmState -> [GmState]
eval = undefined
| caasi/spj-book-student-1992 | src/GmState.hs | bsd-3-clause | 1,868 | 0 | 7 | 394 | 643 | 384 | 259 | 65 | 1 |
module Handler.Lists where
import Import
import Yesod.Form.Bootstrap3
import Database.Persist.Sql
import qualified Data.Text as T
import qualified Data.List as L
listForm :: Text -> Text -> AForm Handler List
listForm category username = List
<$> areq textField (bfs ("Name" :: Text)) Nothing
<*> areq hiddenField "" (Just username)
<*> areq hiddenField "" (Just category)
<*> areq hiddenField "" (Just Nothing)
getCompletionValue (Entity lid list) = do
total <- runDB $ count [ItemList ==. lid]
if total == 0
then
return (0, (Entity lid list))
else do
numDone <- runDB $ count [ItemStatus ==. True, ItemList ==. lid]
return ((fromIntegral numDone) / (fromIntegral total) * 100, (Entity lid list))
filterCompletesOut (num, l) = do
if num < 100
then
True
else
False
getLists :: Text -> Text -> Bool -> Bool -> HandlerT App IO Html
getLists category username doFilter showComplete = do
lists <- runDB $ selectList (if doFilter then [ListOwner ==. username, ListCategory ==. category] else [ListCategory ==. category]) [Desc ListId]
(newListForm, enctype) <- generateFormPost $ renderBootstrap3 BootstrapInlineForm (listForm category username)
users <- runDB $ selectList [] [Asc UserName]
let filterName = if doFilter then username else "All"
let pageName = T.unpack $ "Lists"
let postRoute = ListsR
lists' <- mapM getCompletionValue lists
let lists2 = if showComplete then lists' else filter filterCompletesOut lists'
cats <- runDB $ selectList [] [Desc ListId]
let categories = L.nubBy (\(Entity _ x) (Entity _ y) -> listCategory x == listCategory y) cats
defaultLayout $ do
setTitle "Lists"
$(widgetFile "lists")
getListsR :: Text -> Handler Html
getListsR category = do
(Entity _ user) <- requireAuth
getLists category (userName user) False False
getListsFilteredR :: Text -> Bool -> Handler Html
getListsFilteredR category showComplete = do
(Entity _ user) <- requireAuth
getLists category (userName user) False showComplete
getListsForUserR :: Text -> Text -> Handler Html
getListsForUserR category username = getLists category username True False
getListsFilteredForUserR :: Text -> Text -> Bool -> Handler Html
getListsFilteredForUserR category username showComplete = getLists category username True showComplete
postListsR :: Text -> Handler Html
postListsR category = do
(Entity _ user) <- requireAuth
((result, _), _) <- runFormPost $ renderDivs (listForm category $ userName user)
case result of
FormSuccess list -> do
nid <- runDB $ insert list
redirect (ListR nid)
_ -> redirect $ ListsR category
| Ulrar/cstodo | Handler/Lists.hs | bsd-3-clause | 2,659 | 0 | 15 | 526 | 946 | 469 | 477 | 59 | 4 |
module Bench.Pos.Criterion.TxSigningBench
( runBenchmark
) where
import Criterion.Main (Benchmark, bench, defaultConfig,
defaultMainWith, env, whnf)
import Criterion.Types (Config (..))
import Test.QuickCheck (generate)
import Universum
import Pos.Chain.Ssc ()
import Pos.Chain.Txp (TxId, TxSig, TxSigData (..))
import Pos.Crypto (SecretKey, SignTag (SignTx), sign)
import Test.Pos.Chain.Txp.Arbitrary.Unsafe ()
import Test.Pos.Util.QuickCheck.Arbitrary (arbitraryUnsafe)
import Bench.Configuration (benchProtocolMagic)
signTx :: (SecretKey, TxId) -> TxSig
signTx (sk, thash) = sign benchProtocolMagic SignTx sk txSigData
where
txSigData = TxSigData
{ txSigTxHash = thash
}
txSignBench :: Benchmark
txSignBench = env genArgs $ bench "Transactions signing" . whnf signTx
where genArgs = generate $ (,)
<$> arbitraryUnsafe
<*> arbitraryUnsafe
txSignConfig :: Config
txSignConfig = defaultConfig
{ reportFile = Just "txSigning.html"
}
runBenchmark :: IO ()
runBenchmark = defaultMainWith txSignConfig [txSignBench]
| input-output-hk/pos-haskell-prototype | lib/bench/Bench/Pos/Criterion/TxSigningBench.hs | mit | 1,223 | 0 | 10 | 327 | 296 | 178 | 118 | 27 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.MachineLearning.GetBatchPrediction
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a 'BatchPrediction' that includes detailed metadata, status, and
-- data file information for a 'Batch Prediction' request.
--
-- /See:/ <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_GetBatchPrediction.html AWS API Reference> for GetBatchPrediction.
module Network.AWS.MachineLearning.GetBatchPrediction
(
-- * Creating a Request
getBatchPrediction
, GetBatchPrediction
-- * Request Lenses
, gbpBatchPredictionId
-- * Destructuring the Response
, getBatchPredictionResponse
, GetBatchPredictionResponse
-- * Response Lenses
, gbprsStatus
, gbprsLastUpdatedAt
, gbprsCreatedAt
, gbprsInputDataLocationS3
, gbprsMLModelId
, gbprsBatchPredictionDataSourceId
, gbprsBatchPredictionId
, gbprsCreatedByIAMUser
, gbprsName
, gbprsLogURI
, gbprsMessage
, gbprsOutputURI
, gbprsResponseStatus
) where
import Network.AWS.MachineLearning.Types
import Network.AWS.MachineLearning.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'getBatchPrediction' smart constructor.
newtype GetBatchPrediction = GetBatchPrediction'
{ _gbpBatchPredictionId :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetBatchPrediction' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gbpBatchPredictionId'
getBatchPrediction
:: Text -- ^ 'gbpBatchPredictionId'
-> GetBatchPrediction
getBatchPrediction pBatchPredictionId_ =
GetBatchPrediction'
{ _gbpBatchPredictionId = pBatchPredictionId_
}
-- | An ID assigned to the 'BatchPrediction' at creation.
gbpBatchPredictionId :: Lens' GetBatchPrediction Text
gbpBatchPredictionId = lens _gbpBatchPredictionId (\ s a -> s{_gbpBatchPredictionId = a});
instance AWSRequest GetBatchPrediction where
type Rs GetBatchPrediction =
GetBatchPredictionResponse
request = postJSON machineLearning
response
= receiveJSON
(\ s h x ->
GetBatchPredictionResponse' <$>
(x .?> "Status") <*> (x .?> "LastUpdatedAt") <*>
(x .?> "CreatedAt")
<*> (x .?> "InputDataLocationS3")
<*> (x .?> "MLModelId")
<*> (x .?> "BatchPredictionDataSourceId")
<*> (x .?> "BatchPredictionId")
<*> (x .?> "CreatedByIamUser")
<*> (x .?> "Name")
<*> (x .?> "LogUri")
<*> (x .?> "Message")
<*> (x .?> "OutputUri")
<*> (pure (fromEnum s)))
instance ToHeaders GetBatchPrediction where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("AmazonML_20141212.GetBatchPrediction" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON GetBatchPrediction where
toJSON GetBatchPrediction'{..}
= object
(catMaybes
[Just
("BatchPredictionId" .= _gbpBatchPredictionId)])
instance ToPath GetBatchPrediction where
toPath = const "/"
instance ToQuery GetBatchPrediction where
toQuery = const mempty
-- | Represents the output of a GetBatchPrediction operation and describes a
-- 'BatchPrediction'.
--
-- /See:/ 'getBatchPredictionResponse' smart constructor.
data GetBatchPredictionResponse = GetBatchPredictionResponse'
{ _gbprsStatus :: !(Maybe EntityStatus)
, _gbprsLastUpdatedAt :: !(Maybe POSIX)
, _gbprsCreatedAt :: !(Maybe POSIX)
, _gbprsInputDataLocationS3 :: !(Maybe Text)
, _gbprsMLModelId :: !(Maybe Text)
, _gbprsBatchPredictionDataSourceId :: !(Maybe Text)
, _gbprsBatchPredictionId :: !(Maybe Text)
, _gbprsCreatedByIAMUser :: !(Maybe Text)
, _gbprsName :: !(Maybe Text)
, _gbprsLogURI :: !(Maybe Text)
, _gbprsMessage :: !(Maybe Text)
, _gbprsOutputURI :: !(Maybe Text)
, _gbprsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GetBatchPredictionResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gbprsStatus'
--
-- * 'gbprsLastUpdatedAt'
--
-- * 'gbprsCreatedAt'
--
-- * 'gbprsInputDataLocationS3'
--
-- * 'gbprsMLModelId'
--
-- * 'gbprsBatchPredictionDataSourceId'
--
-- * 'gbprsBatchPredictionId'
--
-- * 'gbprsCreatedByIAMUser'
--
-- * 'gbprsName'
--
-- * 'gbprsLogURI'
--
-- * 'gbprsMessage'
--
-- * 'gbprsOutputURI'
--
-- * 'gbprsResponseStatus'
getBatchPredictionResponse
:: Int -- ^ 'gbprsResponseStatus'
-> GetBatchPredictionResponse
getBatchPredictionResponse pResponseStatus_ =
GetBatchPredictionResponse'
{ _gbprsStatus = Nothing
, _gbprsLastUpdatedAt = Nothing
, _gbprsCreatedAt = Nothing
, _gbprsInputDataLocationS3 = Nothing
, _gbprsMLModelId = Nothing
, _gbprsBatchPredictionDataSourceId = Nothing
, _gbprsBatchPredictionId = Nothing
, _gbprsCreatedByIAMUser = Nothing
, _gbprsName = Nothing
, _gbprsLogURI = Nothing
, _gbprsMessage = Nothing
, _gbprsOutputURI = Nothing
, _gbprsResponseStatus = pResponseStatus_
}
-- | The status of the 'BatchPrediction', which can be one of the following
-- values:
--
-- - 'PENDING' - Amazon Machine Learning (Amazon ML) submitted a request
-- to generate batch predictions.
-- - 'INPROGRESS' - The batch predictions are in progress.
-- - 'FAILED' - The request to perform a batch prediction did not run to
-- completion. It is not usable.
-- - 'COMPLETED' - The batch prediction process completed successfully.
-- - 'DELETED' - The 'BatchPrediction' is marked as deleted. It is not
-- usable.
gbprsStatus :: Lens' GetBatchPredictionResponse (Maybe EntityStatus)
gbprsStatus = lens _gbprsStatus (\ s a -> s{_gbprsStatus = a});
-- | The time of the most recent edit to 'BatchPrediction'. The time is
-- expressed in epoch time.
gbprsLastUpdatedAt :: Lens' GetBatchPredictionResponse (Maybe UTCTime)
gbprsLastUpdatedAt = lens _gbprsLastUpdatedAt (\ s a -> s{_gbprsLastUpdatedAt = a}) . mapping _Time;
-- | The time when the 'BatchPrediction' was created. The time is expressed
-- in epoch time.
gbprsCreatedAt :: Lens' GetBatchPredictionResponse (Maybe UTCTime)
gbprsCreatedAt = lens _gbprsCreatedAt (\ s a -> s{_gbprsCreatedAt = a}) . mapping _Time;
-- | The location of the data file or directory in Amazon Simple Storage
-- Service (Amazon S3).
gbprsInputDataLocationS3 :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsInputDataLocationS3 = lens _gbprsInputDataLocationS3 (\ s a -> s{_gbprsInputDataLocationS3 = a});
-- | The ID of the 'MLModel' that generated predictions for the
-- 'BatchPrediction' request.
gbprsMLModelId :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsMLModelId = lens _gbprsMLModelId (\ s a -> s{_gbprsMLModelId = a});
-- | The ID of the 'DataSource' that was used to create the
-- 'BatchPrediction'.
gbprsBatchPredictionDataSourceId :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsBatchPredictionDataSourceId = lens _gbprsBatchPredictionDataSourceId (\ s a -> s{_gbprsBatchPredictionDataSourceId = a});
-- | An ID assigned to the 'BatchPrediction' at creation. This value should
-- be identical to the value of the 'BatchPredictionID' in the request.
gbprsBatchPredictionId :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsBatchPredictionId = lens _gbprsBatchPredictionId (\ s a -> s{_gbprsBatchPredictionId = a});
-- | The AWS user account that invoked the 'BatchPrediction'. The account
-- type can be either an AWS root account or an AWS Identity and Access
-- Management (IAM) user account.
gbprsCreatedByIAMUser :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsCreatedByIAMUser = lens _gbprsCreatedByIAMUser (\ s a -> s{_gbprsCreatedByIAMUser = a});
-- | A user-supplied name or description of the 'BatchPrediction'.
gbprsName :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsName = lens _gbprsName (\ s a -> s{_gbprsName = a});
-- | A link to the file that contains logs of the CreateBatchPrediction
-- operation.
gbprsLogURI :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsLogURI = lens _gbprsLogURI (\ s a -> s{_gbprsLogURI = a});
-- | A description of the most recent details about processing the batch
-- prediction request.
gbprsMessage :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsMessage = lens _gbprsMessage (\ s a -> s{_gbprsMessage = a});
-- | The location of an Amazon S3 bucket or directory to receive the
-- operation results.
gbprsOutputURI :: Lens' GetBatchPredictionResponse (Maybe Text)
gbprsOutputURI = lens _gbprsOutputURI (\ s a -> s{_gbprsOutputURI = a});
-- | The response status code.
gbprsResponseStatus :: Lens' GetBatchPredictionResponse Int
gbprsResponseStatus = lens _gbprsResponseStatus (\ s a -> s{_gbprsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-ml/gen/Network/AWS/MachineLearning/GetBatchPrediction.hs | mpl-2.0 | 10,117 | 0 | 23 | 2,269 | 1,508 | 892 | 616 | 168 | 1 |
module SwiftNav.SBP.Settings where
import Control.Monad
import Control.Monad.Loops
import Data.Binary
import Data.Binary.Get
import Data.Binary.IEEE754
import Data.Binary.Put
import Data.ByteString
import Data.ByteString.Lazy hiding ( ByteString )
import Data.Int
import Data.Word
msgSettingsSave :: Word16
msgSettingsSave = 0x00A1
data MsgSettingsSave = MsgSettingsSave
deriving ( Show, Read, Eq )
instance Binary MsgSettingsSave where
get =
return MsgSettingsSave
put MsgSettingsSave =
return ()
msgSettingsWrite :: Word16
msgSettingsWrite = 0x00A0
data MsgSettingsWrite = MsgSettingsWrite
{ msgSettingsWriteSetting :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgSettingsWrite where
get = do
msgSettingsWriteSetting <- liftM toStrict getRemainingLazyByteString
return MsgSettingsWrite {..}
put MsgSettingsWrite {..} = do
putByteString msgSettingsWriteSetting
msgSettingsReadReq :: Word16
msgSettingsReadReq = 0x00A4
data MsgSettingsReadReq = MsgSettingsReadReq
{ msgSettingsReadReqSetting :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgSettingsReadReq where
get = do
msgSettingsReadReqSetting <- liftM toStrict getRemainingLazyByteString
return MsgSettingsReadReq {..}
put MsgSettingsReadReq {..} = do
putByteString msgSettingsReadReqSetting
msgSettingsReadResp :: Word16
msgSettingsReadResp = 0x00A5
data MsgSettingsReadResp = MsgSettingsReadResp
{ msgSettingsReadRespSetting :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgSettingsReadResp where
get = do
msgSettingsReadRespSetting <- liftM toStrict getRemainingLazyByteString
return MsgSettingsReadResp {..}
put MsgSettingsReadResp {..} = do
putByteString msgSettingsReadRespSetting
msgSettingsReadByIndexReq :: Word16
msgSettingsReadByIndexReq = 0x00A2
data MsgSettingsReadByIndexReq = MsgSettingsReadByIndexReq
{ msgSettingsReadByIndexReqIndex :: Word16
} deriving ( Show, Read, Eq )
instance Binary MsgSettingsReadByIndexReq where
get = do
msgSettingsReadByIndexReqIndex <- getWord16le
return MsgSettingsReadByIndexReq {..}
put MsgSettingsReadByIndexReq {..} = do
putWord16le msgSettingsReadByIndexReqIndex
msgSettingsReadByIndexResp :: Word16
msgSettingsReadByIndexResp = 0x00A7
data MsgSettingsReadByIndexResp = MsgSettingsReadByIndexResp
{ msgSettingsReadByIndexRespIndex :: Word16
, msgSettingsReadByIndexRespSetting :: ByteString
} deriving ( Show, Read, Eq )
instance Binary MsgSettingsReadByIndexResp where
get = do
msgSettingsReadByIndexRespIndex <- getWord16le
msgSettingsReadByIndexRespSetting <- liftM toStrict getRemainingLazyByteString
return MsgSettingsReadByIndexResp {..}
put MsgSettingsReadByIndexResp {..} = do
putWord16le msgSettingsReadByIndexRespIndex
putByteString msgSettingsReadByIndexRespSetting
msgSettingsReadByIndexDone :: Word16
msgSettingsReadByIndexDone = 0x00A6
data MsgSettingsReadByIndexDone = MsgSettingsReadByIndexDone
deriving ( Show, Read, Eq )
instance Binary MsgSettingsReadByIndexDone where
get =
return MsgSettingsReadByIndexDone
put MsgSettingsReadByIndexDone =
return ()
| kovach/libsbp | haskell/src/SwiftNav/SBP/Settings.hs | lgpl-3.0 | 3,189 | 0 | 9 | 476 | 684 | 360 | 324 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
module Haskus.Format.Elf.Dynamic
( RawDynamicEntry (..)
, getRawDynamicEntry
, putRawDynamicEntry
, DynamicEntryFlag (..)
, DynamicEntryFlags
, DynamicEntryType (..)
, DynamicStateFlag (..)
, DynamicStateFlags
, DynamicFeature (..)
, DynamicFeatures
, DynamicPositionalFlag (..)
, DynamicPositionalFlags
)
where
import Haskus.Format.Binary.Word
import Haskus.Format.Binary.Get
import Haskus.Format.Binary.Put
import Haskus.Format.Binary.BitSet (CBitSet,BitSet)
import Haskus.Format.Elf.PreHeader
data RawDynamicEntry = RawDynamicEntry
{ rawDynType :: DynamicEntryType
, rawDynValue :: Word64
}
deriving (Show,Eq)
data DynamicEntryType
= DynTypeNone -- ^ Marks end of dynamic section
| DynTypeNeededLibraryName -- ^ Name of needed library
| DynTypePLTRelocSize -- ^ Size in bytes of PLT relocs
| DynTypePLTGOTAddress -- ^ Processor defined value
| DynTypeSymbolHashTableAddress -- ^ Address of symbol hash table
| DynTypeStringTableAddress -- ^ Address of string table
| DynTypeSymbolTableAddress -- ^ Address of symbol table
| DynTypeRelocaAddress -- ^ Address of Rela relocs
| DynTypeRelocaSize -- ^ Total size of Rela relocs
| DynTypeRelocaEntrySize -- ^ Size of one Rela reloc
| DynTypeStringTableSize -- ^ Size of string table
| DynTypeSymbolEntrySize -- ^ Size of one symbol table entry
| DynTypeInitFunctionAddress -- ^ Address of init function
| DynTypeFiniFunctionAddress -- ^ Address of termination function
| DynTypeSharedObjectName -- ^ Name of shared object
| DynTypeLibrarySearchPathOld -- ^ Library search path (deprecated)
| DynTypeSymbolic -- ^ Start symbol search here
| DynTypeRelocAddress -- ^ Address of Rel relocs
| DynTypeRelocSize -- ^ Total size of Rel relocs
| DynTypeRelocEntrySize -- ^ Size of one Rel reloc
| DynTypePLTRelocType -- ^ Type of reloc in PLT
| DynTypeDebug -- ^ For debugging; unspecified
| DynTypeRelocatableText -- ^ Reloc might modify .text
| DynTypePLTRelocAddress -- ^ Address of PLT relocs
| DynTypeBindNow -- ^ Process relocations of object
| DynTypeInitFunctionArrayAddress -- ^ Array with addresses of init fct
| DynTypeFiniFunctionArrayAddress -- ^ Array with addresses of fini fct
| DynTypeInitFunctionArraySize -- ^ Size in bytes of InitFunctionArray
| DynTypeFiniFunctionArraySize -- ^ Size in bytes of FinFunctionArray
| DynTypeLibrarySearchPath -- ^ Library search path
| DynTypeFlags -- ^ Flags for the object being loaded
-- | DynTypeEncoding -- ^ Start of encoded range
| DynTypePreInitFunctionArrayAddress -- ^ Array with addresses of preinit fct
| DynTypePreInitFunctionArraySize -- ^ Size in bytes of PreInitFunctionArray
| DynTypeGNUPrelinkedTimestamp -- ^ Prelinking timestamp
| DynTypeGNUConflictSize -- ^ Size of conflict section
| DynTypeGNULibraryListSize -- ^ Size of library list
| DynTypeChecksum
| DynTypePLTPaddingSize
| DynTypeMoveEntrySize
| DynTypeMoveSize
| DynTypeFeatureSelection -- ^ Feature selection (DTF_*).
| DynTypePositionalFlags -- ^ Flags effecting the following dynamic entry
| DynTypeSymbolInfoSize -- ^ Size of syminfo table (in bytes)
| DynTypeSymbolInfoEntrySize -- ^ Sizeo of syminfo entry
| DynTypeGNUHashTableAddress -- ^ GNU-style hash table.
| DynTypeTLSDescPLT
| DynTypeTLSDescGOT
| DynTypeGNUConflictSection -- ^ Start of conflict section
| DynTypeGNULibraryList -- ^ Library list
| DynTypeConfigInfo -- ^ Configuration information
| DynTypeDependencyAuditing -- ^ Dependency auditing
| DynTypeObjectAuditing -- ^ Object auditing
| DynTypePLTPadding -- ^ PLT padding
| DynTypeMoveTable -- ^ Move table
| DynTypeSymbolInfoTable -- ^ Syminfo table
| DynTypeSymbolVersion
| DynTypeRelocaCount
| DynTypeRelocCount
| DynTypeStateFlags -- ^ State flags
| DynTypeVersionDefinitionTable -- ^ Address of version definition table
| DynTypeVersionDefinitionCount -- ^ Number of version definitions
| DynTypeVersionNeededTable -- ^ Address of table with needed versions
| DynTypeVersionNeededCount -- ^ Number of needed versions
| DynTypeLoadBefore -- ^ Shared object to load before self
| DynTypeGetValuesFrom -- ^ Shared object to get values from
| DynTypeUnknown Word64 -- ^ Unknown dynamic type
deriving (Show,Eq)
getRawDynamicEntry :: PreHeader -> Get RawDynamicEntry
getRawDynamicEntry pre = do
let (_,_,_,_,gwN) = getGetters pre
RawDynamicEntry
<$> (toDynamicEntryType <$> gwN)
<*> gwN
putRawDynamicEntry :: PreHeader -> RawDynamicEntry -> Put
putRawDynamicEntry pre de = do
let (_,_,_,_,pwN) = getPutters pre
pwN (fromDynamicEntryType $ rawDynType de)
pwN (rawDynValue de)
fromDynamicEntryType :: DynamicEntryType -> Word64
fromDynamicEntryType x = case x of
DynTypeNone -> 0
DynTypeNeededLibraryName -> 1
DynTypePLTRelocSize -> 2
DynTypePLTGOTAddress -> 3
DynTypeSymbolHashTableAddress -> 4
DynTypeStringTableAddress -> 5
DynTypeSymbolTableAddress -> 6
DynTypeRelocaAddress -> 7
DynTypeRelocaSize -> 8
DynTypeRelocaEntrySize -> 9
DynTypeStringTableSize -> 10
DynTypeSymbolEntrySize -> 11
DynTypeInitFunctionAddress -> 12
DynTypeFiniFunctionAddress -> 13
DynTypeSharedObjectName -> 14
DynTypeLibrarySearchPathOld -> 15
DynTypeSymbolic -> 16
DynTypeRelocAddress -> 17
DynTypeRelocSize -> 18
DynTypeRelocEntrySize -> 19
DynTypePLTRelocType -> 20
DynTypeDebug -> 21
DynTypeRelocatableText -> 22
DynTypePLTRelocAddress -> 23
DynTypeBindNow -> 24
DynTypeInitFunctionArrayAddress -> 25
DynTypeFiniFunctionArrayAddress -> 26
DynTypeInitFunctionArraySize -> 27
DynTypeFiniFunctionArraySize -> 28
DynTypeLibrarySearchPath -> 29
DynTypeFlags -> 30
--DynTypeEncoding -> 32
DynTypePreInitFunctionArrayAddress -> 32
DynTypePreInitFunctionArraySize -> 33
DynTypeGNUPrelinkedTimestamp -> 0x6ffffdf5
DynTypeGNUConflictSize -> 0x6ffffdf6
DynTypeGNULibraryListSize -> 0x6ffffdf7
DynTypeChecksum -> 0x6ffffdf8
DynTypePLTPaddingSize -> 0x6ffffdf9
DynTypeMoveEntrySize -> 0x6ffffdfa
DynTypeMoveSize -> 0x6ffffdfb
DynTypeFeatureSelection -> 0x6ffffdfc
DynTypePositionalFlags -> 0x6ffffdfd
DynTypeSymbolInfoSize -> 0x6ffffdfe
DynTypeSymbolInfoEntrySize -> 0x6ffffdff
DynTypeGNUHashTableAddress -> 0x6ffffef5
DynTypeTLSDescPLT -> 0x6ffffef6
DynTypeTLSDescGOT -> 0x6ffffef7
DynTypeGNUConflictSection -> 0x6ffffef8
DynTypeGNULibraryList -> 0x6ffffef9
DynTypeConfigInfo -> 0x6ffffefa
DynTypeDependencyAuditing -> 0x6ffffefb
DynTypeObjectAuditing -> 0x6ffffefc
DynTypePLTPadding -> 0x6ffffefd
DynTypeMoveTable -> 0x6ffffefe
DynTypeSymbolInfoTable -> 0x6ffffeff
DynTypeSymbolVersion -> 0x6ffffff0
DynTypeRelocaCount -> 0x6ffffff9
DynTypeRelocCount -> 0x6ffffffa
DynTypeStateFlags -> 0x6ffffffb
DynTypeVersionDefinitionTable -> 0x6ffffffc
DynTypeVersionDefinitionCount -> 0x6ffffffd
DynTypeVersionNeededTable -> 0x6ffffffe
DynTypeVersionNeededCount -> 0x6fffffff
DynTypeLoadBefore -> 0x7ffffffd
DynTypeGetValuesFrom -> 0x7fffffff
DynTypeUnknown v -> v
toDynamicEntryType :: Word64 -> DynamicEntryType
toDynamicEntryType x = case x of
0 -> DynTypeNone
1 -> DynTypeNeededLibraryName
2 -> DynTypePLTRelocSize
3 -> DynTypePLTGOTAddress
4 -> DynTypeSymbolHashTableAddress
5 -> DynTypeStringTableAddress
6 -> DynTypeSymbolTableAddress
7 -> DynTypeRelocaAddress
8 -> DynTypeRelocaSize
9 -> DynTypeRelocaEntrySize
10 -> DynTypeStringTableSize
11 -> DynTypeSymbolEntrySize
12 -> DynTypeInitFunctionAddress
13 -> DynTypeFiniFunctionAddress
14 -> DynTypeSharedObjectName
15 -> DynTypeLibrarySearchPathOld
16 -> DynTypeSymbolic
17 -> DynTypeRelocAddress
18 -> DynTypeRelocSize
19 -> DynTypeRelocEntrySize
20 -> DynTypePLTRelocType
21 -> DynTypeDebug
22 -> DynTypeRelocatableText
23 -> DynTypePLTRelocAddress
24 -> DynTypeBindNow
25 -> DynTypeInitFunctionArrayAddress
26 -> DynTypeFiniFunctionArrayAddress
27 -> DynTypeInitFunctionArraySize
28 -> DynTypeFiniFunctionArraySize
29 -> DynTypeLibrarySearchPath
30 -> DynTypeFlags
--32 -> DynTypeEncoding
32 -> DynTypePreInitFunctionArrayAddress
33 -> DynTypePreInitFunctionArraySize
0x6ffffdf5 -> DynTypeGNUPrelinkedTimestamp
0x6ffffdf6 -> DynTypeGNUConflictSize
0x6ffffdf7 -> DynTypeGNULibraryListSize
0x6ffffdf8 -> DynTypeChecksum
0x6ffffdf9 -> DynTypePLTPaddingSize
0x6ffffdfa -> DynTypeMoveEntrySize
0x6ffffdfb -> DynTypeMoveSize
0x6ffffdfc -> DynTypeFeatureSelection
0x6ffffdfd -> DynTypePositionalFlags
0x6ffffdfe -> DynTypeSymbolInfoSize
0x6ffffdff -> DynTypeSymbolInfoEntrySize
0x6ffffef5 -> DynTypeGNUHashTableAddress
0x6ffffef6 -> DynTypeTLSDescPLT
0x6ffffef7 -> DynTypeTLSDescGOT
0x6ffffef8 -> DynTypeGNUConflictSection
0x6ffffef9 -> DynTypeGNULibraryList
0x6ffffefa -> DynTypeConfigInfo
0x6ffffefb -> DynTypeDependencyAuditing
0x6ffffefc -> DynTypeObjectAuditing
0x6ffffefd -> DynTypePLTPadding
0x6ffffefe -> DynTypeMoveTable
0x6ffffeff -> DynTypeSymbolInfoTable
0x6ffffff0 -> DynTypeSymbolVersion
0x6ffffff9 -> DynTypeRelocaCount
0x6ffffffa -> DynTypeRelocCount
0x6ffffffb -> DynTypeStateFlags
0x6ffffffc -> DynTypeVersionDefinitionTable
0x6ffffffd -> DynTypeVersionDefinitionCount
0x6ffffffe -> DynTypeVersionNeededTable
0x6fffffff -> DynTypeVersionNeededCount
0x7ffffffd -> DynTypeLoadBefore
0x7fffffff -> DynTypeGetValuesFrom
v -> DynTypeUnknown v
-- | Dynamic entry flags (DynTypeFlags)
data DynamicEntryFlag
= DynFlagOrigin -- ^ Object may use DF_ORIGIN
| DynFlagSymbolic -- ^ Symbol resolutions starts here
| DynFlagHasTextRelocation -- ^ Object contains text relocations
| DynFlagBindNow -- ^ No lazy binding for this object
| DynFlagStaticTLS -- ^ Module uses the static TLS model
deriving (Show,Eq,Enum,CBitSet)
type DynamicEntryFlags = BitSet Word64 DynamicEntryFlag
-- | Dynamic state flags (DynTypeStateFlags)
data DynamicStateFlag
= DynStateFlagNow -- ^ Set RTLD_NOW for this object.
| DynStateFlagGlobal -- ^ Set RTLD_GLOBAL for this object.
| DynStateFlagGroup -- ^ Set RTLD_GROUP for this object.
| DynStateFlagNoDelete -- ^ Set RTLD_NODELETE for this object.
| DynStateFlagLoadFilter -- ^ Trigger filtee loading at runtime.
| DynStateFlagInitFirst -- ^ Set RTLD_INITFIRST for this object
| DynStateFlagNoOpen -- ^ Set RTLD_NOOPEN for this object.
| DynStateFlagOrigin -- ^ $ORIGIN must be handled.
| DynStateFlagDirect -- ^ Direct binding enabled.
| DynStateFlagTrans
| DynStateFlagInterpose -- ^ Object is used to interpose.
| DynStateFlagIgnoreDefaultLibrarySearch -- ^ Ignore default lib search path.
| DynStateFlagNoDump -- ^ Object can't be dldump'ed.
| DynStateFlagAlternativeConfig -- ^ Configuration alternative created.
| DynStateFlagEndFiltee -- ^ Filtee terminates filters search.
| DynStateFlagDispRelocDNE -- ^ Disp reloc applied at build time.
| DynStateFlagDispRelocPND -- ^ Disp reloc applied at run-time.
| DynStateFlagNoDirect -- ^ Object has no-direct binding.
| DynStateFlagIgnoreMultipleDef
| DynStateFlagNoKSymbols
| DynStateFlagNoHeader
| DynStateFlagEdited -- ^ Object is modified after built.
| DynStateFlagNoReloc -- ^
| DynStateFlagSymbolInterposers -- ^ Object has individual interposers.
| DynStateFlagGlobalAudit -- ^ Global auditing required.
| DynStateFlagSingletonSymbols -- ^ Singleton symbols are used.
deriving (Show,Eq,Enum,CBitSet)
type DynamicStateFlags = BitSet Word64 DynamicStateFlag
-- | Features
data DynamicFeature
= DynFeatureParInit
| DynFeatureConfExp
deriving (Show,Eq,Enum,CBitSet)
type DynamicFeatures = BitSet Word64 DynamicFeature
-- | Dynamic positional flags affecting only the next entry
data DynamicPositionalFlag
= DynPositionalFlagLazyLoad -- ^ Lazyload following object
| DynPositionalFlagGroupPerm -- ^ Symbols from next object are not generally available
deriving (Show,Eq,Enum,CBitSet)
type DynamicPositionalFlags = BitSet Word64 DynamicPositionalFlag
| hsyl20/ViperVM | haskus-system/src/lib/Haskus/Format/Elf/Dynamic.hs | bsd-3-clause | 14,556 | 0 | 10 | 4,436 | 1,680 | 968 | 712 | 285 | 66 |
module Parser.InputChecker
( CodeString
, nullCode
, appendCode
, isValidCode
, isExit
, toString
) where
import Control.Monad.Trans.Writer.Lazy(runWriter, tell, Writer)
data CodeString = CodeString { codes :: [String], parenthesesCount :: Int, inString :: Bool } deriving Show
nullCode :: CodeString
nullCode = CodeString [] 0 False
appendCode :: CodeString -> String -> CodeString
appendCode (CodeString codes count inStr) str = CodeString newCodes newCount newInString
where
newCodes = codes ++ [trimed]
((newCount, newInString), trimed) = runWriter $ countParentheses str count inStr
isValidCode :: CodeString -> Bool
isValidCode (CodeString _ count _) = count == 0
isExit :: CodeString -> Bool
isExit (CodeString ("(exit)":_) _ _) = True
isExit _ = False
countParentheses :: String -> Int -> Bool -> Writer String (Int, Bool)
countParentheses "" count isStr = return (count, isStr)
countParentheses str@(c:_) count isStr = do
if c /= '(' && count == 0
then return (0, isStr)
else countIter str count isStr
countIter :: String -> Int -> Bool -> Writer String (Int, Bool)
countIter "" count isStr = return (count, isStr)
countIter (';':str) count False = return (count, False)
countIter ('"':str) count True = do { tell "\""; countIter str count False }
countIter ('"':str) count False = do { tell "\""; countIter str count True }
countIter ('\\':'\"':str) count True = do { tell "\\\""; countIter str count True }
countIter (c:str) count True = do { tell [c]; countIter str count True}
countIter (c:str) count isStr = do
tell [c]
let m = count + par2Num c
if m == 0
then return (0, False)
else countIter str m isStr
par2Num :: Char -> Int
par2Num '(' = 1
par2Num ')' = (-1)
par2Num _ = 0
toString :: CodeString -> String
toString (CodeString cs _ _) = foldl (\x y -> x ++ " " ++ y) "" cs
| YuichiroSato/Scheme | src/Parser/InputChecker.hs | bsd-3-clause | 1,854 | 0 | 11 | 366 | 760 | 404 | 356 | 45 | 2 |
{-
The overall structure of the GHC Prelude is a bit tricky.
a) We want to avoid "orphan modules", i.e. ones with instance
decls that don't belong either to a tycon or a class
defined in the same module
b) We want to avoid giant modules
So the rough structure is as follows, in (linearised) dependency order
GHC.Prim Has no implementation. It defines built-in things, and
by importing it you bring them into scope.
The source file is GHC.Prim.hi-boot, which is just
copied to make GHC.Prim.hi
GHC.Base Classes: Eq, Ord, Functor, Monad
Types: list, (), Int, Bool, Ordering, Char, String
Data.Tuple Types: tuples, plus instances for GHC.Base classes
GHC.Show Class: Show, plus instances for GHC.Base/GHC.Tup types
GHC.Enum Class: Enum, plus instances for GHC.Base/GHC.Tup types
Data.Maybe Type: Maybe, plus instances for GHC.Base classes
GHC.List List functions
GHC.Num Class: Num, plus instances for Int
Type: Integer, plus instances for all classes so far (Eq, Ord, Num, Show)
Integer is needed here because it is mentioned in the signature
of 'fromInteger' in class Num
GHC.Real Classes: Real, Integral, Fractional, RealFrac
plus instances for Int, Integer
Types: Ratio, Rational
plus intances for classes so far
Rational is needed here because it is mentioned in the signature
of 'toRational' in class Real
GHC.ST The ST monad, instances and a few helper functions
Ix Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples
GHC.Arr Types: Array, MutableArray, MutableVar
Arrays are used by a function in GHC.Float
GHC.Float Classes: Floating, RealFloat
Types: Float, Double, plus instances of all classes so far
This module contains everything to do with floating point.
It is a big module (900 lines)
With a bit of luck, many modules can be compiled without ever reading GHC.Float.hi
Other Prelude modules are much easier with fewer complex dependencies.
-}
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, BangPatterns
, ExplicitForAll
, MagicHash
, UnboxedTuples
, ExistentialQuantification
, RankNTypes
#-}
-- -fno-warn-orphans is needed for things like:
-- Orphan rule: "x# -# x#" ALWAYS forall x# :: Int# -# x# x# = 0
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Base
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- Basic data types and classes.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Base
(
module GHC.Base,
module GHC.Classes,
module GHC.CString,
module GHC.Magic,
module GHC.Types,
module GHC.Prim, -- Re-export GHC.Prim and [boot] GHC.Err,
-- to avoid lots of people having to
module GHC.Err -- import it explicitly
)
where
import GHC.Types
import GHC.Classes
import GHC.CString
import GHC.Magic
import GHC.Prim
import GHC.Err
import {-# SOURCE #-} GHC.IO (failIO,mplusIO)
import GHC.Tuple () -- Note [Depend on GHC.Tuple]
import GHC.Integer () -- Note [Depend on GHC.Integer]
infixr 9 .
infixr 5 ++
infixl 4 <$
infixl 1 >>, >>=
infixr 1 =<<
infixr 0 $, $!
infixl 4 <*>, <*, *>, <**>
default () -- Double isn't available yet
{-
Note [Depend on GHC.Integer]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Integer type is special because TidyPgm uses
GHC.Integer.Type.mkInteger to construct Integer literal values
Currently it reads the interface file whether or not the current
module *has* any Integer literals, so it's important that
GHC.Integer.Type (in package integer-gmp or integer-simple) is
compiled before any other module. (There's a hack in GHC to disable
this for packages ghc-prim, integer-gmp, integer-simple, which aren't
allowed to contain any Integer literals.)
Likewise we implicitly need Integer when deriving things like Eq
instances.
The danger is that if the build system doesn't know about the dependency
on Integer, it'll compile some base module before GHC.Integer.Type,
resulting in:
Failed to load interface for ‘GHC.Integer.Type’
There are files missing in the ‘integer-gmp’ package,
Bottom line: we make GHC.Base depend on GHC.Integer; and everything
else either depends on GHC.Base, or does not have NoImplicitPrelude
(and hence depends on Prelude).
Note [Depend on GHC.Tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Similarly, tuple syntax (or ()) creates an implicit dependency on
GHC.Tuple, so we use the same rule as for Integer --- see Note [Depend on
GHC.Integer] --- to explain this to the build system. We make GHC.Base
depend on GHC.Tuple, and everything else depends on GHC.Base or Prelude.
-}
#if 0
-- for use when compiling GHC.Base itself doesn't work
data Bool = False | True
data Ordering = LT | EQ | GT
data Char = C# Char#
type String = [Char]
data Int = I# Int#
data () = ()
data [] a = MkNil
not True = False
(&&) True True = True
otherwise = True
build = error "urk"
foldr = error "urk"
#endif
-- | The 'Maybe' type encapsulates an optional value. A value of type
-- @'Maybe' a@ either contains a value of type @a@ (represented as @'Just' a@),
-- or it is empty (represented as 'Nothing'). Using 'Maybe' is a good way to
-- deal with errors or exceptional cases without resorting to drastic
-- measures such as 'error'.
--
-- The 'Maybe' type is also a monad. It is a simple kind of error
-- monad, where all errors are represented by 'Nothing'. A richer
-- error monad can be built using the 'Data.Either.Either' type.
--
data Maybe a = Nothing | Just a
deriving (Eq, Ord)
-- | The class of monoids (types with an associative binary operation that
-- has an identity). Instances should satisfy the following laws:
--
-- * @mappend mempty x = x@
--
-- * @mappend x mempty = x@
--
-- * @mappend x (mappend y z) = mappend (mappend x y) z@
--
-- * @mconcat = 'foldr' mappend mempty@
--
-- The method names refer to the monoid of lists under concatenation,
-- but there are many other instances.
--
-- Some types can be viewed as a monoid in more than one way,
-- e.g. both addition and multiplication on numbers.
-- In such cases we often define @newtype@s and make those instances
-- of 'Monoid', e.g. 'Sum' and 'Product'.
class Monoid a where
mempty :: a
-- ^ Identity of 'mappend'
mappend :: a -> a -> a
-- ^ An associative operation
mconcat :: [a] -> a
-- ^ Fold a list using the monoid.
-- For most types, the default definition for 'mconcat' will be
-- used, but the function is included in the class definition so
-- that an optimized version can be provided for specific types.
mconcat = foldr mappend mempty
instance Monoid [a] where
{-# INLINE mempty #-}
mempty = []
{-# INLINE mappend #-}
mappend = (++)
{-# INLINE mconcat #-}
mconcat xss = [x | xs <- xss, x <- xs]
-- See Note: [List comprehensions and inlining]
{-
Note: [List comprehensions and inlining]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The list monad operations are traditionally described in terms of concatMap:
xs >>= f = concatMap f xs
Similarly, mconcat for lists is just concat. Here in Base, however, we don't
have concatMap, and we'll refrain from adding it here so it won't have to be
hidden in imports. Instead, we use GHC's list comprehension desugaring
mechanism to define mconcat and the Applicative and Monad instances for lists.
We mark them INLINE because the inliner is not generally too keen to inline
build forms such as the ones these desugar to without our insistence. Defining
these using list comprehensions instead of foldr has an additional potential
benefit, as described in compiler/deSugar/DsListComp.lhs: if optimizations
needed to make foldr/build forms efficient are turned off, we'll get reasonably
efficient translations anyway.
-}
instance Monoid b => Monoid (a -> b) where
mempty _ = mempty
mappend f g x = f x `mappend` g x
instance Monoid () where
-- Should it be strict?
mempty = ()
_ `mappend` _ = ()
mconcat _ = ()
instance (Monoid a, Monoid b) => Monoid (a,b) where
mempty = (mempty, mempty)
(a1,b1) `mappend` (a2,b2) =
(a1 `mappend` a2, b1 `mappend` b2)
instance (Monoid a, Monoid b, Monoid c) => Monoid (a,b,c) where
mempty = (mempty, mempty, mempty)
(a1,b1,c1) `mappend` (a2,b2,c2) =
(a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2)
instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a,b,c,d) where
mempty = (mempty, mempty, mempty, mempty)
(a1,b1,c1,d1) `mappend` (a2,b2,c2,d2) =
(a1 `mappend` a2, b1 `mappend` b2,
c1 `mappend` c2, d1 `mappend` d2)
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) =>
Monoid (a,b,c,d,e) where
mempty = (mempty, mempty, mempty, mempty, mempty)
(a1,b1,c1,d1,e1) `mappend` (a2,b2,c2,d2,e2) =
(a1 `mappend` a2, b1 `mappend` b2, c1 `mappend` c2,
d1 `mappend` d2, e1 `mappend` e2)
-- lexicographical ordering
instance Monoid Ordering where
mempty = EQ
LT `mappend` _ = LT
EQ `mappend` y = y
GT `mappend` _ = GT
-- | Lift a semigroup into 'Maybe' forming a 'Monoid' according to
-- <http://en.wikipedia.org/wiki/Monoid>: \"Any semigroup @S@ may be
-- turned into a monoid simply by adjoining an element @e@ not in @S@
-- and defining @e*e = e@ and @e*s = s = s*e@ for all @s ∈ S@.\" Since
-- there is no \"Semigroup\" typeclass providing just 'mappend', we
-- use 'Monoid' instead.
instance Monoid a => Monoid (Maybe a) where
mempty = Nothing
Nothing `mappend` m = m
m `mappend` Nothing = m
Just m1 `mappend` Just m2 = Just (m1 `mappend` m2)
instance Monoid a => Applicative ((,) a) where
pure x = (mempty, x)
(u, f) <*> (v, x) = (u `mappend` v, f x)
instance Monoid a => Monad ((,) a) where
(u, a) >>= k = case k a of (v, b) -> (u `mappend` v, b)
instance Monoid a => Monoid (IO a) where
mempty = pure mempty
mappend = liftA2 mappend
{- | The 'Functor' class is used for types that can be mapped over.
Instances of 'Functor' should satisfy the following laws:
> fmap id == id
> fmap (f . g) == fmap f . fmap g
The instances of 'Functor' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
satisfy these laws.
-}
class Functor f where
fmap :: (a -> b) -> f a -> f b
-- | Replace all locations in the input with the same value.
-- The default definition is @'fmap' . 'const'@, but this may be
-- overridden with a more efficient version.
(<$) :: a -> f b -> f a
(<$) = fmap . const
-- | A functor with application, providing operations to
--
-- * embed pure expressions ('pure'), and
--
-- * sequence computations and combine their results ('<*>').
--
-- A minimal complete definition must include implementations of these
-- functions satisfying the following laws:
--
-- [/identity/]
--
-- @'pure' 'id' '<*>' v = v@
--
-- [/composition/]
--
-- @'pure' (.) '<*>' u '<*>' v '<*>' w = u '<*>' (v '<*>' w)@
--
-- [/homomorphism/]
--
-- @'pure' f '<*>' 'pure' x = 'pure' (f x)@
--
-- [/interchange/]
--
-- @u '<*>' 'pure' y = 'pure' ('$' y) '<*>' u@
--
-- The other methods have the following default definitions, which may
-- be overridden with equivalent specialized implementations:
--
-- * @u '*>' v = 'pure' ('const' 'id') '<*>' u '<*>' v@
--
-- * @u '<*' v = 'pure' 'const' '<*>' u '<*>' v@
--
-- As a consequence of these laws, the 'Functor' instance for @f@ will satisfy
--
-- * @'fmap' f x = 'pure' f '<*>' x@
--
-- If @f@ is also a 'Monad', it should satisfy
--
-- * @'pure' = 'return'@
--
-- * @('<*>') = 'ap'@
--
-- (which implies that 'pure' and '<*>' satisfy the applicative functor laws).
class Functor f => Applicative f where
-- | Lift a value.
pure :: a -> f a
-- | Sequential application.
(<*>) :: f (a -> b) -> f a -> f b
-- | Sequence actions, discarding the value of the first argument.
(*>) :: f a -> f b -> f b
a1 *> a2 = (id <$ a1) <*> a2
-- This is essentially the same as liftA2 (const id), but if the
-- Functor instance has an optimized (<$), we want to use that instead.
-- | Sequence actions, discarding the value of the second argument.
(<*) :: f a -> f b -> f a
(<*) = liftA2 const
-- | A variant of '<*>' with the arguments reversed.
(<**>) :: Applicative f => f a -> f (a -> b) -> f b
(<**>) = liftA2 (flip ($))
-- | Lift a function to actions.
-- This function may be used as a value for `fmap` in a `Functor` instance.
liftA :: Applicative f => (a -> b) -> f a -> f b
liftA f a = pure f <*> a
-- Caution: since this may be used for `fmap`, we can't use the obvious
-- definition of liftA = fmap.
-- | Lift a binary function to actions.
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
liftA2 f a b = fmap f a <*> b
-- | Lift a ternary function to actions.
liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
liftA3 f a b c = fmap f a <*> b <*> c
{-# INLINEABLE liftA #-}
{-# SPECIALISE liftA :: (a1->r) -> IO a1 -> IO r #-}
{-# SPECIALISE liftA :: (a1->r) -> Maybe a1 -> Maybe r #-}
{-# INLINEABLE liftA2 #-}
{-# SPECIALISE liftA2 :: (a1->a2->r) -> IO a1 -> IO a2 -> IO r #-}
{-# SPECIALISE liftA2 :: (a1->a2->r) -> Maybe a1 -> Maybe a2 -> Maybe r #-}
{-# INLINEABLE liftA3 #-}
{-# SPECIALISE liftA3 :: (a1->a2->a3->r) -> IO a1 -> IO a2 -> IO a3 -> IO r #-}
{-# SPECIALISE liftA3 :: (a1->a2->a3->r) ->
Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe r #-}
-- | The 'join' function is the conventional monad join operator. It
-- is used to remove one level of monadic structure, projecting its
-- bound argument into the outer level.
join :: (Monad m) => m (m a) -> m a
join x = x >>= id
{- | The 'Monad' class defines the basic operations over a /monad/,
a concept from a branch of mathematics known as /category theory/.
From the perspective of a Haskell programmer, however, it is best to
think of a monad as an /abstract datatype/ of actions.
Haskell's @do@ expressions provide a convenient syntax for writing
monadic expressions.
Instances of 'Monad' should satisfy the following laws:
* @'return' a '>>=' k = k a@
* @m '>>=' 'return' = m@
* @m '>>=' (\x -> k x '>>=' h) = (m '>>=' k) '>>=' h@
Furthermore, the 'Monad' and 'Applicative' operations should relate as follows:
* @'pure' = 'return'@
* @('<*>') = 'ap'@
The above laws imply:
* @'fmap' f xs = xs '>>=' 'return' . f@
* @('>>') = ('*>')@
and that 'pure' and ('<*>') satisfy the applicative functor laws.
The instances of 'Monad' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
defined in the "Prelude" satisfy these laws.
-}
class Applicative m => Monad m where
-- | Sequentially compose two actions, passing any value produced
-- by the first as an argument to the second.
(>>=) :: forall a b. m a -> (a -> m b) -> m b
-- | Sequentially compose two actions, discarding any value produced
-- by the first, like sequencing operators (such as the semicolon)
-- in imperative languages.
(>>) :: forall a b. m a -> m b -> m b
m >> k = m >>= \_ -> k -- See Note [Recursive bindings for Applicative/Monad]
{-# INLINE (>>) #-}
-- | Inject a value into the monadic type.
return :: a -> m a
return = pure
-- | Fail with a message. This operation is not part of the
-- mathematical definition of a monad, but is invoked on pattern-match
-- failure in a @do@ expression.
--
-- As part of the MonadFail proposal (MFP), this function is moved
-- to its own class 'MonadFail' (see "Control.Monad.Fail" for more
-- details). The definition here will be removed in a future
-- release.
fail :: String -> m a
fail s = error s
{- Note [Recursive bindings for Applicative/Monad]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The original Applicative/Monad proposal stated that after
implementation, the designated implementation of (>>) would become
(>>) :: forall a b. m a -> m b -> m b
(>>) = (*>)
by default. You might be inclined to change this to reflect the stated
proposal, but you really shouldn't! Why? Because people tend to define
such instances the /other/ way around: in particular, it is perfectly
legitimate to define an instance of Applicative (*>) in terms of (>>),
which would lead to an infinite loop for the default implementation of
Monad! And people do this in the wild.
This turned into a nasty bug that was tricky to track down, and rather
than eliminate it everywhere upstream, it's easier to just retain the
original default.
-}
-- | Same as '>>=', but with the arguments interchanged.
{-# SPECIALISE (=<<) :: (a -> [b]) -> [a] -> [b] #-}
(=<<) :: Monad m => (a -> m b) -> m a -> m b
f =<< x = x >>= f
-- | Conditional execution of 'Applicative' expressions. For example,
--
-- > when debug (putStrLn "Debugging")
--
-- will output the string @Debugging@ if the Boolean value @debug@
-- is 'True', and otherwise do nothing.
when :: (Applicative f) => Bool -> f () -> f ()
{-# INLINEABLE when #-}
{-# SPECIALISE when :: Bool -> IO () -> IO () #-}
{-# SPECIALISE when :: Bool -> Maybe () -> Maybe () #-}
when p s = if p then s else pure ()
-- | Evaluate each action in the sequence from left to right,
-- and collect the results.
sequence :: Monad m => [m a] -> m [a]
{-# INLINE sequence #-}
sequence = mapM id
-- Note: [sequence and mapM]
-- | @'mapM' f@ is equivalent to @'sequence' . 'map' f@.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
{-# INLINE mapM #-}
mapM f as = foldr k (return []) as
where
k a r = do { x <- f a; xs <- r; return (x:xs) }
{-
Note: [sequence and mapM]
~~~~~~~~~~~~~~~~~~~~~~~~~
Originally, we defined
mapM f = sequence . map f
This relied on list fusion to produce efficient code for mapM, and led to
excessive allocation in cryptarithm2. Defining
sequence = mapM id
relies only on inlining a tiny function (id) and beta reduction, which tends to
be a more reliable aspect of simplification. Indeed, this does not lead to
similar problems in nofib.
-}
-- | Promote a function to a monad.
liftM :: (Monad m) => (a1 -> r) -> m a1 -> m r
liftM f m1 = do { x1 <- m1; return (f x1) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right. For example,
--
-- > liftM2 (+) [0,1] [0,2] = [0,2,1,3]
-- > liftM2 (+) (Just 1) Nothing = Nothing
--
liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2 = do { x1 <- m1; x2 <- m2; return (f x1 x2) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM3 :: (Monad m) => (a1 -> a2 -> a3 -> r) -> m a1 -> m a2 -> m a3 -> m r
liftM3 f m1 m2 m3 = do { x1 <- m1; x2 <- m2; x3 <- m3; return (f x1 x2 x3) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM4 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m r
liftM4 f m1 m2 m3 m4 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; return (f x1 x2 x3 x4) }
-- | Promote a function to a monad, scanning the monadic arguments from
-- left to right (cf. 'liftM2').
liftM5 :: (Monad m) => (a1 -> a2 -> a3 -> a4 -> a5 -> r) -> m a1 -> m a2 -> m a3 -> m a4 -> m a5 -> m r
liftM5 f m1 m2 m3 m4 m5 = do { x1 <- m1; x2 <- m2; x3 <- m3; x4 <- m4; x5 <- m5; return (f x1 x2 x3 x4 x5) }
{-# INLINEABLE liftM #-}
{-# SPECIALISE liftM :: (a1->r) -> IO a1 -> IO r #-}
{-# SPECIALISE liftM :: (a1->r) -> Maybe a1 -> Maybe r #-}
{-# INLINEABLE liftM2 #-}
{-# SPECIALISE liftM2 :: (a1->a2->r) -> IO a1 -> IO a2 -> IO r #-}
{-# SPECIALISE liftM2 :: (a1->a2->r) -> Maybe a1 -> Maybe a2 -> Maybe r #-}
{-# INLINEABLE liftM3 #-}
{-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> IO a1 -> IO a2 -> IO a3 -> IO r #-}
{-# SPECIALISE liftM3 :: (a1->a2->a3->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe r #-}
{-# INLINEABLE liftM4 #-}
{-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO r #-}
{-# SPECIALISE liftM4 :: (a1->a2->a3->a4->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe r #-}
{-# INLINEABLE liftM5 #-}
{-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> IO a1 -> IO a2 -> IO a3 -> IO a4 -> IO a5 -> IO r #-}
{-# SPECIALISE liftM5 :: (a1->a2->a3->a4->a5->r) -> Maybe a1 -> Maybe a2 -> Maybe a3 -> Maybe a4 -> Maybe a5 -> Maybe r #-}
{- | In many situations, the 'liftM' operations can be replaced by uses of
'ap', which promotes function application.
> return f `ap` x1 `ap` ... `ap` xn
is equivalent to
> liftMn f x1 x2 ... xn
-}
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap m1 m2 = do { x1 <- m1; x2 <- m2; return (x1 x2) }
-- Since many Applicative instances define (<*>) = ap, we
-- cannot define ap = (<*>)
{-# INLINEABLE ap #-}
{-# SPECIALISE ap :: IO (a -> b) -> IO a -> IO b #-}
{-# SPECIALISE ap :: Maybe (a -> b) -> Maybe a -> Maybe b #-}
-- instances for Prelude types
instance Functor ((->) r) where
fmap = (.)
instance Applicative ((->) a) where
pure = const
(<*>) f g x = f x (g x)
instance Monad ((->) r) where
f >>= k = \ r -> k (f r) r
instance Functor ((,) a) where
fmap f (x,y) = (x, f y)
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
instance Applicative Maybe where
pure = Just
Just f <*> m = fmap f m
Nothing <*> _m = Nothing
Just _m1 *> m2 = m2
Nothing *> _m2 = Nothing
instance Monad Maybe where
(Just x) >>= k = k x
Nothing >>= _ = Nothing
(>>) = (*>)
fail _ = Nothing
-- -----------------------------------------------------------------------------
-- The Alternative class definition
infixl 3 <|>
-- | A monoid on applicative functors.
--
-- If defined, 'some' and 'many' should be the least solutions
-- of the equations:
--
-- * @some v = (:) '<$>' v '<*>' many v@
--
-- * @many v = some v '<|>' 'pure' []@
class Applicative f => Alternative f where
-- | The identity of '<|>'
empty :: f a
-- | An associative binary operation
(<|>) :: f a -> f a -> f a
-- | One or more.
some :: f a -> f [a]
some v = some_v
where
many_v = some_v <|> pure []
some_v = (fmap (:) v) <*> many_v
-- | Zero or more.
many :: f a -> f [a]
many v = many_v
where
many_v = some_v <|> pure []
some_v = (fmap (:) v) <*> many_v
instance Alternative Maybe where
empty = Nothing
Nothing <|> r = r
l <|> _ = l
-- -----------------------------------------------------------------------------
-- The MonadPlus class definition
-- | Monads that also support choice and failure.
class (Alternative m, Monad m) => MonadPlus m where
-- | the identity of 'mplus'. It should also satisfy the equations
--
-- > mzero >>= f = mzero
-- > v >> mzero = mzero
--
mzero :: m a
mzero = empty
-- | an associative operation
mplus :: m a -> m a -> m a
mplus = (<|>)
instance MonadPlus Maybe
----------------------------------------------
-- The list type
instance Functor [] where
{-# INLINE fmap #-}
fmap = map
-- See Note: [List comprehensions and inlining]
instance Applicative [] where
{-# INLINE pure #-}
pure x = [x]
{-# INLINE (<*>) #-}
fs <*> xs = [f x | f <- fs, x <- xs]
{-# INLINE (*>) #-}
xs *> ys = [y | _ <- xs, y <- ys]
-- See Note: [List comprehensions and inlining]
instance Monad [] where
{-# INLINE (>>=) #-}
xs >>= f = [y | x <- xs, y <- f x]
{-# INLINE (>>) #-}
(>>) = (*>)
{-# INLINE fail #-}
fail _ = []
instance Alternative [] where
empty = []
(<|>) = (++)
instance MonadPlus []
{-
A few list functions that appear here because they are used here.
The rest of the prelude list functions are in GHC.List.
-}
----------------------------------------------
-- foldr/build/augment
----------------------------------------------
-- | 'foldr', applied to a binary operator, a starting value (typically
-- the right-identity of the operator), and a list, reduces the list
-- using the binary operator, from right to left:
--
-- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
foldr :: (a -> b -> b) -> b -> [a] -> b
-- foldr _ z [] = z
-- foldr f z (x:xs) = f x (foldr f z xs)
{-# INLINE [0] foldr #-}
-- Inline only in the final stage, after the foldr/cons rule has had a chance
-- Also note that we inline it when it has *two* parameters, which are the
-- ones we are keen about specialising!
foldr k z = go
where
go [] = z
go (y:ys) = y `k` go ys
-- | A list producer that can be fused with 'foldr'.
-- This function is merely
--
-- > build g = g (:) []
--
-- but GHC's simplifier will transform an expression of the form
-- @'foldr' k z ('build' g)@, which may arise after inlining, to @g k z@,
-- which avoids producing an intermediate list.
build :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
{-# INLINE [1] build #-}
-- The INLINE is important, even though build is tiny,
-- because it prevents [] getting inlined in the version that
-- appears in the interface file. If [] *is* inlined, it
-- won't match with [] appearing in rules in an importing module.
--
-- The "1" says to inline in phase 1
build g = g (:) []
-- | A list producer that can be fused with 'foldr'.
-- This function is merely
--
-- > augment g xs = g (:) xs
--
-- but GHC's simplifier will transform an expression of the form
-- @'foldr' k z ('augment' g xs)@, which may arise after inlining, to
-- @g k ('foldr' k z xs)@, which avoids producing an intermediate list.
augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]
{-# INLINE [1] augment #-}
augment g xs = g (:) xs
{-# RULES
"fold/build" forall k z (g::forall b. (a->b->b) -> b -> b) .
foldr k z (build g) = g k z
"foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) .
foldr k z (augment g xs) = g k (foldr k z xs)
"foldr/id" foldr (:) [] = \x -> x
"foldr/app" [1] forall ys. foldr (:) ys = \xs -> xs ++ ys
-- Only activate this from phase 1, because that's
-- when we disable the rule that expands (++) into foldr
-- The foldr/cons rule looks nice, but it can give disastrously
-- bloated code when commpiling
-- array (a,b) [(1,2), (2,2), (3,2), ...very long list... ]
-- i.e. when there are very very long literal lists
-- So I've disabled it for now. We could have special cases
-- for short lists, I suppose.
-- "foldr/cons" forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)
"foldr/single" forall k z x. foldr k z [x] = k x z
"foldr/nil" forall k z. foldr k z [] = z
"foldr/cons/build" forall k z x (g::forall b. (a->b->b) -> b -> b) .
foldr k z (x:build g) = k x (g k z)
"augment/build" forall (g::forall b. (a->b->b) -> b -> b)
(h::forall b. (a->b->b) -> b -> b) .
augment g (build h) = build (\c n -> g c (h c n))
"augment/nil" forall (g::forall b. (a->b->b) -> b -> b) .
augment g [] = build g
#-}
-- This rule is true, but not (I think) useful:
-- augment g (augment h t) = augment (\cn -> g c (h c n)) t
----------------------------------------------
-- map
----------------------------------------------
-- | 'map' @f xs@ is the list obtained by applying @f@ to each element
-- of @xs@, i.e.,
--
-- > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
-- > map f [x1, x2, ...] == [f x1, f x2, ...]
map :: (a -> b) -> [a] -> [b]
{-# NOINLINE [0] map #-}
-- We want the RULEs "map" and "map/coerce" to fire first.
-- map is recursive, so won't inline anyway,
-- but saying so is more explicit, and silences warnings
map _ [] = []
map f (x:xs) = f x : map f xs
-- Note eta expanded
mapFB :: (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst
{-# INLINE [0] mapFB #-}
mapFB c f = \x ys -> c (f x) ys
-- The rules for map work like this.
--
-- Up to (but not including) phase 1, we use the "map" rule to
-- rewrite all saturated applications of map with its build/fold
-- form, hoping for fusion to happen.
-- In phase 1 and 0, we switch off that rule, inline build, and
-- switch on the "mapList" rule, which rewrites the foldr/mapFB
-- thing back into plain map.
--
-- It's important that these two rules aren't both active at once
-- (along with build's unfolding) else we'd get an infinite loop
-- in the rules. Hence the activation control below.
--
-- The "mapFB" rule optimises compositions of map.
--
-- This same pattern is followed by many other functions:
-- e.g. append, filter, iterate, repeat, etc.
{-# RULES
"map" [~1] forall f xs. map f xs = build (\c n -> foldr (mapFB c f) n xs)
"mapList" [1] forall f. foldr (mapFB (:) f) [] = map f
"mapFB" forall c f g. mapFB (mapFB c f) g = mapFB c (f.g)
#-}
-- See Breitner, Eisenberg, Peyton Jones, and Weirich, "Safe Zero-cost
-- Coercions for Haskell", section 6.5:
-- http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/coercible.pdf
{-# RULES "map/coerce" [1] map coerce = coerce #-}
----------------------------------------------
-- append
----------------------------------------------
-- | Append two lists, i.e.,
--
-- > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
-- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--
-- If the first list is not finite, the result is the first list.
(++) :: [a] -> [a] -> [a]
{-# NOINLINE [1] (++) #-} -- We want the RULE to fire first.
-- It's recursive, so won't inline anyway,
-- but saying so is more explicit
(++) [] ys = ys
(++) (x:xs) ys = x : xs ++ ys
{-# RULES
"++" [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys
#-}
-- |'otherwise' is defined as the value 'True'. It helps to make
-- guards more readable. eg.
--
-- > f x | x < 0 = ...
-- > | otherwise = ...
otherwise :: Bool
otherwise = True
----------------------------------------------
-- Type Char and String
----------------------------------------------
-- | A 'String' is a list of characters. String constants in Haskell are values
-- of type 'String'.
--
type String = [Char]
unsafeChr :: Int -> Char
unsafeChr (I# i#) = C# (chr# i#)
-- | The 'Prelude.fromEnum' method restricted to the type 'Data.Char.Char'.
ord :: Char -> Int
ord (C# c#) = I# (ord# c#)
-- | This 'String' equality predicate is used when desugaring
-- pattern-matches against strings.
eqString :: String -> String -> Bool
eqString [] [] = True
eqString (c1:cs1) (c2:cs2) = c1 == c2 && cs1 `eqString` cs2
eqString _ _ = False
{-# RULES "eqString" (==) = eqString #-}
-- eqString also has a BuiltInRule in PrelRules.lhs:
-- eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2
----------------------------------------------
-- 'Int' related definitions
----------------------------------------------
maxInt, minInt :: Int
{- Seems clumsy. Should perhaps put minInt and MaxInt directly into MachDeps.h -}
#if WORD_SIZE_IN_BITS == 31
minInt = I# (-0x40000000#)
maxInt = I# 0x3FFFFFFF#
#elif WORD_SIZE_IN_BITS == 32
minInt = I# (-0x80000000#)
maxInt = I# 0x7FFFFFFF#
#else
minInt = I# (-0x8000000000000000#)
maxInt = I# 0x7FFFFFFFFFFFFFFF#
#endif
----------------------------------------------
-- The function type
----------------------------------------------
-- | Identity function.
id :: a -> a
id x = x
-- Assertion function. This simply ignores its boolean argument.
-- The compiler may rewrite it to @('assertError' line)@.
-- | If the first argument evaluates to 'True', then the result is the
-- second argument. Otherwise an 'AssertionFailed' exception is raised,
-- containing a 'String' with the source file and line number of the
-- call to 'assert'.
--
-- Assertions can normally be turned on or off with a compiler flag
-- (for GHC, assertions are normally on unless optimisation is turned on
-- with @-O@ or the @-fignore-asserts@
-- option is given). When assertions are turned off, the first
-- argument to 'assert' is ignored, and the second argument is
-- returned as the result.
-- SLPJ: in 5.04 etc 'assert' is in GHC.Prim,
-- but from Template Haskell onwards it's simply
-- defined here in Base.lhs
assert :: Bool -> a -> a
assert _pred r = r
breakpoint :: a -> a
breakpoint r = r
breakpointCond :: Bool -> a -> a
breakpointCond _ r = r
data Opaque = forall a. O a
-- | Constant function.
const :: a -> b -> a
const x _ = x
-- | Function composition.
{-# INLINE (.) #-}
-- Make sure it has TWO args only on the left, so that it inlines
-- when applied to two functions, even if there is no final argument
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
-- | @'flip' f@ takes its (first) two arguments in the reverse order of @f@.
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
-- | Application operator. This operator is redundant, since ordinary
-- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- > f $ g $ h x = f (g (h x))
--
-- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
-- or @'Data.List.zipWith' ('$') fs xs@.
{-# INLINE ($) #-}
($) :: (a -> b) -> a -> b
f $ x = f x
-- | Strict (call-by-value) application operator. It takes a function and an
-- argument, evaluates the argument to weak head normal form (WHNF), then calls
-- the function with that value.
($!) :: (a -> b) -> a -> b
f $! x = let !vx = x in f vx -- see #2273
-- | @'until' p f@ yields the result of applying @f@ until @p@ holds.
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f = go
where
go x | p x = x
| otherwise = go (f x)
-- | 'asTypeOf' is a type-restricted version of 'const'. It is usually
-- used as an infix operator, and its typing forces its first argument
-- (which is usually overloaded) to have the same type as the second.
asTypeOf :: a -> a -> a
asTypeOf = const
----------------------------------------------
-- Functor/Applicative/Monad instances for IO
----------------------------------------------
instance Functor IO where
fmap f x = x >>= (pure . f)
instance Applicative IO where
{-# INLINE pure #-}
{-# INLINE (*>) #-}
pure = returnIO
m *> k = m >>= \ _ -> k
(<*>) = ap
instance Monad IO where
{-# INLINE (>>) #-}
{-# INLINE (>>=) #-}
(>>) = (*>)
(>>=) = bindIO
fail s = failIO s
instance Alternative IO where
empty = failIO "mzero"
(<|>) = mplusIO
instance MonadPlus IO
returnIO :: a -> IO a
returnIO x = IO $ \ s -> (# s, x #)
bindIO :: IO a -> (a -> IO b) -> IO b
bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s
thenIO :: IO a -> IO b -> IO b
thenIO (IO m) k = IO $ \ s -> case m s of (# new_s, _ #) -> unIO k new_s
unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
unIO (IO a) = a
{- |
Returns the 'tag' of a constructor application; this function is used
by the deriving code for Eq, Ord and Enum.
The primitive dataToTag# requires an evaluated constructor application
as its argument, so we provide getTag as a wrapper that performs the
evaluation before calling dataToTag#. We could have dataToTag#
evaluate its argument, but we prefer to do it this way because (a)
dataToTag# can be an inline primop if it doesn't need to do any
evaluation, and (b) we want to expose the evaluation to the
simplifier, because it might be possible to eliminate the evaluation
in the case when the argument is already known to be evaluated.
-}
{-# INLINE getTag #-}
getTag :: a -> Int#
getTag !x = dataToTag# x
----------------------------------------------
-- Numeric primops
----------------------------------------------
-- Definitions of the boxed PrimOps; these will be
-- used in the case of partial applications, etc.
{-# INLINE quotInt #-}
{-# INLINE remInt #-}
quotInt, remInt, divInt, modInt :: Int -> Int -> Int
(I# x) `quotInt` (I# y) = I# (x `quotInt#` y)
(I# x) `remInt` (I# y) = I# (x `remInt#` y)
(I# x) `divInt` (I# y) = I# (x `divInt#` y)
(I# x) `modInt` (I# y) = I# (x `modInt#` y)
quotRemInt :: Int -> Int -> (Int, Int)
(I# x) `quotRemInt` (I# y) = case x `quotRemInt#` y of
(# q, r #) ->
(I# q, I# r)
divModInt :: Int -> Int -> (Int, Int)
(I# x) `divModInt` (I# y) = case x `divModInt#` y of
(# q, r #) -> (I# q, I# r)
divModInt# :: Int# -> Int# -> (# Int#, Int# #)
x# `divModInt#` y#
| isTrue# (x# ># 0#) && isTrue# (y# <# 0#) =
case (x# -# 1#) `quotRemInt#` y# of
(# q, r #) -> (# q -# 1#, r +# y# +# 1# #)
| isTrue# (x# <# 0#) && isTrue# (y# ># 0#) =
case (x# +# 1#) `quotRemInt#` y# of
(# q, r #) -> (# q -# 1#, r +# y# -# 1# #)
| otherwise =
x# `quotRemInt#` y#
-- Wrappers for the shift operations. The uncheckedShift# family are
-- undefined when the amount being shifted by is greater than the size
-- in bits of Int#, so these wrappers perform a check and return
-- either zero or -1 appropriately.
--
-- Note that these wrappers still produce undefined results when the
-- second argument (the shift amount) is negative.
-- | Shift the argument left by the specified number of bits
-- (which must be non-negative).
shiftL# :: Word# -> Int# -> Word#
a `shiftL#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0##
| otherwise = a `uncheckedShiftL#` b
-- | Shift the argument right by the specified number of bits
-- (which must be non-negative).
-- The "RL" means "right, logical" (as opposed to RA for arithmetic)
-- (although an arithmetic right shift wouldn't make sense for Word#)
shiftRL# :: Word# -> Int# -> Word#
a `shiftRL#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0##
| otherwise = a `uncheckedShiftRL#` b
-- | Shift the argument left by the specified number of bits
-- (which must be non-negative).
iShiftL# :: Int# -> Int# -> Int#
a `iShiftL#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0#
| otherwise = a `uncheckedIShiftL#` b
-- | Shift the argument right (signed) by the specified number of bits
-- (which must be non-negative).
-- The "RA" means "right, arithmetic" (as opposed to RL for logical)
iShiftRA# :: Int# -> Int# -> Int#
a `iShiftRA#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = if isTrue# (a <# 0#)
then (-1#)
else 0#
| otherwise = a `uncheckedIShiftRA#` b
-- | Shift the argument right (unsigned) by the specified number of bits
-- (which must be non-negative).
-- The "RL" means "right, logical" (as opposed to RA for arithmetic)
iShiftRL# :: Int# -> Int# -> Int#
a `iShiftRL#` b | isTrue# (b >=# WORD_SIZE_IN_BITS#) = 0#
| otherwise = a `uncheckedIShiftRL#` b
-- Rules for C strings (the functions themselves are now in GHC.CString)
{-# RULES
"unpack" [~1] forall a . unpackCString# a = build (unpackFoldrCString# a)
"unpack-list" [1] forall a . unpackFoldrCString# a (:) [] = unpackCString# a
"unpack-append" forall a n . unpackFoldrCString# a (:) n = unpackAppendCString# a n
-- There's a built-in rule (in PrelRules.lhs) for
-- unpackFoldr "foo" c (unpackFoldr "baz" c n) = unpackFoldr "foobaz" c n
#-}
| elieux/ghc | libraries/base/GHC/Base.hs | bsd-3-clause | 41,476 | 187 | 46 | 10,932 | 6,451 | 3,630 | 2,821 | 397 | 2 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Control/AutoUpdate.hs" #-}
{-# LANGUAGE CPP #-}
-- | In a multithreaded environment, running actions on a regularly scheduled
-- background thread can dramatically improve performance.
-- For example, web servers need to return the current time with each HTTP response.
-- For a high-volume server, it's much faster for a dedicated thread to run every
-- second, and write the current time to a shared 'IORef', than it is for each
-- request to make its own call to 'getCurrentTime'.
--
-- But for a low-volume server, whose request frequency is less than once per
-- second, that approach will result in /more/ calls to 'getCurrentTime' than
-- necessary, and worse, kills idle GC.
--
-- This library solves that problem by allowing you to define actions which will
-- either be performed by a dedicated thread, or, in times of low volume, will
-- be executed by the calling thread.
--
-- Example usage:
--
-- @
-- import "Data.Time"
-- import "Control.AutoUpdate"
--
-- getTime <- 'mkAutoUpdate' 'defaultUpdateSettings'
-- { 'updateAction' = 'Data.Time.Clock.getCurrentTime'
-- , 'updateFreq' = 1000000 -- The default frequency, once per second
-- }
-- currentTime <- getTime
-- @
--
-- For more examples, <http://www.yesodweb.com/blog/2014/08/announcing-auto-update see the blog post introducing this library>.
module Control.AutoUpdate (
-- * Type
UpdateSettings
, defaultUpdateSettings
-- * Accessors
, updateAction
, updateFreq
, updateSpawnThreshold
-- * Creation
, mkAutoUpdate
, mkAutoUpdateWithModify
) where
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar,
takeMVar, tryPutMVar)
import Control.Exception (SomeException, catch, mask_, throw,
try)
import Control.Monad (void)
import Data.IORef (newIORef, readIORef, writeIORef)
-- | Default value for creating an 'UpdateSettings'.
--
-- @since 0.1.0
defaultUpdateSettings :: UpdateSettings ()
defaultUpdateSettings = UpdateSettings
{ updateFreq = 1000000
, updateSpawnThreshold = 3
, updateAction = return ()
}
-- | Settings to control how values are updated.
--
-- This should be constructed using 'defaultUpdateSettings' and record
-- update syntax, e.g.:
--
-- @
-- let settings = 'defaultUpdateSettings' { 'updateAction' = 'Data.Time.Clock.getCurrentTime' }
-- @
--
-- @since 0.1.0
data UpdateSettings a = UpdateSettings
{ updateFreq :: Int
-- ^ Microseconds between update calls. Same considerations as
-- 'threadDelay' apply.
--
-- Default: 1 second (1000000)
--
-- @since 0.1.0
, updateSpawnThreshold :: Int
-- ^ NOTE: This value no longer has any effect, since worker threads are
-- dedicated instead of spawned on demand.
--
-- Previously, this determined how many times the data must be requested
-- before we decide to spawn a dedicated thread.
--
-- Default: 3
--
-- @since 0.1.0
, updateAction :: IO a
-- ^ Action to be performed to get the current value.
--
-- Default: does nothing.
--
-- @since 0.1.0
}
-- | Generate an action which will either read from an automatically
-- updated value, or run the update action in the current thread.
--
-- @since 0.1.0
mkAutoUpdate :: UpdateSettings a -> IO (IO a)
mkAutoUpdate us = mkAutoUpdateHelper us Nothing
-- | Generate an action which will either read from an automatically
-- updated value, or run the update action in the current thread if
-- the first time or the provided modify action after that.
--
-- @since 0.1.4
mkAutoUpdateWithModify :: UpdateSettings a -> (a -> IO a) -> IO (IO a)
mkAutoUpdateWithModify us f = mkAutoUpdateHelper us (Just f)
mkAutoUpdateHelper :: UpdateSettings a -> Maybe (a -> IO a) -> IO (IO a)
mkAutoUpdateHelper us updateActionModify = do
-- A baton to tell the worker thread to generate a new value.
needsRunning <- newEmptyMVar
-- The initial response variable. Response variables allow the requesting
-- thread to block until a value is generated by the worker thread.
responseVar0 <- newEmptyMVar
-- The current value, if available. We start off with a Left value
-- indicating no value is available, and the above-created responseVar0 to
-- give a variable to block on.
currRef <- newIORef $ Left responseVar0
-- This is used to set a value in the currRef variable when the worker
-- thread exits. In reality, that value should never be used, since the
-- worker thread exiting only occurs if an async exception is thrown, which
-- should only occur if there are no references to needsRunning left.
-- However, this handler will make error messages much clearer if there's a
-- bug in the implementation.
let fillRefOnExit f = do
eres <- try f
case eres of
Left e -> writeIORef currRef $ error $
"Control.AutoUpdate.mkAutoUpdate: worker thread exited with exception: "
++ show (e :: SomeException)
Right () -> writeIORef currRef $ error $
"Control.AutoUpdate.mkAutoUpdate: worker thread exited normally, "
++ "which should be impossible due to usage of infinite loop"
-- fork the worker thread immediately. Note that we mask async exceptions,
-- but *not* in an uninterruptible manner. This will allow a
-- BlockedIndefinitelyOnMVar exception to still be thrown, which will take
-- down this thread when all references to the returned function are
-- garbage collected, and therefore there is no thread that can fill the
-- needsRunning MVar.
--
-- Note that since we throw away the ThreadId of this new thread and never
-- calls myThreadId, normal async exceptions can never be thrown to it,
-- only RTS exceptions.
mask_ $ void $ forkIO $ fillRefOnExit $ do
-- This infinite loop makes up out worker thread. It takes an a
-- responseVar value where the next value should be putMVar'ed to for
-- the benefit of any requesters currently blocked on it.
let loop responseVar maybea = do
-- block until a value is actually needed
takeMVar needsRunning
-- new value requested, so run the updateAction
a <- catchSome $ maybe (updateAction us) id (updateActionModify <*> maybea)
-- we got a new value, update currRef and lastValue
writeIORef currRef $ Right a
putMVar responseVar a
-- delay until we're needed again
threadDelay $ updateFreq us
-- delay's over. create a new response variable and set currRef
-- to use it, so that the next requester will block on that
-- variable. Then loop again with the updated response
-- variable.
responseVar' <- newEmptyMVar
writeIORef currRef $ Left responseVar'
loop responseVar' (Just a)
-- Kick off the loop, with the initial responseVar0 variable.
loop responseVar0 Nothing
return $ do
mval <- readIORef currRef
case mval of
Left responseVar -> do
-- no current value, force the worker thread to run...
void $ tryPutMVar needsRunning ()
-- and block for the result from the worker
readMVar responseVar
-- we have a current value, use it
Right val -> return val
-- | Turn a runtime exception into an impure exception, so that all 'IO'
-- actions will complete successfully. This simply defers the exception until
-- the value is forced.
catchSome :: IO a -> IO a
catchSome act = Control.Exception.catch act $ \e -> return $ throw (e :: SomeException)
| phischu/fragnix | tests/packages/scotty/Control.AutoUpdate.hs | bsd-3-clause | 8,177 | 0 | 19 | 2,272 | 814 | 463 | 351 | 65 | 3 |
-- Tuples definition.
x = (1, "hello")
y = ("pi", [ 1, 2, 3 ], 3.14, 1)
-- Pairs.
first = fst x
second = snd x | M4573R/playground-notes | unfinished-courses/haskell-fundamentals/tuples.hs | mit | 111 | 0 | 6 | 27 | 56 | 34 | 22 | 4 | 1 |
{-| Implementation of the Ganeti Query2 job queries.
-}
{-
Copyright (C) 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.Query.Job
( RuntimeData
, fieldsMap
, wantArchived
) where
import qualified Text.JSON as J
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.JQueue
import Ganeti.Query.Common
import Ganeti.Query.Language
import Ganeti.Query.Types
import Ganeti.Types
-- | The runtime data for a job.
type RuntimeData = Result (QueuedJob, Bool)
-- | Job priority explanation.
jobPrioDoc :: String
jobPrioDoc = "Current job priority (" ++ show C.opPrioLowest ++ " to " ++
show C.opPrioHighest ++ ")"
-- | Timestamp doc.
tsDoc :: String -> String
tsDoc = (++ " (tuple containing seconds and microseconds)")
-- | Wrapper for unavailable job.
maybeJob :: (J.JSON a) =>
(QueuedJob -> a) -> RuntimeData -> JobId -> ResultEntry
maybeJob _ (Bad _) _ = rsUnavail
maybeJob f (Ok (v, _)) _ = rsNormal $ f v
-- | Wrapper for optional fields that should become unavailable.
maybeJobOpt :: (J.JSON a) =>
(QueuedJob -> Maybe a) -> RuntimeData -> JobId -> ResultEntry
maybeJobOpt _ (Bad _) _ = rsUnavail
maybeJobOpt f (Ok (v, _)) _ = case f v of
Nothing -> rsUnavail
Just w -> rsNormal w
-- | Simple helper for a job getter.
jobGetter :: (J.JSON a) => (QueuedJob -> a) -> FieldGetter JobId RuntimeData
jobGetter = FieldRuntime . maybeJob
-- | Simple helper for a per-opcode getter.
opsGetter :: (J.JSON a) => (QueuedOpCode -> a) -> FieldGetter JobId RuntimeData
opsGetter f = FieldRuntime $ maybeJob (map f . qjOps)
-- | Simple helper for a per-opcode optional field getter.
opsOptGetter :: (J.JSON a) =>
(QueuedOpCode -> Maybe a) -> FieldGetter JobId RuntimeData
opsOptGetter f =
FieldRuntime $ maybeJob (map (\qo -> case f qo of
Nothing -> J.JSNull
Just a -> J.showJSON a) . qjOps)
-- | Archived field name.
archivedField :: String
archivedField = "archived"
-- | Check whether we should look at archived jobs as well.
wantArchived :: [FilterField] -> Bool
wantArchived = (archivedField `elem`)
-- | List of all node fields. FIXME: QFF_JOB_ID on the id field.
jobFields :: FieldList JobId RuntimeData
jobFields =
[ (FieldDefinition "id" "ID" QFTNumber "Job ID", FieldSimple rsNormal,
QffNormal)
, (FieldDefinition "status" "Status" QFTText "Job status",
jobGetter calcJobStatus, QffNormal)
, (FieldDefinition "priority" "Priority" QFTNumber jobPrioDoc,
jobGetter calcJobPriority, QffNormal)
, (FieldDefinition archivedField "Archived" QFTBool
"Whether job is archived",
FieldRuntime (\jinfo _ -> case jinfo of
Ok (_, archive) -> rsNormal archive
_ -> rsUnavail), QffNormal)
, (FieldDefinition "ops" "OpCodes" QFTOther "List of all opcodes",
opsGetter qoInput, QffNormal)
, (FieldDefinition "opresult" "OpCode_result" QFTOther
"List of opcodes results", opsGetter qoResult, QffNormal)
, (FieldDefinition "opstatus" "OpCode_status" QFTOther
"List of opcodes status", opsGetter qoStatus, QffNormal)
, (FieldDefinition "oplog" "OpCode_log" QFTOther
"List of opcode output logs", opsGetter qoLog, QffNormal)
, (FieldDefinition "opstart" "OpCode_start" QFTOther
"List of opcode start timestamps (before acquiring locks)",
opsOptGetter qoStartTimestamp, QffNormal)
, (FieldDefinition "opexec" "OpCode_exec" QFTOther
"List of opcode execution start timestamps (after acquiring locks)",
opsOptGetter qoExecTimestamp, QffNormal)
, (FieldDefinition "opend" "OpCode_end" QFTOther
"List of opcode execution end timestamps",
opsOptGetter qoEndTimestamp, QffNormal)
, (FieldDefinition "oppriority" "OpCode_prio" QFTOther
"List of opcode priorities", opsGetter qoPriority, QffNormal)
, (FieldDefinition "summary" "Summary" QFTOther
"List of per-opcode summaries",
opsGetter (extractOpSummary . qoInput), QffNormal)
, (FieldDefinition "received_ts" "Received" QFTOther
(tsDoc "Timestamp of when job was received"),
FieldRuntime (maybeJobOpt qjReceivedTimestamp), QffTimestamp)
, (FieldDefinition "start_ts" "Start" QFTOther
(tsDoc "Timestamp of job start"),
FieldRuntime (maybeJobOpt qjStartTimestamp), QffTimestamp)
, (FieldDefinition "end_ts" "End" QFTOther
(tsDoc "Timestamp of job end"),
FieldRuntime (maybeJobOpt qjEndTimestamp), QffTimestamp)
]
-- | The node fields map.
fieldsMap :: FieldMap JobId RuntimeData
fieldsMap = fieldListToFieldMap jobFields
| kawamuray/ganeti | src/Ganeti/Query/Job.hs | gpl-2.0 | 5,414 | 0 | 16 | 1,189 | 1,065 | 581 | 484 | 88 | 2 |
main = putStrLn "Fuck you Mendez."
| DrItanium/thisisfreesoftware | thisisfreesoftware.hs | agpl-3.0 | 35 | 0 | 5 | 6 | 9 | 4 | 5 | 1 | 1 |
module SalsaAst where
type Program = [Command]
data Command = Rect Ident Expr Expr Expr Expr Colour Bool
| Circ Ident Expr Expr Expr Colour Bool
| Move Ident Pos
| Toggle Ident
| Par Command Command
deriving (Show, Eq)
data Pos = Abs Expr Expr
| Rel Expr Expr
deriving (Show, Eq)
data Expr = Plus Expr Expr
| Minus Expr Expr
| Mult Expr Expr
| Div Expr Expr
| Const Integer
| Xproj Ident
| Yproj Ident
deriving (Show, Eq)
data Colour = Blue | Plum | Red | Green | Orange
deriving (Show, Eq)
type Ident = String
| Rathcke/uni | ap/afl1/SalsaAst.hs | gpl-3.0 | 677 | 0 | 6 | 268 | 202 | 116 | 86 | 22 | 0 |
module TcTypeNats
( typeNatTyCons
, typeNatCoAxiomRules
, BuiltInSynFamily(..)
, typeNatAddTyCon
, typeNatMulTyCon
, typeNatExpTyCon
, typeNatLeqTyCon
, typeNatSubTyCon
, typeNatCmpTyCon
, typeSymbolCmpTyCon
) where
import Type
import Pair
import TcType ( TcType, tcEqType )
import TyCon ( TyCon, FamTyConFlav(..), mkFamilyTyCon
, Injectivity(..) )
import Coercion ( Role(..) )
import TcRnTypes ( Xi )
import CoAxiom ( CoAxiomRule(..), BuiltInSynFamily(..) )
import Name ( Name, BuiltInSyntax(..) )
import TysWiredIn ( typeNatKind, typeSymbolKind
, mkWiredInTyConName
, promotedBoolTyCon
, promotedFalseDataCon, promotedTrueDataCon
, promotedOrderingTyCon
, promotedLTDataCon
, promotedEQDataCon
, promotedGTDataCon
)
import TysPrim ( mkArrowKinds, mkTemplateTyVars )
import PrelNames ( gHC_TYPELITS
, typeNatAddTyFamNameKey
, typeNatMulTyFamNameKey
, typeNatExpTyFamNameKey
, typeNatLeqTyFamNameKey
, typeNatSubTyFamNameKey
, typeNatCmpTyFamNameKey
, typeSymbolCmpTyFamNameKey
)
import FastString ( FastString, fsLit )
import qualified Data.Map as Map
import Data.Maybe ( isJust )
{-------------------------------------------------------------------------------
Built-in type constructors for functions on type-level nats
-}
typeNatTyCons :: [TyCon]
typeNatTyCons =
[ typeNatAddTyCon
, typeNatMulTyCon
, typeNatExpTyCon
, typeNatLeqTyCon
, typeNatSubTyCon
, typeNatCmpTyCon
, typeSymbolCmpTyCon
]
typeNatAddTyCon :: TyCon
typeNatAddTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamAdd
, sfInteractTop = interactTopAdd
, sfInteractInert = interactInertAdd
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "+")
typeNatAddTyFamNameKey typeNatAddTyCon
typeNatSubTyCon :: TyCon
typeNatSubTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamSub
, sfInteractTop = interactTopSub
, sfInteractInert = interactInertSub
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "-")
typeNatSubTyFamNameKey typeNatSubTyCon
typeNatMulTyCon :: TyCon
typeNatMulTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamMul
, sfInteractTop = interactTopMul
, sfInteractInert = interactInertMul
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "*")
typeNatMulTyFamNameKey typeNatMulTyCon
typeNatExpTyCon :: TyCon
typeNatExpTyCon = mkTypeNatFunTyCon2 name
BuiltInSynFamily
{ sfMatchFam = matchFamExp
, sfInteractTop = interactTopExp
, sfInteractInert = interactInertExp
}
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "^")
typeNatExpTyFamNameKey typeNatExpTyCon
typeNatLeqTyCon :: TyCon
typeNatLeqTyCon =
mkFamilyTyCon name
(mkArrowKinds [ typeNatKind, typeNatKind ] boolKind)
(mkTemplateTyVars [ typeNatKind, typeNatKind ])
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "<=?")
typeNatLeqTyFamNameKey typeNatLeqTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamLeq
, sfInteractTop = interactTopLeq
, sfInteractInert = interactInertLeq
}
typeNatCmpTyCon :: TyCon
typeNatCmpTyCon =
mkFamilyTyCon name
(mkArrowKinds [ typeNatKind, typeNatKind ] orderingKind)
(mkTemplateTyVars [ typeNatKind, typeNatKind ])
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CmpNat")
typeNatCmpTyFamNameKey typeNatCmpTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamCmpNat
, sfInteractTop = interactTopCmpNat
, sfInteractInert = \_ _ _ _ -> []
}
typeSymbolCmpTyCon :: TyCon
typeSymbolCmpTyCon =
mkFamilyTyCon name
(mkArrowKinds [ typeSymbolKind, typeSymbolKind ] orderingKind)
(mkTemplateTyVars [ typeSymbolKind, typeSymbolKind ])
Nothing
(BuiltInSynFamTyCon ops)
Nothing
NotInjective
where
name = mkWiredInTyConName UserSyntax gHC_TYPELITS (fsLit "CmpSymbol")
typeSymbolCmpTyFamNameKey typeSymbolCmpTyCon
ops = BuiltInSynFamily
{ sfMatchFam = matchFamCmpSymbol
, sfInteractTop = interactTopCmpSymbol
, sfInteractInert = \_ _ _ _ -> []
}
-- Make a binary built-in constructor of kind: Nat -> Nat -> Nat
mkTypeNatFunTyCon2 :: Name -> BuiltInSynFamily -> TyCon
mkTypeNatFunTyCon2 op tcb =
mkFamilyTyCon op
(mkArrowKinds [ typeNatKind, typeNatKind ] typeNatKind)
(mkTemplateTyVars [ typeNatKind, typeNatKind ])
Nothing
(BuiltInSynFamTyCon tcb)
Nothing
NotInjective
{-------------------------------------------------------------------------------
Built-in rules axioms
-------------------------------------------------------------------------------}
-- If you add additional rules, please remember to add them to
-- `typeNatCoAxiomRules` also.
axAddDef
, axMulDef
, axExpDef
, axLeqDef
, axCmpNatDef
, axCmpSymbolDef
, axAdd0L
, axAdd0R
, axMul0L
, axMul0R
, axMul1L
, axMul1R
, axExp1L
, axExp0R
, axExp1R
, axLeqRefl
, axCmpNatRefl
, axCmpSymbolRefl
, axLeq0L
, axSubDef
, axSub0R
:: CoAxiomRule
axAddDef = mkBinAxiom "AddDef" typeNatAddTyCon $
\x y -> Just $ num (x + y)
axMulDef = mkBinAxiom "MulDef" typeNatMulTyCon $
\x y -> Just $ num (x * y)
axExpDef = mkBinAxiom "ExpDef" typeNatExpTyCon $
\x y -> Just $ num (x ^ y)
axLeqDef = mkBinAxiom "LeqDef" typeNatLeqTyCon $
\x y -> Just $ bool (x <= y)
axCmpNatDef = mkBinAxiom "CmpNatDef" typeNatCmpTyCon
$ \x y -> Just $ ordering (compare x y)
axCmpSymbolDef =
CoAxiomRule
{ coaxrName = fsLit "CmpSymbolDef"
, coaxrTypeArity = 2
, coaxrAsmpRoles = []
, coaxrRole = Nominal
, coaxrProves = \ts cs ->
case (ts,cs) of
([s,t],[]) ->
do x <- isStrLitTy s
y <- isStrLitTy t
return (mkTyConApp typeSymbolCmpTyCon [s,t] ===
ordering (compare x y))
_ -> Nothing
}
axSubDef = mkBinAxiom "SubDef" typeNatSubTyCon $
\x y -> fmap num (minus x y)
axAdd0L = mkAxiom1 "Add0L" $ \t -> (num 0 .+. t) === t
axAdd0R = mkAxiom1 "Add0R" $ \t -> (t .+. num 0) === t
axSub0R = mkAxiom1 "Sub0R" $ \t -> (t .-. num 0) === t
axMul0L = mkAxiom1 "Mul0L" $ \t -> (num 0 .*. t) === num 0
axMul0R = mkAxiom1 "Mul0R" $ \t -> (t .*. num 0) === num 0
axMul1L = mkAxiom1 "Mul1L" $ \t -> (num 1 .*. t) === t
axMul1R = mkAxiom1 "Mul1R" $ \t -> (t .*. num 1) === t
axExp1L = mkAxiom1 "Exp1L" $ \t -> (num 1 .^. t) === num 1
axExp0R = mkAxiom1 "Exp0R" $ \t -> (t .^. num 0) === num 1
axExp1R = mkAxiom1 "Exp1R" $ \t -> (t .^. num 1) === t
axLeqRefl = mkAxiom1 "LeqRefl" $ \t -> (t <== t) === bool True
axCmpNatRefl = mkAxiom1 "CmpNatRefl"
$ \t -> (cmpNat t t) === ordering EQ
axCmpSymbolRefl = mkAxiom1 "CmpSymbolRefl"
$ \t -> (cmpSymbol t t) === ordering EQ
axLeq0L = mkAxiom1 "Leq0L" $ \t -> (num 0 <== t) === bool True
typeNatCoAxiomRules :: Map.Map FastString CoAxiomRule
typeNatCoAxiomRules = Map.fromList $ map (\x -> (coaxrName x, x))
[ axAddDef
, axMulDef
, axExpDef
, axLeqDef
, axCmpNatDef
, axCmpSymbolDef
, axAdd0L
, axAdd0R
, axMul0L
, axMul0R
, axMul1L
, axMul1R
, axExp1L
, axExp0R
, axExp1R
, axLeqRefl
, axCmpNatRefl
, axCmpSymbolRefl
, axLeq0L
, axSubDef
]
{-------------------------------------------------------------------------------
Various utilities for making axioms and types
-------------------------------------------------------------------------------}
(.+.) :: Type -> Type -> Type
s .+. t = mkTyConApp typeNatAddTyCon [s,t]
(.-.) :: Type -> Type -> Type
s .-. t = mkTyConApp typeNatSubTyCon [s,t]
(.*.) :: Type -> Type -> Type
s .*. t = mkTyConApp typeNatMulTyCon [s,t]
(.^.) :: Type -> Type -> Type
s .^. t = mkTyConApp typeNatExpTyCon [s,t]
(<==) :: Type -> Type -> Type
s <== t = mkTyConApp typeNatLeqTyCon [s,t]
cmpNat :: Type -> Type -> Type
cmpNat s t = mkTyConApp typeNatCmpTyCon [s,t]
cmpSymbol :: Type -> Type -> Type
cmpSymbol s t = mkTyConApp typeSymbolCmpTyCon [s,t]
(===) :: Type -> Type -> Pair Type
x === y = Pair x y
num :: Integer -> Type
num = mkNumLitTy
boolKind :: Kind
boolKind = mkTyConApp promotedBoolTyCon []
bool :: Bool -> Type
bool b = if b then mkTyConApp promotedTrueDataCon []
else mkTyConApp promotedFalseDataCon []
isBoolLitTy :: Type -> Maybe Bool
isBoolLitTy tc =
do (tc,[]) <- splitTyConApp_maybe tc
case () of
_ | tc == promotedFalseDataCon -> return False
| tc == promotedTrueDataCon -> return True
| otherwise -> Nothing
orderingKind :: Kind
orderingKind = mkTyConApp promotedOrderingTyCon []
ordering :: Ordering -> Type
ordering o =
case o of
LT -> mkTyConApp promotedLTDataCon []
EQ -> mkTyConApp promotedEQDataCon []
GT -> mkTyConApp promotedGTDataCon []
isOrderingLitTy :: Type -> Maybe Ordering
isOrderingLitTy tc =
do (tc1,[]) <- splitTyConApp_maybe tc
case () of
_ | tc1 == promotedLTDataCon -> return LT
| tc1 == promotedEQDataCon -> return EQ
| tc1 == promotedGTDataCon -> return GT
| otherwise -> Nothing
known :: (Integer -> Bool) -> TcType -> Bool
known p x = case isNumLitTy x of
Just a -> p a
Nothing -> False
-- For the definitional axioms
mkBinAxiom :: String -> TyCon ->
(Integer -> Integer -> Maybe Type) -> CoAxiomRule
mkBinAxiom str tc f =
CoAxiomRule
{ coaxrName = fsLit str
, coaxrTypeArity = 2
, coaxrAsmpRoles = []
, coaxrRole = Nominal
, coaxrProves = \ts cs ->
case (ts,cs) of
([s,t],[]) -> do x <- isNumLitTy s
y <- isNumLitTy t
z <- f x y
return (mkTyConApp tc [s,t] === z)
_ -> Nothing
}
mkAxiom1 :: String -> (Type -> Pair Type) -> CoAxiomRule
mkAxiom1 str f =
CoAxiomRule
{ coaxrName = fsLit str
, coaxrTypeArity = 1
, coaxrAsmpRoles = []
, coaxrRole = Nominal
, coaxrProves = \ts cs ->
case (ts,cs) of
([s],[]) -> return (f s)
_ -> Nothing
}
{-------------------------------------------------------------------------------
Evaluation
-------------------------------------------------------------------------------}
matchFamAdd :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamAdd [s,t]
| Just 0 <- mbX = Just (axAdd0L, [t], t)
| Just 0 <- mbY = Just (axAdd0R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axAddDef, [s,t], num (x + y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamAdd _ = Nothing
matchFamSub :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamSub [s,t]
| Just 0 <- mbY = Just (axSub0R, [s], s)
| Just x <- mbX, Just y <- mbY, Just z <- minus x y =
Just (axSubDef, [s,t], num z)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamSub _ = Nothing
matchFamMul :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamMul [s,t]
| Just 0 <- mbX = Just (axMul0L, [t], num 0)
| Just 0 <- mbY = Just (axMul0R, [s], num 0)
| Just 1 <- mbX = Just (axMul1L, [t], t)
| Just 1 <- mbY = Just (axMul1R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axMulDef, [s,t], num (x * y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamMul _ = Nothing
matchFamExp :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamExp [s,t]
| Just 0 <- mbY = Just (axExp0R, [s], num 1)
| Just 1 <- mbX = Just (axExp1L, [t], num 1)
| Just 1 <- mbY = Just (axExp1R, [s], s)
| Just x <- mbX, Just y <- mbY =
Just (axExpDef, [s,t], num (x ^ y))
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamExp _ = Nothing
matchFamLeq :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamLeq [s,t]
| Just 0 <- mbX = Just (axLeq0L, [t], bool True)
| Just x <- mbX, Just y <- mbY =
Just (axLeqDef, [s,t], bool (x <= y))
| tcEqType s t = Just (axLeqRefl, [s], bool True)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamLeq _ = Nothing
matchFamCmpNat :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamCmpNat [s,t]
| Just x <- mbX, Just y <- mbY =
Just (axCmpNatDef, [s,t], ordering (compare x y))
| tcEqType s t = Just (axCmpNatRefl, [s], ordering EQ)
where mbX = isNumLitTy s
mbY = isNumLitTy t
matchFamCmpNat _ = Nothing
matchFamCmpSymbol :: [Type] -> Maybe (CoAxiomRule, [Type], Type)
matchFamCmpSymbol [s,t]
| Just x <- mbX, Just y <- mbY =
Just (axCmpSymbolDef, [s,t], ordering (compare x y))
| tcEqType s t = Just (axCmpSymbolRefl, [s], ordering EQ)
where mbX = isStrLitTy s
mbY = isStrLitTy t
matchFamCmpSymbol _ = Nothing
{-------------------------------------------------------------------------------
Interact with axioms
-------------------------------------------------------------------------------}
interactTopAdd :: [Xi] -> Xi -> [Pair Type]
interactTopAdd [s,t] r
| Just 0 <- mbZ = [ s === num 0, t === num 0 ] -- (s + t ~ 0) => (s ~ 0, t ~ 0)
| Just x <- mbX, Just z <- mbZ, Just y <- minus z x = [t === num y] -- (5 + t ~ 8) => (t ~ 3)
| Just y <- mbY, Just z <- mbZ, Just x <- minus z y = [s === num x] -- (s + 5 ~ 8) => (s ~ 3)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopAdd _ _ = []
{-
Note [Weakened interaction rule for subtraction]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A simpler interaction here might be:
`s - t ~ r` --> `t + r ~ s`
This would enable us to reuse all the code for addition.
Unfortunately, this works a little too well at the moment.
Consider the following example:
0 - 5 ~ r --> 5 + r ~ 0 --> (5 = 0, r = 0)
This (correctly) spots that the constraint cannot be solved.
However, this may be a problem if the constraint did not
need to be solved in the first place! Consider the following example:
f :: Proxy (If (5 <=? 0) (0 - 5) (5 - 0)) -> Proxy 5
f = id
Currently, GHC is strict while evaluating functions, so this does not
work, because even though the `If` should evaluate to `5 - 0`, we
also evaluate the "then" branch which generates the constraint `0 - 5 ~ r`,
which fails.
So, for the time being, we only add an improvement when the RHS is a constant,
which happens to work OK for the moment, although clearly we need to do
something more general.
-}
interactTopSub :: [Xi] -> Xi -> [Pair Type]
interactTopSub [s,t] r
| Just z <- mbZ = [ s === (num z .+. t) ] -- (s - t ~ 5) => (5 + t ~ s)
where
mbZ = isNumLitTy r
interactTopSub _ _ = []
interactTopMul :: [Xi] -> Xi -> [Pair Type]
interactTopMul [s,t] r
| Just 1 <- mbZ = [ s === num 1, t === num 1 ] -- (s * t ~ 1) => (s ~ 1, t ~ 1)
| Just x <- mbX, Just z <- mbZ, Just y <- divide z x = [t === num y] -- (3 * t ~ 15) => (t ~ 5)
| Just y <- mbY, Just z <- mbZ, Just x <- divide z y = [s === num x] -- (s * 3 ~ 15) => (s ~ 5)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopMul _ _ = []
interactTopExp :: [Xi] -> Xi -> [Pair Type]
interactTopExp [s,t] r
| Just 0 <- mbZ = [ s === num 0 ] -- (s ^ t ~ 0) => (s ~ 0)
| Just x <- mbX, Just z <- mbZ, Just y <- logExact z x = [t === num y] -- (2 ^ t ~ 8) => (t ~ 3)
| Just y <- mbY, Just z <- mbZ, Just x <- rootExact z y = [s === num x] -- (s ^ 2 ~ 9) => (s ~ 3)
where
mbX = isNumLitTy s
mbY = isNumLitTy t
mbZ = isNumLitTy r
interactTopExp _ _ = []
interactTopLeq :: [Xi] -> Xi -> [Pair Type]
interactTopLeq [s,t] r
| Just 0 <- mbY, Just True <- mbZ = [ s === num 0 ] -- (s <= 0) => (s ~ 0)
where
mbY = isNumLitTy t
mbZ = isBoolLitTy r
interactTopLeq _ _ = []
interactTopCmpNat :: [Xi] -> Xi -> [Pair Type]
interactTopCmpNat [s,t] r
| Just EQ <- isOrderingLitTy r = [ s === t ]
interactTopCmpNat _ _ = []
interactTopCmpSymbol :: [Xi] -> Xi -> [Pair Type]
interactTopCmpSymbol [s,t] r
| Just EQ <- isOrderingLitTy r = [ s === t ]
interactTopCmpSymbol _ _ = []
{-------------------------------------------------------------------------------
Interaction with inerts
-------------------------------------------------------------------------------}
interactInertAdd :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertAdd [x1,y1] z1 [x2,y2] z2
| sameZ && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertAdd _ _ _ _ = []
interactInertSub :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertSub [x1,y1] z1 [x2,y2] z2
| sameZ && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertSub _ _ _ _ = []
interactInertMul :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertMul [x1,y1] z1 [x2,y2] z2
| sameZ && known (/= 0) x1 && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && known (/= 0) y1 && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertMul _ _ _ _ = []
interactInertExp :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertExp [x1,y1] z1 [x2,y2] z2
| sameZ && known (> 1) x1 && tcEqType x1 x2 = [ y1 === y2 ]
| sameZ && known (> 0) y1 && tcEqType y1 y2 = [ x1 === x2 ]
where sameZ = tcEqType z1 z2
interactInertExp _ _ _ _ = []
interactInertLeq :: [Xi] -> Xi -> [Xi] -> Xi -> [Pair Type]
interactInertLeq [x1,y1] z1 [x2,y2] z2
| bothTrue && tcEqType x1 y2 && tcEqType y1 x2 = [ x1 === y1 ]
| bothTrue && tcEqType y1 x2 = [ (x1 <== y2) === bool True ]
| bothTrue && tcEqType y2 x1 = [ (x2 <== y1) === bool True ]
where bothTrue = isJust $ do True <- isBoolLitTy z1
True <- isBoolLitTy z2
return ()
interactInertLeq _ _ _ _ = []
{- -----------------------------------------------------------------------------
These inverse functions are used for simplifying propositions using
concrete natural numbers.
----------------------------------------------------------------------------- -}
-- | Subtract two natural numbers.
minus :: Integer -> Integer -> Maybe Integer
minus x y = if x >= y then Just (x - y) else Nothing
-- | Compute the exact logarithm of a natural number.
-- The logarithm base is the second argument.
logExact :: Integer -> Integer -> Maybe Integer
logExact x y = do (z,True) <- genLog x y
return z
-- | Divide two natural numbers.
divide :: Integer -> Integer -> Maybe Integer
divide _ 0 = Nothing
divide x y = case divMod x y of
(a,0) -> Just a
_ -> Nothing
-- | Compute the exact root of a natural number.
-- The second argument specifies which root we are computing.
rootExact :: Integer -> Integer -> Maybe Integer
rootExact x y = do (z,True) <- genRoot x y
return z
{- | Compute the the n-th root of a natural number, rounded down to
the closest natural number. The boolean indicates if the result
is exact (i.e., True means no rounding was done, False means rounded down).
The second argument specifies which root we are computing. -}
genRoot :: Integer -> Integer -> Maybe (Integer, Bool)
genRoot _ 0 = Nothing
genRoot x0 1 = Just (x0, True)
genRoot x0 root = Just (search 0 (x0+1))
where
search from to = let x = from + div (to - from) 2
a = x ^ root
in case compare a x0 of
EQ -> (x, True)
LT | x /= from -> search x to
| otherwise -> (from, False)
GT | x /= to -> search from x
| otherwise -> (from, False)
{- | Compute the logarithm of a number in the given base, rounded down to the
closest integer. The boolean indicates if we the result is exact
(i.e., True means no rounding happened, False means we rounded down).
The logarithm base is the second argument. -}
genLog :: Integer -> Integer -> Maybe (Integer, Bool)
genLog x 0 = if x == 1 then Just (0, True) else Nothing
genLog _ 1 = Nothing
genLog 0 _ = Nothing
genLog x base = Just (exactLoop 0 x)
where
exactLoop s i
| i == 1 = (s,True)
| i < base = (s,False)
| otherwise =
let s1 = s + 1
in s1 `seq` case divMod i base of
(j,r)
| r == 0 -> exactLoop s1 j
| otherwise -> (underLoop s1 j, False)
underLoop s i
| i < base = s
| otherwise = let s1 = s + 1 in s1 `seq` underLoop s1 (div i base)
| AlexanderPankiv/ghc | compiler/typecheck/TcTypeNats.hs | bsd-3-clause | 21,398 | 0 | 18 | 5,879 | 6,687 | 3,518 | 3,169 | 481 | 3 |
undefined = undefined
list :: a -> [a]
list x = [x]
map f [] = []
map f (x:xs) = (f x):(map f xs)
succ :: Int -> Int
succ x = undefined
ones :: [] Int
ones = 1:ones
nats = 1:map succ nats
| themattchan/tandoori | input/list.hs | bsd-3-clause | 216 | 0 | 7 | 74 | 128 | 67 | 61 | 10 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Enum
-- Copyright : (c) The University of Glasgow, 1992-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- The 'Enum' and 'Bounded' classes.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Enum(
Bounded(..), Enum(..),
boundedEnumFrom, boundedEnumFromThen,
toEnumError, fromEnumError, succError, predError,
-- Instances for Bounded and Enum: (), Char, Int
) where
import GHC.Base hiding ( many )
import GHC.Char
import GHC.Integer
import GHC.Num
import GHC.Show
default () -- Double isn't available yet
-- | The 'Bounded' class is used to name the upper and lower limits of a
-- type. 'Ord' is not a superclass of 'Bounded' since types that are not
-- totally ordered may also have upper and lower bounds.
--
-- The 'Bounded' class may be derived for any enumeration type;
-- 'minBound' is the first constructor listed in the @data@ declaration
-- and 'maxBound' is the last.
-- 'Bounded' may also be derived for single-constructor datatypes whose
-- constituent types are in 'Bounded'.
class Bounded a where
minBound, maxBound :: a
-- | Class 'Enum' defines operations on sequentially ordered types.
--
-- The @enumFrom@... methods are used in Haskell's translation of
-- arithmetic sequences.
--
-- Instances of 'Enum' may be derived for any enumeration type (types
-- whose constructors have no fields). The nullary constructors are
-- assumed to be numbered left-to-right by 'fromEnum' from @0@ through @n-1@.
-- See Chapter 10 of the /Haskell Report/ for more details.
--
-- For any type that is an instance of class 'Bounded' as well as 'Enum',
-- the following should hold:
--
-- * The calls @'succ' 'maxBound'@ and @'pred' 'minBound'@ should result in
-- a runtime error.
--
-- * 'fromEnum' and 'toEnum' should give a runtime error if the
-- result value is not representable in the result type.
-- For example, @'toEnum' 7 :: 'Bool'@ is an error.
--
-- * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound,
-- thus:
--
-- > enumFrom x = enumFromTo x maxBound
-- > enumFromThen x y = enumFromThenTo x y bound
-- > where
-- > bound | fromEnum y >= fromEnum x = maxBound
-- > | otherwise = minBound
--
class Enum a where
-- | the successor of a value. For numeric types, 'succ' adds 1.
succ :: a -> a
-- | the predecessor of a value. For numeric types, 'pred' subtracts 1.
pred :: a -> a
-- | Convert from an 'Int'.
toEnum :: Int -> a
-- | Convert to an 'Int'.
-- It is implementation-dependent what 'fromEnum' returns when
-- applied to a value that is too large to fit in an 'Int'.
fromEnum :: a -> Int
-- | Used in Haskell's translation of @[n..]@.
enumFrom :: a -> [a]
-- | Used in Haskell's translation of @[n,n'..]@.
enumFromThen :: a -> a -> [a]
-- | Used in Haskell's translation of @[n..m]@.
enumFromTo :: a -> a -> [a]
-- | Used in Haskell's translation of @[n,n'..m]@.
enumFromThenTo :: a -> a -> a -> [a]
succ = toEnum . (+ 1) . fromEnum
pred = toEnum . (subtract 1) . fromEnum
enumFrom x = map toEnum [fromEnum x ..]
enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromTo x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
-- Default methods for bounded enumerations
boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]
boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]
boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]
boundedEnumFromThen n1 n2
| i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]
| otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]
where
i_n1 = fromEnum n1
i_n2 = fromEnum n2
------------------------------------------------------------------------
-- Helper functions
------------------------------------------------------------------------
{-# NOINLINE toEnumError #-}
toEnumError :: (Show a) => String -> Int -> (a,a) -> b
toEnumError inst_ty i bnds =
errorWithoutStackTrace $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++
show i ++
") is outside of bounds " ++
show bnds
{-# NOINLINE fromEnumError #-}
fromEnumError :: (Show a) => String -> a -> b
fromEnumError inst_ty x =
errorWithoutStackTrace $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++
show x ++
") is outside of Int's bounds " ++
show (minBound::Int, maxBound::Int)
{-# NOINLINE succError #-}
succError :: String -> a
succError inst_ty =
errorWithoutStackTrace $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound"
{-# NOINLINE predError #-}
predError :: String -> a
predError inst_ty =
errorWithoutStackTrace $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound"
------------------------------------------------------------------------
-- Tuples
------------------------------------------------------------------------
instance Bounded () where
minBound = ()
maxBound = ()
instance Enum () where
succ _ = errorWithoutStackTrace "Prelude.Enum.().succ: bad argument"
pred _ = errorWithoutStackTrace "Prelude.Enum.().pred: bad argument"
toEnum x | x == 0 = ()
| otherwise = errorWithoutStackTrace "Prelude.Enum.().toEnum: bad argument"
fromEnum () = 0
enumFrom () = [()]
enumFromThen () () = let many = ():many in many
enumFromTo () () = [()]
enumFromThenTo () () () = let many = ():many in many
-- Report requires instances up to 15
instance (Bounded a, Bounded b) => Bounded (a,b) where
minBound = (minBound, minBound)
maxBound = (maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where
minBound = (minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where
minBound = (minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where
minBound = (minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f)
=> Bounded (a,b,c,d,e,f) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g)
=> Bounded (a,b,c,d,e,f,g) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h)
=> Bounded (a,b,c,d,e,f,g,h) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i)
=> Bounded (a,b,c,d,e,f,g,h,i) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j)
=> Bounded (a,b,c,d,e,f,g,h,i,j) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
------------------------------------------------------------------------
-- Bool
------------------------------------------------------------------------
instance Bounded Bool where
minBound = False
maxBound = True
instance Enum Bool where
succ False = True
succ True = errorWithoutStackTrace "Prelude.Enum.Bool.succ: bad argument"
pred True = False
pred False = errorWithoutStackTrace "Prelude.Enum.Bool.pred: bad argument"
toEnum n | n == 0 = False
| n == 1 = True
| otherwise = errorWithoutStackTrace "Prelude.Enum.Bool.toEnum: bad argument"
fromEnum False = 0
fromEnum True = 1
-- Use defaults for the rest
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
------------------------------------------------------------------------
-- Ordering
------------------------------------------------------------------------
instance Bounded Ordering where
minBound = LT
maxBound = GT
instance Enum Ordering where
succ LT = EQ
succ EQ = GT
succ GT = errorWithoutStackTrace "Prelude.Enum.Ordering.succ: bad argument"
pred GT = EQ
pred EQ = LT
pred LT = errorWithoutStackTrace "Prelude.Enum.Ordering.pred: bad argument"
toEnum n | n == 0 = LT
| n == 1 = EQ
| n == 2 = GT
toEnum _ = errorWithoutStackTrace "Prelude.Enum.Ordering.toEnum: bad argument"
fromEnum LT = 0
fromEnum EQ = 1
fromEnum GT = 2
-- Use defaults for the rest
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
------------------------------------------------------------------------
-- Char
------------------------------------------------------------------------
instance Bounded Char where
minBound = '\0'
maxBound = '\x10FFFF'
instance Enum Char where
succ (C# c#)
| isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#))
| otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.succ: bad argument")
pred (C# c#)
| isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#))
| otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.pred: bad argument")
toEnum = chr
fromEnum = ord
{-# INLINE enumFrom #-}
enumFrom (C# x) = eftChar (ord# x) 0x10FFFF#
-- Blarg: technically I guess enumFrom isn't strict!
{-# INLINE enumFromTo #-}
enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y)
{-# INLINE enumFromThen #-}
enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2)
{-# INLINE enumFromThenTo #-}
enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y)
-- See Note [How the Enum rules work]
{-# RULES
"eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y)
"efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2)
"efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l)
"eftCharList" [1] eftCharFB (:) [] = eftChar
"efdCharList" [1] efdCharFB (:) [] = efdChar
"efdtCharList" [1] efdtCharFB (:) [] = efdtChar
#-}
-- We can do better than for Ints because we don't
-- have hassles about arithmetic overflow at maxBound
{-# INLINE [0] eftCharFB #-}
eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
eftCharFB c n x0 y = go x0
where
go x | isTrue# (x ># y) = n
| otherwise = C# (chr# x) `c` go (x +# 1#)
{-# NOINLINE [1] eftChar #-}
eftChar :: Int# -> Int# -> String
eftChar x y | isTrue# (x ># y ) = []
| otherwise = C# (chr# x) : eftChar (x +# 1#) y
-- For enumFromThenTo we give up on inlining
{-# NOINLINE [0] efdCharFB #-}
efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
efdCharFB c n x1 x2
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF#
| otherwise = go_dn_char_fb c n x1 delta 0#
where
!delta = x2 -# x1
{-# NOINLINE [1] efdChar #-}
efdChar :: Int# -> Int# -> String
efdChar x1 x2
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF#
| otherwise = go_dn_char_list x1 delta 0#
where
!delta = x2 -# x1
{-# NOINLINE [0] efdtCharFB #-}
efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
efdtCharFB c n x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim
| otherwise = go_dn_char_fb c n x1 delta lim
where
!delta = x2 -# x1
{-# NOINLINE [1] efdtChar #-}
efdtChar :: Int# -> Int# -> Int# -> String
efdtChar x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim
| otherwise = go_dn_char_list x1 delta lim
where
!delta = x2 -# x1
go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_up_char_fb c n x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = n
| otherwise = C# (chr# x) `c` go_up (x +# delta)
go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_dn_char_fb c n x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = n
| otherwise = C# (chr# x) `c` go_dn (x +# delta)
go_up_char_list :: Int# -> Int# -> Int# -> String
go_up_char_list x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = []
| otherwise = C# (chr# x) : go_up (x +# delta)
go_dn_char_list :: Int# -> Int# -> Int# -> String
go_dn_char_list x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = []
| otherwise = C# (chr# x) : go_dn (x +# delta)
------------------------------------------------------------------------
-- Int
------------------------------------------------------------------------
{-
Be careful about these instances.
(a) remember that you have to count down as well as up e.g. [13,12..0]
(b) be careful of Int overflow
(c) remember that Int is bounded, so [1..] terminates at maxInt
-}
instance Bounded Int where
minBound = minInt
maxBound = maxInt
instance Enum Int where
succ x
| x == maxBound = errorWithoutStackTrace "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound"
| otherwise = x + 1
pred x
| x == minBound = errorWithoutStackTrace "Prelude.Enum.pred{Int}: tried to take `pred' of minBound"
| otherwise = x - 1
toEnum x = x
fromEnum x = x
{-# INLINE enumFrom #-}
enumFrom (I# x) = eftInt x maxInt#
where !(I# maxInt#) = maxInt
-- Blarg: technically I guess enumFrom isn't strict!
{-# INLINE enumFromTo #-}
enumFromTo (I# x) (I# y) = eftInt x y
{-# INLINE enumFromThen #-}
enumFromThen (I# x1) (I# x2) = efdInt x1 x2
{-# INLINE enumFromThenTo #-}
enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y
-----------------------------------------------------
-- eftInt and eftIntFB deal with [a..b], which is the
-- most common form, so we take a lot of care
-- In particular, we have rules for deforestation
{-# RULES
"eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
"eftIntList" [1] eftIntFB (:) [] = eftInt
#-}
{- Note [How the Enum rules work]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Phase 2: eftInt ---> build . eftIntFB
* Phase 1: inline build; eftIntFB (:) --> eftInt
* Phase 0: optionally inline eftInt
-}
{-# NOINLINE [1] eftInt #-}
eftInt :: Int# -> Int# -> [Int]
-- [x1..x2]
eftInt x0 y | isTrue# (x0 ># y) = []
| otherwise = go x0
where
go x = I# x : if isTrue# (x ==# y)
then []
else go (x +# 1#)
{-# INLINE [0] eftIntFB #-}
eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
eftIntFB c n x0 y | isTrue# (x0 ># y) = n
| otherwise = go x0
where
go x = I# x `c` if isTrue# (x ==# y)
then n
else go (x +# 1#)
-- Watch out for y=maxBound; hence ==, not >
-- Be very careful not to have more than one "c"
-- so that when eftInfFB is inlined we can inline
-- whatever is bound to "c"
-----------------------------------------------------
-- efdInt and efdtInt deal with [a,b..] and [a,b..c].
-- The code is more complicated because of worries about Int overflow.
-- See Note [How the Enum rules work]
{-# RULES
"efdtInt" [~1] forall x1 x2 y.
efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y)
"efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt
#-}
efdInt :: Int# -> Int# -> [Int]
-- [x1,x2..maxInt]
efdInt x1 x2
| isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y
| otherwise = case minInt of I# y -> efdtIntDn x1 x2 y
{-# NOINLINE [1] efdtInt #-}
efdtInt :: Int# -> Int# -> Int# -> [Int]
-- [x1,x2..y]
efdtInt x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y
| otherwise = efdtIntDn x1 x2 y
{-# INLINE [0] efdtIntFB #-}
efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntFB c n x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y
| otherwise = efdtIntDnFB c n x1 x2 y
-- Requires x2 >= x1
efdtIntUp :: Int# -> Int# -> Int# -> [Int]
efdtIntUp x1 x2 y -- Be careful about overflow!
| isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1]
| otherwise = -- Common case: x1 <= x2 <= y
let !delta = x2 -# x1 -- >= 0
!y' = y -# delta -- x1 <= y' <= y; hence y' is representable
-- Invariant: x <= y
-- Note that: z <= y' => z + delta won't overflow
-- so we are guaranteed not to overflow if/when we recurse
go_up x | isTrue# (x ># y') = [I# x]
| otherwise = I# x : go_up (x +# delta)
in I# x1 : go_up x2
-- Requires x2 >= x1
efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntUpFB c n x1 x2 y -- Be careful about overflow!
| isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n
| otherwise = -- Common case: x1 <= x2 <= y
let !delta = x2 -# x1 -- >= 0
!y' = y -# delta -- x1 <= y' <= y; hence y' is representable
-- Invariant: x <= y
-- Note that: z <= y' => z + delta won't overflow
-- so we are guaranteed not to overflow if/when we recurse
go_up x | isTrue# (x ># y') = I# x `c` n
| otherwise = I# x `c` go_up (x +# delta)
in I# x1 `c` go_up x2
-- Requires x2 <= x1
efdtIntDn :: Int# -> Int# -> Int# -> [Int]
efdtIntDn x1 x2 y -- Be careful about underflow!
| isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1]
| otherwise = -- Common case: x1 >= x2 >= y
let !delta = x2 -# x1 -- <= 0
!y' = y -# delta -- y <= y' <= x1; hence y' is representable
-- Invariant: x >= y
-- Note that: z >= y' => z + delta won't underflow
-- so we are guaranteed not to underflow if/when we recurse
go_dn x | isTrue# (x <# y') = [I# x]
| otherwise = I# x : go_dn (x +# delta)
in I# x1 : go_dn x2
-- Requires x2 <= x1
efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntDnFB c n x1 x2 y -- Be careful about underflow!
| isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n
| otherwise = -- Common case: x1 >= x2 >= y
let !delta = x2 -# x1 -- <= 0
!y' = y -# delta -- y <= y' <= x1; hence y' is representable
-- Invariant: x >= y
-- Note that: z >= y' => z + delta won't underflow
-- so we are guaranteed not to underflow if/when we recurse
go_dn x | isTrue# (x <# y') = I# x `c` n
| otherwise = I# x `c` go_dn (x +# delta)
in I# x1 `c` go_dn x2
------------------------------------------------------------------------
-- Word
------------------------------------------------------------------------
instance Bounded Word where
minBound = 0
-- use unboxed literals for maxBound, because GHC doesn't optimise
-- (fromInteger 0xffffffff :: Word).
#if WORD_SIZE_IN_BITS == 32
maxBound = W# (int2Word# 0xFFFFFFFF#)
#elif WORD_SIZE_IN_BITS == 64
maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#)
#else
#error Unhandled value for WORD_SIZE_IN_BITS
#endif
instance Enum Word where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word"
toEnum i@(I# i#)
| i >= 0 = W# (int2Word# i#)
| otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word)
fromEnum x@(W# x#)
| x <= maxIntWord = I# (word2Int# x#)
| otherwise = fromEnumError "Word" x
enumFrom n = map integerToWordX [wordToIntegerX n .. wordToIntegerX (maxBound :: Word)]
enumFromTo n1 n2 = map integerToWordX [wordToIntegerX n1 .. wordToIntegerX n2]
enumFromThenTo n1 n2 m = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX m]
enumFromThen n1 n2 = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX limit]
where
limit :: Word
limit | n2 >= n1 = maxBound
| otherwise = minBound
maxIntWord :: Word
-- The biggest word representable as an Int
maxIntWord = W# (case maxInt of I# i -> int2Word# i)
-- For some reason integerToWord and wordToInteger (GHC.Integer.Type)
-- work over Word#
integerToWordX :: Integer -> Word
integerToWordX i = W# (integerToWord i)
wordToIntegerX :: Word -> Integer
wordToIntegerX (W# x#) = wordToInteger x#
------------------------------------------------------------------------
-- Integer
------------------------------------------------------------------------
instance Enum Integer where
succ x = x + 1
pred x = x - 1
toEnum (I# n) = smallInteger n
fromEnum n = I# (integerToInt n)
{-# INLINE enumFrom #-}
{-# INLINE enumFromThen #-}
{-# INLINE enumFromTo #-}
{-# INLINE enumFromThenTo #-}
enumFrom x = enumDeltaInteger x 1
enumFromThen x y = enumDeltaInteger x (y-x)
enumFromTo x lim = enumDeltaToInteger x 1 lim
enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
-- See Note [How the Enum rules work]
{-# RULES
"enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y)
"efdtInteger" [~1] forall x d l. enumDeltaToInteger x d l = build (\c n -> enumDeltaToIntegerFB c n x d l)
"efdtInteger1" [~1] forall x l. enumDeltaToInteger x 1 l = build (\c n -> enumDeltaToInteger1FB c n x l)
"enumDeltaToInteger1FB" [1] forall c n x. enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x
"enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger
"enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger
"enumDeltaToInteger1" [1] enumDeltaToInteger1FB (:) [] = enumDeltaToInteger1
#-}
{- Note [Enum Integer rules for literal 1]
The "1" rules above specialise for the common case where delta = 1,
so that we can avoid the delta>=0 test in enumDeltaToIntegerFB.
Then enumDeltaToInteger1FB is nice and small and can be inlined,
which would allow the constructor to be inlined and good things to happen.
We match on the literal "1" both in phase 2 (rule "efdtInteger1") and
phase 1 (rule "enumDeltaToInteger1FB"), just for belt and braces
We do not do it for Int this way because hand-tuned code already exists, and
the special case varies more from the general case, due to the issue of overflows.
-}
{-# NOINLINE [0] enumDeltaIntegerFB #-}
enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
enumDeltaIntegerFB c x0 d = go x0
where go x = x `seq` (x `c` go (x+d))
{-# NOINLINE [1] enumDeltaInteger #-}
enumDeltaInteger :: Integer -> Integer -> [Integer]
enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)
-- strict accumulator, so
-- head (drop 1000000 [1 .. ]
-- works
{-# NOINLINE [0] enumDeltaToIntegerFB #-}
-- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
enumDeltaToIntegerFB :: (Integer -> a -> a) -> a
-> Integer -> Integer -> Integer -> a
enumDeltaToIntegerFB c n x delta lim
| delta >= 0 = up_fb c n x delta lim
| otherwise = dn_fb c n x delta lim
{-# NOINLINE [0] enumDeltaToInteger1FB #-}
-- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
enumDeltaToInteger1FB :: (Integer -> a -> a) -> a
-> Integer -> Integer -> a
enumDeltaToInteger1FB c n x0 lim = go (x0 :: Integer)
where
go x | x > lim = n
| otherwise = x `c` go (x+1)
{-# NOINLINE [1] enumDeltaToInteger #-}
enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
enumDeltaToInteger x delta lim
| delta >= 0 = up_list x delta lim
| otherwise = dn_list x delta lim
{-# NOINLINE [1] enumDeltaToInteger1 #-}
enumDeltaToInteger1 :: Integer -> Integer -> [Integer]
-- Special case for Delta = 1
enumDeltaToInteger1 x0 lim = go (x0 :: Integer)
where
go x | x > lim = []
| otherwise = x : go (x+1)
up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
up_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = n
| otherwise = x `c` go (x+delta)
dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
dn_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = n
| otherwise = x `c` go (x+delta)
up_list :: Integer -> Integer -> Integer -> [Integer]
up_list x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = []
| otherwise = x : go (x+delta)
dn_list :: Integer -> Integer -> Integer -> [Integer]
dn_list x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = []
| otherwise = x : go (x+delta)
| tjakway/ghcjvm | libraries/base/GHC/Enum.hs | bsd-3-clause | 30,077 | 0 | 15 | 8,302 | 7,762 | 4,159 | 3,603 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls #-}
{-| Ganeti-specific implementation of the Curl multi interface
(<http://curl.haxx.se/libcurl/c/libcurl-multi.html>).
TODO: Evaluate implementing and switching to
curl_multi_socket_action(3) interface, which is deemed to be more
performant for high-numbers of connections (but this is not the case
for Ganeti).
-}
{-
Copyright (C) 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.Curl.Multi where
import Control.Concurrent
import Control.Monad
import Data.IORef
import qualified Data.Map as Map
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal
import Foreign.Ptr
import Foreign.Storable
import Network.Curl
import Ganeti.Curl.Internal
import Ganeti.Logging
-- * Data types
-- | Empty data type denoting a Curl multi handle. Naming is similar to
-- "Network.Curl" types.
data CurlM_
-- | Type alias for a pointer to a Curl multi handle.
type CurlMH = Ptr CurlM_
-- | Our type alias for maps indexing 'CurlH' handles to the 'IORef'
-- for the Curl code.
type HandleMap = Map.Map CurlH (IORef CurlCode)
-- * FFI declarations
foreign import ccall
"curl_multi_init" curl_multi_init :: IO CurlMH
foreign import ccall
"curl_multi_cleanup" curl_multi_cleanup :: CurlMH -> IO CInt
foreign import ccall
"curl_multi_add_handle" curl_multi_add_handle :: CurlMH -> CurlH -> IO CInt
foreign import ccall
"curl_multi_remove_handle" curl_multi_remove_handle :: CurlMH -> CurlH ->
IO CInt
foreign import ccall
"curl_multi_perform" curl_multi_perform :: CurlMH -> Ptr CInt -> IO CInt
foreign import ccall
"curl_multi_info_read" curl_multi_info_read :: CurlMH -> Ptr CInt
-> IO (Ptr CurlMsg)
-- * Wrappers over FFI functions
-- | Adds an easy handle to a multi handle. This is a nicer wrapper
-- over 'curl_multi_add_handle' that fails for wrong codes.
curlMultiAddHandle :: CurlMH -> Curl -> IO ()
curlMultiAddHandle multi easy = do
r <- curlPrim easy $ \_ x -> curl_multi_add_handle multi x
when (toMCode r /= CurlmOK) .
fail $ "Failed adding easy handle to multi handle: " ++ show r
-- | Nice wrapper over 'curl_multi_info_read' that massages the
-- results into Haskell types.
curlMultiInfoRead :: CurlMH -> IO (Maybe CurlMsg, CInt)
curlMultiInfoRead multi =
alloca $ \ppending -> do
pmsg <- curl_multi_info_read multi ppending
pending <- peek ppending
msg <- if pmsg == nullPtr
then return Nothing
else Just `fmap` peek pmsg
return (msg, pending)
-- | Nice wrapper over 'curl_multi_perform'.
curlMultiPerform :: CurlMH -> IO (CurlMCode, CInt)
curlMultiPerform multi =
alloca $ \running -> do
mcode <- curl_multi_perform multi running
running' <- peek running
return (toMCode mcode, running')
-- * Helper functions
-- | Magical constant for the polling delay. This needs to be chosen such that:
--
-- * we don't poll too often; a slower poll allows the RTS to schedule
-- other threads, and let them work
--
-- * we don't want to pool too slow, so that Curl gets to act on the
-- handles that need it
pollDelayInterval :: Int
pollDelayInterval = 10000
-- | Writes incoming curl data to a list of strings, stored in an 'IORef'.
writeHandle :: IORef [String] -> Ptr CChar -> CInt -> CInt -> Ptr () -> IO CInt
writeHandle bufref cstr sz nelems _ = do
let full_sz = sz * nelems
hs_str <- peekCStringLen (cstr, fromIntegral full_sz)
modifyIORef bufref (hs_str:)
return full_sz
-- | Loops and extracts all pending messages from a Curl multi handle.
readMessages :: CurlMH -> HandleMap -> IO ()
readMessages mh hmap = do
(cmsg, pending) <- curlMultiInfoRead mh
case cmsg of
Nothing -> return ()
Just (CurlMsg msg eh res) -> do
logDebug $ "Got msg! msg " ++ show msg ++ " res " ++ show res ++
", " ++ show pending ++ " messages left"
let cref = (Map.!) hmap eh
writeIORef cref res
_ <- curl_multi_remove_handle mh eh
when (pending > 0) $ readMessages mh hmap
-- | Loops and polls curl until there are no more remaining handles.
performMulti :: CurlMH -> HandleMap -> CInt -> IO ()
performMulti mh hmap expected = do
(mcode, running) <- curlMultiPerform mh
delay <- case mcode of
CurlmCallMultiPerform -> return $ return ()
CurlmOK -> return $ threadDelay pollDelayInterval
code -> error $ "Received bad return code from" ++
"'curl_multi_perform': " ++ show code
logDebug $ "mcode: " ++ show mcode ++ ", remaining: " ++ show running
-- check if any handles are done and then retrieve their messages
when (expected /= running) $ readMessages mh hmap
-- and if we still have handles running, loop
when (running > 0) $ delay >> performMulti mh hmap running
-- | Template for the Curl error buffer.
errorBuffer :: String
errorBuffer = replicate errorBufferSize '\0'
-- | Allocate a NULL-initialised error buffer.
mallocErrorBuffer :: IO CString
mallocErrorBuffer = fst `fmap` newCStringLen errorBuffer
-- | Initialise a curl handle. This is just a wrapper over the
-- "Network.Curl" function 'initialize', plus adding our options.
makeEasyHandle :: (IORef [String], Ptr CChar, ([CurlOption], URLString))
-> IO Curl
makeEasyHandle (f, e, (opts, url)) = do
h <- initialize
setopts h opts
setopts h [ CurlWriteFunction (writeHandle f)
, CurlErrorBuffer e
, CurlURL url
, CurlFailOnError True
, CurlNoSignal True
, CurlProxy ""
]
return h
-- * Main multi-call work function
-- | Perform a multi-call against a list of nodes.
execMultiCall :: [([CurlOption], String)] -> IO [(CurlCode, String)]
execMultiCall ous = do
-- error buffers
errorbufs <- mapM (const mallocErrorBuffer) ous
-- result buffers
outbufs <- mapM (\_ -> newIORef []) ous
-- handles
ehandles <- mapM makeEasyHandle $ zip3 outbufs errorbufs ous
-- data.map holding handles to error code iorefs
hmap <- foldM (\m h -> curlPrim h (\_ hnd -> do
ccode <- newIORef CurlOK
return $ Map.insert hnd ccode m
)) Map.empty ehandles
mh <- curl_multi_init
mapM_ (curlMultiAddHandle mh) ehandles
performMulti mh hmap (fromIntegral $ length ehandles)
-- dummy code to keep the handles alive until here
mapM_ (\h -> curlPrim h (\_ _ -> return ())) ehandles
-- cleanup the multi handle
mh_cleanup <- toMCode `fmap` curl_multi_cleanup mh
when (mh_cleanup /= CurlmOK) .
logError $ "Non-OK return from multi_cleanup: " ++ show mh_cleanup
-- and now extract the data from the IORefs
mapM (\(e, b, h) -> do
s <- peekCString e
free e
cref <- curlPrim h (\_ hnd -> return $ (Map.!) hmap hnd)
ccode <- readIORef cref
result <- if ccode == CurlOK
then (concat . reverse) `fmap` readIORef b
else return s
return (ccode, result)
) $ zip3 errorbufs outbufs ehandles
| apyrgio/snf-ganeti | src/Ganeti/Curl/Multi.hs | bsd-2-clause | 8,411 | 0 | 19 | 1,947 | 1,636 | 833 | 803 | -1 | -1 |
module Mod180_A where
data T = T
x = T
| urbanslug/ghc | testsuite/tests/module/Mod180_A.hs | bsd-3-clause | 40 | 0 | 5 | 11 | 16 | 10 | 6 | 3 | 1 |
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
--primesUpTo num = sieve [2..num]
primesUpTo' :: Integer -> [Integer] -> [Integer]
primesUpTo' _ [] = []
primesUpTo' num (l:ls) = l : primesUpTo' num (filter (\x -> x `mod` l /= 0) ls)
primesUpTo :: Integer -> [Integer]
primesUpTo n = primesUpTo' n [2..n]
-- Project Euler: Problem 10
ans10 :: Integer -> Integer
ans10 n = sum.primesUpTo $ n
main :: IO ()
main = do
ip <- getContents
let ns = map read . tail . lines $ ip
mapM_ (putStrLn . show) $ map ans10 ns
| cbrghostrider/Hacking | HackerRank/Contests/ProjectEuler/010_summationOfPrimes.hs | mit | 884 | 0 | 13 | 161 | 214 | 113 | 101 | 12 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest ["lib/Control/Checkpointed.hs"]
| danidiaz/checkpointed-pipeline | tests/doctests.hs | mit | 101 | 0 | 6 | 15 | 30 | 17 | 13 | 4 | 1 |
module GHCJS.DOM.StorageQuota (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/StorageQuota.hs | mit | 42 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-|
Module: Octobunce.Types
Description: Define types for the Octobunce IRC bot library
Copyright: © 2014 Josh Holland
License: MIT
Maintainer: [email protected]
Stability: experimental
Portability: any
-}
module Octobunce.Types
( IrcMessage(..)
, IrcCommand(..)
,
) where
import Data.ByteString (ByteString)
import Control.Applicative
import Control.Monad.Trans
-- | Represent an IRC message, in either direction.
data IrcMessage = IrcMessage
{ ircMsgSource :: ByteString -- ^ The prefixed source part of the message.
, ircMsgCommand :: IrcCommand -- ^ The command or numeric response code.
, ircMsgArgs :: [ByteString] -- ^ Any arguments to the command.
} deriving Show
-- | Represent an IRC command or numeric response code.
data IrcCommand = IrcNumeric Int -- ^ A numeric response code; should be in [0,1000)
| IrcUnknown ByteString -- ^ Unrecognised command.
| IrcPass
| IrcNick
| IrcUser
| IrcOper
| IrcMode
| IrcService
| IrcQuit
| IrcSquit
| IrcJoin
| IrcPart
| IrcTopic
| IrcNames
| IrcList
| IrcInvite
| IrcKick
| IrcPrivmsg
| IrcNotice
| IrcMotd
| IrcLusers
| IrcVersion
| IrcStats
| IrcLinks
| IrcTime
| IrcConnect
| IrcTrace
| IrcAdmin
| IrcInfo
| IrcServlist
| IrcSquery
| IrcWho
| IrcWhois
| IrcWhowas
| IrcKill
| IrcPing
| IrcPong
| IrcError
| IrcAway
| IrcRehash
| IrcDie
| IrcRestart
| IrcSummon
| IrcUsers
| IrcWallops
| IrcUserhost
| IrcIson
deriving Show
data Nick bot = NickBS ByteString
| NickBot (bot -> ByteString)
class Octobunce bot where
nick :: Nick bot
nick = NickBS "octobunce"
type Address = ByteString
type Channel = ByteString
newtype ActionT bot m a = ActionT
{ unActionT :: m a
}
instance Monad m => Monad (ActionT bot m) where
return = ActionT . return
act >>= f = ActionT $ unActionT act >>= unActionT . f
instance Applicative m => Applicative (ActionT bot m) where
pure = ActionT . pure
f <*> act = ActionT $ unActionT f <*> unActionT act
instance Functor m => Functor (ActionT bot m) where
fmap f = ActionT . fmap f . unActionT
instance MonadTrans (ActionT bot) where
lift = ActionT
| jshholland/octobunce | src/Octobunce/Types.hs | mit | 2,885 | 0 | 9 | 1,201 | 491 | 289 | 202 | 78 | 0 |
{-# LANGUAGE Safe #-}
module SMTLib2.PP where
import Prelude hiding ((<>))
import SMTLib2.AST
import Text.PrettyPrint
import Numeric
import Data.List(genericReplicate)
class PP t where
pp :: t -> Doc
instance PP Bool where
pp True = text "true"
pp False = text "false"
instance PP Integer where
pp = integer
ppString :: String -> Doc
ppString = text . show
instance PP Name where
pp (N x) = text x
instance PP Ident where
pp (I x []) = pp x
pp (I x is) = parens (char '_' <+> pp x <+> fsep (map integer is))
instance PP Attr where
pp (Attr x v) = char ':' <> pp x <+> maybe empty pp v
instance PP Quant where
pp Forall = text "forall"
pp Exists = text "exists"
instance PP Expr where
pp expr =
case expr of
Lit l -> pp l
App c ty ts ->
case ts of
[] -> ppFun
_ -> parens (ppFun <+> fsep (map pp ts))
where ppFun = case ty of
Nothing -> pp c
Just t -> parens (text "as" <+> pp c <+> pp t)
Quant q bs e ->
case bs of
[] -> pp e
_ -> parens (pp q <+> parens (fsep (map pp bs)) $$ nest 2 (pp e))
Let ds e ->
case ds of
[] -> pp e
_ -> parens (text "let" <+> (parens (vcat (map pp ds)) $$ pp e))
Annot e as ->
case as of
[] -> pp e
_ -> parens (char '!' <+> pp e $$ nest 2 (vcat (map pp as)))
instance PP Binder where
pp (Bind x t) = parens (pp x <+> pp t)
instance PP Defn where
pp (Defn x e) = parens (pp x <+> pp e)
instance PP Type where
pp ty =
case ty of
TApp c ts ->
case ts of
[] -> pp c
_ -> parens (pp c <+> fsep (map pp ts))
TVar x -> pp x
instance PP Literal where
pp lit =
case lit of
LitBV n w ->
case divMod w 4 of
-- For the moment we do not print using HEX literals as
-- some solvers do not support them (how hard is that???)
-- (x,0) -> text "#x" <> text (pad x (showHex v ""))
_ -> text "#b" <> text (pad w (showIntAtBase 2 (head . show) v ""))
where pad digs xs = genericReplicate
(digs - fromIntegral (length xs)) '0' ++ xs
v = if n < 0 then 2^w + n else n
LitNum n -> integer n
LitFrac x -> text (show (fromRational x :: Double)) -- XXX: Good enough?
LitStr x -> ppString x
instance PP Option where
pp opt =
case opt of
OptPrintSuccess b -> std "print-success" b
OptExpandDefinitions b -> std "expand-definitions" b
OptInteractiveMode b -> std "interactive-mode" b
OptProduceProofs b -> std "produce-proofs" b
OptProduceUnsatCores b -> std "produce-unsat-cores" b
OptProduceModels b -> std "produce-models" b
OptProduceAssignments b -> std "produce-assignments" b
OptRegularOutputChannel s -> str "regular-output-channel" s
OptDiagnosticOutputChannel s -> str "diagnostic-output-channel" s
OptRandomSeed n -> std "random-seed" n
OptVerbosity n -> std "verbosity" n
OptAttr a -> pp a
where mk a b = char ':' <> text a <+> b
std a b = mk a (pp b)
str a b = mk a (ppString b)
instance PP InfoFlag where
pp info =
case info of
InfoAllStatistics -> mk "all-statistics"
InfoErrorBehavior -> mk "error-behavior"
InfoName -> mk "name"
InfoAuthors -> mk "authors"
InfoVersion -> mk "version"
InfoStatus -> mk "status"
InfoReasonUnknown -> mk "reason-unknown"
InfoAttr a -> pp a
where mk x = char ':' <> text x
instance PP Command where
pp cmd =
case cmd of
CmdSetLogic n -> std "set-logic" n
CmdSetOption o -> std "set-option" o
CmdSetInfo a -> std "set-info" a
CmdDeclareType x n -> mk "declare-sort" (pp x <+> integer n)
CmdDefineType x as t -> fun "define-sort" x as (pp t)
CmdDeclareConst x t -> mk "declare-const" (pp x <+> pp t)
CmdDeclareFun x ts t -> fun "declare-fun" x ts (pp t)
CmdDeclareDatatype name tyvars constructors ->
mk "declare-datatype" $ vcat [pp name, par tyvars . sep $ map constructor constructors]
CmdDeclareDatatypes types constructors ->
mk "declare-datatypes" $
vcat [ parens . sep . map argType $ types
, parens . sep . map constructorFamily $ constructors
]
where
constructorFamily (tyvars, cons) = par tyvars . sep $ map constructor cons
CmdDefineFun x bs t e -> fun "define-fun" x bs (pp t $$ nest 2 (pp e))
CmdPush n -> std "push" n
CmdPop n -> std "pop" n
CmdAssert e -> std "assert" e
CmdCheckSat -> one "check-sat"
CmdGetAssertions -> one "get-assertions"
CmdGetValue es -> mk "get-value" (parens (fsep (map pp es)))
CmdGetProof -> one "get-proof"
CmdGetUnsatCore -> one "get-unsat-core"
CmdGetInfo i -> std "get-info" i
CmdGetOption n -> std "get-option" n
CmdComment s -> vcat (map comment (lines s))
CmdExit -> one "exit"
where mk x d = parens (text x <+> d)
one x = mk x empty
std x a = mk x (pp a)
fun x y as d = mk x (pp y <+> parens (fsep (map pp as)) <+> d)
comment s = text ";" <+> text s
argType (x, t) = parens (pp x <+> pp t)
constructor (con, []) = pp con
constructor (con, args) = parens . sep $ pp con : map argType args
par [] doc = parens doc
par tyvars doc = parens (text "par" <+> parens (sep (map pp tyvars)) <+> doc)
instance PP Script where
pp (Script cs) = vcat (map pp cs)
| yav/smtLib | src/SMTLib2/PP.hs | mit | 5,906 | 0 | 21 | 2,102 | 2,226 | 1,051 | 1,175 | 145 | 1 |
import qualified ElfParser as ELF
import qualified Data.ByteString as B
import Arm.ArmType
import Arm.Core
import qualified Graphics.UI.Threepenny as UI
import System.Environment
import System.Exit (ExitCode(..), exitWith)
import System.IO
import System.Console.GetOpt
import Graphics.UI.Threepenny.Core
import Control.Monad
import Control.Monad.Reader
import Data.Monoid
import Data.IORef
import qualified Control.Monad.State as S
import qualified Data.Map as Map
import Text.Printf
import Data.Int (Int64)
getStaticDir :: IO FilePath
getStaticDir = return "./"
data Options = GetSectionHeader | GetHeader | GetProgramHeader | GetSections | GetHelp | StartGui
option :: [OptDescr Options]
option = [ Option ['p'] ["program-headers"] (NoArg GetProgramHeader) "List program headers",
Option ['s'] ["section-headers"] (NoArg GetSectionHeader) "List section headers",
Option ['S'] ["sections"] (NoArg GetSections) "List sections",
Option ['e'] ["header"] (NoArg GetHeader) "Show the elf header",
Option ['h'] ["help"] (NoArg GetHelp) "Show this message"]
parseArgs :: IO Options
parseArgs = do
argv <- getArgs
name <- getProgName
case parse argv of
([], _, _) -> return StartGui
([GetProgramHeader], file, []) -> return GetProgramHeader
([GetSectionHeader], file, []) -> return GetSectionHeader
([GetHeader], file, []) -> return GetHeader
([GetSections], file, []) -> return GetSections
([GetHelp], _, _) -> help name
(_, _, errs) -> die errs name
where
parse = getOpt Permute option
header name = "Usage: " ++ name ++ " [-hpse]"
info name = usageInfo (header name) option
dump = hPutStrLn stderr
die errs name = dump (concat errs ++ (info name)) >> exitWith (ExitFailure 1)
help name = dump (info name) >> exitWith ExitSuccess
main :: IO ()
main = do
opt <- parseArgs
input <- B.readFile "linker"
case opt of
StartGui -> do
static <- getStaticDir
startGUI defaultConfig {tpStatic=Just static} setup
_ -> case ELF.parse ELF.parseFile input of
Right value ->
case opt of
GetProgramHeader -> putStrLn $ show (ELF.programHeaders value)
GetSectionHeader -> putStrLn $ show (ELF.sectionHeaders value)
GetHeader -> putStrLn $ show (ELF.header value)
GetSections -> putStrLn $ show (ELF.sections value)
Left d -> putStrLn d
{--
- Make an element draggable
--}
draggable :: Element -> UI ()
draggable e = runFunction $ ffi "jsPlumb.getInstance().draggable($(%1))" e
{--
- Connect ui element
--}
connect :: Element -> Element -> UI ()
connect s t = runFunction $ ffi "jsPlumb.getInstance().connect({source:$(%1), target: $(%2)})" s t
{--
- Add all the javascript required
--}
setupJavascript :: Window -> UI Element
setupJavascript w = do
js1 <- UI.mkElement "script" #
set (UI.attr "src") "/static/js/jquery-ui.js" #
set (UI.attr "type") "text/javascript"
js2 <- UI.mkElement "script" #
set (UI.attr "src") "/static/js/jquery.jsPlumb-1.6.4-min.js" #
set (UI.attr "type") "text/javascript"
getHead w #+ [element js1, element js2]
setup :: Window -> UI ()
setup w = do
return w # set UI.title "ELF Parser"
UI.addStyleSheet w "style.css"
input <- liftIO $ B.readFile "linker"
case ELF.parse ELF.parseFile input of
Right value -> do
let Just (ELF.BinarySection sectionOffset stream) = ELF.sectionFromName ".text" value
setupJavascript w
div <- UI.div
body <- getBody w
element body #+ [element div]
canvas <- UI.div #. "asm-block"
{--on (domEvent "resize") body $ \_ -> do
width <- body # get elementWidth
height <- body # get elementHeight
element div # set text (printf "(%d,%d)" width height)--}
element body #+ ((UI.h1 # set UI.text "ELF Header") : (displayElfHeader (ELF.header value) ++ [element canvas]) {-++ [displayElfCanvas value] -})
runReaderT (displayElfTextSection (parseArmBlock 0 stream)) (canvas,value)
return ()
Left d -> do
getBody w #+ [UI.h1 # set UI.text ("Error while parsing: " ++ d)]
return ()
displayElfHeader :: ELF.ELFHeader -> [UI Element]
displayElfHeader ELF.ELFHeader {
ELF.magic=m,
ELF.format=c,
ELF.fileEndianness=e,
ELF.version=v,
ELF.osabi=abi,
ELF.objectType=t,
ELF.machine=arch,
ELF.entry=ent,
ELF.phoff=ph,
ELF.shoff=sh,
ELF.flags=f,
ELF.hsize=hs,
ELF.phentsize=phes,
ELF.phnum=phn,
ELF.shentsize=shes,
ELF.shnum=shn,
ELF.shstrndx=shsi} =
[UI.dlist #+ [
UI.ddef # set UI.text "e_ident",
UI.dterm # set UI.text (printf "%s, %s, %s, %s, %s" (show m) (show c) (show e) (show v) (show abi)),
UI.ddef # set UI.text "e_type",
UI.dterm # set UI.text (show t),
UI.ddef # set UI.text "e_machine",
UI.dterm # set UI.text (show arch),
UI.ddef # set UI.text "e_entry",
UI.dterm # set UI.text (show ent),
UI.ddef # set UI.text "e_phoff",
UI.dterm # set UI.text (show ph),
UI.ddef # set UI.text "e_shoff",
UI.dterm # set UI.text (show sh),
UI.ddef # set UI.text "e_flags",
UI.dterm # set UI.text (show f),
UI.ddef # set UI.text "e_ehsize",
UI.dterm # set UI.text (show hs),
UI.ddef # set UI.text "e_phentsize",
UI.dterm # set UI.text (show phes),
UI.ddef # set UI.text "e_phnum",
UI.dterm # set UI.text (show phn),
UI.ddef # set UI.text "e_shentsize",
UI.dterm # set UI.text (show shes),
UI.ddef # set UI.text "e_shnum",
UI.dterm # set UI.text (show shn),
UI.ddef # set UI.text "e_shstrndx",
UI.dterm # set UI.text (show shsi)]]
type BlockGraph = ReaderT (Element,ELF.ELFInfo) UI
askElement :: BlockGraph Element
askElement = do
(e,_) <- ask
return e
askInfo :: BlockGraph ELF.ELFInfo
askInfo = do
(_,i) <- ask
return i
makeNextBlockButton :: Int64 -> BlockGraph Element
makeNextBlockButton offset = do
info <- askInfo
let Just (ELF.BinarySection sectionOffset stream) = ELF.sectionFromName ".text" info
w <- askElement
buttonArm <- lift $ UI.button #. "button" #+ [string $ printf "Next Arm at: %d" offset]
buttonThumb <-lift $ UI.button #. "button" #+ [string $ printf "Next Thumb at: %d" offset]
lift $ (on UI.click buttonArm $ \_ -> do
runReaderT (displayElfTextSection $ parseArmBlock offset stream) (w,info))
lift $ (on UI.click buttonThumb $ \_ -> do
runReaderT (displayElfTextSection $ parseThumbBlock offset stream) (w,info))
lift $ UI.div #+ [element buttonArm, UI.br, element buttonThumb]
displayElfTextSection :: ArmBlock -> BlockGraph ()
displayElfTextSection block = do
info <- askInfo
let offset = offsetBlock block
let Just (ELF.BinarySection sectionOffset stream) = ELF.sectionFromName ".text" info
let instructions = instructionsBlock block
buttonNext <- sequence $ map makeNextBlockButton (nextBlocks block)
title <- lift $ UI.h4 # set UI.text (printf "Block at offset: %08X" (offset+sectionOffset))
listInstruction <- sequence $ map (displayInstruction (offset + sectionOffset)) instructions
displayBlock <- lift $ UI.div #+ listInstruction
body <- askElement
gridElem <- lift $ grid [[element title], [element displayBlock], fmap element buttonNext] # set (UI.attr "id") (printf "block%d" offset)
lift $ element gridElem # set UI.draggable True
{-- lift $ draggable gridElem --}
lift $ element body #+ [element gridElem]
return ()
displayInstruction :: Int64 -> ArmInstr -> BlockGraph (UI Element)
displayInstruction sectionOffset inst = do
info <- askInfo
case ELF.symbolAt info $ (instructionBlockOffset inst) + sectionOffset of
Just s -> return $ UI.p #+ [string (ELF.symbolName s), string ":", UI.br, string (show inst)]
Nothing -> return $ UI.p # set UI.text (show inst)
{------------------------------------------------------------------------------
- Drawing canvas with all the different section
-----------------------------------------------------------------------------}
{-- Using a canvas modified version of threepenny
displayElfCanvas :: ELF.ELFInfo -> UI Element
displayElfCanvas info = do
canvas <- UI.canvas #
set UI.height 1700 #
set UI.width 600 #
set style [("border", "solid black 1px")]
UI.renderDrawing canvas (
(UI.translate 0.0 50.0) <>
--(UI.scale 300.0 (-1600.0)) <>
(displayElfHeaderOffset info))
--(UI.openedPath red 0.001
-- ((UI.translate 150.0 1600.0) <>
-- (UI.scale 150.0 (-1600.0)) <>
-- (displayElfHeaderOffset info)) )
-- (UI.line (-1.0,0.9) (1.0,0.9))))
--(UI.move (150.0,100.0)) <>
--(UI.bezierCurve [(180.0,30.0), (250.0,180.0), (300.0,100.0)]))) <>
-- (UI.openedPath red 4.0 (UI.arc (125.0, 115.0) 30.0 0.0 360.0)))
element canvas
normalizeY :: Int64 -> Int -> Double
normalizeY value max= (((fromIntegral value) * 1640.0) / (fromIntegral max))
regionSeparator :: Int64 -> Int -> UI.DrawingPath
regionSeparator offset size = UI.line (0.0,offsetCoord) (300.0,offsetCoord)
where offsetCoord = normalizeY offset size
programSectionOffset :: Int -> ELF.ELFProgramHeader -> UI.Drawing
programSectionOffset size (ELF.ELFProgramHeader {ELF.phoffset=off}) =
(UI.openedPath red 2.0 (regionSeparator off size))
where red = UI.solidColor $ UI.rgbColor 0xFF 0 0
sectionOffset :: Int -> ELF.ELFSectionHeader -> UI.Drawing
sectionOffset size (ELF.ELFSectionHeader {ELF.shoffset=off, ELF.shname=sectionName}) =
(UI.openedPath blue 2.0 $ regionSeparator off size) <>
(UI.setDraw UI.textFont "bold 16px sans-serif") <>
(UI.setDraw UI.strokeStyle black) <>
(UI.fillText (show sectionName) (300.0, (normalizeY off size)))
where
blue = UI.solidColor $ UI.rgbColor 0x50 0x50 0xFF
black = UI.solidColor $ UI.rgbColor 0 0 0
initialOffsetMap :: [ELF.ELFSectionHeader] -> Int -> Map.Map Double Double
initialOffsetMap [] _ = Map.empty
initialOffsetMap ((ELF.ELFSectionHeader {ELF.shoffset=off}):xs) maxOffset = Map.insert initialPostion initialPostion (initialOffsetMap xs maxOffset)
where
initialPostion = normalizeY off maxOffset
sign :: Double -> Double
sign a | a >= 0.0 = 1.0
| a < 0.0 = -1.0
repulseForce :: Double -> Double -> Double -> Double
repulseForce origin distant preferedSign
| abs d > 100.0 = 0
| d < 0 = (-(100.0 + d)) / 15.0
| otherwise = (100.0 - d) / 15.0
where d = origin - distant
simbling :: Map.Map Double Double -> Double -> Map.Map Double Double
simbling mapOffset key = Map.filterWithKey checkRange mapOffset
where checkRange filterKey value = and [ key /= filterKey, (abs $ (mapOffset Map.! key) - value) < 100.0 ]
forceAt :: Map.Map Double Double -> Double -> Double
forceAt mapOffset key = (Map.foldl sumingForce 0.0 (simbling mapOffset key)) + ((key - origin) / 200.0)
where origin = (mapOffset Map.! key)
preferedSign = sign (key - origin)
sumingForce acc value = (repulseForce origin value preferedSign ) + acc
constrainForceAt :: Map.Map Double Double -> Int -> Double -> Double
constrainForceAt mapOffset maxValue key
| left < newValue && newValue < right = force
| newValue < left = min 0.0 (left + 0.000001 - oldValue)
| otherwise = max 0.0 (right - 0.000001 - oldValue)
where (left,right) = neighbour key mapOffset maxValue
force = forceAt mapOffset key
oldValue = (mapOffset Map.! key)
newValue = oldValue + force
neighbour :: Double -> Map.Map Double Double -> Int -> (Double,Double)
neighbour key mapOffset max
| mapSize == 1 = (0.0 , valueAt 0)
| keyIndex == 0 && mapSize > 1 = (0.0 , valueAt 1)
| keyIndex == mapSize - 1 = (valueAt $ mapSize - 1 , (normalizeY (fromIntegral max) max))
| otherwise = (valueAt $ keyIndex - 1 , min 1640.0 (valueAt $ keyIndex + 1))
where keyIndex = Map.findIndex key mapOffset
mapSize = Map.size mapOffset
valueAt index = snd $ Map.elemAt index mapOffset
forceBaseStep :: Map.Map Double Double -> Int -> Map.Map Double Double
forceBaseStep map max = foldl tranform map (Map.keys map)
where tranform currentMap key = Map.update (Just . ((constrainForceAt currentMap max key)+)) key currentMap
forceBaseLayout :: Map.Map Double Double -> Int -> Int -> Map.Map Double Double
forceBaseLayout mapOffset _ 0 = mapOffset
forceBaseLayout mapOffset max n = forceBaseLayout (forceBaseStep mapOffset max) max (n - 1)
layoutSectionName :: [ELF.ELFSectionHeader] -> Int -> Map.Map Double Double
layoutSectionName headers max = forceBaseLayout (initialOffsetMap headers max) max 450
drawSectionHeader :: ELF.ELFSectionHeader -> Int -> Map.Map Double Double -> UI.Drawing
drawSectionHeader (ELF.ELFSectionHeader {ELF.shname=sectionName,ELF.shoffset=off}) size layoutMap =
(UI.openedPath blue 2.0 (UI.line (0.0,position) (300.0,position))) <>
(UI.setDraw UI.textFont "bold 16px sans-serif") <>
(UI.setDraw UI.strokeStyle black) <>
(UI.openedPath blue 2.0 (UI.line (300.0,position) (380.0,textPosition))) <>
(UI.fillText (printf "%s (%.02g)" (show sectionName) textPosition) (380.0,textPosition))
where
position = normalizeY off size
textPosition = layoutMap Map.! position
blue = UI.solidColor $ UI.rgbColor 0x50 0x50 0xFF
black = UI.solidColor $ UI.rgbColor 0 0 0
drawSectionHeaders :: [ELF.ELFSectionHeader] -> Int -> Map.Map Double Double -> UI.Drawing
drawSectionHeaders [] _ _ = mempty
drawSectionHeaders (h:xs) size layoutMap = (drawSectionHeader h size layoutMap) <> (drawSectionHeaders xs size layoutMap)
layoutAndDrawSectionHeaders :: [ELF.ELFSectionHeader] -> Int -> UI.Drawing
layoutAndDrawSectionHeaders headers maxSize = drawSectionHeaders headers maxSize (layoutSectionName headers maxSize)
displayElfHeaderOffset :: ELF.ELFInfo -> UI.Drawing
displayElfHeaderOffset info =
--(mconcat (fmap (sectionOffset size) sh )) <>
(layoutAndDrawSectionHeaders shs size) <>
(mconcat (fmap (programSectionOffset size) phs ))
where
shs = ELF.sectionHeaders info
phs = ELF.programHeaders info
size = ELF.size info
green = UI.solidColor $ UI.rgbColor 0x20 0xFF 0
red = UI.solidColor $ UI.rgbColor 0xFF 0 0
--}
| mathk/arm-isa | Main.hs | mit | 15,564 | 0 | 20 | 4,197 | 2,861 | 1,445 | 1,416 | 181 | 7 |
-- Problems/Problem092Spec.hs
module Problems.Problem092Spec (main, spec) where
import Test.Hspec
import Problems.Problem092
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 92" $
it "Should evaluate to 8581146" $
p92 `shouldBe` 8581146
| Sgoettschkes/learning | haskell/ProjectEuler/tests/Problems/Problem092Spec.hs | mit | 272 | 0 | 8 | 51 | 73 | 41 | 32 | 9 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module FP15.Modules where
import Text.PrettyPrint
import GHC.Generics(Generic)
import Control.DeepSeq
import Data.Map.Strict(Map)
import FP15.Disp
import FP15.Name
import FP15.Expr
-- * Type Synonyms
type FFixity = Fixity F
type FlFixity = Fixity Fl
-- * Compilation
-- TODO belongs elsewhere
-- TODO moduleSource should be Maybe
data ModuleSource = ModuleSource { moduleFile :: !(Maybe String)
, moduleSource :: !String }
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ModuleSource where rnf x = seq x ()
data ModuleResolutionError = ModuleNotFound
| ParseError String
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ModuleResolutionError where rnf x = seq x ()
-- * Custom Operators
-- | An operator precedence is a pair of 'Int's, ordered by the first element,
-- then by the second element.
type Prec = (Int, Int)
data OperatorType = Prefix | LeftAssoc | RightAssoc | VarAssoc
deriving (Eq, Ord, Show, Read, Generic)
instance NFData OperatorType where rnf x = seq x ()
-- | Fixity declaration.
data Fixity a = Fixity OperatorType Prec (Name (a, Abs))
deriving (Eq, Ord, Show, Read, Generic)
instance NFData (Fixity a) where rnf x = seq x ()
type LocFixity a = Located (Fixity a)
-- TODO why is this here?
type FunctionalDefinition = ()
-- | The 'MIRef' type represents a reference to an item from a module interface.
-- This type is used to express lookups, imports, and exports.
data MIRef f fl op = MIF f | MIFl fl | MIOp op
deriving (Eq, Ord, Show, Read, Generic)
instance (NFData f, NFData fl, NFData op) => NFData (MIRef f fl op) where rnf x = seq x ()
-- | A selective import.
type SelImp = MIRef (Id F) (Id Fl) (Id Unknown)
newtype ModRename = ModRename ModuleName
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ModRename where rnf x = seq x ()
instance Disp ModRename where
pretty (ModRename m) = pretty m <+> text "=" <> space
data ImpQual = Unqual | Qual
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ImpQual where rnf x = seq x ()
instance Disp ImpQual where
pretty Unqual = text ""
pretty Qual = text "."
-- An import filter.
data ImpFilters = Selective ![SelImp] | Hiding ![SelImp]
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ImpFilters where rnf x = seq x ()
instance Disp ImpFilters where
pretty (Selective _) = text "(...)"
pretty (Hiding _) = text "-(...)"
-- An import statement.
data Import = Import { impModule :: !ModuleName
, impQual :: !ImpQual
, impRename :: !(Maybe ModRename)
, impFilters :: !(Maybe ImpFilters) }
deriving (Eq, Ord, Show, Read, Generic)
mkImport, mkImportQual :: ModuleName -> Import
mkImport m = Import m Unqual Nothing Nothing
mkImportQual m = Import m Qual Nothing Nothing
instance Disp Import where
pretty (Import m q r f)
= text "+" <> mp r <> pretty m <> pretty q <> mp f where
mp :: Disp a => Maybe a -> Doc
mp = maybe empty pretty
-- +Module import Module
-- +Module. import qualified Module
-- +M = Module import Module as M
-- +M = Module. import qualified Module as M
-- +Module(a) import Module(a)
-- +Module.(a) import qualified Module(a)
-- +M = Module(a) import Module(a) as M
-- +M = Module.(a) import qualified Module(a) as M
-- +Module-(a) import Module hiding (a)
instance NFData Import where rnf x = seq x ()
type ImportList = [Located Import]
type ExportList = [Located SelImp]
-- ** AST
data ModuleAST = ModuleAST { astMN :: !ModuleName
, astImps :: !ImportList
, astExps :: !ExportList
, astFs :: Map (LocId F) ExprAST
, astFls :: Map (LocId Fl) FunctionalAST
, astFFixes :: Map (LocId FOp) FFixity
, astFlFixes :: Map (LocId FlOp) FlFixity
}
deriving (Eq, Ord, Show, Read, Generic)
instance NFData ModuleAST where rnf x = seq x ()
| Ming-Tang/FP15 | src/FP15/Modules.hs | mit | 4,291 | 0 | 11 | 1,249 | 1,218 | 649 | 569 | 96 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html
module Stratosphere.ResourceProperties.OpsWorksStackSource where
import Stratosphere.ResourceImports
-- | Full data type definition for OpsWorksStackSource. See
-- 'opsWorksStackSource' for a more convenient constructor.
data OpsWorksStackSource =
OpsWorksStackSource
{ _opsWorksStackSourcePassword :: Maybe (Val Text)
, _opsWorksStackSourceRevision :: Maybe (Val Text)
, _opsWorksStackSourceSshKey :: Maybe (Val Text)
, _opsWorksStackSourceType :: Maybe (Val Text)
, _opsWorksStackSourceUrl :: Maybe (Val Text)
, _opsWorksStackSourceUsername :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON OpsWorksStackSource where
toJSON OpsWorksStackSource{..} =
object $
catMaybes
[ fmap (("Password",) . toJSON) _opsWorksStackSourcePassword
, fmap (("Revision",) . toJSON) _opsWorksStackSourceRevision
, fmap (("SshKey",) . toJSON) _opsWorksStackSourceSshKey
, fmap (("Type",) . toJSON) _opsWorksStackSourceType
, fmap (("Url",) . toJSON) _opsWorksStackSourceUrl
, fmap (("Username",) . toJSON) _opsWorksStackSourceUsername
]
-- | Constructor for 'OpsWorksStackSource' containing required fields as
-- arguments.
opsWorksStackSource
:: OpsWorksStackSource
opsWorksStackSource =
OpsWorksStackSource
{ _opsWorksStackSourcePassword = Nothing
, _opsWorksStackSourceRevision = Nothing
, _opsWorksStackSourceSshKey = Nothing
, _opsWorksStackSourceType = Nothing
, _opsWorksStackSourceUrl = Nothing
, _opsWorksStackSourceUsername = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-password
owssPassword :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssPassword = lens _opsWorksStackSourcePassword (\s a -> s { _opsWorksStackSourcePassword = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-revision
owssRevision :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssRevision = lens _opsWorksStackSourceRevision (\s a -> s { _opsWorksStackSourceRevision = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-sshkey
owssSshKey :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssSshKey = lens _opsWorksStackSourceSshKey (\s a -> s { _opsWorksStackSourceSshKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-type
owssType :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssType = lens _opsWorksStackSourceType (\s a -> s { _opsWorksStackSourceType = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-url
owssUrl :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssUrl = lens _opsWorksStackSourceUrl (\s a -> s { _opsWorksStackSourceUrl = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-username
owssUsername :: Lens' OpsWorksStackSource (Maybe (Val Text))
owssUsername = lens _opsWorksStackSourceUsername (\s a -> s { _opsWorksStackSourceUsername = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/OpsWorksStackSource.hs | mit | 3,555 | 0 | 12 | 397 | 628 | 355 | 273 | 47 | 1 |
-- |
-- Module : PhantomPhases.AST
-- Copyright : © 2019 Elias Castegren and Kiko Fernandez-Reyes
-- License : MIT
--
-- Stability : experimental
-- Portability : portable
--
-- This module includes functionality for creating an Abstract Syntax Tree (AST),
-- as well as helper functions for checking different
-- aspects of the AST. The AST abstract over their kind 'Phase', where
-- 'Phase' represent the current state of the AST. For example, after parsing
-- the AST is of 'Parsed' @Phase@; after type checking with 'PhantomFunctors.tcProgram' the
-- returned AST is of 'Checked' @Phase@, indicating that the AST has been
-- type checked.
{-# LANGUAGE NamedFieldPuns, KindSignatures, DataKinds #-}
module PhantomPhases.AST where
import Data.Maybe
import Data.List
import Text.Printf (printf)
type Name = String
-- | Check if a name is a constructor name
isConstructorName = (=="init")
-- * AST declarations
-- $
-- Declaration for the Abstract Syntax Tree of the language. This section
-- contains the type, class, methods, fields and expressions represented
-- as an AST. The AST is produced by a parser. For more information on
-- building parsers, we recommend to read
-- <https://hackage.haskell.org/package/megaparsec-7.0.5 megaparsec>.
-- | Representation of types abstracting over the 'Phase'
data Type (p :: Phase) =
ClassType Name
-- ^ Represents a class of name 'Name'
| IntType
-- ^ Represents integers
| BoolType
-- ^ Represents booleans
| Arrow {tparams :: [Type p], tresult :: Type p}
-- ^ Represents a function type
| UnitType
-- ^ Represents the unit (void) type
deriving (Eq)
instance Show (Type p) where
show (ClassType c) = c
show IntType = "int"
show BoolType = "bool"
show (Arrow ts t) = "(" ++ commaSep ts ++ ")" ++ " -> " ++ show t
show UnitType = "unit"
-- | The representation of a program in the form of an AST node.
newtype Program (ip :: Phase) =
-- | Programs are simply a list of class definitions ('ClassDef') in a certain 'Phase'
Program [ClassDef ip] deriving (Show)
-- | Phases that have already been passed. This has been thought as going
-- through different phases of a compiler. We assume that there is a total order
-- between phases.
data Phase = Parsed -- ^ -- ^ Initial status of an AST node after parsing
| Checked -- ^ Status of an AST node after type checking
-- | A representation of a class in the form of an AST node. As an example:
--
-- > class Foo:
-- > val x: Int
-- > var y: Bool
-- > def main(): Int
-- > 42
--
-- the code above, after parsing, would generate the following AST:
--
-- > ClassDef {cname = "Foo"
-- > ,fields = [FieldDef {fname = "x"
-- > ,ftype = IntType
-- > ,fmod = Val}]
-- > ,methods = [MethodDef {mname = "main"
-- > ,mparams = []
-- > ,mtype = IntType
-- > ,mbody = [IntLit {etype = Nothing, ival = 42}]
-- > }]}
data ClassDef (ip :: Phase) =
ClassDef {cname :: Name -- ^ String that represents the name of the class
,fields :: [FieldDef ip] -- ^ List of field definitions of a class
,methods :: [MethodDef ip] -- ^ List of method definitions of a class
}
instance Show (ClassDef ip) where
show ClassDef {cname, fields, methods} =
"class " ++ cname ++ concatMap show fields ++ concatMap show methods ++ "end"
-- | Field qualifiers in a class. It is thought for a made up syntax such as:
--
-- > class Foo:
-- > val x: Int
-- > var y: Bool
--
-- This indicates that the variable @x@ is immutable, and @y@ can be mutated.
--
data Mod = Var -- ^ Indicates that the field can be mutated
| Val -- ^ Indicates that the field is immutable
deriving (Eq)
instance Show Mod where
show Var = "var"
show Val = "val"
-- | Representation of a field declaration in the form of an AST node.
-- As an example, the following code:
--
-- > class Foo:
-- > val x: Int
--
-- could be parsed to the following field representation:
--
-- > FieldDef {fname = "x"
-- > ,ftype = IntType
-- > ,fmod = Val}
--
data FieldDef (p :: Phase) =
FieldDef {fname :: Name -- ^ Name of the field name
,ftype :: Type p -- ^ Type of the field
,fmod :: Mod -- ^ Field qualifier
}
-- | Helper function to check whether a 'FieldDef' is immutable.
isValField :: FieldDef p -> Bool
isValField FieldDef{fmod} = fmod == Val
-- | Helper function to check whether a 'FieldDef' is mutable.
isVarField :: FieldDef p -> Bool
isVarField = not . isValField
instance Show (FieldDef p) where
show FieldDef{fname, ftype, fmod} =
show fmod ++ " " ++ fname ++ " : " ++ show ftype
-- | Representation of parameters in the form of an AST.
data Param (p :: Phase) = Param {pname :: Name -- ^ Name of the parameter
,ptype :: Type p -- ^ Type of the parameter
}
instance Show (Param p) where
show Param{pname, ptype} = pname ++ " : " ++ show ptype
-- | Representation of a method declaration in the form of an AST. For example:
--
-- > class Foo:
-- > def main(): Int
-- > 42
--
-- the code above, after parsing, would generate the following AST:
--
-- > ClassDef {cname = "Foo"
-- > ,fields = []
-- > ,methods = [MethodDef {mname = "main"
-- > ,mparams = []
-- > ,mtype = IntType
-- > ,mbody = [IntLit {etype = Nothing, ival = 42}]
-- > }]}
--
data MethodDef (ip :: Phase) =
MethodDef {mname :: Name -- ^ Name of the method definition
,mparams :: [Param ip] -- ^ List of arguments to the method
,mtype :: Type ip -- ^ Return type
,mbody :: Expr ip -- ^ Body of the method
}
-- | Takes a list of things that can be shown, and creates a comma
-- separated string.
commaSep :: Show t => [t] -> String
commaSep = intercalate ", " . map show
instance Show (MethodDef ip) where
show MethodDef{mname, mparams, mtype, mbody} =
"def " ++ mname ++ "(" ++ commaSep mparams ++ ") : " ++
show mtype ++ show mbody
-- | Representation of integer operations
data Op = Add | Sub | Mul | Div deriving (Eq)
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
-- | Representation of expressions in the form of an AST node. The language
-- is expression-based, so there are no statements. As an example, the following
-- identity function:
--
-- > let id = \x: Int -> x
-- > in id 42
--
-- generates this 'Expr':
--
-- > Let {etype = Nothing
-- > ,name = "id"
-- > ,val = Lambda {etype = Nothing
-- > ,params = [Param "x" IntType]
-- > ,body = FunctionCall {etype = Nothing
-- > ,target = VarAccess Nothing "id"
-- > ,args = [IntLit Nothing 42]}
-- > }
-- > ,body :: Expr p
-- > }
-- >
data Expr (p :: Phase) =
-- | Representation of a boolean literal
BoolLit {etype :: Maybe (Type p) -- ^ Type of the expression
,bval :: Bool -- ^ The "Haskell" 'Bool' data constructor
}
| IntLit {etype :: Maybe (Type p) -- ^ Type of the expression
,ival :: Int
}
-- ^ Representation of an integer literal
| Null {etype :: Maybe (Type p) -- ^ Type of the expression
}
| Lambda {etype :: Maybe (Type p) -- ^ Type of the expression
,params :: [Param p] -- ^ List of arguments with their types ('Param')
,body :: Expr p -- ^ The body of the lambda abstraction
}
| VarAccess {etype :: Maybe (Type p) -- ^ Type of the expression
,name :: Name -- ^ Variable name
}
| FieldAccess {etype :: Maybe (Type p) -- ^ Type of the expression
,target :: Expr p -- ^ The target in a field access, e.g., @x.foo@, then @x@ is the target.
,name :: Name -- ^ Field name, e.g., @x.foo@, then @foo@ is the 'Name'
}
| Assignment {etype :: Maybe (Type p) -- ^ Type of the expression
,lhs :: Expr p -- ^ Left-hand side expression
,rhs :: Expr p -- ^ Right-hand side expression
}
| MethodCall {etype :: Maybe (Type p) -- ^ Type of the expression
,target :: Expr p -- ^ The target of a method call, e.g., @x.bar()@, then @x@ is the target
,name :: Name -- ^ The method name
,args :: [Expr p] -- ^ The arguments of the method call
}
| FunctionCall {etype :: Maybe (Type p) -- ^ Type of the expression
,target :: Expr p -- ^ The target of the function call, e.g., @bar()@, then @bar@ is the target
,args :: [Expr p] -- ^ The function arguments
}
| If {etype :: Maybe (Type p) -- ^ Type of the expression
,cond :: Expr p -- ^ The condition in the @if-else@ expression
,thn :: Expr p -- ^ The body of the @then@ branch
,els :: Expr p -- ^ The body of the @else@ branch
}
| Let {etype :: Maybe (Type p) -- ^ Type of the expression
,name :: Name -- ^ Variable name to bound a value to
,val :: Expr p -- ^ Expression that will bound variable @name@ with value @val@
,body :: Expr p -- ^ Body of the let expression
}
| BinOp {etype :: Maybe (Type p) -- ^ Type of the expression
,op :: Op -- ^ Binary operation
,lhs :: Expr p -- ^ Left-hand side expression
,rhs :: Expr p -- ^ Right-hand side expression
}
| New {etype :: Maybe (Type p) -- ^ The type of the expression
,ty :: Type p -- ^ The class that one instantiates, e.g., `new C`
,args :: [Expr p] -- ^ Constructor arguments
}
-- ^ It is useful to decouple the type of the expression from the type of the
-- instantiated class. This distinction becomes important whenever we have
-- subtyping, e.g., an interface `Animal` where `Animal x = new Dog`
| Cast {etype :: Maybe (Type p) -- ^ Type of the expression
,body :: Expr p -- ^ Body that will be casted to type @ty@
,ty :: Type p -- ^ The casting type
}
-- * Helper functions
-- $helper-functions
-- The helper functions of this section operate on AST nodes to check
-- for different properties. As an example, to check whether an expression
-- is a field, instead of having to pattern match in all places, i.e.,
--
-- > exampleFunction :: Expr -> Bool
-- > exampleFunction expr =
-- > -- does some stuff
-- > ...
-- > case expr of
-- > FieldAccess expr -> True
-- > _ -> False
-- >
-- we define the 'isFieldAccess' helper function, which checks
-- whether a given expression is a 'FieldAccess':
--
-- > exampleFunction :: Expr -> Bool
-- > exampleFunction expr =
-- > -- does some stuff
-- > ...
-- > isFieldAccess expr
-- >
-- | Constant for the name @this@, commonly used in object-oriented languages.
thisName :: Name
thisName = "this"
-- | Checks whether a 'Type' is a function (arrow) type
isArrowType :: (Type p) -> Bool
isArrowType Arrow {} = True
isArrowType _ = False
-- | Checks whether an expression is a 'FieldAccess'.
isFieldAccess :: Expr p -> Bool
isFieldAccess FieldAccess{} = True
isFieldAccess _ = False
-- | Checks whether an expression is a 'VarAccess'.
isVarAccess :: Expr p -> Bool
isVarAccess VarAccess{} = True
isVarAccess _ = False
-- | Checks whether an expression is a 'VarAccess' of 'this'.
isThisAccess :: Expr p -> Bool
isThisAccess VarAccess{name} = name == thisName
isThisAccess _ = False
-- | Checks whether an expression is an lval.
isLVal :: Expr p -> Bool
isLVal e = isFieldAccess e || isVarAccess e
instance Show (Expr p) where
show BoolLit{bval} = show bval
show IntLit{ival} = show ival
show Null{} = "null"
show Lambda{params, body} =
printf "fun (%s) => %s" (commaSep params) (show body)
show VarAccess{name} = name
show FieldAccess{target, name} =
printf "%s.%s" (show target) name
show Assignment{lhs, rhs} =
printf "%s = %s" (show lhs) (show rhs)
show MethodCall{target, name, args} =
printf "%s.%s(%s)" (show target) name (commaSep args)
show FunctionCall{target, args} =
printf "%s(%s)" (show target) (commaSep args)
show If{cond, thn, els} =
printf "if %s then %s else %s" (show cond) (show thn) (show els)
show Let{name, val, body} =
printf "let %s = %s in %s" name (show val) (show body)
show BinOp{op, lhs, rhs} =
printf "%s %s %s" (show lhs) (show op) (show rhs)
show New {ty, args} =
printf "new %s(%s)" (show ty) (commaSep args)
show Cast{body, ty} =
printf "%s : %s" (show body) (show ty)
-- | Helper function to check whether a 'Type' is a class
isClassType :: Type p -> Bool
isClassType (ClassType _) = True
isClassType _ = False
-- | Helper function to extract the type from an expression.
getType :: Expr 'Checked -> Type 'Checked
getType = fromJust . etype
-- | Sets the type of an expression @e@ to @t@.
setType :: Type 'Checked -> Expr 'Checked -> Expr 'Checked
setType t e = e{etype = Just t}
| kikofernandez/kikofernandez.github.io | files/monadic-typechecker/typechecker/src/PhantomPhases/AST.hs | mit | 13,387 | 0 | 11 | 3,841 | 2,292 | 1,323 | 969 | 159 | 1 |
module Main where
import Layer
import Models
import Numeric.LinearAlgebra
import ImageProcess
import Optimization
import Trainer
import Data.Vector.Storable (Vector, length, toList)
main :: IO()
main =
do
let inputLayer = linearLayerInit 2 2
let sigmoidLayer = sigmoidLayerInit 2 2
let outputLayer = linearLayerInit 2 1 in
let model = Model [inputLayer, sigmoidLayer, outputLayer] in
let input = (1><2)[1.0, 2.0]::Matrix R in
let output = forward input model in
print output
testImageRegression :: FilePath -> IO()
testImageRegression filepath = do
imageM <- getImageInfo filepath
case imageM of
Nothing -> putStrLn "Nohthing ! Guess what happened ? :) " >> return ()
Just imagePixel8 ->
let rgbs = getImageRGBs imagePixel8
w = getImageWidth imagePixel8
h = getImageHeight imagePixel8
rgbsList = Data.Vector.Storable.toList rgbs
(rlist, glist, blist) = genRGBList rgbsList
Just rMat = genMatrixFromList rlist w h
Just gMat = genMatrixFromList glist w h
Just bMat = genMatrixFromList blist w h in
--- test
print "prepare the model!" >>
let rinputLayer = linearLayerInit w h
rreluLayer1 = reluLayerInit w h
rreluLayer2 = reluLayerInit w h
rreluLayer3 = reluLayerInit w h
routputLayer= linearLayerInit w h
rmodel = Model [rinputLayer, rreluLayer1, rreluLayer2, rreluLayer3, routputLayer]
ginputLayer = linearLayerInit w h
greluLayer1 = reluLayerInit w h
greluLayer2 = reluLayerInit w h
greluLayer3 = reluLayerInit w h
goutputLayer= linearLayerInit w h
gmodel = Model [ginputLayer, greluLayer1, greluLayer2, greluLayer3, goutputLayer]
binputLayer = linearLayerInit w h
breluLayer1 = reluLayerInit w h
breluLayer2 = reluLayerInit w h
breluLayer3 = reluLayerInit w h
boutputLayer= linearLayerInit w h
bmodel = Model [binputLayer, breluLayer1, breluLayer2, breluLayer3, boutputLayer] in
print "begin to train the model" >>
let trainConfig = TrainConfig {
trainConfigRowNum=w,
trainConfigColNum=h,
trainConfigLearningRate=0.95,
trainConfigMomentum=1.0,
trainConfigDecay=0.95,
trainConfigEpsilon=0.00001,
trainConfigBatchSize=100,
trainConfigOptimization="adadelta"
} in
trainSingleData rmodel trainConfig rMat
| neutronest/vortex | vortex/Main.hs | mit | 2,728 | 0 | 21 | 904 | 660 | 341 | 319 | 62 | 2 |
{-|
Module: ConfigParser
Description: Handles fetching and parsing of configuration information
-}
module ConfigParser (
getConfig,
getCommands,
getVerifiers,
commandName,
verifierName,
verifierPrefix,
buildCommandString,
listArgs,
Config,
Command
) where
import Data.List (sort, nub)
data Config = Config [Verifier] [Command] deriving Show
data Verifier = Verifier String String deriving Show
data Command = Command String String deriving Show
getConfig :: IO Config
getConfig = getConfigPath >>= parseFile
parseFile :: FilePath -> IO Config
parseFile path = readFile path >>= return . parseConfigString
parseConfigString :: String -> Config
parseConfigString str = Config verifiers commands
where
commands = map (\(key, val) -> Command key val) cmdPairs
verifiers = map (\(key, val) -> Verifier key val) verifierPairs
verifierPairs = extractFromConfig "verifier." configPairs
cmdPairs = extractFromConfig "command." configPairs
configPairs = foldl add [] $ filter ignorable (lines str)
add xs l = (parse l):xs
parse l = let (k, v') = span (/='=') l in (trim k, trim $ tail v')
ignorable l = (l /= "") && ('#' /= head l)
trim = f . f
where f = reverse . dropWhile (==' ')
getCommands (Config _ commands) = commands
getVerifiers (Config verifiers _) = verifiers
commandName (Command name _) = name
verifierName (Verifier name _) = name
verifierPrefix (Verifier _ prefix) = prefix
listArgs :: Command -> Maybe [String]
listArgs (Command _ cmd) = result
where
result = case (foldl parse init cmd) of
Just (_, _, args) -> Just (nub $ reverse args)
Nothing -> Nothing
-- First part is state machine for parse, second is buffer, third is results
init = Just ("none", "", [])
parse Nothing _ = Nothing
parse (Just carry) c = parse' carry c
parse' ("none", buffer, xs) '%' = Just ("open one", buffer, xs)
parse' ("none", buffer, xs) _ = Just ("none", buffer, xs)
parse' ("open one", buffer, xs) '%' = Just ("open two", buffer, xs)
parse' ("open one", buffer, xs) _ = Just ("none", buffer, xs)
parse' ("open two", buffer, xs) '%' = Just ("close one", buffer, xs)
parse' ("open two", buffer, xs) c = Just ("open two", c:buffer, xs)
parse' ("close one", buffer, xs) '%' = Just ("none", "", (reverse buffer):xs)
parse' ("close one", buffer, xs) _ = Nothing
buildCommandString :: Command -> [(String, String)] -> Maybe String
buildCommandString cmd args = result
where
result = case listArgs cmd of
Just cmdArgs -> if (hasAllArgs cmdArgs) then Just insertValues else Nothing
Nothing -> Nothing
hasAllArgs cmdArgs = (sort cmdArgs) == (sort (map fst args))
insertValues = foldl addArg cmdTemplate args
addArg str (name, value) = replace str ("%%" ++ name ++ "%%") value
Command _ cmdTemplate = cmd
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace [] _ _ = []
replace s find repl =
if take (length find) s == find
then repl ++ (replace (drop (length find) s) find repl)
else [head s] ++ (replace (tail s) find repl)
extractFromConfig prefix config = foldl addIfMatches [] config
where
addIfMatches c (key,val) = if startsWith prefix key then (strip key,val):c else c
strip key = drop (length prefix) key
startsWith (x:xs) (y:ys) = if x == y then startsWith xs ys else False
startsWith [] ys = True
startsWith xs [] = False
-- TODO: Check environment variable
getConfigPath = return "default.conf"
| splondike/samesame | ConfigParser.hs | gpl-2.0 | 3,602 | 0 | 13 | 860 | 1,339 | 716 | 623 | 74 | 10 |
{-# LANGUAGE RankNTypes #-}
module Main (main) where
import qualified Graphics.UI.SDL as SDL
import Shared.DrawingSimple
import Shared.Input
import Shared.Lifecycle
import Shared.Polling
import Shared.Utilities
title :: String
title = "lesson04"
size :: ScreenSize
size = (640, 480)
inWindow :: (SDL.Window -> IO ()) -> IO ()
inWindow = withSDL . withWindow title size
drawInWindow :: forall a. (RenderOperation -> IO a) -> IO ()
drawInWindow drawFunc = inWindow $ \window -> do
screenSurface <- SDL.getWindowSurface window
_ <- drawFunc $ drawOn window screenSurface
_ <- SDL.freeSurface screenSurface
return ()
surfacePaths :: [FilePath]
surfacePaths = [
"./assets/press.bmp" ,
"./assets/up.bmp" ,
"./assets/down.bmp" ,
"./assets/left.bmp" ,
"./assets/right.bmp" ]
selectSurface :: forall a. [a] -> KeyPress -> a
selectSurface surfaces KeyUp = surfaces !! 1
selectSurface surfaces KeyDown = surfaces !! 2
selectSurface surfaces KeyLeft = surfaces !! 3
selectSurface surfaces KeyRight = surfaces !! 4
selectSurface surfaces _ = head surfaces
handleKeyInput :: IO (Maybe SDL.Event) -> (KeyPress -> IO a) -> IO Bool
handleKeyInput stream keyHandler = do
maybeEvent <- stream
case maybeEvent of
Nothing -> return False
Just (SDL.QuitEvent _ _) -> return True
Just (SDL.KeyboardEvent _ _ _ _ _ keysym) -> do
_ <- keyHandler $ getKey keysym
return False
_ -> return False
main :: IO ()
main = drawInWindow $ \draw -> do
surfaces <- mapM getSurfaceFrom surfacePaths
let drawSurfaceForKey = draw . selectSurface surfaces
_ <- draw (head surfaces)
repeatUntilTrue $ handleKeyInput pollEvent drawSurfaceForKey
mapM_ SDL.freeSurface surfaces
| Rydgel/haskellSDL2Examples | src/lesson04.hs | gpl-2.0 | 1,765 | 0 | 14 | 372 | 562 | 283 | 279 | 50 | 4 |
{- |
Module : $Header$
Description : Signatures for the EnCL logic
Copyright : (c) Dominik Dietrich, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Types and functions for EnCL logic signatures
-}
module CSL.Sign
( Sign (Sign) -- EnCL Signatures
, opIds
, OpType (..) -- Operator Information attached to ids
, pretty -- pretty printing
, isLegalSignature -- is a signature ok?
, addToSig -- adds an id to the given Signature
, unite -- union of signatures
, emptySig -- empty signature
, isSubSigOf -- is subsiganture?
, sigDiff -- Difference of Signatures
, sigUnion -- Union for Logic.Logic
, lookupSym
, optypeFromArity
, addEPDefValToSig
, addEPDeclToSig
, addEPDomVarDeclToSig
) where
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Maybe
import Common.Id
import Common.Result
import Common.Doc
import Common.DocUtils
import CSL.TreePO (ClosedInterval (ClosedInterval))
import CSL.AS_BASIC_CSL
import CSL.Print_AS ()
data OpType = OpType { opArity :: Int
} deriving (Eq, Ord, Show)
defaultType :: OpType
defaultType = OpType { opArity = 0 }
optypeFromArity :: Int -> OpType
optypeFromArity i = defaultType { opArity = i }
-- | Datatype for EnCL Signatures
-- Signatures are just sets of Tokens for the operators
data Sign = Sign { items :: Map.Map Token OpType
, epvars :: Map.Map Token (Maybe APInt)
, epdecls :: Map.Map Token EPDecl
} deriving (Eq, Ord, Show)
opIds :: Sign -> Set.Set Id
opIds = Set.map simpleIdToId . Map.keysSet . items
-- | The empty signature, use this one to create new signatures
emptySig :: Sign
emptySig = Sign { items = Map.empty
, epvars = Map.empty
, epdecls = Map.empty
}
instance Pretty Sign where
pretty = printSign
-- | pretty printer for EnCL signatures
printSign :: Sign -> Doc
printSign s = vcat [ printEPVars $ Map.toList $ epvars s
, printEPDecls $ Map.elems $ epdecls s]
printEPVars :: [(Token, Maybe APInt)] -> Doc
printEPVars [] = empty
printEPVars l = hsep [text "set", sepBySemis $ map f l] where
f (x, Nothing) = pretty x
f (x, Just y) = hcat [pretty x, text "=", pretty y]
printEPDecls :: [EPDecl] -> Doc
printEPDecls l = vcat $ map f l where
f x = hsep [text "ep", pretty x]
-- | checks whether a Id is declared in the signature
lookupSym :: Sign -> Id -> Bool
lookupSym sig item = Map.member (idToSimpleId item) $ items sig
-- TODO: adapt the operations to new signature components
-- | determines whether a signature is valid. all sets are ok, so glued to true
isLegalSignature :: Sign -> Bool
isLegalSignature _ = True
-- | Basic function to extend a given signature by adding an item (id) to it
addToSig :: Sign -> Token -> OpType -> Sign
addToSig sig tok ot = sig {items = Map.insert tok ot $ items sig}
addEPDefValToSig :: Sign -> Token -> APInt -> Sign
addEPDefValToSig sig tok i
| mD == Nothing = error $ "addEPDefValToSig: The extended parameter"
++ " declaration for " ++ show tok ++ " is missing"
| otherwise = sig {epdecls = ed'}
where (mD, ed') = Map.insertLookupWithKey f tok err $ epdecls sig
err = error "addEPDefValToSig: dummyval"
f _ _ (EPDecl _ dom Nothing) = EPDecl tok dom $ Just i
f _ _ (EPDecl _ _ (Just j)) =
error $ "addEPDefValToSig: default value already set to "
++ show j
addEmptyEPDomVarDeclToSig :: Sign -> Token -> Sign
addEmptyEPDomVarDeclToSig sig tok = sig {epvars = ev'}
where ev' = Map.insertWith f tok Nothing $ epvars sig
f _ v = v
addEPDomVarDeclToSig :: Sign -> Token -> APInt -> Sign
addEPDomVarDeclToSig sig tok i = sig {epvars = ev'}
where ev' = Map.insertWith f tok (Just i) $ epvars sig
f _ (Just x)
| x == i = error $ "addEPDomVarDeclToSig: equal values for "
++ show tok
| otherwise = error $ "addEPDomVarDeclToSig: variable already"
++ " set to different value " ++ show tok ++ "="
++ show x
f n _ = n
-- | Adds an extended parameter declaration for a given domain and
-- eventually implicitly defined EP domain vars, e.g., for 'I = [0, n]'
-- 'n' is implicitly added
addEPDeclToSig :: Sign -> Token -> EPDomain -> Sign
addEPDeclToSig sig tok dom = g $ sig {epdecls = ed'}
where (mD, ed') = Map.insertLookupWithKey f tok epd $ epdecls sig
epd = EPDecl tok dom Nothing
f _ _ v@(EPDecl _ dom' _)
| dom' == dom = v
| otherwise = error $ "addEPDeclToSig: EP already"
++ " assigned another domain: " ++ show tok ++ "in"
++ show dom'
g s =
case (mD, dom) of
(Nothing, ClosedInterval a b) ->
case mapMaybe getEPVarRef [a, b] of
[] -> s
l -> foldl addEmptyEPDomVarDeclToSig s l
_ -> s
-- TODO: add support for epdecls and report errors if they do not match!
{- Two signatures s1 and s2 are compatible if the common part has the
following properties:
* if the default value of an extparam is defined in s1 and s2 it has to be the same
* if the domains (of extparams or vars) are both given, they must not be disjoint
* the arities must conincide for the same operator
-}
-- | Union of signatures
unite :: Sign -> Sign -> Sign
unite sig1 sig2 =
sig1 { items = Map.union (items sig1) $ items sig2
}
-- | Determines if sig1 is subsignature of sig2
isSubSigOf :: Sign -> Sign -> Bool
isSubSigOf sig1 sig2 = Map.isSubmapOf (items sig1) $ items sig2
-- | difference of Signatures
sigDiff :: Sign -> Sign -> Sign
sigDiff sig1 sig2 = sig1 {items = Map.difference (items sig1) $ items sig2}
-- | union of Signatures
-- or do I have to care about more things here?
sigUnion :: Sign -> Sign -> Result Sign
sigUnion s1 = Result [Diag Debug "All fine sigUnion" nullRange]
. Just . unite s1
| nevrenato/Hets_Fork | CSL/Sign.hs | gpl-2.0 | 6,499 | 0 | 13 | 2,007 | 1,533 | 814 | 719 | 115 | 3 |
{-| Module : Messages
License : GPL
Maintainer : [email protected]
Stability : experimental
Portability : portable
Datatype to represent error messages. One abstraction is the datatype
MessageBlock, which contains (atomic) pieces of information that are
reported in the error messages such as types, ranges and code fragments.
-}
module Helium.StaticAnalysis.Messages.Messages where
import Helium.Syntax.UHA_Syntax
import Helium.Syntax.UHA_Range
import Helium.Syntax.UHA_Utils ()
import Top.Types
import Helium.Utils.OneLiner
import Helium.Utils.Similarity (similar)
import Helium.Utils.Utils (internalError)
import Data.List (sortBy, partition)
import Data.Char (toUpper)
import Data.Function
type Message = [MessageLine]
data MessageLine = MessageOneLiner MessageBlock
| MessageTable [(Bool, MessageBlock, MessageBlock)] -- Bool: indented or not
| MessageHints String MessageBlocks
type MessageBlocks = [MessageBlock]
data MessageBlock = MessageString String
| MessageRange Range
| MessageType TpScheme
| MessagePredicate Predicate
| MessageOneLineTree OneLineTree
| MessageCompose MessageBlocks
class HasMessage a where
getRanges :: a -> [Range]
getMessage :: a -> Message
-- default definitions
getRanges _ = []
instance (HasMessage a, HasMessage b) => HasMessage (Either a b) where
getRanges = either getRanges getRanges
getMessage = either getMessage getMessage
instance Substitutable MessageLine where
sub |-> ml = case ml of
MessageOneLiner mb -> MessageOneLiner (sub |-> mb)
MessageTable table -> MessageTable [ (b, sub |-> mb1, sub |-> mb2) | (b, mb1, mb2) <- table ]
MessageHints s mbs -> MessageHints s (sub |-> mbs)
ftv ml = case ml of
MessageOneLiner mb -> ftv mb
MessageTable table -> ftv [ [mb1, mb2] | (_, mb1, mb2) <- table ]
MessageHints _ mbs -> ftv mbs
instance Substitutable MessageBlock where
sub |-> mb = case mb of
MessageType tp -> MessageType (sub |-> tp)
MessagePredicate p -> MessagePredicate (sub |-> p)
MessageCompose mbs -> MessageCompose (sub |-> mbs)
_ -> mb
ftv mb = case mb of
MessageType tp -> ftv tp
MessagePredicate p -> ftv p
MessageCompose mbs -> ftv mbs
_ -> []
-------------------------------------------------------------
-- Smart row constructors for tables
infixl 1 <:>, >:> -- very low priority
-- do not indent
(<:>) :: String -> MessageBlock -> (Bool, MessageBlock, MessageBlock)
s <:> mb = (False, MessageString s, mb)
-- indented row
(>:>) :: String -> MessageBlock -> (Bool, MessageBlock, MessageBlock)
s >:> mb = (True, MessageString s, mb)
-------------------------------------------------------------
-- Misc
data Entity = TypeSignature
| TypeVariable
| TypeConstructor
| Definition
| Constructor
| Variable
| Import
| ExportVariable
| ExportModule
| ExportConstructor
| ExportTypeConstructor
| Fixity
deriving Eq
sortMessages :: HasMessage a => [a] -> [a]
sortMessages = let f x y = compare (getRanges x) (getRanges y)
in sortBy f
sortNamesByRange :: Names -> Names
sortNamesByRange names =
let tupleList = [ (name, getNameRange name) | name <- names ]
(xs,ys) = partition (isImportRange . snd) tupleList
in map fst (sortBy (compare `on` snd ) ys ++ xs)
-- The first argument indicates whether numbers up to ten should be
-- printed "verbose"
ordinal :: Bool -> Int -> String
ordinal b i
| i >= 1 && i <= 10 && b = table !! (i - 1)
| i >= 0 = show i ++ extension i
| otherwise = internalError "Messages.hs"
"ordinal"
"can't show numbers smaller than 0"
where
table =
[ "first", "second", "third", "fourth", "fifth", "sixth","seventh"
, "eighth", "ninth", "tenth"
]
extension j
| j > 3 && i < 20 = "th"
| j `mod` 10 == 1 = "st"
| j `mod` 10 == 2 = "nd"
| j `mod` 10 == 3 = "rd"
| otherwise = "th"
showNumber :: Int -> String
showNumber i | i <= 10 && i >=0 = list !! i
| otherwise = show i
where list = [ "zero", "one", "two", "three", "four", "five"
, "six", "seven", "eight", "nine", "ten"
]
prettyOrList :: [String] -> String
prettyOrList [] = ""
prettyOrList [s] = s
prettyOrList xs = foldr1 (\x y -> x++", "++y) (init xs) ++ " or "++last xs
prettyAndList :: [String] -> String
prettyAndList [] = ""
prettyAndList [s] = s
prettyAndList xs = foldr1 (\x y -> x++", "++y) (init xs) ++ " and "++last xs
prettyNumberOfParameters :: Int -> String
prettyNumberOfParameters 0 = "no parameters"
prettyNumberOfParameters 1 = "1 parameter"
prettyNumberOfParameters n = show n++" parameters"
capitalize :: String -> String
capitalize [] = []
capitalize (x:xs) = toUpper x : xs
findSimilar :: Name -> Names -> Names
findSimilar n = filter (\x -> show n `similar` show x)
instance Show Entity where
show entity =
case entity of
TypeSignature -> "type signature"
TypeVariable -> "type variable"
TypeConstructor -> "type constructor"
Definition -> "definition"
Constructor -> "constructor"
Variable -> "variable"
Import -> "import"
ExportVariable -> "exported variable"
ExportModule -> "exported module"
ExportConstructor
-> "exported constructor"
ExportTypeConstructor
-> "exported type constructor"
Fixity -> "infix declaration"
| roberth/uu-helium | src/Helium/StaticAnalysis/Messages/Messages.hs | gpl-3.0 | 6,478 | 0 | 13 | 2,282 | 1,612 | 861 | 751 | 130 | 1 |
{-# LANGUAGE CPP, FlexibleInstances, IncoherentInstances#-}
module Time where
-- Code from quickcheck-instances package
import Test.QuickCheck
import Test.QuickCheck.Function
import qualified Data.Time as Time
import qualified Data.Time.Clock.TAI as Time
instance Arbitrary Time.Day where
arbitrary = Time.ModifiedJulianDay <$> (2000 +) <$> arbitrary
shrink = (Time.ModifiedJulianDay <$>) . shrink . Time.toModifiedJulianDay
instance CoArbitrary Time.Day where
coarbitrary = coarbitrary . Time.toModifiedJulianDay
instance Function Time.Day where
function = functionMap Time.toModifiedJulianDay Time.ModifiedJulianDay
instance Arbitrary Time.UniversalTime where
arbitrary = Time.ModJulianDate <$> (2000 +) <$> arbitrary
shrink = (Time.ModJulianDate <$>) . shrink . Time.getModJulianDate
instance CoArbitrary Time.UniversalTime where
coarbitrary = coarbitrary . Time.getModJulianDate
instance Arbitrary Time.DiffTime where
arbitrary = arbitrarySizedFractional
#if MIN_VERSION_time(1,3,0)
shrink = shrinkRealFrac
#else
shrink = (fromRational <$>) . shrink . toRational
#endif
instance CoArbitrary Time.DiffTime where
coarbitrary = coarbitraryReal
instance Function Time.DiffTime where
function = functionMap toRational fromRational
instance Arbitrary Time.UTCTime where
arbitrary =
Time.UTCTime
<$> arbitrary
<*> (fromRational . toRational <$> choose (0::Double, 86400))
shrink ut@(Time.UTCTime day dayTime) =
[ ut { Time.utctDay = d' } | d' <- shrink day ] ++
[ ut { Time.utctDayTime = t' } | t' <- shrink dayTime ]
instance CoArbitrary Time.UTCTime where
coarbitrary (Time.UTCTime day dayTime) =
coarbitrary day >< coarbitrary dayTime
instance Function Time.UTCTime where
function = functionMap (\(Time.UTCTime day dt) -> (day,dt))
(uncurry Time.UTCTime)
instance Arbitrary Time.NominalDiffTime where
arbitrary = arbitrarySizedFractional
shrink = shrinkRealFrac
instance CoArbitrary Time.NominalDiffTime where
coarbitrary = coarbitraryReal
instance Arbitrary Time.TimeZone where
arbitrary =
Time.TimeZone
<$> choose (-12*60,14*60) -- utc offset (m)
<*> arbitrary -- is summer time
<*> (sequence . replicate 4 $ choose ('A','Z'))
shrink tz@(Time.TimeZone minutes summerOnly name) =
[ tz { Time.timeZoneMinutes = m' } | m' <- shrink minutes ] ++
[ tz { Time.timeZoneSummerOnly = s' } | s' <- shrink summerOnly ] ++
[ tz { Time.timeZoneName = n' } | n' <- shrink name ]
instance CoArbitrary Time.TimeZone where
coarbitrary (Time.TimeZone minutes summerOnly name) =
coarbitrary minutes >< coarbitrary summerOnly >< coarbitrary name
instance Arbitrary Time.TimeOfDay where
arbitrary =
Time.TimeOfDay
<$> choose (0, 23) -- hour
<*> choose (0, 59) -- minute
<*> (fromRational . toRational <$> choose (0::Double, 60)) -- picoseconds, via double
shrink tod@(Time.TimeOfDay hour minute second) =
[ tod { Time.todHour = h' } | h' <- shrink hour ] ++
[ tod { Time.todMin = m' } | m' <- shrink minute ] ++
[ tod { Time.todSec = s' } | s' <- shrink second ]
instance CoArbitrary Time.TimeOfDay where
coarbitrary (Time.TimeOfDay hour minute second) =
coarbitrary hour >< coarbitrary minute >< coarbitrary second
instance Arbitrary Time.LocalTime where
arbitrary =
Time.LocalTime
<$> arbitrary
<*> arbitrary
shrink lt@(Time.LocalTime day tod) =
[ lt { Time.localDay = d' } | d' <- shrink day ] ++
[ lt { Time.localTimeOfDay = t' } | t' <- shrink tod ]
instance CoArbitrary Time.LocalTime where
coarbitrary (Time.LocalTime day tod) =
coarbitrary day >< coarbitrary tod
instance Arbitrary Time.ZonedTime where
arbitrary =
Time.ZonedTime
<$> arbitrary
<*> arbitrary
shrink zt@(Time.ZonedTime lt zone) =
[ zt { Time.zonedTimeToLocalTime = l' } | l' <- shrink lt ] ++
[ zt { Time.zonedTimeZone = z' } | z' <- shrink zone ]
instance CoArbitrary Time.ZonedTime where
coarbitrary (Time.ZonedTime lt zone) =
coarbitrary lt >< coarbitrary zone
instance Arbitrary Time.AbsoluteTime where
arbitrary =
Time.addAbsoluteTime
<$> arbitrary
<*> return Time.taiEpoch
shrink at =
(`Time.addAbsoluteTime` at) <$> shrink (Time.diffAbsoluteTime at Time.taiEpoch)
instance CoArbitrary Time.AbsoluteTime where
coarbitrary = coarbitrary . flip Time.diffAbsoluteTime Time.taiEpoch
| fcostantini/QuickFuzz | src/Time.hs | gpl-3.0 | 4,708 | 0 | 12 | 1,131 | 1,316 | 700 | 616 | 101 | 0 |
import Control.Applicative
import System.Directory
import System.Environment
import System.Process
import qualified Text.StringTemplate as ST
render :: String -> [(String,String)] -> String
render tmpl attribs = (ST.render . ST.setManyAttrib attribs . ST.newSTMP) tmpl
strtmpl = "prospino {\n basedir = \"$basedir$\"\n resultFileName = \"$result$\"\n remoteDir = \"$remotedir$\"\n}\n"
minfty :: Double
minfty = 50000.0
createRdirBName procname (mg,mn) =
let rdir = "montecarlo/admproject/SimplifiedSUSYlep/8TeV/scan_" ++ procname
basename = "SimplifiedSUSYlepN" ++ show mn ++ "G"++show mg ++ "QL" ++ show minfty ++ "C"++show (0.5*(mn+mg))++ "L" ++ show minfty ++ "NN" ++ show minfty ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set1"
in (rdir,basename)
datalst :: [ (Double,Double) ]
datalst = [ (mg,mn) | mg <- [ 200,250..1500 ], mn <- [ 50,100..mg-50] ]
-- datalst = [ (mq,mn) | mq <- [ 200,250..1300], mn <- [ 50,100..mq-50 ] ]
-- datalst = [ (1300,300) ]
fst3 (a,_,_) = a
snd3 (_,a,_) = a
trd3 (_,_,a) = a
main :: IO ()
main = do
args <- getArgs
let cfgfile = args !! 0
dirname = args !! 1
n1 = read (args !! 2) :: Int
n2 = read (args !! 3) :: Int
datasublst = (zip [1..] . drop (n1-1) . take n2) datalst
filenames = map ((,,) <$> fst <*> snd <*> createRdirBName "1step_2sg" . snd) datasublst
makecfg rdirbname = render strtmpl [ ("basedir", dirname )
, ("result", (snd rdirbname) ++"_xsecKfactor.json" )
, ("remotedir", (fst rdirbname) )
]
cfglst = map ((,,) <$> (\x-> "runprospino"++show x++".conf") . fst3
<*> snd3
<*> makecfg . trd3)
filenames
-- mapM_ print cfglst
setCurrentDirectory dirname
mapM_ (\(x,_,y)->writeFile x y) cfglst
mapM_ (\(x,(g,n),y) -> let c = cmd cfgfile x (g,n) in print c >> system c) cfglst
cmd cfgfile jobfile (g,n) = "/home2/iankim/repo/src/lhc-analysis-collection/analysis/runProspino gluinopair " ++ cfgfile ++ " " ++ show minfty ++ " " ++ show g ++ " --config=" ++ jobfile
| wavewave/lhc-analysis-collection | analysis/2013-07-26_prospino.hs | gpl-3.0 | 2,236 | 0 | 23 | 610 | 766 | 412 | 354 | 39 | 1 |
{- Copyright 2012 Dustin DeWeese
This file is part of peg.
peg 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.
peg 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 peg. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE CPP, ImplicitParams #-}
module Peg.Monad (module Peg.Monad, newVar, newSVar) where
import Peg.Types
import Peg.Parse
import qualified Peg.Constraints as C
import Peg.Constraints (newVar, newSVar)
import Peg.Utils
import Control.Applicative
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as M
import Control.Exception
import Data.List
import Data.Char (toUpper)
import Debug.Trace
-- | pop an argument from the stack, push onto argument stack
getArg check = do
force
x <- popStack
guard $ check x
pushArg x
pushStack x = modify (\(PegState s a w n c b p) -> PegState (x:s) a w n c b p)
appendStack x = modify (\(PegState s a w n c b p) -> PegState (x++s) a w n c b p)
popStack :: Peg Value
popStack = do PegState s a w n c b p <- get
guard . not $ null s
put $ PegState (tail s) a w n c b p
return $ head s
emptyStack :: Peg Bool
emptyStack = null . psStack <$> get
setStack s = modify (\(PegState _ a w n c b p) -> PegState s a w n c b p)
getStack :: Peg Stack
getStack = psStack <$> get
pushArg x = modify (\(PegState s a w n c b p) -> PegState s (x:a) w n c b p)
popArg :: Peg Value
popArg = do PegState s (x:a) w n c b p <- get
put $ PegState s a w n c b p
return x
peekArg :: Peg Value
peekArg = do PegState s (x:a) w n c b p <- get
return x
pushAnc x = modify $ \(PegState s a w n c b p) -> PegState s a w n c b (x:p)
popAnc :: Peg Stack
popAnc = do PegState s a w n c b (x:p) <- get
put $ PegState s a w n c b p
return x
hidingAnc f = popAnc >>= \a -> f >> pushAnc a
hidingAllAnc f = do PegState s a w n c b p <- get
put $ PegState s a w n c b []
f
PegState s' a' w' n' c' b' p' <- get
put $ PegState s' a' w' n' c' b' p
varBind vn x = modify $ \(PegState s a w n c b p) ->
PegState s a w n c (M.insert vn x b) p
getVarBindings :: Peg (Map String Value)
getVarBindings = psBindings <$> get
substStack :: Stack -> Peg Stack
substStack s = flip map s . f <$> getVarBindings
where f m (V n) | Just x <- n `M.lookup` m = x
f _ x = x
doWord w = do --checkUnify $ do
popStack
m <- psWords <$> get
pushArg (W w)
case w `M.lookup` m of
Nothing -> mzero
Just [x] -> x
Just x -> msum x
popArg
return ()
substAll bs x = foldr f x bs
where f (v@(V _), x) = substs v [x]
f (s@(S _), L x) = substs s x
f _ = id
checkUnify :: Peg () -> Peg ()
checkUnify m = do
PegState s _ _ _ _ _ p <- get
if topIs (isList ||. (== W "]")) s
then m
else case maybeAny (\x -> ((,) x) <$> unify (trim isStackVar s) (x ++ [S "_rest"]) []) p of
Nothing -> --trace (show $ map showStack p) $
pushAnc s >> m >> popAnc >> return ()
Just (s', b) -> do sv <- newSVar
trace (showStack s ++ " == " ++
showStack s') $ return ()
trace (show b) $ return ()
setStack [sv]
addConstraint ([sv], substAll b s')
mapM_ substBinding b
--where unifyS a b = trace (showStack a ++ " == " ++ showStack b) $ unify a b
substBinding = let ?eval = eval in C.substBinding
trim p [x] | p x = []
| otherwise = [x]
trim _ [] = []
trim p (x:xs) = x : trim p xs
addConstraint x = let ?eval = eval in C.addConstraint x >> return ()
substVar = let ?eval = eval in C.substVar
force = do
st <- get
case psStack st of
(W w : _) -> doWord w
#ifdef DEBUG
>> traceStack
#endif
(S s : _) -> (popStack >> addConstraint ([S s], [])) `mplus` do
v <- newVar
s' <- newSVar
popStack
pushStack s'
pushStack v
addConstraint ([v, s'], [S s])
_ -> return ()
bind nm l = modify $ \(PegState s a w n c b p) ->
PegState s a (minsert nm (f l) w) n c b p
where f l = do w <- popArg
--appendStack l
pushStack $ L l
pushStack $ W "$#"
force
pushArg w
unbind nm = modify $ \(PegState s a w n c b p) -> PegState s a (M.delete nm w) n c b p
eval s' = do
st@(PegState s a w n c b p) <- get
put $ PegState s' [] w n c b p
force
s'' <- getStack
put st
return s''
| HackerFoo/peg | Peg/Monad.hs | gpl-3.0 | 5,208 | 0 | 18 | 1,808 | 2,060 | 1,015 | 1,045 | 122 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module ArbitraryInstances where
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import Food2ForkAPI
import Test.QuickCheck
import Control.Applicative
instance Arbitrary B.ByteString where
arbitrary = fmap B.pack arbitrary
instance Arbitrary T.Text where
arbitrary = fmap T.pack arbitrary
instance Arbitrary SortOrder where
arbitrary = elements[Rating, Trendingness]
instance Arbitrary Recipe where
arbitrary = Recipe <$> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
<*> arbitrary
| moosingin3space/dailymenu | tests/ArbitraryInstances.hs | gpl-3.0 | 817 | 0 | 14 | 282 | 150 | 84 | 66 | 23 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.CloudIOT.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.CloudIOT.Types.Product where
import Network.Google.CloudIOT.Types.Sum
import Network.Google.Prelude
-- | The \`Status\` type defines a logical error model that is suitable for
-- different programming environments, including REST APIs and RPC APIs. It
-- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message
-- contains three pieces of data: error code, error message, and error
-- details. You can find out more about this error model and how to work
-- with it in the [API Design
-- Guide](https:\/\/cloud.google.com\/apis\/design\/errors).
--
-- /See:/ 'status' smart constructor.
data Status =
Status'
{ _sDetails :: !(Maybe [StatusDetailsItem])
, _sCode :: !(Maybe (Textual Int32))
, _sMessage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Status' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sDetails'
--
-- * 'sCode'
--
-- * 'sMessage'
status
:: Status
status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing}
-- | A list of messages that carry the error details. There is a common set
-- of message types for APIs to use.
sDetails :: Lens' Status [StatusDetailsItem]
sDetails
= lens _sDetails (\ s a -> s{_sDetails = a}) .
_Default
. _Coerce
-- | The status code, which should be an enum value of google.rpc.Code.
sCode :: Lens' Status (Maybe Int32)
sCode
= lens _sCode (\ s a -> s{_sCode = a}) .
mapping _Coerce
-- | A developer-facing error message, which should be in English. Any
-- user-facing error message should be localized and sent in the
-- google.rpc.Status.details field, or localized by the client.
sMessage :: Lens' Status (Maybe Text)
sMessage = lens _sMessage (\ s a -> s{_sMessage = a})
instance FromJSON Status where
parseJSON
= withObject "Status"
(\ o ->
Status' <$>
(o .:? "details" .!= mempty) <*> (o .:? "code") <*>
(o .:? "message"))
instance ToJSON Status where
toJSON Status'{..}
= object
(catMaybes
[("details" .=) <$> _sDetails,
("code" .=) <$> _sCode,
("message" .=) <$> _sMessage])
-- | Response for \`UnbindDeviceFromGateway\`.
--
-- /See:/ 'unbindDeviceFromGatewayResponse' smart constructor.
data UnbindDeviceFromGatewayResponse =
UnbindDeviceFromGatewayResponse'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnbindDeviceFromGatewayResponse' with the minimum fields required to make a request.
--
unbindDeviceFromGatewayResponse
:: UnbindDeviceFromGatewayResponse
unbindDeviceFromGatewayResponse = UnbindDeviceFromGatewayResponse'
instance FromJSON UnbindDeviceFromGatewayResponse
where
parseJSON
= withObject "UnbindDeviceFromGatewayResponse"
(\ o -> pure UnbindDeviceFromGatewayResponse')
instance ToJSON UnbindDeviceFromGatewayResponse where
toJSON = const emptyObject
-- | The device state, as reported by the device.
--
-- /See:/ 'deviceState' smart constructor.
data DeviceState =
DeviceState'
{ _dsUpdateTime :: !(Maybe DateTime')
, _dsBinaryData :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeviceState' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dsUpdateTime'
--
-- * 'dsBinaryData'
deviceState
:: DeviceState
deviceState = DeviceState' {_dsUpdateTime = Nothing, _dsBinaryData = Nothing}
-- | [Output only] The time at which this state version was updated in Cloud
-- IoT Core.
dsUpdateTime :: Lens' DeviceState (Maybe UTCTime)
dsUpdateTime
= lens _dsUpdateTime (\ s a -> s{_dsUpdateTime = a})
. mapping _DateTime
-- | The device state data.
dsBinaryData :: Lens' DeviceState (Maybe ByteString)
dsBinaryData
= lens _dsBinaryData (\ s a -> s{_dsBinaryData = a})
. mapping _Bytes
instance FromJSON DeviceState where
parseJSON
= withObject "DeviceState"
(\ o ->
DeviceState' <$>
(o .:? "updateTime") <*> (o .:? "binaryData"))
instance ToJSON DeviceState where
toJSON DeviceState'{..}
= object
(catMaybes
[("updateTime" .=) <$> _dsUpdateTime,
("binaryData" .=) <$> _dsBinaryData])
-- | Represents a textual expression in the Common Expression Language (CEL)
-- syntax. CEL is a C-like expression language. The syntax and semantics of
-- CEL are documented at https:\/\/github.com\/google\/cel-spec. Example
-- (Comparison): title: \"Summary size limit\" description: \"Determines if
-- a summary is less than 100 chars\" expression: \"document.summary.size()
-- \< 100\" Example (Equality): title: \"Requestor is owner\" description:
-- \"Determines if requestor is the document owner\" expression:
-- \"document.owner == request.auth.claims.email\" Example (Logic): title:
-- \"Public documents\" description: \"Determine whether the document
-- should be publicly visible\" expression: \"document.type != \'private\'
-- && document.type != \'internal\'\" Example (Data Manipulation): title:
-- \"Notification string\" description: \"Create a notification string with
-- a timestamp.\" expression: \"\'New message received at \' +
-- string(document.create_time)\" The exact variables and functions that
-- may be referenced within an expression are determined by the service
-- that evaluates it. See the service documentation for additional
-- information.
--
-- /See:/ 'expr' smart constructor.
data Expr =
Expr'
{ _eLocation :: !(Maybe Text)
, _eExpression :: !(Maybe Text)
, _eTitle :: !(Maybe Text)
, _eDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Expr' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eLocation'
--
-- * 'eExpression'
--
-- * 'eTitle'
--
-- * 'eDescription'
expr
:: Expr
expr =
Expr'
{ _eLocation = Nothing
, _eExpression = Nothing
, _eTitle = Nothing
, _eDescription = Nothing
}
-- | Optional. String indicating the location of the expression for error
-- reporting, e.g. a file name and a position in the file.
eLocation :: Lens' Expr (Maybe Text)
eLocation
= lens _eLocation (\ s a -> s{_eLocation = a})
-- | Textual representation of an expression in Common Expression Language
-- syntax.
eExpression :: Lens' Expr (Maybe Text)
eExpression
= lens _eExpression (\ s a -> s{_eExpression = a})
-- | Optional. Title for the expression, i.e. a short string describing its
-- purpose. This can be used e.g. in UIs which allow to enter the
-- expression.
eTitle :: Lens' Expr (Maybe Text)
eTitle = lens _eTitle (\ s a -> s{_eTitle = a})
-- | Optional. Description of the expression. This is a longer text which
-- describes the expression, e.g. when hovered over it in a UI.
eDescription :: Lens' Expr (Maybe Text)
eDescription
= lens _eDescription (\ s a -> s{_eDescription = a})
instance FromJSON Expr where
parseJSON
= withObject "Expr"
(\ o ->
Expr' <$>
(o .:? "location") <*> (o .:? "expression") <*>
(o .:? "title")
<*> (o .:? "description"))
instance ToJSON Expr where
toJSON Expr'{..}
= object
(catMaybes
[("location" .=) <$> _eLocation,
("expression" .=) <$> _eExpression,
("title" .=) <$> _eTitle,
("description" .=) <$> _eDescription])
-- | Request message for \`GetIamPolicy\` method.
--
-- /See:/ 'getIAMPolicyRequest' smart constructor.
newtype GetIAMPolicyRequest =
GetIAMPolicyRequest'
{ _giprOptions :: Maybe GetPolicyOptions
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GetIAMPolicyRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'giprOptions'
getIAMPolicyRequest
:: GetIAMPolicyRequest
getIAMPolicyRequest = GetIAMPolicyRequest' {_giprOptions = Nothing}
-- | OPTIONAL: A \`GetPolicyOptions\` object for specifying options to
-- \`GetIamPolicy\`.
giprOptions :: Lens' GetIAMPolicyRequest (Maybe GetPolicyOptions)
giprOptions
= lens _giprOptions (\ s a -> s{_giprOptions = a})
instance FromJSON GetIAMPolicyRequest where
parseJSON
= withObject "GetIAMPolicyRequest"
(\ o -> GetIAMPolicyRequest' <$> (o .:? "options"))
instance ToJSON GetIAMPolicyRequest where
toJSON GetIAMPolicyRequest'{..}
= object
(catMaybes [("options" .=) <$> _giprOptions])
-- | Response for \`ListDeviceRegistries\`.
--
-- /See:/ 'listDeviceRegistriesResponse' smart constructor.
data ListDeviceRegistriesResponse =
ListDeviceRegistriesResponse'
{ _ldrrNextPageToken :: !(Maybe Text)
, _ldrrDeviceRegistries :: !(Maybe [DeviceRegistry])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListDeviceRegistriesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldrrNextPageToken'
--
-- * 'ldrrDeviceRegistries'
listDeviceRegistriesResponse
:: ListDeviceRegistriesResponse
listDeviceRegistriesResponse =
ListDeviceRegistriesResponse'
{_ldrrNextPageToken = Nothing, _ldrrDeviceRegistries = Nothing}
-- | If not empty, indicates that there may be more registries that match the
-- request; this value should be passed in a new
-- \`ListDeviceRegistriesRequest\`.
ldrrNextPageToken :: Lens' ListDeviceRegistriesResponse (Maybe Text)
ldrrNextPageToken
= lens _ldrrNextPageToken
(\ s a -> s{_ldrrNextPageToken = a})
-- | The registries that matched the query.
ldrrDeviceRegistries :: Lens' ListDeviceRegistriesResponse [DeviceRegistry]
ldrrDeviceRegistries
= lens _ldrrDeviceRegistries
(\ s a -> s{_ldrrDeviceRegistries = a})
. _Default
. _Coerce
instance FromJSON ListDeviceRegistriesResponse where
parseJSON
= withObject "ListDeviceRegistriesResponse"
(\ o ->
ListDeviceRegistriesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "deviceRegistries" .!= mempty))
instance ToJSON ListDeviceRegistriesResponse where
toJSON ListDeviceRegistriesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _ldrrNextPageToken,
("deviceRegistries" .=) <$> _ldrrDeviceRegistries])
-- | The device configuration. Eventually delivered to devices.
--
-- /See:/ 'deviceConfig' smart constructor.
data DeviceConfig =
DeviceConfig'
{ _dcDeviceAckTime :: !(Maybe DateTime')
, _dcCloudUpdateTime :: !(Maybe DateTime')
, _dcBinaryData :: !(Maybe Bytes)
, _dcVersion :: !(Maybe (Textual Int64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeviceConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcDeviceAckTime'
--
-- * 'dcCloudUpdateTime'
--
-- * 'dcBinaryData'
--
-- * 'dcVersion'
deviceConfig
:: DeviceConfig
deviceConfig =
DeviceConfig'
{ _dcDeviceAckTime = Nothing
, _dcCloudUpdateTime = Nothing
, _dcBinaryData = Nothing
, _dcVersion = Nothing
}
-- | [Output only] The time at which Cloud IoT Core received the
-- acknowledgment from the device, indicating that the device has received
-- this configuration version. If this field is not present, the device has
-- not yet acknowledged that it received this version. Note that when the
-- config was sent to the device, many config versions may have been
-- available in Cloud IoT Core while the device was disconnected, and on
-- connection, only the latest version is sent to the device. Some versions
-- may never be sent to the device, and therefore are never acknowledged.
-- This timestamp is set by Cloud IoT Core.
dcDeviceAckTime :: Lens' DeviceConfig (Maybe UTCTime)
dcDeviceAckTime
= lens _dcDeviceAckTime
(\ s a -> s{_dcDeviceAckTime = a})
. mapping _DateTime
-- | [Output only] The time at which this configuration version was updated
-- in Cloud IoT Core. This timestamp is set by the server.
dcCloudUpdateTime :: Lens' DeviceConfig (Maybe UTCTime)
dcCloudUpdateTime
= lens _dcCloudUpdateTime
(\ s a -> s{_dcCloudUpdateTime = a})
. mapping _DateTime
-- | The device configuration data.
dcBinaryData :: Lens' DeviceConfig (Maybe ByteString)
dcBinaryData
= lens _dcBinaryData (\ s a -> s{_dcBinaryData = a})
. mapping _Bytes
-- | [Output only] The version of this update. The version number is assigned
-- by the server, and is always greater than 0 after device creation. The
-- version must be 0 on the \`CreateDevice\` request if a \`config\` is
-- specified; the response of \`CreateDevice\` will always have a value of
-- 1.
dcVersion :: Lens' DeviceConfig (Maybe Int64)
dcVersion
= lens _dcVersion (\ s a -> s{_dcVersion = a}) .
mapping _Coerce
instance FromJSON DeviceConfig where
parseJSON
= withObject "DeviceConfig"
(\ o ->
DeviceConfig' <$>
(o .:? "deviceAckTime") <*> (o .:? "cloudUpdateTime")
<*> (o .:? "binaryData")
<*> (o .:? "version"))
instance ToJSON DeviceConfig where
toJSON DeviceConfig'{..}
= object
(catMaybes
[("deviceAckTime" .=) <$> _dcDeviceAckTime,
("cloudUpdateTime" .=) <$> _dcCloudUpdateTime,
("binaryData" .=) <$> _dcBinaryData,
("version" .=) <$> _dcVersion])
-- | Response for \`ListDeviceConfigVersions\`.
--
-- /See:/ 'listDeviceConfigVersionsResponse' smart constructor.
newtype ListDeviceConfigVersionsResponse =
ListDeviceConfigVersionsResponse'
{ _ldcvrDeviceConfigs :: Maybe [DeviceConfig]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListDeviceConfigVersionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldcvrDeviceConfigs'
listDeviceConfigVersionsResponse
:: ListDeviceConfigVersionsResponse
listDeviceConfigVersionsResponse =
ListDeviceConfigVersionsResponse' {_ldcvrDeviceConfigs = Nothing}
-- | The device configuration for the last few versions. Versions are listed
-- in decreasing order, starting from the most recent one.
ldcvrDeviceConfigs :: Lens' ListDeviceConfigVersionsResponse [DeviceConfig]
ldcvrDeviceConfigs
= lens _ldcvrDeviceConfigs
(\ s a -> s{_ldcvrDeviceConfigs = a})
. _Default
. _Coerce
instance FromJSON ListDeviceConfigVersionsResponse
where
parseJSON
= withObject "ListDeviceConfigVersionsResponse"
(\ o ->
ListDeviceConfigVersionsResponse' <$>
(o .:? "deviceConfigs" .!= mempty))
instance ToJSON ListDeviceConfigVersionsResponse
where
toJSON ListDeviceConfigVersionsResponse'{..}
= object
(catMaybes
[("deviceConfigs" .=) <$> _ldcvrDeviceConfigs])
-- | Gateway-related configuration and state.
--
-- /See:/ 'gatewayConfig' smart constructor.
data GatewayConfig =
GatewayConfig'
{ _gcLastAccessedGatewayId :: !(Maybe Text)
, _gcGatewayAuthMethod :: !(Maybe GatewayConfigGatewayAuthMethod)
, _gcLastAccessedGatewayTime :: !(Maybe DateTime')
, _gcGatewayType :: !(Maybe GatewayConfigGatewayType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GatewayConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gcLastAccessedGatewayId'
--
-- * 'gcGatewayAuthMethod'
--
-- * 'gcLastAccessedGatewayTime'
--
-- * 'gcGatewayType'
gatewayConfig
:: GatewayConfig
gatewayConfig =
GatewayConfig'
{ _gcLastAccessedGatewayId = Nothing
, _gcGatewayAuthMethod = Nothing
, _gcLastAccessedGatewayTime = Nothing
, _gcGatewayType = Nothing
}
-- | [Output only] The ID of the gateway the device accessed most recently.
gcLastAccessedGatewayId :: Lens' GatewayConfig (Maybe Text)
gcLastAccessedGatewayId
= lens _gcLastAccessedGatewayId
(\ s a -> s{_gcLastAccessedGatewayId = a})
-- | Indicates how to authorize and\/or authenticate devices to access the
-- gateway.
gcGatewayAuthMethod :: Lens' GatewayConfig (Maybe GatewayConfigGatewayAuthMethod)
gcGatewayAuthMethod
= lens _gcGatewayAuthMethod
(\ s a -> s{_gcGatewayAuthMethod = a})
-- | [Output only] The most recent time at which the device accessed the
-- gateway specified in \`last_accessed_gateway\`.
gcLastAccessedGatewayTime :: Lens' GatewayConfig (Maybe UTCTime)
gcLastAccessedGatewayTime
= lens _gcLastAccessedGatewayTime
(\ s a -> s{_gcLastAccessedGatewayTime = a})
. mapping _DateTime
-- | Indicates whether the device is a gateway.
gcGatewayType :: Lens' GatewayConfig (Maybe GatewayConfigGatewayType)
gcGatewayType
= lens _gcGatewayType
(\ s a -> s{_gcGatewayType = a})
instance FromJSON GatewayConfig where
parseJSON
= withObject "GatewayConfig"
(\ o ->
GatewayConfig' <$>
(o .:? "lastAccessedGatewayId") <*>
(o .:? "gatewayAuthMethod")
<*> (o .:? "lastAccessedGatewayTime")
<*> (o .:? "gatewayType"))
instance ToJSON GatewayConfig where
toJSON GatewayConfig'{..}
= object
(catMaybes
[("lastAccessedGatewayId" .=) <$>
_gcLastAccessedGatewayId,
("gatewayAuthMethod" .=) <$> _gcGatewayAuthMethod,
("lastAccessedGatewayTime" .=) <$>
_gcLastAccessedGatewayTime,
("gatewayType" .=) <$> _gcGatewayType])
-- | Response for \`ListDeviceStates\`.
--
-- /See:/ 'listDeviceStatesResponse' smart constructor.
newtype ListDeviceStatesResponse =
ListDeviceStatesResponse'
{ _ldsrDeviceStates :: Maybe [DeviceState]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListDeviceStatesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldsrDeviceStates'
listDeviceStatesResponse
:: ListDeviceStatesResponse
listDeviceStatesResponse =
ListDeviceStatesResponse' {_ldsrDeviceStates = Nothing}
-- | The last few device states. States are listed in descending order of
-- server update time, starting from the most recent one.
ldsrDeviceStates :: Lens' ListDeviceStatesResponse [DeviceState]
ldsrDeviceStates
= lens _ldsrDeviceStates
(\ s a -> s{_ldsrDeviceStates = a})
. _Default
. _Coerce
instance FromJSON ListDeviceStatesResponse where
parseJSON
= withObject "ListDeviceStatesResponse"
(\ o ->
ListDeviceStatesResponse' <$>
(o .:? "deviceStates" .!= mempty))
instance ToJSON ListDeviceStatesResponse where
toJSON ListDeviceStatesResponse'{..}
= object
(catMaybes
[("deviceStates" .=) <$> _ldsrDeviceStates])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'empty' smart constructor.
data Empty =
Empty'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
--
empty
:: Empty
empty = Empty'
instance FromJSON Empty where
parseJSON = withObject "Empty" (\ o -> pure Empty')
instance ToJSON Empty where
toJSON = const emptyObject
-- | The configuration for notification of new states received from the
-- device.
--
-- /See:/ 'stateNotificationConfig' smart constructor.
newtype StateNotificationConfig =
StateNotificationConfig'
{ _sncPubsubTopicName :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StateNotificationConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sncPubsubTopicName'
stateNotificationConfig
:: StateNotificationConfig
stateNotificationConfig =
StateNotificationConfig' {_sncPubsubTopicName = Nothing}
-- | A Cloud Pub\/Sub topic name. For example,
-- \`projects\/myProject\/topics\/deviceEvents\`.
sncPubsubTopicName :: Lens' StateNotificationConfig (Maybe Text)
sncPubsubTopicName
= lens _sncPubsubTopicName
(\ s a -> s{_sncPubsubTopicName = a})
instance FromJSON StateNotificationConfig where
parseJSON
= withObject "StateNotificationConfig"
(\ o ->
StateNotificationConfig' <$>
(o .:? "pubsubTopicName"))
instance ToJSON StateNotificationConfig where
toJSON StateNotificationConfig'{..}
= object
(catMaybes
[("pubsubTopicName" .=) <$> _sncPubsubTopicName])
-- | The device resource.
--
-- /See:/ 'device' smart constructor.
data Device =
Device'
{ _dState :: !(Maybe DeviceState)
, _dLastHeartbeatTime :: !(Maybe DateTime')
, _dGatewayConfig :: !(Maybe GatewayConfig)
, _dLogLevel :: !(Maybe DeviceLogLevel)
, _dConfig :: !(Maybe DeviceConfig)
, _dCredentials :: !(Maybe [DeviceCredential])
, _dNumId :: !(Maybe (Textual Word64))
, _dLastErrorStatus :: !(Maybe Status)
, _dLastConfigSendTime :: !(Maybe DateTime')
, _dLastConfigAckTime :: !(Maybe DateTime')
, _dName :: !(Maybe Text)
, _dLastErrorTime :: !(Maybe DateTime')
, _dMetadata :: !(Maybe DeviceMetadata)
, _dId :: !(Maybe Text)
, _dLastStateTime :: !(Maybe DateTime')
, _dBlocked :: !(Maybe Bool)
, _dLastEventTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Device' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dState'
--
-- * 'dLastHeartbeatTime'
--
-- * 'dGatewayConfig'
--
-- * 'dLogLevel'
--
-- * 'dConfig'
--
-- * 'dCredentials'
--
-- * 'dNumId'
--
-- * 'dLastErrorStatus'
--
-- * 'dLastConfigSendTime'
--
-- * 'dLastConfigAckTime'
--
-- * 'dName'
--
-- * 'dLastErrorTime'
--
-- * 'dMetadata'
--
-- * 'dId'
--
-- * 'dLastStateTime'
--
-- * 'dBlocked'
--
-- * 'dLastEventTime'
device
:: Device
device =
Device'
{ _dState = Nothing
, _dLastHeartbeatTime = Nothing
, _dGatewayConfig = Nothing
, _dLogLevel = Nothing
, _dConfig = Nothing
, _dCredentials = Nothing
, _dNumId = Nothing
, _dLastErrorStatus = Nothing
, _dLastConfigSendTime = Nothing
, _dLastConfigAckTime = Nothing
, _dName = Nothing
, _dLastErrorTime = Nothing
, _dMetadata = Nothing
, _dId = Nothing
, _dLastStateTime = Nothing
, _dBlocked = Nothing
, _dLastEventTime = Nothing
}
-- | [Output only] The state most recently received from the device. If no
-- state has been reported, this field is not present.
dState :: Lens' Device (Maybe DeviceState)
dState = lens _dState (\ s a -> s{_dState = a})
-- | [Output only] The last time an MQTT \`PINGREQ\` was received. This field
-- applies only to devices connecting through MQTT. MQTT clients usually
-- only send \`PINGREQ\` messages if the connection is idle, and no other
-- messages have been sent. Timestamps are periodically collected and
-- written to storage; they may be stale by a few minutes.
dLastHeartbeatTime :: Lens' Device (Maybe UTCTime)
dLastHeartbeatTime
= lens _dLastHeartbeatTime
(\ s a -> s{_dLastHeartbeatTime = a})
. mapping _DateTime
-- | Gateway-related configuration and state.
dGatewayConfig :: Lens' Device (Maybe GatewayConfig)
dGatewayConfig
= lens _dGatewayConfig
(\ s a -> s{_dGatewayConfig = a})
-- | **Beta Feature** The logging verbosity for device activity. If
-- unspecified, DeviceRegistry.log_level will be used.
dLogLevel :: Lens' Device (Maybe DeviceLogLevel)
dLogLevel
= lens _dLogLevel (\ s a -> s{_dLogLevel = a})
-- | The most recent device configuration, which is eventually sent from
-- Cloud IoT Core to the device. If not present on creation, the
-- configuration will be initialized with an empty payload and version
-- value of \`1\`. To update this field after creation, use the
-- \`DeviceManager.ModifyCloudToDeviceConfig\` method.
dConfig :: Lens' Device (Maybe DeviceConfig)
dConfig = lens _dConfig (\ s a -> s{_dConfig = a})
-- | The credentials used to authenticate this device. To allow credential
-- rotation without interruption, multiple device credentials can be bound
-- to this device. No more than 3 credentials can be bound to a single
-- device at a time. When new credentials are added to a device, they are
-- verified against the registry credentials. For details, see the
-- description of the \`DeviceRegistry.credentials\` field.
dCredentials :: Lens' Device [DeviceCredential]
dCredentials
= lens _dCredentials (\ s a -> s{_dCredentials = a})
. _Default
. _Coerce
-- | [Output only] A server-defined unique numeric ID for the device. This is
-- a more compact way to identify devices, and it is globally unique.
dNumId :: Lens' Device (Maybe Word64)
dNumId
= lens _dNumId (\ s a -> s{_dNumId = a}) .
mapping _Coerce
-- | [Output only] The error message of the most recent error, such as a
-- failure to publish to Cloud Pub\/Sub. \'last_error_time\' is the
-- timestamp of this field. If no errors have occurred, this field has an
-- empty message and the status code 0 == OK. Otherwise, this field is
-- expected to have a status code other than OK.
dLastErrorStatus :: Lens' Device (Maybe Status)
dLastErrorStatus
= lens _dLastErrorStatus
(\ s a -> s{_dLastErrorStatus = a})
-- | [Output only] The last time a cloud-to-device config version was sent to
-- the device.
dLastConfigSendTime :: Lens' Device (Maybe UTCTime)
dLastConfigSendTime
= lens _dLastConfigSendTime
(\ s a -> s{_dLastConfigSendTime = a})
. mapping _DateTime
-- | [Output only] The last time a cloud-to-device config version
-- acknowledgment was received from the device. This field is only for
-- configurations sent through MQTT.
dLastConfigAckTime :: Lens' Device (Maybe UTCTime)
dLastConfigAckTime
= lens _dLastConfigAckTime
(\ s a -> s{_dLastConfigAckTime = a})
. mapping _DateTime
-- | The resource path name. For example,
-- \`projects\/p1\/locations\/us-central1\/registries\/registry0\/devices\/dev0\`
-- or
-- \`projects\/p1\/locations\/us-central1\/registries\/registry0\/devices\/{num_id}\`.
-- When \`name\` is populated as a response from the service, it always
-- ends in the device numeric ID.
dName :: Lens' Device (Maybe Text)
dName = lens _dName (\ s a -> s{_dName = a})
-- | [Output only] The time the most recent error occurred, such as a failure
-- to publish to Cloud Pub\/Sub. This field is the timestamp of
-- \'last_error_status\'.
dLastErrorTime :: Lens' Device (Maybe UTCTime)
dLastErrorTime
= lens _dLastErrorTime
(\ s a -> s{_dLastErrorTime = a})
. mapping _DateTime
-- | The metadata key-value pairs assigned to the device. This metadata is
-- not interpreted or indexed by Cloud IoT Core. It can be used to add
-- contextual information for the device. Keys must conform to the regular
-- expression a-zA-Z+ and be less than 128 bytes in length. Values are
-- free-form strings. Each value must be less than or equal to 32 KB in
-- size. The total size of all keys and values must be less than 256 KB,
-- and the maximum number of key-value pairs is 500.
dMetadata :: Lens' Device (Maybe DeviceMetadata)
dMetadata
= lens _dMetadata (\ s a -> s{_dMetadata = a})
-- | The user-defined device identifier. The device ID must be unique within
-- a device registry.
dId :: Lens' Device (Maybe Text)
dId = lens _dId (\ s a -> s{_dId = a})
-- | [Output only] The last time a state event was received. Timestamps are
-- periodically collected and written to storage; they may be stale by a
-- few minutes.
dLastStateTime :: Lens' Device (Maybe UTCTime)
dLastStateTime
= lens _dLastStateTime
(\ s a -> s{_dLastStateTime = a})
. mapping _DateTime
-- | If a device is blocked, connections or requests from this device will
-- fail. Can be used to temporarily prevent the device from connecting if,
-- for example, the sensor is generating bad data and needs maintenance.
dBlocked :: Lens' Device (Maybe Bool)
dBlocked = lens _dBlocked (\ s a -> s{_dBlocked = a})
-- | [Output only] The last time a telemetry event was received. Timestamps
-- are periodically collected and written to storage; they may be stale by
-- a few minutes.
dLastEventTime :: Lens' Device (Maybe UTCTime)
dLastEventTime
= lens _dLastEventTime
(\ s a -> s{_dLastEventTime = a})
. mapping _DateTime
instance FromJSON Device where
parseJSON
= withObject "Device"
(\ o ->
Device' <$>
(o .:? "state") <*> (o .:? "lastHeartbeatTime") <*>
(o .:? "gatewayConfig")
<*> (o .:? "logLevel")
<*> (o .:? "config")
<*> (o .:? "credentials" .!= mempty)
<*> (o .:? "numId")
<*> (o .:? "lastErrorStatus")
<*> (o .:? "lastConfigSendTime")
<*> (o .:? "lastConfigAckTime")
<*> (o .:? "name")
<*> (o .:? "lastErrorTime")
<*> (o .:? "metadata")
<*> (o .:? "id")
<*> (o .:? "lastStateTime")
<*> (o .:? "blocked")
<*> (o .:? "lastEventTime"))
instance ToJSON Device where
toJSON Device'{..}
= object
(catMaybes
[("state" .=) <$> _dState,
("lastHeartbeatTime" .=) <$> _dLastHeartbeatTime,
("gatewayConfig" .=) <$> _dGatewayConfig,
("logLevel" .=) <$> _dLogLevel,
("config" .=) <$> _dConfig,
("credentials" .=) <$> _dCredentials,
("numId" .=) <$> _dNumId,
("lastErrorStatus" .=) <$> _dLastErrorStatus,
("lastConfigSendTime" .=) <$> _dLastConfigSendTime,
("lastConfigAckTime" .=) <$> _dLastConfigAckTime,
("name" .=) <$> _dName,
("lastErrorTime" .=) <$> _dLastErrorTime,
("metadata" .=) <$> _dMetadata, ("id" .=) <$> _dId,
("lastStateTime" .=) <$> _dLastStateTime,
("blocked" .=) <$> _dBlocked,
("lastEventTime" .=) <$> _dLastEventTime])
-- | A server-stored device credential used for authentication.
--
-- /See:/ 'deviceCredential' smart constructor.
data DeviceCredential =
DeviceCredential'
{ _dcPublicKey :: !(Maybe PublicKeyCredential)
, _dcExpirationTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeviceCredential' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcPublicKey'
--
-- * 'dcExpirationTime'
deviceCredential
:: DeviceCredential
deviceCredential =
DeviceCredential' {_dcPublicKey = Nothing, _dcExpirationTime = Nothing}
-- | A public key used to verify the signature of JSON Web Tokens (JWTs).
-- When adding a new device credential, either via device creation or via
-- modifications, this public key credential may be required to be signed
-- by one of the registry level certificates. More specifically, if the
-- registry contains at least one certificate, any new device credential
-- must be signed by one of the registry certificates. As a result, when
-- the registry contains certificates, only X.509 certificates are accepted
-- as device credentials. However, if the registry does not contain a
-- certificate, self-signed certificates and public keys will be accepted.
-- New device credentials must be different from every registry-level
-- certificate.
dcPublicKey :: Lens' DeviceCredential (Maybe PublicKeyCredential)
dcPublicKey
= lens _dcPublicKey (\ s a -> s{_dcPublicKey = a})
-- | [Optional] The time at which this credential becomes invalid. This
-- credential will be ignored for new client authentication requests after
-- this timestamp; however, it will not be automatically deleted.
dcExpirationTime :: Lens' DeviceCredential (Maybe UTCTime)
dcExpirationTime
= lens _dcExpirationTime
(\ s a -> s{_dcExpirationTime = a})
. mapping _DateTime
instance FromJSON DeviceCredential where
parseJSON
= withObject "DeviceCredential"
(\ o ->
DeviceCredential' <$>
(o .:? "publicKey") <*> (o .:? "expirationTime"))
instance ToJSON DeviceCredential where
toJSON DeviceCredential'{..}
= object
(catMaybes
[("publicKey" .=) <$> _dcPublicKey,
("expirationTime" .=) <$> _dcExpirationTime])
-- | The configuration for forwarding telemetry events.
--
-- /See:/ 'eventNotificationConfig' smart constructor.
data EventNotificationConfig =
EventNotificationConfig'
{ _encPubsubTopicName :: !(Maybe Text)
, _encSubfolderMatches :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EventNotificationConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'encPubsubTopicName'
--
-- * 'encSubfolderMatches'
eventNotificationConfig
:: EventNotificationConfig
eventNotificationConfig =
EventNotificationConfig'
{_encPubsubTopicName = Nothing, _encSubfolderMatches = Nothing}
-- | A Cloud Pub\/Sub topic name. For example,
-- \`projects\/myProject\/topics\/deviceEvents\`.
encPubsubTopicName :: Lens' EventNotificationConfig (Maybe Text)
encPubsubTopicName
= lens _encPubsubTopicName
(\ s a -> s{_encPubsubTopicName = a})
-- | If the subfolder name matches this string exactly, this configuration
-- will be used. The string must not include the leading \'\/\' character.
-- If empty, all strings are matched. This field is used only for telemetry
-- events; subfolders are not supported for state changes.
encSubfolderMatches :: Lens' EventNotificationConfig (Maybe Text)
encSubfolderMatches
= lens _encSubfolderMatches
(\ s a -> s{_encSubfolderMatches = a})
instance FromJSON EventNotificationConfig where
parseJSON
= withObject "EventNotificationConfig"
(\ o ->
EventNotificationConfig' <$>
(o .:? "pubsubTopicName") <*>
(o .:? "subfolderMatches"))
instance ToJSON EventNotificationConfig where
toJSON EventNotificationConfig'{..}
= object
(catMaybes
[("pubsubTopicName" .=) <$> _encPubsubTopicName,
("subfolderMatches" .=) <$> _encSubfolderMatches])
-- | Details of an X.509 certificate. For informational purposes only.
--
-- /See:/ 'x509CertificateDetails' smart constructor.
data X509CertificateDetails =
X509CertificateDetails'
{ _xcdSubject :: !(Maybe Text)
, _xcdExpiryTime :: !(Maybe DateTime')
, _xcdStartTime :: !(Maybe DateTime')
, _xcdSignatureAlgorithm :: !(Maybe Text)
, _xcdIssuer :: !(Maybe Text)
, _xcdPublicKeyType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'X509CertificateDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'xcdSubject'
--
-- * 'xcdExpiryTime'
--
-- * 'xcdStartTime'
--
-- * 'xcdSignatureAlgorithm'
--
-- * 'xcdIssuer'
--
-- * 'xcdPublicKeyType'
x509CertificateDetails
:: X509CertificateDetails
x509CertificateDetails =
X509CertificateDetails'
{ _xcdSubject = Nothing
, _xcdExpiryTime = Nothing
, _xcdStartTime = Nothing
, _xcdSignatureAlgorithm = Nothing
, _xcdIssuer = Nothing
, _xcdPublicKeyType = Nothing
}
-- | The entity the certificate and public key belong to.
xcdSubject :: Lens' X509CertificateDetails (Maybe Text)
xcdSubject
= lens _xcdSubject (\ s a -> s{_xcdSubject = a})
-- | The time the certificate becomes invalid.
xcdExpiryTime :: Lens' X509CertificateDetails (Maybe UTCTime)
xcdExpiryTime
= lens _xcdExpiryTime
(\ s a -> s{_xcdExpiryTime = a})
. mapping _DateTime
-- | The time the certificate becomes valid.
xcdStartTime :: Lens' X509CertificateDetails (Maybe UTCTime)
xcdStartTime
= lens _xcdStartTime (\ s a -> s{_xcdStartTime = a})
. mapping _DateTime
-- | The algorithm used to sign the certificate.
xcdSignatureAlgorithm :: Lens' X509CertificateDetails (Maybe Text)
xcdSignatureAlgorithm
= lens _xcdSignatureAlgorithm
(\ s a -> s{_xcdSignatureAlgorithm = a})
-- | The entity that signed the certificate.
xcdIssuer :: Lens' X509CertificateDetails (Maybe Text)
xcdIssuer
= lens _xcdIssuer (\ s a -> s{_xcdIssuer = a})
-- | The type of public key in the certificate.
xcdPublicKeyType :: Lens' X509CertificateDetails (Maybe Text)
xcdPublicKeyType
= lens _xcdPublicKeyType
(\ s a -> s{_xcdPublicKeyType = a})
instance FromJSON X509CertificateDetails where
parseJSON
= withObject "X509CertificateDetails"
(\ o ->
X509CertificateDetails' <$>
(o .:? "subject") <*> (o .:? "expiryTime") <*>
(o .:? "startTime")
<*> (o .:? "signatureAlgorithm")
<*> (o .:? "issuer")
<*> (o .:? "publicKeyType"))
instance ToJSON X509CertificateDetails where
toJSON X509CertificateDetails'{..}
= object
(catMaybes
[("subject" .=) <$> _xcdSubject,
("expiryTime" .=) <$> _xcdExpiryTime,
("startTime" .=) <$> _xcdStartTime,
("signatureAlgorithm" .=) <$> _xcdSignatureAlgorithm,
("issuer" .=) <$> _xcdIssuer,
("publicKeyType" .=) <$> _xcdPublicKeyType])
-- | A public key certificate format and data.
--
-- /See:/ 'publicKeyCertificate' smart constructor.
data PublicKeyCertificate =
PublicKeyCertificate'
{ _pkcFormat :: !(Maybe PublicKeyCertificateFormat)
, _pkcCertificate :: !(Maybe Text)
, _pkcX509Details :: !(Maybe X509CertificateDetails)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PublicKeyCertificate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pkcFormat'
--
-- * 'pkcCertificate'
--
-- * 'pkcX509Details'
publicKeyCertificate
:: PublicKeyCertificate
publicKeyCertificate =
PublicKeyCertificate'
{_pkcFormat = Nothing, _pkcCertificate = Nothing, _pkcX509Details = Nothing}
-- | The certificate format.
pkcFormat :: Lens' PublicKeyCertificate (Maybe PublicKeyCertificateFormat)
pkcFormat
= lens _pkcFormat (\ s a -> s{_pkcFormat = a})
-- | The certificate data.
pkcCertificate :: Lens' PublicKeyCertificate (Maybe Text)
pkcCertificate
= lens _pkcCertificate
(\ s a -> s{_pkcCertificate = a})
-- | [Output only] The certificate details. Used only for X.509 certificates.
pkcX509Details :: Lens' PublicKeyCertificate (Maybe X509CertificateDetails)
pkcX509Details
= lens _pkcX509Details
(\ s a -> s{_pkcX509Details = a})
instance FromJSON PublicKeyCertificate where
parseJSON
= withObject "PublicKeyCertificate"
(\ o ->
PublicKeyCertificate' <$>
(o .:? "format") <*> (o .:? "certificate") <*>
(o .:? "x509Details"))
instance ToJSON PublicKeyCertificate where
toJSON PublicKeyCertificate'{..}
= object
(catMaybes
[("format" .=) <$> _pkcFormat,
("certificate" .=) <$> _pkcCertificate,
("x509Details" .=) <$> _pkcX509Details])
--
-- /See:/ 'statusDetailsItem' smart constructor.
newtype StatusDetailsItem =
StatusDetailsItem'
{ _sdiAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdiAddtional'
statusDetailsItem
:: HashMap Text JSONValue -- ^ 'sdiAddtional'
-> StatusDetailsItem
statusDetailsItem pSdiAddtional_ =
StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue)
sdiAddtional
= lens _sdiAddtional (\ s a -> s{_sdiAddtional = a})
. _Coerce
instance FromJSON StatusDetailsItem where
parseJSON
= withObject "StatusDetailsItem"
(\ o -> StatusDetailsItem' <$> (parseJSONObject o))
instance ToJSON StatusDetailsItem where
toJSON = toJSON . _sdiAddtional
-- | Encapsulates settings provided to GetIamPolicy.
--
-- /See:/ 'getPolicyOptions' smart constructor.
newtype GetPolicyOptions =
GetPolicyOptions'
{ _gpoRequestedPolicyVersion :: Maybe (Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GetPolicyOptions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gpoRequestedPolicyVersion'
getPolicyOptions
:: GetPolicyOptions
getPolicyOptions = GetPolicyOptions' {_gpoRequestedPolicyVersion = Nothing}
-- | Optional. The policy format version to be returned. Valid values are 0,
-- 1, and 3. Requests specifying an invalid value will be rejected.
-- Requests for policies with any conditional bindings must specify version
-- 3. Policies without any conditional bindings may specify any valid value
-- or leave the field unset. To learn which resources support conditions in
-- their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
gpoRequestedPolicyVersion :: Lens' GetPolicyOptions (Maybe Int32)
gpoRequestedPolicyVersion
= lens _gpoRequestedPolicyVersion
(\ s a -> s{_gpoRequestedPolicyVersion = a})
. mapping _Coerce
instance FromJSON GetPolicyOptions where
parseJSON
= withObject "GetPolicyOptions"
(\ o ->
GetPolicyOptions' <$>
(o .:? "requestedPolicyVersion"))
instance ToJSON GetPolicyOptions where
toJSON GetPolicyOptions'{..}
= object
(catMaybes
[("requestedPolicyVersion" .=) <$>
_gpoRequestedPolicyVersion])
-- | The configuration of MQTT for a device registry.
--
-- /See:/ 'mqttConfig' smart constructor.
newtype MqttConfig =
MqttConfig'
{ _mcMqttEnabledState :: Maybe MqttConfigMqttEnabledState
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MqttConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mcMqttEnabledState'
mqttConfig
:: MqttConfig
mqttConfig = MqttConfig' {_mcMqttEnabledState = Nothing}
-- | If enabled, allows connections using the MQTT protocol. Otherwise, MQTT
-- connections to this registry will fail.
mcMqttEnabledState :: Lens' MqttConfig (Maybe MqttConfigMqttEnabledState)
mcMqttEnabledState
= lens _mcMqttEnabledState
(\ s a -> s{_mcMqttEnabledState = a})
instance FromJSON MqttConfig where
parseJSON
= withObject "MqttConfig"
(\ o -> MqttConfig' <$> (o .:? "mqttEnabledState"))
instance ToJSON MqttConfig where
toJSON MqttConfig'{..}
= object
(catMaybes
[("mqttEnabledState" .=) <$> _mcMqttEnabledState])
-- | Request message for \`SetIamPolicy\` method.
--
-- /See:/ 'setIAMPolicyRequest' smart constructor.
newtype SetIAMPolicyRequest =
SetIAMPolicyRequest'
{ _siprPolicy :: Maybe Policy
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SetIAMPolicyRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'siprPolicy'
setIAMPolicyRequest
:: SetIAMPolicyRequest
setIAMPolicyRequest = SetIAMPolicyRequest' {_siprPolicy = Nothing}
-- | REQUIRED: The complete policy to be applied to the \`resource\`. The
-- size of the policy is limited to a few 10s of KB. An empty policy is a
-- valid policy but certain Cloud Platform services (such as Projects)
-- might reject them.
siprPolicy :: Lens' SetIAMPolicyRequest (Maybe Policy)
siprPolicy
= lens _siprPolicy (\ s a -> s{_siprPolicy = a})
instance FromJSON SetIAMPolicyRequest where
parseJSON
= withObject "SetIAMPolicyRequest"
(\ o -> SetIAMPolicyRequest' <$> (o .:? "policy"))
instance ToJSON SetIAMPolicyRequest where
toJSON SetIAMPolicyRequest'{..}
= object (catMaybes [("policy" .=) <$> _siprPolicy])
-- | A server-stored registry credential used to validate device credentials.
--
-- /See:/ 'registryCredential' smart constructor.
newtype RegistryCredential =
RegistryCredential'
{ _rcPublicKeyCertificate :: Maybe PublicKeyCertificate
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RegistryCredential' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcPublicKeyCertificate'
registryCredential
:: RegistryCredential
registryCredential = RegistryCredential' {_rcPublicKeyCertificate = Nothing}
-- | A public key certificate used to verify the device credentials.
rcPublicKeyCertificate :: Lens' RegistryCredential (Maybe PublicKeyCertificate)
rcPublicKeyCertificate
= lens _rcPublicKeyCertificate
(\ s a -> s{_rcPublicKeyCertificate = a})
instance FromJSON RegistryCredential where
parseJSON
= withObject "RegistryCredential"
(\ o ->
RegistryCredential' <$>
(o .:? "publicKeyCertificate"))
instance ToJSON RegistryCredential where
toJSON RegistryCredential'{..}
= object
(catMaybes
[("publicKeyCertificate" .=) <$>
_rcPublicKeyCertificate])
-- | Request for \`SendCommandToDevice\`.
--
-- /See:/ 'sendCommandToDeviceRequest' smart constructor.
data SendCommandToDeviceRequest =
SendCommandToDeviceRequest'
{ _sctdrBinaryData :: !(Maybe Bytes)
, _sctdrSubfolder :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SendCommandToDeviceRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sctdrBinaryData'
--
-- * 'sctdrSubfolder'
sendCommandToDeviceRequest
:: SendCommandToDeviceRequest
sendCommandToDeviceRequest =
SendCommandToDeviceRequest'
{_sctdrBinaryData = Nothing, _sctdrSubfolder = Nothing}
-- | Required. The command data to send to the device.
sctdrBinaryData :: Lens' SendCommandToDeviceRequest (Maybe ByteString)
sctdrBinaryData
= lens _sctdrBinaryData
(\ s a -> s{_sctdrBinaryData = a})
. mapping _Bytes
-- | Optional subfolder for the command. If empty, the command will be
-- delivered to the \/devices\/{device-id}\/commands topic, otherwise it
-- will be delivered to the \/devices\/{device-id}\/commands\/{subfolder}
-- topic. Multi-level subfolders are allowed. This field must not have more
-- than 256 characters, and must not contain any MQTT wildcards (\"+\" or
-- \"#\") or null characters.
sctdrSubfolder :: Lens' SendCommandToDeviceRequest (Maybe Text)
sctdrSubfolder
= lens _sctdrSubfolder
(\ s a -> s{_sctdrSubfolder = a})
instance FromJSON SendCommandToDeviceRequest where
parseJSON
= withObject "SendCommandToDeviceRequest"
(\ o ->
SendCommandToDeviceRequest' <$>
(o .:? "binaryData") <*> (o .:? "subfolder"))
instance ToJSON SendCommandToDeviceRequest where
toJSON SendCommandToDeviceRequest'{..}
= object
(catMaybes
[("binaryData" .=) <$> _sctdrBinaryData,
("subfolder" .=) <$> _sctdrSubfolder])
-- | Response for \`BindDeviceToGateway\`.
--
-- /See:/ 'bindDeviceToGatewayResponse' smart constructor.
data BindDeviceToGatewayResponse =
BindDeviceToGatewayResponse'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BindDeviceToGatewayResponse' with the minimum fields required to make a request.
--
bindDeviceToGatewayResponse
:: BindDeviceToGatewayResponse
bindDeviceToGatewayResponse = BindDeviceToGatewayResponse'
instance FromJSON BindDeviceToGatewayResponse where
parseJSON
= withObject "BindDeviceToGatewayResponse"
(\ o -> pure BindDeviceToGatewayResponse')
instance ToJSON BindDeviceToGatewayResponse where
toJSON = const emptyObject
-- | The configuration of the HTTP bridge for a device registry.
--
-- /See:/ 'hTTPConfig' smart constructor.
newtype HTTPConfig =
HTTPConfig'
{ _httpcHTTPEnabledState :: Maybe HTTPConfigHTTPEnabledState
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'HTTPConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'httpcHTTPEnabledState'
hTTPConfig
:: HTTPConfig
hTTPConfig = HTTPConfig' {_httpcHTTPEnabledState = Nothing}
-- | If enabled, allows devices to use DeviceService via the HTTP protocol.
-- Otherwise, any requests to DeviceService will fail for this registry.
httpcHTTPEnabledState :: Lens' HTTPConfig (Maybe HTTPConfigHTTPEnabledState)
httpcHTTPEnabledState
= lens _httpcHTTPEnabledState
(\ s a -> s{_httpcHTTPEnabledState = a})
instance FromJSON HTTPConfig where
parseJSON
= withObject "HTTPConfig"
(\ o -> HTTPConfig' <$> (o .:? "httpEnabledState"))
instance ToJSON HTTPConfig where
toJSON HTTPConfig'{..}
= object
(catMaybes
[("httpEnabledState" .=) <$> _httpcHTTPEnabledState])
-- | Request message for \`TestIamPermissions\` method.
--
-- /See:/ 'testIAMPermissionsRequest' smart constructor.
newtype TestIAMPermissionsRequest =
TestIAMPermissionsRequest'
{ _tiprPermissions :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestIAMPermissionsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiprPermissions'
testIAMPermissionsRequest
:: TestIAMPermissionsRequest
testIAMPermissionsRequest =
TestIAMPermissionsRequest' {_tiprPermissions = Nothing}
-- | The set of permissions to check for the \`resource\`. Permissions with
-- wildcards (such as \'*\' or \'storage.*\') are not allowed. For more
-- information see [IAM
-- Overview](https:\/\/cloud.google.com\/iam\/docs\/overview#permissions).
tiprPermissions :: Lens' TestIAMPermissionsRequest [Text]
tiprPermissions
= lens _tiprPermissions
(\ s a -> s{_tiprPermissions = a})
. _Default
. _Coerce
instance FromJSON TestIAMPermissionsRequest where
parseJSON
= withObject "TestIAMPermissionsRequest"
(\ o ->
TestIAMPermissionsRequest' <$>
(o .:? "permissions" .!= mempty))
instance ToJSON TestIAMPermissionsRequest where
toJSON TestIAMPermissionsRequest'{..}
= object
(catMaybes [("permissions" .=) <$> _tiprPermissions])
-- | Response for \`ListDevices\`.
--
-- /See:/ 'listDevicesResponse' smart constructor.
data ListDevicesResponse =
ListDevicesResponse'
{ _ldrNextPageToken :: !(Maybe Text)
, _ldrDevices :: !(Maybe [Device])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListDevicesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldrNextPageToken'
--
-- * 'ldrDevices'
listDevicesResponse
:: ListDevicesResponse
listDevicesResponse =
ListDevicesResponse' {_ldrNextPageToken = Nothing, _ldrDevices = Nothing}
-- | If not empty, indicates that there may be more devices that match the
-- request; this value should be passed in a new \`ListDevicesRequest\`.
ldrNextPageToken :: Lens' ListDevicesResponse (Maybe Text)
ldrNextPageToken
= lens _ldrNextPageToken
(\ s a -> s{_ldrNextPageToken = a})
-- | The devices that match the request.
ldrDevices :: Lens' ListDevicesResponse [Device]
ldrDevices
= lens _ldrDevices (\ s a -> s{_ldrDevices = a}) .
_Default
. _Coerce
instance FromJSON ListDevicesResponse where
parseJSON
= withObject "ListDevicesResponse"
(\ o ->
ListDevicesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "devices" .!= mempty))
instance ToJSON ListDevicesResponse where
toJSON ListDevicesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _ldrNextPageToken,
("devices" .=) <$> _ldrDevices])
-- | The metadata key-value pairs assigned to the device. This metadata is
-- not interpreted or indexed by Cloud IoT Core. It can be used to add
-- contextual information for the device. Keys must conform to the regular
-- expression a-zA-Z+ and be less than 128 bytes in length. Values are
-- free-form strings. Each value must be less than or equal to 32 KB in
-- size. The total size of all keys and values must be less than 256 KB,
-- and the maximum number of key-value pairs is 500.
--
-- /See:/ 'deviceMetadata' smart constructor.
newtype DeviceMetadata =
DeviceMetadata'
{ _dmAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeviceMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dmAddtional'
deviceMetadata
:: HashMap Text Text -- ^ 'dmAddtional'
-> DeviceMetadata
deviceMetadata pDmAddtional_ =
DeviceMetadata' {_dmAddtional = _Coerce # pDmAddtional_}
dmAddtional :: Lens' DeviceMetadata (HashMap Text Text)
dmAddtional
= lens _dmAddtional (\ s a -> s{_dmAddtional = a}) .
_Coerce
instance FromJSON DeviceMetadata where
parseJSON
= withObject "DeviceMetadata"
(\ o -> DeviceMetadata' <$> (parseJSONObject o))
instance ToJSON DeviceMetadata where
toJSON = toJSON . _dmAddtional
-- | A container for a group of devices.
--
-- /See:/ 'deviceRegistry' smart constructor.
data DeviceRegistry =
DeviceRegistry'
{ _drLogLevel :: !(Maybe DeviceRegistryLogLevel)
, _drCredentials :: !(Maybe [RegistryCredential])
, _drStateNotificationConfig :: !(Maybe StateNotificationConfig)
, _drEventNotificationConfigs :: !(Maybe [EventNotificationConfig])
, _drMqttConfig :: !(Maybe MqttConfig)
, _drName :: !(Maybe Text)
, _drHTTPConfig :: !(Maybe HTTPConfig)
, _drId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeviceRegistry' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'drLogLevel'
--
-- * 'drCredentials'
--
-- * 'drStateNotificationConfig'
--
-- * 'drEventNotificationConfigs'
--
-- * 'drMqttConfig'
--
-- * 'drName'
--
-- * 'drHTTPConfig'
--
-- * 'drId'
deviceRegistry
:: DeviceRegistry
deviceRegistry =
DeviceRegistry'
{ _drLogLevel = Nothing
, _drCredentials = Nothing
, _drStateNotificationConfig = Nothing
, _drEventNotificationConfigs = Nothing
, _drMqttConfig = Nothing
, _drName = Nothing
, _drHTTPConfig = Nothing
, _drId = Nothing
}
-- | **Beta Feature** The default logging verbosity for activity from devices
-- in this registry. The verbosity level can be overridden by
-- Device.log_level.
drLogLevel :: Lens' DeviceRegistry (Maybe DeviceRegistryLogLevel)
drLogLevel
= lens _drLogLevel (\ s a -> s{_drLogLevel = a})
-- | The credentials used to verify the device credentials. No more than 10
-- credentials can be bound to a single registry at a time. The
-- verification process occurs at the time of device creation or update. If
-- this field is empty, no verification is performed. Otherwise, the
-- credentials of a newly created device or added credentials of an updated
-- device should be signed with one of these registry credentials. Note,
-- however, that existing devices will never be affected by modifications
-- to this list of credentials: after a device has been successfully
-- created in a registry, it should be able to connect even if its registry
-- credentials are revoked, deleted, or modified.
drCredentials :: Lens' DeviceRegistry [RegistryCredential]
drCredentials
= lens _drCredentials
(\ s a -> s{_drCredentials = a})
. _Default
. _Coerce
-- | The configuration for notification of new states received from the
-- device. State updates are guaranteed to be stored in the state history,
-- but notifications to Cloud Pub\/Sub are not guaranteed. For example, if
-- permissions are misconfigured or the specified topic doesn\'t exist, no
-- notification will be published but the state will still be stored in
-- Cloud IoT Core.
drStateNotificationConfig :: Lens' DeviceRegistry (Maybe StateNotificationConfig)
drStateNotificationConfig
= lens _drStateNotificationConfig
(\ s a -> s{_drStateNotificationConfig = a})
-- | The configuration for notification of telemetry events received from the
-- device. All telemetry events that were successfully published by the
-- device and acknowledged by Cloud IoT Core are guaranteed to be delivered
-- to Cloud Pub\/Sub. If multiple configurations match a message, only the
-- first matching configuration is used. If you try to publish a device
-- telemetry event using MQTT without specifying a Cloud Pub\/Sub topic for
-- the device\'s registry, the connection closes automatically. If you try
-- to do so using an HTTP connection, an error is returned. Up to 10
-- configurations may be provided.
drEventNotificationConfigs :: Lens' DeviceRegistry [EventNotificationConfig]
drEventNotificationConfigs
= lens _drEventNotificationConfigs
(\ s a -> s{_drEventNotificationConfigs = a})
. _Default
. _Coerce
-- | The MQTT configuration for this device registry.
drMqttConfig :: Lens' DeviceRegistry (Maybe MqttConfig)
drMqttConfig
= lens _drMqttConfig (\ s a -> s{_drMqttConfig = a})
-- | The resource path name. For example,
-- \`projects\/example-project\/locations\/us-central1\/registries\/my-registry\`.
drName :: Lens' DeviceRegistry (Maybe Text)
drName = lens _drName (\ s a -> s{_drName = a})
-- | The DeviceService (HTTP) configuration for this device registry.
drHTTPConfig :: Lens' DeviceRegistry (Maybe HTTPConfig)
drHTTPConfig
= lens _drHTTPConfig (\ s a -> s{_drHTTPConfig = a})
-- | The identifier of this device registry. For example, \`myRegistry\`.
drId :: Lens' DeviceRegistry (Maybe Text)
drId = lens _drId (\ s a -> s{_drId = a})
instance FromJSON DeviceRegistry where
parseJSON
= withObject "DeviceRegistry"
(\ o ->
DeviceRegistry' <$>
(o .:? "logLevel") <*>
(o .:? "credentials" .!= mempty)
<*> (o .:? "stateNotificationConfig")
<*> (o .:? "eventNotificationConfigs" .!= mempty)
<*> (o .:? "mqttConfig")
<*> (o .:? "name")
<*> (o .:? "httpConfig")
<*> (o .:? "id"))
instance ToJSON DeviceRegistry where
toJSON DeviceRegistry'{..}
= object
(catMaybes
[("logLevel" .=) <$> _drLogLevel,
("credentials" .=) <$> _drCredentials,
("stateNotificationConfig" .=) <$>
_drStateNotificationConfig,
("eventNotificationConfigs" .=) <$>
_drEventNotificationConfigs,
("mqttConfig" .=) <$> _drMqttConfig,
("name" .=) <$> _drName,
("httpConfig" .=) <$> _drHTTPConfig,
("id" .=) <$> _drId])
-- | A public key format and data.
--
-- /See:/ 'publicKeyCredential' smart constructor.
data PublicKeyCredential =
PublicKeyCredential'
{ _pFormat :: !(Maybe PublicKeyCredentialFormat)
, _pKey :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PublicKeyCredential' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pFormat'
--
-- * 'pKey'
publicKeyCredential
:: PublicKeyCredential
publicKeyCredential = PublicKeyCredential' {_pFormat = Nothing, _pKey = Nothing}
-- | The format of the key.
pFormat :: Lens' PublicKeyCredential (Maybe PublicKeyCredentialFormat)
pFormat = lens _pFormat (\ s a -> s{_pFormat = a})
-- | The key data.
pKey :: Lens' PublicKeyCredential (Maybe Text)
pKey = lens _pKey (\ s a -> s{_pKey = a})
instance FromJSON PublicKeyCredential where
parseJSON
= withObject "PublicKeyCredential"
(\ o ->
PublicKeyCredential' <$>
(o .:? "format") <*> (o .:? "key"))
instance ToJSON PublicKeyCredential where
toJSON PublicKeyCredential'{..}
= object
(catMaybes
[("format" .=) <$> _pFormat, ("key" .=) <$> _pKey])
-- | Request for \`UnbindDeviceFromGateway\`.
--
-- /See:/ 'unbindDeviceFromGatewayRequest' smart constructor.
data UnbindDeviceFromGatewayRequest =
UnbindDeviceFromGatewayRequest'
{ _udfgrDeviceId :: !(Maybe Text)
, _udfgrGatewayId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnbindDeviceFromGatewayRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'udfgrDeviceId'
--
-- * 'udfgrGatewayId'
unbindDeviceFromGatewayRequest
:: UnbindDeviceFromGatewayRequest
unbindDeviceFromGatewayRequest =
UnbindDeviceFromGatewayRequest'
{_udfgrDeviceId = Nothing, _udfgrGatewayId = Nothing}
-- | Required. The device to disassociate from the specified gateway. The
-- value of \`device_id\` can be either the device numeric ID or the
-- user-defined device identifier.
udfgrDeviceId :: Lens' UnbindDeviceFromGatewayRequest (Maybe Text)
udfgrDeviceId
= lens _udfgrDeviceId
(\ s a -> s{_udfgrDeviceId = a})
-- | Required. The value of \`gateway_id\` can be either the device numeric
-- ID or the user-defined device identifier.
udfgrGatewayId :: Lens' UnbindDeviceFromGatewayRequest (Maybe Text)
udfgrGatewayId
= lens _udfgrGatewayId
(\ s a -> s{_udfgrGatewayId = a})
instance FromJSON UnbindDeviceFromGatewayRequest
where
parseJSON
= withObject "UnbindDeviceFromGatewayRequest"
(\ o ->
UnbindDeviceFromGatewayRequest' <$>
(o .:? "deviceId") <*> (o .:? "gatewayId"))
instance ToJSON UnbindDeviceFromGatewayRequest where
toJSON UnbindDeviceFromGatewayRequest'{..}
= object
(catMaybes
[("deviceId" .=) <$> _udfgrDeviceId,
("gatewayId" .=) <$> _udfgrGatewayId])
-- | Response message for \`TestIamPermissions\` method.
--
-- /See:/ 'testIAMPermissionsResponse' smart constructor.
newtype TestIAMPermissionsResponse =
TestIAMPermissionsResponse'
{ _tiamprPermissions :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestIAMPermissionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiamprPermissions'
testIAMPermissionsResponse
:: TestIAMPermissionsResponse
testIAMPermissionsResponse =
TestIAMPermissionsResponse' {_tiamprPermissions = Nothing}
-- | A subset of \`TestPermissionsRequest.permissions\` that the caller is
-- allowed.
tiamprPermissions :: Lens' TestIAMPermissionsResponse [Text]
tiamprPermissions
= lens _tiamprPermissions
(\ s a -> s{_tiamprPermissions = a})
. _Default
. _Coerce
instance FromJSON TestIAMPermissionsResponse where
parseJSON
= withObject "TestIAMPermissionsResponse"
(\ o ->
TestIAMPermissionsResponse' <$>
(o .:? "permissions" .!= mempty))
instance ToJSON TestIAMPermissionsResponse where
toJSON TestIAMPermissionsResponse'{..}
= object
(catMaybes
[("permissions" .=) <$> _tiamprPermissions])
-- | An Identity and Access Management (IAM) policy, which specifies access
-- controls for Google Cloud resources. A \`Policy\` is a collection of
-- \`bindings\`. A \`binding\` binds one or more \`members\` to a single
-- \`role\`. Members can be user accounts, service accounts, Google groups,
-- and domains (such as G Suite). A \`role\` is a named list of
-- permissions; each \`role\` can be an IAM predefined role or a
-- user-created custom role. For some types of Google Cloud resources, a
-- \`binding\` can also specify a \`condition\`, which is a logical
-- expression that allows access to a resource only if the expression
-- evaluates to \`true\`. A condition can add constraints based on
-- attributes of the request, the resource, or both. To learn which
-- resources support conditions in their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
-- **JSON example:** { \"bindings\": [ { \"role\":
-- \"roles\/resourcemanager.organizationAdmin\", \"members\": [
-- \"user:mike\'example.com\", \"group:admins\'example.com\",
-- \"domain:google.com\",
-- \"serviceAccount:my-project-id\'appspot.gserviceaccount.com\" ] }, {
-- \"role\": \"roles\/resourcemanager.organizationViewer\", \"members\": [
-- \"user:eve\'example.com\" ], \"condition\": { \"title\": \"expirable
-- access\", \"description\": \"Does not grant access after Sep 2020\",
-- \"expression\": \"request.time \<
-- timestamp(\'2020-10-01T00:00:00.000Z\')\", } } ], \"etag\":
-- \"BwWWja0YfJA=\", \"version\": 3 } **YAML example:** bindings: -
-- members: - user:mike\'example.com - group:admins\'example.com -
-- domain:google.com -
-- serviceAccount:my-project-id\'appspot.gserviceaccount.com role:
-- roles\/resourcemanager.organizationAdmin - members: -
-- user:eve\'example.com role: roles\/resourcemanager.organizationViewer
-- condition: title: expirable access description: Does not grant access
-- after Sep 2020 expression: request.time \<
-- timestamp(\'2020-10-01T00:00:00.000Z\') - etag: BwWWja0YfJA= - version:
-- 3 For a description of IAM and its features, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/docs\/).
--
-- /See:/ 'policy' smart constructor.
data Policy =
Policy'
{ _pEtag :: !(Maybe Bytes)
, _pVersion :: !(Maybe (Textual Int32))
, _pBindings :: !(Maybe [Binding])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Policy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pEtag'
--
-- * 'pVersion'
--
-- * 'pBindings'
policy
:: Policy
policy = Policy' {_pEtag = Nothing, _pVersion = Nothing, _pBindings = Nothing}
-- | \`etag\` is used for optimistic concurrency control as a way to help
-- prevent simultaneous updates of a policy from overwriting each other. It
-- is strongly suggested that systems make use of the \`etag\` in the
-- read-modify-write cycle to perform policy updates in order to avoid race
-- conditions: An \`etag\` is returned in the response to \`getIamPolicy\`,
-- and systems are expected to put that etag in the request to
-- \`setIamPolicy\` to ensure that their change will be applied to the same
-- version of the policy. **Important:** If you use IAM Conditions, you
-- must include the \`etag\` field whenever you call \`setIamPolicy\`. If
-- you omit this field, then IAM allows you to overwrite a version \`3\`
-- policy with a version \`1\` policy, and all of the conditions in the
-- version \`3\` policy are lost.
pEtag :: Lens' Policy (Maybe ByteString)
pEtag
= lens _pEtag (\ s a -> s{_pEtag = a}) .
mapping _Bytes
-- | Specifies the format of the policy. Valid values are \`0\`, \`1\`, and
-- \`3\`. Requests that specify an invalid value are rejected. Any
-- operation that affects conditional role bindings must specify version
-- \`3\`. This requirement applies to the following operations: * Getting a
-- policy that includes a conditional role binding * Adding a conditional
-- role binding to a policy * Changing a conditional role binding in a
-- policy * Removing any role binding, with or without a condition, from a
-- policy that includes conditions **Important:** If you use IAM
-- Conditions, you must include the \`etag\` field whenever you call
-- \`setIamPolicy\`. If you omit this field, then IAM allows you to
-- overwrite a version \`3\` policy with a version \`1\` policy, and all of
-- the conditions in the version \`3\` policy are lost. If a policy does
-- not include any conditions, operations on that policy may specify any
-- valid version or leave the field unset. To learn which resources support
-- conditions in their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
pVersion :: Lens' Policy (Maybe Int32)
pVersion
= lens _pVersion (\ s a -> s{_pVersion = a}) .
mapping _Coerce
-- | Associates a list of \`members\` to a \`role\`. Optionally, may specify
-- a \`condition\` that determines how and when the \`bindings\` are
-- applied. Each of the \`bindings\` must contain at least one member.
pBindings :: Lens' Policy [Binding]
pBindings
= lens _pBindings (\ s a -> s{_pBindings = a}) .
_Default
. _Coerce
instance FromJSON Policy where
parseJSON
= withObject "Policy"
(\ o ->
Policy' <$>
(o .:? "etag") <*> (o .:? "version") <*>
(o .:? "bindings" .!= mempty))
instance ToJSON Policy where
toJSON Policy'{..}
= object
(catMaybes
[("etag" .=) <$> _pEtag,
("version" .=) <$> _pVersion,
("bindings" .=) <$> _pBindings])
-- | Response for \`SendCommandToDevice\`.
--
-- /See:/ 'sendCommandToDeviceResponse' smart constructor.
data SendCommandToDeviceResponse =
SendCommandToDeviceResponse'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SendCommandToDeviceResponse' with the minimum fields required to make a request.
--
sendCommandToDeviceResponse
:: SendCommandToDeviceResponse
sendCommandToDeviceResponse = SendCommandToDeviceResponse'
instance FromJSON SendCommandToDeviceResponse where
parseJSON
= withObject "SendCommandToDeviceResponse"
(\ o -> pure SendCommandToDeviceResponse')
instance ToJSON SendCommandToDeviceResponse where
toJSON = const emptyObject
-- | Request for \`BindDeviceToGateway\`.
--
-- /See:/ 'bindDeviceToGatewayRequest' smart constructor.
data BindDeviceToGatewayRequest =
BindDeviceToGatewayRequest'
{ _bdtgrDeviceId :: !(Maybe Text)
, _bdtgrGatewayId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BindDeviceToGatewayRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bdtgrDeviceId'
--
-- * 'bdtgrGatewayId'
bindDeviceToGatewayRequest
:: BindDeviceToGatewayRequest
bindDeviceToGatewayRequest =
BindDeviceToGatewayRequest'
{_bdtgrDeviceId = Nothing, _bdtgrGatewayId = Nothing}
-- | Required. The device to associate with the specified gateway. The value
-- of \`device_id\` can be either the device numeric ID or the user-defined
-- device identifier.
bdtgrDeviceId :: Lens' BindDeviceToGatewayRequest (Maybe Text)
bdtgrDeviceId
= lens _bdtgrDeviceId
(\ s a -> s{_bdtgrDeviceId = a})
-- | Required. The value of \`gateway_id\` can be either the device numeric
-- ID or the user-defined device identifier.
bdtgrGatewayId :: Lens' BindDeviceToGatewayRequest (Maybe Text)
bdtgrGatewayId
= lens _bdtgrGatewayId
(\ s a -> s{_bdtgrGatewayId = a})
instance FromJSON BindDeviceToGatewayRequest where
parseJSON
= withObject "BindDeviceToGatewayRequest"
(\ o ->
BindDeviceToGatewayRequest' <$>
(o .:? "deviceId") <*> (o .:? "gatewayId"))
instance ToJSON BindDeviceToGatewayRequest where
toJSON BindDeviceToGatewayRequest'{..}
= object
(catMaybes
[("deviceId" .=) <$> _bdtgrDeviceId,
("gatewayId" .=) <$> _bdtgrGatewayId])
-- | Request for \`ModifyCloudToDeviceConfig\`.
--
-- /See:/ 'modifyCloudToDeviceConfigRequest' smart constructor.
data ModifyCloudToDeviceConfigRequest =
ModifyCloudToDeviceConfigRequest'
{ _mctdcrVersionToUpdate :: !(Maybe (Textual Int64))
, _mctdcrBinaryData :: !(Maybe Bytes)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ModifyCloudToDeviceConfigRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mctdcrVersionToUpdate'
--
-- * 'mctdcrBinaryData'
modifyCloudToDeviceConfigRequest
:: ModifyCloudToDeviceConfigRequest
modifyCloudToDeviceConfigRequest =
ModifyCloudToDeviceConfigRequest'
{_mctdcrVersionToUpdate = Nothing, _mctdcrBinaryData = Nothing}
-- | The version number to update. If this value is zero, it will not check
-- the version number of the server and will always update the current
-- version; otherwise, this update will fail if the version number found on
-- the server does not match this version number. This is used to support
-- multiple simultaneous updates without losing data.
mctdcrVersionToUpdate :: Lens' ModifyCloudToDeviceConfigRequest (Maybe Int64)
mctdcrVersionToUpdate
= lens _mctdcrVersionToUpdate
(\ s a -> s{_mctdcrVersionToUpdate = a})
. mapping _Coerce
-- | Required. The configuration data for the device.
mctdcrBinaryData :: Lens' ModifyCloudToDeviceConfigRequest (Maybe ByteString)
mctdcrBinaryData
= lens _mctdcrBinaryData
(\ s a -> s{_mctdcrBinaryData = a})
. mapping _Bytes
instance FromJSON ModifyCloudToDeviceConfigRequest
where
parseJSON
= withObject "ModifyCloudToDeviceConfigRequest"
(\ o ->
ModifyCloudToDeviceConfigRequest' <$>
(o .:? "versionToUpdate") <*> (o .:? "binaryData"))
instance ToJSON ModifyCloudToDeviceConfigRequest
where
toJSON ModifyCloudToDeviceConfigRequest'{..}
= object
(catMaybes
[("versionToUpdate" .=) <$> _mctdcrVersionToUpdate,
("binaryData" .=) <$> _mctdcrBinaryData])
-- | Associates \`members\` with a \`role\`.
--
-- /See:/ 'binding' smart constructor.
data Binding =
Binding'
{ _bMembers :: !(Maybe [Text])
, _bRole :: !(Maybe Text)
, _bCondition :: !(Maybe Expr)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Binding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bMembers'
--
-- * 'bRole'
--
-- * 'bCondition'
binding
:: Binding
binding =
Binding' {_bMembers = Nothing, _bRole = Nothing, _bCondition = Nothing}
-- | Specifies the identities requesting access for a Cloud Platform
-- resource. \`members\` can have the following values: * \`allUsers\`: A
-- special identifier that represents anyone who is on the internet; with
-- or without a Google account. * \`allAuthenticatedUsers\`: A special
-- identifier that represents anyone who is authenticated with a Google
-- account or a service account. * \`user:{emailid}\`: An email address
-- that represents a specific Google account. For example,
-- \`alice\'example.com\` . * \`serviceAccount:{emailid}\`: An email
-- address that represents a service account. For example,
-- \`my-other-app\'appspot.gserviceaccount.com\`. * \`group:{emailid}\`: An
-- email address that represents a Google group. For example,
-- \`admins\'example.com\`. * \`deleted:user:{emailid}?uid={uniqueid}\`: An
-- email address (plus unique identifier) representing a user that has been
-- recently deleted. For example,
-- \`alice\'example.com?uid=123456789012345678901\`. If the user is
-- recovered, this value reverts to \`user:{emailid}\` and the recovered
-- user retains the role in the binding. *
-- \`deleted:serviceAccount:{emailid}?uid={uniqueid}\`: An email address
-- (plus unique identifier) representing a service account that has been
-- recently deleted. For example,
-- \`my-other-app\'appspot.gserviceaccount.com?uid=123456789012345678901\`.
-- If the service account is undeleted, this value reverts to
-- \`serviceAccount:{emailid}\` and the undeleted service account retains
-- the role in the binding. * \`deleted:group:{emailid}?uid={uniqueid}\`:
-- An email address (plus unique identifier) representing a Google group
-- that has been recently deleted. For example,
-- \`admins\'example.com?uid=123456789012345678901\`. If the group is
-- recovered, this value reverts to \`group:{emailid}\` and the recovered
-- group retains the role in the binding. * \`domain:{domain}\`: The G
-- Suite domain (primary) that represents all the users of that domain. For
-- example, \`google.com\` or \`example.com\`.
bMembers :: Lens' Binding [Text]
bMembers
= lens _bMembers (\ s a -> s{_bMembers = a}) .
_Default
. _Coerce
-- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`,
-- \`roles\/editor\`, or \`roles\/owner\`.
bRole :: Lens' Binding (Maybe Text)
bRole = lens _bRole (\ s a -> s{_bRole = a})
-- | The condition that is associated with this binding. If the condition
-- evaluates to \`true\`, then this binding applies to the current request.
-- If the condition evaluates to \`false\`, then this binding does not
-- apply to the current request. However, a different role binding might
-- grant the same role to one or more of the members in this binding. To
-- learn which resources support conditions in their IAM policies, see the
-- [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
bCondition :: Lens' Binding (Maybe Expr)
bCondition
= lens _bCondition (\ s a -> s{_bCondition = a})
instance FromJSON Binding where
parseJSON
= withObject "Binding"
(\ o ->
Binding' <$>
(o .:? "members" .!= mempty) <*> (o .:? "role") <*>
(o .:? "condition"))
instance ToJSON Binding where
toJSON Binding'{..}
= object
(catMaybes
[("members" .=) <$> _bMembers,
("role" .=) <$> _bRole,
("condition" .=) <$> _bCondition])
| brendanhay/gogol | gogol-cloudiot/gen/Network/Google/CloudIOT/Types/Product.hs | mpl-2.0 | 81,597 | 0 | 27 | 17,871 | 12,216 | 7,086 | 5,130 | 1,354 | 1 |
module RunAndParse (runAndParse) where
import System.Process
import Data.Attoparsec.ByteString.Char8 (eitherResult, parseWith)
import Data.ByteString (hGetSome, empty)
runAndParse parser cmd args = do
(_,Just hIn,_,hProc) <- createProcess (proc cmd args){std_out = CreatePipe}
out <- parseWith (hGetSome hIn 1024) parser empty
waitForProcess hProc
return $ eitherResult out
| OH6AD/puputti | src/RunAndParse.hs | agpl-3.0 | 384 | 0 | 11 | 53 | 133 | 71 | 62 | 9 | 1 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2019 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Server.Requests.Api.RunGame (handler) where
import HabitOfFate.Prelude
import Network.HTTP.Types.Status (ok200)
import Web.Scotty (ScottyM)
import qualified Web.Scotty as Scotty
import HabitOfFate.Server.Common
import HabitOfFate.Server.Requests.Shared.RunGame
import HabitOfFate.Server.Transaction
handler ∷ Environment → ScottyM ()
handler environment =
Scotty.post "/api/run" <<< apiTransaction environment $
runGame <&> (fst >>> markdownResult ok200)
| gcross/habit-of-fate | sources/library/HabitOfFate/Server/Requests/Api/RunGame.hs | agpl-3.0 | 1,288 | 0 | 9 | 218 | 126 | 77 | 49 | 16 | 1 |
-- Canvas.Hs, control javascript canvas with Haskell
-- Copyright (C) 2013, Lennart Buit, Joost van Doorn, Pim Jager, Martijn Roo,
-- Thijs Scheepers
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library 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
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
-- USA
{-# LANGUAGE OverloadedStrings #-}
{- |
The CanvasHs.Protocol.Input module exposes a FromJSON instance for 'Event' which allows
JOSN strings describing an event te bo decoded by Aeson
-}
module CanvasHs.Protocol.Input (FromJSON(..)) where
import Data.Aeson ((.:), (.:?), FromJSON(..), Value(..))
import Control.Applicative ((<$>), (<*>))
import System.FilePath.Posix (takeExtension)
import qualified Data.ByteString.Lazy as BSL
import qualified Data.ByteString.UTF8 as BU
import qualified Data.ByteString.Lazy.UTF8 as BUL
import qualified Data.ByteString.Base64.Lazy as B64
import CanvasHs.Data
-- | JSONEventData describes eventdata which could be incoming in a JSONstring as a record which can later be used
-- to construct an 'Event'
data JSONEventData = JSONEventData {
jeventId :: Maybe BU.ByteString,
x :: Maybe Int,
y :: Maybe Int,
x1 :: Maybe Int, -- Only for mousedrag
y1 :: Maybe Int, -- Only for mousedrag
x2 :: Maybe Int, -- Only for mousedrag
y2 :: Maybe Int, -- Only for mousedrag
key :: Maybe BU.ByteString,
control :: Maybe Bool,
alt :: Maybe Bool,
shift :: Maybe Bool,
xdelta :: Maybe Int,
ydelta :: Maybe Int,
width :: Maybe Int,
height :: Maybe Int,
filename :: Maybe BSL.ByteString,
filecontents :: Maybe BSL.ByteString,
value :: Maybe BSL.ByteString
} deriving(Eq, Show)
-- | The FromJSON instance for JSONEventData allows the fromJSON instance of 'Event' to use parseJSON on the data field
instance FromJSON JSONEventData where
parseJSON (Object v) = JSONEventData <$>
v .:? "id" <*>
v .:? "x" <*>
v .:? "y" <*>
v .:? "x1" <*> -- Only for mousedrag
v .:? "y1" <*> -- Only for mousedrag
v .:? "x2" <*> -- Only for mousedrag
v .:? "y2" <*> -- Only for mousedrag
v .:? "key" <*>
v .:? "control" <*>
v .:? "alt" <*>
v .:? "shift" <*>
v .:? "xdelta" <*>
v .:? "ydelta" <*>
v .:? "width" <*>
v .:? "height" <*>
v .:? "filename" <*> -- Only for upload events
v .:? "filecontents" <*> -- Only for upload events
v .:? "value"
parseJSON _ = error "A toplevel JSON should be an object"
-- | The FromJSON instance of 'Event' allows incoming JSON strings describing an event to be decoded by Aeson,
-- incoming strings hold an event field identyfing the type of event and a datafield which describes the event
-- both of these are read by Aeson and read by the makeEvent function
instance FromJSON Event where
parseJSON (Object v) = do
makeEvent <$>
v .: "event" <*>
v .: "data"
parseJSON _ = error "A toplevel JSON should be an object"
-- Ooit gehoord van pattern matching, nou ik blijkbaar wel
makeEvent :: BU.ByteString -> JSONEventData -> Event
makeEvent "mousedown"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseDown (x, y) (BU.toString eid)
makeEvent "mouseclick"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseClick (x, y) (BU.toString eid)
makeEvent "mouseup"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseUp (x, y) (BU.toString eid)
makeEvent "mousedoubleclick"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseDoubleClick (x, y) (BU.toString eid)
makeEvent "mousedrag"
(JSONEventData{jeventId = Just eid1, x1 = Just x1, y1 = Just y1, x2 = Just x2, y2 = Just y2})
= MouseDrag (x1, y1) (BU.toString eid1) (x2, y2)
makeEvent "mouseover"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseOver (x, y) (BU.toString eid)
makeEvent "mouseout"
(JSONEventData{jeventId = Just eid, x = Just x, y = Just y})
= MouseOut (x, y) (BU.toString eid)
makeEvent "keydown"
(JSONEventData{key = Just k, control = Just c, alt = Just a, shift = Just sh})
= KeyDown (BU.toString k) (makeModifiers c a sh)
makeEvent "keypress"
(JSONEventData{key = Just k, control = Just c, alt = Just a, shift = Just sh})
= KeyPress (BU.toString k) (makeModifiers c a sh)
makeEvent "keyup"
(JSONEventData{key = Just k, control = Just c, alt = Just a, shift = Just sh})
= KeyUp (BU.toString k) (makeModifiers c a sh)
makeEvent "scroll"
(JSONEventData{jeventId = Just eid, xdelta = Just xd, ydelta = Just yd})
= Scroll (BU.toString eid) xd yd
makeEvent "upload"
(JSONEventData{filecontents = Just fc})
= UploadComplete (BUL.toString $ b, b)
where
(Right b) = B64.decode fc
makeEvent "resizewindow"
(JSONEventData{width = Just w, height = Just h})
= WindowResize w h
makeEvent "prompt"
(JSONEventData{value = Just val})
= PromptResponse (BUL.toString val)
makeEvent _ a = error ("JSON did not match any event" ++ (show a))
-- | a helper function to make a modifierlist from the incoming JSON
makeModifiers :: Bool -> Bool -> Bool -> [Modifier]
makeModifiers ctrl alt shift =
(if ctrl then [Ctrl] else []) ++
(if alt then [Alt] else []) ++
(if shift then [Shift] else [])
| CanvasHS/Canvas.hs | canvashs-module/CanvasHs/Protocol/Input.hs | lgpl-2.1 | 6,652 | 0 | 41 | 2,040 | 1,583 | 875 | 708 | 107 | 4 |
{-# OPTIONS_GHC -Wall #-}
-- !! WARNING: SPOILERS AHEAD !! --
-- CIS 194: Homework 10
module Homework10 where
import Control.Applicative
import Control.Arrow ( first )
import Data.Char
-- A parser for a value of type a is a function which takes a String
-- representing the input to be parsed, and succeeds or fails; if it
-- succeeds, it returns the parsed value along with the remainder of
-- the input.
newtype Parser a = Parser { runParser :: String -> Maybe (a, String) }
-- For example, 'satisfy' takes a predicate on Char, and constructs a
-- parser which succeeds only if it sees a Char that satisfies the
-- predicate (which it then returns). If it encounters a Char that
-- does not satisfy the predicate (or an empty input), it fails.
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing -- fail on the empty input
f (x:xs) -- check if x satisfies the predicate
-- if so, return x along with the remainder
-- of the input (that is, xs)
| p x = Just (x, xs)
| otherwise = Nothing -- otherwise, fail
-- Using satisfy, we can define the parser 'char c' which expects to
-- see exactly the character c, and fails otherwise.
char :: Char -> Parser Char
char c = satisfy (== c)
{- For example:
*Parser> runParser (satisfy isUpper) "ABC"
Just ('A',"BC")
*Parser> runParser (satisfy isUpper) "abc"
Nothing
*Parser> runParser (char 'x') "xyz"
Just ('x',"yz")
-}
-- For convenience, we've also provided a parser for positive
-- integers.
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
------------------------------------------------------------
-- Your code goes below here
------------------------------------------------------------
inParser :: ((String -> Maybe (a, String)) ->
(String -> Maybe (b, String))) ->
Parser a ->
Parser b
inParser = (Parser .) . (. runParser)
instance Functor Parser where
fmap f = inParser $ fmap fmap fmap (first f)
instance Applicative Parser where
pure x = Parser $ Just . (x,)
pf <*> px = Parser $ \ys -> case runParser pf ys of
Just (f, ys') -> first f <$> runParser px ys'
_ -> Nothing
abParser :: Parser (Char, Char)
abParser = (,) <$> char 'a' <*> char 'b'
abParser_ :: Parser ()
abParser_ = pure (pure ()) <$> char 'a' <*> char 'b'
intPair :: Parser [Integer]
intPair = (\x _ y -> [x,y]) <$> posInt <*> char ' ' <*> posInt
instance Alternative Parser where
empty = Parser $ const Nothing
p1 <|> p2 = Parser $ \xs -> runParser p1 xs <|> runParser p2 xs
mute :: Parser a -> Parser ()
mute = fmap $ pure ()
intOrUppercase :: Parser ()
intOrUppercase = mute posInt <|> mute (satisfy isUpper)
| nilthehuman/cis194 | Homework10.hs | unlicense | 2,963 | 0 | 12 | 787 | 700 | 371 | 329 | -1 | -1 |
module FormalContext.Wrapper where
import FormalContext.FormalContext
import FormalContext.FormalContext2
import Data.Map
import Data.List
toFormalContext2 :: FormalContext g m -> FormalContext2 g m
toFormalContext2 cxt@(FormalContext dom cod mat)
= FormalContext2 (reverse $ sort dom) (reverse $ sort cod) rows cols
where rows = fromList $ [(obj, FormalContext.FormalContext.objIntent cxt obj) | obj <- dom]
cols = fromList $ [(att, FormalContext.FormalContext.attExtent cxt att) | att <- cod]
| francesco-kriegel/conexp-hs | src/FormalContext/Wrapper.hs | apache-2.0 | 514 | 0 | 11 | 81 | 165 | 89 | 76 | 10 | 1 |
-- Copyright (c) 2013-2015 PivotCloud, Inc.
--
-- Aws.Kinesis.Client.Producer.Kit
--
-- Please feel free to contact us at [email protected] 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.
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Module: Aws.Kinesis.Client.Producer.Kit
-- Copyright: Copyright © 2013-2015 PivotCloud, Inc.
-- License: Apache-2.0
-- Maintainer: Jon Sterling <[email protected]>
-- Stability: experimental
--
module Aws.Kinesis.Client.Producer.Kit
( -- * Producer Kit
ProducerKit
, makeProducerKit
, pkKinesisKit
, pkStreamName
, pkBatchPolicy
, pkRetryPolicy
, pkMessageQueueBounds
, pkMaxConcurrency
, pkCleanupTimeout
, pkQueueImplementation
-- * Queue Implementations
, QueueImplementation(..)
, defaultQueueImplementation
-- * Policies
, BatchPolicy
, defaultBatchPolicy
, bpBatchSize
, RetryPolicy
, defaultRetryPolicy
, rpRetryCount
-- ** Constants
, pattern MaxMessageSize
) where
import Aws.Kinesis.Client.Producer.Internal
-- | The maximum size in bytes of a message.
--
pattern MaxMessageSize = 51000
| alephcloud/hs-aws-kinesis-client | src/Aws/Kinesis/Client/Producer/Kit.hs | apache-2.0 | 1,680 | 0 | 5 | 246 | 122 | 92 | 30 | 25 | 0 |
infixr 5 :-:
data List a = Empty | a :-: (List a) deriving (Show, Read, Ord, Eq)
| Oscarzhao/haskell | learnyouahaskell/infixr.hs | apache-2.0 | 81 | 0 | 8 | 18 | 45 | 25 | 20 | 2 | 0 |
import qualified Data.Map as Map
a1 = [(1, "one"), (2, "two"), (3, "three")]
mapFromL =
Map.fromList a1
mapFold =
foldl (\map (k, v) -> Map.insert k v map ) Map.empty a1
mapManual =
Map.insert 2 "two" .
Map.insert 3 "three" .
Map.insert 1 "one" .
Map.insert 4 "four" $ Map.empty
| EricYT/real-world | src/chapter-13/buildmap.hs | apache-2.0 | 308 | 0 | 10 | 79 | 141 | 77 | 64 | 11 | 1 |
{-# LANGUAGE BangPatterns #-}
module Distribution.Solver.Modular.Message (
Message(..),
showMessages
) where
import qualified Data.List as L
import Prelude hiding (pi)
import Distribution.Text -- from Cabal
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Package
import Distribution.Solver.Modular.Tree
( FailReason(..), POption(..) )
import Distribution.Solver.Types.ConstraintSource
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.Progress
data Message =
Enter -- ^ increase indentation level
| Leave -- ^ decrease indentation level
| TryP QPN POption
| TryF QFN Bool
| TryS QSN Bool
| Next (Goal QPN)
| Success
| Failure ConflictSet FailReason
-- | Transforms the structured message type to actual messages (strings).
--
-- Takes an additional relevance predicate. The predicate gets a stack of goal
-- variables and can decide whether messages regarding these goals are relevant.
-- You can plug in 'const True' if you're interested in a full trace. If you
-- want a slice of the trace concerning a particular conflict set, then plug in
-- a predicate returning 'True' on the empty stack and if the head is in the
-- conflict set.
--
-- The second argument indicates if the level numbers should be shown. This is
-- recommended for any trace that involves backtracking, because only the level
-- numbers will allow to keep track of backjumps.
showMessages :: ([Var QPN] -> Bool) -> Bool -> Progress Message a b -> Progress String a b
showMessages p sl = go [] 0
where
-- The stack 'v' represents variables that are currently assigned by the
-- solver. 'go' pushes a variable for a recursive call when it encounters
-- 'TryP', 'TryF', or 'TryS' and pops a variable when it encounters 'Leave'.
-- When 'go' processes a package goal, or a package goal followed by a
-- 'Failure', it calls 'atLevel' with the goal variable at the head of the
-- stack so that the predicate can also select messages relating to package
-- goal choices.
go :: [Var QPN] -> Int -> Progress Message a b -> Progress String a b
go !_ !_ (Done x) = Done x
go !_ !_ (Fail x) = Fail x
-- complex patterns
go !v !l (Step (TryP qpn i) (Step Enter (Step (Failure c fr) (Step Leave ms)))) =
goPReject v l qpn [i] c fr ms
go !v !l (Step (TryF qfn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) =
(atLevel (F qfn : v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms)
go !v !l (Step (TryS qsn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) =
(atLevel (S qsn : v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms)
go !v !l (Step (Next (Goal (P qpn) gr)) (Step (TryP qpn' i) ms@(Step Enter (Step (Next _) _)))) =
(atLevel (P qpn : v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGR gr) (go (P qpn : v) l ms)
go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Fail _)) =
(atLevel (P qpn : v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms
-- the previous case potentially arises in the error output, because we remove the backjump itself
-- if we cut the log after the first error
go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Step (Failure _c Backjump) _)) =
(atLevel (P qpn : v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms
go !v !l (Step (Next (Goal (P qpn) gr)) (Step (Failure c fr) ms)) =
let v' = P qpn : v
in (atLevel v' l $ showPackageGoal qpn gr) $ (atLevel v' l $ showFailure c fr) (go v l ms)
go !v !l (Step (Failure c Backjump) ms@(Step Leave (Step (Failure c' Backjump) _)))
| c == c' = go v l ms
-- standard display
go !v !l (Step Enter ms) = go v (l+1) ms
go !v !l (Step Leave ms) = go (drop 1 v) (l-1) ms
go !v !l (Step (TryP qpn i) ms) = (atLevel (P qpn : v) l $ "trying: " ++ showQPNPOpt qpn i) (go (P qpn : v) l ms)
go !v !l (Step (TryF qfn b) ms) = (atLevel (F qfn : v) l $ "trying: " ++ showQFNBool qfn b) (go (F qfn : v) l ms)
go !v !l (Step (TryS qsn b) ms) = (atLevel (S qsn : v) l $ "trying: " ++ showQSNBool qsn b) (go (S qsn : v) l ms)
go !v !l (Step (Next (Goal (P qpn) gr)) ms) = (atLevel (P qpn : v) l $ showPackageGoal qpn gr) (go v l ms)
go !v !l (Step (Next _) ms) = go v l ms -- ignore flag goals in the log
go !v !l (Step (Success) ms) = (atLevel v l $ "done") (go v l ms)
go !v !l (Step (Failure c fr) ms) = (atLevel v l $ showFailure c fr) (go v l ms)
showPackageGoal :: QPN -> QGoalReason -> String
showPackageGoal qpn gr = "next goal: " ++ showQPN qpn ++ showGR gr
showFailure :: ConflictSet -> FailReason -> String
showFailure c fr = "fail" ++ showFR c fr
-- special handler for many subsequent package rejections
goPReject :: [Var QPN]
-> Int
-> QPN
-> [POption]
-> ConflictSet
-> FailReason
-> Progress Message a b
-> Progress String a b
goPReject v l qpn is c fr (Step (TryP qpn' i) (Step Enter (Step (Failure _ fr') (Step Leave ms))))
| qpn == qpn' && fr `compareFR` fr' = goPReject v l qpn (i : is) c fr ms
goPReject v l qpn is c fr ms =
(atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms)
-- write a message, but only if it's relevant; we can also enable or disable the display of the current level
atLevel :: [Var QPN] -> Int -> String -> Progress String a b -> Progress String a b
atLevel v l x xs
| sl && p v = let s = show l
in Step ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) xs
| p v = Step x xs
| otherwise = xs
-- Compares 'FailReasons' for equality, with one exception. It ignores the
-- package instance (I) in the 'DependencyReason' of an 'LDep' in a
-- 'Conflicting' failure. It ignores the package instance so that the solver
-- can combine messages when consecutive choices for one package all lead to
-- the same conflict. Implementing #4142 would allow us to remove this
-- function and use "==".
compareFR :: FailReason -> FailReason -> Bool
compareFR (Conflicting ds1) (Conflicting ds2) =
compareListsOn compareDeps ds1 ds2
where
compareDeps :: LDep QPN -> LDep QPN -> Bool
compareDeps (LDep dr1 d1) (LDep dr2 d2) =
compareDRs dr1 dr2 && d1 == d2
compareDRs :: DependencyReason QPN -> DependencyReason QPN -> Bool
compareDRs (DependencyReason (PI qpn1 _) fs1 ss1) (DependencyReason (PI qpn2 _) fs2 ss2) =
qpn1 == qpn2 && fs1 == fs2 && ss1 == ss2
compareListsOn :: (a -> a -> Bool) -> [a] -> [a] -> Bool
compareListsOn _ [] [] = True
compareListsOn _ [] _ = False
compareListsOn _ _ [] = False
compareListsOn f (x : xs) (y : ys) = f x y && compareListsOn f xs ys
compareFR fr1 fr2 = fr1 == fr2
showQPNPOpt :: QPN -> POption -> String
showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) =
case linkedTo of
Nothing -> showPI (PI qpn i) -- Consistent with prior to POption
Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i)
showGR :: QGoalReason -> String
showGR UserGoal = " (user goal)"
showGR (DependencyGoal dr) = " (dependency of " ++ showDependencyReason showPI dr ++ ")"
showFR :: ConflictSet -> FailReason -> String
showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)"
showFR _ (Conflicting ds) =
let showDep' = showDep $ \(PI qpn _) -> showQPN qpn
in " (conflict: " ++ L.intercalate ", " (L.map showDep' ds) ++ ")"
showFR _ CannotInstall = " (only already installed instances can be used)"
showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)"
showFR _ Shadowed = " (shadowed by another installed package with same version)"
showFR _ Broken = " (package is broken)"
showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")"
showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)"
showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)"
showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)"
showFR _ ManualFlag = " (manual flag can only be changed explicitly)"
showFR c Backjump = " (backjumping, conflict set: " ++ showConflictSet c ++ ")"
showFR _ MultipleInstances = " (multiple instances)"
showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showConflictSet c ++ ")"
showFR c CyclicDependencies = " (cyclic dependencies; conflict set: " ++ showConflictSet c ++ ")"
-- The following are internal failures. They should not occur. In the
-- interest of not crashing unnecessarily, we still just print an error
-- message though.
showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")"
showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")"
showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)"
constraintSource :: ConstraintSource -> String
constraintSource src = "constraint from " ++ showConstraintSource src
| themoritz/cabal | cabal-install/Distribution/Solver/Modular/Message.hs | bsd-3-clause | 9,938 | 0 | 19 | 2,734 | 3,150 | 1,571 | 1,579 | 123 | 24 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A Matrix - singly represented by an Int pair
module Tower.M where
import qualified Protolude as P
import Protolude
(($), Functor(..), Show, Eq(..), (.), (<$>))
import GHC.TypeLits
import qualified Data.Vector as V
import Data.Proxy (Proxy(..))
import Data.Functor.Rep
import Data.Distributive as D
import Tower.V
import Tower.Additive
import Test.QuickCheck
import Tower.Multiplicative
import Tower.Integral
import Tower.Module
import Tower.Ring
newtype M m n a = M { flattenM :: V.Vector a }
deriving (Functor, Show, Eq, P.Foldable)
instance (KnownNat m, KnownNat n, Arbitrary a, AdditiveUnital a) => Arbitrary (M m n a) where
arbitrary = frequency
[ (1, P.pure zero)
, (9, toM <$> vector (m*n))
]
where
n = P.fromInteger $ natVal (Proxy :: Proxy n)
m = P.fromInteger $ natVal (Proxy :: Proxy m)
instance (KnownNat m, KnownNat n) => Distributive (M m n) where
distribute f = M $ V.generate (n*m)
$ \i -> fmap (\(M v) -> V.unsafeIndex v i) f
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
n = P.fromInteger $ natVal (Proxy :: Proxy n)
instance (KnownNat m, KnownNat n) => Representable (M m n) where
type Rep (M m n) = (P.Int, P.Int)
tabulate f = M $ V.generate (m*n) (\x -> f (divMod x (m*n)))
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
n = P.fromInteger $ natVal (Proxy :: Proxy n)
index (M xs) (i0,i1) = xs V.! (i0*m + i1)
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
toM :: forall a m n . (AdditiveUnital a, KnownNat m, KnownNat n) => [a] -> M m n a
toM l = M $ V.fromList $ P.take (m*n) $ l P.++ P.repeat zero
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
n = P.fromInteger $ natVal (Proxy :: Proxy n)
fromVV :: forall a m n. ( ) => V m (V n a) -> M m n a
fromVV vv = M $ P.foldr ((V.++) . toVector) V.empty vv
colM :: forall a n. ( ) => V n a -> M 1 n a
colM v = M $ toVector v
rowM :: forall a m. ( ) => V m a -> M m 1 a
rowM v = M $ toVector v
colV :: forall a n. ( ) => M 1 n a -> V n a
colV m = V $ flattenM m
rowV :: forall a m. ( ) => M m 1 a -> V m a
rowV m = V $ flattenM m
row :: forall a m n. (KnownNat m, KnownNat n) => P.Int -> M m n a -> V n a
row i (M a) = V $ V.unsafeSlice (i*m) n a
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
n = P.fromInteger $ natVal (Proxy :: Proxy n)
col :: forall a m n. (KnownNat m, KnownNat n) => P.Int -> M m n a -> V m a
col i (M a) = V $ V.generate m (\x -> a V.! (i+x*n))
where
m = P.fromInteger $ natVal (Proxy :: Proxy m)
n = P.fromInteger $ natVal (Proxy :: Proxy n)
mmult :: forall m n k a. (CRing a, KnownNat m, KnownNat n, KnownNat k) =>
M m k a -> M k n a -> M m n a
mmult x y = tabulate (\(i,j) -> row i x <.> col j y)
| tonyday567/tower | src/Tower/M.hs | bsd-3-clause | 3,091 | 0 | 14 | 789 | 1,463 | 792 | 671 | -1 | -1 |
module Opaleye.Order (module Opaleye.Order, O.OrderSpec) where
import qualified Opaleye.Column as C
import Opaleye.QueryArr (Query)
import qualified Opaleye.QueryArr as Q
import qualified Opaleye.Internal.Order as O
import qualified Database.HaskellDB.PrimQuery as HPQ
orderBy :: O.OrderSpec a -> Query a -> Query a
orderBy os q =
Q.simpleQueryArr (O.orderByU os . Q.runSimpleQueryArr q)
desc :: (a -> C.Column b) -> O.OrderSpec a
desc = O.orderSpec HPQ.OpDesc
asc :: (a -> C.Column b) -> O.OrderSpec a
asc = O.orderSpec HPQ.OpAsc
limit :: Int -> Query a -> Query a
limit n a = Q.simpleQueryArr (O.limit' n . Q.runSimpleQueryArr a)
offset :: Int -> Query a -> Query a
offset n a = Q.simpleQueryArr (O.offset' n . Q.runSimpleQueryArr a)
| k0001/haskell-opaleye | Opaleye/Order.hs | bsd-3-clause | 755 | 0 | 9 | 132 | 297 | 156 | 141 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent
import Data.Maybe
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as C8
import Data.Serialize
import qualified System.IO as IO
import qualified ClientLib as CL
import qualified Utils as Utils
import qualified Lib as Lib
import KVProtocol
import Math.Probable
import Debug.Trace
main :: IO ()
main = Lib.parseArguments >>= \(Just config) -> do
masterH <- CL.registerWithMaster config
cLIissueRequests masterH
--children <- issueNRequests masterH 1000 []
--mapM_ takeMVar children
issueNRequests :: CL.MasterHandle -> Int -> [MVar ()] -> IO ([MVar ()])
issueNRequests mH n mvars
| n == 0 = return mvars
| otherwise = do
let request = createRequest (n*3)
m <- newEmptyMVar
tid <- forkFinally (case request of
(Left k) -> do
CL.getVal mH k
return ()
(Right (k,v)) -> do
CL.putVal mH k v
return ()
) (\_ -> putMVar m ())
threadDelay 50000
issueNRequests mH (n - 1) (mvars ++ [m])
createRequest n = let nBstring = C8.pack $ show n
in Right (nBstring, nBstring)
cLIissueRequests :: CL.MasterHandle -> IO ()
cLIissueRequests mH = do
text <- IO.getLine
request <- parseInput (C8.pack text)
if isNothing request
then cLIissueRequests mH
else do
let request' = fromJust request
case request' of
(PutReq _ k v) -> do
CL.putVal mH k v >>= (\_ -> return ())
(DelReq _ k) -> do
CL.delVal mH k
(GetReq _ k) -> do
CL.getVal mH k >>= (\_ -> return ())
return ()
cLIissueRequests mH
parseInput :: B.ByteString -> IO(Maybe KVRequest)
parseInput text = do
let pieces = C8.split ' ' text
if Prelude.length pieces > 1
then let reqType = Prelude.head pieces
key = pieces !! 1
val | Prelude.length pieces >= 3 = pieces !! 2
| otherwise = B.empty
in return $ case reqType of
"PUT" -> Just $ PutReq 0 key val
"GET" -> Just $ GetReq 0 key
"DEL" -> Just $ DelReq 0 key
_ -> Nothing
else return Nothing
| ntindall/KVStore | client/Client.hs | bsd-3-clause | 2,336 | 0 | 19 | 784 | 800 | 398 | 402 | 67 | 5 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[RnExpr]{Renaming of expressions}
Basically dependency analysis.
Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
general, all of these functions return a renamed thing, and a set of
free variables.
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
module RnExpr (
rnLExpr, rnExpr, rnStmts
) where
#include "HsVersions.h"
import RnBinds ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
rnMatchGroup, rnGRHS, makeMiniFixityEnv)
import HsSyn
import TcRnMonad
import Module ( getModule )
import RnEnv
import RnSplice ( rnBracket, rnSpliceExpr, checkThLocalName )
import RnTypes
import RnPat
import DynFlags
import BasicTypes ( FixityDirection(..) )
import PrelNames
import Name
import NameSet
import RdrName
import UniqSet
import Data.List
import Util
import ListSetOps ( removeDups )
import ErrUtils
import Outputable
import SrcLoc
import FastString
import Control.Monad
import TysWiredIn ( nilDataConName )
{-
************************************************************************
* *
\subsubsection{Expressions}
* *
************************************************************************
-}
rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
rnExprs ls = rnExprs' ls emptyUniqSet
where
rnExprs' [] acc = return ([], acc)
rnExprs' (expr:exprs) acc =
do { (expr', fvExpr) <- rnLExpr expr
-- Now we do a "seq" on the free vars because typically it's small
-- or empty, especially in very long lists of constants
; let acc' = acc `plusFV` fvExpr
; (exprs', fvExprs) <- acc' `seq` rnExprs' exprs acc'
; return (expr':exprs', fvExprs) }
-- Variables. We look up the variable and return the resulting name.
rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
rnLExpr = wrapLocFstM rnExpr
rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
finishHsVar :: Name -> RnM (HsExpr Name, FreeVars)
-- Separated from rnExpr because it's also used
-- when renaming infix expressions
finishHsVar name
= do { this_mod <- getModule
; when (nameIsLocalOrFrom this_mod name) $
checkThLocalName name
; return (HsVar name, unitFV name) }
rnExpr (HsVar v)
= do { mb_name <- lookupOccRn_maybe v
; case mb_name of {
Nothing -> do { if startsWithUnderscore (rdrNameOcc v)
then return (HsUnboundVar v, emptyFVs)
else do { n <- reportUnboundName v; finishHsVar n } } ;
Just name
| name == nilDataConName -- Treat [] as an ExplicitList, so that
-- OverloadedLists works correctly
-> rnExpr (ExplicitList placeHolderType Nothing [])
| otherwise
-> finishHsVar name }}
rnExpr (HsIPVar v)
= return (HsIPVar v, emptyFVs)
rnExpr (HsLit lit@(HsString src s))
= do { opt_OverloadedStrings <- xoptM Opt_OverloadedStrings
; if opt_OverloadedStrings then
rnExpr (HsOverLit (mkHsIsString src s placeHolderType))
else do {
; rnLit lit
; return (HsLit lit, emptyFVs) } }
rnExpr (HsLit lit)
= do { rnLit lit
; return (HsLit lit, emptyFVs) }
rnExpr (HsOverLit lit)
= do { (lit', fvs) <- rnOverLit lit
; return (HsOverLit lit', fvs) }
rnExpr (HsApp fun arg)
= do { (fun',fvFun) <- rnLExpr fun
; (arg',fvArg) <- rnLExpr arg
; return (HsApp fun' arg', fvFun `plusFV` fvArg) }
rnExpr (OpApp e1 (L op_loc (HsVar op_rdr)) _ e2)
= do { (e1', fv_e1) <- rnLExpr e1
; (e2', fv_e2) <- rnLExpr e2
; op_name <- setSrcSpan op_loc (lookupOccRn op_rdr)
; (op', fv_op) <- finishHsVar op_name
-- NB: op' is usually just a variable, but might be
-- an applicatoin (assert "Foo.hs:47")
-- Deal with fixity
-- When renaming code synthesised from "deriving" declarations
-- we used to avoid fixity stuff, but we can't easily tell any
-- more, so I've removed the test. Adding HsPars in TcGenDeriv
-- should prevent bad things happening.
; fixity <- lookupFixityRn op_name
; final_e <- mkOpAppRn e1' (L op_loc op') fixity e2'
; return (final_e, fv_e1 `plusFV` fv_op `plusFV` fv_e2) }
rnExpr (OpApp _ other_op _ _)
= failWith (vcat [ hang (ptext (sLit "Infix application with a non-variable operator:"))
2 (ppr other_op)
, ptext (sLit "(Probably resulting from a Template Haskell splice)") ])
rnExpr (NegApp e _)
= do { (e', fv_e) <- rnLExpr e
; (neg_name, fv_neg) <- lookupSyntaxName negateName
; final_e <- mkNegAppRn e' neg_name
; return (final_e, fv_e `plusFV` fv_neg) }
------------------------------------------
-- Template Haskell extensions
-- Don't ifdef-GHCI them because we want to fail gracefully
-- (not with an rnExpr crash) in a stage-1 compiler.
rnExpr e@(HsBracket br_body) = rnBracket e br_body
rnExpr (HsSpliceE splice) = rnSpliceExpr splice
---------------------------------------------
-- Sections
-- See Note [Parsing sections] in Parser.y
rnExpr (HsPar (L loc (section@(SectionL {}))))
= do { (section', fvs) <- rnSection section
; return (HsPar (L loc section'), fvs) }
rnExpr (HsPar (L loc (section@(SectionR {}))))
= do { (section', fvs) <- rnSection section
; return (HsPar (L loc section'), fvs) }
rnExpr (HsPar e)
= do { (e', fvs_e) <- rnLExpr e
; return (HsPar e', fvs_e) }
rnExpr expr@(SectionL {})
= do { addErr (sectionErr expr); rnSection expr }
rnExpr expr@(SectionR {})
= do { addErr (sectionErr expr); rnSection expr }
---------------------------------------------
rnExpr (HsCoreAnn src ann expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsCoreAnn src ann expr', fvs_expr) }
rnExpr (HsSCC src lbl expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsSCC src lbl expr', fvs_expr) }
rnExpr (HsTickPragma src info expr)
= do { (expr', fvs_expr) <- rnLExpr expr
; return (HsTickPragma src info expr', fvs_expr) }
rnExpr (HsLam matches)
= do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLExpr matches
; return (HsLam matches', fvMatch) }
rnExpr (HsLamCase _arg matches)
= do { (matches', fvs_ms) <- rnMatchGroup CaseAlt rnLExpr matches
-- ; return (HsLamCase arg matches', fvs_ms) }
; return (HsLamCase placeHolderType matches', fvs_ms) }
rnExpr (HsCase expr matches)
= do { (new_expr, e_fvs) <- rnLExpr expr
; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLExpr matches
; return (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs) }
rnExpr (HsLet binds expr)
= rnLocalBindsAndThen binds $ \binds' -> do
{ (expr',fvExpr) <- rnLExpr expr
; return (HsLet binds' expr', fvExpr) }
rnExpr (HsDo do_or_lc stmts _)
= do { ((stmts', _), fvs) <- rnStmts do_or_lc rnLExpr stmts (\ _ -> return ((), emptyFVs))
; return ( HsDo do_or_lc stmts' placeHolderType, fvs ) }
rnExpr (ExplicitList _ _ exps)
= do { opt_OverloadedLists <- xoptM Opt_OverloadedLists
; (exps', fvs) <- rnExprs exps
; if opt_OverloadedLists
then do {
; (from_list_n_name, fvs') <- lookupSyntaxName fromListNName
; return (ExplicitList placeHolderType (Just from_list_n_name) exps'
, fvs `plusFV` fvs') }
else
return (ExplicitList placeHolderType Nothing exps', fvs) }
rnExpr (ExplicitPArr _ exps)
= do { (exps', fvs) <- rnExprs exps
; return (ExplicitPArr placeHolderType exps', fvs) }
rnExpr (ExplicitTuple tup_args boxity)
= do { checkTupleSection tup_args
; checkTupSize (length tup_args)
; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args
; return (ExplicitTuple tup_args' boxity, plusFVs fvs) }
where
rnTupArg (L l (Present e)) = do { (e',fvs) <- rnLExpr e
; return (L l (Present e'), fvs) }
rnTupArg (L l (Missing _)) = return (L l (Missing placeHolderType)
, emptyFVs)
rnExpr (RecordCon con_id _ rbinds)
= do { conname <- lookupLocatedOccRn con_id
; (rbinds', fvRbinds) <- rnHsRecBinds (HsRecFieldCon (unLoc conname)) rbinds
; return (RecordCon conname noPostTcExpr rbinds',
fvRbinds `addOneFV` unLoc conname) }
rnExpr (RecordUpd expr rbinds _ _ _)
= do { (expr', fvExpr) <- rnLExpr expr
; (rbinds', fvRbinds) <- rnHsRecBinds HsRecFieldUpd rbinds
; return (RecordUpd expr' rbinds' [] [] [],
fvExpr `plusFV` fvRbinds) }
rnExpr (ExprWithTySig expr pty PlaceHolder)
= do { (wcs, pty') <- extractWildcards pty
; bindLocatedLocalsFV wcs $ \wcs_new -> do {
(pty'', fvTy) <- rnLHsType ExprWithTySigCtx pty'
; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty'') $
rnLExpr expr
; return (ExprWithTySig expr' pty'' wcs_new, fvExpr `plusFV` fvTy) } }
rnExpr (HsIf _ p b1 b2)
= do { (p', fvP) <- rnLExpr p
; (b1', fvB1) <- rnLExpr b1
; (b2', fvB2) <- rnLExpr b2
; (mb_ite, fvITE) <- lookupIfThenElse
; return (HsIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
rnExpr (HsMultiIf _ty alts)
= do { (alts', fvs) <- mapFvRn (rnGRHS IfAlt rnLExpr) alts
-- ; return (HsMultiIf ty alts', fvs) }
; return (HsMultiIf placeHolderType alts', fvs) }
rnExpr (HsType a)
= do { (t, fvT) <- rnLHsType HsTypeCtx a
; return (HsType t, fvT) }
rnExpr (ArithSeq _ _ seq)
= do { opt_OverloadedLists <- xoptM Opt_OverloadedLists
; (new_seq, fvs) <- rnArithSeq seq
; if opt_OverloadedLists
then do {
; (from_list_name, fvs') <- lookupSyntaxName fromListName
; return (ArithSeq noPostTcExpr (Just from_list_name) new_seq, fvs `plusFV` fvs') }
else
return (ArithSeq noPostTcExpr Nothing new_seq, fvs) }
rnExpr (PArrSeq _ seq)
= do { (new_seq, fvs) <- rnArithSeq seq
; return (PArrSeq noPostTcExpr new_seq, fvs) }
{-
These three are pattern syntax appearing in expressions.
Since all the symbols are reservedops we can simply reject them.
We return a (bogus) EWildPat in each case.
-}
rnExpr EWildPat = return (hsHoleExpr, emptyFVs)
rnExpr e@(EAsPat {}) = patSynErr e
rnExpr e@(EViewPat {}) = patSynErr e
rnExpr e@(ELazyPat {}) = patSynErr e
{-
************************************************************************
* *
Static values
* *
************************************************************************
For the static form we check that the free variables are all top-level
value bindings. This is done by checking that the name is external or
wired-in. See the Notes about the NameSorts in Name.hs.
-}
rnExpr e@(HsStatic expr) = do
target <- fmap hscTarget getDynFlags
case target of
-- SPT entries are expected to exist in object code so far, and this is
-- not the case in interpreted mode. See bug #9878.
HscInterpreted -> addErr $ sep
[ text "The static form is not supported in interpreted mode."
, text "Please use -fobject-code."
]
_ -> return ()
(expr',fvExpr) <- rnLExpr expr
stage <- getStage
case stage of
Brack _ _ -> return () -- Don't check names if we are inside brackets.
-- We don't want to reject cases like:
-- \e -> [| static $(e) |]
-- if $(e) turns out to produce a legal expression.
Splice _ -> addErr $ sep
[ text "static forms cannot be used in splices:"
, nest 2 $ ppr e
]
_ -> do
let isTopLevelName n = isExternalName n || isWiredInName n
case nameSetElems $ filterNameSet
(\n -> not (isTopLevelName n || isUnboundName n))
fvExpr of
[] -> return ()
fvNonGlobal -> addErr $ cat
[ text $ "Only identifiers of top-level bindings can "
++ "appear in the body of the static form:"
, nest 2 $ ppr e
, text "but the following identifiers were found instead:"
, nest 2 $ vcat $ map ppr fvNonGlobal
]
return (HsStatic expr', fvExpr)
{-
************************************************************************
* *
Arrow notation
* *
************************************************************************
-}
rnExpr (HsProc pat body)
= newArrowScope $
rnPat ProcExpr pat $ \ pat' -> do
{ (body',fvBody) <- rnCmdTop body
; return (HsProc pat' body', fvBody) }
-- Ideally, these would be done in parsing, but to keep parsing simple, we do it here.
rnExpr e@(HsArrApp {}) = arrowFail e
rnExpr e@(HsArrForm {}) = arrowFail e
rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
-- HsWrap
hsHoleExpr :: HsExpr Name
hsHoleExpr = HsUnboundVar (mkRdrUnqual (mkVarOcc "_"))
arrowFail :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
arrowFail e
= do { addErr (vcat [ ptext (sLit "Arrow command found where an expression was expected:")
, nest 2 (ppr e) ])
-- Return a place-holder hole, so that we can carry on
-- to report other errors
; return (hsHoleExpr, emptyFVs) }
----------------------
-- See Note [Parsing sections] in Parser.y
rnSection :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
rnSection section@(SectionR op expr)
= do { (op', fvs_op) <- rnLExpr op
; (expr', fvs_expr) <- rnLExpr expr
; checkSectionPrec InfixR section op' expr'
; return (SectionR op' expr', fvs_op `plusFV` fvs_expr) }
rnSection section@(SectionL expr op)
= do { (expr', fvs_expr) <- rnLExpr expr
; (op', fvs_op) <- rnLExpr op
; checkSectionPrec InfixL section op' expr'
; return (SectionL expr' op', fvs_op `plusFV` fvs_expr) }
rnSection other = pprPanic "rnSection" (ppr other)
{-
************************************************************************
* *
Records
* *
************************************************************************
-}
rnHsRecBinds :: HsRecFieldContext -> HsRecordBinds RdrName
-> RnM (HsRecordBinds Name, FreeVars)
rnHsRecBinds ctxt rec_binds@(HsRecFields { rec_dotdot = dd })
= do { (flds, fvs) <- rnHsRecFields ctxt HsVar rec_binds
; (flds', fvss) <- mapAndUnzipM rn_field flds
; return (HsRecFields { rec_flds = flds', rec_dotdot = dd },
fvs `plusFV` plusFVs fvss) }
where
rn_field (L l fld) = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
; return (L l (fld { hsRecFieldArg = arg' }), fvs) }
{-
************************************************************************
* *
Arrow commands
* *
************************************************************************
-}
rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
rnCmdArgs [] = return ([], emptyFVs)
rnCmdArgs (arg:args)
= do { (arg',fvArg) <- rnCmdTop arg
; (args',fvArgs) <- rnCmdArgs args
; return (arg':args', fvArg `plusFV` fvArgs) }
rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
rnCmdTop = wrapLocFstM rnCmdTop'
where
rnCmdTop' (HsCmdTop cmd _ _ _)
= do { (cmd', fvCmd) <- rnLCmd cmd
; let cmd_names = [arrAName, composeAName, firstAName] ++
nameSetElems (methodNamesCmd (unLoc cmd'))
-- Generate the rebindable syntax for the monad
; (cmd_names', cmd_fvs) <- lookupSyntaxNames cmd_names
; return (HsCmdTop cmd' placeHolderType placeHolderType
(cmd_names `zip` cmd_names'),
fvCmd `plusFV` cmd_fvs) }
rnLCmd :: LHsCmd RdrName -> RnM (LHsCmd Name, FreeVars)
rnLCmd = wrapLocFstM rnCmd
rnCmd :: HsCmd RdrName -> RnM (HsCmd Name, FreeVars)
rnCmd (HsCmdArrApp arrow arg _ ho rtl)
= do { (arrow',fvArrow) <- select_arrow_scope (rnLExpr arrow)
; (arg',fvArg) <- rnLExpr arg
; return (HsCmdArrApp arrow' arg' placeHolderType ho rtl,
fvArrow `plusFV` fvArg) }
where
select_arrow_scope tc = case ho of
HsHigherOrderApp -> tc
HsFirstOrderApp -> escapeArrowScope tc
-- See Note [Escaping the arrow scope] in TcRnTypes
-- Before renaming 'arrow', use the environment of the enclosing
-- proc for the (-<) case.
-- Local bindings, inside the enclosing proc, are not in scope
-- inside 'arrow'. In the higher-order case (-<<), they are.
-- infix form
rnCmd (HsCmdArrForm op (Just _) [arg1, arg2])
= do { (op',fv_op) <- escapeArrowScope (rnLExpr op)
; let L _ (HsVar op_name) = op'
; (arg1',fv_arg1) <- rnCmdTop arg1
; (arg2',fv_arg2) <- rnCmdTop arg2
-- Deal with fixity
; fixity <- lookupFixityRn op_name
; final_e <- mkOpFormRn arg1' op' fixity arg2'
; return (final_e, fv_arg1 `plusFV` fv_op `plusFV` fv_arg2) }
rnCmd (HsCmdArrForm op fixity cmds)
= do { (op',fvOp) <- escapeArrowScope (rnLExpr op)
; (cmds',fvCmds) <- rnCmdArgs cmds
; return (HsCmdArrForm op' fixity cmds', fvOp `plusFV` fvCmds) }
rnCmd (HsCmdApp fun arg)
= do { (fun',fvFun) <- rnLCmd fun
; (arg',fvArg) <- rnLExpr arg
; return (HsCmdApp fun' arg', fvFun `plusFV` fvArg) }
rnCmd (HsCmdLam matches)
= do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLCmd matches
; return (HsCmdLam matches', fvMatch) }
rnCmd (HsCmdPar e)
= do { (e', fvs_e) <- rnLCmd e
; return (HsCmdPar e', fvs_e) }
rnCmd (HsCmdCase expr matches)
= do { (new_expr, e_fvs) <- rnLExpr expr
; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLCmd matches
; return (HsCmdCase new_expr new_matches, e_fvs `plusFV` ms_fvs) }
rnCmd (HsCmdIf _ p b1 b2)
= do { (p', fvP) <- rnLExpr p
; (b1', fvB1) <- rnLCmd b1
; (b2', fvB2) <- rnLCmd b2
; (mb_ite, fvITE) <- lookupIfThenElse
; return (HsCmdIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
rnCmd (HsCmdLet binds cmd)
= rnLocalBindsAndThen binds $ \ binds' -> do
{ (cmd',fvExpr) <- rnLCmd cmd
; return (HsCmdLet binds' cmd', fvExpr) }
rnCmd (HsCmdDo stmts _)
= do { ((stmts', _), fvs) <- rnStmts ArrowExpr rnLCmd stmts (\ _ -> return ((), emptyFVs))
; return ( HsCmdDo stmts' placeHolderType, fvs ) }
rnCmd cmd@(HsCmdCast {}) = pprPanic "rnCmd" (ppr cmd)
---------------------------------------------------
type CmdNeeds = FreeVars -- Only inhabitants are
-- appAName, choiceAName, loopAName
-- find what methods the Cmd needs (loop, choice, apply)
methodNamesLCmd :: LHsCmd Name -> CmdNeeds
methodNamesLCmd = methodNamesCmd . unLoc
methodNamesCmd :: HsCmd Name -> CmdNeeds
methodNamesCmd (HsCmdArrApp _arrow _arg _ HsFirstOrderApp _rtl)
= emptyFVs
methodNamesCmd (HsCmdArrApp _arrow _arg _ HsHigherOrderApp _rtl)
= unitFV appAName
methodNamesCmd (HsCmdArrForm {}) = emptyFVs
methodNamesCmd (HsCmdCast _ cmd) = methodNamesCmd cmd
methodNamesCmd (HsCmdPar c) = methodNamesLCmd c
methodNamesCmd (HsCmdIf _ _ c1 c2)
= methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
methodNamesCmd (HsCmdLet _ c) = methodNamesLCmd c
methodNamesCmd (HsCmdDo stmts _) = methodNamesStmts stmts
methodNamesCmd (HsCmdApp c _) = methodNamesLCmd c
methodNamesCmd (HsCmdLam match) = methodNamesMatch match
methodNamesCmd (HsCmdCase _ matches)
= methodNamesMatch matches `addOneFV` choiceAName
--methodNamesCmd _ = emptyFVs
-- Other forms can't occur in commands, but it's not convenient
-- to error here so we just do what's convenient.
-- The type checker will complain later
---------------------------------------------------
methodNamesMatch :: MatchGroup Name (LHsCmd Name) -> FreeVars
methodNamesMatch (MG { mg_alts = ms })
= plusFVs (map do_one ms)
where
do_one (L _ (Match _ _ _ grhss)) = methodNamesGRHSs grhss
-------------------------------------------------
-- gaw 2004
methodNamesGRHSs :: GRHSs Name (LHsCmd Name) -> FreeVars
methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
-------------------------------------------------
methodNamesGRHS :: Located (GRHS Name (LHsCmd Name)) -> CmdNeeds
methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
---------------------------------------------------
methodNamesStmts :: [Located (StmtLR Name Name (LHsCmd Name))] -> FreeVars
methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
---------------------------------------------------
methodNamesLStmt :: Located (StmtLR Name Name (LHsCmd Name)) -> FreeVars
methodNamesLStmt = methodNamesStmt . unLoc
methodNamesStmt :: StmtLR Name Name (LHsCmd Name) -> FreeVars
methodNamesStmt (LastStmt cmd _) = methodNamesLCmd cmd
methodNamesStmt (BodyStmt cmd _ _ _) = methodNamesLCmd cmd
methodNamesStmt (BindStmt _ cmd _ _) = methodNamesLCmd cmd
methodNamesStmt (RecStmt { recS_stmts = stmts }) = methodNamesStmts stmts `addOneFV` loopAName
methodNamesStmt (LetStmt {}) = emptyFVs
methodNamesStmt (ParStmt {}) = emptyFVs
methodNamesStmt (TransStmt {}) = emptyFVs
-- ParStmt and TransStmt can't occur in commands, but it's not convenient to error
-- here so we just do what's convenient
{-
************************************************************************
* *
Arithmetic sequences
* *
************************************************************************
-}
rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
rnArithSeq (From expr)
= do { (expr', fvExpr) <- rnLExpr expr
; return (From expr', fvExpr) }
rnArithSeq (FromThen expr1 expr2)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; return (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
rnArithSeq (FromTo expr1 expr2)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; return (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
rnArithSeq (FromThenTo expr1 expr2 expr3)
= do { (expr1', fvExpr1) <- rnLExpr expr1
; (expr2', fvExpr2) <- rnLExpr expr2
; (expr3', fvExpr3) <- rnLExpr expr3
; return (FromThenTo expr1' expr2' expr3',
plusFVs [fvExpr1, fvExpr2, fvExpr3]) }
{-
************************************************************************
* *
\subsubsection{@Stmt@s: in @do@ expressions}
* *
************************************************************************
-}
rnStmts :: Outputable (body RdrName) => HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [LStmt RdrName (Located (body RdrName))]
-> ([Name] -> RnM (thing, FreeVars))
-> RnM (([LStmt Name (Located (body Name))], thing), FreeVars)
-- Variables bound by the Stmts, and mentioned in thing_inside,
-- do not appear in the result FreeVars
rnStmts ctxt _ [] thing_inside
= do { checkEmptyStmts ctxt
; (thing, fvs) <- thing_inside []
; return (([], thing), fvs) }
rnStmts MDoExpr rnBody stmts thing_inside -- Deal with mdo
= -- Behave like do { rec { ...all but last... }; last }
do { ((stmts1, (stmts2, thing)), fvs)
<- rnStmt MDoExpr rnBody (noLoc $ mkRecStmt all_but_last) $ \ _ ->
do { last_stmt' <- checkLastStmt MDoExpr last_stmt
; rnStmt MDoExpr rnBody last_stmt' thing_inside }
; return (((stmts1 ++ stmts2), thing), fvs) }
where
Just (all_but_last, last_stmt) = snocView stmts
rnStmts ctxt rnBody (lstmt@(L loc _) : lstmts) thing_inside
| null lstmts
= setSrcSpan loc $
do { lstmt' <- checkLastStmt ctxt lstmt
; rnStmt ctxt rnBody lstmt' thing_inside }
| otherwise
= do { ((stmts1, (stmts2, thing)), fvs)
<- setSrcSpan loc $
do { checkStmt ctxt lstmt
; rnStmt ctxt rnBody lstmt $ \ bndrs1 ->
rnStmts ctxt rnBody lstmts $ \ bndrs2 ->
thing_inside (bndrs1 ++ bndrs2) }
; return (((stmts1 ++ stmts2), thing), fvs) }
----------------------
rnStmt :: Outputable (body RdrName) => HsStmtContext Name
-> (Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> LStmt RdrName (Located (body RdrName))
-> ([Name] -> RnM (thing, FreeVars))
-> RnM (([LStmt Name (Located (body Name))], thing), FreeVars)
-- Variables bound by the Stmt, and mentioned in thing_inside,
-- do not appear in the result FreeVars
rnStmt ctxt rnBody (L loc (LastStmt body _)) thing_inside
= do { (body', fv_expr) <- rnBody body
; (ret_op, fvs1) <- lookupStmtName ctxt returnMName
; (thing, fvs3) <- thing_inside []
; return (([L loc (LastStmt body' ret_op)], thing),
fv_expr `plusFV` fvs1 `plusFV` fvs3) }
rnStmt ctxt rnBody (L loc (BodyStmt body _ _ _)) thing_inside
= do { (body', fv_expr) <- rnBody body
; (then_op, fvs1) <- lookupStmtName ctxt thenMName
; (guard_op, fvs2) <- if isListCompExpr ctxt
then lookupStmtName ctxt guardMName
else return (noSyntaxExpr, emptyFVs)
-- Only list/parr/monad comprehensions use 'guard'
-- Also for sub-stmts of same eg [ e | x<-xs, gd | blah ]
-- Here "gd" is a guard
; (thing, fvs3) <- thing_inside []
; return (([L loc (BodyStmt body' then_op guard_op placeHolderType)], thing),
fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }
rnStmt ctxt rnBody (L loc (BindStmt pat body _ _)) thing_inside
= do { (body', fv_expr) <- rnBody body
-- The binders do not scope over the expression
; (bind_op, fvs1) <- lookupStmtName ctxt bindMName
; (fail_op, fvs2) <- lookupStmtName ctxt failMName
; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
{ (thing, fvs3) <- thing_inside (collectPatBinders pat')
; return (([L loc (BindStmt pat' body' bind_op fail_op)], thing),
fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
-- fv_expr shouldn't really be filtered by the rnPatsAndThen
-- but it does not matter because the names are unique
rnStmt _ _ (L loc (LetStmt binds)) thing_inside
= do { rnLocalBindsAndThen binds $ \binds' -> do
{ (thing, fvs) <- thing_inside (collectLocalBinders binds')
; return (([L loc (LetStmt binds')], thing), fvs) } }
rnStmt ctxt rnBody (L loc (RecStmt { recS_stmts = rec_stmts })) thing_inside
= do { (return_op, fvs1) <- lookupStmtName ctxt returnMName
; (mfix_op, fvs2) <- lookupStmtName ctxt mfixName
; (bind_op, fvs3) <- lookupStmtName ctxt bindMName
; let empty_rec_stmt = emptyRecStmtName { recS_ret_fn = return_op
, recS_mfix_fn = mfix_op
, recS_bind_fn = bind_op }
-- Step1: Bring all the binders of the mdo into scope
-- (Remember that this also removes the binders from the
-- finally-returned free-vars.)
-- And rename each individual stmt, making a
-- singleton segment. At this stage the FwdRefs field
-- isn't finished: it's empty for all except a BindStmt
-- for which it's the fwd refs within the bind itself
-- (This set may not be empty, because we're in a recursive
-- context.)
; rnRecStmtsAndThen rnBody rec_stmts $ \ segs -> do
{ let bndrs = nameSetElems $ foldr (unionNameSet . (\(ds,_,_,_) -> ds))
emptyNameSet segs
; (thing, fvs_later) <- thing_inside bndrs
; let (rec_stmts', fvs) = segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
; return ((rec_stmts', thing), fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }
rnStmt ctxt _ (L loc (ParStmt segs _ _)) thing_inside
= do { (mzip_op, fvs1) <- lookupStmtName ctxt mzipName
; (bind_op, fvs2) <- lookupStmtName ctxt bindMName
; (return_op, fvs3) <- lookupStmtName ctxt returnMName
; ((segs', thing), fvs4) <- rnParallelStmts (ParStmtCtxt ctxt) return_op segs thing_inside
; return ( ([L loc (ParStmt segs' mzip_op bind_op)], thing)
, fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
rnStmt ctxt _ (L loc (TransStmt { trS_stmts = stmts, trS_by = by, trS_form = form
, trS_using = using })) thing_inside
= do { -- Rename the 'using' expression in the context before the transform is begun
(using', fvs1) <- rnLExpr using
-- Rename the stmts and the 'by' expression
-- Keep track of the variables mentioned in the 'by' expression
; ((stmts', (by', used_bndrs, thing)), fvs2)
<- rnStmts (TransStmtCtxt ctxt) rnLExpr stmts $ \ bndrs ->
do { (by', fvs_by) <- mapMaybeFvRn rnLExpr by
; (thing, fvs_thing) <- thing_inside bndrs
; let fvs = fvs_by `plusFV` fvs_thing
used_bndrs = filter (`elemNameSet` fvs) bndrs
-- The paper (Fig 5) has a bug here; we must treat any free variable
-- of the "thing inside", **or of the by-expression**, as used
; return ((by', used_bndrs, thing), fvs) }
-- Lookup `return`, `(>>=)` and `liftM` for monad comprehensions
; (return_op, fvs3) <- lookupStmtName ctxt returnMName
; (bind_op, fvs4) <- lookupStmtName ctxt bindMName
; (fmap_op, fvs5) <- case form of
ThenForm -> return (noSyntaxExpr, emptyFVs)
_ -> lookupStmtName ctxt fmapName
; let all_fvs = fvs1 `plusFV` fvs2 `plusFV` fvs3
`plusFV` fvs4 `plusFV` fvs5
bndr_map = used_bndrs `zip` used_bndrs
-- See Note [TransStmt binder map] in HsExpr
; traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr bndr_map)
; return (([L loc (TransStmt { trS_stmts = stmts', trS_bndrs = bndr_map
, trS_by = by', trS_using = using', trS_form = form
, trS_ret = return_op, trS_bind = bind_op
, trS_fmap = fmap_op })], thing), all_fvs) }
rnParallelStmts :: forall thing. HsStmtContext Name
-> SyntaxExpr Name
-> [ParStmtBlock RdrName RdrName]
-> ([Name] -> RnM (thing, FreeVars))
-> RnM (([ParStmtBlock Name Name], thing), FreeVars)
-- Note [Renaming parallel Stmts]
rnParallelStmts ctxt return_op segs thing_inside
= do { orig_lcl_env <- getLocalRdrEnv
; rn_segs orig_lcl_env [] segs }
where
rn_segs :: LocalRdrEnv
-> [Name] -> [ParStmtBlock RdrName RdrName]
-> RnM (([ParStmtBlock Name Name], thing), FreeVars)
rn_segs _ bndrs_so_far []
= do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
; mapM_ dupErr dups
; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
; return (([], thing), fvs) }
rn_segs env bndrs_so_far (ParStmtBlock stmts _ _ : segs)
= do { ((stmts', (used_bndrs, segs', thing)), fvs)
<- rnStmts ctxt rnLExpr stmts $ \ bndrs ->
setLocalRdrEnv env $ do
{ ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
; let used_bndrs = filter (`elemNameSet` fvs) bndrs
; return ((used_bndrs, segs', thing), fvs) }
; let seg' = ParStmtBlock stmts' used_bndrs return_op
; return ((seg':segs', thing), fvs) }
cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
dupErr vs = addErr (ptext (sLit "Duplicate binding in parallel list comprehension for:")
<+> quotes (ppr (head vs)))
lookupStmtName :: HsStmtContext Name -> Name -> RnM (HsExpr Name, FreeVars)
-- Like lookupSyntaxName, but ListComp/PArrComp are never rebindable
-- Neither is ArrowExpr, which has its own desugarer in DsArrows
lookupStmtName ctxt n
= case ctxt of
ListComp -> not_rebindable
PArrComp -> not_rebindable
ArrowExpr -> not_rebindable
PatGuard {} -> not_rebindable
DoExpr -> rebindable
MDoExpr -> rebindable
MonadComp -> rebindable
GhciStmtCtxt -> rebindable -- I suppose?
ParStmtCtxt c -> lookupStmtName c n -- Look inside to
TransStmtCtxt c -> lookupStmtName c n -- the parent context
where
rebindable = lookupSyntaxName n
not_rebindable = return (HsVar n, emptyFVs)
{-
Note [Renaming parallel Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Renaming parallel statements is painful. Given, say
[ a+c | a <- as, bs <- bss
| c <- bs, a <- ds ]
Note that
(a) In order to report "Defined by not used" about 'bs', we must rename
each group of Stmts with a thing_inside whose FreeVars include at least {a,c}
(b) We want to report that 'a' is illegally bound in both branches
(c) The 'bs' in the second group must obviously not be captured by
the binding in the first group
To satisfy (a) we nest the segements.
To satisfy (b) we check for duplicates just before thing_inside.
To satisfy (c) we reset the LocalRdrEnv each time.
************************************************************************
* *
\subsubsection{mdo expressions}
* *
************************************************************************
-}
type FwdRefs = NameSet
type Segment stmts = (Defs,
Uses, -- May include defs
FwdRefs, -- A subset of uses that are
-- (a) used before they are bound in this segment, or
-- (b) used here, and bound in subsequent segments
stmts) -- Either Stmt or [Stmt]
-- wrapper that does both the left- and right-hand sides
rnRecStmtsAndThen :: Outputable (body RdrName) =>
(Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [LStmt RdrName (Located (body RdrName))]
-- assumes that the FreeVars returned includes
-- the FreeVars of the Segments
-> ([Segment (LStmt Name (Located (body Name)))] -> RnM (a, FreeVars))
-> RnM (a, FreeVars)
rnRecStmtsAndThen rnBody s cont
= do { -- (A) Make the mini fixity env for all of the stmts
fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
-- (B) Do the LHSes
; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
-- ...bring them and their fixities into scope
; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
-- Fake uses of variables introduced implicitly (warning suppression, see #4404)
implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
; bindLocalNamesFV bound_names $
addLocalFixities fix_env bound_names $ do
-- (C) do the right-hand-sides and thing-inside
{ segs <- rn_rec_stmts rnBody bound_names new_lhs_and_fv
; (res, fvs) <- cont segs
; warnUnusedLocalBinds bound_names (fvs `unionNameSet` implicit_uses)
; return (res, fvs) }}
-- get all the fixity decls in any Let stmt
collectRecStmtsFixities :: [LStmtLR RdrName RdrName body] -> [LFixitySig RdrName]
collectRecStmtsFixities l =
foldr (\ s -> \acc -> case s of
(L _ (LetStmt (HsValBinds (ValBindsIn _ sigs)))) ->
foldr (\ sig -> \ acc -> case sig of
(L loc (FixSig s)) -> (L loc s) : acc
_ -> acc) acc sigs
_ -> acc) [] l
-- left-hand sides
rn_rec_stmt_lhs :: Outputable body => MiniFixityEnv
-> LStmt RdrName body
-- rename LHS, and return its FVs
-- Warning: we will only need the FreeVars below in the case of a BindStmt,
-- so we don't bother to compute it accurately in the other cases
-> RnM [(LStmtLR Name RdrName body, FreeVars)]
rn_rec_stmt_lhs _ (L loc (BodyStmt body a b c))
= return [(L loc (BodyStmt body a b c), emptyFVs)]
rn_rec_stmt_lhs _ (L loc (LastStmt body a))
= return [(L loc (LastStmt body a), emptyFVs)]
rn_rec_stmt_lhs fix_env (L loc (BindStmt pat body a b))
= do
-- should the ctxt be MDo instead?
(pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat
return [(L loc (BindStmt pat' body a b),
fv_pat)]
rn_rec_stmt_lhs _ (L _ (LetStmt binds@(HsIPBinds _)))
= failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds)))
= do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
return [(L loc (LetStmt (HsValBinds binds')),
-- Warning: this is bogus; see function invariant
emptyFVs
)]
-- XXX Do we need to do something with the return and mfix names?
rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts })) -- Flatten Rec inside Rec
= rn_rec_stmts_lhs fix_env stmts
rn_rec_stmt_lhs _ stmt@(L _ (ParStmt {})) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt" (ppr stmt)
rn_rec_stmt_lhs _ stmt@(L _ (TransStmt {})) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt" (ppr stmt)
rn_rec_stmt_lhs _ (L _ (LetStmt EmptyLocalBinds))
= panic "rn_rec_stmt LetStmt EmptyLocalBinds"
rn_rec_stmts_lhs :: Outputable body => MiniFixityEnv
-> [LStmt RdrName body]
-> RnM [(LStmtLR Name RdrName body, FreeVars)]
rn_rec_stmts_lhs fix_env stmts
= do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
; let boundNames = collectLStmtsBinders (map fst ls)
-- First do error checking: we need to check for dups here because we
-- don't bind all of the variables from the Stmt at once
-- with bindLocatedLocals.
; checkDupNames boundNames
; return ls }
-- right-hand-sides
rn_rec_stmt :: (Outputable (body RdrName)) =>
(Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [Name]
-> (LStmtLR Name RdrName (Located (body RdrName)), FreeVars)
-> RnM [Segment (LStmt Name (Located (body Name)))]
-- Rename a Stmt that is inside a RecStmt (or mdo)
-- Assumes all binders are already in scope
-- Turns each stmt into a singleton Stmt
rn_rec_stmt rnBody _ (L loc (LastStmt body _), _)
= do { (body', fv_expr) <- rnBody body
; (ret_op, fvs1) <- lookupSyntaxName returnMName
; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,
L loc (LastStmt body' ret_op))] }
rn_rec_stmt rnBody _ (L loc (BodyStmt body _ _ _), _)
= do { (body', fvs) <- rnBody body
; (then_op, fvs1) <- lookupSyntaxName thenMName
; return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
L loc (BodyStmt body' then_op noSyntaxExpr placeHolderType))] }
rn_rec_stmt rnBody _ (L loc (BindStmt pat' body _ _), fv_pat)
= do { (body', fv_expr) <- rnBody body
; (bind_op, fvs1) <- lookupSyntaxName bindMName
; (fail_op, fvs2) <- lookupSyntaxName failMName
; let bndrs = mkNameSet (collectPatBinders pat')
fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
; return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
L loc (BindStmt pat' body' bind_op fail_op))] }
rn_rec_stmt _ _ (L _ (LetStmt binds@(HsIPBinds _)), _)
= failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
rn_rec_stmt _ all_bndrs (L loc (LetStmt (HsValBinds binds')), _)
= do { (binds', du_binds) <- rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
-- fixities and unused are handled above in rnRecStmtsAndThen
; return [(duDefs du_binds, allUses du_binds,
emptyNameSet, L loc (LetStmt (HsValBinds binds')))] }
-- no RecStmt case because they get flattened above when doing the LHSes
rn_rec_stmt _ _ stmt@(L _ (RecStmt {}), _)
= pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
rn_rec_stmt _ _ stmt@(L _ (ParStmt {}), _) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
rn_rec_stmt _ _ stmt@(L _ (TransStmt {}), _) -- Syntactically illegal in mdo
= pprPanic "rn_rec_stmt: TransStmt" (ppr stmt)
rn_rec_stmt _ _ (L _ (LetStmt EmptyLocalBinds), _)
= panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
rn_rec_stmts :: Outputable (body RdrName) =>
(Located (body RdrName) -> RnM (Located (body Name), FreeVars))
-> [Name]
-> [(LStmtLR Name RdrName (Located (body RdrName)), FreeVars)]
-> RnM [Segment (LStmt Name (Located (body Name)))]
rn_rec_stmts rnBody bndrs stmts
= do { segs_s <- mapM (rn_rec_stmt rnBody bndrs) stmts
; return (concat segs_s) }
---------------------------------------------
segmentRecStmts :: SrcSpan -> HsStmtContext Name
-> Stmt Name body
-> [Segment (LStmt Name body)] -> FreeVars
-> ([LStmt Name body], FreeVars)
segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
| null segs
= ([], fvs_later)
| MDoExpr <- ctxt
= segsToStmts empty_rec_stmt grouped_segs fvs_later
-- Step 4: Turn the segments into Stmts
-- Use RecStmt when and only when there are fwd refs
-- Also gather up the uses from the end towards the
-- start, so we can tell the RecStmt which things are
-- used 'after' the RecStmt
| otherwise
= ([ L loc $
empty_rec_stmt { recS_stmts = ss
, recS_later_ids = nameSetElems (defs `intersectNameSet` fvs_later)
, recS_rec_ids = nameSetElems (defs `intersectNameSet` uses) }]
, uses `plusFV` fvs_later)
where
(defs_s, uses_s, _, ss) = unzip4 segs
defs = plusFVs defs_s
uses = plusFVs uses_s
-- Step 2: Fill in the fwd refs.
-- The segments are all singletons, but their fwd-ref
-- field mentions all the things used by the segment
-- that are bound after their use
segs_w_fwd_refs = addFwdRefs segs
-- Step 3: Group together the segments to make bigger segments
-- Invariant: in the result, no segment uses a variable
-- bound in a later segment
grouped_segs = glomSegments ctxt segs_w_fwd_refs
----------------------------
addFwdRefs :: [Segment a] -> [Segment a]
-- So far the segments only have forward refs *within* the Stmt
-- (which happens for bind: x <- ...x...)
-- This function adds the cross-seg fwd ref info
addFwdRefs segs
= fst (foldr mk_seg ([], emptyNameSet) segs)
where
mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
= (new_seg : segs, all_defs)
where
new_seg = (defs, uses, new_fwds, stmts)
all_defs = later_defs `unionNameSet` defs
new_fwds = fwds `unionNameSet` (uses `intersectNameSet` later_defs)
-- Add the downstream fwd refs here
{-
Note [Segmenting mdo]
~~~~~~~~~~~~~~~~~~~~~
NB. June 7 2012: We only glom segments that appear in an explicit mdo;
and leave those found in "do rec"'s intact. See
http://ghc.haskell.org/trac/ghc/ticket/4148 for the discussion
leading to this design choice. Hence the test in segmentRecStmts.
Note [Glomming segments]
~~~~~~~~~~~~~~~~~~~~~~~~
Glomming the singleton segments of an mdo into minimal recursive groups.
At first I thought this was just strongly connected components, but
there's an important constraint: the order of the stmts must not change.
Consider
mdo { x <- ...y...
p <- z
y <- ...x...
q <- x
z <- y
r <- x }
Here, the first stmt mention 'y', which is bound in the third.
But that means that the innocent second stmt (p <- z) gets caught
up in the recursion. And that in turn means that the binding for
'z' has to be included... and so on.
Start at the tail { r <- x }
Now add the next one { z <- y ; r <- x }
Now add one more { q <- x ; z <- y ; r <- x }
Now one more... but this time we have to group a bunch into rec
{ rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
Now one more, which we can add on without a rec
{ p <- z ;
rec { y <- ...x... ; q <- x ; z <- y } ;
r <- x }
Finally we add the last one; since it mentions y we have to
glom it together with the first two groups
{ rec { x <- ...y...; p <- z ; y <- ...x... ;
q <- x ; z <- y } ;
r <- x }
-}
glomSegments :: HsStmtContext Name
-> [Segment (LStmt Name body)]
-> [Segment [LStmt Name body]] -- Each segment has a non-empty list of Stmts
-- See Note [Glomming segments]
glomSegments _ [] = []
glomSegments ctxt ((defs,uses,fwds,stmt) : segs)
-- Actually stmts will always be a singleton
= (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
where
segs' = glomSegments ctxt segs
(extras, others) = grab uses segs'
(ds, us, fs, ss) = unzip4 extras
seg_defs = plusFVs ds `plusFV` defs
seg_uses = plusFVs us `plusFV` uses
seg_fwds = plusFVs fs `plusFV` fwds
seg_stmts = stmt : concat ss
grab :: NameSet -- The client
-> [Segment a]
-> ([Segment a], -- Needed by the 'client'
[Segment a]) -- Not needed by the client
-- The result is simply a split of the input
grab uses dus
= (reverse yeses, reverse noes)
where
(noes, yeses) = span not_needed (reverse dus)
not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
----------------------------------------------------
segsToStmts :: Stmt Name body -- A RecStmt with the SyntaxOps filled in
-> [Segment [LStmt Name body]] -- Each Segment has a non-empty list of Stmts
-> FreeVars -- Free vars used 'later'
-> ([LStmt Name body], FreeVars)
segsToStmts _ [] fvs_later = ([], fvs_later)
segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later
= ASSERT( not (null ss) )
(new_stmt : later_stmts, later_uses `plusFV` uses)
where
(later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later
new_stmt | non_rec = head ss
| otherwise = L (getLoc (head ss)) rec_stmt
rec_stmt = empty_rec_stmt { recS_stmts = ss
, recS_later_ids = nameSetElems used_later
, recS_rec_ids = nameSetElems fwds }
non_rec = isSingleton ss && isEmptyNameSet fwds
used_later = defs `intersectNameSet` later_uses
-- The ones needed after the RecStmt
{-
************************************************************************
* *
\subsubsection{Errors}
* *
************************************************************************
-}
checkEmptyStmts :: HsStmtContext Name -> RnM ()
-- We've seen an empty sequence of Stmts... is that ok?
checkEmptyStmts ctxt
= unless (okEmpty ctxt) (addErr (emptyErr ctxt))
okEmpty :: HsStmtContext a -> Bool
okEmpty (PatGuard {}) = True
okEmpty _ = False
emptyErr :: HsStmtContext Name -> SDoc
emptyErr (ParStmtCtxt {}) = ptext (sLit "Empty statement group in parallel comprehension")
emptyErr (TransStmtCtxt {}) = ptext (sLit "Empty statement group preceding 'group' or 'then'")
emptyErr ctxt = ptext (sLit "Empty") <+> pprStmtContext ctxt
----------------------
checkLastStmt :: Outputable (body RdrName) => HsStmtContext Name
-> LStmt RdrName (Located (body RdrName))
-> RnM (LStmt RdrName (Located (body RdrName)))
checkLastStmt ctxt lstmt@(L loc stmt)
= case ctxt of
ListComp -> check_comp
MonadComp -> check_comp
PArrComp -> check_comp
ArrowExpr -> check_do
DoExpr -> check_do
MDoExpr -> check_do
_ -> check_other
where
check_do -- Expect BodyStmt, and change it to LastStmt
= case stmt of
BodyStmt e _ _ _ -> return (L loc (mkLastStmt e))
LastStmt {} -> return lstmt -- "Deriving" clauses may generate a
-- LastStmt directly (unlike the parser)
_ -> do { addErr (hang last_error 2 (ppr stmt)); return lstmt }
last_error = (ptext (sLit "The last statement in") <+> pprAStmtContext ctxt
<+> ptext (sLit "must be an expression"))
check_comp -- Expect LastStmt; this should be enforced by the parser!
= case stmt of
LastStmt {} -> return lstmt
_ -> pprPanic "checkLastStmt" (ppr lstmt)
check_other -- Behave just as if this wasn't the last stmt
= do { checkStmt ctxt lstmt; return lstmt }
-- Checking when a particular Stmt is ok
checkStmt :: HsStmtContext Name
-> LStmt RdrName (Located (body RdrName))
-> RnM ()
checkStmt ctxt (L _ stmt)
= do { dflags <- getDynFlags
; case okStmt dflags ctxt stmt of
IsValid -> return ()
NotValid extra -> addErr (msg $$ extra) }
where
msg = sep [ ptext (sLit "Unexpected") <+> pprStmtCat stmt <+> ptext (sLit "statement")
, ptext (sLit "in") <+> pprAStmtContext ctxt ]
pprStmtCat :: Stmt a body -> SDoc
pprStmtCat (TransStmt {}) = ptext (sLit "transform")
pprStmtCat (LastStmt {}) = ptext (sLit "return expression")
pprStmtCat (BodyStmt {}) = ptext (sLit "body")
pprStmtCat (BindStmt {}) = ptext (sLit "binding")
pprStmtCat (LetStmt {}) = ptext (sLit "let")
pprStmtCat (RecStmt {}) = ptext (sLit "rec")
pprStmtCat (ParStmt {}) = ptext (sLit "parallel")
------------
emptyInvalid :: Validity -- Payload is the empty document
emptyInvalid = NotValid Outputable.empty
okStmt, okDoStmt, okCompStmt, okParStmt, okPArrStmt
:: DynFlags -> HsStmtContext Name
-> Stmt RdrName (Located (body RdrName)) -> Validity
-- Return Nothing if OK, (Just extra) if not ok
-- The "extra" is an SDoc that is appended to an generic error message
okStmt dflags ctxt stmt
= case ctxt of
PatGuard {} -> okPatGuardStmt stmt
ParStmtCtxt ctxt -> okParStmt dflags ctxt stmt
DoExpr -> okDoStmt dflags ctxt stmt
MDoExpr -> okDoStmt dflags ctxt stmt
ArrowExpr -> okDoStmt dflags ctxt stmt
GhciStmtCtxt -> okDoStmt dflags ctxt stmt
ListComp -> okCompStmt dflags ctxt stmt
MonadComp -> okCompStmt dflags ctxt stmt
PArrComp -> okPArrStmt dflags ctxt stmt
TransStmtCtxt ctxt -> okStmt dflags ctxt stmt
-------------
okPatGuardStmt :: Stmt RdrName (Located (body RdrName)) -> Validity
okPatGuardStmt stmt
= case stmt of
BodyStmt {} -> IsValid
BindStmt {} -> IsValid
LetStmt {} -> IsValid
_ -> emptyInvalid
-------------
okParStmt dflags ctxt stmt
= case stmt of
LetStmt (HsIPBinds {}) -> emptyInvalid
_ -> okStmt dflags ctxt stmt
----------------
okDoStmt dflags ctxt stmt
= case stmt of
RecStmt {}
| Opt_RecursiveDo `xopt` dflags -> IsValid
| ArrowExpr <- ctxt -> IsValid -- Arrows allows 'rec'
| otherwise -> NotValid (ptext (sLit "Use RecursiveDo"))
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
_ -> emptyInvalid
----------------
okCompStmt dflags _ stmt
= case stmt of
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
ParStmt {}
| Opt_ParallelListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (ptext (sLit "Use ParallelListComp"))
TransStmt {}
| Opt_TransformListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (ptext (sLit "Use TransformListComp"))
RecStmt {} -> emptyInvalid
LastStmt {} -> emptyInvalid -- Should not happen (dealt with by checkLastStmt)
----------------
okPArrStmt dflags _ stmt
= case stmt of
BindStmt {} -> IsValid
LetStmt {} -> IsValid
BodyStmt {} -> IsValid
ParStmt {}
| Opt_ParallelListComp `xopt` dflags -> IsValid
| otherwise -> NotValid (ptext (sLit "Use ParallelListComp"))
TransStmt {} -> emptyInvalid
RecStmt {} -> emptyInvalid
LastStmt {} -> emptyInvalid -- Should not happen (dealt with by checkLastStmt)
---------
checkTupleSection :: [LHsTupArg RdrName] -> RnM ()
checkTupleSection args
= do { tuple_section <- xoptM Opt_TupleSections
; checkErr (all tupArgPresent args || tuple_section) msg }
where
msg = ptext (sLit "Illegal tuple section: use TupleSections")
---------
sectionErr :: HsExpr RdrName -> SDoc
sectionErr expr
= hang (ptext (sLit "A section must be enclosed in parentheses"))
2 (ptext (sLit "thus:") <+> (parens (ppr expr)))
patSynErr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
patSynErr e = do { addErr (sep [ptext (sLit "Pattern syntax in expression context:"),
nest 4 (ppr e)])
; return (EWildPat, emptyFVs) }
badIpBinds :: Outputable a => SDoc -> a -> SDoc
badIpBinds what binds
= hang (ptext (sLit "Implicit-parameter bindings illegal in") <+> what)
2 (ppr binds)
| fmthoma/ghc | compiler/rename/RnExpr.hs | bsd-3-clause | 55,827 | 6 | 22 | 16,535 | 14,476 | 7,629 | 6,847 | 840 | 11 |
module Main where
import Network.Skkserv
import Text.InputMethod.SKK
import Control.Applicative ((<$>))
import Control.Concurrent.STM (atomically, newTVarIO, readTVarIO)
import Control.Concurrent.STM (writeTVar)
import Data.String (fromString)
import qualified Data.Text.IO as T
import FRP.Ordrea
import System.Environment (getArgs)
import System.FilePath
import System.FSNotify
main :: IO ()
main = withManager $ \man -> do
[dic] <- getArgs
dic0 <- parseDic dic
tvar <- newTVarIO dic0
_ <- watchDir man (fromString $ takeDirectory dic)
((== fromString dic) . eventPath) $ const $ do
atomically . writeTVar tvar =<< parseDic dic
runSkkserv SkkservSettings { port = 1728, dicPath = dic } $ \a -> do
dicB <- externalB $ readTVarIO tvar
skkserv dicB a
parseDic :: FilePath -> IO Dictionary
parseDic fp = do
Right dic <- parseDictionary <$> T.readFile fp
return dic
| konn/hskk | examples/simplesrv.hs | bsd-3-clause | 1,003 | 0 | 16 | 264 | 312 | 165 | 147 | 27 | 1 |
module Gidl
( run
) where
import Prelude ()
import Prelude.Compat
import Data.Char
import Data.Maybe (catMaybes)
import Control.Monad (when)
import System.Console.GetOpt
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import Text.Show.Pretty
import Ivory.Artifact
import Gidl.Parse
import Gidl.Interface
import Gidl.Backend.Elm (elmBackend)
import Gidl.Backend.Haskell
import Gidl.Backend.Ivory
import Gidl.Backend.Rpc (rpcBackend)
import Gidl.Backend.Tower
data OptParser opt = OptParser [String] (opt -> opt)
instance Monoid (OptParser opt) where
mempty = OptParser [] id
OptParser as f `mappend` OptParser bs g = OptParser (as ++ bs) (f . g)
success :: (opt -> opt) -> OptParser opt
success = OptParser []
invalid :: String -> OptParser opt
invalid e = OptParser [e] id
parseOptions :: [OptDescr (OptParser opt)] -> [String]
-> Either [String] (opt -> opt)
parseOptions opts args = case getOpt Permute opts args of
(fs,[],[]) -> case mconcat fs of
OptParser [] f -> Right f
OptParser es _ -> Left es
(_,_,es) -> Left es
data Backend
= HaskellBackend
| IvoryBackend
| TowerBackend
| RpcBackend
| ElmBackend
deriving (Eq, Show)
data Opts = Opts
{ backend :: Backend
, idlpath :: FilePath
, outpath :: FilePath
, ivoryrepo :: FilePath
, towerrepo :: FilePath
, ivorytowerstm32repo :: FilePath
, packagename :: String
, namespace :: String
, debug :: Bool
, help :: Bool
}
initialOpts :: Opts
initialOpts = Opts
{ backend = error (usage ["must specify a backend"])
, idlpath = error (usage ["must specify an idl file"])
, outpath = error (usage ["must specify an output path"])
, ivoryrepo = "ivory"
, towerrepo = "tower"
, ivorytowerstm32repo = "ivory-tower-stm32"
, packagename = error (usage ["must specify a package name"])
, namespace = ""
, debug = False
, help = False
}
setBackend :: String -> OptParser Opts
setBackend b = case map toUpper b of
"HASKELL" -> success (\o -> o { backend = HaskellBackend })
"IVORY" -> success (\o -> o { backend = IvoryBackend })
"TOWER" -> success (\o -> o { backend = TowerBackend })
"HASKELL-RPC" -> success (\o -> o { backend = RpcBackend })
"ELM" -> success (\o -> o { backend = ElmBackend })
_ -> invalid e
where e = "\"" ++ b ++ "\" is not a valid backend.\n"
++ "Supported backends: haskell, ivory, tower, haskell-rpc"
setIdlPath :: String -> OptParser Opts
setIdlPath p = success (\o -> o { idlpath = p })
setOutPath :: String -> OptParser Opts
setOutPath p = success (\o -> o { outpath = p })
setIvoryRepo :: String -> OptParser Opts
setIvoryRepo p = success (\o -> o { ivoryrepo = p })
setTowerRepo :: String -> OptParser Opts
setTowerRepo p = success (\o -> o { towerrepo = p })
setIvoryTowerSTM32Repo :: String -> OptParser Opts
setIvoryTowerSTM32Repo p = success (\o -> o { ivorytowerstm32repo = p })
setPackageName :: String -> OptParser Opts
setPackageName p = success (\o -> o { packagename = p })
setNamespace :: String -> OptParser Opts
setNamespace p = success (\o -> o { namespace = p })
setDebug :: OptParser Opts
setDebug = success (\o -> o { debug = True })
setHelp :: OptParser Opts
setHelp = success (\o -> o { help = True })
options :: [OptDescr (OptParser Opts)]
options =
[ Option "b" ["backend"] (ReqArg setBackend "BACKEND")
"code generator backend"
, Option "i" ["idl"] (ReqArg setIdlPath "FILE")
"IDL file"
, Option "o" ["out"] (ReqArg setOutPath "DIR")
"root directory for output"
, Option [] ["ivory-repo"] (ReqArg setIvoryRepo "REPO")
"root of ivory.git (for Ivory and Tower backends only)"
, Option [] ["tower-repo"] (ReqArg setTowerRepo "REPO")
"root of tower.git (for Tower backend only)"
, Option [] ["ivory-tower-stm32-repo"]
(ReqArg setIvoryTowerSTM32Repo "REPO")
"root of ivory-tower-stm32.git (for Tower backend only)"
, Option "p" ["package"] (ReqArg setPackageName "NAME")
"package name for output"
, Option "n" ["namespace"] (ReqArg setNamespace "NAME")
"namespace for output"
, Option "" ["debug"] (NoArg setDebug)
"enable debugging output"
, Option "h" ["help"] (NoArg setHelp)
"display this message and exit"
]
parseOpts :: [String] -> IO Opts
parseOpts args = case parseOptions options args of
Right f -> let opts = f initialOpts in
if help opts then putStrLn (usage []) >> exitSuccess
else return opts
Left errs -> putStrLn (usage errs) >> exitFailure
usage :: [String] -> String
usage errs = usageInfo banner options
where
banner = unlines (errs ++ ["", "Usage: gidl OPTIONS"])
run :: IO ()
run = do
args <- getArgs
opts <- parseOpts args
idl <- readFile (idlpath opts)
case parseDecls idl of
Left e -> putStrLn ("Error parsing " ++ (idlpath opts) ++ ": " ++ e)
>> exitFailure
Right (te, ie) -> do
when (debug opts) $ do
putStrLn (ppShow te)
putStrLn (ppShow ie)
let InterfaceEnv ie' = ie
interfaces = map snd ie'
absolutize p name = do
pAbs <- fmap normalise $
if isRelative p
then fmap (</> p) getCurrentDirectory
else return p
ex <- doesDirectoryExist pAbs
when (not ex) $
error (usage [ "Directory \"" ++ p ++ "\" does not exist."
, "Make sure that the " ++ name
++ " repository is checked out." ])
return pAbs
b <- case backend opts of
HaskellBackend -> return haskellBackend
IvoryBackend -> do
ivoryAbs <- absolutize (ivoryrepo opts) "Ivory"
return (ivoryBackend ivoryAbs)
TowerBackend -> do
ivoryAbs <- absolutize (ivoryrepo opts) "Ivory"
towerAbs <- absolutize (towerrepo opts) "Tower"
ivoryTowerSTM32Abs <- absolutize (ivorytowerstm32repo opts)
"ivory-tower-stm32"
return (towerBackend ivoryAbs towerAbs ivoryTowerSTM32Abs)
RpcBackend -> return rpcBackend
ElmBackend -> return elmBackend
artifactBackend opts (b interfaces (packagename opts) (namespace opts))
where
artifactBackend :: Opts -> [Artifact] -> IO ()
artifactBackend opts as = do
when (debug opts) $ mapM_ printArtifact as
es <- mapM (putArtifact (outpath opts)) as
case catMaybes es of
[] -> exitSuccess
ees -> putStrLn (unlines ees) >> exitFailure
| GaloisInc/gidl | src/Gidl.hs | bsd-3-clause | 6,912 | 0 | 23 | 2,003 | 2,144 | 1,120 | 1,024 | 172 | 8 |
module TwentyFour where
import Control.Monad (guard)
import Data.Function (on)
import Data.List (groupBy, sortBy, tails, unfoldr, (\\))
import Data.Ord (comparing)
newtype Package = Package { weight :: Int }
deriving (Show, Eq, Ord)
nGroups :: Int -> [Package] -> [[[Package]]]
nGroups n pkgs = do
group1 <- bestGroups limit pkgs
otherGroups <- takeGroups (n - 1) (pkgs \\ group1)
let groups = group1 : otherGroups in do
guard (length pkgs == length (concat groups))
return groups
where
limit = totalWeight pkgs `div` n
takeGroups 0 _ = return []
takeGroups i ps = do
g <- groupsOfWeight limit ps
(g:) <$> takeGroups (i-1) (ps \\ g)
bestGroups :: Int -> [Package] -> [[Package]]
bestGroups limit pkgs = concatMap (sortBy (comparing entanglement)) $ groupBy ((==) `on` length) $ groupsOfWeight limit pkgs
-- Unlike Data.List.subsequences, this returns subsequences in increasing length order
subsequences :: [a] -> [[a]]
subsequences xs = concat $ unfoldr f [([], xs)]
where
f :: [([a], [a])] -> Maybe ([[a]], [([a], [a])])
f lasts = if null nexts then Nothing
else Just (map fst nexts, nexts)
where nexts = [ (soFar ++ [nxt], rest) | (soFar, remaining) <- lasts, (nxt, rest) <- splits remaining ]
splits ys = zip ys (drop 1 $ tails ys)
groupsOfWeight :: Int -> [Package] -> [[Package]]
groupsOfWeight limit packages = filter ((limit ==) . totalWeight) $ subsequences packages
weights :: [Package] -> [Int]
weights = map weight
totalWeight :: [Package] -> Int
totalWeight = sum . weights
entanglement :: [Package] -> Int
entanglement = product . weights
packagesFrom :: FilePath -> IO [Package]
packagesFrom file = do
text <- readFile file
return $ Package . read <$> lines text
twentyFour :: IO (Int, Int)
twentyFour = do
pkgs <- packagesFrom "input/24.txt"
return (answer 3 pkgs,
answer 4 pkgs)
where answer n = entanglement . head . head . nGroups n
| purcell/adventofcodeteam | app/TwentyFour.hs | bsd-3-clause | 2,029 | 0 | 16 | 484 | 826 | 444 | 382 | 46 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Files.State where
import Control.Exception
import Data.Aeson
import Data.Monoid ((<>))
import Data.Text (Text)
import GHC.Generics
instance ToJSON SomeException where
toJSON e = toJSON $ show e
toEncoding e = toEncoding $ show e
data DownloadResult = DownloadResult {
filePath :: String,
result :: ResultEnum
} deriving (Generic)
instance ToJSON DownloadResult
data ResultEnum = Succeed | Exists | Failed SomeException deriving (Generic)
instance ToJSON ResultEnum where
toJSON Succeed = object ["code" .= ("succeed" :: Text)]
toJSON Exists = object ["code" .= ("exists" :: Text)]
toJSON (Failed ex) = object [
"code" .= ("failed" :: Text),
"diagnose" .= toJSON ex ]
toEncoding = genericToEncoding defaultOptions
instance Show ResultEnum where
show Succeed = "was successfully written."
show Exists = "was already there."
show (Failed ex) = "failed to write with exception " ++ show ex
instance Show DownloadResult where
show DownloadResult{..} =
"Entry " ++ filePath ++ " " ++ show result
singleExState, singleSuState :: FilePath -> DownloadResult
singleExState path = DownloadResult path Exists
singleSuState path = DownloadResult path Succeed
singleFaStateWith :: FilePath -> SomeException -> DownloadResult
singleFaStateWith path ex = DownloadResult path (Failed ex)
data DownloadSummary = DownloadSummary {
existN :: Int,
succeedN :: Int,
failedN :: Int,
failureSample :: [SomeException]
}
instance ToJSON DownloadSummary where
toJSON DownloadSummary {..} =
object ["exist" .= existN, "succeed" .= succeedN
, "failed" .= failedN
, "exception" .= failureSample
]
toEncoding DownloadSummary {..} =
pairs ("exist" .= existN <> "succeed" .= succeedN
<> "failed" .= failedN
<> "exception" .= failureSample
)
instance Show DownloadSummary where
show (DownloadSummary 0 0 0 _) = "No files to download."
show (DownloadSummary _ 0 0 _) = "All file exists; no change applied."
show (DownloadSummary 0 _ 0 _) = "Successfully downloaded all files."
show (DownloadSummary 0 0 _ _) = "All downloads failed."
show (DownloadSummary e s f r) = succ' ++ fail' ++ exist where
succ' = "Successfully downloaded " ++ show s ++ " files."
fail' = if f /= 0 then "\n" ++ show f ++
" files failed when downloading; faliure reasons include" ++ show r
else ""
exist = if e /= 0 then "\n" ++ show e ++ " files were already there; no change applied." else ""
instance Monoid DownloadSummary where
mempty = DownloadSummary 0 0 0 []
mappend state1 state2 = DownloadSummary {
existN = existN state1 + existN state2,
succeedN = succeedN state1 + succeedN state2,
failedN = failedN state1 + failedN state2,
failureSample = failureSample state2 ++ failureSample state1
}
summarize :: DownloadResult -> DownloadSummary
summarize (DownloadResult path Succeed) = DownloadSummary 0 1 0 []
summarize (DownloadResult path Exists) = DownloadSummary 1 0 0 []
summarize (DownloadResult path (Failed reason)) = DownloadSummary 0 1 0 [reason]
| Evan-Zhao/FastCanvas | src/Files/State.hs | bsd-3-clause | 3,458 | 0 | 14 | 910 | 929 | 485 | 444 | 73 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Kafka.Specs.Kafka.EndToEnd.KeepAliveProducerSpecs where
import Control.Concurrent.MVar
import Network.Kafka.Producer
import Network.Kafka.Producer.KeepAlive
import Network.Kafka.Types
import Network.Kafka.Specs.IntegrationHelper
import System.IO
import System.Timeout
import Test.Hspec.Monadic
import Test.Hspec.HUnit()
keepAliveProducerProduces :: Spec
keepAliveProducerProduces = it "keep alive producer produces" $ do
let stream = Stream (Topic "keepAliveProducerProduces") (Partition 0)
(testProducer, testConsumer) = coupledProducerConsumer stream
message = Message "keepAliveProducerProduces"
result <- newEmptyMVar
p <- keepAliveProducer testProducer
produce p [message]
recordMatching testConsumer message result
waitFor result message (killSocket' p)
keepAliveProducerReconnects :: Spec
keepAliveProducerReconnects = it "reconnects after the socket is closed" $ do
let stream = Stream (Topic "keep_alive_producer_reconnects_to_closed_sockets") (Partition 0)
message = Message "keep_alive_producer_should_receive_this_after_closing_socket"
(testProducer, testConsumer) = coupledProducerConsumer stream
result <- newEmptyMVar
p <- keepAliveProducer testProducer
killSocket' p
recordMatching testConsumer message result
produce p [message]
waitFor result message (killSocket' p)
killSocket' :: KeepAliveProducer -> IO ()
killSocket' p = do
r <- timeout 100000 $ takeMVar (kapSocket p)
case r of
(Just h) -> do
hClose h
putMVar (kapSocket p) h
Nothing -> error "timed out whilst trying to kill the socket"
| tcrayford/hafka | Network/Kafka/Specs/Kafka/EndToEnd/KeepAliveProducerSpecs.hs | bsd-3-clause | 1,713 | 0 | 14 | 319 | 407 | 203 | 204 | 40 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-|
Module : Idris.ASTUtils
Description : This implements just a few basic lens-like concepts to ease state updates. Similar to fclabels in approach, just without the extra dependency.
Copyright :
License : BSD3
Maintainer : The Idris Community.
This implements just a few basic lens-like concepts to ease state updates.
Similar to fclabels in approach, just without the extra dependency.
We don't include an explicit export list
because everything here is meant to be exported.
Short synopsis:
---------------
@
f :: Idris ()
f = do
-- these two steps:
detaggable <- fgetState (opt_detaggable . ist_optimisation typeName)
fputState (opt_detaggable . ist_optimisation typeName) (not detaggable)
-- are equivalent to:
fmodifyState (opt_detaggable . ist_optimisation typeName) not
-- of course, the long accessor can be put in a variable;
-- everything is first-class
let detag n = opt_detaggable . ist_optimisation n
fputState (detag n1) True
fputState (detag n2) False
-- Note that all these operations handle missing items consistently
-- and transparently, as prescribed by the default values included
-- in the definitions of the ist_* functions.
--
-- Especially, it's no longer necessary to have initial values of
-- data structures copied (possibly inconsistently) all over the compiler.
@
-}
module Idris.ASTUtils(
Field(), cg_usedpos, ctxt_lookup, fgetState, fmodifyState
, fputState, idris_fixities, ist_callgraph, ist_optimisation
, known_interfaces, known_terms, opt_detaggable, opt_inaccessible
, opt_forceable, opts_idrisCmdline, repl_definitions
) where
import Idris.AbsSyntaxTree
import Idris.Core.Evaluate
import Idris.Core.TT
import Idris.Options
import Prelude hiding (id, (.))
import Control.Category
import Control.Monad.State.Class
import Data.Maybe
data Field rec fld = Field
{ fget :: rec -> fld
, fset :: fld -> rec -> rec
}
fmodify :: Field rec fld -> (fld -> fld) -> rec -> rec
fmodify field f x = fset field (f $ fget field x) x
instance Category Field where
id = Field id const
Field g2 s2 . Field g1 s1 = Field (g2 . g1) (\v2 x1 -> s1 (s2 v2 $ g1 x1) x1)
fgetState :: MonadState s m => Field s a -> m a
fgetState field = gets $ fget field
fputState :: MonadState s m => Field s a -> a -> m ()
fputState field x = fmodifyState field (const x)
fmodifyState :: MonadState s m => Field s a -> (a -> a) -> m ()
fmodifyState field f = modify $ fmodify field f
-- | Exact-name context lookup; uses Nothing for deleted values
-- (read+write!).
--
-- Reading a non-existing value yields Nothing,
-- writing Nothing deletes the value (if it existed).
ctxt_lookup :: Name -> Field (Ctxt a) (Maybe a)
ctxt_lookup n = Field
{ fget = lookupCtxtExact n
, fset = \newVal -> case newVal of
Just x -> addDef n x
Nothing -> deleteDefExact n
}
-- Maybe-lens with a default value.
maybe_default :: a -> Field (Maybe a) a
maybe_default dflt = Field (fromMaybe dflt) (const . Just)
-----------------------------------
-- Individual records and fields --
-----------------------------------
--
-- These could probably be generated; let's use lazy addition for now.
--
-- OptInfo
----------
-- | the optimisation record for the given (exact) name
ist_optimisation :: Name -> Field IState OptInfo
ist_optimisation n =
maybe_default Optimise
{ inaccessible = []
, detaggable = False
, forceable = []
}
. ctxt_lookup n
. Field idris_optimisation (\v ist -> ist{ idris_optimisation = v })
-- | two fields of the optimisation record
opt_inaccessible :: Field OptInfo [(Int, Name)]
opt_inaccessible = Field inaccessible (\v opt -> opt{ inaccessible = v })
opt_detaggable :: Field OptInfo Bool
opt_detaggable = Field detaggable (\v opt -> opt{ detaggable = v })
opt_forceable :: Field OptInfo [Int]
opt_forceable = Field forceable (\v opt -> opt{ forceable = v })
-- | callgraph record for the given (exact) name
ist_callgraph :: Name -> Field IState CGInfo
ist_callgraph n =
maybe_default CGInfo
{ calls = [], allCalls = Nothing, scg = [], usedpos = []
}
. ctxt_lookup n
. Field idris_callgraph (\v ist -> ist{ idris_callgraph = v })
cg_usedpos :: Field CGInfo [(Int, [UsageReason])]
cg_usedpos = Field usedpos (\v cg -> cg{ usedpos = v })
-- | Commandline flags
opts_idrisCmdline :: Field IState [Opt]
opts_idrisCmdline =
Field opt_cmdline (\v opts -> opts{ opt_cmdline = v })
. Field idris_options (\v ist -> ist{ idris_options = v })
-- | TT Context
--
-- This has a terrible name, but I'm not sure of a better one that
-- isn't confusingly close to tt_ctxt
known_terms :: Field IState (Ctxt (Def, RigCount, Injectivity, Accessibility, Totality, MetaInformation))
known_terms = Field (definitions . tt_ctxt)
(\v state -> state {tt_ctxt = (tt_ctxt state) {definitions = v}})
known_interfaces :: Field IState (Ctxt InterfaceInfo)
known_interfaces = Field idris_interfaces (\v state -> state {idris_interfaces = idris_interfaces state})
-- | Names defined at the repl
repl_definitions :: Field IState [Name]
repl_definitions = Field idris_repl_defs (\v state -> state {idris_repl_defs = v})
-- | Fixity declarations in an IState
idris_fixities :: Field IState [FixDecl]
idris_fixities = Field idris_infixes (\v state -> state {idris_infixes = v})
| uuhan/Idris-dev | src/Idris/ASTUtils.hs | bsd-3-clause | 5,476 | 0 | 12 | 1,120 | 1,223 | 678 | 545 | 74 | 2 |
module Examples.Example6 where
import Examples.Utils(testC)
import Graphics.UI.VE
import ErrVal
data Variant = VString String
| VNumber Double
| VArray [Variant]
| VNUll
deriving (Show)
instance HasVE Variant
where
mkVE = mapVE (eVal.toVariant) fromVariant
( label "string" mkVE
.+. label "number" mkVE
.+. label "array" (ListVE show mkVE)
.+. label "null" NullVE
)
where
toVariant :: Either String (Either Double (Either [Variant] ())) -> Variant
toVariant = either VString
$ either VNumber
$ either VArray
(const VNUll)
fromVariant :: Variant -> Either String (Either Double (Either [Variant] ()))
fromVariant (VString v) = Left v
fromVariant (VNumber v) = Right (Left v)
fromVariant (VArray v) = Right (Right (Left v))
fromVariant VNUll = Right (Right (Right ()))
test = testC (mkVE :: VE ConstE Variant) | timbod7/veditor | demo/Examples/Example6.hs | bsd-3-clause | 1,049 | 0 | 14 | 364 | 340 | 174 | 166 | 26 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Network.IRC.ByteString.Parser
(
-- |IRC message types
ServerName, IRCMsg(..), UserInfo(..)
-- |Conversion functions
, toIRCMsg, fromIRCMsg
-- |Attoparsec parser
, ircLine
) where
import Data.Attoparsec.Char8 as Char8
import qualified Data.Attoparsec.ByteString as Word8
import Data.ByteString.Char8 as BS
(cons, append, intercalate, ByteString, concat)
import Data.Maybe (fromMaybe)
import Data.Char (isNumber, isAlpha)
import Control.Applicative
import Prelude hiding (takeWhile)
import Network.IRC.ByteString.Config
import Network.IRC.ByteString.Utils
--Types--
type ServerName = ByteString
data IRCMsg = IRCMsg { msgPrefix :: Maybe (Either UserInfo ServerName)
, msgCmd :: ByteString
, msgParams :: [ByteString]
, msgTrail :: Maybe ByteString
}
deriving (Show, Eq, Read)
data UserInfo = UserInfo { userNick :: ByteString
, userName :: Maybe ByteString
, userHost :: Maybe ByteString
}
deriving (Eq, Show, Read)
fromIRCMsg :: IRCMsg -> ByteString
fromIRCMsg msg = BS.concat $ [prefix', command', params', trail', "\r\n"]
where prefix' = case msgPrefix msg of
Nothing -> ""
Just (Right serv) -> ':' `cons` serv `append` " "
Just (Left info) -> ':' `cons` userNick info
`append` maybeUser
`append` maybeHost
`append` " "
where
maybeUser = maybe "" ('!' `cons`) (userName info)
maybeHost = maybe "" ('@' `cons`) (userHost info)
command' = msgCmd msg
paramList = msgParams msg
params'
| Prelude.null paramList = ""
| otherwise = ' ' `cons` intercalate " " (msgParams msg)
trail' = case msgTrail msg of
Nothing -> ""
Just t -> " :" `append` t
toIRCMsg :: IRCParserConfig -> ByteString -> Result IRCMsg
toIRCMsg = parse . ircLine
-- |zero or more spaces as defined by 'isSpace'
ircSpaces c = skipWhile (isIRCSpace c) <?> "optional space"
-- |one or more spaces as defined by 'isSpace'
ircSpaces1 c = satisfy (isIRCSpace c)
>> skipWhile (isIRCSpace c)
<?> "required space"
ircLine conf = IRCMsg <$> optional (prefix conf) <*> command <*> params conf <*> trail conf <* optional (string "\r\n")
<?> "IRC line"
prefix conf = char ':'
*> eitherP (userInfo <* end) (serverName <* end)
<?> "prefix"
where
end = ircSpaces1 conf <|> endOfInput
nick = nickParser conf <?> "nick"
user = userParser conf <?> "user"
host = hostParser conf <?> "host"
serverName = host <?> "server name"
userInfo = UserInfo <$> nick
<*> optional (char '!' >> user)
<*> optional (char '@' >> host)
<?> "user info"
command = (alpha <|> numeric) <?> "command name"
where
alpha = takeWhile1 isAlpha
numeric = n <:> n <:> n <:> pure ""
where n = satisfy isNumber
params conf = fromMaybe [] <$> optional
(ircSpaces1 conf >> paramParser conf `sepBy` ircSpaces1 conf)
<?> "params list"
trail conf = ircSpaces conf
>> optional (char ':' >> Word8.takeWhile (not . isEndOfLine))
<?> "message body"
| kallisti-dev/irc-bytestring | src/Network/IRC/ByteString/Parser.hs | bsd-3-clause | 3,731 | 0 | 14 | 1,324 | 950 | 518 | 432 | 76 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
module SMACCMPilot.GCS.Gateway.Serial
( serialServer
) where
import Data.Word
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Control.Concurrent
import Control.Concurrent.Async
import Control.Monad
import qualified System.Hardware.Serialport as SP
import SMACCMPilot.GCS.Gateway.Opts
import SMACCMPilot.GCS.Gateway.Queue
import SMACCMPilot.GCS.Gateway.Monad
import SMACCMPilot.GCS.Gateway.Console
import SMACCMPilot.GCS.Gateway.Async
serialServer :: Options
-> Console
-> QueueOutput Word8
-> QueueInput ByteString
-> IO ()
serialServer opts console toser fromser =
void $ forkIO $ SP.withSerial port settings $ server console toser fromser
where
settings = SP.defaultSerialSettings { SP.commSpeed = serBaud opts }
port = serPort opts
server consle outp inp serialport = do
consoleLog consle "Connected to serial client"
SP.flush serialport
a1 <- asyncRunGW consle "serial input" $ forever $ do
bs <- lift $ SP.recv serialport 2048
mapM_ (queuePushGW outp) (B.unpack bs)
a2 <- asyncRunGW consle "serial output" $ forever $
queuePopGW inp >>= lift . (SP.send serialport)
mapM_ wait [a1, a2]
consoleLog consle "Disconnecting from serial client"
| GaloisInc/smaccmpilot-gcs-gateway | SMACCMPilot/GCS/Gateway/Serial.hs | bsd-3-clause | 1,385 | 0 | 16 | 322 | 350 | 185 | 165 | 34 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PostfixOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
--------------------------------------------------------------------------------
-- Camera VM test.
--
-- (c) 2015 Galois, Inc.
--
--------------------------------------------------------------------------------
module Main where
import Ivory.Language
import Ivory.Tower
import Tower.AADL
import Tower.Odroid.CameraVM
--------------------------------------------------------------------------------
testCameraVM :: Tower e ()
testCameraVM = do
towerModule towerDepModule
towerDepends towerDepModule
reboot_chan <- channel
rx <- cameraVMTower (snd reboot_chan :: ChanOutput ('Stored IBool))
monitor "receiverMonitor" $
handler rx "receiver" $
callback $ \msg -> do
call_ printf "left %u\n" =<< deref (msg ~> bbox_l)
call_ printf "right %u\n" =<< deref (msg ~> bbox_r)
call_ printf "top %u\n" =<< deref (msg ~> bbox_t)
call_ printf "bottom %u\n" =<< deref (msg ~> bbox_b)
--------------------------------------------------------------------------------
-- Compiler
main :: IO ()
main = compileTowerAADL id p testCameraVM
where
p _ = return cameraVMConfig
--------------------------------------------------------------------------------
-- Helpers
[ivory|
import (stdio.h, printf) void printf(string x, uint16_t y)
|]
towerDepModule :: Module
towerDepModule = package "towerDeps" $ do
incl printf
| GaloisInc/tower-camkes-odroid | test/camera_vm/CameraVMTest.hs | bsd-3-clause | 1,696 | 0 | 14 | 253 | 293 | 153 | 140 | 35 | 1 |
module Data.TTask.Types.Part
( projectsAllStory
, stWait
, stRunning
, stFinished
, stNotAchieved
, stRejected
, getLastStatus'
, statusToList'
) where
import Control.Lens
import Data.Maybe
import Data.TTask.Types.Types
projectsAllStory :: Project -> [UserStory]
projectsAllStory p = concat
[ concatMap _sprintStorys $ _projectSprints p , _projectBacklog $ p ]
----
stWait :: TStatusRecord -> Bool
stWait (StatusWait _) = True
stWait _ = False
stRunning :: TStatusRecord -> Bool
stRunning (StatusRunning _) = True
stRunning _ = False
stFinished :: TStatusRecord -> Bool
stFinished (StatusFinished _) = True
stFinished _ = False
stNotAchieved :: TStatusRecord -> Bool
stNotAchieved (StatusNotAchieved _) = True
stNotAchieved _ = False
stRejected :: TStatusRecord -> Bool
stRejected (StatusReject _) = True
stRejected _ = False
getLastStatus' :: TStatus -> TStatusRecord
getLastStatus' (TStatusOne x) = x
getLastStatus' (TStatusCons x _) = x
statusToList' :: TStatus -> [TStatusRecord]
statusToList' (TStatusOne x) = [x]
statusToList' (TStatusCons x xs) = x : statusToList' xs
| tokiwoousaka/ttask | src/Data/TTask/Types/Part.hs | bsd-3-clause | 1,113 | 0 | 8 | 190 | 341 | 184 | 157 | 36 | 1 |
-----------------------------------------------------------------------------
-- |
-- License : BSD-3-Clause
-- Maintainer : Oleg Grenrus <[email protected]>
--
-- The Github Search API, as described at
-- <http://developer.github.com/v3/search/>.
module GitHub.Endpoints.Search(
searchReposR,
searchCodeR,
searchIssuesR,
module GitHub.Data,
) where
import GitHub.Data
import GitHub.Internal.Prelude
import Prelude ()
import qualified Data.Text.Encoding as TE
-- | Search repositories.
-- See <https://developer.github.com/v3/search/#search-repositories>
searchReposR :: Text -> Request k (SearchResult Repo)
searchReposR searchString =
query ["search", "repositories"] [("q", Just $ TE.encodeUtf8 searchString)]
-- | Search code.
-- See <https://developer.github.com/v3/search/#search-code>
searchCodeR :: Text -> Request k (SearchResult Code)
searchCodeR searchString =
query ["search", "code"] [("q", Just $ TE.encodeUtf8 searchString)]
-- | Search issues.
-- See <https://developer.github.com/v3/search/#search-issues>
searchIssuesR :: Text -> Request k (SearchResult Issue)
searchIssuesR searchString =
query ["search", "issues"] [("q", Just $ TE.encodeUtf8 searchString)]
| jwiegley/github | src/GitHub/Endpoints/Search.hs | bsd-3-clause | 1,224 | 0 | 10 | 167 | 235 | 138 | 97 | 18 | 1 |
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, FlexibleInstances, UndecidableInstances #-}
module Sync.Base.Types (
Repo(..), Change(..), Action(..), Merged(..), Diff, Patch, Merge,
RepoItem(..)
) where
import Data.Map (Map)
import qualified Data.Map as M
-- | Named items
newtype Repo k a = Repo { repoItems ∷ Map k a } deriving (Eq, Ord, Functor, Traversable, Foldable)
-- | Change between repos
data Change a = ChangeLeft a | ChangeRight a | ChangeBoth a a deriving (Eq, Ord, Functor)
-- | Action on item
data Action a = Create a | Update a a | Delete a deriving (Eq, Ord, Functor)
-- | Merged or conflicted
data Merged a = Merged (Action a) | Conflict (Action a) (Action a) deriving (Eq, Ord, Functor)
-- | Diff is repo if changes
type Diff k a = Repo k (Change a)
-- | Patch is repo of actions
type Patch k a = Repo k (Action a)
-- | Merge state
type Merge k a = Repo k (Merged a)
instance Show a ⇒ Show (Change a) where
show (ChangeLeft v) = "⇐ " ++ show v
show (ChangeRight v) = "⇒ " ++ show v
show (ChangeBoth l r) = "⇔ " ++ show l ++ " " ++ show r
instance Show a ⇒ Show (Action a) where
show (Create v) = "+ " ++ show v
show (Update v v') = "* " ++ show v ++ " -> " ++ show v'
show (Delete v) = "- " ++ show v
instance Show a ⇒ Show (Merged a) where
show (Merged v) = "✓ " ++ show v
show (Conflict l r) = "✗ " ++ show l ++ " ≠ " ++ show r
-- | Used for printing items
data RepoItem k a = RepoItem k a deriving (Eq, Ord)
instance Show k ⇒ Show (RepoItem k (Change a)) where
show (RepoItem name (ChangeLeft _)) = "⇐ " ++ show name
show (RepoItem name (ChangeRight _)) = "⇒ " ++ show name
show (RepoItem name (ChangeBoth _ _)) = "⇔ " ++ show name
instance Show k ⇒ Show (RepoItem k (Action a)) where
show (RepoItem name (Create _)) = "✓ " ++ show name
show (RepoItem name (Update _ _)) = "✓ " ++ show name
show (RepoItem name (Delete _)) = "✗ " ++ show name
instance Show k ⇒ Show (RepoItem k (Merged a)) where
show (RepoItem name (Merged _)) = "✓ " ++ show name
show (RepoItem name (Conflict _ _)) = "✗ " ++ show name
instance {-# OVERLAPPABLE #-} Show k ⇒ Show (RepoItem k a) where
show (RepoItem name _) = show name
instance Show (RepoItem k a) ⇒ Show (Repo k a) where
show (Repo r) = unlines $ do
(k, v) ← M.toList r
return $ show $ RepoItem k v
| mvoidex/hsync | src/Sync/Base/Types.hs | bsd-3-clause | 2,359 | 6 | 11 | 507 | 1,055 | 548 | 507 | -1 | -1 |
{-# LINE 1 "GHC.StaticPtr.hs" #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.StaticPtr
-- Copyright : (C) 2014 I/O Tweag
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Symbolic references to values.
--
-- References to values are usually implemented with memory addresses, and this
-- is practical when communicating values between the different pieces of a
-- single process.
--
-- When values are communicated across different processes running in possibly
-- different machines, though, addresses are no longer useful since each
-- process may use different addresses to store a given value.
--
-- To solve such concern, the references provided by this module offer a key
-- that can be used to locate the values on each process. Each process maintains
-- a global table of references which can be looked up with a given key. This
-- table is known as the Static Pointer Table. The reference can then be
-- dereferenced to obtain the value.
--
-----------------------------------------------------------------------------
module GHC.StaticPtr
( StaticPtr
, deRefStaticPtr
, StaticKey
, staticKey
, unsafeLookupStaticPtr
, StaticPtrInfo(..)
, staticPtrInfo
, staticPtrKeys
, IsStatic(..)
) where
import Foreign.C.Types (CInt(..))
import Foreign.Marshal (allocaArray, peekArray, withArray)
import Foreign.Ptr (castPtr)
import GHC.Exts (addrToAny#)
import GHC.Ptr (Ptr(..), nullPtr)
import GHC.Fingerprint (Fingerprint(..))
-- | A reference to a value of type 'a'.
data StaticPtr a = StaticPtr StaticKey StaticPtrInfo a
-- | Dereferences a static pointer.
deRefStaticPtr :: StaticPtr a -> a
deRefStaticPtr (StaticPtr _ _ v) = v
-- | A key for `StaticPtrs` that can be serialized and used with
-- 'unsafeLookupStaticPtr'.
type StaticKey = Fingerprint
-- | The 'StaticKey' that can be used to look up the given 'StaticPtr'.
staticKey :: StaticPtr a -> StaticKey
staticKey (StaticPtr k _ _) = k
-- | Looks up a 'StaticPtr' by its 'StaticKey'.
--
-- If the 'StaticPtr' is not found returns @Nothing@.
--
-- This function is unsafe because the program behavior is undefined if the type
-- of the returned 'StaticPtr' does not match the expected one.
--
unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a))
unsafeLookupStaticPtr (Fingerprint w1 w2) = do
ptr@(Ptr addr) <- withArray [w1,w2] (hs_spt_lookup . castPtr)
if (ptr == nullPtr)
then return Nothing
else case addrToAny# addr of
(# spe #) -> return (Just spe)
foreign import ccall unsafe hs_spt_lookup :: Ptr () -> IO (Ptr a)
-- | A class for things buildable from static pointers.
class IsStatic p where
fromStaticPtr :: StaticPtr a -> p a
instance IsStatic StaticPtr where
fromStaticPtr = id
-- | Miscelaneous information available for debugging purposes.
data StaticPtrInfo = StaticPtrInfo
{ -- | Package key of the package where the static pointer is defined
spInfoUnitId :: String
-- | Name of the module where the static pointer is defined
, spInfoModuleName :: String
-- | An internal name that is distinct for every static pointer defined in
-- a given module.
, spInfoName :: String
-- | Source location of the definition of the static pointer as a
-- @(Line, Column)@ pair.
, spInfoSrcLoc :: (Int, Int)
}
deriving (Show)
-- | 'StaticPtrInfo' of the given 'StaticPtr'.
staticPtrInfo :: StaticPtr a -> StaticPtrInfo
staticPtrInfo (StaticPtr _ n _) = n
-- | A list of all known keys.
staticPtrKeys :: IO [StaticKey]
staticPtrKeys = do
keyCount <- hs_spt_key_count
allocaArray (fromIntegral keyCount) $ \p -> do
count <- hs_spt_keys p keyCount
peekArray (fromIntegral count) p >>=
mapM (\pa -> peekArray 2 pa >>= \[w1, w2] -> return $ Fingerprint w1 w2)
{-# NOINLINE staticPtrKeys #-}
foreign import ccall unsafe hs_spt_key_count :: IO CInt
foreign import ccall unsafe hs_spt_keys :: Ptr a -> CInt -> IO CInt
| phischu/fragnix | builtins/base/GHC.StaticPtr.hs | bsd-3-clause | 4,300 | 0 | 18 | 886 | 676 | 391 | 285 | 55 | 2 |
{-# Language RebindableSyntax #-}
{-# Language TypeOperators #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
module PingMulti00 where
import Prelude hiding ((>>=), (>>), fail, return)
import Symmetry.Language
import Symmetry.Verify
pingServer :: (DSL repr) => repr (Pid RSing -> Process repr ())
pingServer = lam $ \p -> do send p tt
master :: (DSL repr) => repr (RMulti -> Int -> Process repr ())
master = lam $ \r -> lam $ \n ->
do myPid <- self
ps <- spawnMany r n (app pingServer myPid)
doMany "loop_0" ps (lam $ \_ -> do (_ :: repr ()) <- recv
return tt)
return tt
mainProc :: (DSL repr) => repr (Int -> ())
mainProc = lam $ \n -> exec $ do r <- newRMulti
app (app master r) n
main :: IO ()
main = checkerMain (arb |> mainProc)
| gokhankici/symmetry | checker/tests/pos/PingMultiBaby00.hs | mit | 995 | 0 | 21 | 255 | 331 | 175 | 156 | 25 | 1 |
{--------------------------------------------------------------------------------
Author: Daan Leijen
Demo that shows how one can manipulate pixels directly in an image
to do fast customized drawing.
--------------------------------------------------------------------------------}
module Main where
import Graphics.UI.WXCore
import Graphics.UI.WX
rgbSize :: Size2D Int
rgbSize = sz 256 256
main :: IO ()
main
= start gui
gui :: IO ()
gui
= do im <- imageCreateSized rgbSize
withPixelBuffer im fillGreenBlue
bm <- bitmapCreateFromImage im (-1)
f <- frame [text := "Paint demo", fullRepaintOnResize := False]
sw <- scrolledWindow f [on paintRaw := onpaint bm
,virtualSize := rgbSize, scrollRate := sz 10 10
,fullRepaintOnResize := False ]
set f [layout := fill $ widget sw
,clientSize := sz 200 200
,on closing := do bitmapDelete bm
imageDelete im
propagateEvent
]
return ()
where
onpaint :: Bitmap () -> DC b -> Rect -> [Rect] -> IO ()
onpaint bm dc _viewArea _dirtyAreas
= do drawBitmap dc bm pointZero True []
fillGreenBlue pb
= mapM_ (drawGreenBlue pb) [Point x y | x <- [0..255], y <- [0..255]]
drawGreenBlue pb point_
= pixelBufferSetPixel pb point_ (colorRGB 0 (pointX point_) (pointY point_))
| jacekszymanski/wxHaskell | samples/contrib/PaintDirect.hs | lgpl-2.1 | 1,494 | 0 | 12 | 472 | 406 | 198 | 208 | 30 | 1 |
module Main where
import qualified Network.Hackage.CabalInstall.Main as CabalInstall
main :: IO ()
main = CabalInstall.main
| FranklinChen/hugs98-plus-Sep2006 | packages/Cabal/cabal-install/CabalInstall.hs | bsd-3-clause | 126 | 0 | 6 | 17 | 31 | 20 | 11 | 4 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Editor
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The top level editor state, and operations on it. This is inside an
-- internal module for easy re-export with Yi.Types bits.
module Yi.Editor ( Editor(..), EditorM, MonadEditor(..)
, runEditor
, acceptedInputsOtherWindow
, addJumpAtE
, addJumpHereE
, alternateBufferE
, askConfigVariableA
, bufferSet
, buffersA
, closeBufferAndWindowE
, closeBufferE
, closeOtherE
, clrStatus
, commonNamePrefix
, currentBuffer
, currentRegexA
, currentWindowA
, deleteBuffer
, deleteTabE
, emptyEditor
, findBuffer
, findBufferWith
, findBufferWithName
, findWindowWith
, focusWindowE
, getBufferStack
, getBufferWithName
, getBufferWithNameOrCurrent
, getEditorDyn
, getRegE
, jumpBackE
, jumpForwardE
, killringA
, layoutManagerNextVariantE
, layoutManagerPreviousVariantE
, layoutManagersNextE
, layoutManagersPreviousE
, layoutManagersPrintMsgE
, maxStatusHeightA
, moveTabE
, moveWinNextE
, moveWinPrevE
, newBufferE
, newEmptyBufferE
, newTabE
, newTempBufferE
, newWindowE
, nextTabE
, nextWinE
, onCloseActionsA
, pendingEventsA
, prevWinE
, previousTabE
, printMsg
, printMsgs
, printStatus
, pushWinToFirstE
, putEditorDyn
, searchDirectionA
, setDividerPosE
, setRegE
, setStatus
, shiftOtherWindow
, splitE
, statusLine
, statusLineInfo
, statusLinesA
, stringToNewBuffer
, swapWinWithFirstE
, switchToBufferE
, switchToBufferWithNameE
, tabsA
, tryCloseE
, windows
, windowsA
, windowsOnBufferE
, withCurrentBuffer
, withEveryBuffer
, withGivenBuffer
, withGivenBufferAndWindow
, withOtherWindow
, withWindowE
) where
import Prelude hiding (all, concatMap, foldl, foldr)
import Lens.Micro.Platform (Lens', lens, mapped,
use, view, (%=), (%~),
(&), (.~), (^.), (.=),
ASetter)
import Control.Monad (forM_, liftM)
import Control.Monad.Reader (MonadReader (ask), asks,
unless, when)
import Control.Monad.State (gets, modify, MonadState)
import Data.Binary (Binary, get, put)
import Data.Default (Default, def)
import qualified Data.DelayList as DelayList (insert)
import Data.DynamicState.Serializable (getDyn, putDyn)
import Data.Foldable (Foldable (foldl, foldr), all, concatMap, toList)
import Data.List (delete, (\\))
import Data.List.NonEmpty (NonEmpty (..), fromList, nub)
import qualified Data.List.NonEmpty as NE (filter, head, length, toList, (<|))
import qualified Data.List.PointedList as PL (atEnd, moveTo)
import qualified Data.List.PointedList.Circular as PL (PointedList (..), delete,
deleteLeft, deleteOthers,
deleteRight, focus,
insertLeft, insertRight,
length, next, previous,
singleton, _focus)
import qualified Data.Map as M (delete, elems, empty,
insert, lookup, singleton, (!))
import Data.Maybe (fromJust, fromMaybe, isNothing)
import qualified Data.Monoid as Mon ((<>))
import Data.Semigroup ((<>))
import qualified Data.Text as T (Text, null, pack, unlines, unpack, unwords)
import System.FilePath (splitPath)
import Yi.Buffer
import Yi.Config
import Yi.Interact as I (accepted, mkAutomaton)
import Yi.JumpList (Jump (..), JumpList, addJump, jumpBack, jumpForward)
import Yi.KillRing (krEmpty, krGet, krPut, krSet)
import Yi.Layout
import Yi.Monad (getsAndModify)
import Yi.Rope (YiString, empty, fromText)
import qualified Yi.Rope as R (YiString, fromText, snoc)
import Yi.String (listify)
import Yi.Style (defaultStyle)
import Yi.Tab
import Yi.Types
import Yi.Utils
import Yi.Window
assign :: MonadState s m => ASetter s s a b -> b -> m ()
assign = (.=)
uses l f = f <$> use l
instance Binary Editor where
put (Editor bss bs supply ts dv _sl msh kr regex _dir _ev _cwa ) =
let putNE (x :| xs) = put x >> put xs
in putNE bss >> put bs >> put supply >> put ts
>> put dv >> put msh >> put kr >> put regex
get = do
bss <- (:|) <$> get <*> get
bs <- get
supply <- get
ts <- get
dv <- get
msh <- get
kr <- get
regex <- get
return $ emptyEditor { bufferStack = bss
, buffers = bs
, refSupply = supply
, tabs_ = ts
, dynamic = dv
, maxStatusHeight = msh
, killring = kr
, currentRegex = regex
}
-- | The initial state
emptyEditor :: Editor
emptyEditor = Editor
{ buffers = M.singleton (bkey buf) buf
, tabs_ = PL.singleton tab
, bufferStack = bkey buf :| []
, refSupply = 3
, currentRegex = Nothing
, searchDirection = Forward
, dynamic = mempty
, statusLines = DelayList.insert (maxBound, ([""], defaultStyle)) []
, killring = krEmpty
, pendingEvents = []
, maxStatusHeight = 1
, onCloseActions = M.empty
}
where buf = newB 0 (MemBuffer "console") mempty
win = (dummyWindow (bkey buf)) { wkey = WindowRef 1 , isMini = False }
tab = makeTab1 2 win
-- ---------------------------------------------------------------------
makeLensesWithSuffix "A" ''Editor
windows :: Editor -> PL.PointedList Window
windows e = e ^. windowsA
windowsA :: Lens' Editor (PL.PointedList Window)
windowsA = currentTabA . tabWindowsA
tabsA :: Lens' Editor (PL.PointedList Tab)
tabsA = fixCurrentBufferA_ . tabs_A
currentTabA :: Lens' Editor Tab
currentTabA = tabsA . PL.focus
askConfigVariableA :: (YiConfigVariable b, MonadEditor m) => m b
askConfigVariableA = do cfg <- askCfg
return $ cfg ^. configVariable
-- ---------------------------------------------------------------------
-- Buffer operations
newRef :: MonadEditor m => m Int
newRef = withEditor (refSupplyA %= (+ 1) >> use refSupplyA)
newBufRef :: MonadEditor m => m BufferRef
newBufRef = liftM BufferRef newRef
-- | Create and fill a new buffer, using contents of string.
-- | Does not focus the window, or make it the current window.
-- | Call newWindowE or switchToBufferE to take care of that.
stringToNewBuffer :: MonadEditor m
=> BufferId -- ^ The buffer indentifier
-> YiString -- ^ The contents with which to populate
-- the buffer
-> m BufferRef
stringToNewBuffer nm cs = withEditor $ do
u <- newBufRef
defRegStyle <- configRegionStyle <$> askCfg
insertBuffer $ newB u nm cs
m <- asks configFundamentalMode
withGivenBuffer u $ do
putRegionStyle defRegStyle
setAnyMode m
return u
insertBuffer :: MonadEditor m => FBuffer -> m ()
insertBuffer b = withEditor . modify $ \e ->
-- insert buffers at the end, so that
-- "background" buffers do not interfere.
e { bufferStack = nub (bufferStack e <> (bkey b :| []))
, buffers = M.insert (bkey b) b (buffers e)}
-- Prevent possible space leaks in the editor structure
forceFold1 :: Foldable t => t a -> t a
forceFold1 x = foldr seq x x
forceFoldTabs :: Foldable t => t Tab -> t Tab
forceFoldTabs x = foldr (seq . forceTab) x x
-- | Delete a buffer (and release resources associated with it).
deleteBuffer :: MonadEditor m => BufferRef -> m ()
deleteBuffer k = withEditor $ do
-- If the buffer has an associated close action execute that now.
-- Unless the buffer is the last buffer in the editor. In which case
-- it cannot be closed and, I think, the close action should not be
-- applied.
--
-- The close actions seem dangerous, but I know of no other simple
-- way to resolve issues related to what buffer receives actions
-- after the minibuffer closes.
gets bufferStack >>= \case
_ :| [] -> return ()
_ -> M.lookup k <$> gets onCloseActions
>>= \m_action -> fromMaybe (return ()) m_action
-- Now try deleting the buffer. Checking, once again, that it is not
-- the last buffer.
bs <- gets bufferStack
ws <- use windowsA
case bs of
b0 :| nextB : _ -> do
let pickOther w = if bufkey w == k then w {bufkey = other} else w
visibleBuffers = bufkey <$> toList ws
-- This ‘head’ always works because we witness that length of
-- bs ≥ 2 (through case) and ‘delete’ only deletes up to 1
-- element so we at worst we end up with something like
-- ‘head $ [] ++ [foo]’ when bs ≡ visibleBuffers
bs' = NE.toList bs
other = head $ (bs' \\ visibleBuffers) ++ delete k bs'
when (b0 == k) $
-- we delete the currently selected buffer: the next buffer
-- will become active in the main window, therefore it must be
-- assigned a new window.
switchToBufferE nextB
-- NOTE: This *only* works if not all bufferStack buffers are
-- equivalent to ‘k’. Assuring that there are no duplicates in
-- the bufferStack is equivalent in this case because of its
-- length.
modify $ \e ->
e & bufferStackA %~ fromList . forceFold1 . NE.filter (k /=)
& buffersA %~ M.delete k
& tabs_A %~ forceFoldTabs . fmap (mapWindows pickOther)
-- all windows open on that buffer must switch to another
-- buffer.
windowsA . mapped . bufAccessListA %= forceFold1 . filter (k /=)
_ -> return () -- Don't delete the last buffer.
-- | Return the buffers we have, /in no particular order/
bufferSet :: Editor -> [FBuffer]
bufferSet = M.elems . buffers
-- | Return a prefix that can be removed from all buffer paths while
-- keeping them unique.
commonNamePrefix :: Editor -> [FilePath]
commonNamePrefix = commonPrefix . fmap (dropLast . splitPath)
. fbufs . fmap (^. identA) . bufferSet
where dropLast [] = []
dropLast x = init x
fbufs xs = [ x | FileBuffer x <- xs ]
-- drop the last component, so that it is never hidden.
getBufferStack :: MonadEditor m => m (NonEmpty FBuffer)
getBufferStack = withEditor $ do
bufMap <- gets buffers
gets $ fmap (bufMap M.!) . bufferStack
findBuffer :: MonadEditor m => BufferRef -> m (Maybe FBuffer)
findBuffer k = withEditor (gets (M.lookup k . buffers))
-- | Find buffer with this key
findBufferWith :: BufferRef -> Editor -> FBuffer
findBufferWith k e = case M.lookup k (buffers e) of
Just x -> x
Nothing -> error "Editor.findBufferWith: no buffer has this key"
-- | Find buffers with this name
findBufferWithName :: T.Text -> Editor -> [BufferRef]
findBufferWithName n e =
let bufs = M.elems $ buffers e
sameIdent b = shortIdentString (length $ commonNamePrefix e) b == n
in map bkey $ filter sameIdent bufs
-- | Find buffer with given name. Fail if not found.
getBufferWithName :: MonadEditor m => T.Text -> m BufferRef
getBufferWithName bufName = withEditor $ do
bs <- gets $ findBufferWithName bufName
case bs of
[] -> fail ("Buffer not found: " ++ T.unpack bufName)
b:_ -> return b
------------------------------------------------------------------------
-- | Perform action with any given buffer, using the last window that
-- was used for that buffer.
withGivenBuffer :: MonadEditor m => BufferRef -> BufferM a -> m a
withGivenBuffer k f = do
b <- gets (findBufferWith k)
withGivenBufferAndWindow (b ^. lastActiveWindowA) k f
-- | Perform action with any given buffer
withGivenBufferAndWindow :: MonadEditor m
=> Window -> BufferRef -> BufferM a -> m a
withGivenBufferAndWindow w k f = withEditor $ do
accum <- asks configKillringAccumulate
let edit e = let b = findBufferWith k e
(v, us, b') = runBufferFull w b f
in (e & buffersA .~ mapAdjust' (const b') k (buffers e)
& killringA %~
if accum && all updateIsDelete us
then foldl (.) id $ reverse [ krPut dir s
| Delete _ dir s <- us ]
else id
, (us, v))
(us, v) <- getsAndModify edit
updHandler <- return . bufferUpdateHandler =<< ask
unless (null us || null updHandler) $
forM_ updHandler (\h -> withGivenBufferAndWindow w k (h us))
return v
-- | Perform action with current window's buffer
withCurrentBuffer :: MonadEditor m => BufferM a -> m a
withCurrentBuffer f = withEditor $ do
w <- use currentWindowA
withGivenBufferAndWindow w (bufkey w) f
withEveryBuffer :: MonadEditor m => BufferM a -> m [a]
withEveryBuffer action =
withEditor (gets bufferStack) >>= mapM (`withGivenBuffer` action) . NE.toList
currentWindowA :: Lens' Editor Window
currentWindowA = windowsA . PL.focus
-- | Return the current buffer
currentBuffer :: Editor -> BufferRef
currentBuffer = NE.head . bufferStack
-----------------------
-- Handling of status
-- | Prints a message with 'defaultStyle'.
printMsg :: MonadEditor m => T.Text -> m ()
printMsg s = printStatus ([s], defaultStyle)
-- | Prints a all given messages with 'defaultStyle'.
printMsgs :: MonadEditor m => [T.Text] -> m ()
printMsgs s = printStatus (s, defaultStyle)
printStatus :: MonadEditor m => Status -> m ()
printStatus = setTmpStatus 1
-- | Set the "background" status line
setStatus :: MonadEditor m => Status -> m ()
setStatus = setTmpStatus maxBound
-- | Clear the status line
clrStatus :: EditorM ()
clrStatus = setStatus ([""], defaultStyle)
statusLine :: Editor -> [T.Text]
statusLine = fst . statusLineInfo
statusLineInfo :: Editor -> Status
statusLineInfo = snd . head . statusLines
setTmpStatus :: MonadEditor m => Int -> Status -> m ()
setTmpStatus delay s = withEditor $ do
statusLinesA %= DelayList.insert (delay, s)
-- also show in the messages buffer, so we don't loose any message
bs <- gets (filter ((== MemBuffer "messages") . view identA) . M.elems . buffers)
b <- case bs of
(b':_) -> return $ bkey b'
[] -> stringToNewBuffer (MemBuffer "messages") mempty
let m = listify $ R.fromText <$> fst s
withGivenBuffer b $ botB >> insertN (m `R.snoc` '\n')
-- ---------------------------------------------------------------------
-- kill-register (vim-style) interface to killring.
--
-- Note that our vim keymap currently has its own registers
-- and doesn't use killring.
-- | Put string into yank register
setRegE :: R.YiString -> EditorM ()
setRegE s = killringA %= krSet s
-- | Return the contents of the yank register
getRegE :: EditorM R.YiString
getRegE = uses killringA krGet
-- ---------------------------------------------------------------------
-- | Dynamically-extensible state components.
--
-- These hooks are used by keymaps to store values that result from
-- Actions (i.e. that restult from IO), as opposed to the pure values
-- they generate themselves, and can be stored internally.
--
-- The `dynamic' field is a type-indexed map.
--
-- | Retrieve a value from the extensible state
getEditorDyn :: (MonadEditor m, YiVariable a, Default a, Functor m) => m a
getEditorDyn = fromMaybe def <$> getDyn (use dynamicA) (assign dynamicA)
-- | Insert a value into the extensible state, keyed by its type
putEditorDyn :: (MonadEditor m, YiVariable a, Functor m) => a -> m ()
putEditorDyn = putDyn (use dynamicA) (assign dynamicA)
-- | Like fnewE, create a new buffer filled with the String @s@,
-- Switch the current window to this buffer. Doesn't associate any
-- file with the buffer (unlike fnewE) and so is good for popup
-- internal buffers (like scratch)
newBufferE :: BufferId -- ^ buffer name
-> YiString -- ^ buffer contents
-> EditorM BufferRef
newBufferE f s = do
b <- stringToNewBuffer f s
switchToBufferE b
return b
-- | Like 'newBufferE' but defaults to empty contents.
newEmptyBufferE :: BufferId -> EditorM BufferRef
newEmptyBufferE f = newBufferE f Yi.Rope.empty
alternateBufferE :: Int -> EditorM ()
alternateBufferE n = do
Window { bufAccessList = lst } <- use currentWindowA
if null lst || (length lst - 1) < n
then fail "no alternate buffer"
else switchToBufferE $ lst!!n
-- | Create a new zero size window on a given buffer
newZeroSizeWindow :: Bool -> BufferRef -> WindowRef -> Window
newZeroSizeWindow mini bk ref = Window mini bk [] 0 0 emptyRegion ref 0 Nothing
-- | Create a new window onto the given buffer.
newWindowE :: Bool -> BufferRef -> EditorM Window
newWindowE mini bk = newZeroSizeWindow mini bk . WindowRef <$> newRef
-- | Attach the specified buffer to the current window
switchToBufferE :: BufferRef -> EditorM ()
switchToBufferE bk = windowsA . PL.focus %= \w ->
w & bufkeyA .~ bk
& bufAccessListA %~ forceFold1 . (bufkey w:) . filter (bk /=)
-- | Switch to the buffer specified as parameter. If the buffer name
-- is empty, switch to the next buffer.
switchToBufferWithNameE :: T.Text -> EditorM ()
switchToBufferWithNameE "" = alternateBufferE 0
switchToBufferWithNameE bufName = switchToBufferE =<< getBufferWithName bufName
-- | Close a buffer.
-- Note: close the current buffer if the empty string is given
closeBufferE :: T.Text -> EditorM ()
closeBufferE nm = deleteBuffer =<< getBufferWithNameOrCurrent nm
getBufferWithNameOrCurrent :: MonadEditor m => T.Text -> m BufferRef
getBufferWithNameOrCurrent t = withEditor $
case T.null t of
True -> gets currentBuffer
False -> getBufferWithName t
------------------------------------------------------------------------
-- | Close current buffer and window, unless it's the last one.
closeBufferAndWindowE :: EditorM ()
closeBufferAndWindowE = do
-- Fetch the current buffer *before* closing the window.
-- The tryCloseE, since it uses tabsA, will have the
-- current buffer "fixed" to the buffer of the window that is
-- brought into focus. If the current buffer is accessed after the
-- tryCloseE then the current buffer may not be the same as the
-- buffer before tryCloseE. This would be bad.
b <- gets currentBuffer
tryCloseE
deleteBuffer b
-- | Rotate focus to the next window
nextWinE :: EditorM ()
nextWinE = windowsA %= PL.next
-- | Rotate focus to the previous window
prevWinE :: EditorM ()
prevWinE = windowsA %= PL.previous
-- | Swaps the focused window with the first window. Useful for
-- layouts such as 'HPairOneStack', for which the first window is the
-- largest.
swapWinWithFirstE :: EditorM ()
swapWinWithFirstE = windowsA %= swapFocus (fromJust . PL.moveTo 0)
-- | Moves the focused window to the first window, and moves all other
-- windows down the stack.
pushWinToFirstE :: EditorM ()
pushWinToFirstE = windowsA %= pushToFirst
where
pushToFirst ws = case PL.delete ws of
Nothing -> ws
Just ws' -> PL.insertLeft (ws ^. PL.focus) (fromJust $ PL.moveTo 0 ws')
-- | Swap focused window with the next one
moveWinNextE :: EditorM ()
moveWinNextE = windowsA %= swapFocus PL.next
-- | Swap focused window with the previous one
moveWinPrevE :: EditorM ()
moveWinPrevE = windowsA %= swapFocus PL.previous
-- | A "fake" accessor that fixes the current buffer after a change of
-- the current window.
--
-- Enforces invariant that top of buffer stack is the buffer of the
-- current window.
fixCurrentBufferA_ :: Lens' Editor Editor
fixCurrentBufferA_ = lens id (\_old new -> let
ws = windows new
b = findBufferWith (bufkey $ PL._focus ws) new
newBufferStack = nub (bkey b NE.<| bufferStack new)
-- make sure we do not hold to old versions by seqing the length.
in NE.length newBufferStack `seq` new & bufferStackA .~ newBufferStack)
withWindowE :: Window -> BufferM a -> EditorM a
withWindowE w = withGivenBufferAndWindow w (bufkey w)
findWindowWith :: WindowRef -> Editor -> Window
findWindowWith k e =
head $ concatMap (\win -> [win | wkey win == k]) $ windows e
-- | Return the windows that are currently open on the buffer whose
-- key is given
windowsOnBufferE :: BufferRef -> EditorM [Window]
windowsOnBufferE k = do
ts <- use tabsA
let tabBufEq = concatMap (\win -> [win | bufkey win == k]) . (^. tabWindowsA)
return $ concatMap tabBufEq ts
-- | bring the editor focus the window with the given key.
--
-- Fails if no window with the given key is found.
focusWindowE :: WindowRef -> EditorM ()
focusWindowE k = do
-- Find the tab index and window index
ts <- use tabsA
let check (False, i) win = if wkey win == k
then (True, i)
else (False, i + 1)
check r@(True, _) _win = r
searchWindowSet (False, tabIndex, _) ws =
case foldl check (False, 0) (ws ^. tabWindowsA) of
(True, winIndex) -> (True, tabIndex, winIndex)
(False, _) -> (False, tabIndex + 1, 0)
searchWindowSet r@(True, _, _) _ws = r
case foldl searchWindowSet (False, 0, 0) ts of
(False, _, _) -> fail $ "No window with key " ++ show k ++ "found. (focusWindowE)"
(True, tabIndex, winIndex) -> do
assign tabsA (fromJust $ PL.moveTo tabIndex ts)
windowsA %= fromJust . PL.moveTo winIndex
-- | Split the current window, opening a second window onto current buffer.
-- TODO: unfold newWindowE here?
splitE :: EditorM ()
splitE = do
w <- gets currentBuffer >>= newWindowE False
windowsA %= PL.insertRight w
-- | Prints the description of the current layout manager in the status bar
layoutManagersPrintMsgE :: EditorM ()
layoutManagersPrintMsgE = do
lm <- use $ currentTabA . tabLayoutManagerA
printMsg . T.pack $ describeLayout lm
-- | Cycle to the next layout manager, or the first one if the current
-- one is nonstandard.
layoutManagersNextE :: EditorM ()
layoutManagersNextE = withLMStackE PL.next >> layoutManagersPrintMsgE
-- | Cycle to the previous layout manager, or the first one if the
-- current one is nonstandard.
layoutManagersPreviousE :: EditorM ()
layoutManagersPreviousE = withLMStackE PL.previous >> layoutManagersPrintMsgE
-- | Helper function for 'layoutManagersNext' and 'layoutManagersPrevious'
withLMStackE :: (PL.PointedList AnyLayoutManager
-> PL.PointedList AnyLayoutManager)
-> EditorM ()
withLMStackE f = askCfg >>= \cfg ->
currentTabA . tabLayoutManagerA %= go (layoutManagers cfg)
where
go [] lm = lm
go lms lm =
case findPL (layoutManagerSameType lm) lms of
Nothing -> head lms
Just lmsPL -> f lmsPL ^. PL.focus
-- | Next variant of the current layout manager, as given by 'nextVariant'
layoutManagerNextVariantE :: EditorM ()
layoutManagerNextVariantE = do
currentTabA . tabLayoutManagerA %= nextVariant
layoutManagersPrintMsgE
-- | Previous variant of the current layout manager, as given by
-- 'previousVariant'
layoutManagerPreviousVariantE :: EditorM ()
layoutManagerPreviousVariantE = do
currentTabA . tabLayoutManagerA %= previousVariant
layoutManagersPrintMsgE
-- | Sets the given divider position on the current tab
setDividerPosE :: DividerRef -> DividerPosition -> EditorM ()
setDividerPosE ref = assign (currentTabA . tabDividerPositionA ref)
-- | Creates a new tab containing a window that views the current buffer.
newTabE :: EditorM ()
newTabE = do
bk <- gets currentBuffer
win <- newWindowE False bk
ref <- newRef
tabsA %= PL.insertRight (makeTab1 ref win)
-- | Moves to the next tab in the round robin set of tabs
nextTabE :: EditorM ()
nextTabE = tabsA %= PL.next
-- | Moves to the previous tab in the round robin set of tabs
previousTabE :: EditorM ()
previousTabE = tabsA %= PL.previous
-- | Moves the focused tab to the given index, or to the end if the
-- index is not specified.
moveTabE :: Maybe Int -> EditorM ()
moveTabE Nothing = do
count <- uses tabsA PL.length
tabsA %= fromJust . PL.moveTo (pred count)
moveTabE (Just n) = do
newTabs <- uses tabsA (PL.moveTo n)
when (isNothing newTabs) failure
assign tabsA $ fromJust newTabs
where failure = fail $ "moveTab " ++ show n ++ ": no such tab"
-- | Deletes the current tab. If there is only one tab open then error out.
-- When the last tab is focused, move focus to the left, otherwise
-- move focus to the right.
deleteTabE :: EditorM ()
deleteTabE = tabsA %= fromMaybe failure . deleteTab
where failure = error "deleteTab: cannot delete sole tab"
deleteTab tabs = if PL.atEnd tabs
then PL.deleteLeft tabs
else PL.deleteRight tabs
-- | Close the current window. If there is only one tab open and the tab
-- contains only one window then do nothing.
tryCloseE :: EditorM ()
tryCloseE = do
ntabs <- uses tabsA PL.length
nwins <- uses windowsA PL.length
unless (ntabs == 1 && nwins == 1) $ if nwins == 1
-- Could the Maybe response from deleteLeft be used instead of the
-- def 'if'?
then tabsA %= fromJust . PL.deleteLeft
else windowsA %= fromJust . PL.deleteLeft
-- | Make the current window the only window on the screen
closeOtherE :: EditorM ()
closeOtherE = windowsA %= PL.deleteOthers
-- | Switch focus to some other window. If none is available, create one.
shiftOtherWindow :: MonadEditor m => m ()
shiftOtherWindow = withEditor $ do
len <- uses windowsA PL.length
if len == 1
then splitE
else nextWinE
-- | Execute the argument in the context of an other window. Create
-- one if necessary. The current window is re-focused after the
-- argument has completed.
withOtherWindow :: MonadEditor m => m a -> m a
withOtherWindow f = do
shiftOtherWindow
x <- f
withEditor prevWinE
return x
acceptedInputs :: EditorM [T.Text]
acceptedInputs = do
km <- defaultKm <$> askCfg
keymap <- withCurrentBuffer $ gets (withMode0 modeKeymap)
let l = I.accepted 3 . I.mkAutomaton . extractTopKeymap . keymap $ km
return $ fmap T.unwords l
-- | Shows the current key bindings in a new window
acceptedInputsOtherWindow :: EditorM ()
acceptedInputsOtherWindow = do
ai <- acceptedInputs
b <- stringToNewBuffer (MemBuffer "keybindings") (fromText $ T.unlines ai)
w <- newWindowE False b
windowsA %= PL.insertRight w
addJumpHereE :: EditorM ()
addJumpHereE = addJumpAtE =<< withCurrentBuffer pointB
addJumpAtE :: Point -> EditorM ()
addJumpAtE point = do
w <- use currentWindowA
shouldAddJump <- case jumpList w of
Just (PL.PointedList _ (Jump mark bf) _) -> do
bfStillAlive <- gets (M.lookup bf . buffers)
case bfStillAlive of
Nothing -> return False
_ -> do
p <- withGivenBuffer bf . use $ markPointA mark
return $! (p, bf) /= (point, bufkey w)
_ -> return True
when shouldAddJump $ do
m <- withCurrentBuffer setMarkHereB
let bf = bufkey w
j = Jump m bf
assign currentWindowA $ w & jumpListA %~ addJump j
return ()
jumpBackE :: EditorM ()
jumpBackE = addJumpHereE >> modifyJumpListE jumpBack
jumpForwardE :: EditorM ()
jumpForwardE = modifyJumpListE jumpForward
modifyJumpListE :: (JumpList -> JumpList) -> EditorM ()
modifyJumpListE f = do
w <- use currentWindowA
case f $ w ^. jumpListA of
Nothing -> return ()
Just (PL.PointedList _ (Jump mark bf) _) -> do
switchToBufferE bf
withCurrentBuffer $ use (markPointA mark) >>= moveTo
currentWindowA . jumpListA %= f
-- | Creates an in-memory buffer with a unique name.
newTempBufferE :: EditorM BufferRef
newTempBufferE = do
e <- gets id
-- increment the index of the hint until no buffer is found with that name
let find_next currentName (nextName:otherNames) =
case findBufferWithName currentName e of
(_b : _) -> find_next nextName otherNames
[] -> currentName
find_next _ [] = error "Looks like nearly infinite list has just ended."
next_tmp_name = find_next name names
(name : names) = (fmap (("tmp-" Mon.<>) . T.pack . show) [0 :: Int ..])
newEmptyBufferE (MemBuffer next_tmp_name)
| siddhanathan/yi | yi-core/src/Yi/Editor.hs | gpl-2.0 | 30,549 | 0 | 23 | 8,891 | 7,012 | 3,689 | 3,323 | -1 | -1 |
module Lib2 where
import Text.PrettyPrint.ANSI.Leijen
printGreeting :: String -> IO ()
printGreeting greeting = putDoc $ text greeting <> linebreak
| prezi/gradle-haskell-plugin | src/test-projects/test1/lib2/src/main/haskell/Lib2.hs | apache-2.0 | 150 | 0 | 7 | 22 | 44 | 24 | 20 | 4 | 1 |
module TestSbasics(tests) where
import Test.HUnit
import Database.HDBC
import TestUtils
import System.IO
import Control.Exception
openClosedb = sqlTestCase $
do dbh <- connectDB
disconnect dbh
multiFinish = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
sExecute sth []
finish sth
finish sth
finish sth
)
basicQueries = dbTestCase (\dbh ->
do sth <- prepare dbh "SELECT 1 + 1"
sExecute sth []
sFetchRow sth >>= (assertEqual "row 1" (Just [Just "2"]))
sFetchRow sth >>= (assertEqual "last row" Nothing)
)
createTable = dbTestCase (\dbh ->
do sRun dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT) ENGINE INNODB" []
commit dbh
)
dropTable = dbTestCase (\dbh ->
do sRun dbh "DROP TABLE hdbctest1" []
commit dbh
)
runReplace = dbTestCase (\dbh ->
do sRun dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
sRun dbh "INSERT INTO hdbctest1 VALUES (?, ?, 2, ?)" r2
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
sExecute sth []
sFetchRow sth >>= (assertEqual "r1" (Just r1))
sFetchRow sth >>= (assertEqual "r2" (Just [Just "runReplace", Just "2",
Just "2", Nothing]))
sFetchRow sth >>= (assertEqual "lastrow" Nothing)
)
where r1 = [Just "runReplace", Just "1", Just "1234", Just "testdata"]
r2 = [Just "runReplace", Just "2", Nothing]
executeReplace = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
sExecute sth [Just "1", Just "1234", Just "Foo"]
sExecute sth [Just "2", Nothing, Just "Bar"]
commit dbh
sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
sExecute sth [Just "executeReplace"]
sFetchRow sth >>= (assertEqual "r1"
(Just $ map Just ["executeReplace", "1", "1234",
"Foo"]))
sFetchRow sth >>= (assertEqual "r2"
(Just [Just "executeReplace", Just "2", Nothing,
Just "Bar"]))
sFetchRow sth >>= (assertEqual "lastrow" Nothing)
)
testExecuteMany = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
sExecuteMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
sExecute sth []
mapM_ (\r -> sFetchRow sth >>= (assertEqual "" (Just r))) rows
sFetchRow sth >>= (assertEqual "lastrow" Nothing)
)
where rows = [map Just ["1", "1234", "foo"],
map Just ["2", "1341", "bar"],
[Just "3", Nothing, Nothing]]
testsFetchAllRows = dbTestCase (\dbh ->
do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows', ?, NULL, NULL)"
sExecuteMany sth rows
commit dbh
sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows' ORDER BY testid"
sExecute sth []
results <- sFetchAllRows sth
assertEqual "" rows results
)
where rows = map (\x -> [Just . show $ x]) [1..9]
basicTransactions = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
sExecute sth [Just "0"]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "initial commit" [[Just "0"]])
-- Now try a rollback
sExecuteMany sth rows
rollback dbh
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "rollback" [[Just "0"]])
-- Now try another commit
sExecuteMany sth rows
commit dbh
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "final commit" ([Just "0"]:rows))
)
where rows = map (\x -> [Just . show $ x]) [1..9]
testWithTransaction = dbTestCase (\dbh ->
do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
sExecute sth [Just "0"]
commit dbh
qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "initial commit" [[Just "0"]])
-- Let's try a rollback.
try $ withTransaction dbh (\_ -> do sExecuteMany sth rows
fail "Foo")
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "rollback" [[Just "0"]])
-- And now a commit.
withTransaction dbh (\_ -> sExecuteMany sth rows)
sExecute qrysth []
sFetchAllRows qrysth >>= (assertEqual "final commit" ([Just "0"]:rows))
)
where rows = map (\x -> [Just . show $ x]) [1..9]
tests = TestList
[
TestLabel "openClosedb" openClosedb,
TestLabel "multiFinish" multiFinish,
TestLabel "basicQueries" basicQueries,
TestLabel "createTable" createTable,
TestLabel "runReplace" runReplace,
TestLabel "executeReplace" executeReplace,
TestLabel "executeMany" testExecuteMany,
TestLabel "sFetchAllRows" testsFetchAllRows,
TestLabel "basicTransactions" basicTransactions,
TestLabel "withTransaction" testWithTransaction,
TestLabel "dropTable" dropTable
]
| ryantm/hdbc-mysql | testsrc/TestSbasics.hs | lgpl-2.1 | 6,142 | 0 | 17 | 1,930 | 1,608 | 766 | 842 | 118 | 1 |
{-# LANGUAGE BangPatterns, FlexibleContexts, ScopedTypeVariables #-}
module Ros.Node.RosTcp (subStream, runServer, runServers, callServiceWithMaster) where
import Control.Applicative ((<$>))
import Control.Arrow (first)
import Control.Concurrent (forkIO, killThread, newEmptyMVar, takeMVar, putMVar)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar
import qualified Control.Exception as E
import Control.Monad.Reader
import Data.Binary.Put (runPut, putWord32le)
import Data.Binary.Get (runGet, getWord32le)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Network.BSD (getHostByName, hostAddress)
import Network.Socket hiding (send, sendTo, recv, recvFrom, Stream, ServiceName)
import qualified Network.Socket as Sock
import Network.Socket.ByteString
import Prelude hiding (getContents)
import System.IO (IOMode(ReadMode), hClose)
import Text.URI (parseURI, uriRegName, uriPort)
import Ros.Node.BinaryIter (streamIn, getServiceResult)
import Ros.Internal.Msg.MsgInfo
import Ros.Internal.Msg.SrvInfo
import Ros.Internal.RosBinary
import Ros.Internal.RosTypes
import Ros.Internal.Util.RingChan
import Ros.Internal.Util.AppConfig (Config, debug, forkConfig)
import Ros.Topic (Topic(..))
import Ros.Node.ConnectionHeader
import Ros.Graph.Slave (requestTopicClient)
import Ros.Graph.Master (lookupService)
import Data.Maybe (fromMaybe)
import Ros.Service.ServiceTypes
import Control.Monad.Except
import System.IO.Error (tryIOError)
-- |Push each item from this client's buffer over the connected
-- socket.
serviceClient :: RingChan ByteString -> Socket -> IO ()
serviceClient c s = forever $ do bs <- readChan c
sendBS s bs
sendBS :: Socket -> ByteString -> IO ()
sendBS sock bs =
let len = runPut $
putWord32le . fromIntegral $
BL.length bs
in
sendAll sock (BL.toStrict $ BL.append len bs)
recvAll :: Socket -> Int -> IO B.ByteString
recvAll s = flip go []
where go len acc = do bs <- recv s len
if B.length bs < len
then go (len - B.length bs) (bs:acc)
else return $ B.concat (reverse (bs:acc))
negotiatePub :: String -> String -> Socket -> IO ()
negotiatePub ttype md5 sock =
do headerLength <- runGet (fromIntegral <$> getWord32le) <$>
BL.fromChunks . (:[]) <$> recvAll sock 4
headerBytes <- recvAll sock headerLength
let connHeader = parseHeader headerBytes
wildCard = case lookup "type" connHeader of
Just t | t == "*" -> True
| t == ttype -> False
| otherwise -> error $
"Disagreeing Topic types: " ++
"publisher expected "++ttype++
", but client asked for "++t
Nothing -> error $ "Client did not include the "++
"topic type in its "++
"connection request."
when (not wildCard)
(case lookup "md5sum" connHeader of
Just s | s == md5 -> return ()
| otherwise -> error "Disagreement on Topic type MD5"
Nothing -> error $ "Client did not include MD5 sum "++
"in its request.")
case lookup "tcp_nodelay" connHeader of
Just "1" -> setSocketOption sock NoDelay 0
_ -> return ()
sendAll sock . genHeader $
[("md5sum",md5), ("type",ttype), ("callerid","roshask")]
-- |Accept new client connections. A new send buffer is allocated for
-- each new client and added to the client list along with an action
-- for cleaning up the client connection.
-- FIXME: cleaning up a disconnected client should be reflected at a
-- higher level, too.
acceptClients :: Socket -> TVar [(Config (), RingChan ByteString)] ->
(Socket -> IO ()) -> IO (RingChan ByteString) -> Config ()
acceptClients sock clients negotiate mkBuffer = forever acceptClient
where acceptClient = do (client,_) <- liftIO $ accept sock
debug "Accepted client socket"
liftIO $ negotiate client
chan <- liftIO mkBuffer
let cleanup1 =
do debug "Closing client socket"
liftIO $
shutdown client ShutdownBoth `E.catch`
\(_::E.SomeException) -> return ()
r <- ask
t <- liftIO . forkIO $
serviceClient chan client `E.catch`
\(_::E.SomeException) -> runReaderT cleanup1 r
let cleanup2 = cleanup1 >>
(liftIO $ killThread t)
liftIO . atomically $
readTVar clients >>=
writeTVar clients . ((cleanup2,chan) :)
-- |Publish each item obtained from a 'Topic' to each connected client.
pubStream :: RosBinary a
=> Topic IO a -> TVar [(b, RingChan ByteString)] -> Config ()
pubStream t0 clients = liftIO $ go 0 t0
where go !n t = do (x, t') <- runTopic t
let bytes = runPut $ putMsg n x
cs <- readTVarIO clients
mapM_ (flip writeChan bytes . snd) cs
go (n+1) t'
-- |Produce a publishing action associated with a list of
-- clients. This is used by runServers.
pubStreamIO :: RosBinary a => IO (TVar [(b, RingChan ByteString)] -> Config (),
a -> IO ())
pubStreamIO = do m <- newEmptyMVar
let feed clients =
let go !n = do x <- takeMVar m
let bytes = runPut $ putMsg n x
cs <- readTVarIO clients
mapM_ (flip writeChan bytes . snd) cs
go (n+1)
in liftIO $ go 0
return (feed, putMVar m)
-- Negotiate a TCPROS subscriber connection.
-- Precondition: The socket is connected
negotiateSub :: Socket -> String -> String -> String -> IO ()
negotiateSub sock tname ttype md5 =
do sendAll sock $ genHeader [ ("callerid", "roshask"), ("topic", tname)
, ("md5sum", md5), ("type", ttype)
, ("tcp_nodelay", "1") ]
responseLength <- runGet (fromIntegral <$> getWord32le) <$>
BL.fromChunks . (:[]) <$> recvAll sock 4
headerBytes <- recvAll sock responseLength
let connHeader = parseHeader headerBytes
case lookup "type" connHeader of
Just t | t == ttype -> return ()
| otherwise -> error $ "Disagreeing Topic types: " ++
"subscriber expected "++ttype++
", but server replied with "++t
Nothing -> error $ "Server did not include the topic type "++
"in its response."
case lookup "md5sum" connHeader of
Just s | s == md5 -> return ()
| otherwise -> error "Disagreement on Topic type MD5"
Nothing -> error "Server did not include MD5 sum in its response."
setSocketOption sock KeepAlive 1
-- |Connect to a publisher and return the stream of data it is
-- publishing.
subStream :: forall a. (RosBinary a, MsgInfo a) =>
URI -> String -> (Int -> IO ()) -> Config (Topic IO a)
subStream target tname _updateStats =
do debug $ "Opening stream to " ++target++" for "++tname
h <- liftIO $
do response <- requestTopicClient target "/roshask" tname
[["TCPROS"]]
let port = case response of
(1,_,("TCPROS",_,port')) -> fromIntegral port'
_ -> error $ "Couldn't get publisher's port for "++
tname++" from node "++target
sock <- socket AF_INET Sock.Stream defaultProtocol
ip <- hostAddress <$> getHostByName host
connect sock $ SockAddrInet port ip
let md5 = sourceMD5 (undefined::a)
ttype = msgTypeName (undefined::a)
negotiateSub sock tname ttype md5
socketToHandle sock ReadMode
--hSetBuffering h NoBuffering
debug $ "Streaming "++tname++" from "++target
return $ streamIn h
where host = parseHost target
parseHost :: URI -> String
parseHost target = case parseURI target of
Just u -> fromMaybe
(error $ "Couldn't parse hostname "++ "from "++target)
(uriRegName u)
Nothing -> error $ "Couldn't parse URI "++target
parseHostAndPort :: URI -> Either ServiceResponseExcept (String, PortNumber)
parseHostAndPort target = do
uri <- maybeToEither (ConnectExcept $ "Could not parse URI "++target) $ parseURI target
host <- maybeToEither (ConnectExcept $ "Could not parse hostname from "++target) $ uriRegName uri
port <- maybeToEither (ConnectExcept $ "Could not parse port from "++target) $ uriPort uri
return (host, fromIntegral port)
maybeToEither :: a -> Maybe b -> Either a b
maybeToEither left m = case m of
Just x -> Right x
Nothing -> Left left
--TODO: use the correct callerID
callServiceWithMaster :: forall a b. (RosBinary a, SrvInfo a, RosBinary b, SrvInfo b) =>
URI -> ServiceName -> a -> IO (Either ServiceResponseExcept b)
callServiceWithMaster rosMaster serviceName message = runExceptT $ do
checkServicesMatch message (undefined::b)
--lookup the service with the master
(code, statusMessage, serviceUrl) <- lookupService rosMaster callerID serviceName
checkLookupServiceCode code statusMessage
(host, port) <- ExceptT . return $ parseHostAndPort serviceUrl
-- make a socket
let makeSocket = socket AF_INET Sock.Stream defaultProtocol
closeSocket sock = liftIO $ sClose sock
withSocket sock = do
ioErrorToExceptT ConnectExcept "Problem connecting to server. Got exception : " $ do
--Connect to the socket
ip <- hostAddress <$> getHostByName host
connect sock $ SockAddrInet port ip
let reqMd5 = srvMD5 message
reqServiceType = srvTypeName message
negotiateService sock serviceName reqServiceType reqMd5
let bytes = runPut $ putMsg 0 message
ioErrorToExceptT SendRequestExcept "Problem sending request. Got exception: " $
sendBS sock bytes
liftIO $ socketToHandle sock ReadMode
handle <- bracketOnErrorME (liftIO makeSocket) closeSocket withSocket
result <- getServiceResult handle
liftIO $ hClose handle
return result
where
callerID = "roshask"
checkLookupServiceCode 1 _ = return ()
checkLookupServiceCode code statusMessage =
throwError $ MasterExcept
("lookupService failed, code: " ++ show code ++ ", statusMessage: " ++ statusMessage)
checkServicesMatch x y =
unless match $
-- throw error here since the calling code needs to be changed
error "Request and response type do not match"
where
match = srvMD5 x == srvMD5 y && srvTypeName x == srvTypeName y
-- | bracketOnError equivalent for MonadError
bracketOnErrorME :: MonadError e m => m a -> (a -> m b) -> (a -> m c) -> m c
bracketOnErrorME before after thing = do
a <- before
let handler e = after a >> throwError e
catchError (thing a) handler
-- | Catch any IOErrors and convert them to a different type
catchConvertIO :: (String -> a) -> IO b -> IO (Either a b)
catchConvertIO excep action = do
err <- tryIOError action
return $ case err of
Left e -> Left . excep $ show e
Right r -> Right r
-- | Catch all IOErrors that might occur and convert them to a custom error type
-- with the IOError message postpended to the given string
ioErrorToExceptT :: (String -> e) -> String -> IO a -> ExceptT e IO a
ioErrorToExceptT except msg acc =
ExceptT . catchConvertIO (\m -> except $ msg ++ m) $ acc
-- Precondition: The socket is already connected to the server
-- Exchange ROSTCP connection headers with the server
negotiateService :: Socket -> String -> String -> String -> ExceptT ServiceResponseExcept IO ()
negotiateService sock serviceName serviceType md5 = do
headerBytes <- liftIO $
do sendAll sock $ genHeader [ ("callerid", "roshask"), ("service", serviceName)
, ("md5sum", md5), ("type", serviceType) ]
responseLength <- runGet (fromIntegral <$> getWord32le) <$>
BL.fromChunks . (:[]) <$> recvAll sock 4
recvAll sock responseLength
let connHeader = parseHeader headerBytes
case lookup "error" connHeader of
Nothing -> return ()
Just _ -> throwError . ConHeadExcept $
"Connection header from server has error, connection header is: " ++ show connHeader
-- Helper to run the publisher's side of a topic negotiation with a
-- new client.
mkPubNegotiator :: MsgInfo a => a -> Socket -> IO ()
mkPubNegotiator x = negotiatePub (msgTypeName x) (sourceMD5 x)
-- Run a publication server given a function that returns a
-- negotiation action given a client 'Socket', a function that returns
-- a publication action given a client list, a statistics updater, and
-- the size of the send buffer.
runServerAux :: (Socket -> IO ()) ->
(TVar [(Config (), RingChan ByteString)] -> Config ()) ->
(URI -> Int -> IO ()) -> Int -> Config (Config (), Int)
runServerAux negotiate pubAction _updateStats bufferSize =
do r <- ask
liftIO . withSocketsDo $ runReaderT go r
where go = do sock <- liftIO $ socket AF_INET Sock.Stream defaultProtocol
liftIO $ bindSocket sock (SockAddrInet aNY_PORT iNADDR_ANY)
port <- liftIO (fromInteger . toInteger <$> socketPort sock)
liftIO $ listen sock 5
clients <- liftIO $ newTVarIO []
let mkBuffer = newRingChan bufferSize
acceptThread <- forkConfig $
acceptClients sock clients negotiate mkBuffer
pubThread <- forkConfig $ pubAction clients
let cleanup = liftIO (atomically (readTVar clients)) >>=
sequence_ . map fst >>
liftIO (shutdown sock ShutdownBoth >>
killThread acceptThread >>
killThread pubThread)
return (cleanup, port)
-- |The server starts a thread that peels elements off the stream as
-- they become available and sends them to all connected
-- clients. Returns an action for cleaning up resources allocated by
-- this publication server along with the port the server is listening
-- on.
runServer :: forall a. (RosBinary a, MsgInfo a) =>
Topic IO a -> (URI -> Int -> IO ()) -> Int ->
Config (Config (), Int)
runServer stream = runServerAux (mkPubNegotiator (undefined::a))
(pubStream stream)
-- |The 'MsgInfo' type class dictionary made explicit to strip off the
-- actual message type.
data MsgInfoRcd = MsgInfoRcd { _md5, _typeName :: String }
-- |A 'Feeder' represents a 'Topic' fully prepared to accept
-- subscribers.
data Feeder = Feeder MsgInfoRcd -- Explicit MsgInfo dictionary
Int -- Transmit buffer size
(URI -> Int -> IO ()) -- Update topic stats
(TVar [(Config (), RingChan ByteString)] -> Config ())
-- 'pubStream' partial application
-- |Prepare an action for publishing messages. Arguments are a monadic
-- function for updating topic statistics, and a transmit buffer
-- size. The returned 'Feeder' value may be supplied to 'runServers',
-- while the returned 'IO' function may be used to push out new
-- messages.
feedTopic :: forall a. (MsgInfo a, RosBinary a) =>
(URI -> Int -> IO ()) -> Int -> IO (Feeder, a -> IO ())
feedTopic updateStats bufSize =
do (feed,pub) <- pubStreamIO
let f = Feeder info bufSize updateStats feed
return (f, pub)
where info = mkInfo (undefined::a)
mkInfo x = MsgInfoRcd (msgTypeName x) (sourceMD5 x)
-- |Publish several 'Topic's. A single cleanup action for all 'Topic's
-- is returned, along with each 'Topic's server port in the order of
-- the input 'Feeder's.
runServers :: [Feeder] -> Config (Config (), [Int])
runServers = return . first sequence_ . unzip <=< mapM feed
where feed (Feeder (MsgInfoRcd md5 typeName) bufSize stats push) =
let pub = negotiatePub typeName md5
in runServerAux pub push stats bufSize
| bitemyapp/roshask | src/Ros/Node/RosTcp.hs | bsd-3-clause | 17,325 | 0 | 20 | 5,517 | 4,382 | 2,204 | 2,178 | -1 | -1 |
module PatternIn3 where
sumSquares y =let x = 1 in
(1 ^ pow) + sq y
where sq 0=0
sq x=x^pow
pow = 2 | SAdams601/HaRe | old/testing/simplifyExpr/PatternIn3_TokOut.hs | bsd-3-clause | 137 | 0 | 9 | 61 | 64 | 33 | 31 | 6 | 2 |
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--short-names" @-}
{- LIQUID "--diff" @-}
module KMP (search) where
import Language.Haskell.Liquid.Prelude (liquidError, liquidAssert)
import Data.IORef
import Control.Applicative ((<$>))
import qualified Data.Map as M
import Prelude hiding (map)
{-@ type Upto N = {v:Nat | v < N} @-}
---------------------------------------------------------------------------
{-@ search :: pat:String -> str:String -> IO (Maybe (Upto (len str))) @-}
---------------------------------------------------------------------------
search :: String -> String -> IO (Maybe Int)
search pat str = do
p <- ofListIO pat
s <- ofListIO str
kmpSearch p s
---------------------------------------------------------------------------
-- | Do the Search --------------------------------------------------------
---------------------------------------------------------------------------
kmpSearch p@(IOA m _) s@(IOA n _) = do
t <- kmpTable p
find p s t 0 0
find p@(IOA m _) s@(IOA n _) t = go
where
go i j
| i >= n = return $ Nothing
| j >= m = return $ Just (i - m)
| otherwise = do si <- getIO s i
pj <- getIO p j
tj <- getIO t j
case () of
_ | si == pj -> go (i+1) (j+1)
| j == 0 -> go (i+1) j
| otherwise -> go i tj
---------------------------------------------------------------------------
-- | Make Table -----------------------------------------------------------
---------------------------------------------------------------------------
-- BUG WHAT's going on?
{-@ bob :: Nat -> IO () @-}
bob n = do
t <- newIO (n + 1) (\_ -> 0)
setIO t 0 100
r <- getIO t 0
liquidAssert (r == 0) $ return ()
kmpTable p@(IOA m _) = do
t <- newIO m (\_ -> 0)
fill p t 1 0
return t
fill p t@(IOA m _) = go
where
go i j
| i < m - 1 = do
pi <- getIO p (id i)
pj <- getIO p j
case () of
_ | pi == pj -> do
let i' = i + 1
let j' = j + 1
setIO t i' j'
go i' j'
| j == 0 -> do
let i' = i + 1
setIO t i' 0
go i' j
| otherwise -> do
j' <- getIO t j
go i j'
| otherwise = return t
-------------------------------------------------------------------------------
-- | An Imperative Array ------------------------------------------------------
-------------------------------------------------------------------------------
data IOArr a = IOA { size :: Int
, pntr :: IORef (Arr a)
}
{-@ data IOArr a <p :: Int -> a -> Prop>
= IOA { size :: Nat
, pntr :: IORef ({v:Arr<p> a | alen v = size})
}
@-}
{-@ newIO :: forall <p :: Int -> a -> Prop>.
n:Nat -> (i:Upto n -> a<p i>) -> IO ({v: IOArr<p> a | size v = n})
@-}
newIO n f = IOA n <$> newIORef (new n f)
{-@ getIO :: forall <p :: Int -> a -> Prop>.
a:IOArr<p> a -> i:Upto (size a) -> IO (a<p i>)
@-}
getIO a@(IOA sz p) i
= do arr <- readIORef p
return $ (arr ! i)
{-@ setIO :: forall <p :: Int -> a -> Prop>.
a:IOArr<p> a -> i:Upto (size a) -> a<p i> -> IO ()
@-}
setIO a@(IOA sz p) i v
= do arr <- readIORef p
let arr' = set arr i v
writeIORef p arr'
{-@ ofListIO :: xs:[a] -> IO ({v:IOArr a | size v = len xs}) @-}
ofListIO xs = newIO n f
where
n = length xs
m = M.fromList $ zip [0..] xs
f i = (M.!) m i
{-@ mapIO :: (a -> b) -> a:IOArr a -> IO ({v:IOArr b | size v = size a}) @-}
mapIO f (IOA n p)
= do a <- readIORef p
IOA n <$> newIORef (map f a)
-------------------------------------------------------------------------------
-- | A Pure Array -------------------------------------------------------------
-------------------------------------------------------------------------------
data Arr a = A { alen :: Int
, aval :: Int -> a
}
{-@ data Arr a <p :: Int -> a -> Prop>
= A { alen :: Nat
, aval :: i:Upto alen -> a<p i>
}
@-}
{-@ new :: forall <p :: Int -> a -> Prop>.
n:Nat -> (i:Upto n -> a<p i>) -> {v: Arr<p> a | alen v = n}
@-}
new n v = A { alen = n
, aval = \i -> if (0 <= i && i < n)
then v i
else liquidError "Out of Bounds!"
}
{-@ (!) :: forall <p :: Int -> a -> Prop>.
a:Arr<p> a -> i:Upto (alen a) -> a<p i>
@-}
(A _ f) ! i = f i
{-@ set :: forall <p :: Int -> a -> Prop>.
a:Arr<p> a -> i:Upto (alen a) -> a<p i> -> {v:Arr<p> a | alen v = alen a}
@-}
set a@(A _ f) i v = a { aval = \j -> if (i == j) then v else f j }
{-@ ofList :: xs:[a] -> {v:Arr a | alen v = len xs} @-}
ofList xs = new n f
where
n = length xs
m = M.fromList $ zip [0..] xs
f i = (M.!) m i
{-@ map :: (a -> b) -> a:Arr a -> {v:Arr b | alen v = alen a} @-}
map f a@(A n z) = A n (f . z)
| ssaavedra/liquidhaskell | tests/todo/kmpMonad.hs | bsd-3-clause | 5,260 | 0 | 19 | 1,806 | 1,310 | 659 | 651 | 83 | 2 |
{-# LANGUAGE FlexibleInstances, ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.GhcUtils
-- Copyright : (c) David Waern 2006-2009
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Utils for dealing with types from the GHC API
-----------------------------------------------------------------------------
module Haddock.GhcUtils where
import Control.Arrow
import Data.Function
import Exception
import Outputable
import Name
import Lexeme
import Module
import RdrName (GlobalRdrEnv)
import GhcMonad (withSession)
import HscTypes
import UniqFM
import GHC
import Class
moduleString :: Module -> String
moduleString = moduleNameString . moduleName
lookupLoadedHomeModuleGRE :: GhcMonad m => ModuleName -> m (Maybe GlobalRdrEnv)
lookupLoadedHomeModuleGRE mod_name = withSession $ \hsc_env ->
case lookupUFM (hsc_HPT hsc_env) mod_name of
Just mod_info -> return (mi_globals (hm_iface mod_info))
_not_a_home_module -> return Nothing
isNameSym :: Name -> Bool
isNameSym = isSymOcc . nameOccName
isVarSym :: OccName -> Bool
isVarSym = isLexVarSym . occNameFS
isConSym :: OccName -> Bool
isConSym = isLexConSym . occNameFS
getMainDeclBinder :: HsDecl name -> [name]
getMainDeclBinder (TyClD d) = [tcdName d]
getMainDeclBinder (ValD d) =
case collectHsBindBinders d of
[] -> []
(name:_) -> [name]
getMainDeclBinder (SigD d) = sigNameNoLoc d
getMainDeclBinder (ForD (ForeignImport name _ _ _)) = [unLoc name]
getMainDeclBinder (ForD (ForeignExport _ _ _ _)) = []
getMainDeclBinder _ = []
-- Extract the source location where an instance is defined. This is used
-- to correlate InstDecls with their Instance/CoAxiom Names, via the
-- instanceMap.
getInstLoc :: InstDecl name -> SrcSpan
getInstLoc (ClsInstD (ClsInstDecl { cid_poly_ty = L l _ })) = l
getInstLoc (DataFamInstD (DataFamInstDecl { dfid_tycon = L l _ })) = l
getInstLoc (TyFamInstD (TyFamInstDecl
-- Since CoAxioms' Names refer to the whole line for type family instances
-- in particular, we need to dig a bit deeper to pull out the entire
-- equation. This does not happen for data family instances, for some reason.
{ tfid_eqn = L _ (TyFamEqn { tfe_rhs = L l _ })})) = l
-- Useful when there is a signature with multiple names, e.g.
-- foo, bar :: Types..
-- but only one of the names is exported and we have to change the
-- type signature to only include the exported names.
filterLSigNames :: (name -> Bool) -> LSig name -> Maybe (LSig name)
filterLSigNames p (L loc sig) = L loc <$> (filterSigNames p sig)
filterSigNames :: (name -> Bool) -> Sig name -> Maybe (Sig name)
filterSigNames p orig@(SpecSig n _ _) = ifTrueJust (p $ unLoc n) orig
filterSigNames p orig@(InlineSig n _) = ifTrueJust (p $ unLoc n) orig
filterSigNames p (FixSig (FixitySig ns ty)) =
case filter (p . unLoc) ns of
[] -> Nothing
filtered -> Just (FixSig (FixitySig filtered ty))
filterSigNames _ orig@(MinimalSig _ _) = Just orig
filterSigNames p (TypeSig ns ty nwcs) =
case filter (p . unLoc) ns of
[] -> Nothing
filtered -> Just (TypeSig filtered ty nwcs)
filterSigNames _ _ = Nothing
ifTrueJust :: Bool -> name -> Maybe name
ifTrueJust True = Just
ifTrueJust False = const Nothing
sigName :: LSig name -> [name]
sigName (L _ sig) = sigNameNoLoc sig
sigNameNoLoc :: Sig name -> [name]
sigNameNoLoc (TypeSig ns _ _) = map unLoc ns
sigNameNoLoc (PatSynSig n _ _ _ _) = [unLoc n]
sigNameNoLoc (SpecSig n _ _) = [unLoc n]
sigNameNoLoc (InlineSig n _) = [unLoc n]
sigNameNoLoc (FixSig (FixitySig ns _)) = map unLoc ns
sigNameNoLoc _ = []
isTyClD :: HsDecl a -> Bool
isTyClD (TyClD _) = True
isTyClD _ = False
isClassD :: HsDecl a -> Bool
isClassD (TyClD d) = isClassDecl d
isClassD _ = False
isDocD :: HsDecl a -> Bool
isDocD (DocD _) = True
isDocD _ = False
isInstD :: HsDecl a -> Bool
isInstD (InstD _) = True
isInstD _ = False
isValD :: HsDecl a -> Bool
isValD (ValD _) = True
isValD _ = False
declATs :: HsDecl a -> [a]
declATs (TyClD d) | isClassDecl d = map (unL . fdLName . unL) $ tcdATs d
declATs _ = []
pretty :: Outputable a => DynFlags -> a -> String
pretty = showPpr
trace_ppr :: Outputable a => DynFlags -> a -> b -> b
trace_ppr dflags x y = trace (pretty dflags x) y
-------------------------------------------------------------------------------
-- * Located
-------------------------------------------------------------------------------
unL :: Located a -> a
unL (L _ x) = x
reL :: a -> Located a
reL = L undefined
before :: Located a -> Located a -> Bool
before = (<) `on` getLoc
-------------------------------------------------------------------------------
-- * NamedThing instances
-------------------------------------------------------------------------------
instance NamedThing (TyClDecl Name) where
getName = tcdName
-------------------------------------------------------------------------------
-- * Subordinates
-------------------------------------------------------------------------------
class Parent a where
children :: a -> [Name]
instance Parent (ConDecl Name) where
children con =
case con_details con of
RecCon fields -> map unL $ concatMap (cd_fld_names . unL) (unL fields)
_ -> []
instance Parent (TyClDecl Name) where
children d
| isDataDecl d = map unL $ concatMap (con_names . unL)
$ (dd_cons . tcdDataDefn) $ d
| isClassDecl d =
map (unL . fdLName . unL) (tcdATs d) ++
[ unL n | L _ (TypeSig ns _ _) <- tcdSigs d, n <- ns ]
| otherwise = []
-- | A parent and its children
family :: (NamedThing a, Parent a) => a -> (Name, [Name])
family = getName &&& children
familyConDecl :: ConDecl Name -> [(Name, [Name])]
familyConDecl d = zip (map unL (con_names d)) (repeat $ children d)
-- | A mapping from the parent (main-binder) to its children and from each
-- child to its grand-children, recursively.
families :: TyClDecl Name -> [(Name, [Name])]
families d
| isDataDecl d = family d : concatMap (familyConDecl . unL) (dd_cons (tcdDataDefn d))
| isClassDecl d = [family d]
| otherwise = []
-- | A mapping from child to parent
parentMap :: TyClDecl Name -> [(Name, Name)]
parentMap d = [ (c, p) | (p, cs) <- families d, c <- cs ]
-- | The parents of a subordinate in a declaration
parents :: Name -> HsDecl Name -> [Name]
parents n (TyClD d) = [ p | (c, p) <- parentMap d, c == n ]
parents _ _ = []
-------------------------------------------------------------------------------
-- * Utils that work in monads defined by GHC
-------------------------------------------------------------------------------
modifySessionDynFlags :: (DynFlags -> DynFlags) -> Ghc ()
modifySessionDynFlags f = do
dflags <- getSessionDynFlags
_ <- setSessionDynFlags (f dflags)
return ()
-- | A variant of 'gbracket' where the return value from the first computation
-- is not required.
gbracket_ :: ExceptionMonad m => m a -> m b -> m c -> m c
gbracket_ before_ after thing = gbracket before_ (const after) (const thing)
-- Extract the minimal complete definition of a Name, if one exists
minimalDef :: GhcMonad m => Name -> m (Maybe ClassMinimalDef)
minimalDef n = do
mty <- lookupGlobalName n
case mty of
Just (ATyCon (tyConClass_maybe -> Just c)) -> return . Just $ classMinimalDef c
_ -> return Nothing
-------------------------------------------------------------------------------
-- * DynFlags
-------------------------------------------------------------------------------
setObjectDir, setHiDir, setStubDir, setOutputDir :: String -> DynFlags -> DynFlags
setObjectDir f d = d{ objectDir = Just f}
setHiDir f d = d{ hiDir = Just f}
setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
-- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
-- \#included from the .hc file when compiling with -fvia-C.
setOutputDir f = setObjectDir f . setHiDir f . setStubDir f
| adamse/haddock | haddock-api/src/Haddock/GhcUtils.hs | bsd-2-clause | 8,294 | 0 | 17 | 1,667 | 2,462 | 1,266 | 1,196 | 149 | 3 |
module ShouldFail where
data Test a = T a
deriving( Show a, Read )
| hferreiro/replay | testsuite/tests/deriving/should_fail/drvfail005.hs | bsd-3-clause | 71 | 0 | 6 | 18 | 27 | 16 | 11 | 3 | 0 |
-- Copyright (C) 2013 Jorge Aparicio
main :: IO()
main = do
contents <- readFile "018.in"
let triangle = map (map read . words) $ lines contents :: [[Int]]
print . maximum . foldl1 traverse $ triangle
traverse
:: [Int] -- previous row
-> [Int] -- current row
-> [Int] -- traversed row
traverse p = traverse' (0 : p)
traverse' :: [Int] -> [Int] -> [Int]
traverse' [p] [c] = [p+c]
traverse' (p1:p2:ps) (c:cs) = (c + max p1 p2) : traverse' (p2:ps) cs
| japaric/eulermark | problems/0/1/8/018.hs | mit | 467 | 0 | 14 | 104 | 227 | 120 | 107 | 13 | 1 |
divisors n = filter (\x -> n `mod` x == 0) [1..n-1]
abundant x = (sum $ divisors x) > x
maxSum = sum [1..28123]
abundants = filter abundant [1..28123]
abundantCombs = filter (<=28123) $ zipWith (+) abundants abundants
answer = maxSum - (sum abundantCombs)
| tamasgal/haskell_exercises | ProjectEuler/p023.hs | mit | 256 | 0 | 9 | 45 | 131 | 70 | 61 | 6 | 1 |
module Stackage.Database
( module X
) where
import Stackage.Database.Schema as X
import Stackage.Database.Query as X
import Stackage.Database.Types as X
| fpco/stackage-server | src/Stackage/Database.hs | mit | 161 | 0 | 4 | 27 | 36 | 26 | 10 | 5 | 0 |
{-# LANGUAGE GADTs, StandaloneDeriving,DeriveFunctor, TypeSynonymInstances, FlexibleInstances #-}
module Main where
import Context
import Lang
import Parse
import Debug.Trace
import Data.List
import Data.Function
import Data.Set (Set,member)
import Control.Applicative
import Control.Monad
import qualified Data.Set as Set
countTo :: Expr
countTo = (Lam "y"
(If (BinOp Equal (Ident "y") (Lit (LInt 1)))
(Lit (LInt 1))
(BinOp Plus
(App (Ident "countTo") (BinOp Minus (Ident "y") (Lit (LInt 1))))
(Lit (LInt 1))
)
))
addOne :: Expr
addOne = (Lam "w" (BinOp Plus (Ident "w") (Lit (LInt 1))))
addTwo :: Expr
addTwo = (Lam "w" (BinOp Plus (Ident "w") (Lit (LInt 2))))
mult :: Expr
mult = (Lam "x" (Lam "y"
(If (BinOp Equal
(Ident "x")
(Lit (LInt 0)))
(Lit $ LInt 0)
(BinOp Plus
(Ident "y")
(App (App (Ident "mult") (BinOp Minus (Ident "x") (Lit (LInt 1)))) (Ident "y"))
)
)))
fact :: Expr
fact = (Lam "x"
(If (BinOp Equal
(Ident "x")
(Lit (LInt 0))
)
(Lit (LInt 1))
(BinOp Times
(Ident "x") (App (Ident "fact") (BinOp Minus (Ident "x") (Lit (LInt 1))))
)
)
)
appList :: Expr -> [Expr] -> Expr
appList lam (e : []) = App lam e
appList lam (e : es) = appList (App lam e) es
top = (Lam "x" (Lam "y" (Ident "x")))
env :: Env
env = [Bind "mult" mult]
test = appList (Ident "mult") [(Lit $ LInt 3), (Lit $ LInt 4)]
prog :: State
prog = State
[Bind "fact" fact,
Bind "countTo" countTo,
Bind "mult" mult,
Bind "result" (App (Ident "countTo") (App (Ident "fact") (Lit (LInt 4)))),
Bind "r2" $ appList (Ident "mult") [(Ident "result"), (Lit $ LInt 4)]
]
[]
main :: IO ()
main = forever $ do
input <- getLine
putStrLn $ "> " ++ show (manyStep $ fst $ (parse parseExpr input)!!0)
yc :: Expr
yc = fst ((Parse.parse Parse.parseExpr "(\\f -> ((\\x -> (f (x x))) (\\x -> (f (x x)))))") !! 0)
fact' :: Expr
fact' = fst ((Parse.parse Parse.parseExpr "(\\f -> (\\x -> if (x == 0) then 1 else (x * (f (-1 + x)))))") !! 0)
| jdublu10/toy_lang | src/Main.hs | mit | 2,329 | 0 | 22 | 775 | 972 | 506 | 466 | 63 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.Geolocation (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Geolocation
#else
module Graphics.UI.Gtk.WebKit.DOM.Geolocation
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Geolocation
#else
import Graphics.UI.Gtk.WebKit.DOM.Geolocation
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/Geolocation.hs | mit | 420 | 0 | 5 | 39 | 31 | 24 | 7 | 4 | 0 |
Subsets and Splits