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 Graphics.UI.Threepenny.Elements.ID where
import Graphics.UI.Threepenny.Attributes.Extra
import Graphics.UI.Threepenny.Extra
import Data.UUID
import Data.UUID.V4
newtype UID = UID
{ unUID :: String
} deriving (Eq,Ord,Show)
newID :: UI UID
newID = liftIO $ shortenUUID <$> nextRandom
shortenUUID :: UUID -> UID
shortenUUID = UID . takeWhile (/= '-') . toString
uid :: MAttr Element UID
uid = strMAttr "id"
& bimapAttr unUID (fmap UID)
identify :: Widget w => w -> UI UID
identify w = do
i <- newID
element w # set uid i
return i
type Selector = String
selUID :: UID -> Selector
selUID = ('#':) . unUID
toVar :: UID -> String
toVar = unUID
byUID :: Identified a => a -> Selector
byUID = selUID . getUID
jsVar :: Identified a => a -> String
jsVar = (\p i -> p ++ "_" ++ i)
<$> jsVarPrefix
<*> toVar . getUID
class Identified a where
getUID :: a -> UID
jsVarPrefix :: a -> String
| kylcarte/threepenny-extra | src/Graphics/UI/Threepenny/Elements/ID.hs | bsd-3-clause | 921 | 0 | 11 | 197 | 346 | 188 | 158 | 34 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Applicative ((<**>), (<|>), optional)
import Data.Char (toLower)
import Data.Semigroup ((<>))
import System.IO (IOMode (WriteMode), stdout, openFile)
import Genotype.Comparison (PhaseKnowledge (..))
import Genotype.Processor (Processor, preprocess)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Genotype.Parser.FastPhase as FastPhase
import qualified Genotype.Printer.Arlequin as Arlequin
import qualified Genotype.Printer.Geno as Geno
import qualified Genotype.Processor.KeepColumnNumbers as KeepColumns
import qualified Options.Applicative as O
data InputFormat
= FastPhase
deriving (Eq, Show)
parseInputFormat :: O.Parser InputFormat
parseInputFormat =
O.option (O.maybeReader formats)
( O.long "input-format"
<> O.metavar "NAME"
<> O.help "Select from: fastphase"
)
where
formats str = case map toLower str of
"fastphase" -> Just FastPhase
_ -> Nothing
data InputSource
= STDIN
| InputFile T.Text
deriving (Eq, Show)
parseInputSourceFile :: O.Parser InputSource
parseInputSourceFile =
InputFile . T.pack <$> O.strOption
( O.long "input-file"
<> O.metavar "FILENAME"
<> O.help "Input file"
)
parseInputSource :: O.Parser InputSource
parseInputSource = parseInputSourceFile <|> pure STDIN
data OutputFormat
= Arlequin
| Geno
deriving (Eq, Show)
parseOutputFormat :: O.Parser OutputFormat
parseOutputFormat =
O.option (O.maybeReader formats)
( O.long "output-format"
<> O.metavar "NAME"
<> O.help "Select from: arlequin, geno"
)
where
formats str = case map toLower str of
"arlequin" -> Just Arlequin
"geno" -> Just Geno
_ -> Nothing
data OutputSink
= STDOUT
| OutputFile T.Text
deriving (Eq, Show)
parseOutputSinkFile :: O.Parser OutputSink
parseOutputSinkFile =
OutputFile . T.pack <$> O.strOption
( O.long "output-file"
<> O.metavar "FILENAME"
<> O.help "Output file"
)
parseOutputSink :: O.Parser OutputSink
parseOutputSink = parseOutputSinkFile <|> pure STDOUT
parseFilterColumns :: O.Parser (Maybe T.Text)
parseFilterColumns =
optional $ T.pack <$> O.strOption
( O.long "keep-columns"
<> O.metavar "FILENAME"
<> O.help "File containing list of column numbers to keep"
)
parsePhaseKnown :: O.Parser PhaseKnowledge
parsePhaseKnown =
O.flag Unknown Known
( O.long "phase-known"
<> O.help "Differeniate between phases in comparison output"
)
data Options = Options
{ opt_inputFormat :: InputFormat
, opt_inputSource :: InputSource
, opt_outputFormat :: OutputFormat
, opt_outputSink :: OutputSink
, opt_filterColumns :: Maybe T.Text
, opt_phaseKnown :: PhaseKnowledge
} deriving (Eq, Show)
parseOptions :: O.Parser Options
parseOptions =
Options
<$> parseInputFormat
<*> parseInputSource
<*> parseOutputFormat
<*> parseOutputSink
<*> parseFilterColumns
<*> parsePhaseKnown
parseOptionsWithInfo :: O.ParserInfo Options
parseOptionsWithInfo =
O.info
(parseOptions <**> O.helper)
(O.header "genotype-parser - parser and printer of genotype data formats")
-- TODO: ensure output file handle closes after use
main :: IO ()
main = do
opts <- O.execParser parseOptionsWithInfo
input <- case opt_inputSource opts of
InputFile file -> T.readFile $ T.unpack file
STDIN -> T.getContents
parsed <- either fail return $ case opt_inputFormat opts of
FastPhase -> FastPhase.runParser input
processed <- preprocess parsed $ preprocessors opts
sink <- case opt_outputSink opts of
OutputFile file -> openFile (T.unpack file) WriteMode
STDOUT -> return stdout
case opt_outputFormat opts of
Arlequin -> Arlequin.print (opt_phaseKnown opts) sink processed
Geno -> Geno.print (opt_phaseKnown opts) sink processed
preprocessors :: Options -> [Processor]
preprocessors = maybe [] (\f -> [KeepColumns.process f]) . opt_filterColumns
| Jonplussed/genotype-parser | app/Main.hs | bsd-3-clause | 4,008 | 0 | 14 | 760 | 1,100 | 579 | 521 | 115 | 4 |
{- It can be verified that there are 23 positive integers less than 1000 that are divisible by at least four distinct primes less than 100.
Find how many positive integers less than 10^16 are divisible by at least four distinct primes less than 100. -}
{-# LANGUAGE ScopedTypeVariables #-}
import qualified Zora.List as ZList
import qualified Zora.Math as ZMath
import qualified Data.Ord as Ord
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Numbers.Primes as Primes
import qualified Data.MemoCombinators as Memo
import Data.Maybe
import Data.Ratio
import Data.Function
import Debug.Trace
import Data.Monoid
import Control.Monad
import Control.Applicative
ub :: Integer
ub = 1000
primes :: [Integer]
primes = takeWhile (< 100) ZMath.primes
prime_sets :: [[Integer]]
prime_sets
= takeWhile (any (< ub))
. map (map product . ZList.subsets_of_size primes)
$ [4..]
main :: IO ()
main = do
putStrLn . show $ prime_sets
| bgwines/project-euler | src/in progress/problem269.hs | bsd-3-clause | 1,042 | 2 | 11 | 171 | 231 | 143 | 88 | 29 | 1 |
module Yesod.Goodies.PNotify.Modules.Nonblock
( Nonblock(..)
, defaultNonblock
)where
import Data.Aeson
import Data.Text (Text)
import Yesod.Goodies.PNotify.Types
import Yesod.Goodies.PNotify.Types.Instances
data Nonblock = Nonblock { _nonblock :: Maybe Bool
, _nonblock_opacity :: Maybe Double
}
deriving (Read, Show, Eq, Ord)
instance FromJSON Nonblock where
parseJSON (Object v) = Nonblock <$>
v .:? "nonblock" <*>
v .:? "nonblock_opacity"
instance ToJSON Nonblock where
toJSON (Nonblock { _nonblock
, _nonblock_opacity
})
= object $ maybe [] (\x -> ["nonblock" .= x]) _nonblock ++
maybe [] (\x -> ["nonblock_opacity" .= x]) _nonblock_opacity ++
[]
defaultNonblock :: Nonblock
defaultNonblock = Nonblock
{ _nonblock = Nothing
, _nonblock_opacity = Nothing
}
| cutsea110/yesod-pnotify | Yesod/Goodies/PNotify/Modules/Nonblock.hs | bsd-3-clause | 1,058 | 0 | 13 | 398 | 249 | 142 | 107 | -1 | -1 |
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE CPP #-}
{-|
This module defines a generic web application interface. It is a common
protocol between web servers and web applications.
The overriding design principles here are performance and generality. To
address performance, this library is built on top of the conduit and
blaze-builder packages. The advantages of conduits over lazy IO have been
debated elsewhere and so will not be addressed here. However, helper functions
like 'responseLBS' allow you to continue using lazy IO if you so desire.
Generality is achieved by removing many variables commonly found in similar
projects that are not universal to all servers. The goal is that the 'Request'
object contains only data which is meaningful in all circumstances.
Please remember when using this package that, while your application may
compile without a hitch against many different servers, there are other
considerations to be taken when moving to a new backend. For example, if you
transfer from a CGI application to a FastCGI one, you might suddenly find you
have a memory leak. Conversely, a FastCGI application would be well served to
preload all templates from disk when first starting; this would kill the
performance of a CGI application.
This package purposely provides very little functionality. You can find various
middlewares, backends and utilities on Hackage. Some of the most commonly used
include:
[warp] <http://hackage.haskell.org/package/warp>
[wai-extra] <http://hackage.haskell.org/package/wai-extra>
[wai-test] <http://hackage.haskell.org/package/wai-test>
-}
module Network.Wai
(
-- * Types
Application
, Middleware
, ResponseReceived
-- * Request
, Request
, defaultRequest
, RequestBodyLength (..)
-- ** Request accessors
, requestMethod
, httpVersion
, rawPathInfo
, rawQueryString
, requestHeaders
, isSecure
, remoteHost
, pathInfo
, queryString
, requestBody
, vault
, requestBodyLength
, requestHeaderHost
, requestHeaderRange
, lazyRequestBody
-- * Response
, Response
, StreamingBody
, FilePart (..)
-- ** Response composers
, responseFile
, responseBuilder
, responseLBS
, responseStream
, responseRaw
-- * Response accessors
, responseStatus
, responseHeaders
, responseToStream
) where
import Blaze.ByteString.Builder (Builder, fromLazyByteString)
import Blaze.ByteString.Builder (fromByteString)
import Control.Monad (unless)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Internal as LI
import Data.ByteString.Lazy.Internal (defaultChunkSize)
import Data.ByteString.Lazy.Char8 ()
import Data.Function (fix)
import Data.Monoid (mempty)
import qualified Network.HTTP.Types as H
import Network.Socket (SockAddr (SockAddrInet))
import Network.Wai.Internal
import qualified System.IO as IO
import System.IO.Unsafe (unsafeInterleaveIO)
----------------------------------------------------------------
-- | Creating 'Response' from a file.
responseFile :: H.Status -> H.ResponseHeaders -> FilePath -> Maybe FilePart -> Response
responseFile = ResponseFile
-- | Creating 'Response' from 'Builder'.
--
-- Some questions and answers about the usage of 'Builder' here:
--
-- Q1. Shouldn't it be at the user's discretion to use Builders internally and
-- then create a stream of ByteStrings?
--
-- A1. That would be less efficient, as we wouldn't get cheap concatenation
-- with the response headers.
--
-- Q2. Isn't it really inefficient to convert from ByteString to Builder, and
-- then right back to ByteString?
--
-- A2. No. If the ByteStrings are small, then they will be copied into a larger
-- buffer, which should be a performance gain overall (less system calls). If
-- they are already large, then blaze-builder uses an InsertByteString
-- instruction to avoid copying.
--
-- Q3. Doesn't this prevent us from creating comet-style servers, since data
-- will be cached?
--
-- A3. You can force blaze-builder to output a ByteString before it is an
-- optimal size by sending a flush command.
responseBuilder :: H.Status -> H.ResponseHeaders -> Builder -> Response
responseBuilder = ResponseBuilder
-- | Creating 'Response' from 'L.ByteString'. This is a wrapper for
-- 'responseBuilder'.
responseLBS :: H.Status -> H.ResponseHeaders -> L.ByteString -> Response
responseLBS s h = ResponseBuilder s h . fromLazyByteString
-- | Creating 'Response' from 'C.Source'.
responseStream :: H.Status
-> H.ResponseHeaders
-> StreamingBody
-> Response
responseStream = ResponseStream
-- | Create a response for a raw application. This is useful for \"upgrade\"
-- situations such as WebSockets, where an application requests for the server
-- to grant it raw network access.
--
-- This function requires a backup response to be provided, for the case where
-- the handler in question does not support such upgrading (e.g., CGI apps).
--
-- In the event that you read from the request body before returning a
-- @responseRaw@, behavior is undefined.
--
-- Since 2.1.0
responseRaw :: (IO B.ByteString -> (B.ByteString -> IO ()) -> IO ())
-> Response
-> Response
responseRaw = ResponseRaw
----------------------------------------------------------------
-- | Accessing 'H.Status' in 'Response'.
responseStatus :: Response -> H.Status
responseStatus (ResponseFile s _ _ _) = s
responseStatus (ResponseBuilder s _ _ ) = s
responseStatus (ResponseStream s _ _ ) = s
responseStatus (ResponseRaw _ res ) = responseStatus res
-- | Accessing 'H.ResponseHeaders' in 'Response'.
responseHeaders :: Response -> H.ResponseHeaders
responseHeaders (ResponseFile _ hs _ _) = hs
responseHeaders (ResponseBuilder _ hs _ ) = hs
responseHeaders (ResponseStream _ hs _ ) = hs
responseHeaders (ResponseRaw _ res) = responseHeaders res
-- | Converting the body information in 'Response' to 'Source'.
responseToStream :: Response
-> ( H.Status
, H.ResponseHeaders
, (StreamingBody -> IO a) -> IO a
)
responseToStream (ResponseStream s h b) = (s, h, ($ b))
responseToStream (ResponseFile s h fp (Just part)) =
( s
, h
, \withBody -> IO.withBinaryFile fp IO.ReadMode $ \handle -> withBody $ \sendChunk _flush -> do
IO.hSeek handle IO.AbsoluteSeek $ filePartOffset part
let loop remaining | remaining <= 0 = return ()
loop remaining = do
bs <- B.hGetSome handle defaultChunkSize
unless (B.null bs) $ do
let x = B.take remaining bs
sendChunk $ fromByteString x
loop $ remaining - B.length x
loop $ fromIntegral $ filePartByteCount part
)
responseToStream (ResponseFile s h fp Nothing) =
( s
, h
, \withBody -> IO.withBinaryFile fp IO.ReadMode $ \handle ->
withBody $ \sendChunk _flush -> fix $ \loop -> do
bs <- B.hGetSome handle defaultChunkSize
unless (B.null bs) $ do
sendChunk $ fromByteString bs
loop
)
responseToStream (ResponseBuilder s h b) =
(s, h, \withBody -> withBody $ \sendChunk _flush -> sendChunk b)
responseToStream (ResponseRaw _ res) = responseToStream res
----------------------------------------------------------------
-- | The WAI application.
type Application = Request -> (Response -> IO ResponseReceived) -> IO ResponseReceived
-- | Middleware is a component that sits between the server and application. It
-- can do such tasks as GZIP encoding or response caching. What follows is the
-- general definition of middleware, though a middleware author should feel
-- free to modify this.
--
-- As an example of an alternate type for middleware, suppose you write a
-- function to load up session information. The session information is simply a
-- string map \[(String, String)\]. A logical type signature for this middleware
-- might be:
--
-- @ loadSession :: ([(String, String)] -> Application) -> Application @
--
-- Here, instead of taking a standard 'Application' as its first argument, the
-- middleware takes a function which consumes the session information as well.
type Middleware = Application -> Application
-- | A default, blank request.
--
-- Since 2.0.0
defaultRequest :: Request
defaultRequest = Request
{ requestMethod = H.methodGet
, httpVersion = H.http10
, rawPathInfo = B.empty
, rawQueryString = B.empty
, requestHeaders = []
, isSecure = False
, remoteHost = SockAddrInet 0 0
, pathInfo = []
, queryString = []
, requestBody = return B.empty
, vault = mempty
, requestBodyLength = KnownLength 0
, requestHeaderHost = Nothing
, requestHeaderRange = Nothing
}
-- | Get the request body as a lazy ByteString. This uses lazy I\/O under the
-- surface, and therefore all typical warnings regarding lazy I/O apply.
--
-- Since 1.4.1
lazyRequestBody :: Request -> IO L.ByteString
lazyRequestBody req =
loop
where
loop = unsafeInterleaveIO $ do
bs <- requestBody req
if B.null bs
then return LI.Empty
else do
bss <- loop
return $ LI.Chunk bs bss
| sol/wai | wai/Network/Wai.hs | mit | 9,632 | 0 | 25 | 2,273 | 1,399 | 796 | 603 | 134 | 2 |
{-|
Low-Level Inferface for LMDB Event Log.
-}
module Urbit.Vere.LMDB where
import Urbit.Prelude hiding (init)
import Data.RAcquire
import Database.LMDB.Raw
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Urbit.Vere.Pier.Types
import Foreign.Storable (peek, poke, sizeOf)
import qualified Data.ByteString.Unsafe as BU
-- Types -----------------------------------------------------------------------
type Env = MDB_env
type Val = MDB_val
type Txn = MDB_txn
type Dbi = MDB_dbi
type Cur = MDB_cursor
data VereLMDBExn
= NoLogIdentity
| MissingEvent EventId
| BadNounInLogIdentity ByteString DecodeErr ByteString
| BadKeyInEventLog
| BadWriteLogIdentity LogIdentity
| BadWriteEvent EventId
| BadWriteEffect EventId
deriving Show
instance Exception VereLMDBExn where
-- Transactions ----------------------------------------------------------------
{-|
A read-only transaction that commits at the end.
Use this when opening database handles.
-}
openTxn :: Env -> RAcquire e Txn
openTxn env = mkRAcquire begin commit
where
begin = io $ mdb_txn_begin env Nothing True
commit = io . mdb_txn_commit
{-|
A read-only transaction that aborts at the end.
Use this when reading data from already-opened databases.
-}
readTxn :: Env -> RAcquire e Txn
readTxn env = mkRAcquire begin abort
where
begin = io $ mdb_txn_begin env Nothing True
abort = io . mdb_txn_abort
{-|
A read-write transaction that commits upon sucessful completion and
aborts on exception.
Use this when reading data from already-opened databases.
-}
writeTxn :: Env -> RAcquire e Txn
writeTxn env = mkRAcquireType begin finalize
where
begin = io $ mdb_txn_begin env Nothing False
finalize txn = io . \case
ReleaseNormal -> mdb_txn_commit txn
ReleaseEarly -> mdb_txn_commit txn
ReleaseException -> mdb_txn_abort txn
-- Cursors ---------------------------------------------------------------------
cursor :: Txn -> Dbi -> RAcquire e Cur
cursor txn dbi = mkRAcquire open close
where
open = io $ mdb_cursor_open txn dbi
close = io . mdb_cursor_close
-- Last Key In Dbi -------------------------------------------------------------
lastKeyWord64 :: Env -> Dbi -> Txn -> RIO e Word64
lastKeyWord64 env dbi txn =
rwith (cursor txn dbi) $ \cur ->
withKVPtrs' nullVal nullVal $ \pKey pVal ->
io $ mdb_cursor_get MDB_LAST cur pKey pVal >>= \case
False -> pure 0
True -> peek pKey >>= mdbValToWord64
-- Delete Rows -----------------------------------------------------------------
deleteAllRows :: Env -> Dbi -> RIO e ()
deleteAllRows env dbi =
rwith (writeTxn env) $ \txn ->
rwith (cursor txn dbi) $ \cur ->
withKVPtrs' nullVal nullVal $ \pKey pVal -> do
let loop = io (mdb_cursor_get MDB_LAST cur pKey pVal) >>= \case
False -> pure ()
True -> do io $ mdb_cursor_del (compileWriteFlags []) cur
loop
loop
deleteRowsFrom :: HasLogFunc e => Env -> Dbi -> Word64 -> RIO e ()
deleteRowsFrom env dbi start = do
rwith (writeTxn env) $ \txn -> do
last <- lastKeyWord64 env dbi txn
for_ [start..last] $ \eId -> do
withWordPtr eId $ \pKey -> do
let key = MDB_val 8 (castPtr pKey)
found <- io $ mdb_del txn dbi key Nothing
unless found $
throwIO (MissingEvent eId)
-- Append Rows to Sequence -----------------------------------------------------
{-
appendToSequence :: Env -> Dbi -> Vector ByteString -> RIO e ()
appendToSequence env dbi events = do
numEvs <- readIORef (numEvents log)
next <- pure (numEvs + 1)
doAppend $ zip [next..] $ toList events
writeIORef (numEvents log) (numEvs + word (length events))
where
flags = compileWriteFlags [MDB_NOOVERWRITE]
doAppend = \kvs ->
rwith (writeTxn env) $ \txn ->
for_ kvs $ \(k,v) -> do
putBytes flags txn dbi k v >>= \case
True -> pure ()
False -> throwIO (BadWriteEvent k)
-}
-- Insert ----------------------------------------------------------------------
insertWord64 :: Env -> Dbi -> Word64 -> ByteString -> RIO e ()
insertWord64 env dbi k v = do
rwith (writeTxn env) $ \txn ->
putBytes flags txn dbi k v >>= \case
True -> pure ()
False -> throwIO (BadWriteEffect k)
where
flags = compileWriteFlags []
{-
--------------------------------------------------------------------------------
-- Read Events -----------------------------------------------------------------
streamEvents :: HasLogFunc e
=> EventLog -> Word64
-> ConduitT () ByteString (RIO e) ()
streamEvents log first = do
last <- lift $ lastEv log
batch <- lift $ readBatch log first
unless (null batch) $ do
for_ batch yield
streamEvents log (first + word (length batch))
streamEffectsRows :: ∀e. HasLogFunc e
=> EventLog -> EventId
-> ConduitT () (Word64, ByteString) (RIO e) ()
streamEffectsRows log = go
where
go :: EventId -> ConduitT () (Word64, ByteString) (RIO e) ()
go next = do
batch <- lift $ readRowsBatch (env log) (effectsTbl log) next
unless (null batch) $ do
for_ batch yield
go (next + fromIntegral (length batch))
{-
Read 1000 rows from the events table, starting from event `first`.
Throws `MissingEvent` if an event was missing from the log.
-}
readBatch :: EventLog -> Word64 -> RIO e (V.Vector ByteString)
readBatch log first = start
where
start = do
last <- lastEv log
if (first > last)
then pure mempty
else readRows $ fromIntegral $ min 1000 $ ((last+1) - first)
assertFound :: EventId -> Bool -> RIO e ()
assertFound id found = do
unless found $ throwIO $ MissingEvent id
readRows count =
withWordPtr first $ \pIdx ->
withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal ->
rwith (readTxn $ env log) $ \txn ->
rwith (cursor txn $ eventsTbl log) $ \cur -> do
assertFound first =<< io (mdb_cursor_get MDB_SET_KEY cur pKey pVal)
fetchRows count cur pKey pVal
fetchRows count cur pKey pVal = do
env <- ask
V.generateM count $ \i -> runRIO env $ do
key <- io $ peek pKey >>= mdbValToWord64
val <- io $ peek pVal >>= mdbValToBytes
idx <- pure (first + word i)
unless (key == idx) $ throwIO $ MissingEvent idx
when (count /= succ i) $ do
assertFound idx =<< io (mdb_cursor_get MDB_NEXT cur pKey pVal)
pure val
{-
Read 1000 rows from the database, starting from key `first`.
-}
readRowsBatch :: ∀e. HasLogFunc e
=> Env -> Dbi -> Word64 -> RIO e (V.Vector (Word64, ByteString))
readRowsBatch env dbi first = readRows
where
readRows = do
logDebug $ display ("(readRowsBatch) From: " <> tshow first)
withWordPtr first $ \pIdx ->
withKVPtrs' (MDB_val 8 (castPtr pIdx)) nullVal $ \pKey pVal ->
rwith (readTxn env) $ \txn ->
rwith (cursor txn dbi) $ \cur ->
io (mdb_cursor_get MDB_SET_RANGE cur pKey pVal) >>= \case
False -> pure mempty
True -> V.unfoldrM (fetchBatch cur pKey pVal) 1000
fetchBatch :: Cur -> Ptr Val -> Ptr Val -> Word
-> RIO e (Maybe ((Word64, ByteString), Word))
fetchBatch cur pKey pVal 0 = pure Nothing
fetchBatch cur pKey pVal n = do
key <- io $ peek pKey >>= mdbValToWord64
val <- io $ peek pVal >>= mdbValToBytes
io $ mdb_cursor_get MDB_NEXT cur pKey pVal >>= \case
False -> pure $ Just ((key, val), 0)
True -> pure $ Just ((key, val), pred n)
-}
-- Utils -----------------------------------------------------------------------
withKVPtrs' :: (MonadIO m, MonadUnliftIO m)
=> Val -> Val -> (Ptr Val -> Ptr Val -> m a) -> m a
withKVPtrs' k v cb =
withRunInIO $ \run ->
withKVPtrs k v $ \x y -> run (cb x y)
nullVal :: MDB_val
nullVal = MDB_val 0 nullPtr
word :: Int -> Word64
word = fromIntegral
assertExn :: Exception e => Bool -> e -> IO ()
assertExn True _ = pure ()
assertExn False e = throwIO e
eitherExn :: Exception e => Either a b -> (a -> e) -> IO b
eitherExn eat exn = either (throwIO . exn) pure eat
byteStringAsMdbVal :: ByteString -> (MDB_val -> IO a) -> IO a
byteStringAsMdbVal bs k =
BU.unsafeUseAsCStringLen bs $ \(ptr,sz) ->
k (MDB_val (fromIntegral sz) (castPtr ptr))
mdbValToWord64 :: MDB_val -> IO Word64
mdbValToWord64 (MDB_val sz ptr) = do
assertExn (sz == 8) BadKeyInEventLog
peek (castPtr ptr)
withWord64AsMDBval :: (MonadIO m, MonadUnliftIO m)
=> Word64 -> (MDB_val -> m a) -> m a
withWord64AsMDBval w cb = do
withWordPtr w $ \p ->
cb (MDB_val (fromIntegral (sizeOf w)) (castPtr p))
withWordPtr :: (MonadIO m, MonadUnliftIO m)
=> Word64 -> (Ptr Word64 -> m a) -> m a
withWordPtr w cb =
withRunInIO $ \run ->
allocaBytes (sizeOf w) (\p -> poke p w >> run (cb p))
-- Lower-Level Operations ------------------------------------------------------
getMb :: MonadIO m => Txn -> Dbi -> ByteString -> m (Maybe Noun)
getMb txn db key =
io $
byteStringAsMdbVal key $ \mKey ->
mdb_get txn db mKey >>= traverse (mdbValToNoun key)
mdbValToBytes :: MDB_val -> IO ByteString
mdbValToBytes (MDB_val sz ptr) = do
BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz)
mdbValToNoun :: ByteString -> MDB_val -> IO Noun
mdbValToNoun key (MDB_val sz ptr) = do
bs <- BU.unsafePackCStringLen (castPtr ptr, fromIntegral sz)
let res = cueBS bs
eitherExn res (\err -> BadNounInLogIdentity key err bs)
putNoun :: MonadIO m
=> MDB_WriteFlags -> Txn -> Dbi -> ByteString -> Noun -> m Bool
putNoun flags txn db key val =
io $
byteStringAsMdbVal key $ \mKey ->
byteStringAsMdbVal (jamBS val) $ \mVal ->
mdb_put flags txn db mKey mVal
putBytes :: MonadIO m
=> MDB_WriteFlags -> Txn -> Dbi -> Word64 -> ByteString -> m Bool
putBytes flags txn db id bs = io $
withWord64AsMDBval id $ \idVal ->
byteStringAsMdbVal bs $ \mVal ->
mdb_put flags txn db idVal mVal
| jfranklin9000/urbit | pkg/hs/urbit-king/lib/Urbit/Vere/LMDB.hs | mit | 10,406 | 0 | 26 | 2,749 | 1,958 | 983 | 975 | -1 | -1 |
module Haskmon.Types.MetaData(
module Haskmon.Types.MetaData,
I.MetaData
) where
import Data.Time.Clock
import Haskmon.Types.Internals(MetaData)
import qualified Haskmon.Types.Internals as I
resourceUri :: MetaData -> String
resourceUri = I.resourceUri
created :: MetaData -> UTCTime
created = I.created
modified :: MetaData -> UTCTime
modified = I.modified
| bitemyapp/Haskmon | src/Haskmon/Types/MetaData.hs | mit | 368 | 0 | 5 | 50 | 95 | 59 | 36 | 12 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>TLS Debug | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_hu_HU/helpset_hu_HU.hs | apache-2.0 | 971 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="da-DK">
<title>HTTPS Info | ZAP Add-on</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/httpsInfo/src/main/javahelp/org/zaproxy/zap/extension/httpsinfo/resources/help_da_DK/helpset_da_DK.hs | apache-2.0 | 969 | 80 | 67 | 160 | 419 | 212 | 207 | -1 | -1 |
--------------------------------------------------------------------
-- |
-- Module : Flickr.Photos.Geo
-- Description : flickr.photos.geo - setting/getting photo geo location.
-- Copyright : (c) Sigbjorn Finne, 2008
-- License : BSD3
--
-- Maintainer : Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- flickr.photos.geo API, setting/getting photo geo location.
--------------------------------------------------------------------
module Flickr.Photos.Geo
( getLocation -- :: PhotoID -> FM GeoLocation
, removeLocation -- :: PhotoID -> FM ()
, setLocation -- :: PhotoID -> GeoLocation -> FM ()
, batchCorrectLocation -- :: GeoLocation -> Either PlaceID WhereOnEarthID -> FM ()
, correctLocation -- :: PhotoID -> Either PlaceID WhereOnEarthID -> FM ()
, photosForLocation -- :: GeoLocation -> [PhotoInfo] -> FM [Photo]
, setContext -- :: PhotoID -> ContextID -> FM ()
, getPerms -- :: PhotoID -> FM Permissions
, setPerms -- :: PhotoID -> Permissions -> FM ()
) where
import Flickr.Monad
import Flickr.Utils
import Flickr.Types
import Flickr.Types.Import
-- | Correct the places hierarchy for all the photos for a user at
-- a given latitude, longitude and accuracy.
--
-- Batch corrections are processed in a delayed queue so it may take
-- a few minutes before the changes are reflected in a user's photos.
batchCorrectLocation :: GeoLocation -> Either PlaceID WhereOnEarthID -> FM ()
batchCorrectLocation (lat,lon,acc) ei = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.batchCorrectLocation"
(eiArg "place_id" "woe_id" ei $
mbArg "accuracy" (fmap show acc) $
[ ("latitude", lat)
, ("longitude", lon)
])
-- | update/correct the location of attached to a photo.
correctLocation :: PhotoID -> Either PlaceID WhereOnEarthID -> FM ()
correctLocation pid ei = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.correctLocation"
(eiArg "place_id" "woe_id" ei $
[ ("photo_id", pid) ])
-- | Get the geo data (latitude and longitude and the accuracy level) for a photo.
getLocation :: PhotoID -> FM GeoLocation
getLocation pid =
flickTranslate toGeoLocation $
flickrCall "flickr.photos.geo.getLocation"
[ ("photo_id", pid) ]
-- | Get permissions for who may view geo data for a photo.
getPerms :: PhotoID -> FM Permissions
getPerms pid =
flickTranslate toPermissions $
flickrCall "flickr.photos.geo.getPerms"
[ ("photo_id", pid) ]
-- | Return a list of photos for a user at a specific latitude, longitude and accuracy
photosForLocation :: GeoLocation -> [PhotoInfo] -> FM (PhotoContext, [Photo])
photosForLocation (lat,lon,acc) extras = withReadPerm $
flickTranslate toPhotoList $
flickrCall "flickr.photo.geo.photosForLocation"
(mbArg "accuracy" (fmap show acc) $
lsArg "extras" (map show extras) $
[ ("latitude", lat)
, ("longitude", lon)
])
-- | Removes the geo data associated with a photo.
removeLocation :: PhotoID -> FM ()
removeLocation pid = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.removeLocation"
[ ("photo_id", pid) ]
-- | Indicate the state of a photo's geotagginess beyond
-- latitude and longitude. Photos passed to this method must
-- already be geotagged (using the 'setLocation' method).
setContext :: PhotoID -> ContextID -> FM ()
setContext pid ctxtId = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.setContext"
[ ("photo_id", pid)
, ("context", show ctxtId)
]
-- | Sets the geo data (latitude and longitude and, optionally,
-- the accuracy level) for a photo. Before users may assign
-- location data to a photo they must define who, by default,
-- may view that information. Users can edit this preference
-- at http://www.flickr.com/account/geo/privacy/. If a user
-- has not set this preference, the API method will return
-- an error.
setLocation :: PhotoID -> GeoLocation -> FM ()
setLocation pid (la,lo,ac) = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.setLocation"
(mbArg "accuracy" (fmap show ac) $
[ ("photo_id", pid)
, ("lat", la)
, ("lon", lo)
])
-- | Set the permission for who may view the geo data associated with a photo.
setPerms :: PhotoID -> Permissions -> FM ()
setPerms pid p = withWritePerm $ postMethod $
flickCall_ "flickr.photos.geo.setPerms"
[ ("photo_id", pid)
, ("is_public", showBool $ permIsPublic p)
, ("is_friend", showBool $ permIsFriend p)
, ("is_family", showBool $ permIsFamily p)
, ("is_contact", showBool (permIsFamily p || permIsFriend p))
]
| sof/flickr | Flickr/Photos/Geo.hs | bsd-3-clause | 4,894 | 22 | 12 | 1,134 | 821 | 463 | 358 | 68 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Pretty printing.
module HIndent.Pretty
(
-- * Printing
Pretty
, pretty
, prettyNoExt
-- * User state
,getState
,putState
,modifyState
-- * Insertion
, write
, newline
, space
, comma
, int
, string
-- * Common node types
, withCtx
, printComment
, printComments
, withCaseContext
, rhsSeparator
-- * Interspersing
, inter
, spaced
, lined
, prefixedLined
, commas
-- * Wrapping
, parens
, brackets
, braces
-- * Indentation
, indented
, indentedBlock
, column
, getColumn
, getLineNum
, depend
, dependBind
, swing
, swingBy
, getIndentSpaces
, getColumnLimit
-- * Predicates
, nullBinds
-- * Sandboxing
, sandbox
-- * Fallback
, pretty'
)
where
import Control.Monad.Trans.Maybe
import Data.Functor.Identity
import HIndent.Types
import Language.Haskell.Exts.Comments
import Control.Monad.State.Strict hiding (state)
import Data.Int
import Data.List
import Data.Maybe
import Data.Foldable (traverse_)
import Data.Monoid hiding (Alt)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Builder (Builder)
import qualified Data.Text.Lazy.Builder as T
import Data.Text.Lazy.Builder.Int
import Data.Typeable
import qualified Language.Haskell.Exts as P
import Language.Haskell.Exts.Syntax
import Language.Haskell.Exts.SrcLoc
import Prelude hiding (exp)
--------------------------------------------------------------------------------
-- * Pretty printing class
-- | Pretty printing class.
class (Annotated ast,Typeable ast) => Pretty ast where
prettyInternal :: MonadState (PrintState s) m => ast NodeInfo -> m ()
-- | Pretty print using extenders.
pretty :: (Pretty ast,MonadState (PrintState s) m)
=> ast NodeInfo -> m ()
pretty a =
do st <- get
case st of
PrintState{psExtenders = es,psUserState = s} ->
do
printComments Before a
depend
(case listToMaybe (mapMaybe (makePrinter s) es) of
Just (Printer m) ->
modify (\s' ->
fromMaybe s'
(runIdentity (runMaybeT (execStateT m s'))))
Nothing -> prettyNoExt a)
(printComments After a)
where makePrinter _ (Extender f) =
case cast a of
Just v -> Just (f v)
Nothing -> Nothing
makePrinter s (CatchAll f) = f s a
-- | Run the basic printer for the given node without calling an
-- extension hook for this node, but do allow extender hooks in child
-- nodes. Also auto-inserts comments.
prettyNoExt :: (Pretty ast,MonadState (PrintState s) m)
=> ast NodeInfo -> m ()
prettyNoExt = prettyInternal
-- | Print comments of a node.
printComments :: (Pretty ast,MonadState (PrintState s) m)
=> ComInfoLocation -> ast NodeInfo -> m ()
printComments loc' ast = do
preprocessor <- gets psCommentPreprocessor
let correctLocation comment = comInfoLocation comment == Just loc'
commentsWithLocation = filter correctLocation (nodeInfoComments info)
comments <- preprocessor $ map comInfoComment commentsWithLocation
forM_ comments $ \comment -> do
-- Preceeding comments must have a newline before them.
hasNewline <- gets psNewline
when (not hasNewline && loc' == Before) newline
printComment (Just $ srcInfoSpan $ nodeInfoSpan info) comment
where info = ann ast
-- | Pretty print a comment.
printComment :: MonadState (PrintState s) m => Maybe SrcSpan -> Comment -> m ()
printComment mayNodespan (Comment inline cspan str) =
do -- Insert proper amount of space before comment.
-- This maintains alignment. This cannot force comments
-- to go before the left-most possible indent (specified by depends).
case mayNodespan of
Just nodespan ->
do let neededSpaces = srcSpanStartColumn cspan -
max 1 (srcSpanEndColumn nodespan)
replicateM_ neededSpaces space
Nothing -> return ()
if inline
then do write "{-"
string str
write "-}"
when (1 == srcSpanStartColumn cspan) $
modify (\s -> s {psEolComment = True})
else do write "--"
string str
modify (\s ->
s {psEolComment = True})
-- | Pretty print using HSE's own printer. The 'P.Pretty' class here
-- is HSE's.
pretty' :: (Pretty ast,P.Pretty (ast SrcSpanInfo),Functor ast,MonadState (PrintState s) m)
=> ast NodeInfo -> m ()
pretty' = write . T.fromText . T.pack . P.prettyPrint . fmap nodeInfoSpan
--------------------------------------------------------------------------------
-- * Combinators
-- | Get the user state.
getState :: Printer s s
getState = gets psUserState
-- | Put the user state.
putState :: s -> Printer s ()
putState s' = modifyState (const s')
-- | Modify the user state.
modifyState :: (s -> s) -> Printer s ()
modifyState f = modify (\s -> s {psUserState = f (psUserState s)})
-- | Increase indentation level by n spaces for the given printer.
indented :: MonadState (PrintState s) m => Int64 -> m a -> m a
indented i p =
do level <- gets psIndentLevel
modify (\s -> s {psIndentLevel = level + i})
m <- p
modify (\s -> s {psIndentLevel = level})
return m
indentedBlock :: MonadState (PrintState s) m => m a -> m a
indentedBlock p =
do indentSpaces <- getIndentSpaces
indented indentSpaces p
-- | Print all the printers separated by spaces.
spaced :: MonadState (PrintState s) m => [m ()] -> m ()
spaced = inter space
-- | Print all the printers separated by commas.
commas :: MonadState (PrintState s) m => [m ()] -> m ()
commas = inter comma
-- | Print all the printers separated by sep.
inter :: MonadState (PrintState s) m => m () -> [m ()] -> m ()
inter sep ps =
foldr (\(i,p) next ->
depend (do p
if i < length ps
then sep
else return ())
next)
(return ())
(zip [1 ..] ps)
-- | Print all the printers separated by newlines.
lined :: MonadState (PrintState s) m => [m ()] -> m ()
lined ps = sequence_ (intersperse newline ps)
-- | Print all the printers separated newlines and optionally a line
-- prefix.
prefixedLined :: MonadState (PrintState s) m => Text -> [m ()] -> m ()
prefixedLined pref ps' =
case ps' of
[] -> return ()
(p:ps) ->
do p
indented (fromIntegral
(T.length pref *
(-1)))
(mapM_ (\p' ->
do newline
depend (write (T.fromText pref)) p')
ps)
-- | Set the (newline-) indent level to the given column for the given
-- printer.
column :: MonadState (PrintState s) m => Int64 -> m a -> m a
column i p =
do level <- gets psIndentLevel
modify (\s -> s {psIndentLevel = i})
m <- p
modify (\s -> s {psIndentLevel = level})
return m
-- | Get the current indent level.
getColumn :: MonadState (PrintState s) m => m Int64
getColumn = gets psColumn
-- | Get the current line number.
getLineNum :: MonadState (PrintState s) m => m Int64
getLineNum = gets psLine
-- | Output a newline.
newline :: MonadState (PrintState s) m => m ()
newline =
do write "\n"
modify (\s -> s {psNewline = True})
-- | Set the context to a case context, where RHS is printed with -> .
withCaseContext :: MonadState (PrintState s) m
=> Bool -> m a -> m a
withCaseContext bool pr =
do original <- gets psInsideCase
modify (\s -> s {psInsideCase = bool})
result <- pr
modify (\s -> s {psInsideCase = original})
return result
-- | Get the current RHS separator, either = or -> .
rhsSeparator :: MonadState (PrintState s) m
=> m ()
rhsSeparator =
do inCase <- gets psInsideCase
if inCase
then write "->"
else write "="
-- | Make the latter's indentation depend upon the end column of the
-- former.
depend :: MonadState (PrintState s) m => m () -> m b -> m b
depend maker dependent =
do state' <- get
maker
st <- get
col <- gets psColumn
if psLine state' /= psLine st || psColumn state' /= psColumn st
then column col dependent
else dependent
-- | Make the latter's indentation depend upon the end column of the
-- former.
dependBind :: MonadState (PrintState s) m => m a -> (a -> m b) -> m b
dependBind maker dependent =
do state' <- get
v <- maker
st <- get
col <- gets psColumn
if psLine state' /= psLine st || psColumn state' /= psColumn st
then column col (dependent v)
else (dependent v)
-- | Wrap in parens.
parens :: MonadState (PrintState s) m => m a -> m a
parens p =
depend (write "(")
(do v <- p
write ")"
return v)
-- | Wrap in braces.
braces :: MonadState (PrintState s) m => m a -> m a
braces p =
depend (write "{")
(do v <- p
write "}"
return v)
-- | Wrap in brackets.
brackets :: MonadState (PrintState s) m => m a -> m a
brackets p =
depend (write "[")
(do v <- p
write "]"
return v)
-- | Write a space.
space :: MonadState (PrintState s) m => m ()
space = write " "
-- | Write a comma.
comma :: MonadState (PrintState s) m => m ()
comma = write ","
-- | Write an integral.
int :: (Integral n, MonadState (PrintState s) m)
=> n -> m ()
int = write . decimal
-- | Write out a string, updating the current position information.
write :: MonadState (PrintState s) m => Builder -> m ()
write x =
do eol <- gets psEolComment
when (eol && x /= "\n") newline
state <- get
let clearEmpty =
configClearEmptyLines (psConfig state)
writingNewline = x == "\n"
out =
if psNewline state &&
not (clearEmpty && writingNewline)
then T.fromText
(T.replicate (fromIntegral (psIndentLevel state))
" ") <>
x
else x
out' = T.toLazyText out
modify (\s ->
s {psOutput = psOutput state <> out
,psNewline = False
,psEolComment = False
,psLine = psLine state + additionalLines
,psColumn =
if additionalLines > 0
then LT.length (LT.concat (take 1 (reverse srclines)))
else psColumn state + LT.length out'})
where x' = T.toLazyText x
srclines = LT.lines x'
additionalLines =
LT.length (LT.filter (== '\n') x')
-- | Write a string.
string :: MonadState (PrintState s) m =>String -> m ()
string = write . T.fromText . T.pack
-- | Indent spaces, e.g. 2.
getIndentSpaces :: MonadState (PrintState s) m => m Int64
getIndentSpaces =
gets (configIndentSpaces . psConfig)
-- | Column limit, e.g. 80
getColumnLimit :: MonadState (PrintState s) m => m Int64
getColumnLimit =
gets (configMaxColumns . psConfig)
-- | Play with a printer and then restore the state to what it was
-- before.
sandbox :: MonadState s m
=> m a -> m (a,s)
sandbox p =
do orig <- get
a <- p
new <- get
put orig
return (a,new)
-- | No binds?
nullBinds :: Binds NodeInfo -> Bool
nullBinds (BDecls _ x) = null x
nullBinds (IPBinds _ x) = null x
-- | Render a type with a context, or not.
withCtx :: (MonadState (PrintState s) m
,Pretty ast)
=> Maybe (ast NodeInfo) -> m b -> m b
withCtx Nothing m = m
withCtx (Just ctx) m =
do pretty ctx
write " =>"
newline
m
-- | Maybe render an overlap definition.
maybeOverlap :: MonadState (PrintState s) m => Maybe (Overlap NodeInfo) -> m ()
maybeOverlap =
maybe (return ())
(\p ->
pretty p >>
space)
-- | Swing the second printer below and indented with respect to the first.
swing :: MonadState (PrintState s) m => m () -> m b -> m b
swing a b =
do orig <- gets psIndentLevel
a
newline
indentSpaces <- getIndentSpaces
column (orig + indentSpaces) b
-- | Swing the second printer below and indented with respect to the first by
-- the specified amount.
swingBy :: MonadState (PrintState s) m => Int64 -> m () -> m b -> m b
swingBy i a b =
do orig <- gets psIndentLevel
a
newline
column (orig + i) b
--------------------------------------------------------------------------------
-- * Instances
instance Pretty Context where
prettyInternal ctx =
case ctx of
CxSingle _ a -> pretty a
CxTuple _ as ->
parens (prefixedLined ","
(map pretty as))
CxEmpty _ -> parens (return ())
instance Pretty Pat where
prettyInternal x =
case x of
PLit _ sign l -> pretty sign >> pretty l
PNPlusK _ n k ->
depend (do pretty n
write "+")
(int k)
PInfixApp _ a op b ->
case op of
Special{} ->
depend (pretty a)
(depend (prettyInfixOp op)
(pretty b))
_ ->
depend (do pretty a
space)
(depend (do prettyInfixOp op
space)
(pretty b))
PApp _ f args ->
depend (do pretty f
unless (null args) space)
(spaced (map pretty args))
PTuple _ boxed pats ->
depend (write (case boxed of
Unboxed -> "(#"
Boxed -> "("))
(do commas (map pretty pats)
write (case boxed of
Unboxed -> "#)"
Boxed -> ")"))
PList _ ps ->
brackets (commas (map pretty ps))
PParen _ e -> parens (pretty e)
PRec _ qname fields ->
do indentSpaces <- getIndentSpaces
depend (do pretty qname
space)
(braces (prefixedLined ","
(map (indented indentSpaces . pretty) fields)))
PAsPat _ n p ->
depend (do pretty n
write "@")
(pretty p)
PWildCard _ -> write "_"
PIrrPat _ p ->
depend (write "~")
(pretty p)
PatTypeSig _ p ty ->
depend (do pretty p
write " :: ")
(pretty ty)
PViewPat _ e p ->
depend (do pretty e
write " -> ")
(pretty p)
PQuasiQuote _ name str ->
brackets (depend (do write "$"
string name
write "|")
(string str))
PBangPat _ p ->
depend (write "!")
(pretty p)
PRPat{} -> pretty' x
PXTag{} -> pretty' x
PXETag{} -> pretty' x
PXPcdata{} -> pretty' x
PXPatTag{} -> pretty' x
PXRPats{} -> pretty' x
PVar{} -> pretty' x
-- | Pretty print a name for being an infix operator.
prettyInfixOp :: MonadState (PrintState s) m => QName NodeInfo -> m ()
prettyInfixOp x =
case x of
Qual _ mn n ->
case n of
Ident _ i -> do write "`"; pretty mn; write "."; string i; write "`";
Symbol _ s -> do pretty mn; write "."; string s;
UnQual _ n ->
case n of
Ident _ i -> string ("`" ++ i ++ "`")
Symbol _ s -> string s
Special _ s -> pretty s
instance Pretty Type where
prettyInternal x =
case x of
TyForall _ mbinds ctx ty ->
depend (case mbinds of
Nothing -> return ()
Just ts ->
do write "forall "
spaced (map pretty ts)
write ". ")
(withCtx ctx (pretty ty))
TyFun _ a b ->
depend (do pretty a
write " -> ")
(pretty b)
TyTuple _ boxed tys ->
depend (write (case boxed of
Unboxed -> "(#"
Boxed -> "("))
(do commas (map pretty tys)
write (case boxed of
Unboxed -> "#)"
Boxed -> ")"))
TyList _ t -> brackets (pretty t)
TyParArray _ t ->
brackets (do write ":"
pretty t
write ":")
TyApp _ f a -> spaced [pretty f,pretty a]
TyVar _ n -> pretty n
TyCon _ p -> pretty p
TyParen _ e -> parens (pretty e)
TyInfix _ a op b ->
depend (do pretty a
space)
(depend (do prettyInfixOp op
space)
(pretty b))
TyKind _ ty k ->
parens (do pretty ty
write " :: "
pretty k)
TyBang _ bangty unpackty right ->
do pretty unpackty
pretty bangty
pretty right
TyEquals _ left right ->
do pretty left
write " ~ "
pretty right
ty@TyPromoted{} -> pretty' ty
TySplice{} -> error "FIXME: No implementation for TySplice."
TyWildCard _ name ->
case name of
Nothing -> write "_"
Just n ->
do write "_"
pretty n
instance Pretty Exp where
prettyInternal = exp
-- | Render an expression.
exp :: MonadState (PrintState s) m => Exp NodeInfo -> m ()
exp (ExprHole {}) = write "_"
exp (InfixApp _ a op b) =
depend (do pretty a
space
pretty op
space)
(do pretty b)
exp (App _ op a) =
swing (do pretty f)
(lined (map pretty args))
where (f,args) = flatten op [a]
flatten :: Exp NodeInfo
-> [Exp NodeInfo]
-> (Exp NodeInfo,[Exp NodeInfo])
flatten (App _ f' a') b =
flatten f' (a' : b)
flatten f' as = (f',as)
exp (NegApp _ e) =
depend (write "-")
(pretty e)
exp (Lambda _ ps e) =
depend (write "\\")
(do spaced (map pretty ps)
swing (write " -> ")
(pretty e))
exp (Let _ binds e) =
do depend (write "let ")
(pretty binds)
newline
depend (write "in ")
(pretty e)
exp (If _ p t e) =
do depend (write "if ")
(do pretty p
newline
depend (write "then ")
(pretty t)
newline
depend (write "else ")
(pretty e))
exp (Paren _ e) = parens (pretty e)
exp (Case _ e alts) =
do depend (write "case ")
(do pretty e
write " of")
newline
indentedBlock (lined (map (withCaseContext True . pretty) alts))
exp (Do _ stmts) =
depend (write "do ")
(lined (map pretty stmts))
exp (MDo _ stmts) =
depend (write "mdo ")
(lined (map pretty stmts))
exp (Tuple _ boxed exps) =
depend (write (case boxed of
Unboxed -> "(#"
Boxed -> "("))
(do prefixedLined ","
(map pretty exps)
write (case boxed of
Unboxed -> "#)"
Boxed -> ")"))
exp (TupleSection _ boxed mexps) =
depend (write (case boxed of
Unboxed -> "(#"
Boxed -> "("))
(do commas (map (maybe (return ()) pretty) mexps)
write (case boxed of
Unboxed -> "#)"
Boxed -> ")"))
exp (List _ es) =
brackets (prefixedLined ","
(map pretty es))
exp (LeftSection _ e op) =
parens (depend (do pretty e
space)
(pretty op))
exp (RightSection _ e op) =
parens (depend (do pretty e
space)
(pretty op))
exp (RecConstr _ n fs) =
depend (do pretty n
space)
(braces (prefixedLined ","
(map (indentedBlock . pretty) fs)))
exp (RecUpdate _ n fs) =
depend (do pretty n
space)
(braces (prefixedLined ","
(map (indentedBlock . pretty) fs)))
exp (EnumFrom _ e) =
brackets (do pretty e
write " ..")
exp (EnumFromTo _ e f) =
brackets (depend (do pretty e
write " .. ")
(pretty f))
exp (EnumFromThen _ e t) =
brackets (depend (do pretty e
write ",")
(do pretty t
write " .."))
exp (EnumFromThenTo _ e t f) =
brackets (depend (do pretty e
write ",")
(depend (do pretty t
write " .. ")
(pretty f)))
exp (ListComp _ e qstmt) =
brackets (do pretty e
unless (null qstmt)
(do newline
indented (-1)
(write "|")
prefixedLined ","
(map pretty qstmt)))
exp (ExpTypeSig _ e t) =
depend (do pretty e
write " :: ")
(pretty t)
exp (VarQuote _ x) =
depend (write "'")
(pretty x)
exp (TypQuote _ x) =
depend (write "''")
(pretty x)
exp (BracketExp _ b) = pretty b
exp (SpliceExp _ s) = pretty s
exp (QuasiQuote _ n s) =
brackets (depend (do string n
write "|")
(do string s
write "|"))
exp (LCase _ alts) =
do write "\\case"
newline
indentedBlock (lined (map (withCaseContext True . pretty) alts))
exp (MultiIf _ alts) =
withCaseContext
True
(depend (write "if ")
(lined (map (\p ->
do write "| "
pretty p)
alts)))
exp (Lit _ lit) = prettyInternal lit
exp x@XTag{} = pretty' x
exp x@XETag{} = pretty' x
exp x@XPcdata{} = pretty' x
exp x@XExpTag{} = pretty' x
exp x@XChildTag{} = pretty' x
exp x@Var{} = pretty' x
exp x@IPVar{} = pretty' x
exp x@Con{} = pretty' x
exp x@CorePragma{} = pretty' x
exp x@SCCPragma{} = pretty' x
exp x@GenPragma{} = pretty' x
exp x@Proc{} = pretty' x
exp x@LeftArrApp{} = pretty' x
exp x@RightArrApp{} = pretty' x
exp x@LeftArrHighApp{} = pretty' x
exp x@RightArrHighApp{} = pretty' x
exp x@ParArray{} = pretty' x
exp x@ParArrayFromTo{} = pretty' x
exp x@ParArrayFromThenTo{} = pretty' x
exp x@ParArrayComp{} = pretty' x
exp ParComp{} =
error "FIXME: No implementation for ParComp."
instance Pretty Stmt where
prettyInternal x =
case x of
Generator _ p e ->
depend (do pretty p
write " <- ")
(pretty e)
Qualifier _ e -> pretty e
LetStmt _ binds ->
depend (write "let ")
(pretty binds)
RecStmt{} ->
error "FIXME: No implementation for RecStmt."
instance Pretty QualStmt where
prettyInternal x =
case x of
QualStmt _ s -> pretty s
ThenTrans{} ->
error "FIXME: No implementation for ThenTrans."
ThenBy{} ->
error "FIXME: No implementation for ThenBy."
GroupBy{} ->
error "FIXME: No implementation for GroupBy."
GroupUsing{} ->
error "FIXME: No implementation for GroupUsing."
GroupByUsing{} ->
error "FIXME: No implementation for GroupByUsing."
instance Pretty Decl where
prettyInternal = decl
-- | Render a declaration.
decl :: MonadState (PrintState s) m => Decl NodeInfo -> m ()
decl (PatBind _ pat rhs mbinds) =
do pretty pat
withCaseContext False (pretty rhs)
case mbinds of
Nothing -> return ()
Just binds ->
do newline
indentedBlock (depend (write "where ")
(pretty binds))
decl (InstDecl _ moverlap dhead decls) =
do depend (write "instance ")
(depend (maybeOverlap moverlap)
(depend (pretty dhead)
(unless (null (fromMaybe [] decls))
(write " where"))))
unless (null (fromMaybe [] decls))
(do newline
indentedBlock (lined (map pretty (fromMaybe [] decls))))
decl (SpliceDecl _ e) = pretty e
decl (TypeSig _ names ty) =
depend (do inter (write ", ")
(map pretty names)
write " :: ")
(pretty ty)
decl (FunBind _ matches) =
lined (map pretty matches)
decl (ClassDecl _ ctx dhead fundeps decls) =
do depend (write "class ")
(withCtx ctx
(depend (do pretty dhead
space)
(depend (unless (null fundeps)
(do write " | "
commas (map pretty fundeps)))
(unless (null (fromMaybe [] decls))
(write " where")))))
unless (null (fromMaybe [] decls))
(do newline
indentedBlock (lined (map pretty (fromMaybe [] decls))))
decl (TypeDecl _ typehead typ) =
depend (write "type ")
(depend (pretty typehead)
(depend (write " = ")
(pretty typ)))
decl TypeFamDecl{} =
error "FIXME: No implementation for TypeFamDecl."
decl (DataDecl _ dataornew ctx dhead condecls mderivs) =
do depend (do pretty dataornew
space)
(withCtx ctx
(do pretty dhead
case condecls of
[] -> return ()
[x] -> singleCons x
xs -> multiCons xs))
indentSpaces <- getIndentSpaces
case mderivs of
Nothing -> return ()
Just derivs ->
do newline
column indentSpaces (pretty derivs)
where singleCons x =
do write " ="
indentSpaces <- getIndentSpaces
column indentSpaces
(do newline
pretty x)
multiCons xs =
do newline
indentSpaces <- getIndentSpaces
column indentSpaces
(depend (write "=")
(prefixedLined "|"
(map (depend space . pretty) xs)))
decl (InlineSig _ inline _ name) = do
write "{-# "
unless inline $ write "NO"
write "INLINE "
pretty name
write " #-}"
decl x = pretty' x
instance Pretty Deriving where
prettyInternal (Deriving _ heads) =
do write "deriving"
space
let heads' =
if length heads == 1
then map stripParens heads
else heads
parens (commas (map pretty heads'))
where stripParens (IParen _ iRule) = stripParens iRule
stripParens x = x
instance Pretty Alt where
prettyInternal x =
case x of
Alt _ p galts mbinds ->
do pretty p
pretty galts
case mbinds of
Nothing -> return ()
Just binds ->
do newline
indentedBlock (depend (write "where ")
(pretty binds))
instance Pretty Asst where
prettyInternal x =
case x of
ClassA _ name types -> spaced (pretty name : map pretty types)
i@InfixA{} -> pretty' i
IParam{} -> error "FIXME: No implementation for IParam."
EqualP _ a b ->
do pretty a
write " ~ "
pretty b
ParenA _ asst -> parens (pretty asst)
AppA _ name tys -> spaced (pretty name : map pretty tys)
WildCardA _ name ->
case name of
Nothing -> write "_"
Just n ->
do write "_"
pretty n
instance Pretty BangType where
prettyInternal x =
case x of
BangedTy _ -> write "!"
LazyTy _ -> write "~"
NoStrictAnnot _ -> pure ()
instance Pretty Unpackedness where
prettyInternal (Unpack _) = write "{-# UNPACK -#}"
prettyInternal (NoUnpack _) = write "{-# NOUNPACK -#}"
prettyInternal (NoUnpackPragma _) = pure ()
instance Pretty Binds where
prettyInternal x =
case x of
BDecls _ ds -> lined (map pretty ds)
IPBinds _ i -> lined (map pretty i)
instance Pretty ClassDecl where
prettyInternal x =
case x of
ClsDecl _ d -> pretty d
ClsDataFam _ ctx h mkind ->
depend (write "data ")
(withCtx ctx
(do pretty h
(case mkind of
Nothing -> return ()
Just kind ->
do write " :: "
pretty kind)))
ClsTyFam _ h mkind minj ->
depend (write "type ")
(depend (pretty h)
(depend (traverse_ (\kind -> write " :: " >> pretty kind) mkind)
(traverse_ pretty minj)))
ClsTyDef _ (TypeEqn _ this that) ->
do write "type "
pretty this
write " = "
pretty that
ClsDefSig _ name ty ->
do write "default "
pretty name
write " :: "
pretty ty
instance Pretty ConDecl where
prettyInternal x =
case x of
ConDecl _ name bangty ->
depend (do pretty name
space)
(lined (map pretty bangty))
InfixConDecl l a f b ->
pretty (ConDecl l f [a,b])
RecDecl _ name fields ->
depend (do pretty name
write " ")
(do depend (write "{")
(prefixedLined ","
(map pretty fields))
write "}")
instance Pretty FieldDecl where
prettyInternal (FieldDecl _ names ty) =
depend (do commas (map pretty names)
write " :: ")
(pretty ty)
instance Pretty FieldUpdate where
prettyInternal x =
case x of
FieldUpdate _ n e ->
swing (do pretty n
write " = ")
(pretty e)
FieldPun _ n -> pretty n
FieldWildcard _ -> write ".."
instance Pretty GuardedRhs where
prettyInternal x =
case x of
GuardedRhs _ stmts e ->
do indented 1
(do prefixedLined
","
(map (\p ->
do space
pretty p)
stmts))
swing (write " " >> rhsSeparator >> write " ")
(pretty e)
instance Pretty InjectivityInfo where
prettyInternal x = pretty' x
instance Pretty InstDecl where
prettyInternal i =
case i of
InsDecl _ d -> pretty d
InsType _ name ty ->
depend (do write "type "
pretty name
write " = ")
(pretty ty)
_ -> pretty' i
instance Pretty Match where
prettyInternal x =
case x of
Match _ name pats rhs mbinds ->
do depend (do pretty name
space)
(spaced (map pretty pats))
withCaseContext False (pretty rhs)
case mbinds of
Nothing -> return ()
Just binds ->
do newline
indentedBlock (depend (write "where ")
(pretty binds))
InfixMatch _ pat1 name pats rhs mbinds ->
do depend (do pretty pat1
space
case name of
Ident _ i ->
string ("`" ++ i ++ "`")
Symbol _ s -> string s)
(do space
spaced (map pretty pats))
withCaseContext False (pretty rhs)
case mbinds of
Nothing -> return ()
Just binds ->
do newline
indentedBlock (depend (write "where ")
(pretty binds))
instance Pretty PatField where
prettyInternal x =
case x of
PFieldPat _ n p ->
depend (do pretty n
write " = ")
(pretty p)
PFieldPun _ n -> pretty n
PFieldWildcard _ -> write ".."
instance Pretty QualConDecl where
prettyInternal x =
case x of
QualConDecl _ tyvars ctx d ->
depend (unless (null (fromMaybe [] tyvars))
(do write "forall "
spaced (map pretty (fromMaybe [] tyvars))
write ". "))
(withCtx ctx
(pretty d))
instance Pretty Rhs where
prettyInternal x =
case x of
UnGuardedRhs _ e -> do
(swing (write " " >> rhsSeparator >> write " ")
(pretty e))
GuardedRhss _ gas ->
do newline
indented 2
(lined (map (\p ->
do write "|"
pretty p)
gas))
instance Pretty Splice where
prettyInternal x =
case x of
IdSplice _ str ->
do write "$"
string str
ParenSplice _ e ->
depend (write "$")
(parens (pretty e))
instance Pretty InstRule where
prettyInternal (IParen _ rule) = parens $ pretty rule
prettyInternal (IRule _ mvarbinds mctx ihead) =
do case mvarbinds of
Nothing -> return ()
Just xs -> spaced (map pretty xs)
withCtx mctx (pretty ihead)
instance Pretty InstHead where
prettyInternal x =
case x of
-- Base cases
IHCon _ name -> pretty name
IHInfix _ typ name ->
depend (pretty typ)
(do space
prettyInfixOp name)
-- Recursive application
IHApp _ ihead typ ->
depend (pretty ihead)
(do space
pretty typ)
-- Wrapping in parens
IHParen _ h -> parens (pretty h)
instance Pretty DeclHead where
prettyInternal x =
case x of
DHead _ name -> pretty name
DHParen _ h -> parens (pretty h)
DHInfix _ var name ->
do pretty var
space
write "`"
pretty name
write "`"
DHApp _ dhead var ->
depend (pretty dhead)
(do space
pretty var)
instance Pretty SpecialCon where
prettyInternal s =
case s of
UnitCon _ -> write "()"
ListCon _ -> write "[]"
FunCon _ -> write "->"
TupleCon _ Boxed i ->
string ("(" ++
replicate (i - 1) ',' ++
")")
TupleCon _ Unboxed i ->
string ("(#" ++
replicate (i - 1) ',' ++
"#)")
Cons _ -> write ":"
UnboxedSingleCon _ -> write "(##)"
instance Pretty Overlap where
prettyInternal (Overlap _) = write "{-# OVERLAP #-}"
prettyInternal (NoOverlap _) = write "{-# NO_OVERLAP #-}"
prettyInternal (Incoherent _) = write "{-# INCOHERENT #-}"
instance Pretty Sign where
prettyInternal (Signless _) = return ()
prettyInternal (Negative _) = write "-"
--------------------------------------------------------------------------------
-- * Unimplemented or incomplete printers
instance Pretty Module where
prettyInternal x =
case x of
Module _ mayModHead pragmas imps decls ->
inter (do newline
newline)
(mapMaybe (\(isNull,r) ->
if isNull
then Nothing
else Just r)
[(null pragmas,inter newline (map pretty pragmas))
,(case mayModHead of
Nothing -> (True,return ())
Just modHead -> (False,pretty modHead))
,(null imps,inter newline (map pretty imps))
,(null decls
,interOf newline
(map (\case
r@TypeSig{} -> (1,pretty r)
r -> (2,pretty r))
decls))])
where interOf i ((c,p):ps) =
case ps of
[] -> p
_ ->
do p
replicateM_ c i
interOf i ps
interOf _ [] = return ()
XmlPage{} -> error "FIXME: No implementation for XmlPage."
XmlHybrid{} -> error "FIXME: No implementation for XmlHybrid."
instance Pretty Bracket where
prettyInternal x =
case x of
ExpBracket _ p ->
brackets (depend (write "|")
(do pretty p
write "|"))
PatBracket _ _ ->
error "FIXME: No implementation for PatBracket."
TypeBracket _ _ ->
error "FIXME: No implementation for TypeBracket."
d@(DeclBracket _ _) -> pretty' d
instance Pretty IPBind where
prettyInternal x =
case x of
IPBind _ _ _ ->
error "FIXME: No implementation for IPBind."
--------------------------------------------------------------------------------
-- * Fallback printers
instance Pretty DataOrNew where
prettyInternal = pretty'
instance Pretty FunDep where
prettyInternal = pretty'
instance Pretty Kind where
prettyInternal = pretty'
instance Pretty ResultSig where
prettyInternal (KindSig _ kind) = pretty kind
prettyInternal (TyVarSig _ tyVarBind) = pretty tyVarBind
instance Pretty Literal where
prettyInternal (String _ _ rep) = do
write "\""
string rep
write "\""
prettyInternal (Char _ _ rep) = do
write "'"
string rep
write "'"
prettyInternal (PrimString _ _ rep) = do
write "\""
string rep
write "\"#"
prettyInternal (PrimChar _ _ rep) = do
write "'"
string rep
write "'#"
-- We print the original notation (because HSE doesn't track Hex
-- vs binary vs decimal notation).
prettyInternal (Int _l _i originalString) =
string originalString
prettyInternal (Frac _l _r originalString) =
string originalString
prettyInternal x = pretty' x
instance Pretty Name where
prettyInternal = pretty'
instance Pretty QName where
prettyInternal = pretty'
instance Pretty QOp where
prettyInternal = pretty'
instance Pretty TyVarBind where
prettyInternal = pretty'
instance Pretty ModuleHead where
prettyInternal (ModuleHead _ name mwarnings mexports) =
do write "module "
pretty name
maybe (return ()) pretty mwarnings
maybe (return ())
(\exports ->
do newline
indented 2 (pretty exports)
newline
space)
mexports
write " where"
instance Pretty ModulePragma where
prettyInternal = pretty'
instance Pretty ImportDecl where
prettyInternal = pretty'
instance Pretty ModuleName where
prettyInternal (ModuleName _ name) =
write (T.fromString name)
instance Pretty ImportSpecList where
prettyInternal = pretty'
instance Pretty ImportSpec where
prettyInternal = pretty'
instance Pretty WarningText where
prettyInternal (DeprText _ s) =
write "{-# DEPRECATED " >> string s >> write " #-}"
prettyInternal (WarnText _ s) =
write "{-# WARNING " >> string s >> write " #-}"
instance Pretty ExportSpecList where
prettyInternal (ExportSpecList _ es) =
parens (prefixedLined ","
(map pretty es))
instance Pretty ExportSpec where
prettyInternal = pretty'
| ennocramer/hindent | src/HIndent/Pretty.hs | bsd-3-clause | 40,383 | 0 | 26 | 15,585 | 12,852 | 6,130 | 6,722 | 1,148 | 6 |
{-# LANGUAGE MagicHash,
UnboxedTuples,
ScopedTypeVariables #-}
module UU.Parsing.StateParser(StateParser(..)) where
import GHC.Prim
import UU.Parsing.MachineInterface
import UU.Parsing.Machine(AnaParser, ParsRec(..),RealParser(..),RealRecogn(..), mkPR, anaDynE)
instance (InputState inp s p) => InputState (inp, state) s p where
splitStateE (inp, st) = case splitStateE inp of
Left' x xs -> Left' x (xs, st)
Right' xs -> Right' (xs, st)
splitState (inp, st) = case splitState inp of
(# x,xs #) -> (# x, (xs, st) #)
getPosition (inp, _) = getPosition inp
class StateParser p st | p -> st where
change :: (st -> st) -> p st -- return the old state
set :: st -> p st
set x = change (const x)
get :: p st
get = change id
fconst x y = y
instance (InputState inp s p ,OutputState out) =>
StateParser (AnaParser (inp, st) out s p) st where
get = anaDynE (mkPR (rp,rr))
where f addRes k state = (val (addRes (snd state)) (k state))
rp = P f
rr = R (f fconst )
change ch = anaDynE (mkPR (rp,rr))
where f addRes k state = case state of (inp, st) -> val (addRes st) (k (inp, ch st))
rp = P f
rr = R (f fconst)
newtype Errors s p = Errors [[Message s p]]
| UU-ComputerScience/uulib | src/UU/Parsing/StateParser.hs | bsd-3-clause | 1,343 | 0 | 15 | 409 | 561 | 305 | 256 | -1 | -1 |
module Syntax.Common
( module Syntax.Common
, module Text.Megaparsec
, module Syntax.ParseState
, module Syntax.Tree
) where
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Control.Monad.State.Lazy (put, get)
import qualified Text.Megaparsec.Lexer as L
import Text.Megaparsec hiding (State)
import Syntax.ParseState
import Syntax.Tree
-- Produces a whitespace consumer using `sc` as the space consumer. Consumes
-- whole line and in-line comments. The syntax for both comment types are the
-- same as C, with '//' indicating a whole line comment and '/* ... */'
-- indicating an in-line comment.
whitespaceConsumer :: Parser Char -> Parser ()
whitespaceConsumer sc = L.space (void sc) lineCmnt blockCmnt
where lineCmnt = L.skipLineComment "//" <* void (many newline)
blockCmnt = L.skipBlockComment "/*" "*/" <* void (many newline)
-- Comsumes whitespace and comments, but not newlines.
whitespace :: Parser ()
whitespace = whitespaceConsumer (oneOf "\t ")
lWhitespace :: ParserM ()
lWhitespace = lift whitespace
whitespaceNewline :: Parser ()
whitespaceNewline = whitespaceConsumer spaceChar
-- Consumes whitespace, comments, and newlines.
lWhitespaceNewline :: ParserM ()
lWhitespaceNewline = lift whitespaceNewline
-- Succeeds if the specified string can be parsed, followed by any ignored
-- whitespace or comments.
tok :: String -> Parser String
tok s = string s <* whitespace
-- Succeeds if the specified string can be parsed, followed by any ignored
-- whitespace or comments.
lTok :: String -> ParserM String
lTok = lift . tok
-- Parses a string enclosed in parenthesis.
parens :: ParserM a -> ParserM a
parens = between (lTok "(") (lTok ")")
-- Parses a string enclosed in curly braces.
braces :: ParserM a -> ParserM a
braces = between (lTok "{" <* lWhitespaceNewline) (lTok "}")
-- Allows any variables or functions inside the block to overwrite definitions
-- outside the block.
block :: ParserM a -> ParserM a
block p = do
savedState <- get
descendScopeM
x <- p
put savedState
return x
quoted :: ParserM a -> ParserM a
quoted = between (lTok "\"") (lTok "\"")
-- Parses a string encased in double quotes.
quotedString :: ParserM String
quotedString = quoted (many (noneOf "\""))
-- Creates a parser for each member of expTypes. Useful for ensuring many
-- parses have the correct type, e.g. when invoking a function.
matchedTypes :: (DataType -> ParserM a) -> [DataType] -> ParserM [a]
matchedTypes makeP expTypes = foldl combine (return []) ps where
combine acc p = (++) <$> acc <*> (fmap (\x -> [x]) p)
ps = zipWith (\x y -> x y) (repeat makeP) expTypes
| BakerSmithA/Turing | src/Syntax/Common.hs | bsd-3-clause | 2,648 | 0 | 12 | 461 | 656 | 348 | 308 | 47 | 1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#if __GLASGOW_HASKELL__ >= 703
{-# LANGUAGE Trustworthy #-}
#endif
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.Tree
-- Copyright : (c) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Multi-way trees (/aka/ rose trees) and forests.
--
-----------------------------------------------------------------------------
module Data.Tree(
Tree(..), Forest,
-- * Two-dimensional drawing
drawTree, drawForest,
-- * Extraction
flatten, levels,
-- * Building trees
unfoldTree, unfoldForest,
unfoldTreeM, unfoldForestM,
unfoldTreeM_BF, unfoldForestM_BF,
) where
#if MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
import Data.Foldable (toList)
#else
import Control.Applicative (Applicative(..), (<$>))
import Data.Foldable (Foldable(foldMap), toList)
import Data.Monoid (Monoid(..))
import Data.Traversable (Traversable(traverse))
#endif
import Control.Monad (liftM)
import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList,
ViewL(..), ViewR(..), viewl, viewr)
import Data.Typeable
import Control.DeepSeq (NFData(rnf))
#ifdef __GLASGOW_HASKELL__
import Data.Data (Data)
#endif
#if MIN_VERSION_base(4,8,0)
import Data.Coerce
#endif
-- | Multi-way trees, also known as /rose trees/.
data Tree a = Node {
rootLabel :: a, -- ^ label value
subForest :: Forest a -- ^ zero or more child trees
}
#ifdef __GLASGOW_HASKELL__
deriving (Eq, Read, Show, Data)
#else
deriving (Eq, Read, Show)
#endif
type Forest a = [Tree a]
INSTANCE_TYPEABLE1(Tree,treeTc,"Tree")
instance Functor Tree where
fmap = fmapTree
fmapTree :: (a -> b) -> Tree a -> Tree b
fmapTree f (Node x ts) = Node (f x) (map (fmapTree f) ts)
#if MIN_VERSION_base(4,8,0)
-- Safe coercions were introduced in 4.7.0, but I am not sure if they played
-- well enough with RULES to do what we want.
{-# NOINLINE [1] fmapTree #-}
{-# RULES
"fmapTree/coerce" fmapTree coerce = coerce
#-}
#endif
instance Applicative Tree where
pure x = Node x []
Node f tfs <*> tx@(Node x txs) =
Node (f x) (map (f <$>) txs ++ map (<*> tx) tfs)
instance Monad Tree where
return x = Node x []
Node x ts >>= f = Node x' (ts' ++ map (>>= f) ts)
where Node x' ts' = f x
instance Traversable Tree where
traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
instance Foldable Tree where
foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
#if MIN_VERSION_base(4,8,0)
null _ = False
{-# INLINE null #-}
toList = flatten
{-# INLINE toList #-}
#endif
instance NFData a => NFData (Tree a) where
rnf (Node x ts) = rnf x `seq` rnf ts
-- | Neat 2-dimensional drawing of a tree.
drawTree :: Tree String -> String
drawTree = unlines . draw
-- | Neat 2-dimensional drawing of a forest.
drawForest :: Forest String -> String
drawForest = unlines . map drawTree
draw :: Tree String -> [String]
draw (Node x ts0) = x : drawSubTrees ts0
where
drawSubTrees [] = []
drawSubTrees [t] =
"|" : shift "`- " " " (draw t)
drawSubTrees (t:ts) =
"|" : shift "+- " "| " (draw t) ++ drawSubTrees ts
shift first other = zipWith (++) (first : repeat other)
-- | The elements of a tree in pre-order.
flatten :: Tree a -> [a]
flatten t = squish t []
where squish (Node x ts) xs = x:Prelude.foldr squish xs ts
-- | Lists of nodes at each level of the tree.
levels :: Tree a -> [[a]]
levels t =
map (map rootLabel) $
takeWhile (not . null) $
iterate (concatMap subForest) [t]
-- | Build a tree from a seed value
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
-- | Build a forest from a list of seed values
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForest f = map (unfoldTree f)
-- | Monadic tree builder, in depth-first order
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM f b = do
(a, bs) <- f b
ts <- unfoldForestM f bs
return (Node a ts)
-- | Monadic forest builder, in depth-first order
#ifndef __NHC__
unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
#endif
unfoldForestM f = Prelude.mapM (unfoldTreeM f)
-- | Monadic tree builder, in breadth-first order,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
-- by Chris Okasaki, /ICFP'00/.
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
where
getElement xs = case viewl xs of
x :< _ -> x
EmptyL -> error "unfoldTreeM_BF"
-- | Monadic forest builder, in breadth-first order,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
-- by Chris Okasaki, /ICFP'00/.
unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
-- takes a sequence (queue) of seeds
-- produces a sequence (reversed queue) of trees of the same length
unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
unfoldForestQ f aQ = case viewl aQ of
EmptyL -> return empty
a :< aQ' -> do
(b, as) <- f a
tQ <- unfoldForestQ f (Prelude.foldl (|>) aQ' as)
let (tQ', ts) = splitOnto [] as tQ
return (Node b ts <| tQ')
where
splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
splitOnto as [] q = (q, as)
splitOnto as (_:bs) q = case viewr q of
q' :> a -> splitOnto (a:as) bs q'
EmptyR -> error "unfoldForestQ"
| shockkolate/containers | Data/Tree.hs | bsd-3-clause | 5,981 | 0 | 14 | 1,329 | 1,804 | 967 | 837 | -1 | -1 |
module Control.Aufgabe.TH where
import Control.Aufgabe.Type
import Control.TH
import Network.XmlRpc.THDeriveXmlRpcType
$(asXmlRpcStruct ''Aufgabe)
| Erdwolf/autotool-bonn | src/Control/Aufgabe/TH.hs | gpl-2.0 | 149 | 0 | 8 | 13 | 36 | 21 | 15 | -1 | -1 |
-- | Render some text to HTML, replacing any URIs with actual links.
module Text.Blaze.Linkify where
import Data.Text (Text)
import Text.Blaze.Html5
import Text.Blaze.Html5.Attributes
import Text.Links
import Data.String.Extra
-- | Render some text to HTML, replacing any URIs with actual links.
linkify :: Text -> Html
linkify = mapM_ renderOrLeave . explodeLinks where
renderOrLeave (Right text) = toHtml text
renderOrLeave (Left uri) = a ! href (toValue (show uri)) $
toHtml (limitLen 100 (show uri))
| plow-technologies/ircbrowse | src/Text/Blaze/Linkify.hs | bsd-3-clause | 516 | 0 | 13 | 86 | 137 | 75 | 62 | 11 | 2 |
yes = map (\(a,_) -> a) xs | mpickering/hlint-refactor | tests/examples/Default22.hs | bsd-3-clause | 26 | 0 | 8 | 6 | 25 | 14 | 11 | 1 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- Operations on affine spaces.
-----------------------------------------------------------------------------
module Linear.Covector
( Covector(..)
, ($*)
) where
import Control.Applicative
import Control.Monad
import Data.Functor.Plus hiding (zero)
import qualified Data.Functor.Plus as Plus
import Data.Functor.Bind
import Data.Functor.Rep as Rep
import Linear.Algebra
-- | Linear functionals from elements of an (infinite) free module to a scalar
newtype Covector r a = Covector { runCovector :: (a -> r) -> r }
infixr 0 $*
($*) :: Representable f => Covector r (Rep f) -> f r -> r
Covector f $* m = f (Rep.index m)
instance Functor (Covector r) where
fmap f (Covector m) = Covector $ \k -> m (k . f)
instance Apply (Covector r) where
Covector mf <.> Covector ma = Covector $ \k -> mf $ \f -> ma (k . f)
instance Applicative (Covector r) where
pure a = Covector $ \k -> k a
Covector mf <*> Covector ma = Covector $ \k -> mf $ \f -> ma $ k . f
instance Bind (Covector r) where
Covector m >>- f = Covector $ \k -> m $ \a -> runCovector (f a) k
instance Monad (Covector r) where
return a = Covector $ \k -> k a
Covector m >>= f = Covector $ \k -> m $ \a -> runCovector (f a) k
instance Num r => Alt (Covector r) where
Covector m <!> Covector n = Covector $ \k -> m k + n k
instance Num r => Plus (Covector r) where
zero = Covector (const 0)
instance Num r => Alternative (Covector r) where
Covector m <|> Covector n = Covector $ \k -> m k + n k
empty = Covector (const 0)
instance Num r => MonadPlus (Covector r) where
Covector m `mplus` Covector n = Covector $ \k -> m k + n k
mzero = Covector (const 0)
instance Coalgebra r m => Num (Covector r m) where
Covector f + Covector g = Covector $ \k -> f k + g k
Covector f - Covector g = Covector $ \k -> f k - g k
Covector f * Covector g = Covector $ \k -> f $ \m -> g $ comult k m
negate (Covector f) = Covector $ \k -> negate (f k)
abs _ = error "Covector.abs: undefined"
signum _ = error "Covector.signum: undefined"
fromInteger n = Covector $ \ k -> fromInteger n * counital k
| bgamari/linear | src/Linear/Covector.hs | bsd-3-clause | 2,413 | 0 | 12 | 510 | 950 | 481 | 469 | 45 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
module Main where
import Control.Lens
import qualified Graphics.Vty as V
import qualified Brick.Main as M
import qualified Brick.Types as T
import Brick.Widgets.Core
( (<+>)
, (<=>)
, hLimit
, vLimit
, str
)
import qualified Brick.Widgets.Center as C
import qualified Brick.Widgets.Edit as E
import qualified Brick.AttrMap as A
import Brick.Util (on)
data St =
St { _currentEditor :: T.Name
, _edit1 :: E.Editor
, _edit2 :: E.Editor
}
makeLenses ''St
firstEditor :: T.Name
firstEditor = "edit1"
secondEditor :: T.Name
secondEditor = "edit2"
switchEditors :: St -> St
switchEditors st =
let next = if st^.currentEditor == firstEditor
then secondEditor else firstEditor
in st & currentEditor .~ next
currentEditorL :: St -> Lens' St E.Editor
currentEditorL st =
if st^.currentEditor == firstEditor
then edit1
else edit2
drawUI :: St -> [T.Widget]
drawUI st = [ui]
where
ui = C.center $ (str "Input 1 (unlimited): " <+> (hLimit 30 $ vLimit 5 $ E.renderEditor $ st^.edit1)) <=>
str " " <=>
(str "Input 2 (limited to 2 lines): " <+> (hLimit 30 $ E.renderEditor $ st^.edit2)) <=>
str " " <=>
str "Press Tab to switch between editors, Esc to quit."
appEvent :: St -> V.Event -> T.EventM (T.Next St)
appEvent st ev =
case ev of
V.EvKey V.KEsc [] -> M.halt st
V.EvKey (V.KChar '\t') [] -> M.continue $ switchEditors st
_ -> M.continue =<< T.handleEventLensed st (currentEditorL st) ev
initialState :: St
initialState =
St firstEditor
(E.editor firstEditor (str . unlines) Nothing "")
(E.editor secondEditor (str . unlines) (Just 2) "")
theMap :: A.AttrMap
theMap = A.attrMap V.defAttr
[ (E.editAttr, V.white `on` V.blue)
]
appCursor :: St -> [T.CursorLocation] -> Maybe T.CursorLocation
appCursor st = M.showCursorNamed (st^.currentEditor)
theApp :: M.App St V.Event
theApp =
M.App { M.appDraw = drawUI
, M.appChooseCursor = appCursor
, M.appHandleEvent = appEvent
, M.appStartEvent = return
, M.appAttrMap = const theMap
, M.appLiftVtyEvent = id
}
main :: IO ()
main = do
st <- M.defaultMain theApp initialState
putStrLn "In input 1 you entered:\n"
putStrLn $ unlines $ E.getEditContents $ st^.edit1
putStrLn "In input 2 you entered:\n"
putStrLn $ unlines $ E.getEditContents $ st^.edit2
| sisirkoppaka/brick | programs/EditDemo.hs | bsd-3-clause | 2,609 | 0 | 19 | 694 | 816 | 442 | 374 | 75 | 3 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sk-SK">
<title>Code Dx | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_sk_SK/helpset_sk_SK.hs | apache-2.0 | 968 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
"http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="en-GB">
<title>ViewState</title>
<maps>
<homeID>viewstate</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
| thc202/zap-extensions | addOns/viewstate/src/main/javahelp/help/helpset.hs | apache-2.0 | 973 | 81 | 67 | 168 | 414 | 212 | 202 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal
-- Copyright : (C) 2012-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : Rank2Types
--
-- These are some of the explicit 'Functor' instances that leak into the
-- type signatures of @Control.Lens@. You shouldn't need to import this
-- module directly for most use-cases.
--
----------------------------------------------------------------------------
module Control.Lens.Internal
( module Control.Lens.Internal.Bazaar
, module Control.Lens.Internal.Context
, module Control.Lens.Internal.Fold
, module Control.Lens.Internal.Getter
, module Control.Lens.Internal.Indexed
, module Control.Lens.Internal.Iso
, module Control.Lens.Internal.Level
, module Control.Lens.Internal.Magma
, module Control.Lens.Internal.Prism
, module Control.Lens.Internal.Review
, module Control.Lens.Internal.Setter
, module Control.Lens.Internal.Zoom
) where
import Control.Lens.Internal.Bazaar
import Control.Lens.Internal.Context
import Control.Lens.Internal.Fold
import Control.Lens.Internal.Getter
import Control.Lens.Internal.Indexed
import Control.Lens.Internal.Instances ()
import Control.Lens.Internal.Iso
import Control.Lens.Internal.Level
import Control.Lens.Internal.Magma
import Control.Lens.Internal.Prism
import Control.Lens.Internal.Review
import Control.Lens.Internal.Setter
import Control.Lens.Internal.Zoom
#ifdef HLINT
{-# ANN module "HLint: ignore Use import/export shortcut" #-}
#endif
| danidiaz/lens | src/Control/Lens/Internal.hs | bsd-3-clause | 1,676 | 0 | 5 | 200 | 217 | 163 | 54 | 27 | 0 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, ForeignFunctionInterface
, MagicHash
, UnboxedTuples
, ScopedTypeVariables
#-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
-- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN
-- and Control.Concurrent.SampleVar imports.
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- A common interface to a collection of useful concurrency
-- abstractions.
--
-----------------------------------------------------------------------------
module Control.Concurrent (
-- * Concurrent Haskell
-- $conc_intro
-- * Basic concurrency operations
ThreadId,
#ifdef __GLASGOW_HASKELL__
myThreadId,
#endif
forkIO,
#ifdef __GLASGOW_HASKELL__
forkFinally,
forkIOWithUnmask,
killThread,
throwTo,
#endif
-- ** Threads with affinity
forkOn,
forkOnWithUnmask,
getNumCapabilities,
setNumCapabilities,
threadCapability,
-- * Scheduling
-- $conc_scheduling
yield, -- :: IO ()
-- ** Blocking
-- $blocking
#ifdef __GLASGOW_HASKELL__
-- ** Waiting
threadDelay, -- :: Int -> IO ()
threadWaitRead, -- :: Int -> IO ()
threadWaitWrite, -- :: Int -> IO ()
#endif
-- * Communication abstractions
module Control.Concurrent.MVar,
module Control.Concurrent.Chan,
module Control.Concurrent.QSem,
module Control.Concurrent.QSemN,
module Control.Concurrent.SampleVar,
-- * Merging of streams
#ifndef __HUGS__
mergeIO, -- :: [a] -> [a] -> IO [a]
nmergeIO, -- :: [[a]] -> IO [a]
#endif
-- $merge
#ifdef __GLASGOW_HASKELL__
-- * Bound Threads
-- $boundthreads
rtsSupportsBoundThreads,
forkOS,
isCurrentThreadBound,
runInBoundThread,
runInUnboundThread,
#endif
-- * Weak references to ThreadIds
mkWeakThreadId,
-- * GHC's implementation of concurrency
-- |This section describes features specific to GHC's
-- implementation of Concurrent Haskell.
-- ** Haskell threads and Operating System threads
-- $osthreads
-- ** Terminating the program
-- $termination
-- ** Pre-emption
-- $preemption
-- * Deprecated functions
forkIOUnmasked
) where
import Prelude
import Control.Exception.Base as Exception
#ifdef __GLASGOW_HASKELL__
import GHC.Exception
import GHC.Conc hiding (threadWaitRead, threadWaitWrite)
import qualified GHC.Conc
import GHC.IO ( IO(..), unsafeInterleaveIO, unsafeUnmask )
import GHC.IORef ( newIORef, readIORef, writeIORef )
import GHC.Base
import System.Posix.Types ( Fd )
import Foreign.StablePtr
import Foreign.C.Types
import Control.Monad ( when )
#ifdef mingw32_HOST_OS
import Foreign.C
import System.IO
#endif
#endif
#ifdef __HUGS__
import Hugs.ConcBase
#endif
import Control.Concurrent.MVar
import Control.Concurrent.Chan
import Control.Concurrent.QSem
import Control.Concurrent.QSemN
import Control.Concurrent.SampleVar
#ifdef __HUGS__
type ThreadId = ()
#endif
{- $conc_intro
The concurrency extension for Haskell is described in the paper
/Concurrent Haskell/
<http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
Concurrency is \"lightweight\", which means that both thread creation
and context switching overheads are extremely low. Scheduling of
Haskell threads is done internally in the Haskell runtime system, and
doesn't make use of any operating system-supplied thread packages.
However, if you want to interact with a foreign library that expects your
program to use the operating system-supplied thread package, you can do so
by using 'forkOS' instead of 'forkIO'.
Haskell threads can communicate via 'MVar's, a kind of synchronised
mutable variable (see "Control.Concurrent.MVar"). Several common
concurrency abstractions can be built from 'MVar's, and these are
provided by the "Control.Concurrent" library.
In GHC, threads may also communicate via exceptions.
-}
{- $conc_scheduling
Scheduling may be either pre-emptive or co-operative,
depending on the implementation of Concurrent Haskell (see below
for information related to specific compilers). In a co-operative
system, context switches only occur when you use one of the
primitives defined in this module. This means that programs such
as:
> main = forkIO (write 'a') >> write 'b'
> where write c = putChar c >> write c
will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
instead of some random interleaving of @a@s and @b@s. In
practice, cooperative multitasking is sufficient for writing
simple graphical user interfaces.
-}
{- $blocking
Different Haskell implementations have different characteristics with
regard to which operations block /all/ threads.
Using GHC without the @-threaded@ option, all foreign calls will block
all other Haskell threads in the system, although I\/O operations will
not. With the @-threaded@ option, only foreign calls with the @unsafe@
attribute will block all other threads.
Using Hugs, all I\/O operations and foreign calls will block all other
Haskell threads.
-}
-- | fork a thread and call the supplied function when the thread is about
-- to terminate, with an exception or a returned value. The function is
-- called with asynchronous exceptions masked.
--
-- > forkFinally action and_then =
-- > mask $ \restore ->
-- > forkIO $ try (restore action) >>= and_then
--
-- This function is useful for informing the parent when a child
-- terminates, for example.
--
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_then
-- -----------------------------------------------------------------------------
-- Merging streams
#ifndef __HUGS__
max_buff_size :: Int
max_buff_size = 1
{-# DEPRECATED mergeIO "Control.Concurrent.mergeIO will be removed in GHC 7.8. Please use an alternative, e.g. the SafeSemaphore package, instead." #-}
{-# DEPRECATED nmergeIO "Control.Concurrent.nmergeIO will be removed in GHC 7.8. Please use an alternative, e.g. the SafeSemaphore package, instead." #-}
mergeIO :: [a] -> [a] -> IO [a]
nmergeIO :: [[a]] -> IO [a]
-- $merge
-- The 'mergeIO' and 'nmergeIO' functions fork one thread for each
-- input list that concurrently evaluates that list; the results are
-- merged into a single output list.
--
-- Note: Hugs does not provide these functions, since they require
-- preemptive multitasking.
mergeIO ls rs
= newEmptyMVar >>= \ tail_node ->
newMVar tail_node >>= \ tail_list ->
newQSem max_buff_size >>= \ e ->
newMVar 2 >>= \ branches_running ->
let
buff = (tail_list,e)
in
forkIO (suckIO branches_running buff ls) >>
forkIO (suckIO branches_running buff rs) >>
takeMVar tail_node >>= \ val ->
signalQSem e >>
return val
type Buffer a
= (MVar (MVar [a]), QSem)
suckIO :: MVar Int -> Buffer a -> [a] -> IO ()
suckIO branches_running buff@(tail_list,e) vs
= case vs of
[] -> takeMVar branches_running >>= \ val ->
if val == 1 then
takeMVar tail_list >>= \ node ->
putMVar node [] >>
putMVar tail_list node
else
putMVar branches_running (val-1)
(x:xs) ->
waitQSem e >>
takeMVar tail_list >>= \ node ->
newEmptyMVar >>= \ next_node ->
unsafeInterleaveIO (
takeMVar next_node >>= \ y ->
signalQSem e >>
return y) >>= \ next_node_val ->
putMVar node (x:next_node_val) >>
putMVar tail_list next_node >>
suckIO branches_running buff xs
nmergeIO lss
= let
len = length lss
in
newEmptyMVar >>= \ tail_node ->
newMVar tail_node >>= \ tail_list ->
newQSem max_buff_size >>= \ e ->
newMVar len >>= \ branches_running ->
let
buff = (tail_list,e)
in
mapIO (\ x -> forkIO (suckIO branches_running buff x)) lss >>
takeMVar tail_node >>= \ val ->
signalQSem e >>
return val
where
mapIO f xs = sequence (map f xs)
#endif /* __HUGS__ */
#ifdef __GLASGOW_HASKELL__
-- ---------------------------------------------------------------------------
-- Bound Threads
{- $boundthreads
#boundthreads#
Support for multiple operating system threads and bound threads as described
below is currently only available in the GHC runtime system if you use the
/-threaded/ option when linking.
Other Haskell systems do not currently support multiple operating system threads.
A bound thread is a haskell thread that is /bound/ to an operating system
thread. While the bound thread is still scheduled by the Haskell run-time
system, the operating system thread takes care of all the foreign calls made
by the bound thread.
To a foreign library, the bound thread will look exactly like an ordinary
operating system thread created using OS functions like @pthread_create@
or @CreateThread@.
Bound threads can be created using the 'forkOS' function below. All foreign
exported functions are run in a bound thread (bound to the OS thread that
called the function). Also, the @main@ action of every Haskell program is
run in a bound thread.
Why do we need this? Because if a foreign library is called from a thread
created using 'forkIO', it won't have access to any /thread-local state/ -
state variables that have specific values for each OS thread
(see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
libraries (OpenGL, for example) will not work from a thread created using
'forkIO'. They work fine in threads created using 'forkOS' or when called
from @main@ or from a @foreign export@.
In terms of performance, 'forkOS' (aka bound) threads are much more
expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'
thread is tied to a particular OS thread, whereas a 'forkIO' thread
can be run by any OS thread. Context-switching between a 'forkOS'
thread and a 'forkIO' thread is many times more expensive than between
two 'forkIO' threads.
Note in particular that the main program thread (the thread running
@Main.main@) is always a bound thread, so for good concurrency
performance you should ensure that the main thread is not doing
repeated communication with other threads in the system. Typically
this means forking subthreads to do the work using 'forkIO', and
waiting for the results in the main thread.
-}
-- | 'True' if bound threads are supported.
-- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
-- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
-- fail.
foreign import ccall rtsSupportsBoundThreads :: Bool
{- |
Like 'forkIO', this sparks off a new thread to run the 'IO'
computation passed as the first argument, and returns the 'ThreadId'
of the newly created thread.
However, 'forkOS' creates a /bound/ thread, which is necessary if you
need to call foreign (non-Haskell) libraries that make use of
thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").
Using 'forkOS' instead of 'forkIO' makes no difference at all to the
scheduling behaviour of the Haskell runtime system. It is a common
misconception that you need to use 'forkOS' instead of 'forkIO' to
avoid blocking all the Haskell threads when making a foreign call;
this isn't the case. To allow foreign calls to be made without
blocking all the Haskell threads (with GHC), it is only necessary to
use the @-threaded@ option when linking your program, and to make sure
the foreign import is not marked @unsafe@.
-}
forkOS :: IO () -> IO ThreadId
foreign export ccall forkOS_entry
:: StablePtr (IO ()) -> IO ()
foreign import ccall "forkOS_entry" forkOS_entry_reimported
:: StablePtr (IO ()) -> IO ()
forkOS_entry :: StablePtr (IO ()) -> IO ()
forkOS_entry stableAction = do
action <- deRefStablePtr stableAction
action
foreign import ccall forkOS_createThread
:: StablePtr (IO ()) -> IO CInt
failNonThreaded :: IO a
failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
++"(use ghc -threaded when linking)"
forkOS action0
| rtsSupportsBoundThreads = do
mv <- newEmptyMVar
b <- Exception.getMaskingState
let
-- async exceptions are masked in the child if they are masked
-- in the parent, as for forkIO (see #1048). forkOS_createThread
-- creates a thread with exceptions masked by default.
action1 = case b of
Unmasked -> unsafeUnmask action0
MaskedInterruptible -> action0
MaskedUninterruptible -> uninterruptibleMask_ action0
action_plus = Exception.catch action1 childHandler
entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
err <- forkOS_createThread entry
when (err /= 0) $ fail "Cannot create OS thread."
tid <- takeMVar mv
freeStablePtr entry
return tid
| otherwise = failNonThreaded
-- | Returns 'True' if the calling thread is /bound/, that is, if it is
-- safe to use foreign libraries that rely on thread-local state from the
-- calling thread.
isCurrentThreadBound :: IO Bool
isCurrentThreadBound = IO $ \ s# ->
case isCurrentThreadBound# s# of
(# s2#, flg #) -> (# s2#, not (isTrue# (flg ==# 0#)) #)
{- |
Run the 'IO' computation passed as the first argument. If the calling thread
is not /bound/, a bound thread is created temporarily. @runInBoundThread@
doesn't finish until the 'IO' computation finishes.
You can wrap a series of foreign function calls that rely on thread-local state
with @runInBoundThread@ so that you can use them without knowing whether the
current thread is /bound/.
-}
runInBoundThread :: IO a -> IO a
runInBoundThread action
| rtsSupportsBoundThreads = do
bound <- isCurrentThreadBound
if bound
then action
else do
ref <- newIORef undefined
let action_plus = Exception.try action >>= writeIORef ref
bracket (newStablePtr action_plus)
freeStablePtr
(\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>=
unsafeResult
| otherwise = failNonThreaded
{- |
Run the 'IO' computation passed as the first argument. If the calling thread
is /bound/, an unbound thread is created temporarily using 'forkIO'.
@runInBoundThread@ doesn't finish until the 'IO' computation finishes.
Use this function /only/ in the rare case that you have actually observed a
performance loss due to the use of bound threads. A program that
doesn't need it's main thread to be bound and makes /heavy/ use of concurrency
(e.g. a web server), might want to wrap it's @main@ action in
@runInUnboundThread@.
Note that exceptions which are thrown to the current thread are thrown in turn
to the thread that is executing the given computation. This ensures there's
always a way of killing the forked thread.
-}
runInUnboundThread :: IO a -> IO a
runInUnboundThread action = do
bound <- isCurrentThreadBound
if bound
then do
mv <- newEmptyMVar
mask $ \restore -> do
tid <- forkIO $ Exception.try (restore action) >>= putMVar mv
let wait = takeMVar mv `Exception.catch` \(e :: SomeException) ->
Exception.throwTo tid e >> wait
wait >>= unsafeResult
else action
unsafeResult :: Either SomeException a -> IO a
unsafeResult = either Exception.throwIO return
#endif /* __GLASGOW_HASKELL__ */
#ifdef __GLASGOW_HASKELL__
-- ---------------------------------------------------------------------------
-- threadWaitRead/threadWaitWrite
-- | Block the current thread until data is available to read on the
-- given file descriptor (GHC only).
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitRead', use
-- 'GHC.Conc.closeFdWith'.
threadWaitRead :: Fd -> IO ()
threadWaitRead fd
#ifdef mingw32_HOST_OS
-- we have no IO manager implementing threadWaitRead on Windows.
-- fdReady does the right thing, but we have to call it in a
-- separate thread, otherwise threadWaitRead won't be interruptible,
-- and this only works with -threaded.
| threaded = withThread (waitFd fd 0)
| otherwise = case fd of
0 -> do _ <- hWaitForInput stdin (-1)
return ()
-- hWaitForInput does work properly, but we can only
-- do this for stdin since we know its FD.
_ -> error "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput"
#else
= GHC.Conc.threadWaitRead fd
#endif
-- | Block the current thread until data can be written to the
-- given file descriptor (GHC only).
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitWrite', use
-- 'GHC.Conc.closeFdWith'.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite fd
#ifdef mingw32_HOST_OS
| threaded = withThread (waitFd fd 1)
| otherwise = error "threadWaitWrite requires -threaded on Windows"
#else
= GHC.Conc.threadWaitWrite fd
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool
withThread :: IO a -> IO a
withThread io = do
m <- newEmptyMVar
_ <- mask_ $ forkIO $ try io >>= putMVar m
x <- takeMVar m
case x of
Right a -> return a
Left e -> throwIO (e :: IOException)
waitFd :: Fd -> CInt -> IO ()
waitFd fd write = do
throwErrnoIfMinus1_ "fdReady" $
fdReady (fromIntegral fd) write iNFINITE 0
iNFINITE :: CInt
iNFINITE = 0xFFFFFFFF -- urgh
foreign import ccall safe "fdReady"
fdReady :: CInt -> CInt -> CInt -> CInt -> IO CInt
#endif
-- ---------------------------------------------------------------------------
-- More docs
{- $osthreads
#osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
are managed entirely by the GHC runtime. Typically Haskell
threads are an order of magnitude or two more efficient (in
terms of both time and space) than operating system threads.
The downside of having lightweight threads is that only one can
run at a time, so if one thread blocks in a foreign call, for
example, the other threads cannot continue. The GHC runtime
works around this by making use of full OS threads where
necessary. When the program is built with the @-threaded@
option (to link against the multithreaded version of the
runtime), a thread making a @safe@ foreign call will not block
the other threads in the system; another OS thread will take
over running Haskell threads until the original call returns.
The runtime maintains a pool of these /worker/ threads so that
multiple Haskell threads can be involved in external calls
simultaneously.
The "System.IO" library manages multiplexing in its own way. On
Windows systems it uses @safe@ foreign calls to ensure that
threads doing I\/O operations don't block the whole runtime,
whereas on Unix systems all the currently blocked I\/O requests
are managed by a single thread (the /IO manager thread/) using
a mechanism such as @epoll@ or @kqueue@, depending on what is
provided by the host operating system.
The runtime will run a Haskell thread using any of the available
worker OS threads. If you need control over which particular OS
thread is used to run a given Haskell thread, perhaps because
you need to call a foreign library that uses OS-thread-local
state, then you need bound threads (see "Control.Concurrent#boundthreads").
If you don't use the @-threaded@ option, then the runtime does
not make use of multiple OS threads. Foreign calls will block
all other running Haskell threads until the call returns. The
"System.IO" library still does multiplexing, so there can be multiple
threads doing I\/O, and this is handled internally by the runtime using
@select@.
-}
{- $termination
In a standalone GHC program, only the main thread is
required to terminate in order for the process to terminate.
Thus all other forked threads will simply terminate at the same
time as the main thread (the terminology for this kind of
behaviour is \"daemonic threads\").
If you want the program to wait for child threads to
finish before exiting, you need to program this yourself. A
simple mechanism is to have each child thread write to an
'MVar' when it completes, and have the main
thread wait on all the 'MVar's before
exiting:
> myForkIO :: IO () -> IO (MVar ())
> myForkIO io = do
> mvar <- newEmptyMVar
> forkFinally io (\_ -> putMVar mvar ())
> return mvar
Note that we use 'forkFinally' to make sure that the
'MVar' is written to even if the thread dies or
is killed for some reason.
A better method is to keep a global list of all child
threads which we should wait for at the end of the program:
> children :: MVar [MVar ()]
> children = unsafePerformIO (newMVar [])
>
> waitForChildren :: IO ()
> waitForChildren = do
> cs <- takeMVar children
> case cs of
> [] -> return ()
> m:ms -> do
> putMVar children ms
> takeMVar m
> waitForChildren
>
> forkChild :: IO () -> IO ThreadId
> forkChild io = do
> mvar <- newEmptyMVar
> childs <- takeMVar children
> putMVar children (mvar:childs)
> forkFinally io (\_ -> putMVar mvar ())
>
> main =
> later waitForChildren $
> ...
The main thread principle also applies to calls to Haskell from
outside, using @foreign export@. When the @foreign export@ed
function is invoked, it starts a new main thread, and it returns
when this main thread terminates. If the call causes new
threads to be forked, they may remain in the system after the
@foreign export@ed function has returned.
-}
{- $preemption
GHC implements pre-emptive multitasking: the execution of
threads are interleaved in a random fashion. More specifically,
a thread may be pre-empted whenever it allocates some memory,
which unfortunately means that tight loops which do no
allocation tend to lock out other threads (this only seems to
happen with pathological benchmark-style code, however).
The rescheduling timer runs on a 20ms granularity by
default, but this may be altered using the
@-i\<n\>@ RTS option. After a rescheduling
\"tick\" the running thread is pre-empted as soon as
possible.
One final note: the
@aaaa@ @bbbb@ example may not
work too well on GHC (see Scheduling, above), due
to the locking on a 'System.IO.Handle'. Only one thread
may hold the lock on a 'System.IO.Handle' at any one
time, so if a reschedule happens while a thread is holding the
lock, the other thread won't be able to run. The upshot is that
the switch from @aaaa@ to
@bbbbb@ happens infrequently. It can be
improved by lowering the reschedule tick period. We also have a
patch that causes a reschedule whenever a thread waiting on a
lock is woken up, but haven't found it to be useful for anything
other than this example :-)
-}
#endif /* __GLASGOW_HASKELL__ */
| beni55/haste-compiler | libraries/ghc-7.8/base/Control/Concurrent.hs | bsd-3-clause | 24,702 | 0 | 24 | 6,089 | 2,167 | 1,178 | 989 | 91 | 3 |
module SPARC.CodeGen.Amode (
getAmode
)
where
import {-# SOURCE #-} SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.AddrMode
import SPARC.Imm
import SPARC.Instr
import SPARC.Regs
import SPARC.Base
import NCGMonad
import Size
import Cmm
import OrdList
-- | Generate code to reference a memory address.
getAmode
:: CmmExpr -- ^ expr producing an address
-> NatM Amode
getAmode tree@(CmmRegOff _ _)
= do dflags <- getDynFlags
getAmode (mangleIndexTree dflags tree)
getAmode (CmmMachOp (MO_Sub _) [x, CmmLit (CmmInt i _)])
| fits13Bits (-i)
= do
(reg, code) <- getSomeReg x
let
off = ImmInt (-(fromInteger i))
return (Amode (AddrRegImm reg off) code)
getAmode (CmmMachOp (MO_Add _) [x, CmmLit (CmmInt i _)])
| fits13Bits i
= do
(reg, code) <- getSomeReg x
let
off = ImmInt (fromInteger i)
return (Amode (AddrRegImm reg off) code)
getAmode (CmmMachOp (MO_Add _) [x, y])
= do
(regX, codeX) <- getSomeReg x
(regY, codeY) <- getSomeReg y
let
code = codeX `appOL` codeY
return (Amode (AddrRegReg regX regY) code)
getAmode (CmmLit lit)
= do
let imm__2 = litToImm lit
tmp1 <- getNewRegNat II32
tmp2 <- getNewRegNat II32
let code = toOL [ SETHI (HI imm__2) tmp1
, OR False tmp1 (RIImm (LO imm__2)) tmp2]
return (Amode (AddrRegReg tmp2 g0) code)
getAmode other
= do
(reg, code) <- getSomeReg other
let
off = ImmInt 0
return (Amode (AddrRegImm reg off) code)
| forked-upstream-packages-for-ghcjs/ghc | compiler/nativeGen/SPARC/CodeGen/Amode.hs | bsd-3-clause | 1,625 | 0 | 16 | 487 | 607 | 301 | 306 | 54 | 1 |
module Main where
main = print (fib' 100)
-- This will time out unless memoing works properly
data Nat = Z | S Nat
deriving (Show, Eq)
memo f = g
where
fz = f Z
fs = memo (f . S)
g Z = fz
g (S n) = fs n
-- It is a BAD BUG to inline 'fs' inside g
-- and that happened in 6.4.1, resulting in exponential behaviour
-- memo f = g (f Z) (memo (f . S))
-- = g (f Z) (g (f (S Z)) (memo (f . S . S)))
-- = g (f Z) (g (f (S Z)) (g (f (S (S Z))) (memo (f . S . S . S))))
fib' :: Nat -> Integer
fib' = memo fib
where
fib Z = 0
fib (S Z) = 1
fib (S (S n)) = fib' (S n) + fib' n
instance Num Nat where
fromInteger 0 = Z
fromInteger n = S (fromInteger (n - 1))
Z + n = n
S m + n = S (m + n)
Z * n = Z
S m * n = (m * n) + n
Z - n = Z
S m - Z = S m
S m - S n = m - n
instance Enum Nat where
succ = S
pred Z = Z
pred (S n) = n
toEnum = fromInteger . toInteger
fromEnum Z = 0
fromEnum (S n) = fromEnum n + 1
| ezyang/ghc | testsuite/tests/simplCore/should_run/simplrun005.hs | bsd-3-clause | 1,232 | 0 | 11 | 592 | 415 | 207 | 208 | 31 | 3 |
import Control.Monad
import Data.Word (Word8)
import Foreign.Ptr
import Foreign.Marshal.Array
import GHC.Foreign (peekCStringLen, withCStringLen)
import GHC.IO.Encoding.Failure (CodingFailureMode(..))
import qualified GHC.IO.Encoding.Latin1 as Latin1
import System.IO
import System.IO.Error
-- Tests for single-byte encodings that map directly to Unicode
-- (module GHC.IO.Encoding.Latin1)
eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Left _) = Nothing
eitherToMaybe (Right b) = Just b
decode :: TextEncoding -> [Word8] -> IO (Maybe String)
decode enc xs = fmap eitherToMaybe . tryIOError $ withArrayLen xs (\sz p -> peekCStringLen enc (castPtr p, sz))
encode :: TextEncoding -> String -> IO (Maybe [Word8])
encode enc cs = fmap eitherToMaybe . tryIOError $ withCStringLen enc cs (\(p, sz) -> peekArray sz (castPtr p))
testIO :: (Eq a, Show a) => IO a -> a -> IO ()
testIO action expected = do
result <- action
when (result /= expected) $
putStrLn $ "Test failed: expected " ++ show expected ++ ", but got " ++ show result
-- Test char8-like encodings
test_char8 :: TextEncoding -> IO ()
test_char8 enc = do
testIO (decode enc [0..0xff]) $ Just ['\0'..'\xff']
testIO (encode enc ['\0'..'\x200']) $ Just ([0..0xff] ++ [0..0xff] ++ [0])
-- Test latin1-like encodings
test_latin1 :: CodingFailureMode -> TextEncoding -> IO ()
test_latin1 cfm enc = do
testIO (decode enc [0..0xff]) $ Just ['\0'..'\xff']
testIO (encode enc ['\0'..'\xff']) $ Just [0..0xff]
testIO (encode enc "\xfe\xff\x100\x101\x100\xff\xfe") $ case cfm of
ErrorOnCodingFailure -> Nothing
IgnoreCodingFailure -> Just [0xfe,0xff,0xff,0xfe]
TransliterateCodingFailure -> Just [0xfe,0xff,0x3f,0x3f,0x3f,0xff,0xfe]
-- N.B. The argument "latin1//TRANSLIT" to mkTextEncoding does not
-- correspond to "latin1//TRANSLIT" in iconv! Instead GHC asks iconv
-- to encode to "latin1" and uses its own "evil hack" to insert '?'
-- (ASCII 0x3f) in place of failures. See GHC.IO.Encoding.recoverEncode.
--
-- U+0100 is LATIN CAPITAL LETTER A WITH MACRON, which iconv would
-- transliterate to 'A' (ASCII 0x41). Similarly iconv would
-- transliterate U+0101 LATIN SMALL LETTER A WITH MACRON to 'a'
-- (ASCII 0x61).
RoundtripFailure -> Nothing
test_ascii :: CodingFailureMode -> TextEncoding -> IO ()
test_ascii cfm enc = do
testIO (decode enc [0..0x7f]) $ Just ['\0'..'\x7f']
testIO (decode enc [0x7e,0x7f,0x80,0x81,0x80,0x7f,0x7e]) $ case cfm of
ErrorOnCodingFailure -> Nothing
IgnoreCodingFailure -> Just "\x7e\x7f\x7f\x7e"
TransliterateCodingFailure -> Just "\x7e\x7f\xfffd\xfffd\xfffd\x7f\x7e"
-- Another GHC special: decode invalid input to the Char U+FFFD
-- REPLACEMENT CHARACTER.
RoundtripFailure -> Just "\x7e\x7f\xdc80\xdc81\xdc80\x7f\x7e"
-- GHC's PEP383-style String-encoding of invalid input,
-- see Note [Roundtripping]
testIO (encode enc ['\0'..'\x7f']) $ Just [0..0x7f]
testIO (encode enc "\x7e\x7f\x80\x81\x80\x7f\xe9") $ case cfm of
ErrorOnCodingFailure -> Nothing
IgnoreCodingFailure -> Just [0x7e,0x7f,0x7f]
TransliterateCodingFailure -> Just [0x7e,0x7f,0x3f,0x3f,0x3f,0x7f,0x3f]
-- See comment in test_latin1. iconv -t ASCII//TRANSLIT would encode
-- U+00E9 LATIN SMALL LETTER E WITH ACUTE as 'e' (ASCII 0x65).
RoundtripFailure -> Nothing
-- Test roundtripping for good measure
case cfm of
RoundtripFailure -> do
Just s <- decode enc [0..0xff]
testIO (encode enc s) $ Just [0..0xff]
_ -> return ()
main = do
putStrLn "char8 tests"
test_char8 char8 -- char8 never fails in either direction
-- These use GHC's own implementation
putStrLn "Latin1.ascii tests"
test_ascii ErrorOnCodingFailure (Latin1.ascii)
test_ascii IgnoreCodingFailure (Latin1.mkAscii IgnoreCodingFailure)
test_ascii TransliterateCodingFailure (Latin1.mkAscii TransliterateCodingFailure)
test_ascii RoundtripFailure (Latin1.mkAscii RoundtripFailure)
putStrLn "Latin1.latin1_checked tests"
test_latin1 ErrorOnCodingFailure (Latin1.latin1_checked)
test_latin1 IgnoreCodingFailure (Latin1.mkLatin1_checked IgnoreCodingFailure)
test_latin1 TransliterateCodingFailure (Latin1.mkLatin1_checked TransliterateCodingFailure)
test_latin1 RoundtripFailure (Latin1.mkLatin1_checked RoundtripFailure)
-- These use iconv (normally, unless it is broken)
putStrLn "mkTextEncoding ASCII tests"
test_ascii ErrorOnCodingFailure =<< mkTextEncoding "ASCII"
test_ascii IgnoreCodingFailure =<< mkTextEncoding "ASCII//IGNORE"
test_ascii TransliterateCodingFailure =<< mkTextEncoding "ASCII//TRANSLIT"
test_ascii RoundtripFailure =<< mkTextEncoding "ASCII//ROUNDTRIP"
putStrLn "mkTextEncoding latin1 tests"
test_latin1 ErrorOnCodingFailure =<< mkTextEncoding "latin1"
test_latin1 IgnoreCodingFailure =<< mkTextEncoding "latin1//IGNORE"
test_latin1 TransliterateCodingFailure =<< mkTextEncoding "latin1//TRANSLIT"
test_latin1 RoundtripFailure =<< mkTextEncoding "latin1//ROUNDTRIP"
| ezyang/ghc | libraries/base/tests/IO/encoding005.hs | bsd-3-clause | 5,035 | 0 | 15 | 818 | 1,244 | 622 | 622 | 76 | 8 |
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
{-# LANGUAGE FlexibleInstances, IncoherentInstances, PatternGuards #-}
module Idris.IdeMode(parseMessage, convSExp, WhatDocs(..), IdeModeCommand(..), sexpToCommand, toSExp, SExp(..), SExpable, Opt(..), ideModeEpoch, getLen, getNChar, sExpToString) where
import Text.Printf
import Numeric
import Data.List
import Data.Maybe (isJust)
import qualified Data.Binary as Binary
import qualified Data.ByteString.Base64 as Base64
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Text as T
import Text.Trifecta hiding (Err)
import Text.Trifecta.Delta
import System.IO
import Idris.Core.TT
import Idris.Core.Binary
import Control.Applicative hiding (Const)
getNChar :: Handle -> Int -> String -> IO (String)
getNChar _ 0 s = return (reverse s)
getNChar h n s = do c <- hGetChar h
getNChar h (n - 1) (c : s)
getLen :: Handle -> IO (Either Err Int)
getLen h = do s <- getNChar h 6 ""
case readHex s of
((num, ""):_) -> return $ Right num
_ -> return $ Left . Msg $ "Couldn't read length " ++ s
data SExp = SexpList [SExp]
| StringAtom String
| BoolAtom Bool
| IntegerAtom Integer
| SymbolAtom String
deriving ( Eq, Show )
sExpToString :: SExp -> String
sExpToString (StringAtom s) = "\"" ++ escape s ++ "\""
sExpToString (BoolAtom True) = ":True"
sExpToString (BoolAtom False) = ":False"
sExpToString (IntegerAtom i) = printf "%d" i
sExpToString (SymbolAtom s) = ":" ++ s
sExpToString (SexpList l) = "(" ++ intercalate " " (map sExpToString l) ++ ")"
class SExpable a where
toSExp :: a -> SExp
instance SExpable SExp where
toSExp a = a
instance SExpable Bool where
toSExp True = BoolAtom True
toSExp False = BoolAtom False
instance SExpable String where
toSExp s = StringAtom s
instance SExpable Integer where
toSExp n = IntegerAtom n
instance SExpable Int where
toSExp n = IntegerAtom (toInteger n)
instance SExpable Name where
toSExp s = StringAtom (show s)
instance (SExpable a) => SExpable (Maybe a) where
toSExp Nothing = SexpList [SymbolAtom "Nothing"]
toSExp (Just a) = SexpList [SymbolAtom "Just", toSExp a]
instance (SExpable a) => SExpable [a] where
toSExp l = SexpList (map toSExp l)
instance (SExpable a, SExpable b) => SExpable (a, b) where
toSExp (l, r) = SexpList [toSExp l, toSExp r]
instance (SExpable a, SExpable b, SExpable c) => SExpable (a, b, c) where
toSExp (l, m, n) = SexpList [toSExp l, toSExp m, toSExp n]
instance (SExpable a, SExpable b, SExpable c, SExpable d) => SExpable (a, b, c, d) where
toSExp (l, m, n, o) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o]
instance (SExpable a, SExpable b, SExpable c, SExpable d, SExpable e) =>
SExpable (a, b, c, d, e) where
toSExp (l, m, n, o, p) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o, toSExp p]
instance SExpable NameOutput where
toSExp TypeOutput = SymbolAtom "type"
toSExp FunOutput = SymbolAtom "function"
toSExp DataOutput = SymbolAtom "data"
toSExp MetavarOutput = SymbolAtom "metavar"
toSExp PostulateOutput = SymbolAtom "postulate"
maybeProps :: SExpable a => [(String, Maybe a)] -> [(SExp, SExp)]
maybeProps [] = []
maybeProps ((n, Just p):ps) = (SymbolAtom n, toSExp p) : maybeProps ps
maybeProps ((n, Nothing):ps) = maybeProps ps
constTy :: Const -> String
constTy (I _) = "Int"
constTy (BI _) = "Integer"
constTy (Fl _) = "Double"
constTy (Ch _) = "Char"
constTy (Str _) = "String"
constTy (B8 _) = "Bits8"
constTy (B16 _) = "Bits16"
constTy (B32 _) = "Bits32"
constTy (B64 _) = "Bits64"
constTy _ = "Type"
namespaceOf :: Name -> Maybe String
namespaceOf (NS _ ns) = Just (intercalate "." $ reverse (map T.unpack ns))
namespaceOf _ = Nothing
instance SExpable OutputAnnotation where
toSExp (AnnName n ty d t) = toSExp $ [(SymbolAtom "name", StringAtom (show n)),
(SymbolAtom "implicit", BoolAtom False)] ++
maybeProps [("decor", ty)] ++
maybeProps [("doc-overview", d), ("type", t)] ++
maybeProps [("namespace", namespaceOf n)]
toSExp (AnnBoundName n imp) = toSExp [(SymbolAtom "name", StringAtom (show n)),
(SymbolAtom "decor", SymbolAtom "bound"),
(SymbolAtom "implicit", BoolAtom imp)]
toSExp (AnnConst c) = toSExp [(SymbolAtom "decor",
SymbolAtom (if constIsType c then "type" else "data")),
(SymbolAtom "type", StringAtom (constTy c)),
(SymbolAtom "doc-overview", StringAtom (constDocs c)),
(SymbolAtom "name", StringAtom (show c))]
toSExp (AnnData ty doc) = toSExp [(SymbolAtom "decor", SymbolAtom "data"),
(SymbolAtom "type", StringAtom ty),
(SymbolAtom "doc-overview", StringAtom doc)]
toSExp (AnnType name doc) = toSExp $ [(SymbolAtom "decor", SymbolAtom "type"),
(SymbolAtom "type", StringAtom "Type"),
(SymbolAtom "doc-overview", StringAtom doc)] ++
if not (null name) then [(SymbolAtom "name", StringAtom name)] else []
toSExp AnnKeyword = toSExp [(SymbolAtom "decor", SymbolAtom "keyword")]
toSExp (AnnFC fc) = toSExp [(SymbolAtom "source-loc", toSExp fc)]
toSExp (AnnTextFmt fmt) = toSExp [(SymbolAtom "text-formatting", SymbolAtom format)]
where format = case fmt of
BoldText -> "bold"
ItalicText -> "italic"
UnderlineText -> "underline"
toSExp (AnnLink url) = toSExp [(SymbolAtom "link-href", StringAtom url)]
toSExp (AnnTerm bnd tm)
| termSmallerThan 1000 tm = toSExp [(SymbolAtom "tt-term", StringAtom (encodeTerm bnd tm))]
| otherwise = SexpList []
toSExp (AnnSearchResult ordr) = toSExp [(SymbolAtom "doc-overview",
StringAtom ("Result type is " ++ descr))]
where descr = case ordr of
EQ -> "isomorphic"
LT -> "more general than searched type"
GT -> "more specific than searched type"
toSExp (AnnErr e) = toSExp [(SymbolAtom "error", StringAtom (encodeErr e))]
toSExp (AnnNamespace ns file) =
toSExp $ [(SymbolAtom "namespace", StringAtom (intercalate "." (map T.unpack ns)))] ++
[(SymbolAtom "decor", SymbolAtom $ if isJust file then "module" else "namespace")] ++
maybeProps [("source-file", file)]
toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)]
toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)]
encodeTerm :: [(Name, Bool)] -> Term -> String
encodeTerm bnd tm = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $
(bnd, tm)
decodeTerm :: String -> ([(Name, Bool)], Term)
decodeTerm = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString
encodeErr :: Err -> String
encodeErr e = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ e
decodeErr :: String -> Err
decodeErr = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString
instance SExpable FC where
toSExp (FC f (sl, sc) (el, ec)) =
toSExp ((SymbolAtom "filename", StringAtom f),
(SymbolAtom "start", IntegerAtom (toInteger sl), IntegerAtom (toInteger sc)),
(SymbolAtom "end", IntegerAtom (toInteger el), IntegerAtom (toInteger ec)))
toSExp NoFC = toSExp ([] :: [String])
toSExp (FileFC f) = toSExp [(SymbolAtom "filename", StringAtom f)]
escape :: String -> String
escape = concatMap escapeChar
where
escapeChar '\\' = "\\\\"
escapeChar '"' = "\\\""
escapeChar c = [c]
pSExp = do xs <- between (char '(') (char ')') (pSExp `sepBy` (char ' '))
return (SexpList xs)
<|> atom
atom = do string "nil"; return (SexpList [])
<|> do char ':'; x <- atomC; return x
<|> do char '"'; xs <- many quotedChar; char '"'; return (StringAtom xs)
<|> do ints <- some digit
case readDec ints of
((num, ""):_) -> return (IntegerAtom (toInteger num))
_ -> return (StringAtom ints)
atomC = do string "True"; return (BoolAtom True)
<|> do string "False"; return (BoolAtom False)
<|> do xs <- many (noneOf " \n\t\r\"()"); return (SymbolAtom xs)
quotedChar = try (string "\\\\" >> return '\\')
<|> try (string "\\\"" >> return '"')
<|> noneOf "\""
parseSExp :: String -> Result SExp
parseSExp = parseString pSExp (Directed (UTF8.fromString "(unknown)") 0 0 0 0)
data Opt = ShowImpl | ErrContext deriving Show
data WhatDocs = Overview | Full
data IdeModeCommand = REPLCompletions String
| Interpret String
| TypeOf String
| CaseSplit Int String
| AddClause Int String
| AddProofClause Int String
| AddMissing Int String
| MakeWithBlock Int String
| MakeCaseBlock Int String
| ProofSearch Bool Int String [String] (Maybe Int) -- ^^ Recursive?, line, name, hints, depth
| MakeLemma Int String
| LoadFile String (Maybe Int)
| DocsFor String WhatDocs
| Apropos String
| GetOpts
| SetOpt Opt Bool
| Metavariables Int -- ^^ the Int is the column count for pretty-printing
| WhoCalls String
| CallsWho String
| BrowseNS String
| TermNormalise [(Name, Bool)] Term
| TermShowImplicits [(Name, Bool)] Term
| TermNoImplicits [(Name, Bool)] Term
| TermElab [(Name, Bool)] Term
| PrintDef String
| ErrString Err
| ErrPPrint Err
| GetIdrisVersion
sexpToCommand :: SExp -> Maybe IdeModeCommand
sexpToCommand (SexpList (x:[])) = sexpToCommand x
sexpToCommand (SexpList [SymbolAtom "interpret", StringAtom cmd]) = Just (Interpret cmd)
sexpToCommand (SexpList [SymbolAtom "repl-completions", StringAtom prefix]) = Just (REPLCompletions prefix)
sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename, IntegerAtom line]) = Just (LoadFile filename (Just (fromInteger line)))
sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename]) = Just (LoadFile filename Nothing)
sexpToCommand (SexpList [SymbolAtom "type-of", StringAtom name]) = Just (TypeOf name)
sexpToCommand (SexpList [SymbolAtom "case-split", IntegerAtom line, StringAtom name]) = Just (CaseSplit (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "add-clause", IntegerAtom line, StringAtom name]) = Just (AddClause (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "add-proof-clause", IntegerAtom line, StringAtom name]) = Just (AddProofClause (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "add-missing", IntegerAtom line, StringAtom name]) = Just (AddMissing (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "make-with", IntegerAtom line, StringAtom name]) = Just (MakeWithBlock (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "make-case", IntegerAtom line, StringAtom name]) = Just (MakeCaseBlock (fromInteger line) name)
-- The Boolean in ProofSearch means "search recursively"
-- If it's False, that means "refine", i.e. apply the name and fill in any
-- arguments which can be done by unification.
sexpToCommand (SexpList (SymbolAtom "proof-search" : IntegerAtom line : StringAtom name : rest))
| [] <- rest = Just (ProofSearch True (fromInteger line) name [] Nothing)
| [SexpList hintexp] <- rest
, Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints Nothing)
| [SexpList hintexp, IntegerAtom depth] <- rest
, Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints (Just (fromInteger depth)))
where getHints = mapM (\h -> case h of
StringAtom s -> Just s
_ -> Nothing)
sexpToCommand (SexpList [SymbolAtom "make-lemma", IntegerAtom line, StringAtom name]) = Just (MakeLemma (fromInteger line) name)
sexpToCommand (SexpList [SymbolAtom "refine", IntegerAtom line, StringAtom name, StringAtom hint]) = Just (ProofSearch False (fromInteger line) name [hint] Nothing)
sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name]) = Just (DocsFor name Full)
sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name, SymbolAtom s])
| Just w <- lookup s opts = Just (DocsFor name w)
where opts = [("overview", Overview), ("full", Full)]
sexpToCommand (SexpList [SymbolAtom "apropos", StringAtom search]) = Just (Apropos search)
sexpToCommand (SymbolAtom "get-options") = Just GetOpts
sexpToCommand (SexpList [SymbolAtom "set-option", SymbolAtom s, BoolAtom b])
| Just opt <- lookup s opts = Just (SetOpt opt b)
where opts = [("show-implicits", ShowImpl), ("error-context", ErrContext)] --TODO support more options. Issue #1611 in the Issue tracker. https://github.com/idris-lang/Idris-dev/issues/1611
sexpToCommand (SexpList [SymbolAtom "metavariables", IntegerAtom cols]) = Just (Metavariables (fromIntegral cols))
sexpToCommand (SexpList [SymbolAtom "who-calls", StringAtom name]) = Just (WhoCalls name)
sexpToCommand (SexpList [SymbolAtom "calls-who", StringAtom name]) = Just (CallsWho name)
sexpToCommand (SexpList [SymbolAtom "browse-namespace", StringAtom ns]) = Just (BrowseNS ns)
sexpToCommand (SexpList [SymbolAtom "normalise-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in
Just (TermNormalise bnd tm)
sexpToCommand (SexpList [SymbolAtom "show-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in
Just (TermShowImplicits bnd tm)
sexpToCommand (SexpList [SymbolAtom "hide-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in
Just (TermNoImplicits bnd tm)
sexpToCommand (SexpList [SymbolAtom "elaborate-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in
Just (TermElab bnd tm)
sexpToCommand (SexpList [SymbolAtom "print-definition", StringAtom name]) = Just (PrintDef name)
sexpToCommand (SexpList [SymbolAtom "error-string", StringAtom encoded]) = Just . ErrString . decodeErr $ encoded
sexpToCommand (SexpList [SymbolAtom "error-pprint", StringAtom encoded]) = Just . ErrPPrint . decodeErr $ encoded
sexpToCommand (SymbolAtom "version") = Just GetIdrisVersion
sexpToCommand _ = Nothing
parseMessage :: String -> Either Err (SExp, Integer)
parseMessage x = case receiveString x of
Right (SexpList [cmd, (IntegerAtom id)]) -> Right (cmd, id)
Right x -> Left . Msg $ "Invalid message " ++ show x
Left err -> Left err
receiveString :: String -> Either Err SExp
receiveString x =
case parseSExp x of
Failure _ -> Left . Msg $ "parse failure"
Success r -> Right r
convSExp :: SExpable a => String -> a -> Integer -> String
convSExp pre s id =
let sex = SexpList [SymbolAtom pre, toSExp s, IntegerAtom id] in
let str = sExpToString sex in
(getHexLength str) ++ str
getHexLength :: String -> String
getHexLength s = printf "%06x" (1 + (length s))
-- | The version of the IDE mode command set. Increment this when you
-- change it so clients can adapt.
ideModeEpoch :: Int
ideModeEpoch = 1
| ExNexu/Idris-dev | src/Idris/IdeMode.hs | bsd-3-clause | 16,974 | 0 | 16 | 5,044 | 5,500 | 2,816 | 2,684 | 276 | 3 |
{-# LANGUAGE TypeFamilies #-}
module Main where
data A a
type T a = A a
f :: (A a ~ T Int) => a -> Int
f x = x
main :: IO ()
main = return () | siddhanathan/ghc | testsuite/tests/typecheck/should_compile/GivenTypeSynonym.hs | bsd-3-clause | 163 | 0 | 8 | 60 | 73 | 40 | 33 | -1 | -1 |
import Control.Concurrent
import Control.Monad
import Control.Exception
import System.Mem
-- caused an assertion failure with -debug in 7.0.1 (#4813)
main = do
m <- newEmptyMVar
ts <- replicateM 100 $ mask_ $ forkIO $ threadDelay 100000; putMVar m ()
mapM_ killThread (reverse (init ts))
takeMVar m
| urbanslug/ghc | testsuite/tests/concurrent/should_run/T4813.hs | bsd-3-clause | 313 | 0 | 11 | 59 | 96 | 46 | 50 | 9 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | Kernel extraction.
--
-- In the following, I will use the term "width" to denote the amount
-- of immediate parallelism in a map - that is, the outer size of the
-- array(s) being used as input.
--
-- = Basic Idea
--
-- If we have:
--
-- @
-- map
-- map(f)
-- stms_a...
-- map(g)
-- @
--
-- Then we want to distribute to:
--
-- @
-- map
-- map(f)
-- map
-- stms_a
-- map
-- map(g)
-- @
--
-- But for now only if
--
-- (0) it can be done without creating irregular arrays.
-- Specifically, the size of the arrays created by @map(f)@, by
-- @map(g)@ and whatever is created by @stms_a@ that is also used
-- in @map(g)@, must be invariant to the outermost loop.
--
-- (1) the maps are _balanced_. That is, the functions @f@ and @g@
-- must do the same amount of work for every iteration.
--
-- The advantage is that the map-nests containing @map(f)@ and
-- @map(g)@ can now be trivially flattened at no cost, thus exposing
-- more parallelism. Note that the @stms_a@ map constitutes array
-- expansion, which requires additional storage.
--
-- = Distributing Sequential Loops
--
-- As a starting point, sequential loops are treated like scalar
-- expressions. That is, not distributed. However, sometimes it can
-- be worthwhile to distribute if they contain a map:
--
-- @
-- map
-- loop
-- map
-- map
-- @
--
-- If we distribute the loop and interchange the outer map into the
-- loop, we get this:
--
-- @
-- loop
-- map
-- map
-- map
-- map
-- @
--
-- Now more parallelism may be available.
--
-- = Unbalanced Maps
--
-- Unbalanced maps will as a rule be sequentialised, but sometimes,
-- there is another way. Assume we find this:
--
-- @
-- map
-- map(f)
-- map(g)
-- map
-- @
--
-- Presume that @map(f)@ is unbalanced. By the simple rule above, we
-- would then fully sequentialise it, resulting in this:
--
-- @
-- map
-- loop
-- map
-- map
-- @
--
-- == Balancing by Loop Interchange
--
-- The above is not ideal, as we cannot flatten the @map-loop@ nest,
-- and we are thus limited in the amount of parallelism available.
--
-- But assume now that the width of @map(g)@ is invariant to the outer
-- loop. Then if possible, we can interchange @map(f)@ and @map(g)@,
-- sequentialise @map(f)@ and distribute, interchanging the outer
-- parallel loop into the sequential loop:
--
-- @
-- loop(f)
-- map
-- map(g)
-- map
-- map
-- @
--
-- After flattening the two nests we can obtain more parallelism.
--
-- When distributing a map, we also need to distribute everything that
-- the map depends on - possibly as its own map. When distributing a
-- set of scalar bindings, we will need to know which of the binding
-- results are used afterwards. Hence, we will need to compute usage
-- information.
--
-- = Redomap
--
-- Redomap can be handled much like map. Distributed loops are
-- distributed as maps, with the parameters corresponding to the
-- neutral elements added to their bodies. The remaining loop will
-- remain a redomap. Example:
--
-- @
-- redomap(op,
-- fn (v) =>
-- map(f)
-- map(g),
-- e,a)
-- @
--
-- distributes to
--
-- @
-- let b = map(fn v =>
-- let acc = e
-- map(f),
-- a)
-- redomap(op,
-- fn (v,dist) =>
-- map(g),
-- e,a,b)
-- @
--
-- Note that there may be further kernel extraction opportunities
-- inside the @map(f)@. The downside of this approach is that the
-- intermediate array (@b@ above) must be written to main memory. An
-- often better approach is to just turn the entire @redomap@ into a
-- single kernel.
module Futhark.Pass.ExtractKernels (extractKernels) where
import Control.Monad.Identity
import Control.Monad.RWS.Strict
import Control.Monad.Reader
import Data.Bifunctor (first)
import Data.Maybe
import qualified Futhark.IR.GPU as Out
import Futhark.IR.GPU.Op
import Futhark.IR.SOACS
import Futhark.IR.SOACS.Simplify (simplifyStms)
import Futhark.MonadFreshNames
import Futhark.Pass
import Futhark.Pass.ExtractKernels.BlockedKernel
import Futhark.Pass.ExtractKernels.DistributeNests
import Futhark.Pass.ExtractKernels.Distribution
import Futhark.Pass.ExtractKernels.ISRWIM
import Futhark.Pass.ExtractKernels.Intragroup
import Futhark.Pass.ExtractKernels.StreamKernel
import Futhark.Pass.ExtractKernels.ToGPU
import Futhark.Tools
import qualified Futhark.Transform.FirstOrderTransform as FOT
import Futhark.Transform.Rename
import Futhark.Util.Log
import Prelude hiding (log)
-- | Transform a program using SOACs to a program using explicit
-- kernels, using the kernel extraction transformation.
extractKernels :: Pass SOACS Out.GPU
extractKernels =
Pass
{ passName = "extract kernels",
passDescription = "Perform kernel extraction",
passFunction = transformProg
}
transformProg :: Prog SOACS -> PassM (Prog Out.GPU)
transformProg (Prog consts funs) = do
consts' <- runDistribM $ transformStms mempty $ stmsToList consts
funs' <- mapM (transformFunDef $ scopeOf consts') funs
return $ Prog consts' funs'
-- In order to generate more stable threshold names, we keep track of
-- the numbers used for thresholds separately from the ordinary name
-- source,
data State = State
{ stateNameSource :: VNameSource,
stateThresholdCounter :: Int
}
newtype DistribM a = DistribM (RWS (Scope Out.GPU) Log State a)
deriving
( Functor,
Applicative,
Monad,
HasScope Out.GPU,
LocalScope Out.GPU,
MonadState State,
MonadLogger
)
instance MonadFreshNames DistribM where
getNameSource = gets stateNameSource
putNameSource src = modify $ \s -> s {stateNameSource = src}
runDistribM ::
(MonadLogger m, MonadFreshNames m) =>
DistribM a ->
m a
runDistribM (DistribM m) = do
(x, msgs) <- modifyNameSource $ \src ->
let (x, s, msgs) = runRWS m mempty (State src 0)
in ((x, msgs), stateNameSource s)
addLog msgs
return x
transformFunDef ::
(MonadFreshNames m, MonadLogger m) =>
Scope Out.GPU ->
FunDef SOACS ->
m (Out.FunDef Out.GPU)
transformFunDef scope (FunDef entry attrs name rettype params body) = runDistribM $ do
body' <-
localScope (scope <> scopeOfFParams params) $
transformBody mempty body
return $ FunDef entry attrs name rettype params body'
type GPUStms = Stms Out.GPU
transformBody :: KernelPath -> Body -> DistribM (Out.Body Out.GPU)
transformBody path body = do
stms <- transformStms path $ stmsToList $ bodyStms body
return $ mkBody stms $ bodyResult body
transformStms :: KernelPath -> [Stm] -> DistribM GPUStms
transformStms _ [] =
return mempty
transformStms path (stm : stms) =
sequentialisedUnbalancedStm stm >>= \case
Nothing -> do
stm' <- transformStm path stm
inScopeOf stm' $
(stm' <>) <$> transformStms path stms
Just stms' ->
transformStms path $ stmsToList stms' <> stms
unbalancedLambda :: Lambda -> Bool
unbalancedLambda orig_lam =
unbalancedBody (namesFromList $ map paramName $ lambdaParams orig_lam) $
lambdaBody orig_lam
where
subExpBound (Var i) bound = i `nameIn` bound
subExpBound (Constant _) _ = False
unbalancedBody bound body =
any (unbalancedStm (bound <> boundInBody body) . stmExp) $
bodyStms body
-- XXX - our notion of balancing is probably still too naive.
unbalancedStm bound (Op (Stream w _ _ _ _)) =
w `subExpBound` bound
unbalancedStm bound (Op (Screma w _ _)) =
w `subExpBound` bound
unbalancedStm _ Op {} =
False
unbalancedStm _ DoLoop {} = False
unbalancedStm bound (WithAcc _ lam) =
unbalancedBody bound (lambdaBody lam)
unbalancedStm bound (If cond tbranch fbranch _) =
cond `subExpBound` bound
&& (unbalancedBody bound tbranch || unbalancedBody bound fbranch)
unbalancedStm _ (BasicOp _) =
False
unbalancedStm _ (Apply fname _ _ _) =
not $ isBuiltInFunction fname
sequentialisedUnbalancedStm :: Stm -> DistribM (Maybe (Stms SOACS))
sequentialisedUnbalancedStm (Let pat _ (Op soac@(Screma _ _ form)))
| Just (_, lam2) <- isRedomapSOAC form,
unbalancedLambda lam2,
lambdaContainsParallelism lam2 = do
types <- asksScope scopeForSOACs
Just . snd <$> runBuilderT (FOT.transformSOAC pat soac) types
sequentialisedUnbalancedStm _ =
return Nothing
cmpSizeLe ::
String ->
Out.SizeClass ->
[SubExp] ->
DistribM ((SubExp, Name), Out.Stms Out.GPU)
cmpSizeLe desc size_class to_what = do
x <- gets stateThresholdCounter
modify $ \s -> s {stateThresholdCounter = x + 1}
let size_key = nameFromString $ desc ++ "_" ++ show x
runBuilder $ do
to_what' <-
letSubExp "comparatee"
=<< foldBinOp (Mul Int64 OverflowUndef) (intConst Int64 1) to_what
cmp_res <- letSubExp desc $ Op $ SizeOp $ CmpSizeLe size_key size_class to_what'
return (cmp_res, size_key)
kernelAlternatives ::
(MonadFreshNames m, HasScope Out.GPU m) =>
Out.Pat Out.GPU ->
Out.Body Out.GPU ->
[(SubExp, Out.Body Out.GPU)] ->
m (Out.Stms Out.GPU)
kernelAlternatives pat default_body [] = runBuilder_ $ do
ses <- bodyBind default_body
forM_ (zip (patNames pat) ses) $ \(name, SubExpRes cs se) ->
certifying cs $ letBindNames [name] $ BasicOp $ SubExp se
kernelAlternatives pat default_body ((cond, alt) : alts) = runBuilder_ $ do
alts_pat <- fmap Pat . forM (patElems pat) $ \pe -> do
name <- newVName $ baseString $ patElemName pe
return pe {patElemName = name}
alt_stms <- kernelAlternatives alts_pat default_body alts
let alt_body = mkBody alt_stms $ varsRes $ patNames alts_pat
letBind pat $
If cond alt alt_body $
IfDec (staticShapes (patTypes pat)) IfEquiv
transformLambda :: KernelPath -> Lambda -> DistribM (Out.Lambda Out.GPU)
transformLambda path (Lambda params body ret) =
Lambda params
<$> localScope (scopeOfLParams params) (transformBody path body)
<*> pure ret
transformStm :: KernelPath -> Stm -> DistribM GPUStms
transformStm _ stm
| "sequential" `inAttrs` stmAuxAttrs (stmAux stm) =
runBuilder_ $ FOT.transformStmRecursively stm
transformStm path (Let pat aux (Op soac))
| "sequential_outer" `inAttrs` stmAuxAttrs aux =
transformStms path . stmsToList . fmap (certify (stmAuxCerts aux))
=<< runBuilder_ (FOT.transformSOAC pat soac)
transformStm path (Let pat aux (If c tb fb rt)) = do
tb' <- transformBody path tb
fb' <- transformBody path fb
return $ oneStm $ Let pat aux $ If c tb' fb' rt
transformStm path (Let pat aux (WithAcc inputs lam)) =
oneStm . Let pat aux
<$> (WithAcc (map transformInput inputs) <$> transformLambda path lam)
where
transformInput (shape, arrs, op) =
(shape, arrs, fmap (first soacsLambdaToGPU) op)
transformStm path (Let pat aux (DoLoop merge form body)) =
localScope (castScope (scopeOf form) <> scopeOfFParams params) $
oneStm . Let pat aux . DoLoop merge form' <$> transformBody path body
where
params = map fst merge
form' = case form of
WhileLoop cond ->
WhileLoop cond
ForLoop i it bound ps ->
ForLoop i it bound ps
transformStm path (Let pat aux (Op (Screma w arrs form)))
| Just lam <- isMapSOAC form =
onMap path $ MapLoop pat aux w lam arrs
transformStm path (Let res_pat (StmAux cs _ _) (Op (Screma w arrs form)))
| Just scans <- isScanSOAC form,
Scan scan_lam nes <- singleScan scans,
Just do_iswim <- iswim res_pat w scan_lam $ zip nes arrs = do
types <- asksScope scopeForSOACs
transformStms path . stmsToList . snd =<< runBuilderT (certifying cs do_iswim) types
| Just (scans, map_lam) <- isScanomapSOAC form = runBuilder_ $ do
scan_ops <- forM scans $ \(Scan scan_lam nes) -> do
(scan_lam', nes', shape) <- determineReduceOp scan_lam nes
let scan_lam'' = soacsLambdaToGPU scan_lam'
return $ SegBinOp Noncommutative scan_lam'' nes' shape
let map_lam_sequential = soacsLambdaToGPU map_lam
lvl <- segThreadCapped [w] "segscan" $ NoRecommendation SegNoVirt
addStms . fmap (certify cs)
=<< segScan lvl res_pat mempty w scan_ops map_lam_sequential arrs [] []
transformStm path (Let res_pat aux (Op (Screma w arrs form)))
| Just [Reduce comm red_fun nes] <- isReduceSOAC form,
let comm'
| commutativeLambda red_fun = Commutative
| otherwise = comm,
Just do_irwim <- irwim res_pat w comm' red_fun $ zip nes arrs = do
types <- asksScope scopeForSOACs
stms <- fst <$> runBuilderT (simplifyStms =<< collectStms_ (auxing aux do_irwim)) types
transformStms path $ stmsToList stms
transformStm path (Let pat aux@(StmAux cs _ _) (Op (Screma w arrs form)))
| Just (reds, map_lam) <- isRedomapSOAC form = do
let paralleliseOuter = runBuilder_ $ do
red_ops <- forM reds $ \(Reduce comm red_lam nes) -> do
(red_lam', nes', shape) <- determineReduceOp red_lam nes
let comm'
| commutativeLambda red_lam' = Commutative
| otherwise = comm
red_lam'' = soacsLambdaToGPU red_lam'
return $ SegBinOp comm' red_lam'' nes' shape
let map_lam_sequential = soacsLambdaToGPU map_lam
lvl <- segThreadCapped [w] "segred" $ NoRecommendation SegNoVirt
addStms . fmap (certify cs)
=<< nonSegRed lvl pat w red_ops map_lam_sequential arrs
outerParallelBody =
renameBody
=<< (mkBody <$> paralleliseOuter <*> pure (varsRes (patNames pat)))
paralleliseInner path' = do
(mapstm, redstm) <-
redomapToMapAndReduce pat (w, reds, map_lam, arrs)
types <- asksScope scopeForSOACs
transformStms path' . stmsToList <=< (`runBuilderT_` types) $
addStms =<< simplifyStms (stmsFromList [certify cs mapstm, certify cs redstm])
innerParallelBody path' =
renameBody
=<< (mkBody <$> paralleliseInner path' <*> pure (varsRes (patNames pat)))
if not (lambdaContainsParallelism map_lam)
|| "sequential_inner" `inAttrs` stmAuxAttrs aux
then paralleliseOuter
else do
((outer_suff, outer_suff_key), suff_stms) <-
sufficientParallelism "suff_outer_redomap" [w] path Nothing
outer_stms <- outerParallelBody
inner_stms <- innerParallelBody ((outer_suff_key, False) : path)
(suff_stms <>) <$> kernelAlternatives pat inner_stms [(outer_suff, outer_stms)]
-- Streams can be handled in two different ways - either we
-- sequentialise the body or we keep it parallel and distribute.
transformStm path (Let pat aux@(StmAux cs _ _) (Op (Stream w arrs Parallel {} [] map_fun)))
| not ("sequential_inner" `inAttrs` stmAuxAttrs aux) = do
-- No reduction part. Remove the stream and leave the body
-- parallel. It will be distributed.
types <- asksScope scopeForSOACs
transformStms path . stmsToList . snd
=<< runBuilderT (certifying cs $ sequentialStreamWholeArray pat w [] map_fun arrs) types
transformStm path (Let pat aux@(StmAux cs _ _) (Op (Stream w arrs (Parallel o comm red_fun) nes fold_fun)))
| "sequential_inner" `inAttrs` stmAuxAttrs aux =
paralleliseOuter path
| otherwise = do
((outer_suff, outer_suff_key), suff_stms) <-
sufficientParallelism "suff_outer_stream" [w] path Nothing
outer_stms <- outerParallelBody ((outer_suff_key, True) : path)
inner_stms <- innerParallelBody ((outer_suff_key, False) : path)
(suff_stms <>)
<$> kernelAlternatives pat inner_stms [(outer_suff, outer_stms)]
where
paralleliseOuter path'
| not $ all primType $ lambdaReturnType red_fun = do
-- Split into a chunked map and a reduction, with the latter
-- further transformed.
let fold_fun' = soacsLambdaToGPU fold_fun
let (red_pat_elems, concat_pat_elems) =
splitAt (length nes) $ patElems pat
red_pat = Pat red_pat_elems
((num_threads, red_results), stms) <-
streamMap
segThreadCapped
(map (baseString . patElemName) red_pat_elems)
concat_pat_elems
w
Noncommutative
fold_fun'
nes
arrs
reduce_soac <- reduceSOAC [Reduce comm' red_fun nes]
(stms <>)
<$> inScopeOf
stms
( transformStm path' $
Let red_pat aux {stmAuxAttrs = mempty} $
Op (Screma num_threads red_results reduce_soac)
)
| otherwise = do
let red_fun_sequential = soacsLambdaToGPU red_fun
fold_fun_sequential = soacsLambdaToGPU fold_fun
fmap (certify cs)
<$> streamRed
segThreadCapped
pat
w
comm'
red_fun_sequential
fold_fun_sequential
nes
arrs
outerParallelBody path' =
renameBody
=<< (mkBody <$> paralleliseOuter path' <*> pure (varsRes (patNames pat)))
paralleliseInner path' = do
types <- asksScope scopeForSOACs
transformStms path' . fmap (certify cs) . stmsToList . snd
=<< runBuilderT (sequentialStreamWholeArray pat w nes fold_fun arrs) types
innerParallelBody path' =
renameBody
=<< (mkBody <$> paralleliseInner path' <*> pure (varsRes (patNames pat)))
comm'
| commutativeLambda red_fun, o /= InOrder = Commutative
| otherwise = comm
transformStm path (Let pat (StmAux cs _ _) (Op (Screma w arrs form))) = do
-- This screma is too complicated for us to immediately do
-- anything, so split it up and try again.
scope <- asksScope scopeForSOACs
transformStms path . map (certify cs) . stmsToList . snd
=<< runBuilderT (dissectScrema pat w form arrs) scope
transformStm path (Let pat _ (Op (Stream w arrs Sequential nes fold_fun))) = do
-- Remove the stream and leave the body parallel. It will be
-- distributed.
types <- asksScope scopeForSOACs
transformStms path . stmsToList . snd
=<< runBuilderT (sequentialStreamWholeArray pat w nes fold_fun arrs) types
transformStm _ (Let pat (StmAux cs _ _) (Op (Scatter w ivs lam as))) = runBuilder_ $ do
let lam' = soacsLambdaToGPU lam
write_i <- newVName "write_i"
let (as_ws, _, _) = unzip3 as
kstms = bodyStms $ lambdaBody lam'
krets = do
(a_w, a, is_vs) <- groupScatterResults as $ bodyResult $ lambdaBody lam'
let res_cs =
foldMap (foldMap resCerts . fst) is_vs
<> foldMap (resCerts . snd) is_vs
is_vs' = [(Slice $ map (DimFix . resSubExp) is, resSubExp v) | (is, v) <- is_vs]
return $ WriteReturns res_cs a_w a is_vs'
body = KernelBody () kstms krets
inputs = do
(p, p_a) <- zip (lambdaParams lam') ivs
return $ KernelInput (paramName p) (paramType p) p_a [Var write_i]
(kernel, stms) <-
mapKernel
segThreadCapped
[(write_i, w)]
inputs
(zipWith (stripArray . length) as_ws $ patTypes pat)
body
certifying cs $ do
addStms stms
letBind pat $ Op $ SegOp kernel
transformStm _ (Let orig_pat (StmAux cs _ _) (Op (Hist w imgs ops bucket_fun))) = do
let bfun' = soacsLambdaToGPU bucket_fun
-- It is important not to launch unnecessarily many threads for
-- histograms, because it may mean we unnecessarily need to reduce
-- subhistograms as well.
runBuilder_ $ do
lvl <- segThreadCapped [w] "seghist" $ NoRecommendation SegNoVirt
addStms =<< histKernel onLambda lvl orig_pat [] [] cs w ops bfun' imgs
where
onLambda = pure . soacsLambdaToGPU
transformStm _ stm =
runBuilder_ $ FOT.transformStmRecursively stm
sufficientParallelism ::
String ->
[SubExp] ->
KernelPath ->
Maybe Int64 ->
DistribM ((SubExp, Name), Out.Stms Out.GPU)
sufficientParallelism desc ws path def =
cmpSizeLe desc (Out.SizeThreshold path def) ws
-- | Intra-group parallelism is worthwhile if the lambda contains more
-- than one instance of non-map nested parallelism, or any nested
-- parallelism inside a loop.
worthIntraGroup :: Lambda -> Bool
worthIntraGroup lam = bodyInterest (lambdaBody lam) > 1
where
bodyInterest body =
sum $ interest <$> bodyStms body
interest stm
| "sequential" `inAttrs` attrs =
0 :: Int
| Op (Screma w _ form) <- stmExp stm,
Just lam' <- isMapSOAC form =
mapLike w lam'
| Op (Scatter w _ lam' _) <- stmExp stm =
mapLike w lam'
| DoLoop _ _ body <- stmExp stm =
bodyInterest body * 10
| If _ tbody fbody _ <- stmExp stm =
max (bodyInterest tbody) (bodyInterest fbody)
| Op (Screma w _ (ScremaForm _ _ lam')) <- stmExp stm =
zeroIfTooSmall w + bodyInterest (lambdaBody lam')
| Op (Stream _ _ Sequential _ lam') <- stmExp stm =
bodyInterest $ lambdaBody lam'
| otherwise =
0
where
attrs = stmAuxAttrs $ stmAux stm
sequential_inner = "sequential_inner" `inAttrs` attrs
zeroIfTooSmall (Constant (IntValue x))
| intToInt64 x < 32 = 0
zeroIfTooSmall _ = 1
mapLike w lam' =
if sequential_inner
then 0
else max (zeroIfTooSmall w) (bodyInterest (lambdaBody lam'))
-- | A lambda is worth sequentialising if it contains enough nested
-- parallelism of an interesting kind.
worthSequentialising :: Lambda -> Bool
worthSequentialising lam = bodyInterest (lambdaBody lam) > 1
where
bodyInterest body =
sum $ interest <$> bodyStms body
interest stm
| "sequential" `inAttrs` attrs =
0 :: Int
| Op (Screma _ _ form@(ScremaForm _ _ lam')) <- stmExp stm,
isJust $ isMapSOAC form =
if sequential_inner
then 0
else bodyInterest (lambdaBody lam')
| Op Scatter {} <- stmExp stm =
0 -- Basically a map.
| DoLoop _ ForLoop {} body <- stmExp stm =
bodyInterest body * 10
| WithAcc _ withacc_lam <- stmExp stm =
bodyInterest (lambdaBody withacc_lam)
| Op (Screma _ _ form@(ScremaForm _ _ lam')) <- stmExp stm =
1 + bodyInterest (lambdaBody lam')
+
-- Give this a bigger score if it's a redomap, as these
-- are often tileable and thus benefit more from
-- sequentialisation.
case isRedomapSOAC form of
Just _ -> 1
Nothing -> 0
| otherwise =
0
where
attrs = stmAuxAttrs $ stmAux stm
sequential_inner = "sequential_inner" `inAttrs` attrs
onTopLevelStms ::
KernelPath ->
Stms SOACS ->
DistNestT Out.GPU DistribM GPUStms
onTopLevelStms path stms =
liftInner $ transformStms path $ stmsToList stms
onMap :: KernelPath -> MapLoop -> DistribM GPUStms
onMap path (MapLoop pat aux w lam arrs) = do
types <- askScope
let loopnest = MapNesting pat aux w $ zip (lambdaParams lam) arrs
env path' =
DistEnv
{ distNest = singleNesting (Nesting mempty loopnest),
distScope =
scopeOfPat pat
<> scopeForGPU (scopeOf lam)
<> types,
distOnInnerMap = onInnerMap path',
distOnTopLevelStms = onTopLevelStms path',
distSegLevel = segThreadCapped,
distOnSOACSStms = pure . oneStm . soacsStmToGPU,
distOnSOACSLambda = pure . soacsLambdaToGPU
}
exploitInnerParallelism path' =
runDistNestT (env path') $
distributeMapBodyStms acc (bodyStms $ lambdaBody lam)
let exploitOuterParallelism path' = do
let lam' = soacsLambdaToGPU lam
runDistNestT (env path') $
distribute $
addStmsToAcc (bodyStms $ lambdaBody lam') acc
onMap' (newKernel loopnest) path exploitOuterParallelism exploitInnerParallelism pat lam
where
acc =
DistAcc
{ distTargets = singleTarget (pat, bodyResult $ lambdaBody lam),
distStms = mempty
}
onlyExploitIntra :: Attrs -> Bool
onlyExploitIntra attrs =
AttrComp "incremental_flattening" ["only_intra"] `inAttrs` attrs
mayExploitOuter :: Attrs -> Bool
mayExploitOuter attrs =
not $
AttrComp "incremental_flattening" ["no_outer"] `inAttrs` attrs
|| AttrComp "incremental_flattening" ["only_inner"] `inAttrs` attrs
mayExploitIntra :: Attrs -> Bool
mayExploitIntra attrs =
not $
AttrComp "incremental_flattening" ["no_intra"] `inAttrs` attrs
|| AttrComp "incremental_flattening" ["only_inner"] `inAttrs` attrs
-- The minimum amount of inner parallelism we require (by default) in
-- intra-group versions. Less than this is usually pointless on a GPU
-- (but we allow tuning to change it).
intraMinInnerPar :: Int64
intraMinInnerPar = 32 -- One NVIDIA warp
onMap' ::
KernelNest ->
KernelPath ->
(KernelPath -> DistribM (Out.Stms Out.GPU)) ->
(KernelPath -> DistribM (Out.Stms Out.GPU)) ->
Pat ->
Lambda ->
DistribM (Out.Stms Out.GPU)
onMap' loopnest path mk_seq_stms mk_par_stms pat lam = do
-- Some of the control flow here looks a bit convoluted because we
-- are trying to avoid generating unneeded threshold parameters,
-- which means we need to do all the pruning checks up front.
types <- askScope
intra <-
if onlyExploitIntra (stmAuxAttrs aux)
|| (worthIntraGroup lam && mayExploitIntra attrs)
then flip runReaderT types $ intraGroupParallelise loopnest lam
else return Nothing
case intra of
_ | "sequential_inner" `inAttrs` attrs -> do
seq_body <- renameBody =<< mkBody <$> mk_seq_stms path <*> pure res
kernelAlternatives pat seq_body []
--
Nothing
| Just m <- mkSeqAlts -> do
(outer_suff, outer_suff_key, outer_suff_stms, seq_body) <- m
par_body <-
renameBody =<< mkBody
<$> mk_par_stms ((outer_suff_key, False) : path) <*> pure res
(outer_suff_stms <>) <$> kernelAlternatives pat par_body [(outer_suff, seq_body)]
--
| otherwise -> do
par_body <- renameBody =<< mkBody <$> mk_par_stms path <*> pure res
kernelAlternatives pat par_body []
--
Just intra'@(_, _, log, intra_prelude, intra_stms)
| onlyExploitIntra attrs -> do
addLog log
group_par_body <- renameBody $ mkBody intra_stms res
(intra_prelude <>) <$> kernelAlternatives pat group_par_body []
--
| otherwise -> do
addLog log
case mkSeqAlts of
Nothing -> do
(group_par_body, intra_ok, intra_suff_key, intra_suff_stms) <-
checkSuffIntraPar path intra'
par_body <-
renameBody =<< mkBody
<$> mk_par_stms ((intra_suff_key, False) : path) <*> pure res
(intra_suff_stms <>)
<$> kernelAlternatives pat par_body [(intra_ok, group_par_body)]
Just m -> do
(outer_suff, outer_suff_key, outer_suff_stms, seq_body) <- m
(group_par_body, intra_ok, intra_suff_key, intra_suff_stms) <-
checkSuffIntraPar ((outer_suff_key, False) : path) intra'
par_body <-
renameBody =<< mkBody
<$> mk_par_stms
( [ (outer_suff_key, False),
(intra_suff_key, False)
]
++ path
)
<*> pure res
((outer_suff_stms <> intra_suff_stms) <>)
<$> kernelAlternatives
pat
par_body
[(outer_suff, seq_body), (intra_ok, group_par_body)]
where
nest_ws = kernelNestWidths loopnest
res = varsRes $ patNames pat
aux = loopNestingAux $ innermostKernelNesting loopnest
attrs = stmAuxAttrs aux
mkSeqAlts
| worthSequentialising lam,
mayExploitOuter attrs = Just $ do
((outer_suff, outer_suff_key), outer_suff_stms) <- checkSuffOuterPar
seq_body <-
renameBody =<< mkBody
<$> mk_seq_stms ((outer_suff_key, True) : path) <*> pure res
pure (outer_suff, outer_suff_key, outer_suff_stms, seq_body)
| otherwise =
Nothing
checkSuffOuterPar =
sufficientParallelism "suff_outer_par" nest_ws path Nothing
checkSuffIntraPar
path'
((_intra_min_par, intra_avail_par), group_size, _, intra_prelude, intra_stms) = do
-- We must check that all intra-group parallelism fits in a group.
((intra_ok, intra_suff_key), intra_suff_stms) <- do
((intra_suff, suff_key), check_suff_stms) <-
sufficientParallelism
"suff_intra_par"
[intra_avail_par]
path'
(Just intraMinInnerPar)
runBuilder $ do
addStms intra_prelude
max_group_size <-
letSubExp "max_group_size" $ Op $ SizeOp $ Out.GetSizeMax Out.SizeGroup
fits <-
letSubExp "fits" $
BasicOp $
CmpOp (CmpSle Int64) group_size max_group_size
addStms check_suff_stms
intra_ok <- letSubExp "intra_suff_and_fits" $ BasicOp $ BinOp LogAnd fits intra_suff
return (intra_ok, suff_key)
group_par_body <- renameBody $ mkBody intra_stms res
pure (group_par_body, intra_ok, intra_suff_key, intra_suff_stms)
onInnerMap ::
KernelPath ->
MapLoop ->
DistAcc Out.GPU ->
DistNestT Out.GPU DistribM (DistAcc Out.GPU)
onInnerMap path maploop@(MapLoop pat aux w lam arrs) acc
| unbalancedLambda lam,
lambdaContainsParallelism lam =
addStmToAcc (mapLoopStm maploop) acc
| otherwise =
distributeSingleStm acc (mapLoopStm maploop) >>= \case
Just (post_kernels, res, nest, acc')
| Just (perm, _pat_unused) <- permutationAndMissing pat res -> do
addPostStms post_kernels
multiVersion perm nest acc'
_ -> distributeMap maploop acc
where
discardTargets acc' =
-- FIXME: work around bogus targets.
acc' {distTargets = singleTarget (mempty, mempty)}
multiVersion perm nest acc' = do
-- The kernel can be distributed by itself, so now we can
-- decide whether to just sequentialise, or exploit inner
-- parallelism.
dist_env <- ask
let extra_scope = targetsScope $ distTargets acc'
stms <- liftInner $
localScope extra_scope $ do
let maploop' = MapLoop pat aux w lam arrs
exploitInnerParallelism path' = do
let dist_env' =
dist_env
{ distOnTopLevelStms = onTopLevelStms path',
distOnInnerMap = onInnerMap path'
}
runDistNestT dist_env' $
inNesting nest $
localScope extra_scope $
discardTargets <$> distributeMap maploop' acc {distStms = mempty}
-- Normally the permutation is for the output pattern, but
-- we can't really change that, so we change the result
-- order instead.
let lam_res' =
rearrangeShape (rearrangeInverse perm) $
bodyResult $ lambdaBody lam
lam' = lam {lambdaBody = (lambdaBody lam) {bodyResult = lam_res'}}
map_nesting = MapNesting pat aux w $ zip (lambdaParams lam) arrs
nest' = pushInnerKernelNesting (pat, lam_res') map_nesting nest
-- XXX: we do not construct a new KernelPath when
-- sequentialising. This is only OK as long as further
-- versioning does not take place down that branch (it currently
-- does not).
(sequentialised_kernel, nestw_stms) <- localScope extra_scope $ do
let sequentialised_lam = soacsLambdaToGPU lam'
constructKernel segThreadCapped nest' $ lambdaBody sequentialised_lam
let outer_pat = loopNestingPat $ fst nest
(nestw_stms <>)
<$> onMap'
nest'
path
(const $ return $ oneStm sequentialised_kernel)
exploitInnerParallelism
outer_pat
lam'
postStm stms
return acc'
| HIPERFIT/futhark | src/Futhark/Pass/ExtractKernels.hs | isc | 32,554 | 0 | 25 | 8,664 | 8,456 | 4,261 | 4,195 | -1 | -1 |
-- Copyright 2015-2016 Yury Gribov
--
-- Use of this source code is governed by MIT license that can be
-- found in the LICENSE.txt file.
module Support where
import qualified System.Environment
import qualified System.Exit
import qualified Data.Array
import Debug.Trace (trace)
-- Create Data.Array.Array with all elements initialized to some value
filled :: (Data.Array.Ix a) => (a, a) -> b -> Data.Array.Array a b
filled bnds x = Data.Array.array bnds [(i, x) | i <- Data.Array.range bnds]
-- From http://www.haskell.org/ghc/docs/6.12.1/html/users_guide/assertions.html
arsert :: Bool -> a -> a
arsert False _ = error "assertion failed"
arsert True x = x
-- Inverse of Data.List.intersperse: split list at value
deintersperse :: (Eq a) => a -> [a] -> [[a]]
deintersperse x xs =
let
deintersperse' [] acc = [reverse acc]
deintersperse' (y:ys) acc =
if x == y
then reverse acc : deintersperse' ys []
else deintersperse' ys (y:acc)
in
deintersperse' xs []
-- Same as deintersperse but treat multiple separators as single one
deintersperse_multi :: (Eq a) => a -> [a] -> [[a]]
deintersperse_multi x xs =
filter (not . null) $ deintersperse x xs
-- Helper for main functions: if cmdline args contain filename - read it, otherwise read stdin
readFileOrStdin :: [String] -> IO String
readFileOrStdin [] = getContents
readFileOrStdin (arg:_) = readFile arg
-- Print user-friendly error and exit
report_error :: String -> IO a
report_error msg = do
progname <- System.Environment.getProgName
putStrLn $ progname ++ ": " ++ msg
_ <- System.Exit.exitFailure
return undefined
-- Drop last element of list
drop_last :: [a] -> [a]
drop_last [_] = []
drop_last (x:xs) = x:drop_last xs
force :: a -> a
force x = seq x x
trace_it :: (Show a) => a -> a
trace_it x = trace (show x) x
-- Split list to equally-sized chunks
chunks :: [a] -> Int -> [[a]]
chunks [] _ = []
chunks xs n = take n xs : chunks (drop n xs) n
-- Left-pad list to a given size
pad :: Int -> a -> [a] -> [a]
pad n x xs =
replicate nx x ++ xs
where
nx = max 0 (n - length xs)
-- Integer sqrt
isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral
| yugr/sudoku | src/Support.hs | mit | 2,176 | 0 | 12 | 448 | 718 | 383 | 335 | 47 | 3 |
module Philed.Data.List (module Data.List
,module Philed.Data.ListExtras) where
import Data.List
import Philed.Data.ListExtras
| Chattered/PhilEdCommon | Philed/Data/List.hs | mit | 152 | 0 | 5 | 36 | 33 | 22 | 11 | 4 | 0 |
{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
module Kachushi.KState
(
KState (..)
, boards
, deck
, initialState
, putCard
, putCards
) where
import Kachushi.Cards (Card (..), fullDeck)
import Kachushi.OFCP (Board (..), emptyBoard, Slot (..), Row (..))
import Control.Lens (over, makeLenses, element)
import Control.Monad.State (MonadState (..), get, modify, forM_)
import Data.List ((\\))
import Data.Array.ST (runSTArray, thaw, newListArray, STArray (..), readArray, writeArray)
import Control.Monad.ST (ST (..))
import Control.Applicative ((<*>))
---------------------------
-- Types
---------------------------
data KState = KState { _boards :: [Board] , _deck :: [Card] } deriving Show
makeLenses ''KState
---------------------------
-- Costructors
---------------------------
initialState n = KState (replicate n emptyBoard) fullDeck
---------------------------
-- State monad
---------------------------
putCard :: MonadState KState m => Int -> Card -> Row -> m ()
putCard n card row = putCards n [(card, row)]
putCards :: MonadState KState m => Int -> [(Card, Row)] -> m ()
putCards n crs = let
boardArray brd = runSTArray $ do
array <- thaw (asArray brd)
empties <- newListArray (0,2)
$ [nextTop, nextMiddle, nextBottom] <*> [brd]
:: (ST s) ((STArray s) Int Int)
forM_ crs $ \(card, row) -> do
index <- readArray empties (fromEnum row)
writeArray empties (fromEnum row) (index + 1)
writeArray array index (Filled card)
return array
t brd = (nextTop brd)
+ (length . filter (== Top) . map snd $ crs)
m brd = (nextMiddle brd)
+ (length . filter (== Middle) . map snd $ crs)
b brd = (nextBottom brd)
+ (length . filter (== Bottom) . map snd $ crs)
in
do
state <- get
modify $ over deck (\\ (map fst crs) )
. over boards (over (element n)
(\brd -> (Board (boardArray brd) (t brd) (m brd) (b brd))))
| ScrambledEggsOnToast/Kachushi | Kachushi/KState.hs | mit | 2,114 | 0 | 19 | 584 | 766 | 421 | 345 | 45 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLLegendElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLLegendElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLLegendElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLLegendElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLLegendElement
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/HTMLLegendElement.hs | mit | 470 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Lambency.Camera (
mkOrthoCamera,
mkPerspCamera,
getViewProjMatrix,
getCamXForm,
setCamXForm,
getCamDist,
setCamDist,
getCamPos,
setCamPos,
getCamDir,
setCamDir,
getCamUp,
setCamUp,
getCamNear,
setCamNear,
getCamFar,
setCamFar,
camLookAt,
mkFixedCam,
mkViewerCam,
mkFreeCam,
mk2DCam,
) where
--------------------------------------------------------------------------------
import Control.Wire
import qualified Graphics.UI.GLFW as GLFW
import FRP.Netwire.Input
import GHC.Float
import Lambency.Types
import qualified Lambency.Transform as XForm
import qualified Linear.Quaternion as Quat
import Linear
import Prelude hiding (id, (.))
--------------------------------------------------------------------------------
mkXForm :: Vec3f -> Vec3f -> Vec3f -> XForm.Transform
mkXForm pos dir up = let
r = signorm $ dir `cross` up
u' = signorm $ r `cross` dir
in XForm.translate pos $ XForm.fromCoordinateBasis (r, u', negate dir)
mkOrthoCamera :: Vec3f -> Vec3f -> Vec3f ->
Float -> Float -> Float -> Float -> Float -> Float ->
Camera
mkOrthoCamera pos dir up l r t b n f = Camera
(mkXForm pos (signorm dir) (signorm up))
(Ortho l r t b)
(CameraViewDistance n f)
mkPerspCamera :: Vec3f -> Vec3f -> Vec3f ->
Float -> Float -> Float -> Float -> Camera
mkPerspCamera pos dir up fovy aspratio n f = Camera
(mkXForm pos (signorm dir) (signorm up))
Persp {
fovY = fovy,
aspect = aspratio
}
CameraViewDistance {
near = n,
far = f
}
-- !FIXME! Change the following functions to val -> Camera -> Camera
getCamXForm :: Camera -> XForm.Transform
getCamXForm (Camera xf _ _) = xf
setCamXForm :: Camera -> XForm.Transform -> Camera
setCamXForm (Camera _ cam dist) xf = Camera xf cam dist
getCamDist :: Camera -> CameraViewDistance
getCamDist (Camera _ _ dist) = dist
setCamDist :: Camera -> CameraViewDistance -> Camera
setCamDist (Camera loc cam _) dist = Camera loc cam dist
getCamPos :: Camera -> Vec3f
getCamPos = XForm.position . getCamXForm
setCamPos :: Camera -> Vec3f -> Camera
setCamPos c p = let
xf = getCamXForm c
nd = XForm.forward xf
u = XForm.up xf
in
setCamXForm c $ mkXForm p (negate nd) u
getCamDir :: Camera -> Vec3f
getCamDir = negate . XForm.forward . getCamXForm
setCamDir :: Camera -> Vec3f -> Camera
setCamDir c d = let
xf = getCamXForm c
u = XForm.up xf
p = XForm.position xf
in
setCamXForm c $ mkXForm p d u
getCamUp :: Camera -> Vec3f
getCamUp = XForm.up . getCamXForm
setCamUp :: Camera -> Vec3f -> Camera
setCamUp c u = let
xf = getCamXForm c
nd = XForm.forward xf
p = XForm.position xf
in
setCamXForm c $ mkXForm p (negate nd) u
getCamNear :: Camera -> Float
getCamNear = near . getCamDist
setCamNear :: Camera -> Float -> Camera
setCamNear c n = let
dist = getCamDist c
in
setCamDist c $ (\d -> d { near = n }) dist
getCamFar :: Camera -> Float
getCamFar = (far . getCamDist)
setCamFar :: Camera -> Float -> Camera
setCamFar c f = let
dist = getCamDist c
in
setCamDist c $ (\d -> d { far = f }) dist
camLookAt :: Vec3f -> Camera -> Camera
camLookAt focus (Camera xf ty dist)
| focus == pos = Camera xf ty dist
| otherwise = Camera (mkXForm pos dir up) ty dist
where
pos = XForm.position xf
dir = signorm $ focus - pos
up = XForm.up xf
getViewMatrix :: Camera -> Mat4f
getViewMatrix (Camera xf _ _) =
let
extendWith :: Float -> Vec3f -> Vec4f
extendWith w (V3 x y z) = V4 x y z w
pos = negate . XForm.position $ xf
(V3 sx sy sz) = XForm.scale xf
r = XForm.right xf
u = XForm.up xf
f = XForm.forward xf
te :: Vec3f -> Float -> Vec4f
te n sc = extendWith (pos `dot` n) (sc *^ n)
in adjoint $ V4 (te r sx) (te u sy) (te f sz) (V4 0 0 0 1)
mkProjMatrix :: CameraType -> CameraViewDistance -> Mat4f
mkProjMatrix (Ortho l r t b) (CameraViewDistance{..}) =
transpose $ ortho l r b t near far
mkProjMatrix (Persp {..}) (CameraViewDistance{..}) =
transpose $ perspective fovY aspect near far
getProjMatrix :: Camera -> Mat4f
getProjMatrix (Camera _ ty dist) = mkProjMatrix ty dist
getViewProjMatrix :: Camera -> Mat4f
getViewProjMatrix c = (getViewMatrix c) !*! (getProjMatrix c)
--
mkFixedCam :: Camera -> ContWire a Camera
mkFixedCam cam = CW $ mkConst $ Right cam
type ViewCam = (Camera, Vec3f)
mkViewerCam :: Camera -> Vec3f -> ContWire a Camera
mkViewerCam initialCam initialFocus =
let handleRotation :: ((Float, Float), ViewCam) -> ViewCam
handleRotation ((0, 0), c) = c
handleRotation ((mx, my), (c@(Camera xform _ _), focus)) =
(setCamPos (setCamDir c (signorm $ negate newPos)) (newPos ^+^ focus), focus)
where
oldPos :: Vec3f
oldPos = XForm.position xform ^-^ focus
newPos :: Vec3f
newPos = XForm.transformPoint rotation oldPos
rotation :: XForm.Transform
rotation = flip XForm.rotate XForm.identity $
foldl1 (*) [
Quat.axisAngle (XForm.up xform) (-asin mx),
Quat.axisAngle (XForm.right xform) (-asin my)]
dxScale :: Vec3f -> Vec3f -> Float
dxScale pos focus = (0.4 *) $ distance pos focus
handleScroll :: ((Double, Double), ViewCam) -> ViewCam
handleScroll ((_, sy), (c, x)) =
let camPos = getCamPos c
camDir = getCamDir c
dx = (dxScale camPos x * double2Float sy) *^ camDir
-- !FIXME! We should really do mouse picking here to keep the focus
-- on whatever point we're intersecting with the mesh... for right now
-- just don't move the focus.
-- in (setCamPos c $ camPos ^+^ dx, x ^+^ dx)
in (setCamPos c $ camPos ^+^ dx, x)
handlePanning :: ((Float, Float), ViewCam) -> ViewCam
handlePanning ((0, 0), c) = c
handlePanning ((mx, my), (c@(Camera xform _ _), focus)) =
(setCamPos c (oldPos ^+^ dx), focus ^+^ dx)
where
oldPos = XForm.position xform
dx = (dxScale oldPos focus *^) $
(-mx *^ (XForm.right xform)) ^+^ (my *^ (XForm.up xform))
{-- !TODO! This might be good to add to netwire-input --}
mouseIfThen :: GLFW.MouseButton -> GameWire a b -> GameWire a b -> GameWire a b
mouseIfThen mb ifPressed elsePressed = whilePressed
where
whilePressed = (mousePressed mb >>> ifPressed) --> whileNotPressed
whileNotPressed = switch $
elsePressed &&&
((mousePressed mb >>> pure whilePressed >>> now)
<|> never)
mouseDeltas :: GLFW.MouseButton -> GameWire a (Float, Float)
mouseDeltas mb = mouseIfThen mb getDelta $ pure (0, 0)
where
delayM :: Monad m => m a -> Wire s e m a a
delayM x' = mkGenN $ \x -> do
r <- x'
return (Right r, delayM $ return x)
delayCursor :: GameWire (Float, Float) (Float, Float)
delayCursor = delayM cursor
getDelta :: GameWire a (Float, Float)
getDelta =
loop $ (mouseCursor *** delayCursor) >>>
(arr $ \((x, y), (x', y')) -> ((x - x', y - y'), (x, y)))
rotationalDeltas :: GameWire a (Float, Float)
rotationalDeltas =
(keyPressed GLFW.Key'LeftShift >>> pure (0, 0))
<|> mouseDeltas GLFW.MouseButton'1
panningDeltas :: GameWire a (Float, Float)
panningDeltas =
(keyPressed GLFW.Key'LeftShift >>> mouseDeltas GLFW.MouseButton'1)
<|> mouseDeltas GLFW.MouseButton'3
in
CW $ loop $ second (
delay (initialCam, initialFocus) >>>
(rotationalDeltas &&& id) >>> (arr handleRotation) >>>
(panningDeltas &&& id) >>> (arr handlePanning) >>>
(mouseScroll &&& id) >>> (arr handleScroll))
>>> (arr $ \(_, c@(cam, _)) -> (cam, c))
mkFreeCam :: Camera -> ContWire a Camera
mkFreeCam initCam =
CW $ loop ((second (delay initCam >>> updCam)) >>> feedback)
where
feedback :: GameWire (a, b) (b, b)
feedback = mkPure_ $ \(_, x) -> Right (x, x)
tr :: GLFW.Key -> Float -> (XForm.Transform -> Vec3f) ->
GameWire XForm.Transform XForm.Transform
tr key sc dir = (trans >>> (keyPressed key)) <|> id
where
trans :: GameWire XForm.Transform XForm.Transform
trans = mkSF $ \ts xf ->
(XForm.translate (3.0 * (dtime ts) * sc *^ (dir xf)) xf, trans)
updCam :: GameWire Camera Camera
updCam = (id &&& (arr getCamXForm >>> xfWire))
>>> (mkSF_ $ uncurry stepCam)
where
xfWire :: GameWire XForm.Transform XForm.Transform
xfWire =
(tr GLFW.Key'W (-1.0) XForm.forward) >>>
(tr GLFW.Key'S (1.0) XForm.forward) >>>
(tr GLFW.Key'A (-1.0) XForm.right) >>>
(tr GLFW.Key'D (1.0) XForm.right) >>>
(id &&& mouseMickies) >>>
(mkSF_ $ \(xf, (mx, my)) ->
XForm.rotate
(foldl1 (*) [
Quat.axisAngle (XForm.up xf) (-asin mx),
Quat.axisAngle (XForm.right xf) (-asin my)])
xf)
stepCam :: Camera -> XForm.Transform -> Camera
stepCam cam newXForm = setCamXForm cam finalXForm
where
finalXForm = mkXForm
(XForm.position newXForm)
(negate $ XForm.forward newXForm)
(V3 0 1 0)
mk2DCam :: Int -> Int -> ContWire Vec2f Camera
mk2DCam sx sy = let
toHalfF :: Integral a => a -> Float
toHalfF x = 0.5 * (fromIntegral x)
hx :: Float
hx = toHalfF sx
hy :: Float
hy = toHalfF sy
screenCenter :: V3 Float
screenCenter = V3 hx hy 1
trPos :: Vec2f -> Vec3f
trPos (V2 x y) = (V3 x y 0) ^+^ screenCenter
in
CW $ mkSF_ $ \vec -> mkOrthoCamera
(trPos vec) (negate XForm.localForward) XForm.localUp
(-hx) (hx) (hy) (-hy)
0.01 50.0
| Mokosha/Lambency | lib/Lambency/Camera.hs | mit | 9,911 | 4 | 20 | 2,720 | 3,558 | 1,888 | 1,670 | 243 | 3 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
module Lib where
import Alex
import Control.Monad
import Control.Monad.Except
import Control.Monad.State (MonadState, get, state)
import Control.Monad.Trans.State.Strict hiding (get, state)
import Data.Coerce
import Data.Functor.Identity
import Data.Tuple
import Token
{-
Let's do something interesting, say parse Java.
Latest spec seems to be:
- https://docs.oracle.com/javase/specs/jls/se15/html/index.html
- https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html
-}
{-
TODO: project idea: a super verbose tokenizer just to see what can be carried around?
TODO: it seems both GHC and Agda are not using any wrappers - how does that work?
TODO: find a way to use startcode.
-}
main :: IO ()
main = print $ runAlex "let xzzz = 1234 in ts" parseAll
where
parseAll =
alexMonadScan >>= \case
EOF -> pure []
x -> (x :) <$> parseAll
newtype AlexWrappper a = AW (Alex a)
deriving
(Functor, Applicative, Monad)
via Alex
deriving
(MonadError String, MonadState AlexState)
via StateT' AlexState (Except String)
newtype StateT' s m a = ST' (s -> m (s, a)) deriving (Functor)
from' :: Functor m => StateT' s m a -> StateT s m a
from' (ST' f) = StateT (fmap swap . f)
to' :: Functor m => StateT s m a -> StateT' s m a
to' (StateT f) = ST' (fmap swap . f)
-- instance Functor m => Functor (StateT' s m) where
-- fmap f a = to' $ fmap f (from' a)
instance Monad m => Applicative (StateT' s m) where
pure a = to' $ from' (pure a)
f <*> a = to' $ from' f <*> from' a
instance Monad m => Monad (StateT' s m) where
m >>= f = to' $ from' m >>= \a -> from' $ f a
instance MonadError e m => MonadError e (StateT' s m) where
throwError a = to' $ from' (throwError a)
m `catchError` h = to' $ from' m `catchError` (from' . h)
instance Monad m => MonadState s (StateT' s m) where
state f = ST' $ pure . swap . f
{-
instance MonadError String AlexWrappper where
throwError e = AW $ Alex (const (Left e))
(AW (Alex m)) `catchError` h = AW $
Alex $ \s -> case m s of
Left l | AW (Alex f) <- h l -> f s
Right r -> pure r
-}
{-
AlexInput is of type (this can be examined in GHCi):
( AlexPosn -- position in input?
, Char -- char before input
, Data.ByteString.Lazy.Internal.ByteString -- current input?
, GHC.Int.Int64 -- this is "bpos", looks like byte consumed so far.
)
-}
| Javran/misc | alex-playground/src/Lib.hs | mit | 2,729 | 0 | 12 | 587 | 613 | 326 | 287 | -1 | -1 |
module Network.WebSockets.Messaging
( Connection(disconnected)
, request
, requestAsync
, notify
, onRequest
, onNotify
, onConnect
, onDisconnect
, startListening
, Request(..)
, Notify(..)
, Some(..)
, deriveRequest
, deriveNotify
, Future
, get
, foldFuture
, clientLibraryPath
, clientLibraryCode
) where
import Network.WebSockets.Messaging.Connection
import Network.WebSockets.Messaging.Message
import Network.WebSockets.Messaging.Message.TH
import Paths_ws_messaging
clientLibraryPath :: IO FilePath
clientLibraryPath = getDataFileName "client/messaging.js"
clientLibraryCode :: IO String
clientLibraryCode = readFile =<< clientLibraryPath
| leonidas/ws-messaging | src/Network/WebSockets/Messaging.hs | mit | 732 | 0 | 5 | 153 | 140 | 91 | 49 | 30 | 1 |
module Rebase.Data.Vector.Storable.Mutable
(
module Data.Vector.Storable.Mutable
)
where
import Data.Vector.Storable.Mutable
| nikita-volkov/rebase | library/Rebase/Data/Vector/Storable/Mutable.hs | mit | 128 | 0 | 5 | 12 | 26 | 19 | 7 | 4 | 0 |
import Geometry
import Drawing
main = drawPicture myPicture
myPicture points = undefined
| alphalambda/k12math | contrib/MHills/GeometryLessons/code/student/lesson2e.hs | mit | 98 | 0 | 5 | 21 | 23 | 12 | 11 | 4 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
-- | Warning: This module should be considered highly experimental.
module Data.Containers where
import qualified Data.Map as Map
import qualified Data.HashMap.Strict as HashMap
import Data.Hashable (Hashable)
import qualified Data.Set as Set
import qualified Data.HashSet as HashSet
import Data.Monoid (Monoid)
import Data.MonoTraversable (MonoFoldable, MonoTraversable, Element)
import qualified Data.IntMap as IntMap
import Data.Function (on)
import qualified Data.List as List
import qualified Data.IntSet as IntSet
class (Monoid set, MonoFoldable set) => Container set where
type ContainerKey set
member :: ContainerKey set -> set -> Bool
notMember :: ContainerKey set -> set -> Bool
union :: set -> set -> set
difference :: set -> set -> set
intersection :: set -> set -> set
instance Ord k => Container (Map.Map k v) where
type ContainerKey (Map.Map k v) = k
member = Map.member
notMember = Map.notMember
union = Map.union
difference = Map.difference
intersection = Map.intersection
instance (Eq k, Hashable k) => Container (HashMap.HashMap k v) where
type ContainerKey (HashMap.HashMap k v) = k
member = HashMap.member
notMember k = not . HashMap.member k
union = HashMap.union
difference = HashMap.difference
intersection = HashMap.intersection
instance Container (IntMap.IntMap v) where
type ContainerKey (IntMap.IntMap v) = Int
member = IntMap.member
notMember = IntMap.notMember
union = IntMap.union
difference = IntMap.difference
intersection = IntMap.intersection
instance Ord e => Container (Set.Set e) where
type ContainerKey (Set.Set e) = e
member = Set.member
notMember = Set.notMember
union = Set.union
difference = Set.difference
intersection = Set.intersection
instance (Eq e, Hashable e) => Container (HashSet.HashSet e) where
type ContainerKey (HashSet.HashSet e) = e
member = HashSet.member
notMember e = not . HashSet.member e
union = HashSet.union
difference = HashSet.difference
intersection = HashSet.intersection
instance Container IntSet.IntSet where
type ContainerKey IntSet.IntSet = Int
member = IntSet.member
notMember = IntSet.notMember
union = IntSet.union
difference = IntSet.difference
intersection = IntSet.intersection
instance Ord k => Container [(k, v)] where
type ContainerKey [(k, v)] = k
member k = List.any ((== k) . fst)
notMember k = not . member k
union = List.unionBy ((==) `on` fst)
x `difference` y = Map.toList (Map.fromList x `Map.difference` Map.fromList y)
intersection = List.intersectBy ((==) `on` fst)
class (MonoTraversable m, Container m) => IsMap m where
-- | Using just @Element@ can lead to very confusing error messages.
type MapValue m
lookup :: ContainerKey m -> m -> Maybe (MapValue m)
insertMap :: ContainerKey m -> MapValue m -> m -> m
deleteMap :: ContainerKey m -> m -> m
singletonMap :: ContainerKey m -> MapValue m -> m
mapFromList :: [(ContainerKey m, MapValue m)] -> m
mapToList :: m -> [(ContainerKey m, MapValue m)]
instance Ord k => IsMap (Map.Map k v) where
type MapValue (Map.Map k v) = v
lookup = Map.lookup
insertMap = Map.insert
deleteMap = Map.delete
singletonMap = Map.singleton
mapFromList = Map.fromList
mapToList = Map.toList
instance (Eq k, Hashable k) => IsMap (HashMap.HashMap k v) where
type MapValue (HashMap.HashMap k v) = v
lookup = HashMap.lookup
insertMap = HashMap.insert
deleteMap = HashMap.delete
singletonMap = HashMap.singleton
mapFromList = HashMap.fromList
mapToList = HashMap.toList
instance IsMap (IntMap.IntMap v) where
type MapValue (IntMap.IntMap v) = v
lookup = IntMap.lookup
insertMap = IntMap.insert
deleteMap = IntMap.delete
singletonMap = IntMap.singleton
mapFromList = IntMap.fromList
mapToList = IntMap.toList
instance Ord k => IsMap [(k, v)] where
type MapValue [(k, v)] = v
lookup = List.lookup
insertMap k v = ((k, v):) . deleteMap k
deleteMap k = List.filter ((/= k) . fst)
singletonMap k v = [(k, v)]
mapFromList = id
mapToList = id
class (Container s, Element s ~ ContainerKey s) => IsSet s where
insertSet :: Element s -> s -> s
deleteSet :: Element s -> s -> s
singletonSet :: Element s -> s
setFromList :: [Element s] -> s
setToList :: s -> [Element s]
instance Ord e => IsSet (Set.Set e) where
insertSet = Set.insert
deleteSet = Set.delete
singletonSet = Set.singleton
setFromList = Set.fromList
setToList = Set.toList
instance (Eq e, Hashable e) => IsSet (HashSet.HashSet e) where
insertSet = HashSet.insert
deleteSet = HashSet.delete
singletonSet = HashSet.singleton
setFromList = HashSet.fromList
setToList = HashSet.toList
instance IsSet IntSet.IntSet where
insertSet = IntSet.insert
deleteSet = IntSet.delete
singletonSet = IntSet.singleton
setFromList = IntSet.fromList
setToList = IntSet.toList
| moonKimura/mono-traversable-0.1.0.0 | src/Data/Containers.hs | mit | 5,148 | 0 | 11 | 1,113 | 1,661 | 909 | 752 | 135 | 0 |
module FSM (
FSM(..),
mapTransitions,
mapToFunc,
accepts
) where
import State (Token(..), State(..), TransitionFunction(..), Transition(..), TransitionMap)
import Data.Set as Set (Set, elems, member)
import Data.Map as Map (Map, (!), empty, insert, singleton, member)
data FSM = FSM {states :: Set State, state0 :: State, accepting :: Set State,
transitionFunction :: TransitionFunction, alphabet :: Set Token}
-- Turns a set describing some transitions into a map of transitions
mapTransitions :: Set Transition -> TransitionMap
mapTransitions set = foldr addTransition Map.empty $ elems set
where
addTransition :: Transition -> Map State (Map Token State) -> Map State (Map Token State)
addTransition (a, t, b) map = map'
where
map' = if a `Map.member` map
then Map.insert a (Map.insert t b (map ! a)) map
else Map.insert a (Map.singleton t b) map
-- Turns a 2-nested map into a 2-arity function
mapToFunc :: (Ord a, Ord b) => Map a (Map b c) -> (a -> b -> c)
mapToFunc m a b = (m ! a) ! b
accepts :: FSM -> [Token] -> Bool
fsm `accepts` string = accepts' fsm (state0 fsm) string
accepts' :: FSM -> State -> [Token] -> Bool
accepts' fsm state [] = state `Set.member` (accepting fsm)
accepts' fsm state (t:tt) = accepts' fsm state' tt
where state' = transitionFunction fsm state t | wyager/NDFSMtoFSM | FSM.hs | mit | 1,310 | 14 | 14 | 244 | 534 | 298 | 236 | 25 | 2 |
class Functor f where
fmap :: (a -> b) -> f a -> f b
--haskell中的functor是一个kind为* -> *的typeclass也就是说在要instance这个typeclass的时候必须是一个类型构造器也就是获取一个类型返回一个新类型的data 比如Maybe
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
--对于list来说 fmap的类型是
fmap :: (a -> b) -> [a] -> [b]
--而一般listfmap其实就是大多数FP语言中的map
instance Functor [] where
fmap = map
--functor law
--Identity
fmap id functor = id functor
--Composition
fmap (f . g) functor = fmap f (fmap g functor)
| zjhmale/monadme | monad/src/monad/haskell/functor.hs | epl-1.0 | 642 | 1 | 9 | 101 | 170 | 88 | 82 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE CPP, FlexibleInstances, StandaloneDeriving, DeriveGeneric #-}
{-# OPTIONS -fno-warn-orphans #-}
module Lib.TimeInstances () where
import Prelude.Compat
import Data.Binary(Binary(..))
import Data.Time.Clock (NominalDiffTime, DiffTime)
import Data.Fixed (Pico, Fixed(..), E12)
toPicos :: Pico -> Integer
fromPicos :: Integer -> Pico
#if __GLASGOW_HASKELL__ <= 706
toPicos = truncate . (*1e12)
fromPicos = (/1e12) . realToFrac
#else
toPicos (MkFixed x) = x
fromPicos = MkFixed
#endif
{-# INLINE toPicos #-}
{-# INLINE fromPicos #-}
instance Binary (Fixed E12) where
get = fromPicos <$> get
put = put . toPicos
{-# INLINE get #-}
{-# INLINE put #-}
{-# INLINE toPico #-}
toPico :: Real a => a -> Pico
toPico = realToFrac
{-# INLINE fromPico #-}
fromPico :: Fractional a => Pico -> a
fromPico = realToFrac
instance Binary NominalDiffTime where
put = put . toPico
get = fromPico <$> get
{-# INLINE get #-}
{-# INLINE put #-}
instance Binary DiffTime where
put = put . toPico
get = fromPico <$> get
{-# INLINE get #-}
{-# INLINE put #-}
| sinelaw/buildsome | src/Lib/TimeInstances.hs | gpl-2.0 | 1,110 | 0 | 7 | 203 | 248 | 149 | 99 | 35 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
module Text.Pandoc.Extended
( module Text.Pandoc
, plainToPara
, newlineToSpace
) where
--------------------------------------------------------------------------------
import Data.Data.Extended (grecT)
import Text.Pandoc
import Prelude
--------------------------------------------------------------------------------
plainToPara :: [Block] -> [Block]
plainToPara = map $ \case
Plain inlines -> Para inlines
block -> block
--------------------------------------------------------------------------------
newlineToSpace :: [Inline] -> [Inline]
newlineToSpace = grecT $ \case
SoftBreak -> Space
LineBreak -> Space
inline -> inline
| jaspervdj/patat | lib/Text/Pandoc/Extended.hs | gpl-2.0 | 854 | 0 | 9 | 153 | 134 | 79 | 55 | 18 | 3 |
{-
Functional parsing library from chapter 8 of Programming in Haskell,
Graham Hutton, Cambridge University Press, 2007.
Minor changes by Edwin Brady
-}
module Parsing where
import Data.Char
import Control.Monad
import Lit
infixr 5 |||
{-
The monad of parsers
--------------------
-}
newtype Parser a = P (String -> [(a,String)])
instance Monad Parser where
return v = P (\inp -> [(v,inp)])
p >>= f = P (\inp -> case parse p inp of
[] -> []
[(v,out)] -> parse (f v) out)
instance MonadPlus Parser where
mzero = P (\inp -> [])
p `mplus` q = P (\inp -> case parse p inp of
[] -> parse q inp
[(v,out)] -> [(v,out)])
{-
Basic parsers
-------------
-}
failure :: Parser a
failure = mzero
item :: Parser Char
item = P (\inp -> case inp of
[] -> []
(x:xs) -> [(x,xs)])
parse :: Parser a -> String -> [(a,String)]
parse (P p) inp = p inp
{-
Choice
------
-}
(|||) :: Parser a -> Parser a -> Parser a
p ||| q = p `mplus` q
{-
Derived primitives
------------------
-}
sat :: (Char -> Bool) -> Parser Char
sat p = do x <- item
if p x then return x else failure
digit :: Parser Char
digit = sat isDigit
lower :: Parser Char
lower = sat isLower
upper :: Parser Char
upper = sat isUpper
letter :: Parser Char
letter = sat isAlpha
alphanum :: Parser Char
alphanum = sat isAlphaNum
any :: Parser Char
any = sat isAnything
isAnything :: Char -> Bool
isAnything c = True
character :: Parser Char
character = sat isAnything
character' :: Parser Char
character' = sat (/='"')
char :: Char -> Parser Char
char x = sat (== x)
string :: String -> Parser String
string [] = return []
string (x:xs) = do char x
string xs
return (x:xs)
many :: Parser a -> Parser [a]
many p = many1 p ||| return []
many1 :: Parser a -> Parser [a]
many1 p = do v <- p
vs <- many p
return (v:vs)
ident :: Parser String
ident = do x <- lower
xs <- many alphanum
return (x:xs)
-- | Accepts any characters from the input stream
anything :: Parser String
anything = do x <- character
xs <- many character
return (x:xs)
-- | Accepts any characters (except double quotes) from the input stream
anything' :: Parser String
anything' = do x <- character'
xs <- many character'
return (x:xs)
nat :: Parser Int
nat = do xs <- many1 digit
return (read xs)
int :: Parser Int
int = do char '-'
n <- nat
return (-n)
||| nat
-- | Parses input for a float or integer
floatInt :: Parser Lit
floatInt = do i <- int
do char '.'
f <- nat
return (FLit (read(show i ++ "." ++ show f)))
||| return (ILit i)
-- | Parse input for strings
str :: Parser Lit
str = do char '\"'
s <- anything'
char '\"'
return (SLit s)
-- | Parses input for a float, integer or string
floatIntStr :: Parser Lit
floatIntStr = do s <- str
return s
||| do i <- floatInt
return i
space :: Parser ()
space = do many (sat isSpace)
return ()
{-
Ignoring spacing
----------------
-}
token :: Parser a -> Parser a
token p = do space
v <- p
space
return v
identifier :: Parser String
identifier = token ident
natural :: Parser Int
natural = token nat
integer :: Parser Int
integer = token int
symbol :: String -> Parser String
symbol xs = token (string xs)
| MaximKN/Haskell1 | src/Parsing.hs | gpl-3.0 | 6,028 | 16 | 18 | 3,579 | 1,349 | 672 | 677 | 112 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Webhooks.Create
-- 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)
--
-- Creates a webhook in the specified agent.
--
-- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.webhooks.create@.
module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Webhooks.Create
(
-- * REST Resource
ProjectsLocationsAgentsWebhooksCreateResource
-- * Creating a Request
, projectsLocationsAgentsWebhooksCreate
, ProjectsLocationsAgentsWebhooksCreate
-- * Request Lenses
, plawcParent
, plawcXgafv
, plawcUploadProtocol
, plawcAccessToken
, plawcUploadType
, plawcPayload
, plawcCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.locations.agents.webhooks.create@ method which the
-- 'ProjectsLocationsAgentsWebhooksCreate' request conforms to.
type ProjectsLocationsAgentsWebhooksCreateResource =
"v3" :>
Capture "parent" Text :>
"webhooks" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GoogleCloudDialogflowCxV3Webhook :>
Post '[JSON] GoogleCloudDialogflowCxV3Webhook
-- | Creates a webhook in the specified agent.
--
-- /See:/ 'projectsLocationsAgentsWebhooksCreate' smart constructor.
data ProjectsLocationsAgentsWebhooksCreate =
ProjectsLocationsAgentsWebhooksCreate'
{ _plawcParent :: !Text
, _plawcXgafv :: !(Maybe Xgafv)
, _plawcUploadProtocol :: !(Maybe Text)
, _plawcAccessToken :: !(Maybe Text)
, _plawcUploadType :: !(Maybe Text)
, _plawcPayload :: !GoogleCloudDialogflowCxV3Webhook
, _plawcCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsAgentsWebhooksCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plawcParent'
--
-- * 'plawcXgafv'
--
-- * 'plawcUploadProtocol'
--
-- * 'plawcAccessToken'
--
-- * 'plawcUploadType'
--
-- * 'plawcPayload'
--
-- * 'plawcCallback'
projectsLocationsAgentsWebhooksCreate
:: Text -- ^ 'plawcParent'
-> GoogleCloudDialogflowCxV3Webhook -- ^ 'plawcPayload'
-> ProjectsLocationsAgentsWebhooksCreate
projectsLocationsAgentsWebhooksCreate pPlawcParent_ pPlawcPayload_ =
ProjectsLocationsAgentsWebhooksCreate'
{ _plawcParent = pPlawcParent_
, _plawcXgafv = Nothing
, _plawcUploadProtocol = Nothing
, _plawcAccessToken = Nothing
, _plawcUploadType = Nothing
, _plawcPayload = pPlawcPayload_
, _plawcCallback = Nothing
}
-- | Required. The agent to create a webhook for. Format:
-- \`projects\/\/locations\/\/agents\/\`.
plawcParent :: Lens' ProjectsLocationsAgentsWebhooksCreate Text
plawcParent
= lens _plawcParent (\ s a -> s{_plawcParent = a})
-- | V1 error format.
plawcXgafv :: Lens' ProjectsLocationsAgentsWebhooksCreate (Maybe Xgafv)
plawcXgafv
= lens _plawcXgafv (\ s a -> s{_plawcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plawcUploadProtocol :: Lens' ProjectsLocationsAgentsWebhooksCreate (Maybe Text)
plawcUploadProtocol
= lens _plawcUploadProtocol
(\ s a -> s{_plawcUploadProtocol = a})
-- | OAuth access token.
plawcAccessToken :: Lens' ProjectsLocationsAgentsWebhooksCreate (Maybe Text)
plawcAccessToken
= lens _plawcAccessToken
(\ s a -> s{_plawcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plawcUploadType :: Lens' ProjectsLocationsAgentsWebhooksCreate (Maybe Text)
plawcUploadType
= lens _plawcUploadType
(\ s a -> s{_plawcUploadType = a})
-- | Multipart request metadata.
plawcPayload :: Lens' ProjectsLocationsAgentsWebhooksCreate GoogleCloudDialogflowCxV3Webhook
plawcPayload
= lens _plawcPayload (\ s a -> s{_plawcPayload = a})
-- | JSONP
plawcCallback :: Lens' ProjectsLocationsAgentsWebhooksCreate (Maybe Text)
plawcCallback
= lens _plawcCallback
(\ s a -> s{_plawcCallback = a})
instance GoogleRequest
ProjectsLocationsAgentsWebhooksCreate
where
type Rs ProjectsLocationsAgentsWebhooksCreate =
GoogleCloudDialogflowCxV3Webhook
type Scopes ProjectsLocationsAgentsWebhooksCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient
ProjectsLocationsAgentsWebhooksCreate'{..}
= go _plawcParent _plawcXgafv _plawcUploadProtocol
_plawcAccessToken
_plawcUploadType
_plawcCallback
(Just AltJSON)
_plawcPayload
dialogFlowService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsAgentsWebhooksCreateResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Webhooks/Create.hs | mpl-2.0 | 5,950 | 0 | 17 | 1,274 | 785 | 459 | 326 | 121 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.Subnetworks.AggregatedList
-- 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)
--
-- Retrieves an aggregated list of subnetworks.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.subnetworks.aggregatedList@.
module Network.Google.Resource.Compute.Subnetworks.AggregatedList
(
-- * REST Resource
SubnetworksAggregatedListResource
-- * Creating a Request
, subnetworksAggregatedList
, SubnetworksAggregatedList
-- * Request Lenses
, salOrderBy
, salProject
, salFilter
, salPageToken
, salMaxResults
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.subnetworks.aggregatedList@ method which the
-- 'SubnetworksAggregatedList' request conforms to.
type SubnetworksAggregatedListResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"aggregated" :>
"subnetworks" :>
QueryParam "orderBy" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] SubnetworkAggregatedList
-- | Retrieves an aggregated list of subnetworks.
--
-- /See:/ 'subnetworksAggregatedList' smart constructor.
data SubnetworksAggregatedList = SubnetworksAggregatedList'
{ _salOrderBy :: !(Maybe Text)
, _salProject :: !Text
, _salFilter :: !(Maybe Text)
, _salPageToken :: !(Maybe Text)
, _salMaxResults :: !(Textual Word32)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SubnetworksAggregatedList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'salOrderBy'
--
-- * 'salProject'
--
-- * 'salFilter'
--
-- * 'salPageToken'
--
-- * 'salMaxResults'
subnetworksAggregatedList
:: Text -- ^ 'salProject'
-> SubnetworksAggregatedList
subnetworksAggregatedList pSalProject_ =
SubnetworksAggregatedList'
{ _salOrderBy = Nothing
, _salProject = pSalProject_
, _salFilter = Nothing
, _salPageToken = Nothing
, _salMaxResults = 500
}
-- | Sorts list results by a certain order. By default, results are returned
-- in alphanumerical order based on the resource name. You can also sort
-- results in descending order based on the creation timestamp using
-- orderBy=\"creationTimestamp desc\". This sorts results based on the
-- creationTimestamp field in reverse chronological order (newest result
-- first). Use this to sort resources like operations so that the newest
-- operation is returned first. Currently, only sorting by name or
-- creationTimestamp desc is supported.
salOrderBy :: Lens' SubnetworksAggregatedList (Maybe Text)
salOrderBy
= lens _salOrderBy (\ s a -> s{_salOrderBy = a})
-- | Project ID for this request.
salProject :: Lens' SubnetworksAggregatedList Text
salProject
= lens _salProject (\ s a -> s{_salProject = a})
-- | Sets a filter expression for filtering listed resources, in the form
-- filter={expression}. Your {expression} must be in the format: field_name
-- comparison_string literal_string. The field_name is the name of the
-- field you want to compare. Only atomic field types are supported
-- (string, number, boolean). The comparison_string must be either eq
-- (equals) or ne (not equals). The literal_string is the string value to
-- filter to. The literal value must be valid for the type of field you are
-- filtering by (string, number, boolean). For string fields, the literal
-- value is interpreted as a regular expression using RE2 syntax. The
-- literal value must match the entire field. For example, to filter for
-- instances that do not have a name of example-instance, you would use
-- filter=name ne example-instance. You can filter on nested fields. For
-- example, you could filter on instances that have set the
-- scheduling.automaticRestart field to true. Use filtering on nested
-- fields to take advantage of labels to organize and search for results
-- based on label values. To filter on multiple expressions, provide each
-- separate expression within parentheses. For example,
-- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple
-- expressions are treated as AND expressions, meaning that resources must
-- match all expressions to pass the filters.
salFilter :: Lens' SubnetworksAggregatedList (Maybe Text)
salFilter
= lens _salFilter (\ s a -> s{_salFilter = a})
-- | Specifies a page token to use. Set pageToken to the nextPageToken
-- returned by a previous list request to get the next page of results.
salPageToken :: Lens' SubnetworksAggregatedList (Maybe Text)
salPageToken
= lens _salPageToken (\ s a -> s{_salPageToken = a})
-- | The maximum number of results per page that should be returned. If the
-- number of available results is larger than maxResults, Compute Engine
-- returns a nextPageToken that can be used to get the next page of results
-- in subsequent list requests.
salMaxResults :: Lens' SubnetworksAggregatedList Word32
salMaxResults
= lens _salMaxResults
(\ s a -> s{_salMaxResults = a})
. _Coerce
instance GoogleRequest SubnetworksAggregatedList
where
type Rs SubnetworksAggregatedList =
SubnetworkAggregatedList
type Scopes SubnetworksAggregatedList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/compute.readonly"]
requestClient SubnetworksAggregatedList'{..}
= go _salProject _salOrderBy _salFilter _salPageToken
(Just _salMaxResults)
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy SubnetworksAggregatedListResource)
mempty
| rueshyna/gogol | gogol-compute/gen/Network/Google/Resource/Compute/Subnetworks/AggregatedList.hs | mpl-2.0 | 6,836 | 0 | 18 | 1,474 | 676 | 407 | 269 | 97 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Compute.TargetSSLProxies.SetProxyHeader
-- 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)
--
-- Changes the ProxyHeaderType for TargetSslProxy.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetSslProxies.setProxyHeader@.
module Network.Google.Resource.Compute.TargetSSLProxies.SetProxyHeader
(
-- * REST Resource
TargetSSLProxiesSetProxyHeaderResource
-- * Creating a Request
, targetSSLProxiesSetProxyHeader
, TargetSSLProxiesSetProxyHeader
-- * Request Lenses
, tspsphRequestId
, tspsphProject
, tspsphPayload
, tspsphTargetSSLProxy
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.targetSslProxies.setProxyHeader@ method which the
-- 'TargetSSLProxiesSetProxyHeader' request conforms to.
type TargetSSLProxiesSetProxyHeaderResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"targetSslProxies" :>
Capture "targetSslProxy" Text :>
"setProxyHeader" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TargetSSLProxiesSetProxyHeaderRequest
:> Post '[JSON] Operation
-- | Changes the ProxyHeaderType for TargetSslProxy.
--
-- /See:/ 'targetSSLProxiesSetProxyHeader' smart constructor.
data TargetSSLProxiesSetProxyHeader =
TargetSSLProxiesSetProxyHeader'
{ _tspsphRequestId :: !(Maybe Text)
, _tspsphProject :: !Text
, _tspsphPayload :: !TargetSSLProxiesSetProxyHeaderRequest
, _tspsphTargetSSLProxy :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TargetSSLProxiesSetProxyHeader' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tspsphRequestId'
--
-- * 'tspsphProject'
--
-- * 'tspsphPayload'
--
-- * 'tspsphTargetSSLProxy'
targetSSLProxiesSetProxyHeader
:: Text -- ^ 'tspsphProject'
-> TargetSSLProxiesSetProxyHeaderRequest -- ^ 'tspsphPayload'
-> Text -- ^ 'tspsphTargetSSLProxy'
-> TargetSSLProxiesSetProxyHeader
targetSSLProxiesSetProxyHeader pTspsphProject_ pTspsphPayload_ pTspsphTargetSSLProxy_ =
TargetSSLProxiesSetProxyHeader'
{ _tspsphRequestId = Nothing
, _tspsphProject = pTspsphProject_
, _tspsphPayload = pTspsphPayload_
, _tspsphTargetSSLProxy = pTspsphTargetSSLProxy_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
tspsphRequestId :: Lens' TargetSSLProxiesSetProxyHeader (Maybe Text)
tspsphRequestId
= lens _tspsphRequestId
(\ s a -> s{_tspsphRequestId = a})
-- | Project ID for this request.
tspsphProject :: Lens' TargetSSLProxiesSetProxyHeader Text
tspsphProject
= lens _tspsphProject
(\ s a -> s{_tspsphProject = a})
-- | Multipart request metadata.
tspsphPayload :: Lens' TargetSSLProxiesSetProxyHeader TargetSSLProxiesSetProxyHeaderRequest
tspsphPayload
= lens _tspsphPayload
(\ s a -> s{_tspsphPayload = a})
-- | Name of the TargetSslProxy resource whose ProxyHeader is to be set.
tspsphTargetSSLProxy :: Lens' TargetSSLProxiesSetProxyHeader Text
tspsphTargetSSLProxy
= lens _tspsphTargetSSLProxy
(\ s a -> s{_tspsphTargetSSLProxy = a})
instance GoogleRequest TargetSSLProxiesSetProxyHeader
where
type Rs TargetSSLProxiesSetProxyHeader = Operation
type Scopes TargetSSLProxiesSetProxyHeader =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient TargetSSLProxiesSetProxyHeader'{..}
= go _tspsphProject _tspsphTargetSSLProxy
_tspsphRequestId
(Just AltJSON)
_tspsphPayload
computeService
where go
= buildClient
(Proxy ::
Proxy TargetSSLProxiesSetProxyHeaderResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/TargetSSLProxies/SetProxyHeader.hs | mpl-2.0 | 5,479 | 0 | 18 | 1,191 | 561 | 335 | 226 | 94 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Tasks.TaskLists.Update
-- 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)
--
-- Updates the authenticated user\'s specified task list.
--
-- /See:/ <https://developers.google.com/tasks/ Tasks API Reference> for @tasks.tasklists.update@.
module Network.Google.Resource.Tasks.TaskLists.Update
(
-- * REST Resource
TaskListsUpdateResource
-- * Creating a Request
, taskListsUpdate
, TaskListsUpdate
-- * Request Lenses
, tluXgafv
, tluUploadProtocol
, tluAccessToken
, tluUploadType
, tluPayload
, tluTaskList
, tluCallback
) where
import Network.Google.AppsTasks.Types
import Network.Google.Prelude
-- | A resource alias for @tasks.tasklists.update@ method which the
-- 'TaskListsUpdate' request conforms to.
type TaskListsUpdateResource =
"tasks" :>
"v1" :>
"users" :>
"@me" :>
"lists" :>
Capture "tasklist" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TaskList :> Put '[JSON] TaskList
-- | Updates the authenticated user\'s specified task list.
--
-- /See:/ 'taskListsUpdate' smart constructor.
data TaskListsUpdate =
TaskListsUpdate'
{ _tluXgafv :: !(Maybe Xgafv)
, _tluUploadProtocol :: !(Maybe Text)
, _tluAccessToken :: !(Maybe Text)
, _tluUploadType :: !(Maybe Text)
, _tluPayload :: !TaskList
, _tluTaskList :: !Text
, _tluCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TaskListsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tluXgafv'
--
-- * 'tluUploadProtocol'
--
-- * 'tluAccessToken'
--
-- * 'tluUploadType'
--
-- * 'tluPayload'
--
-- * 'tluTaskList'
--
-- * 'tluCallback'
taskListsUpdate
:: TaskList -- ^ 'tluPayload'
-> Text -- ^ 'tluTaskList'
-> TaskListsUpdate
taskListsUpdate pTluPayload_ pTluTaskList_ =
TaskListsUpdate'
{ _tluXgafv = Nothing
, _tluUploadProtocol = Nothing
, _tluAccessToken = Nothing
, _tluUploadType = Nothing
, _tluPayload = pTluPayload_
, _tluTaskList = pTluTaskList_
, _tluCallback = Nothing
}
-- | V1 error format.
tluXgafv :: Lens' TaskListsUpdate (Maybe Xgafv)
tluXgafv = lens _tluXgafv (\ s a -> s{_tluXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tluUploadProtocol :: Lens' TaskListsUpdate (Maybe Text)
tluUploadProtocol
= lens _tluUploadProtocol
(\ s a -> s{_tluUploadProtocol = a})
-- | OAuth access token.
tluAccessToken :: Lens' TaskListsUpdate (Maybe Text)
tluAccessToken
= lens _tluAccessToken
(\ s a -> s{_tluAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tluUploadType :: Lens' TaskListsUpdate (Maybe Text)
tluUploadType
= lens _tluUploadType
(\ s a -> s{_tluUploadType = a})
-- | Multipart request metadata.
tluPayload :: Lens' TaskListsUpdate TaskList
tluPayload
= lens _tluPayload (\ s a -> s{_tluPayload = a})
-- | Task list identifier.
tluTaskList :: Lens' TaskListsUpdate Text
tluTaskList
= lens _tluTaskList (\ s a -> s{_tluTaskList = a})
-- | JSONP
tluCallback :: Lens' TaskListsUpdate (Maybe Text)
tluCallback
= lens _tluCallback (\ s a -> s{_tluCallback = a})
instance GoogleRequest TaskListsUpdate where
type Rs TaskListsUpdate = TaskList
type Scopes TaskListsUpdate =
'["https://www.googleapis.com/auth/tasks"]
requestClient TaskListsUpdate'{..}
= go _tluTaskList _tluXgafv _tluUploadProtocol
_tluAccessToken
_tluUploadType
_tluCallback
(Just AltJSON)
_tluPayload
appsTasksService
where go
= buildClient
(Proxy :: Proxy TaskListsUpdateResource)
mempty
| brendanhay/gogol | gogol-apps-tasks/gen/Network/Google/Resource/Tasks/TaskLists/Update.hs | mpl-2.0 | 4,907 | 0 | 20 | 1,236 | 790 | 459 | 331 | 116 | 1 |
module GameSettings where
import Data.Default
data GenMoveType = Simple | WithTime Int | WithComplexity Int
deriving (Eq, Show, Read)
instance Default GenMoveType where
def = Simple
data BeginPattern = Empty | Cross | TwoCrosses | TripleCross
deriving (Eq, Show, Read)
instance Default BeginPattern where
def = Cross
data GameSettings = GameSettings { gsWidth :: Int
, gsHeight :: Int
, gsGenMoveType :: GenMoveType
, gsBeginPattern :: BeginPattern
, gsRedBotPath :: Maybe String
, gsBlackBotPath :: Maybe String
}
instance Default GameSettings where
def = GameSettings { gsWidth = 39
, gsHeight = 32
, gsGenMoveType = def
, gsBeginPattern = def
, gsRedBotPath = Nothing
, gsBlackBotPath = Nothing
}
| kurnevsky/missile | src/GameSettings.hs | agpl-3.0 | 1,041 | 0 | 9 | 451 | 200 | 119 | 81 | 23 | 0 |
-- eidolon -- A simple gallery in Haskell and Yesod
-- Copyright (C) 2015 Amedeo Molnár
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published
-- by the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU 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 <http://www.gnu.org/licenses/>.
module Handler.Upload where
import Import as I
import Data.Time
import Data.Maybe
import qualified Data.Text as T
import Data.List as L
import qualified System.FilePath as FP
import Filesystem.Path.CurrentOS
import Graphics.ImageMagick.MagickWand
import Text.Blaze.Internal
getDirectUploadR :: AlbumId -> Handler Html
getDirectUploadR albumId = do
tempAlbum <- runDB $ get albumId
case tempAlbum of -- does the requested album exist
Just album -> do
ownerId <- return $ albumOwner album
msu <- lookupSession "userId"
case msu of -- is anybody logged in
Just tempUserId -> do
userId <- return $ getUserIdFromText tempUserId
presence <- return $ (userId == ownerId) || (userId `elem` (albumShares album))
case presence of -- is the owner present or a user with whom the album is shared
True -> do
(dUploadWidget, enctype) <- generateFormPost $ dUploadForm userId albumId
formLayout $ do
setTitle $ toHtml ("Eidolon :: Upload medium to " `T.append` (albumTitle album))
$(widgetFile "dUpload")
False -> do
setMessage "You must own this album to upload"
redirect $ AlbumR albumId
Nothing -> do
setMessage "You must be logged in to upload"
redirect $ LoginR
Nothing -> do
setMessage "This album does not exist"
redirect $ HomeR
postDirectUploadR :: AlbumId -> Handler Html
postDirectUploadR albumId = do
tempAlbum <- runDB $ get albumId
case tempAlbum of -- does the album exist
Just album -> do
ownerId <- return $ albumOwner album
msu <- lookupSession "userId"
case msu of -- is anybody logged in
Just tempUserId -> do
userId <- return $ getUserIdFromText tempUserId
presence <- return $ (userId == ownerId) || (userId `elem` (albumShares album))
case presence of -- is the logged in user the owner or is the album shared with him
True -> do
((result, _), _) <- runFormPost (dUploadForm userId albumId)
case result of
FormSuccess temp -> do
fils <- return $ fileBulkFiles temp
indFils <- return $ zip [1..] fils
errNames <- mapM
(\(index, file) -> do
mime <- return $ fileContentType file
case mime `elem` acceptedTypes of
True -> do
path <- writeOnDrive file ownerId albumId
(thumbPath, iWidth, tWidth) <- generateThumb path ownerId albumId
tempName <- case length indFils == 1 of
False -> return $ ((fileBulkPrefix temp) `T.append` " " `T.append` (T.pack (show index)) `T.append` " of " `T.append` (T.pack (show (length indFils))))
True -> return $ fileBulkPrefix temp
medium <- return $ Medium
tempName
('/' : path)
('/' : thumbPath)
mime
(fileBulkTime temp)
(fileBulkOwner temp)
(fileBulkDesc temp)
(fileBulkTags temp)
iWidth
tWidth
albumId
mId <- runDB $ I.insert medium
inALbum <- runDB $ getJust albumId
newMediaList <- return $ mId : (albumContent inALbum)
runDB $ update albumId [AlbumContent =. newMediaList]
return Nothing
False -> do
return $ Just $ fileName file
) indFils
onlyErrNames <- return $ removeItem Nothing errNames
case L.null onlyErrNames of
True -> do
setMessage "All images succesfully uploaded"
redirect $ HomeR
False -> do
justErrNames <- return $ map fromJust onlyErrNames
msg <- return $ Content $ Text $ "File type not supported of: " `T.append` (T.intercalate ", " justErrNames)
setMessage msg
redirect $ HomeR
_ -> do
setMessage "There was an error uploading the file"
redirect $ DirectUploadR albumId
False -> do -- owner is not present
setMessage "You must own this album to upload"
redirect $ AlbumR albumId
Nothing -> do
setMessage "You must be logged in to upload"
redirect $ AlbumR albumId
Nothing -> do
setMessage "This Album does not exist"
redirect $ AlbumR albumId
generateThumb :: FP.FilePath -> UserId -> AlbumId -> Handler (FP.FilePath, Int, Int)
generateThumb path userId albumId = do
newName <- return $ (FP.takeBaseName path) ++ "_thumb.jpg"
newPath <- return $ "static" FP.</> "data"
FP.</> (T.unpack $ extractKey userId)
FP.</> (T.unpack $ extractKey albumId)
FP.</> newName
(iWidth, tWidth) <- liftIO $ withMagickWandGenesis $ do
(_ , w) <- magickWand
p <- pixelWand
readImage w (decodeString path)
w1 <- getImageWidth w
h1 <- getImageHeight w
h2 <- return 230
w2 <- return $ floor (((fromIntegral w1) / (fromIntegral h1)) * (fromIntegral h2) :: Double)
setImageAlphaChannel w deactivateAlphaChannel
setImageFormat w "jpeg"
resizeImage w w2 h2 lanczosFilter 1
setImageCompressionQuality w 95
writeImage w (Just (decodeString newPath))
return (w1, w2)
return (newPath, iWidth, tWidth)
writeOnDrive :: FileInfo -> UserId -> AlbumId -> Handler FP.FilePath
writeOnDrive fil userId albumId = do
--filen <- return $ fileName fil
album <- runDB $ getJust albumId
filen <- return $ show $ (length $ albumContent album) + 1
ext <- return $ FP.takeExtension $ T.unpack $ fileName fil
path <- return $ "static" FP.</> "data"
FP.</> (T.unpack $ extractKey userId)
FP.</> (T.unpack $ extractKey albumId)
FP.</> filen ++ ext
liftIO $ fileMove fil path
return path
dUploadForm :: UserId -> AlbumId -> Form FileBulk
dUploadForm userId albumId = renderDivs $ FileBulk
<$> areq textField "Title" Nothing
<*> areq multiFileField "Select file(s)" Nothing
<*> lift (liftIO getCurrentTime)
<*> pure userId
<*> areq textareaField "Description" Nothing
<*> areq tagField "Enter tags" Nothing
<*> pure albumId
data FileBulk = FileBulk
{ fileBulkPrefix :: Text
, fileBulkFiles :: [FileInfo]
, fileBulkTime :: UTCTime
, fileBulkOwner :: UserId
, fileBulkDesc :: Textarea
, fileBulkTags :: [Text]
, fileBulkAlbum :: AlbumId
}
getUploadR :: Handler Html
getUploadR = do
msu <- lookupSession "userId"
case msu of
Just tempUserId -> do
userId <- return $ getUserIdFromText tempUserId
user <- runDB $ getJust userId
albums <- return $ userAlbums user
case I.null albums of
False -> do
(uploadWidget, enctype) <- generateFormPost (bulkUploadForm userId)
formLayout $ do
setTitle "Eidolon :: Upload Medium"
$(widgetFile "bulkUpload")
True -> do
setMessage "Please create an album first"
redirect $ NewAlbumR
Nothing -> do
setMessage "You need to be logged in"
redirect $ LoginR
bulkUploadForm :: UserId -> Form FileBulk
bulkUploadForm userId = renderDivs $ (\a b c d e f g -> FileBulk b c d e f g a)
<$> areq (selectField albums) "Album" Nothing
<*> areq textField "Title" Nothing
<*> areq multiFileField "Select file(s)" Nothing
<*> lift (liftIO getCurrentTime)
<*> pure userId
<*> areq textareaField "Description" Nothing
<*> areq tagField "Enter tags" Nothing
where
albums = do
allEnts <- runDB $ selectList [] [Desc AlbumTitle]
entities <- return $
map fromJust $
removeItem Nothing $ map
(\ent -> do
case (userId == (albumOwner $ entityVal ent)) || (userId `elem` (albumShares $ entityVal ent)) of
True -> Just ent
False -> Nothing
) allEnts
optionsPairs $ I.map (\alb -> (albumTitle $ entityVal alb, entityKey alb)) entities
postUploadR :: Handler Html
postUploadR = do
msu <- lookupSession "userId"
case msu of
Just tempUserId -> do
userId <- lift $ pure $ getUserIdFromText tempUserId
((result, _), _) <- runFormPost (bulkUploadForm userId)
case result of
FormSuccess temp -> do
fils <- return $ fileBulkFiles temp
indFils <- return $ zip [1..] fils
errNames <- mapM
(\(index, file) -> do
mime <- return $ fileContentType file
case mime `elem` acceptedTypes of
True -> do
inAlbumId <- return $ fileBulkAlbum temp
albRef <- runDB $ getJust inAlbumId
ownerId <- return $ albumOwner albRef
path <- writeOnDrive file ownerId inAlbumId
(thumbPath, iWidth, tWidth) <- generateThumb path ownerId inAlbumId
tempName <- case length indFils == 1 of
False -> return $ ((fileBulkPrefix temp) `T.append` " " `T.append` (T.pack (show index)) `T.append` " of " `T.append` (T.pack (show (length indFils))))
True -> return $ fileBulkPrefix temp
medium <- return $ Medium
tempName
('/' : path)
('/' : thumbPath)
mime
(fileBulkTime temp)
(fileBulkOwner temp)
(fileBulkDesc temp)
(fileBulkTags temp)
iWidth
tWidth
inAlbumId
mId <- runDB $ I.insert medium
inALbum <- runDB $ getJust inAlbumId
newMediaList <- return $ mId : (albumContent inALbum)
runDB $ update inAlbumId [AlbumContent =. newMediaList]
return Nothing
False -> do
return $ Just $ fileName file
) indFils
onlyErrNames <- return $ removeItem Nothing errNames
case L.null onlyErrNames of
True -> do
setMessage "All images succesfully uploaded"
redirect $ HomeR
False -> do
justErrNames <- return $ map fromJust onlyErrNames
msg <- return $ Content $ Text $ "File type not supported of: " `T.append` (T.intercalate ", " justErrNames)
setMessage msg
redirect $ HomeR
_ -> do
setMessage "There was an error uploading the file"
redirect $ UploadR
Nothing -> do
setMessage "You need to be logged in"
redirect $ LoginR
| Mic92/eidolon | Handler/Upload.hs | agpl-3.0 | 11,945 | 0 | 50 | 4,172 | 3,077 | 1,490 | 1,587 | 256 | 8 |
{-
Created : 2013 Dec 01 (Sun) 08:57:06 by carr.
Last Modified : 2013 Dec 01 (Sun) 09:45:26 by carr.
http://en.wikibooks.org/wiki/Haskell/Monad_transformers
-}
import Data.Char
import Data.Maybe
------------------------------------------------------------------------------
-- non-monadic
askPassword :: IO ()
askPassword = do
putStrLn "Insert your new password:"
maybe_value <- getPassword
putStrLn $ if isJust maybe_value then "GOOD" else "BAD"
getPassword :: IO (Maybe String)
getPassword = do
s <- getLine
return $ if isValid s then Just s else Nothing
isValid :: String -> Bool
isValid s = length s >= 8 && any isAlpha s && any isNumber s && any isPunctuation s
------------------------------------------------------------------------------
-- monadic
{-
MaybeT is a monad m, wrapper around m (Maybe a)
newtype (Monad m) => MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) }
- MaybeT type constructor
- term/value constructor: also called MaybeT
- accessor function: runMaybeT
Monad transformers are monads themselves.
instance Monad m => Monad (MaybeT m) where
return = MaybeT . return . Just
-- `Just` injects into `Maybe`
-- generic `return` injects into `m`
-- could have written: `return = MaybeT . return . return`
-- The signature of (>>=), specialized to MaybeT m
-- (>>=) :: MaybeT m a -> (a -> MaybeT m b) -> MaybeT m b
x >>= f =
MaybeT $ do maybe_value <- runMaybeT x
case maybe_value of
Nothing -> return Nothing
Just value -> runMaybeT $ f value
-- `runMaybeT` accessor to unwrap x == `m (Maybe a)`
-- <- extracts `Maybe a` from `m`
-- `return Nothing` == `m Nothing`
-- `f :: MaybeT m b` so `runMaybeT` to give `m (Maybe a)` (i.e., same type as `Nothing` branch)
-- Wrapped with MaybeT
Same structure as `Maybe` except for extra (un)wrapping:
-- (>>=) for Maybe
maybe_value >>= f =
case maybe_value of
Nothing -> Nothing
Just value -> f value
Useful:
-- Maybe is instance of MonadPlus, so MaybeT should be too
instance Monad m => MonadPlus (MaybeT m) where
mzero = MaybeT $ return Nothing
mplus x y = MaybeT $ do maybe_value <- runMaybeT x
case maybe_value of
Nothing -> runMaybeT y
Just _ -> return maybe_value
-- take funs from m monad to the MaybeT m monad
instance MonadTrans MaybeT where lift = MaybeT . (liftM Just)
-}
-- no need to check Nothing/Just - bind handles it
-- lift to get getLine/putStrLn into MaybeT IO
-- since MaybeT IO is MonadPlus instance, can use guard : does return mzero (i.e. IO Nothing) for bad
getValidPasswordM :: MaybeT IO String
getValidPasswordM = do
s <- lift getLine
guard (isValid s) -- MonadPlus provides guard.
return s
askPasswordM :: MaybeT IO ()
askPasswordM = do
lift $ putStrLn "Insert your new password:"
value <- getValidPassword
lift $ putStrLn "Storing in database..."
-- use of MonadPlus.msum
askPasswordM' :: MaybeT IO ()
askPasswordM' = do
lift $ putStrLn "Insert your new password:"
value <- msum $ repeat getValidPassword
lift $ putStrLn "Storing in database..."
{-
base monad : the non-transformer monad on which transformer is based
inner monad : other monad, on which the transformer is applied
-}
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/monads/Wikibooks_haskell_monad_transformers.hs | unlicense | 3,517 | 0 | 9 | 948 | 306 | 150 | 156 | 28 | 2 |
module Network.Haskoin.Wallet.Model
( -- Database types
Account(..)
, AccountId
, WalletAddr(..)
, WalletAddrId
, WalletState(..)
, WalletStateId
, WalletCoin(..)
, WalletCoinId
, SpentCoin(..)
, SpentCoinId
, WalletTx(..)
, WalletTxId
, EntityField(..)
, Unique(..)
, migrateWallet
-- JSON conversion
, toJsonAccount
, toJsonAddr
, toJsonCoin
, toJsonTx
) where
import Data.Word (Word32, Word64)
import Data.Time (UTCTime)
import Data.Text (Text)
import Data.String.Conversions (cs)
import Database.Persist (EntityField, Unique)
import Database.Persist.Quasi (lowerCaseSettings)
import Database.Persist.TH
( share
, mkPersist
, sqlSettings
, mkMigrate
, persistFileWith
)
import Network.Haskoin.Wallet.Types
import Network.Haskoin.Block
import Network.Haskoin.Transaction
import Network.Haskoin.Script
import Network.Haskoin.Crypto
import Network.Haskoin.Network
share [ mkPersist sqlSettings
, mkMigrate "migrateWallet"
]
$(persistFileWith lowerCaseSettings "config/models")
{- JSON Types -}
toJsonAccount :: Maybe Mnemonic -> Account -> JsonAccount
toJsonAccount msM acc = JsonAccount
{ jsonAccountName = accountName acc
, jsonAccountType = accountType acc
, jsonAccountMnemonic = fmap cs msM
, jsonAccountMaster = accountMaster acc
, jsonAccountKeys = accountKeys acc
, jsonAccountGap = accountGap acc
, jsonAccountCreated = accountCreated acc
}
toJsonAddr :: WalletAddr
-> Maybe BalanceInfo
-> JsonAddr
toJsonAddr addr balM = JsonAddr
{ jsonAddrAddress = walletAddrAddress addr
, jsonAddrIndex = walletAddrIndex addr
, jsonAddrType = walletAddrType addr
, jsonAddrLabel = walletAddrLabel addr
, jsonAddrRedeem = walletAddrRedeem addr
, jsonAddrKey = walletAddrKey addr
, jsonAddrCreated = walletAddrCreated addr
, jsonAddrBalance = balM
}
toJsonTx :: AccountName
-> Maybe (BlockHash, BlockHeight) -- ^ Current best block
-> WalletTx
-> JsonTx
toJsonTx acc bbM tx = JsonTx
{ jsonTxHash = walletTxHash tx
, jsonTxNosigHash = walletTxNosigHash tx
, jsonTxType = walletTxType tx
, jsonTxInValue = walletTxInValue tx
, jsonTxOutValue = walletTxOutValue tx
, jsonTxValue = fromIntegral (walletTxInValue tx) -
fromIntegral (walletTxOutValue tx)
, jsonTxInputs = walletTxInputs tx
, jsonTxOutputs = walletTxOutputs tx
, jsonTxChange = walletTxChange tx
, jsonTxTx = walletTxTx tx
, jsonTxIsCoinbase = walletTxIsCoinbase tx
, jsonTxConfidence = walletTxConfidence tx
, jsonTxConfirmedBy = walletTxConfirmedBy tx
, jsonTxConfirmedHeight = walletTxConfirmedHeight tx
, jsonTxConfirmedDate = walletTxConfirmedDate tx
, jsonTxCreated = walletTxCreated tx
, jsonTxAccount = acc
, jsonTxConfirmations = f =<< walletTxConfirmedHeight tx
, jsonTxBestBlock = fst <$> bbM
, jsonTxBestBlockHeight = snd <$> bbM
}
where
f confirmedHeight = case bbM of
Just (_, h) -> return $ fromInteger $
max 0 $ toInteger h - toInteger confirmedHeight + 1
_ -> Nothing
toJsonCoin :: WalletCoin
-> Maybe JsonTx -- ^ Coin’s transaction
-> Maybe JsonAddr -- ^ Coin’s address
-> Maybe JsonTx -- ^ Coin’s spending transaction
-> JsonCoin
toJsonCoin coin txM addrM spendM = JsonCoin
{ jsonCoinHash = walletCoinHash coin
, jsonCoinPos = walletCoinPos coin
, jsonCoinValue = walletCoinValue coin
, jsonCoinScript = walletCoinScript coin
, jsonCoinCreated = walletCoinCreated coin
-- Optional tx
, jsonCoinTx = txM
-- Optional address
, jsonCoinAddress = addrM
-- Optional spending tx
, jsonCoinSpendingTx = spendM
}
| plaprade/haskoin | haskoin-wallet/src/Network/Haskoin/Wallet/Model.hs | unlicense | 4,083 | 0 | 14 | 1,151 | 871 | 500 | 371 | -1 | -1 |
-- Copyright 2013 Matthew Spellings
-- 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.
import Control.Applicative
import Control.Monad
import Data.Array.Accelerate as A
import Data.Map as M
import Data.Monoid
import Data.Text.Lazy.IO (hPutStr)
import Data.Text.Lazy.Builder (toLazyText)
import System.Environment
import System.IO (FilePath(..), IOMode(..), Handle(..), openFile, hFlush, hClose)
import System.Random (randomRs, mkStdGen)
import Data.Array.Accelerate.HasdyContrib as HC
import Hasdy.Types
import Hasdy.Prop
import Hasdy.Prop.Bundle
import Hasdy.Neighbor.Slow as Slow
import Hasdy.Integrate.Leapfrog
import Hasdy.Integrate.VelVerlet
import Hasdy.Potentials.LJ
import Hasdy.Potentials.Sigmoidal
import Hasdy.Spatial
import Hasdy.Vectors
import Hasdy.Dump.Pos
import Hasdy.Thermo
import Hasdy.Thermostats
import Hasdy.Utils
import Hasdy.Utils.Sort
import Hasdy.Neighbor.Fast as Fast
import Data.Array.Accelerate.CUDA
--import Data.Array.Accelerate.Interpreter
-- global constants
scale = 1.5
n = 8
v0 = 1e-1
box = A.constant box'
box' = scale3' scale . pure3' $ Prelude.fromIntegral n
rbuf = constToSingleProp 3
cellR = constToSingleProp 6
lj = LJ (unit 1) (unit 1) :: LJ Float
sig = Sigmoidal (unit 1) (unit 1) (unit 3) :: Sigmoidal Float
dt = constToSingleProp 0.005
typ = ParticleType 0
state = usePP typ <. newPP <. useNList typ <. newNList <. -- neighbor list + old positions
usePP typ <. newPP <. -- accelerations
usePP typ <. newPP <. -- velocities
usePP typ <. newPP -- positions
-- | a single timestep in terms of 'PerParticleProp's
timestep::NList->(PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float))->
(PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float))
timestep nlist (pos, vel, acc) = velVerlet dt masses forceCalc (pos', vel', acc)
where
pos' = perParticleMap (wrapBox box id) pos
vel' = rescale (constToSingleProp 1) masses vel
force = makeAbsolute . wrapBox box . cutoff (A.constant (0, 0, 0)) (3**2) $ ljForce lj
forceCalc p = Fast.foldNeighbors force plus3 (A.constant (0, 0, 0)) nlist typ typ p p
masses = singleToParticleProp (constToSingleProp 1) pos
-- | a group of timesteps glued together under accelerate's run1; also
-- rebuilds neighbor lists if necessary
runTimesteps = runBLens run1 (canal1 state . liftAccs $ f) state state
where
f = Prelude.foldr1 (>->) . Prelude.take 10 . Prelude.repeat $ unliftAccs . bridge1 state $ accTimestep
accTimestep bundIn = bundOut
where
((((((), positions), velocities), accelerations), nlist), oldPositions) = bundleProps bundIn
(rebuilt, nlist', oldIdx) = maybeRebuildNList True cellR rbuf (constToSingleProp box') oldPositions positions nlist
positions' = maybeGatherPerParticle rebuilt oldIdx positions
velocities' = maybeGatherPerParticle rebuilt oldIdx velocities
accelerations' = maybeGatherPerParticle rebuilt oldIdx accelerations
oldPositions' = maybeGatherPerParticle rebuilt oldIdx positions
(positions'', velocities'', accelerations'') = Prelude.iterate (timestep nlist') (positions', velocities', accelerations') Prelude.!! 10
:: (PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float), PerParticleProp (Vec3' Float))
bundOut = Bundle ((((((), positions''), velocities''), accelerations''), nlist'), oldPositions') (A.use ())
-- | several timesteps + dumping to file
-- dumpTimesteps::Handle->(PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float))->
-- IO (PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float), PerParticleProp' (Vec3' Float))
dumpTimesteps handle (positions, velocities, accelerations, nlist, oldPositions) = do
let posvelaccIn = Bundle ((((((), positions), velocities), accelerations), nlist), oldPositions) ()
((((((), positions''), velocities''), accelerations''), nlist''), oldPositions'') =
bundleProps . runTimesteps $ posvelaccIn
Data.Text.Lazy.IO.hPutStr handle $ toLazyText . posFrame box' $ unPerParticleProp' positions'' M.! typ
hFlush handle
return (positions'', velocities'', accelerations'', nlist'', oldPositions'')
-- | run n groups of timesteps
multitimestep n handle (pos, vel, acc, nl, oldP) = do
(pos', vel', acc', nl', oldP') <- dumpTimesteps handle (pos, vel, acc, nl, oldP)
if n <= 0
then return (pos, vel, acc, nl, oldP)
else multitimestep (n-1) handle (pos', vel', acc', nl', oldP')
main = do
let grid idx = r `minus3` center
where
r = scale3 (A.constant scale) $ A.lift (A.fromIntegral x, A.fromIntegral y, A.fromIntegral z)
(Z:.x:.y:.z) = A.unlift idx
center = scale3 0.5 box
positions' = run . A.flatten $ A.generate (A.constant $ (Z:.n:.n:.n) :: Exp DIM3) grid
positions = PerParticleProp $ M.fromList [(ParticleType 0, use positions')]
triplify (x:y:z:rest) = (x, y, z):(triplify rest)
velocities' = A.fromList (Z:.(n*n*n)) . triplify $ randomRs (negate v0, v0) (mkStdGen 5337) :: Vector (Vec3' Float)
velocities = PerParticleProp $ M.fromList [(ParticleType 0, use velocities')] :: PerParticleProp (Vec3' Float)
accelerations = perParticleMap (scale3 0) velocities
vel' = rescale (constToSingleProp 1e-3) masses velocities
masses = singleToParticleProp (constToSingleProp 1) positions
(n':_) <- getArgs
handle <- openFile "dump.pos" WriteMode
let n = read n'::Int
positions' = runPerParticle run positions
velocities' = runPerParticle run velocities
accelerations' = runPerParticle run accelerations
emptyIdx = A.fromList (Z:.0) [] :: A.Vector Int
nlist0 = NList' . M.fromList $ [(typ, SNList' emptyIdx emptyIdx emptyIdx)]
initState = (positions', velocities', accelerations', nlist0, accelerations')
(positions, velocities, accelerations, _, _) <- multitimestep n handle initState
hClose handle
return ()
| klarh/hasdy | test/test.hs | apache-2.0 | 6,548 | 0 | 17 | 1,177 | 1,951 | 1,071 | 880 | 100 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module View.Index (render) where
import Control.Monad (forM_)
import Model.Definition
import Text.Blaze.Html5.Attributes (href, class_)
import Text.Blaze.Html.Renderer.Text
import Data.Monoid((<>))
import View.Header
import qualified Data.Text.Lazy as D
import qualified Text.Blaze.Html5 as H
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import Data.List(isPrefixOf, isSuffixOf)
-- >>> import Test.QuickCheck
-- >>> instance Arbitrary Definition where arbitrary = do a <- arbitrary; b <- arbitrary; return (Definition (D.pack a) (D.pack b))
-- |
--
-- >>> render []
-- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>'ere be some golden terms ye ought to be using me hearties...</h2></div><p>There are no definitions yet.</p><p><a href=\"/add\">Add definition</a></p></body></html>"
--
-- >>> render [Definition "abc" "def"]
-- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>'ere be some golden terms ye ought to be using me hearties...</h2></div><ul><li><span class=\"phrase\">abc</span>: <span class=\"meaning\">def</span></li></ul><p><a href=\"/add\">Add definition</a></p></body></html>"
--
-- >>> render [Definition "abc" "def", Definition "abc&def" "ghi&jkl\"mno"]
-- "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>'ere be some golden terms ye ought to be using me hearties...</h2></div><ul><li><span class=\"phrase\">abc</span>: <span class=\"meaning\">def</span></li><li><span class=\"phrase\">abc&def</span>: <span class=\"meaning\">ghi&jkl"mno</span></li></ul><p><a href=\"/add\">Add definition</a></p></body></html>"
--
-- prop> let r = D.unpack (render s) in "<!DOCTYPE HTML>\n<html><head><title>Pirate Gold</title><link rel=\"stylesheet\" href=\"css/style.css\"></head><body class=\"main\"><div class=\"head\"><h1>Ahoy! Welcome to Pirate Gold.</h1><h2>'ere be some golden terms ye ought to be using me hearties...</h2>" `isPrefixOf` r
--
-- prop> let r = D.unpack (render s) in "<p><a href=\"/add\">Add definition</a></p></body></html>" `isSuffixOf` r
render :: [Definition] -> D.Text
render definitions = renderHtml . H.docTypeHtml $ do
header
H.body H.! class_ "main" $ do
H.div H.! class_ "head" $ do
H.h1 "Ahoy! Welcome to Pirate Gold."
H.h2 "'ere be some golden terms ye ought to be using me hearties..."
if null definitions
then H.p "There are no definitions yet."
else H.ul . forM_ definitions $ (\def -> H.li $ do
(H.span H.! class_ "phrase") (H.toHtml (phrase def)) <> ": "
(H.span H.! class_ "meaning") (H.toHtml (meaning def)))
H.p ((H.a H.! href "/add") "Add definition")
| codemiller/fp-in-the-cloud | src/View/Index.hs | apache-2.0 | 3,131 | 0 | 23 | 446 | 337 | 187 | 150 | 23 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
-- * Demonstrating `non-compositional', context-sensitive processing
-- * The final style
-- * Flatten the additions
module FlatF where
import Intro2 hiding (main)
import PushNegF as Neg hiding (main,Ctx)
-- We are going to write flata as an interpreter.
-- After all, that's all we can do with an expression in a final form.
-- * The nested pattern-matching establishes a context:
-- * flata :: Exp -> Exp
-- * flata e@Lit{} = e
-- * flata e@Neg{} = e
-- * flata (Add (Add e1 e2) e3) = flata (Add e1 (Add e2 e3))
-- * flata (Add e1 e2) = Add e1 (flata e2)
-- The processing is slightly different from push_neg, because we repeatedly
-- process the transformed expression (the last-but one clause)
-- The nested pattern-match again betrays the context-sensitivity.
-- The context in question is expression being the left child of addition.
-- * //
-- So, we define the context
-- (LCA e) means that the context (Add [] e), being the left immediate
-- child of addition whose right child is e. NonLCA is any other context.
data Ctx e = LCA e | NonLCA
-- On other words, LCA e3 represents the context of adding e3 _to the right_ of
-- the expression in focus.
instance ExpSYM repr => ExpSYM (Ctx repr -> repr) where
lit n NonLCA = lit n
lit n (LCA e) = add (lit n) e
neg e NonLCA = neg (e NonLCA)
neg e (LCA e3) = add (neg (e NonLCA)) e3 -- assume only lits are negated
add e1 e2 ctx = e1 (LCA (e2 ctx))
-- The last clause expresses the reassociation-to-the-right
-- * C[Add e1 e2] -> Add e1 C[e2]
-- Recall that after the negations are pushed down, expressions are
-- described by the following grammar
-- * e ::= factor | add e e
-- * factor ::= int | neg int
-- That is, C ::= [] | Add [] e
-- Keep in mind the processing is done bottom-up!
-- A general approach is to use continuations (or monads),
-- or to encode the Ctx with zippers
-- (the defunctionalized continuations, in the present
-- case).
-- The Ctx data type above is tuned to the present example,
-- keeping only the data we need (e.g., we aren't interested
-- in the context of Neg or of the addition on the left,
-- and so we don't represent these cases in Ctx).
-- Exercise: there are several clauses where lit, neg, or add
-- appears on both sides of the definition.
-- In which clause add is being used recursively?
-- The `interpreter' for flattening
flata :: (Ctx repr -> repr) -> repr
flata e = e NonLCA
--norm :: (Neg.Ctx -> Ctx c -> c) -> c
norm = flata . Neg.push_neg
-- Use our sample term
-- We make it a bit complex
tf3 = (add tf1 (neg (neg tf1)))
tf3_view = view tf3
-- "((8 + (-(1 + 2))) + (-(-(8 + (-(1 + 2))))))"
tf3_eval = eval tf3
-- 10
-- The normalized expression can be evaluated with any interpreter
tf3_norm = norm tf3
tf3_norm_view = view tf3_norm
-- "(8 + ((-1) + ((-2) + (8 + ((-1) + (-2))))))"
-- The result of the standard evaluation (the `meaning') is preserved
tf3_norm_eval = eval tf3_norm
-- 10
tf4 = add t (neg t) where t = (add (add (lit 1) (lit 2)) (lit 3))
tf4_view = view tf4
-- "(((1 + 2) + 3) + (-((1 + 2) + 3)))"
tf4_eval = eval tf4
-- 0
tf4_norm = norm tf4
tf4_norm_view = view tf4_norm
-- "(1 + (2 + (3 + ((-1) + ((-2) + (-3))))))"
-- The result of the standard evaluation (the `meaning') is preserved
tf4_norm_eval = eval tf4_norm
-- 0
main = do
print tf3_view
print tf3_eval
print tf3_norm_view
print tf3_norm_eval
if tf3_eval == tf3_norm_eval then return ()
else error "Normalization"
-- normalizing a normal form does not change it
if (view . norm $ tf3_norm) == tf3_norm_view then return ()
else error "Normalization"
print tf4_view
print tf4_eval
print tf4_norm_view
print tf4_norm_eval
if tf4_eval == tf4_norm_eval then return ()
else error "Normalization"
if (view . norm $ tf4_norm) == tf4_norm_view then return ()
else error "Normalization"
| mjhopkins/ttfi | src/haskell/FlatF.hs | apache-2.0 | 4,020 | 8 | 12 | 903 | 621 | 337 | 284 | 44 | 5 |
{-# Language RecordWildCards #-}
-- |
-- Module : GRN.Sparse
-- Copyright : (c) 2011 Jason Knight
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Provides sparse matrix capabilities for an attempt at speeding up the
-- simulation of the Markov Chain.
--
module GRN.Sparse (
calcSSAsDOK
, simulateDOKUnif
, simulateDOK
, normalizeSSD
, simulateCSC
, kmapToDOK
, ssdToSSA
, weightedExpansion
, getNSamples
, module GRN.SparseLib
) where
import GRN.Types
import GRN.SparseLib
import GRN.Utils
import GRN.StateTransition
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import Data.Vector.Strategies
import Control.Monad
import Data.List
import Data.Bits
import Data.Ord (comparing)
import qualified Data.Map as M
import System.Console.ParseArgs
import System.Random.MWC (withSystemRandom, initialize, uniformVector)
import Data.Word (Word32)
simulateDOKUnif :: Args String -> DOK -> SSD
simulateDOKUnif args d@(DOK (m,n) _) = simulateDOK args d (U.replicate n (1.0/(fromIntegral n)))
simulateDOK :: Args String -> DOK -> SSD -> SSD
simulateDOK args d@(DOK (m,n) _) start = regSim (n1+n2) start
where
n1 = getRequiredArg args "n1" :: Int
n2 = getRequiredArg args "n2" :: Int
p = getRequiredArg args "perturb"
csc = dokToCSC d
regSim 0 v = v
regSim n v
| p < 1e-15 = regSim (n-1) (multiplyCSCVM csc v)
| otherwise = regSim (n-1)
(perturb p . multiplyCSCVM csc $ v)
-- | Perturb an SSD by a small amount
perturb :: Double -> SSD -> SSD
perturb p sd = snd . normalizeSSD $ added where
added = U.map (+p) sd
normalizeSSD :: SSD -> (Double,SSA)
normalizeSSD ssd = let fac=U.sum ssd in (fac, U.map (*(1/fac)) ssd)
simulateCSC :: Args String -> CSC -> SSD -> SSD
simulateCSC args csc start = regSim (n1+n2) start
where
n1 = getRequiredArg args "n1" :: Int
n2 = getRequiredArg args "n2" :: Int
avg = getRequiredArg args "avg" :: Int
--norm xv = let fac = (U.sum xv) in (fac,U.map (*(1/fac)) xv)
regSim 0 v = v
regSim n v = regSim (n-1) (multiplyCSCVM csc v)
kmapToDOK :: KmapSet -> Int -> DOK
kmapToDOK kset x = DOK (nStates,nStates) (M.fromList edges)
where
genes = M.keys kset
nGenes = length genes
nStates = 2^nGenes
intStates = [0..nStates-1]
permedStates = map (dec2bin nGenes) intStates
edges = concatMap genEdges permedStates
genEdges :: [Int] -> [((Int,Int),Double)]
genEdges st = map (\(val,to)-> ((from,bin2dec to),val)) tos
where
from = bin2dec st
tos = [(1.0,[])] >>= foldr (>=>) return (stateKmapLus x st genes kset)
calcSSAsDOK :: Args String -> ParseData -> KmapSet -> GeneMC
calcSSAsDOK args p ks = zipNames . allgenes . ssaVec . simVec $ seedList
where
n3 = getRequiredArg args "n3" -- Number of simruns
n4 = getRequiredArg args "n4" -- Starting Seed
pass n f = last.take n.iterate f
-- Get a new randomized graph and simulate
seedList = V.enumFromN (n4) (n3+n4)
simVec :: V.Vector Int -> V.Vector SSD
simVec xv = G.map (simulateDOKUnif args.kmapToDOK ks) xv `using` (parVector 2)
-- Now get the SSAs of these
ssaVec :: V.Vector SSD -> V.Vector SSA
ssaVec xv = G.map ssdToSSA xv `using` (parVector 2)
-- Basically a transpose, to get a list of SSA for each gene instead of
-- each simulation run
allgenes :: V.Vector SSA -> V.Vector (U.Vector Double)
allgenes ssas = G.map (\x-> G.convert $ G.map (G.!x) ssas) (V.fromList [0..(length $ M.keys p)-1])
zipNames :: V.Vector (U.Vector Double) -> M.Map Gene (U.Vector Double)
zipNames xv = M.fromList $ zip (M.keys p) (G.toList xv)
-- | Expands out all determistic networks for a given likelihood network.
-- Number of networks grows superexponentially as (N+1)^(2^N)
-- ie. for n={1-6}: 4, 81, 65536, 1.5e11 (100 billion), 8e24 (8 septillion), 1.2e54 (1.2
-- septendecillion)...
weightedExpansion :: DOK -> V.Vector (Double, CSR)
weightedExpansion dk@(DOK (m,n) _) = wtdlist where
csr = toCSR dk
cols = csrcolIndices csr
rows = csrrowIndices csr
vals = csrValues csr
perrow = (rows U.! 1) - (U.head rows)
cartesian = G.sequence . chunks perrow . G.convert $ cols
cartvals = G.map G.product . G.sequence . chunks perrow . G.convert $ vals
newnnz = G.length . G.head $ cartesian
newrows = U.enumFromN 0 (newnnz+1) --NOTE the +1 here
newvals = U.replicate newnnz 1.0
wtdlist = V.zip cartvals (G.map (\x -> CSR (m,n) newvals (G.convert x) newrows) cartesian)
getNSamples :: Int -> DOK -> IO (V.Vector (Double,CSR))
getNSamples samps dk@(DOK (m,n) _) = do
let
csr = toCSR dk
cols = csrcolIndices csr
rows = csrrowIndices csr
vals = csrValues csr
perrow = (rows U.! 1) - (U.head rows)
wtdvals = G.convert $ G.zip vals cols
rowchunks = chunks perrow $ wtdvals
newnnz = G.length rowchunks
newrows = U.enumFromN 0 (newnnz+1) --NOTE +1 here
newvals = U.replicate newnnz 1.0
go gen = do
unifs <- uniformVector gen m :: IO (V.Vector Double)
let
pickedcols = V.zipWith pick unifs rowchunks
weight = G.product . fst . G.unzip $ pickedcols
network = CSR (m,n) newvals (G.convert . snd . G.unzip $ pickedcols) newrows
return (weight, network)
pick :: Double -> V.Vector (Double,Int) -> (Double,Int)
pick t vec
| G.null vec = error "Pick used with empty list"
| t <= w = (w,x)
| otherwise = pick (t-w) xs
where
(w,x) = G.head vec
xs = G.tail vec
-- Now ,get a list of generators, one for each sample
gen <- withSystemRandom (\gen -> initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32)))
gens <- V.replicateM samps (initialize =<< (uniformVector gen 256 :: IO (U.Vector Word32)))
G.mapM go gens
ssdToSSA :: SSD -> SSA
ssdToSSA ssd = U.reverse $ U.generate ngenes count
where
n = U.length ssd
ngenes = round $ logBase 2 (fromIntegral n)
count i = U.sum $ U.ifilter (\ind _-> testBit ind i) ssd
| binarybana/grn-pathways | GRN/Sparse.hs | bsd-2-clause | 6,308 | 0 | 20 | 1,575 | 2,203 | 1,168 | 1,035 | 127 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextLength.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QTextLength (
QTextLengthType, eVariableLength, eFixedLength, ePercentageLength
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CQTextLengthType a = CQTextLengthType a
type QTextLengthType = QEnum(CQTextLengthType Int)
ieQTextLengthType :: Int -> QTextLengthType
ieQTextLengthType x = QEnum (CQTextLengthType x)
instance QEnumC (CQTextLengthType Int) where
qEnum_toInt (QEnum (CQTextLengthType x)) = x
qEnum_fromInt x = QEnum (CQTextLengthType x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> QTextLengthType -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eVariableLength :: QTextLengthType
eVariableLength
= ieQTextLengthType $ 0
eFixedLength :: QTextLengthType
eFixedLength
= ieQTextLengthType $ 1
ePercentageLength :: QTextLengthType
ePercentageLength
= ieQTextLengthType $ 2
| uduki/hsQt | Qtc/Enums/Gui/QTextLength.hs | bsd-2-clause | 2,552 | 0 | 18 | 530 | 606 | 309 | 297 | 54 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Opaleye.TF.BaseTypes where
import qualified Data.Aeson as Aeson
import Data.ByteString (ByteString)
import Data.Fixed (E0, E1, E2, E3, E6, E9, Fixed)
import Data.Int (Int32, Int64)
import Data.Text
import Data.Time (LocalTime, UTCTime)
import Data.UUID (UUID)
import GHC.TypeLits (Nat)
import qualified Opaleye.Internal.Column as Op
import qualified Opaleye.PGTypes as Op
import Opaleye.TF.Col
import Opaleye.TF.Expr
import Opaleye.TF.Interpretation
import Opaleye.TF.Lit
import Opaleye.TF.Nullable
import Opaleye.TF.Machinery
data WithTimeZone
= WithTimeZone
| WithoutTimeZone
deriving (Eq,Ord,Read,Show,Enum,Bounded)
-- | The universe of base types known about by PostgreSQL.
data PGType
= PGBigint -- ^ @bigint@
| PGBigserial -- ^ @bigserial@
| PGBit (Maybe Nat) -- ^ @bit [ (n) ]@
| PGBitVarying (Maybe Nat) -- ^ @bit varying [ (n) ]@
| PGBoolean -- ^ @boolean@
| PGBox -- ^ @box@
| PGBytea -- ^ @bytea@
| PGCharacter (Maybe Nat) -- ^ @character [ (n) ]@
| PGVarchar Nat -- ^ @character varying (n)@ (unbound @character varying@ is 'PGText')
| PGCidr -- ^ @cidr@
| PGCircle -- ^ @circle@
| PGDate -- ^ @date@
| PGDouble -- ^ @double precision@
| PGInet -- ^ @inet@
| PGInteger -- ^ @integer@
| PGInterval -- ^ @interval@. There is no ability to specify the precision or fields, if you require this please open a feature request.
| PGJSON -- ^ @json@
| PGJSONB -- ^ @jsonb@
| PGLine -- ^ @line@
| PGLseg -- ^ @lseg@
| PGMacaddr -- ^ @macaddr@
| PGMoney -- ^ @money@
| PGNumeric Nat
Nat -- ^ @numeric(p,s)@
| PGPath -- ^ @path@
| PGPGLSN -- ^ @pg_lsn@
| PGPoint -- ^ @point@
| PGPolygon -- ^ @polygon@
| PGReal -- ^ @real@
| PGSmallint -- ^ @smallint@
| PGSmallserial -- ^ @smallserial@
| PGSerial -- ^ @serial@
| PGText -- ^ @text@ and @character varying@
| PGTime WithTimeZone -- ^ @time with/without time zone@
| PGTimestamp WithTimeZone -- ^ @timestamp with/without time zone@
| PGTSQuery -- ^ @tsquery@
| PGTSVector -- ^ @tsvector@
| PGTXIDSnapshot -- ^ @txid_sapnshot@
| PGUUID -- ^ @uuid@
| PGXML -- ^ @xml@
type instance Col (Expr s) (t :: PGType) = Expr s t
type instance Col (Compose (Expr s) 'Nullable) (a :: PGType) = Expr s ('Nullable a)
type instance Col (Compose (Expr s) 'NotNullable) (a :: PGType) = Expr s a
type instance Col Interpret 'PGBigint = Int64
type instance Col Interpret 'PGBoolean = Bool
type instance Col Interpret 'PGInteger = Int32
type instance Col Interpret 'PGReal = Float
type instance Col Interpret 'PGText = Text
type instance Col Interpret ('PGTimestamp 'WithoutTimeZone) = LocalTime
type instance Col Interpret ('PGTimestamp 'WithTimeZone) = UTCTime
type instance Col Interpret 'PGDouble = Double
type instance Col Interpret ('PGNumeric p 0) = Fixed E0
type instance Col Interpret ('PGNumeric p 1) = Fixed E1
type instance Col Interpret ('PGNumeric p 2) = Fixed E2
type instance Col Interpret ('PGNumeric p 3) = Fixed E3
type instance Col Interpret ('PGNumeric p 6) = Fixed E6
type instance Col Interpret ('PGNumeric p 9) = Fixed E9
type instance Col Interpret 'PGBytea = ByteString
type instance Col Interpret ('PGCharacter len) = Text
type instance Col Interpret ('PGVarchar len) = Text
type instance Col Interpret 'PGJSON = Aeson.Value
type instance Col Interpret 'PGJSONB = Aeson.Value
type instance Col Interpret 'PGUUID = UUID
instance Lit 'PGBigint where
lit = Expr . Op.unColumn . Op.pgInt8
instance Lit 'PGBoolean where
lit = Expr . Op.unColumn . Op.pgBool
instance Lit 'PGInteger where
lit = Expr . Op.unColumn . Op.pgInt4 . fromIntegral
instance Lit 'PGReal where
lit = Expr . Op.unColumn . Op.pgDouble . realToFrac
instance Lit 'PGText where
lit = Expr . Op.unColumn . Op.pgStrictText
instance Lit ('PGCharacter n) where
lit = Expr . Op.unColumn . Op.pgStrictText
instance Lit ('PGVarchar n) where
lit = Expr . Op.unColumn . Op.pgStrictText
instance Lit ('PGTimestamp 'WithoutTimeZone) where
lit = Expr . Op.unColumn . Op.pgLocalTime
instance Lit ('PGTimestamp 'WithTimeZone) where
lit = Expr . Op.unColumn . Op.pgUTCTime
instance Lit 'PGDouble where
lit = Expr . Op.unColumn . Op.pgDouble
instance Lit 'PGJSON where
lit = Expr . Op.unColumn . Op.pgValueJSON
instance Lit 'PGJSONB where
lit = Expr . Op.unColumn . Op.pgValueJSON
instance Lit 'PGUUID where
lit = Expr . Op.unColumn . Op.pgUUID
pgNow :: Expr s ('PGTimestamp 'WithTimeZone)
pgNow = mapExpr Cast (lit (pack "now") :: Expr s 'PGText)
| ocharles/opaleye-tf | src/Opaleye/TF/BaseTypes.hs | bsd-3-clause | 5,425 | 0 | 9 | 1,443 | 1,332 | 765 | 567 | 124 | 1 |
module Main where
import Test.Framework (defaultMain)
import Circular.Syntax.Concrete.Tests
main = defaultMain Main.tests
tests =
[ Circular.Syntax.Concrete.Tests.tests
]
| Toxaris/circular | src/tests.hs | bsd-3-clause | 189 | 0 | 6 | 35 | 44 | 28 | 16 | 6 | 1 |
------------------------------------------------------------------------------
-- |
-- Module : Data.TokyoDystopia.IDB
-- Copyright : 8c6794b6 <[email protected]>
-- License : BSD3
-- Maintainer : 8c6794b6
-- Stability : experimental
-- Portability : non-portable
--
-- Haskell binding for tokyodystopia TCIDB interface.
--
module Database.TokyoDystopia.IDB
( -- * Type
IDB()
-- * Basic functions
, close
, copy
, del
, ecode
, fsiz
, get
, iterinit
, iternext
, new
, open
, optimize
, out
, path
, put
, rnum
, search
, search2
, setcache
, setfwmmax
, sync
, tune
, vanish
-- * Advanced functions
, setdbgfd
, getdbgfd
, memsync
, inode
, mtime
, opts
, setsynccb
, setexopts
) where
import Data.ByteString (ByteString)
import Data.Int (Int64)
import Data.Time (UTCTime)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Foreign (Ptr, maybePeek)
import Database.TokyoCabinet.Storable (Storable)
import Database.TokyoCabinet (ECODE(..))
import Database.TokyoDystopia.Internal (bitOr, toTuningOptions)
import Database.TokyoDystopia.Types
( OpenMode(..)
, GetMode(..)
, TuningOption(..) )
import qualified Data.ByteString.Char8 as C8
import qualified Foreign.C.String as CS
import qualified Database.TokyoCabinet.Error as TCE
import qualified Database.TokyoCabinet.Storable as TCS
import qualified Database.TokyoDystopia.FFI.IDB as FI
import qualified Database.TokyoDystopia.Internal as I
-- | Wrapper for TCIDB.
newtype IDB = IDB { unIDB :: Ptr FI.TCIDB }
-- | Creates new IDB.
new :: IO IDB
new = IDB `fmap` FI.c_new
-- | Open database from given path and open modes.
open :: IDB -> FilePath -> [OpenMode] -> IO Bool
open = I.mkOpen FI.c_open unIDB (FI.unOpenMode . f)
where
f OREADER = FI.omReader
f OWRITER = FI.omWriter
f OCREAT = FI.omCreat
f OTRUNC = FI.omTrunc
f ONOLCK = FI.omNolck
f OLCKNB = FI.omLcknb
-- | Closes database
close :: IDB -> IO Bool
close = FI.c_close . unIDB
-- | Put data with given key and value.
put :: (Storable k) => IDB -> k -> ByteString -> IO Bool
put db k v = C8.useAsCString v
(\str -> FI.c_put (unIDB db) (TCS.toInt64 k) str)
-- | Get data with given key.
get :: (Storable k, Storable v) => IDB -> k -> IO (Maybe v)
get db i = do
val <- FI.c_get (unIDB db) (TCS.toInt64 i)
str <- maybePeek CS.peekCString val
return $ fmap TCS.fromString str
-- | Search with GetMode options.
search :: IDB -> String -> [GetMode] -> IO [Int64]
search = I.mkSearch FI.c_search unIDB g
where
g = bitOr . map (FI.unGetMode . f)
f GMSUBSTR = FI.gmSubstr
f GMPREFIX = FI.gmPrefix
f GMSUFFIX = FI.gmSuffix
f GMFULL = FI.gmFull
f GMTOKEN = FI.gmToken
f GMTOKPRE = FI.gmTokPre
f GMTOKSUF = FI.gmTokSuf
-- | Search with given query and returns list of id keys.
search2 :: IDB -> String -> IO [Int64]
search2 = I.mkSearch2 FI.c_search2 unIDB
-- | Delete database, from memory.
del :: IDB -> IO ()
del = FI.c_del . unIDB
-- | Get the last happened error code of an indexed database object.
ecode :: IDB -> IO ECODE
ecode db = fmap TCE.cintToError (FI.c_ecode $ unIDB db)
-- | Tune the database. Must be used before opening database.
tune :: IDB -> Int64 -> Int64 -> Int64 -> [TuningOption] -> IO Bool
tune db ernum etnum iusiz os =
FI.c_tune (unIDB db) ernum etnum iusiz os'
where
os' = fromIntegral $ bitOr $ map (FI.unTuningOption . f) os
f TLARGE = FI.toLarge
f TDEFLATE = FI.toDeflate
f TBZIP = FI.toBzip
f TTCBS = FI.toTcbs
f _ = FI.TuningOption 0
-- | Set caching parameters. Must be used before opening database.
setcache :: IDB -> Int64 -> Int -> IO Bool
setcache db icsiz lcnum = FI.c_setcache (unIDB db) icsiz (fromIntegral lcnum)
-- | Set maximum number of forward matching expansion. Must be used before
-- opening database.
setfwmmax :: IDB -> Int -> IO Bool
setfwmmax db fwmmax = FI.c_setfwmmax (unIDB db) (fromIntegral fwmmax)
-- | Initialize the iterator.
iterinit :: IDB -> IO Bool
iterinit = FI.c_iterinit . unIDB
-- | Get next key for iterator
iternext :: IDB -> IO Int64
iternext = FI.c_iternext . unIDB
-- | Sync database.
sync :: IDB -> IO Bool
sync = FI.c_sync . unIDB
-- | Optimize database.
optimize :: IDB -> IO Bool
optimize = FI.c_optimize . unIDB
-- | Removes record with given key
out :: (Storable k) => IDB -> k -> IO Bool
out db key = FI.c_out (unIDB db) (TCS.toInt64 key)
-- | Delete the database from disk.
vanish :: IDB -> IO Bool
vanish = FI.c_vanish . unIDB
-- | Copy the database to given filepath.
copy :: IDB -> FilePath -> IO Bool
copy db file = FI.c_copy (unIDB db) =<< CS.newCString file
-- | Get filepath of the database
path :: IDB -> IO FilePath
path db = FI.c_path (unIDB db) >>= CS.peekCString
-- | Get number of records in database.
rnum :: IDB -> IO Int64
rnum = FI.c_rnum . unIDB
-- | Get filesize of the database.
fsiz :: IDB -> IO Int64
fsiz = FI.c_fsiz . unIDB
--
-- Advanced features
--
-- | Set file descriptor for debugging output.
setdbgfd :: IDB -> Int -> IO ()
setdbgfd db dbg = FI.c_setdbgfd (unIDB db) (fromIntegral dbg)
-- | Get file descriptor for debugging output
getdbgfd :: IDB -> IO Int
getdbgfd = fmap fromIntegral . FI.c_dbgfd . unIDB
-- | Synchronize updating contents on memory of an indexed database object
memsync :: IDB -> Int -> IO Bool
memsync db level = FI.c_memsync (unIDB db) (fromIntegral level)
-- | Get the inode number of the database dictionary of an indexed database
-- object.
inode :: IDB -> IO Int64
inode = FI.c_inode . unIDB
-- | Get the modificatoin time of the database directory of an indexed database
-- object.
mtime :: IDB -> IO UTCTime
mtime = fmap (posixSecondsToUTCTime . realToFrac) . FI.c_mtime . unIDB
-- | Get the options of an indexed database object.
opts :: IDB -> IO [TuningOption]
opts = fmap toTuningOptions . FI.c_opts . unIDB
-- | Set the callback function for sync progression.
setsynccb :: IDB -> (Int -> Int -> String -> IO Bool) -> IO Bool
setsynccb db cb = do
cb' <- FI.c_setsynccb_wrapper (\i1 i2 s -> do
s' <- CS.peekCString s
let i1' = fromIntegral i1
i2' = fromIntegral i2
cb i1' i2' s')
FI.c_setsynccb (unIDB db) cb'
-- | Set the expert options.
setexopts :: IDB -> [FI.ExpertOption] -> IO ()
setexopts db os = FI.c_setexopts (unIDB db) . fromIntegral . sum $
map FI.unExpertOption os | 8c6794b6/tokyodystopia-haskell | Database/TokyoDystopia/IDB.hs | bsd-3-clause | 6,697 | 0 | 16 | 1,636 | 1,868 | 1,012 | 856 | 146 | 7 |
{-# LANGUAGE ForeignFunctionInterface #-}
-------------------------------------------------------------------------------
-- |
-- Copyright : (c) 2015 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Sound.Csound.Debugger (
csoundDebuggerInit,
csoundDebuggerClean,
--csoundSetInstrumentBreakpoint,
--csoundRemoveInstrumentBreakpoint,
csoundClearBreakpoints,
--csoundSetBreakpointCallback,
csoundDebuggerContinue,
csoundDebugStop,
--csoundDebugGetInstrument
) where
import Control.Monad.IO.Class
import Foreign
import Foreign.Ptr
import Foreign.C.Types
foreign import ccall "csdebug.h csoundDebuggerInit" csoundDebuggerInit' :: Ptr () -> IO ()
foreign import ccall "csdebug.h csoundDebuggerClean" csoundDebuggerClean' :: Ptr () -> IO ()
--foreign import ccall "csdebug.h csoundSetInstrumentBreakpoint" csoundSetInstrumentBreakpoint'
--foreign import ccall "csdebug.h csoundRemoveInstrumentBreakpoint" csoundRemoveInstrumentBreakpoint'
foreign import ccall "csdebug.h csoundClearBreakpoints" csoundClearBreakpoints' :: Ptr () -> IO ()
--foreign import ccall "csdebug.h csoundSetBreakpointCallback" csoundSetBreakpointCallback'
foreign import ccall "csdebug.h csoundDebugContinue" csoundDebugContinue' :: Ptr () -> IO ()
foreign import ccall "csdebug.h csoundDebugStop" csoundDebugStop' :: Ptr () -> IO ()
--foreign import ccall "csdebug.h csoundDebugGetInstrument" csoundDebugGetInstrument'
csoundDebuggerInit :: MonadIO m => Ptr () -> m ()
csoundDebuggerInit csnd = liftIO (csoundDebuggerInit' csnd)
csoundDebuggerClean :: MonadIO m => Ptr () -> m ()
csoundDebuggerClean csnd = liftIO (csoundDebuggerClean' csnd)
--csoundSetInstrumentBreakpoint
--csoundSetInstrumentBreakpoint
--csoundRemoveInstrumentBreakpoint
--csoundRemoveInstrumentBreakpoint
csoundClearBreakpoints :: MonadIO m => Ptr () -> m ()
csoundClearBreakpoints csnd = liftIO (csoundClearBreakpoints' csnd)
--csoundSetBreakpointCallback
--csoundSetBreakpointCallback
csoundDebuggerContinue :: MonadIO m => Ptr () -> m ()
csoundDebuggerContinue csnd = liftIO (csoundDebuggerContinue' csnd)
csoundDebugStop :: MonadIO m => Ptr () -> m ()
csoundDebugStop csnd = liftIO (csoundDebugStop' csnd)
--csoundDebugGetInstrument
--csoundDebugGetInstrument
| oldmanmike/CsoundRaw | src/Sound/Csound/Debugger.hs | bsd-3-clause | 2,460 | 0 | 8 | 291 | 417 | 222 | 195 | 26 | 1 |
module Main ( main ) where
import Control.DeepSeq
import Control.Exception
import qualified Data.Map as Map
import qualified Data.Set as Set
import Distribution.Nixpkgs.Haskell.FromCabal.Configuration.GHC7102
import Distribution.Nixpkgs.License
import Distribution.Nixpkgs.Meta
import Internal.Lens
import Test.Hspec
main :: IO ()
main = do
hspec $ do
describe "DeepSeq instances work properly for" $ do
it "License" $ mapM_ hitsBottom [Known undefined, Unknown (Just undefined)]
it "Meta" $ do mapM_ hitsBottom
[ def & homepage .~ undefined
, def & description .~ undefined
, def & license .~ undefined
, def & platforms .~ undefined
, def & maintainers .~ undefined
, def & broken .~ undefined
]
describe "Configuration records are consistent" $
it "No maintained package is marked as \"dont-distribute\"" $
Map.keysSet (packageMaintainers ghc7102) `Set.intersection` (dontDistributePackages ghc7102) `shouldSatisfy` Set.null
hitsBottom :: NFData a => a -> Expectation
hitsBottom x = evaluate (rnf x) `shouldThrow` anyErrorCall
| psibi/cabal2nix | test/spec.hs | bsd-3-clause | 1,231 | 0 | 19 | 341 | 304 | 163 | 141 | 27 | 1 |
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.DeepSeq(module Idris.DeepSeq, module Idris.Core.DeepSeq) where
import Idris.Core.DeepSeq
import Idris.Docstrings
import Idris.Core.TT
import Idris.AbsSyntaxTree
import Control.DeepSeq
import qualified Cheapskate.Types as CT
import qualified Idris.Docstrings as D
instance NFData a => NFData (D.Docstring a) where
rnf (D.DocString opts contents) = rnf opts `seq` rnf contents `seq` ()
instance NFData CT.Options where
rnf (CT.Options x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance NFData a => NFData (D.Block a) where
rnf (D.Para lines) = rnf lines `seq` ()
rnf (D.Header i lines) = rnf i `seq` rnf lines `seq` ()
rnf (D.Blockquote bs) = rnf bs `seq` ()
rnf (D.List b t xs) = rnf b `seq` rnf t `seq` rnf xs `seq` ()
rnf (D.CodeBlock attr txt tm) = rnf attr `seq` rnf txt `seq` ()
rnf (D.HtmlBlock txt) = rnf txt `seq` ()
rnf D.HRule = ()
instance NFData a => NFData (D.Inline a) where
rnf (D.Str txt) = rnf txt `seq` ()
rnf D.Space = ()
rnf D.SoftBreak = ()
rnf D.LineBreak = ()
rnf (D.Emph xs) = rnf xs `seq` ()
rnf (D.Strong xs) = rnf xs `seq` ()
rnf (D.Code xs tm) = rnf xs `seq` rnf tm `seq` ()
rnf (D.Link a b xs) = rnf a `seq` rnf b `seq` rnf xs `seq` ()
rnf (D.Image a b c) = rnf a `seq` rnf b `seq` rnf c `seq` ()
rnf (D.Entity a) = rnf a `seq` ()
rnf (D.RawHtml x) = rnf x `seq` ()
instance NFData CT.ListType where
rnf (CT.Bullet c) = rnf c `seq` ()
rnf (CT.Numbered nw i) = rnf nw `seq` rnf i `seq` ()
instance NFData CT.CodeAttr where
rnf (CT.CodeAttr a b) = rnf a `seq` rnf b `seq` ()
instance NFData CT.NumWrapper where
rnf CT.PeriodFollowing = ()
rnf CT.ParenFollowing = ()
instance NFData DocTerm where
rnf Unchecked = ()
rnf (Checked x1) = rnf x1 `seq` ()
rnf (Example x1) = rnf x1 `seq` ()
rnf (Failing x1) = rnf x1 `seq` ()
-- All generated by 'derive'
instance NFData SizeChange where
rnf Smaller = ()
rnf Same = ()
rnf Bigger = ()
rnf Unknown = ()
instance NFData FnInfo where
rnf (FnInfo x1) = rnf x1 `seq` ()
instance NFData Codegen where
rnf (Via x1) = rnf x1 `seq` ()
rnf Bytecode = ()
instance NFData CGInfo where
rnf (CGInfo x1 x2 x3 x4 x5)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
instance NFData Fixity where
rnf (Infixl x1) = rnf x1 `seq` ()
rnf (Infixr x1) = rnf x1 `seq` ()
rnf (InfixN x1) = rnf x1 `seq` ()
rnf (PrefixN x1) = rnf x1 `seq` ()
instance NFData FixDecl where
rnf (Fix x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData Static where
rnf Static = ()
rnf Dynamic = ()
instance NFData ArgOpt where
rnf _ = ()
instance NFData Plicity where
rnf (Imp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (Exp x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (Constraint x1 x2)
= rnf x1 `seq` rnf x2 `seq` ()
rnf (TacImp x1 x2 x3)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance NFData FnOpt where
rnf Inlinable = ()
rnf TotalFn = ()
rnf PartialFn = ()
rnf CoveringFn = ()
rnf Coinductive = ()
rnf AssertTotal = ()
rnf Dictionary = ()
rnf Implicit = ()
rnf NoImplicit = ()
rnf (CExport x1) = rnf x1 `seq` ()
rnf ErrorHandler = ()
rnf ErrorReverse = ()
rnf Reflection = ()
rnf (Specialise x1) = rnf x1 `seq` ()
rnf Constructor = ()
rnf AutoHint = ()
rnf PEGenerated = ()
instance NFData DataOpt where
rnf Codata = ()
rnf DefaultEliminator = ()
rnf DefaultCaseFun = ()
rnf DataErrRev = ()
instance (NFData t) => NFData (PDecl' t) where
rnf (PFix x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PTy x1 x2 x3 x4 x5 x6 x7 x8)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
rnf (PPostulate x1 x2 x3 x4 x5 x6 x7 x8)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
rnf (PClauses x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PCAF x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PData x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PParams x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PNamespace x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PRecord x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq`
rnf x6 `seq`
rnf x7 `seq`
rnf x8 `seq`
rnf x9 `seq`
rnf x10 `seq` rnf x11 `seq` rnf x12 `seq` ()
rnf (PClass x1 x2 x3 x4 x5 x6 x8 x7 x9 x10 x11 x12)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq`
rnf x6 `seq`
rnf x7 `seq`
rnf x8 `seq`
rnf x9 `seq`
rnf x10 `seq`
rnf x11 `seq` rnf x12 `seq` ()
rnf (PInstance x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq`
rnf x6 `seq`
rnf x7 `seq`
rnf x8 `seq`
rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` ()
rnf (PDSL x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PSyntax x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PMutual x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PDirective x1) = ()
rnf (PProvider x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq` rnf x6 `seq` ()
rnf (PTransform x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
instance NFData t => NFData (ProvideWhat' t) where
rnf (ProvTerm ty tm) = rnf ty `seq` rnf tm `seq` ()
rnf (ProvPostulate tm) = rnf tm `seq` ()
instance NFData PunInfo where
rnf x = x `seq` ()
instance (NFData t) => NFData (PClause' t) where
rnf (PClause x1 x2 x3 x4 x5 x6)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` ()
rnf (PWith x1 x2 x3 x4 x5 x6 x7)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` ()
rnf (PClauseR x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PWithR x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
instance (NFData t) => NFData (PData' t) where
rnf (PDatadecl x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PLaterdecl x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance NFData PTerm where
rnf (PQuote x1) = rnf x1 `seq` ()
rnf (PRef x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PInferRef x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PPatvar x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PLam _ x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PPi x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PLet _ x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PTyped x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PAppImpl x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PApp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PAppBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PMatchApp x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PCase x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PIfThenElse x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PTrue x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PResolveTC x1) = rnf x1 `seq` ()
rnf (PRewrite x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PPair x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PDPair x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PAs x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (PAlternative x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PHidden x1) = rnf x1 `seq` ()
rnf (PType fc) = rnf fc `seq` ()
rnf (PUniverse _) = ()
rnf (PGoal x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PConstant x1 x2) = x1 `seq` x2 `seq` ()
rnf Placeholder = ()
rnf (PDoBlock x1) = rnf x1 `seq` ()
rnf (PIdiom x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PReturn x1) = rnf x1 `seq` ()
rnf (PMetavar x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PProof x1) = rnf x1 `seq` ()
rnf (PTactics x1) = rnf x1 `seq` ()
rnf (PElabError x1) = rnf x1 `seq` ()
rnf PImpossible = ()
rnf (PCoerced x1) = rnf x1 `seq` ()
rnf (PDisamb x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PUnifyLog x1) = rnf x1 `seq` ()
rnf (PNoImplicits x1) = rnf x1 `seq` ()
rnf (PQuasiquote x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PUnquote x1) = rnf x1 `seq` ()
rnf (PQuoteName x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (PRunElab x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance NFData PAltType where
rnf (ExactlyOne x1) = rnf x1 `seq` ()
rnf FirstSuccess = ()
instance (NFData t) => NFData (PTactic' t) where
rnf (Intro x1) = rnf x1 `seq` ()
rnf Intros = ()
rnf (Focus x1) = rnf x1 `seq` ()
rnf (Refine x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (Rewrite x1) = rnf x1 `seq` ()
rnf DoUnify = ()
rnf (Induction x1) = rnf x1 `seq` ()
rnf (CaseTac x1) = rnf x1 `seq` ()
rnf (Equiv x1) = rnf x1 `seq` ()
rnf (Claim x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (MatchRefine x1) = rnf x1 `seq` ()
rnf (LetTac x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (LetTacTy x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
rnf (Exact x1) = rnf x1 `seq` ()
rnf Compute = ()
rnf Trivial = ()
rnf TCInstance = ()
rnf (ProofSearch r r1 r2 x1 x2)
= rnf x1 `seq` rnf x2 `seq` ()
rnf Solve = ()
rnf Attack = ()
rnf ProofState = ()
rnf ProofTerm = ()
rnf Undo = ()
rnf (Try x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (TSeq x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (ApplyTactic x1) = rnf x1 `seq` ()
rnf (ByReflection x1) = rnf x1 `seq` ()
rnf (Reflect x1) = rnf x1 `seq` ()
rnf (Fill x1) = rnf x1 `seq` ()
rnf (GoalType x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf Qed = ()
rnf Abandon = ()
rnf (TCheck x1) = rnf x1 `seq` ()
rnf (TEval x1) = rnf x1 `seq` ()
rnf (TDocStr x1) = x1 `seq` ()
rnf (TSearch x1) = rnf x1 `seq` ()
rnf Skip = ()
rnf (TFail x1) = rnf x1 `seq` ()
rnf SourceFC = ()
rnf Unfocus = ()
instance (NFData t) => NFData (PDo' t) where
rnf (DoExp x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (DoBind x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (DoBindP x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (DoLet x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (DoLetP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance (NFData t) => NFData (PArg' t) where
rnf (PImp x1 x2 x3 x4 x5)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
rnf (PExp x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PConstraint x1 x2 x3 x4)
= rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` ()
rnf (PTacImplicit x1 x2 x3 x4 x5)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
instance NFData ClassInfo where
rnf (CI x1 x2 x3 x4 x5 x6 x7)
= rnf x1 `seq`
rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` ()
instance NFData OptInfo where
rnf (Optimise x1 x2)
= rnf x1 `seq` rnf x2 `seq` ()
instance NFData TypeInfo where
rnf (TI x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` ()
instance (NFData t) => NFData (DSL' t) where
rnf (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9 x10)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq`
rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` ()
instance NFData SynContext where
rnf PatternSyntax = ()
rnf TermSyntax = ()
rnf AnySyntax = ()
instance NFData Syntax where
rnf (Rule x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` ()
instance NFData SSymbol where
rnf (Keyword x1) = rnf x1 `seq` ()
rnf (Symbol x1) = rnf x1 `seq` ()
rnf (Binding x1) = rnf x1 `seq` ()
rnf (Expr x1) = rnf x1 `seq` ()
rnf (SimpleExpr x1) = rnf x1 `seq` ()
instance NFData Using where
rnf (UImplicit x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
rnf (UConstraint x1 x2) = rnf x1 `seq` rnf x2 `seq` ()
instance NFData SyntaxInfo where
rnf (Syn x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)
= rnf x1 `seq`
rnf x2 `seq`
rnf x3 `seq`
rnf x4 `seq`
rnf x5 `seq`
rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` rnf x10 `seq` rnf x11 `seq` rnf x12 `seq` ()
| bkoropoff/Idris-dev | src/Idris/DeepSeq.hs | bsd-3-clause | 14,948 | 0 | 18 | 5,606 | 7,609 | 4,018 | 3,591 | 343 | 0 |
module Main(main) where
import MonadPoint
--
titlePage title name =
scale 0.9 $ do
scaleh 0.65 $ do
scalehu 0.7 $ do
holstack $ mapM_ txtc $ lines title
scalehd 0.2 $ do
txtc name
tmpl title m =
page $ do
scale 0.9 $ do
scalehu 0.2 $ do
txtc title
scalehd 0.75 $ do
m
--
myPresen = pages $ do
titlePage
"Super Presentation"
"hoge"
tmpl "Introduction..." $ do
list $ do
li "I love Haskell."
li "I always use Haskell."
li "About Haskel"
ul $ do
li "functional"
li "lazy"
li "super language!"
tmpl "continue..." $ do
list $ do
li "continue..."
return ()
--
cfg = Config "./dat" "ARISAKA.ttf" "ARISAKA_fix.ttf"
main :: IO ()
main = runPresentation cfg myPresen
| tanakh/MonadPoint | test/Main.hs | bsd-3-clause | 868 | 0 | 17 | 334 | 278 | 120 | 158 | 36 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
module Fragment.Fix.Helpers (
tmFix
) where
import Control.Lens (review)
import Ast.Term
import Fragment.Fix.Ast.Term
tmFix :: AsTmFix ki ty pt tm
=> Term ki ty pt tm a
-> Term ki ty pt tm a
tmFix = review _TmFix
| dalaing/type-systems | src/Fragment/Fix/Helpers.hs | bsd-3-clause | 388 | 0 | 7 | 89 | 87 | 48 | 39 | 9 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- Module: $HEADER$
-- Description: Abstract API for DHT implementations.
-- Copyright: (c) 2015, Jan Šipr, Matej Kollár, Peter Trško
-- License: BSD3
--
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Abstract API for DHT implementations.
module Data.DHT.Core
(
-- * DHT Handle
--
-- | Specific DHT implementation should provide equivalent of
-- @open\/create\/new@. Such function returns 'DhtHandle'.
DhtHandle
-- * DHT Operations
, DhtResult
, DhtKey
, Encoding
, join
, leave
, lookup
, insert
)
where
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.Function (($), (.))
import Data.DHT.Type.Handle (DhtHandle)
import qualified Data.DHT.Type.Handle as Internal
( forDhtHandle
, hash
, insert
, join
, leave
, lookup
, withDhtHandle
)
import Data.DHT.Type.Key (DhtKey)
import Data.DHT.Type.Result (DhtResult)
import Data.DHT.Type.Encoding (Encoding)
-- | Join DHT overlay.
join :: MonadIO m => DhtHandle -> DhtResult m ()
join = liftIO . Internal.withDhtHandle Internal.join
-- | Leave DHT overlay.
leave :: MonadIO m => DhtHandle -> DhtResult m ()
leave = liftIO . Internal.withDhtHandle Internal.leave
-- | Lookup specified 'DhtKey' in DHT and provide its value as a result, if it
-- is available.
lookup :: MonadIO m => DhtHandle -> DhtKey -> DhtResult m Encoding
lookup h k = liftIO $ Internal.forDhtHandle h $ \h' s ->
Internal.lookup h' s (Internal.hash h' s k)
-- | Insert 'DhtKey' with associated value of type 'Encoding' in DHT.
insert :: MonadIO m => DhtHandle -> DhtKey -> Encoding -> DhtResult m ()
insert h k e = liftIO $ Internal.forDhtHandle h $ \h' s ->
Internal.insert h' s (Internal.hash h' s k) e
| FPBrno/dht-api | src/Data/DHT/Core.hs | bsd-3-clause | 1,861 | 0 | 10 | 401 | 409 | 239 | 170 | 36 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module ZM.Type.Float32(IEEE_754_binary32(..)) where
import Data.Model
import ZM.Type.Bits8
import ZM.Type.Bits23
import ZM.Type.Words
-- |An IEEE-754 Big Endian 32 bits Float
data IEEE_754_binary32 =
IEEE_754_binary32
{ sign :: Sign
, exponent :: MostSignificantFirst Bits8
, fraction :: MostSignificantFirst Bits23
}
deriving (Eq, Ord, Show, Generic, Model)
-- Low Endian
-- data IEEE_754_binary32_LE =
-- IEEE_754_binary32_LE
-- { fractionLE :: LeastSignificantFirst Bits23
-- , exponentLE :: LeastSignificantFirst Bits8
-- , signLE :: Sign
-- }
-- or data IEEE_754_binary32_LE = IEEE_754_binary32 Word64
| tittoassini/typed | src/ZM/Type/Float32.hs | bsd-3-clause | 811 | 0 | 9 | 228 | 106 | 68 | 38 | 13 | 0 |
module Atomo.Parser.Expr where
import Control.Arrow (first, second)
import Control.Monad.State
import Data.Maybe (fromJust, isJust)
import Text.Parsec
import qualified Control.Monad.Trans as MTL
import Atomo.Environment
import Atomo.Helpers (toPattern', toMacroPattern')
import Atomo.Parser.Base
import Atomo.Parser.Expand
import Atomo.Parser.Primitive
import Atomo.Types hiding (keyword, string)
import qualified Atomo.Types as T
-- | The types of values in Dispatch syntax.
data Dispatch
= DParticle (Particle Expr)
| DNormal Expr
deriving Show
-- | The default precedence for an operator (5).
defaultPrec :: Integer
defaultPrec = 5
-- | Parses any Atomo expression.
pExpr :: Parser Expr
pExpr = choice
[ pOperator
, pMacro
, pForMacro
, try pDispatch
, pLiteral
, parens pExpr
]
<?> "expression"
-- | Parses any Atomo literal value.
pLiteral :: Parser Expr
pLiteral = choice
[ pThis
, pBlock
, pList
, pParticle
, pQuoted
, pQuasiQuoted
, pUnquoted
, pPrimitive
]
<?> "literal"
-- | Parses a primitive value.
--
-- Examples: @1@, @2.0@, @3\/4@, @$d@, @\"foo\"@, @True@, @False@
pPrimitive :: Parser Expr
pPrimitive = tagged $ liftM (Primitive Nothing) pPrim
-- | The @this@ keyword, i.e. the toplevel object literal.
pThis :: Parser Expr
pThis = tagged $ reserved "this" >> return (ETop Nothing)
-- | An expression literal.
--
-- Example: @'1@, @'(2 + 2)@
pQuoted :: Parser Expr
pQuoted = tagged $ do
char '\''
e <- pSpacedExpr
return (Primitive Nothing (Expression e))
-- | An expression literal that may contain "unquotes" - expressions to splice
-- in to yield a different expression.
--
-- Examples: @`a@, @`(1 + ~(2 + 2))@
pQuasiQuoted :: Parser Expr
pQuasiQuoted = tagged $ do
char '`'
modifyState $ \ps -> ps { psInQuote = True }
e <- pSpacedExpr
modifyState $ \ps -> ps { psInQuote = False }
return (EQuote Nothing e)
-- | An unquote expression, used inside a quasiquote.
--
-- Examples: @~1@, @~(2 + 2)@
pUnquoted :: Parser Expr
pUnquoted = tagged $ do
char '~'
iq <- fmap psInQuote getState
modifyState $ \ps -> ps { psInQuote = False }
e <- pSpacedExpr
modifyState $ \ps -> ps { psInQuote = iq }
return (EUnquote Nothing e)
-- | Any expression that fits into one lexical "space" - either a simple
-- literal value, a single dispatch to the toplevel object, or an expression in
-- parentheses.
--
-- Examples: @1@, @[1, 2]@, @a@, @(2 + 2)@
pSpacedExpr :: Parser Expr
pSpacedExpr = pLiteral <|> simpleDispatch <|> parens pExpr
where
simpleDispatch = tagged $ do
name <- ident
notFollowedBy (char ':')
spacing
return (Dispatch Nothing (single name (ETop Nothing)))
-- | The for-macro "pragma."
--
-- Example: @for-macro 1 print@
pForMacro :: Parser Expr
pForMacro = tagged (do
reserved "for-macro"
whiteSpace
e <- pExpr
return (EForMacro Nothing e))
<?> "for-macro expression"
-- | A macro definition.
--
-- Example: @macro (n squared) `(~n * ~n)@
pMacro :: Parser Expr
pMacro = tagged (do
reserved "macro"
whiteSpace
p <- parens (pExpr >>= MTL.lift . toMacroPattern')
whiteSpace
e <- pExpr
return (EMacro Nothing p e))
<?> "macro definition"
-- | An operator "pragma" - tells the parser about precedence and associativity
-- for the given operator(s).
--
-- Examples: @operator right 0 ->@, @operator 7 * /@
pOperator :: Parser Expr
pOperator = tagged (do
reserved "operator"
whiteSpace
info <- choice
[ do
a <- choice
[ symbol "right" >> return ARight
, symbol "left" >> return ALeft
]
prec <- option defaultPrec (try integer)
return (a, prec)
, liftM ((,) ALeft) integer
]
ops <- operator `sepBy1` spacing
forM_ ops $ \name ->
modifyState $ \ps -> ps
{ psOperators =
(name, info) : psOperators ps
}
return (uncurry (Operator Nothing ops) info))
<?> "operator pragma"
-- | A particle literal.
--
-- Examples: @\@foo@, @\@(bar: 2)@, @\@bar:@, @\@(foo: 2 bar: _)@
pParticle :: Parser Expr
pParticle = tagged (do
char '@'
c <- choice
[ cKeyword True
, binary
, try (cSingle True)
, symbols
]
return (EParticle Nothing c))
<?> "particle"
where
binary = do
op <- operator
return $ PMKeyword [op] [Nothing, Nothing]
symbols = do
names <- many1 (anyIdent >>= \n -> char ':' >> return n)
spacing
return $ PMKeyword names (replicate (length names + 1) Nothing)
-- | Any dispatch, both single and keyword.
pDispatch :: Parser Expr
pDispatch = try pdKeys <|> pdChain
<?> "dispatch"
-- | A keyword dispatch.
--
-- Examples: @1 foo: 2@, @1 + 2@
pdKeys :: Parser Expr
pdKeys = do
pos <- getPosition
msg <- keywords T.keyword (ETop (Just pos)) (try pdChain <|> headless)
ops <- liftM psOperators getState
return $ Dispatch (Just pos) (toBinaryOps ops msg)
<?> "keyword dispatch"
where
headless = do
p <- getPosition
msg <- ckeywd p
ops <- liftM psOperators getState
return (Dispatch (Just p) (toBinaryOps ops msg))
ckeywd pos = do
ks <- wsMany1 $ keyword pdChain
let (ns, es) = unzip ks
return $ T.keyword ns (ETop (Just pos):es)
<?> "keyword segment"
-- | A chain of message sends, both single and chained keywords.
--
-- Example: @1 sqrt (* 2) floor@
pdChain :: Parser Expr
pdChain = do
pos <- getPosition
chain <- wsManyStart
(liftM DNormal (try pLiteral <|> pThis <|> parens pExpr) <|> chained)
chained
return $ dispatches pos chain
<?> "single dispatch"
where
chained = liftM DParticle $ choice
[ cKeyword False
, cSingle False
]
-- start off by dispatching on either a primitive or Top
dispatches :: SourcePos -> [Dispatch] -> Expr
dispatches p (DNormal e:ps) =
dispatches' p ps e
dispatches p (DParticle (PMSingle n):ps) =
dispatches' p ps (Dispatch (Just p) $ single n (ETop (Just p)))
dispatches p (DParticle (PMKeyword ns (Nothing:es)):ps) =
dispatches' p ps (Dispatch (Just p) $ T.keyword ns (ETop (Just p):map fromJust es))
dispatches _ ds = error $ "impossible: dispatches on " ++ show ds
-- roll a list of partial messages into a bunch of dispatches
dispatches' :: SourcePos -> [Dispatch] -> Expr -> Expr
dispatches' _ [] acc = acc
dispatches' p (DParticle (PMKeyword ns (Nothing:es)):ps) acc =
dispatches' p ps (Dispatch (Just p) $ T.keyword ns (acc : map fromJust es))
dispatches' p (DParticle (PMSingle n):ps) acc =
dispatches' p ps (Dispatch (Just p) $ single n acc)
dispatches' _ x y = error $ "impossible: dispatches' on " ++ show (x, y)
-- | A comma-separated list of zero or more expressions, surrounded by square
-- brackets.
--
-- Examples: @[]@, @[1, $a]@
pList :: Parser Expr
pList = (tagged . liftM (EList Nothing) $ brackets (wsDelim "," pExpr))
<?> "list"
-- | A block of expressions, surrounded by braces and optionally having
-- arguments.
--
-- Examples: @{ }@, @{ a b | a + b }@, @{ a = 1; a + 1 }@
pBlock :: Parser Expr
pBlock = tagged (braces $ do
arguments <- option [] . try $ do
ps <- many1 pSpacedExpr
whiteSpace
string "|"
whiteSpace1
mapM (MTL.lift . toPattern') ps
code <- wsBlock pExpr
return $ EBlock Nothing arguments code)
<?> "block"
-- | A general "single dispatch" form, without a target.
--
-- Used for both chaines and particles.
cSingle :: Bool -> Parser (Particle Expr)
cSingle p = do
n <- if p then anyIdent else ident
notFollowedBy colon
spacing
return (PMSingle n)
<?> "single segment"
-- | A general "keyword dispatch" form, without a head.
--
-- Used for both chaines and particles.
cKeyword :: Bool -> Parser (Particle Expr)
cKeyword wc = do
ks <- parens $ many1 keyword'
let (ns, mvs) = second (Nothing:) $ unzip ks
if any isOperator (tail ns)
then toDispatch ns mvs
else return $ PMKeyword ns mvs
<?> "keyword segment"
where
keywordVal
| wc = wildcard <|> value
| otherwise = value
keywordDispatch
| wc = wildcard <|> disp
| otherwise = disp
value = liftM Just pdChain
disp = liftM Just pDispatch
keyword' = do
name <- try (do
name <- ident
char ':'
return name) <|> operator
whiteSpace1
target <-
if isOperator name
then keywordDispatch
else keywordVal
return (name, target)
wildcard = symbol "_" >> return Nothing
toDispatch [] mvs = error $ "impossible: toDispatch on [] and " ++ show mvs
toDispatch (n:ns) mvs
| all isJust opVals = do
os <- getState
pos <- getPosition
let msg = toBinaryOps (psOperators os) $ T.keyword opers (map fromJust opVals)
return . PMKeyword nonOpers $
partVals ++ [Just $ Dispatch (Just pos) msg]
| otherwise = fail "invalid particle; toplevel operator with wildcards as values"
where
(nonOpers, opers) = first (n:) $ break isOperator ns
(partVals, opVals) = splitAt (length nonOpers) mvs
-- | Work out precadence, associativity, etc. for a keyword dispatch.
--
-- The input is a keyword EMessage with a mix of operators and identifiers as
-- its name, e.g. @keyword { emNames = ["+", "*", "remainder"] }@.
toBinaryOps :: Operators -> Message Expr -> Message Expr
toBinaryOps _ done@(Keyword _ [_] [_, _]) = done
toBinaryOps ops (Keyword h (n:ns) (v:vs))
| nextFirst =
T.keyword [n]
[ v
, Dispatch (eLocation v)
(toBinaryOps ops (T.keyword ns vs))
]
| isOperator n =
toBinaryOps ops . T.keyword ns $
(Dispatch (eLocation v) (T.keyword [n] [v, head vs]):tail vs)
| nonOperators == ns = Keyword h (n:ns) (v:vs)
| null nonOperators && length vs > 2 =
T.keyword [head ns]
[ Dispatch (eLocation v) $
T.keyword [n] [v, head vs]
, Dispatch (eLocation v) $
toBinaryOps ops (T.keyword (tail ns) (tail vs))
]
| otherwise =
toBinaryOps ops . T.keyword (drop numNonOps ns) $
(Dispatch (eLocation v) $
T.keyword (n : nonOperators)
(v : take (numNonOps + 1) vs)) :
drop (numNonOps + 1) vs
where
numNonOps = length nonOperators
nonOperators = takeWhile (not . isOperator) ns
nextFirst =
isOperator n && or
[ null ns
, prec next > prec n
, assoc n == ARight && prec next == prec n
]
where next = head ns
assoc n' =
case lookup n' ops of
Nothing -> ALeft
Just (a, _) -> a
prec n' =
case lookup n' ops of
Nothing -> defaultPrec
Just (_, p) -> p
toBinaryOps _ u = error $ "cannot toBinaryOps: " ++ show u
-- | Parse a block of expressions from a given input string.
parser :: Parser [Expr]
parser = do
whiteSpace
es <- wsBlock pExpr
whiteSpace
eof
return es
-- | Same as `parser', but ignores a shebang at the start of the source.
fileParser :: Parser [Expr]
fileParser = do
optional (string "#!" >> manyTill anyToken (eol <|> eof))
parser
| Mathnerd314/atomo | src/Atomo/Parser/Expr.hs | bsd-3-clause | 11,644 | 0 | 19 | 3,375 | 3,409 | 1,704 | 1,705 | 280 | 7 |
-- | Mutually recursive types.
module Data.Aeson.Validation.Internal.Types where
import Data.Aeson.Validation.Internal.Prelude
import Data.List.NonEmpty ((<|))
import qualified GHC.Exts as GHC
-- $setup
-- >>> import Data.Aeson.Validation.Internal.Schema
data Demand
= Opt
| Req
deriving Eq
instance Hashable Demand where
hash Opt = 0
hash Req = 1
-- Stolen from @hashable@
hashWithSalt s x = s * 16777619 `xor` hash x
-- | An opaque object 'Field'.
--
-- Create a 'Field' with '.:' or '.:?', and bundle it into a 'Schema' using
-- 'object' or 'object''
data Field
= Field !Demand !(NonEmpty Text) !Schema
-- | An opaque JSON 'Schema'.
data Schema
= SBool
| STrue
| SFalse
| SNumber
| SInteger
| STheNumber !Scientific
| STheInteger !Integer
| SSomeNumber !Text {- error msg -} (Scientific -> Bool) {- predicate -}
| SString
| STheString !Text
| SSomeString !Text {- error msg -} (Text -> Bool) {- predicate -}
| SDateTime
| SObject !Strict ![ShallowField]
| SArray !Unique !Int {- min len -} !Int {- max len -} !Schema
| STuple ![Schema]
| SAnything
| SNullable !Schema
| SAlts !(NonEmpty Schema)
| SNegate !Schema
-- | The 'Num' instance only defines two functions; all other 'Num' functions
-- call 'error'.
--
-- (1) 'fromInteger' is provided for integer-literal syntax.
--
-- @
-- 'fromInteger' = 'theInteger'
-- @
--
-- Examples:
--
-- >>> validate 1 (Number 1)
-- []
--
-- (2) @'negate' s@ succeeds whenever @s@ fails.
--
-- 'negate' is its own inverse:
--
-- @
-- 'negate' . 'negate' = 'id'
-- @
--
-- Examples:
--
-- >>> validate (negate bool) (String "foo")
-- []
--
-- >>> validate (negate bool) (Bool True)
-- ["expected anything but a bool but found true"]
instance Num Schema where
(+) = error "Data.Aeson.Validation: (+) not implemented for Schema"
(-) = error "Data.Aeson.Validation: (-) not implemented for Schema"
(*) = error "Data.Aeson.Validation: (*) not implemented for Schema"
abs = error "Data.Aeson.Validation: abs not implemented for Schema"
signum = error "Data.Aeson.Validation: signum not implemented for Schema"
fromInteger = STheInteger
negate = SNegate
-- | The 'Fractional' instance only defines one function; all other 'Fractional'
-- functions call 'error'.
--
-- (1) 'fromRational' is provided for floating point-literal syntax.
--
-- @
-- 'fromRational' = 'theNumber' . 'fromRational'
-- @
--
-- Examples:
--
-- >>> validate 1.5 (Number 1.5)
-- []
--
-- >>> validate 2.5 (Number 2.500000001)
-- []
instance Fractional Schema where
(/) = error "Data.Aeson.Validation: (/) not implemented for Schema"
recip = error "Data.Aeson.Validation: recip not implemented for Schema"
fromRational = STheNumber . fromRational
-- | The '<>' operator is used to create a /sum/ 'Schema' that, when applied to
-- a 'Value', first tries the left 'Schema', then falls back on the right one if
-- the left one fails.
--
-- For 'validate', if any 'Schema's emits no violations, then no violations are
-- emitted. Otherwise, all violations are emitted.
--
-- Examples:
--
-- >>> validate (bool <> string) (Bool True)
-- []
--
-- >>> validate (bool <> string) (String "foo")
-- []
--
-- >>> validate (bool <> string) (Number 1)
-- ["expected a bool but found a number","expected a string but found a number"]
instance Semigroup Schema where
SAlts xs <> SAlts ys = SAlts (xs <> ys)
SAlts (x:|xs) <> y = SAlts (x :| xs ++ [y]) -- Won't happen naturally (infixr)
x <> SAlts ys = SAlts (x <| ys)
x <> y = SAlts (x :| [y])
-- | 'GHC.fromString' is provided for string-literal syntax.
--
-- @
-- 'GHC.fromString' = 'theString' . 'Data.Text.pack'
-- @
--
-- Examples:
--
-- >>> validate "foo" (String "foo")
-- []
instance GHC.IsString Schema where
fromString = STheString . GHC.fromString
data ShallowField
= ShallowField
{ fieldDemand :: !Demand
, fieldKey :: !Text
, fieldSchema :: !Schema
}
-- Are extra properties of an object allowed?
data Strict
= Strict
| NotStrict
-- Are duplicate elements in an array allowed?
data Unique
= Unique
| NotUnique
deriving Eq
| mitchellwrosen/json-validation | src/internal/Data/Aeson/Validation/Internal/Types.hs | bsd-3-clause | 4,349 | 0 | 9 | 1,042 | 640 | 387 | 253 | 107 | 0 |
module AddressUtils
( adjustAddr
, adjustAmount
, IsBitcoinAddress
) where
import qualified Data.Text as T
import qualified Network.BitcoinRPC as RPC
import qualified Network.MtGoxAPI as MtGox
class IsBitcoinAddress a where
addrToText :: a -> T.Text
textToAddr :: T.Text -> a
instance IsBitcoinAddress RPC.BitcoinAddress
where
addrToText = RPC.btcAddress
textToAddr = RPC.BitcoinAddress
instance IsBitcoinAddress MtGox.BitcoinAddress
where
addrToText = MtGox.baAddress
textToAddr = MtGox.BitcoinAddress
instance IsBitcoinAddress MtGox.BitcoinDepositAddress
where
addrToText = addrToText . MtGox.bdaAddr
textToAddr = MtGox.BitcoinDepositAddress . textToAddr
instance IsBitcoinAddress T.Text
where
addrToText = id
textToAddr = id
class IsBitcoinAmount a where
amountToInteger :: a -> Integer
integerToAmount :: Integer -> a
instance IsBitcoinAmount Integer
where
amountToInteger = id
integerToAmount = id
instance IsBitcoinAmount RPC.BitcoinAmount
where
amountToInteger = RPC.btcAmount
integerToAmount = RPC.BitcoinAmount
adjustAddr :: (IsBitcoinAddress a, IsBitcoinAddress b) => a -> b
adjustAddr = textToAddr . addrToText
adjustAmount :: (IsBitcoinAmount a, IsBitcoinAmount b) => a -> b
adjustAmount = integerToAmount . amountToInteger
| javgh/bridgewalker | src/AddressUtils.hs | bsd-3-clause | 1,340 | 0 | 8 | 251 | 305 | 171 | 134 | 35 | 1 |
{-# LANGUAGE CPP #-}
-- This module deliberately defines orphan instances for now (Binary Version).
{-# OPTIONS_GHC -fno-warn-orphans -fno-warn-name-shadowing #-}
-----------------------------------------------------------------------------
-- |
-- Module : ETA.PackageDb
-- Copyright : (c) The University of Glasgow 2009, Duncan Coutts 2014
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides the view of GHC's database of registered packages that
-- is shared between GHC the compiler\/library, and the ghc-pkg program. It
-- defines the database format that is shared between GHC and ghc-pkg.
--
-- The database format, and this library are constructed so that GHC does not
-- have to depend on the Cabal library. The ghc-pkg program acts as the
-- gateway between the external package format (which is defined by Cabal) and
-- the internal package format which is specialised just for GHC.
--
-- GHC the compiler only needs some of the information which is kept about
-- registerd packages, such as module names, various paths etc. On the other
-- hand ghc-pkg has to keep all the information from Cabal packages and be able
-- to regurgitate it for users and other tools.
--
-- The first trick is that we duplicate some of the information in the package
-- database. We essentially keep two versions of the datbase in one file, one
-- version used only by ghc-pkg which keeps the full information (using the
-- serialised form of the 'InstalledPackageInfo' type defined by the Cabal
-- library); and a second version written by ghc-pkg and read by GHC which has
-- just the subset of information that GHC needs.
--
-- The second trick is that this module only defines in detail the format of
-- the second version -- the bit GHC uses -- and the part managed by ghc-pkg
-- is kept in the file but here we treat it as an opaque blob of data. That way
-- this library avoids depending on Cabal.
--
module ETA.PackageDb (
InstalledPackageInfo(..),
ExposedModule(..),
OriginalModule(..),
BinaryStringRep(..),
emptyInstalledPackageInfo,
readPackageDbForGhc,
readPackageDbForGhcPkg,
writePackageDb
) where
import Data.Version (Version(..))
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS.Char8
import qualified Data.ByteString.Lazy as BS.Lazy
import qualified Data.ByteString.Lazy.Internal as BS.Lazy (defaultChunkSize)
import Data.Binary as Bin
import Data.Binary.Put as Bin
import Data.Binary.Get as Bin
import Control.Exception as Exception
import Control.Monad (when)
import System.FilePath
import System.IO
import System.IO.Error
import GHC.IO.Exception (IOErrorType(InappropriateType))
import System.Directory
-- | This is a subset of Cabal's 'InstalledPackageInfo', with just the bits
-- that GHC is interested in.
--
data InstalledPackageInfo instpkgid srcpkgid srcpkgname pkgkey modulename
= InstalledPackageInfo {
installedPackageId :: instpkgid,
sourcePackageId :: srcpkgid,
packageName :: srcpkgname,
packageVersion :: Version,
packageKey :: pkgkey,
depends :: [instpkgid],
importDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries :: [String],
libraryDirs :: [FilePath],
frameworks :: [String],
frameworkDirs :: [FilePath],
ldOptions :: [String],
ccOptions :: [String],
includes :: [String],
includeDirs :: [FilePath],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath],
exposedModules :: [ExposedModule instpkgid modulename],
hiddenModules :: [modulename],
instantiatedWith :: [(modulename,OriginalModule instpkgid modulename)],
exposed :: Bool,
trusted :: Bool
}
deriving (Eq, Show)
-- | An original module is a fully-qualified module name (installed package ID
-- plus module name) representing where a module was *originally* defined
-- (i.e., the 'exposedReexport' field of the original ExposedModule entry should
-- be 'Nothing'). Invariant: an OriginalModule never points to a reexport.
data OriginalModule instpkgid modulename
= OriginalModule {
originalPackageId :: instpkgid,
originalModuleName :: modulename
}
deriving (Eq, Show)
-- | Represents a module name which is exported by a package, stored in the
-- 'exposedModules' field. A module export may be a reexport (in which
-- case 'exposedReexport' is filled in with the original source of the module),
-- and may be a signature (in which case 'exposedSignature is filled in with
-- what the signature was compiled against). Thus:
--
-- * @ExposedModule n Nothing Nothing@ represents an exposed module @n@ which
-- was defined in this package.
--
-- * @ExposedModule n (Just o) Nothing@ represents a reexported module @n@
-- which was originally defined in @o@.
--
-- * @ExposedModule n Nothing (Just s)@ represents an exposed signature @n@
-- which was compiled against the implementation @s@.
--
-- * @ExposedModule n (Just o) (Just s)@ represents a reexported signature
-- which was originally defined in @o@ and was compiled against the
-- implementation @s@.
--
-- We use two 'Maybe' data types instead of an ADT with four branches or
-- four fields because this representation allows us to treat
-- reexports/signatures uniformly.
data ExposedModule instpkgid modulename
= ExposedModule {
exposedName :: modulename,
exposedReexport :: Maybe (OriginalModule instpkgid modulename),
exposedSignature :: Maybe (OriginalModule instpkgid modulename)
}
deriving (Eq, Show)
class BinaryStringRep a where
fromStringRep :: BS.ByteString -> a
toStringRep :: a -> BS.ByteString
emptyInstalledPackageInfo :: (BinaryStringRep a, BinaryStringRep b,
BinaryStringRep c, BinaryStringRep d)
=> InstalledPackageInfo a b c d e
emptyInstalledPackageInfo =
InstalledPackageInfo {
installedPackageId = fromStringRep BS.empty,
sourcePackageId = fromStringRep BS.empty,
packageName = fromStringRep BS.empty,
packageVersion = Version [] [],
packageKey = fromStringRep BS.empty,
depends = [],
importDirs = [],
hsLibraries = [],
extraLibraries = [],
extraGHCiLibraries = [],
libraryDirs = [],
frameworks = [],
frameworkDirs = [],
ldOptions = [],
ccOptions = [],
includes = [],
includeDirs = [],
haddockInterfaces = [],
haddockHTMLs = [],
exposedModules = [],
hiddenModules = [],
instantiatedWith = [],
exposed = False,
trusted = False
}
-- | Read the part of the package DB that GHC is interested in.
--
readPackageDbForGhc :: (BinaryStringRep a, BinaryStringRep b, BinaryStringRep c,
BinaryStringRep d, BinaryStringRep e) =>
FilePath -> IO [InstalledPackageInfo a b c d e]
readPackageDbForGhc file =
decodeFromFile file getDbForGhc
where
getDbForGhc = do
_version <- getHeader
_ghcPartLen <- get :: Get Word32
ghcPart <- get
-- the next part is for ghc-pkg, but we stop here.
return ghcPart
-- | Read the part of the package DB that ghc-pkg is interested in
--
-- Note that the Binary instance for ghc-pkg's representation of packages
-- is not defined in this package. This is because ghc-pkg uses Cabal types
-- (and Binary instances for these) which this package does not depend on.
--
readPackageDbForGhcPkg :: Binary pkgs => FilePath -> IO pkgs
readPackageDbForGhcPkg file =
decodeFromFile file getDbForGhcPkg
where
getDbForGhcPkg = do
_version <- getHeader
-- skip over the ghc part
ghcPartLen <- get :: Get Word32
_ghcPart <- skip (fromIntegral ghcPartLen)
-- the next part is for ghc-pkg
ghcPkgPart <- get
return ghcPkgPart
-- | Write the whole of the package DB, both parts.
--
writePackageDb :: (Binary pkgs, BinaryStringRep a, BinaryStringRep b,
BinaryStringRep c, BinaryStringRep d, BinaryStringRep e) =>
FilePath -> [InstalledPackageInfo a b c d e] -> pkgs -> IO ()
writePackageDb file ghcPkgs ghcPkgPart =
writeFileAtomic file (runPut putDbForGhcPkg)
where
putDbForGhcPkg = do
putHeader
put ghcPartLen
putLazyByteString ghcPart
put ghcPkgPart
where
ghcPartLen :: Word32
ghcPartLen = fromIntegral (BS.Lazy.length ghcPart)
ghcPart = encode ghcPkgs
getHeader :: Get (Word32, Word32)
getHeader = do
magic <- getByteString (BS.length headerMagic)
when (magic /= headerMagic) $
fail "not a ghc-pkg db file, wrong file magic number"
majorVersion <- get :: Get Word32
-- The major version is for incompatible changes
minorVersion <- get :: Get Word32
-- The minor version is for compatible extensions
when (majorVersion /= 1) $
fail "unsupported ghc-pkg db format version"
-- If we ever support multiple major versions then we'll have to change
-- this code
-- The header can be extended without incrementing the major version,
-- we ignore fields we don't know about (currently all).
headerExtraLen <- get :: Get Word32
skip (fromIntegral headerExtraLen)
return (majorVersion, minorVersion)
putHeader :: Put
putHeader = do
putByteString headerMagic
put majorVersion
put minorVersion
put headerExtraLen
where
majorVersion = 1 :: Word32
minorVersion = 0 :: Word32
headerExtraLen = 0 :: Word32
headerMagic :: BS.ByteString
headerMagic = BS.Char8.pack "\0ghcpkg\0"
-- TODO: we may be able to replace the following with utils from the binary
-- package in future.
-- | Feed a 'Get' decoder with data chunks from a file.
--
decodeFromFile :: FilePath -> Get a -> IO a
decodeFromFile file decoder =
withBinaryFile file ReadMode $ \hnd ->
feed hnd (runGetIncremental decoder)
where
feed hnd (Partial k) = do chunk <- BS.hGet hnd BS.Lazy.defaultChunkSize
if BS.null chunk
then feed hnd (k Nothing)
else feed hnd (k (Just chunk))
feed _ (Done _ _ res) = return res
feed _ (Fail _ _ msg) = ioError err
where
err = mkIOError InappropriateType loc Nothing (Just file)
`ioeSetErrorString` msg
loc = "ETA.PackageDb.readPackageDb"
writeFileAtomic :: FilePath -> BS.Lazy.ByteString -> IO ()
writeFileAtomic targetPath content = do
let (targetDir, targetName) = splitFileName targetPath
Exception.bracketOnError
(openBinaryTempFileWithDefaultPermissions targetDir $ targetName <.> "tmp")
(\(tmpPath, hnd) -> hClose hnd >> removeFile tmpPath)
(\(tmpPath, hnd) -> do
BS.Lazy.hPut hnd content
hClose hnd
#if mingw32_HOST_OS || mingw32_TARGET_OS
renameFile tmpPath targetPath
-- If the targetPath exists then renameFile will fail
`catch` \err -> do
exists <- doesFileExist targetPath
if exists
then do removeFile targetPath
-- Big fat hairy race condition
renameFile tmpPath targetPath
-- If the removeFile succeeds and the renameFile fails
-- then we've lost the atomic property.
else throwIO (err :: IOException)
#else
renameFile tmpPath targetPath
#endif
)
instance (BinaryStringRep a, BinaryStringRep b, BinaryStringRep c,
BinaryStringRep d, BinaryStringRep e) =>
Binary (InstalledPackageInfo a b c d e) where
put (InstalledPackageInfo
installedPackageId sourcePackageId
packageName packageVersion packageKey
depends importDirs
hsLibraries extraLibraries extraGHCiLibraries libraryDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
exposedModules hiddenModules instantiatedWith
exposed trusted) = do
put (toStringRep installedPackageId)
put (toStringRep sourcePackageId)
put (toStringRep packageName)
put packageVersion
put (toStringRep packageKey)
put (map toStringRep depends)
put importDirs
put hsLibraries
put extraLibraries
put extraGHCiLibraries
put libraryDirs
put frameworks
put frameworkDirs
put ldOptions
put ccOptions
put includes
put includeDirs
put haddockInterfaces
put haddockHTMLs
put exposedModules
put (map toStringRep hiddenModules)
put (map (\(k,v) -> (toStringRep k, v)) instantiatedWith)
put exposed
put trusted
get = do
installedPackageId <- get
sourcePackageId <- get
packageName <- get
packageVersion <- get
packageKey <- get
depends <- get
importDirs <- get
hsLibraries <- get
extraLibraries <- get
extraGHCiLibraries <- get
libraryDirs <- get
frameworks <- get
frameworkDirs <- get
ldOptions <- get
ccOptions <- get
includes <- get
includeDirs <- get
haddockInterfaces <- get
haddockHTMLs <- get
exposedModules <- get
hiddenModules <- get
instantiatedWith <- get
exposed <- get
trusted <- get
return (InstalledPackageInfo
(fromStringRep installedPackageId)
(fromStringRep sourcePackageId)
(fromStringRep packageName) packageVersion
(fromStringRep packageKey)
(map fromStringRep depends)
importDirs
hsLibraries extraLibraries extraGHCiLibraries libraryDirs
frameworks frameworkDirs
ldOptions ccOptions
includes includeDirs
haddockInterfaces haddockHTMLs
exposedModules
(map fromStringRep hiddenModules)
(map (\(k,v) -> (fromStringRep k, v)) instantiatedWith)
exposed trusted)
instance Binary Version where
put (Version a b) = do
put a
put b
get = do
a <- get
b <- get
return (Version a b)
instance (BinaryStringRep a, BinaryStringRep b) =>
Binary (OriginalModule a b) where
put (OriginalModule originalPackageId originalModuleName) = do
put (toStringRep originalPackageId)
put (toStringRep originalModuleName)
get = do
originalPackageId <- get
originalModuleName <- get
return (OriginalModule (fromStringRep originalPackageId)
(fromStringRep originalModuleName))
instance (BinaryStringRep a, BinaryStringRep b) =>
Binary (ExposedModule a b) where
put (ExposedModule exposedName exposedReexport exposedSignature) = do
put (toStringRep exposedName)
put exposedReexport
put exposedSignature
get = do
exposedName <- get
exposedReexport <- get
exposedSignature <- get
return (ExposedModule (fromStringRep exposedName)
exposedReexport
exposedSignature)
| alexander-at-github/eta | utils/eta-pkgdb/ETA/PackageDb.hs | bsd-3-clause | 15,693 | 0 | 19 | 4,345 | 2,821 | 1,504 | 1,317 | 284 | 4 |
{-# OPTIONS_GHC -Wall #-}
module Atmosphere.Atmosphere( siAtmosphere
, usAtmosphere
) where
-- 1976 US Standard Atmosphere
-- Adapted by
-- Greg Horn
-- Adapted by
-- Richard J. Kwan, Lightsaber Computing
-- from original programs by
-- Ralph L. Carmichael, Public Domain Aeronautical Software
--
-- Revision History
-- Date Vers Person Statement of Changes
-- 2004 Oct 04 1.0 RJK Initial program
-- P H Y S I C A L C O N S T A N T S
_FT2METERS :: (Ord a, Floating a) => a
_KELVIN2RANKINE :: (Ord a, Floating a) => a
_PSF2NSM :: (Ord a, Floating a) => a
_SCF2KCM :: (Ord a, Floating a) => a
_TZERO :: (Ord a, Floating a) => a
_PZERO :: (Ord a, Floating a) => a
_RHOZERO :: (Ord a, Floating a) => a
_AZERO :: (Ord a, Floating a) => a
_BETAVISC :: (Ord a, Floating a) => a
_SUTH :: (Ord a, Floating a) => a
_FT2METERS = 0.3048 -- mult. ft. to get meters (exact)
_KELVIN2RANKINE = 1.8 -- mult deg K to get deg R
_PSF2NSM = 47.880258 -- mult lb/sq.ft to get sq.m
_SCF2KCM = 515.379 -- mult slugs/cu.ft to get kg/cu.m
_TZERO = 288.15 -- sea-level temperature, kelvins
_PZERO = 101325.0 -- sea-level pressure, N/sq.m
_RHOZERO = 1.225 -- sea-level density, kg/cu.m
_AZERO = 340.294 -- speed of sound at S.L. m/sec
_BETAVISC = 1.458E-6 -- viscosity constant
_SUTH = 110.4 -- Sutherland's constant, kelvins
{-
input:
altitude in ft
outputs:
temperature in Rankine
pressure in lb/ft^2
density in slugs/ft^3
speed of sound in ft/sec
viscosity in slugs/(ft-sec)
kinematic viscosity in ft^2/s
-}
usAtmosphere :: (Floating a, Ord a) => a -> (a,a,a,a,a,a)
usAtmosphere alt_ft = (temp, pressure, density, asound, viscosity, kinematicViscosity)
where
alt_km = _FT2METERS*0.001*alt_ft
(sigma, delta, theta) = simpleAtmosphere alt_km
temp = _KELVIN2RANKINE*_TZERO*theta
pressure = _PZERO*delta/47.88
density = _RHOZERO*sigma/515.379
asound = (_AZERO/_FT2METERS)*sqrt(theta)
viscosity=(1.0/_PSF2NSM)*metricViscosity(theta)
kinematicViscosity = viscosity/density
siAtmosphere :: (Floating a, Ord a) => a -> (a,a,a,a,a,a)
siAtmosphere alt_m = (temp, pressure, density, asound, viscosity, kinematicViscosity)
where
alt_km = 0.001*alt_m
(sigma, delta, theta) = simpleAtmosphere alt_km
temp = _TZERO * theta
pressure = _PZERO * delta
density = _RHOZERO * sigma
asound = _AZERO * sqrt(theta)
viscosity = metricViscosity theta
kinematicViscosity = viscosity/density
simpleAtmosphere :: (Floating a, Ord a) => a -> (a,a,a)
simpleAtmosphere alt = (sigma, delta, theta)
where
{- Compute temperature, density, and pressure in simplified
standard atmosphere.
Correct to 20 km. Only approximate thereafter.
Input:
alt geometric altitude, km.
Return: (sigma, delta, theta)
sigma density/sea-level standard density
delta pressure/sea-level standard pressure
theta temperature/sea-level std. temperature
-}
_REARTH = 6369.0 -- radius of the Earth (km)
_GMR = 34.163195 -- gas constant
h = alt*_REARTH/(alt+_REARTH) -- geometric to geopotential altitude
(theta, delta)
-- troposphere
| h < 11.0 = ( (288.15 - 6.5*h)/288.15, theta**(_GMR/6.5) )
-- stratosphere
| h < 20.0 = (216.65/288.15, 0.2233611*exp(-_GMR*(h-11.0)/216.65))
| otherwise = error "simpleAtmosphere invalid higher than 20 km"
sigma = delta/theta
metricViscosity :: (Floating a, Ord a) => a -> a
metricViscosity theta = _BETAVISC*sqrt(t*t*t)/(t+_SUTH)
where
t = theta * _TZERO
| ghorn/conceptual-design | Atmosphere/Atmosphere.hs | bsd-3-clause | 3,780 | 0 | 15 | 984 | 922 | 527 | 395 | 56 | 1 |
{-# LANGUAGE
DataKinds
, FlexibleContexts
, LambdaCase
, TupleSections #-}
module Language.HM.Rename
( NameError (..)
, rename
) where
import Control.Applicative
import Control.Category
import Control.Comonad.Cofree
import Control.Monad.Error.Class
import Control.Monad.Name.Class
import Control.Monad.Reader
import Control.Monad.Wrap
import Data.Fix
import Data.Flip
import Data.Hashable
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as Map
import Data.Monoid
import Data.Tagged
import Data.Text
import Language.HM.Exp
import Language.HM.Parse
import Language.HM.Type (Mono)
import Language.HM.Var
import Prelude hiding ((.))
type Map = HashMap
type RenamedExp name = Cofree (Exp Curry name (Fix (Mono name))) Loc
data NameError = NotInScope Text deriving Show
rename :: ( Eq (name Value)
, Hashable (name Value)
, MonadError (NameError, Loc) m
, MonadName name m
) =>
ParsedExp ->
m (RenamedExp name)
rename = unwrapMonadT . flip runReaderT mempty . loop
where
loop (a :< f) = (a :<) <$> case f of
Lit i ->
pure $ Lit i
Var x ->
Var <$> lookupName' x
Abs x e ->
bindName x $ \ x' -> Abs x' <$> loop e
App e1 e2 ->
App <$> loop e1 <*> loop e2
Let x e1 e2 -> do
e1' <- loop e1
(bindName x $ \ x' -> Let x' e1' <$> loop e2)
where
lookupName' = either (throwError . (, a)) return <=< lookupName
lookupName :: MonadReader (R name) m =>
Flip Tagged Text Value -> m (Either NameError (name Value))
lookupName (Flip (Tagged name)) =
asks (Map.lookup name) >>= \ case
Nothing -> return . Left $ NotInScope name
Just name' -> return $ Right name'
bindName :: ( MonadName name m
, MonadReader (R name) m
) => Flip Tagged Text Value -> (name Value -> m a) -> m a
bindName (Flip (Tagged name)) f = do
name' <- newVar
local (Map.insert name name') $ f name'
type R name = Map Text (name Value)
| sonyandy/unify | examples/unify-hm/Language/HM/Rename.hs | bsd-3-clause | 2,058 | 0 | 17 | 555 | 737 | 389 | 348 | 64 | 5 |
{- |
Copyright : Copyright (C) 2011 Bjorn Buckwalter
License : BSD3
Maintainer : [email protected]
Stability : Stable
Portability: Haskell 98
This purpose of this library is to have a simple API and no
dependencies beyond Haskell 98 in order to let you produce normally
distributed random values with a minimum of fuss. This library does
/not/ attempt to be blazingly fast nor to pass stringent tests of
randomness. It attempts to be very easy to install and use while
being \"good enough\" for many applications (simulations, games, etc.).
The API builds upon and is largely analogous to that of the Haskell
98 @Random@ module (more recently @System.Random@).
Pure:
> (sample,g) = normal myRandomGen -- using a Random.RandomGen
> samples = normals myRandomGen -- infinite list
> samples2 = mkNormals 10831452 -- infinite list using a seed
In the IO monad:
> sample <- normalIO
> samples <- normalsIO -- infinite list
With custom mean and standard deviation:
> (sample,g) = normal' (mean,sigma) myRandomGen
> samples = normals' (mean,sigma) myRandomGen
> samples2 = mkNormals' (mean,sigma) 10831452
> sample <- normalIO' (mean,sigma)
> samples <- normalsIO' (mean,sigma)
Internally the library uses the Box-Muller method to generate
normally distributed values from uniformly distributed random values.
If more than one sample is needed taking samples off an infinite
list (created by e.g. 'normals') will be roughly twice as efficient
as repeatedly generating individual samples with e.g. 'normal'.
-}
module Data.Random.Normal (
-- * Pure interface
normal
, normals
, mkNormals
-- ** Custom mean and standard deviation
, normal'
, normals'
, mkNormals'
-- * Using the global random number generator
, normalIO
, normalsIO
-- ** Custom mean and standard deviation
, normalIO'
, normalsIO'
) where
import Data.List (mapAccumL)
import System.Random
-- Normal distribution approximation
-- ---------------------------------
-- | Box-Muller method for generating two normally distributed
-- independent random values from two uniformly distributed
-- independent random values.
boxMuller :: Floating a => a -> a -> (a,a)
boxMuller u1 u2 = (r * cos t, r * sin t) where r = sqrt (-2 * log u1)
t = 2 * pi * u2
-- | Convert a list of uniformly distributed random values into a
-- list of normally distributed random values. The Box-Muller
-- algorithms converts values two at a time, so if the input list
-- has an uneven number of element the last one will be discarded.
boxMullers :: Floating a => [a] -> [a]
boxMullers (u1:u2:us) = n1:n2:boxMullers us where (n1,n2) = boxMuller u1 u2
boxMullers _ = []
-- API
-- ===
-- | Takes a random number generator g, and returns a random value
-- normally distributed with mean 0 and standard deviation 1,
-- together with a new generator. This function is analogous to
-- 'Random.random'.
normal :: (RandomGen g, Random a, Floating a) => g -> (a,g)
normal g0 = (fst $ boxMuller u1 u2, g2)
-- While The Haskell 98 report says "For fractional types, the
-- range is normally the semi-closed interval [0,1)" we will
-- specify the range explicitly just to be sure.
where
(u1,g1) = randomR (0,1) g0
(u2,g2) = randomR (0,1) g1
-- | Plural variant of 'normal', producing an infinite list of
-- random values instead of returning a new generator. This function
-- is analogous to 'Random.randoms'.
normals :: (RandomGen g, Random a, Floating a) => g -> [a]
normals = boxMullers . randoms
-- | Creates a infinite list of normally distributed random values
-- from the provided random generator seed. (In the implementation
-- the seed is fed to 'Random.mkStdGen' to produce the random
-- number generator.)
mkNormals :: (Random a, Floating a) => Int -> [a]
mkNormals = normals . mkStdGen
-- | A variant of 'normal' that uses the global random number
-- generator. This function is analogous to 'Random.randomIO'.
normalIO :: (Random a, Floating a) => IO a
normalIO = do u1 <- randomRIO (0,1)
u2 <- randomRIO (0,1)
return $ fst $ boxMuller u1 u2
-- | Creates a infinite list of normally distributed random values
-- using the global random number generator. (In the implementation
-- 'Random.newStdGen' is used.)
normalsIO :: (Random a, Floating a) => IO [a]
normalsIO = fmap normals newStdGen
-- With mean and standard deviation
-- --------------------------------
-- | Analogous to 'normal' but uses the supplied (mean, standard
-- deviation).
normal' :: (RandomGen g, Random a, Floating a) => (a,a) -> g -> (a,g)
normal' (mean, sigma) g = (x * sigma + mean, g') where (x, g') = normal g
-- | Analogous to 'normals' but uses the supplied (mean, standard
-- deviation).
normals' :: (RandomGen g, Random a, Floating a) => (a,a) -> g -> [a]
normals' (mean, sigma) g = map (\x -> x * sigma + mean) (normals g)
-- | Analogous to 'mkNormals' but uses the supplied (mean, standard
-- deviation).
mkNormals' :: (Random a, Floating a) => (a,a) -> Int -> [a]
mkNormals' ms = normals' ms . mkStdGen
-- | Analogous to 'normalIO' but uses the supplied (mean, standard
-- deviation).
normalIO' ::(Random a, Floating a) => (a,a) -> IO a
normalIO' (mean,sigma) = fmap (\x -> x * sigma + mean) normalIO
-- | Analogous to 'normalsIO' but uses the supplied (mean, standard
-- deviation).
normalsIO' :: (Random a, Floating a) => (a,a) -> IO [a]
normalsIO' ms = fmap (normals' ms) newStdGen
| bjornbm/normaldistribution | Data/Random/Normal.hs | bsd-3-clause | 5,529 | 0 | 10 | 1,119 | 924 | 523 | 401 | 43 | 1 |
--file: Main.hs
module AnsiExample where
import Prelude hiding (Either(..))
import System.Console.ANSI
import System.IO
type Coord = (Int, Int)
data World = World { wHero :: Coord }
data Input = Up
| Down
| Left
| Right
| Exit
deriving (Eq)
anotherMain = do
hSetEcho stdin False
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hideCursor
setTitle "Thieflike"
gameLoop $ World (0, 0)
drawHero (heroX, heroY) = do
clearScreen
setCursorPosition heroY heroX
setSGR [ SetConsoleIntensity BoldIntensity
, SetColor Foreground Vivid Blue ]
putStr "@"
-- receive a character and return our Input data structure,
-- recursing on invalid input
getInput = do
char <- getChar
case char of
'q' -> return Exit
'w' -> return Up
's' -> return Down
'a' -> return Left
'd' -> return Right
_ -> getInput
-- operator to add 2 coordinates together
(|+|) :: Coord -> Coord -> Coord
(|+|) (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
dirToCoord d
| d == Up = (0, -1)
| d == Down = (0, 1)
| d == Left = (-1, 0)
| d == Right = (1, 0)
| otherwise = (0, 0)
-- add the supplied direction to the hero's position, and set that
-- to be the hero's new position, making sure to limit the hero's
-- position between 0 and 80 in either direction
handleDir w@(World hero) input = gameLoop (w { wHero = newCoord })
where newCoord = (newX, newY)
(heroX, heroY) = hero |+| (dirToCoord input)
hConst i = max 0 (min i 80)
newX = hConst heroX
newY = hConst heroY
-- update the game loop to add in the goodbye message
gameLoop world@(World hero) = do
drawHero hero
input <- getInput
case input of
Exit -> handleExit
_ -> handleDir world input
-- when the user wants to exit we give them a thank you
-- message and then reshow the cursor
handleExit = do
clearScreen
setCursorPosition 0 0
showCursor
putStrLn "Thank you for playing!" | JobaerChowdhury/game-of-life | app/AnsiExample.hs | bsd-3-clause | 2,040 | 0 | 10 | 569 | 605 | 316 | 289 | 59 | 6 |
module Handler.Board where
import Import
import qualified Data.Text as T
import qualified Data.List.Split as S
import Board
import NeuralNets
import CommonDatatypes
getBoardR :: Text -> Handler RepHtml
getBoardR boardRepr = do
ag'white <- liftIO $ mkAgent White
ag'black <- liftIO $ mkAgent Black
let denseRepr = map read $ S.splitOn "," $ T.unpack $ boardRepr
board = denseReprToBoard denseRepr
moves'white = getMoves White board
moves'black = getMoves Black board
-- moves'white'repr = map boardToLink moves'white
-- moves'black'repr = map boardToLink moves'black
boardToLink = T.pack . reprToRow . boardToDense
eval b c = evaluateBoard (if c == White then ag'white :: AgentNNSimple else ag'black :: AgentNNSimple) b
defaultLayout $ do
setTitle "So abaloney..."
$(widgetFile "board")
| Tener/deeplearning-thesis | yesod/abaloney/Handler/Board.hs | bsd-3-clause | 859 | 0 | 14 | 187 | 218 | 114 | 104 | 20 | 2 |
-- | Provides a set implementation for machine CSP sets. This relies heavily
-- on the type checking and assumes in many places that the sets being operated
-- on are suitable for the opertion in question.
--
-- We cannot just use the built in set implementation as FDR assumes in several
-- places that infinite sets are allowed.
module CSPM.Evaluator.ValueSet (
-- * Construction
ValueSet(..),
emptySet, fromList, toList, toSeq, singleton,
-- * Basic Functions
compareValueSets,
member, card, empty,
union, unions, infiniteUnions,
intersection, intersections,
difference,
-- * Derived functions
CartProductType(..), cartesianProduct, powerset, allSequences, allMaps,
fastUnDotCartProduct,
-- * Specialised Functions
singletonValue,
valueSetToEventSet,
unDotProduct,
)
where
import Control.Monad
import qualified Data.Foldable as F
import Data.Hashable
import Data.List (sort)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Sequence as Sq
import qualified Data.Traversable as T
import {-# SOURCE #-} CSPM.Evaluator.Exceptions
import CSPM.Evaluator.Values
--import qualified CSPM.Evaluator.ProcessValues as CE
import Util.Exception
import qualified Util.List as UL
import Util.Prelude
data CartProductType = CartDot | CartTuple deriving (Eq, Ord)
data ValueSet =
-- | Set of all integers
Integers
-- | Set of all processes
| Processes
-- | An explicit set of values
| ExplicitSet (S.Set Value)
-- | The infinite set of integers starting at lb.
| IntSetFrom Int
-- | A union of several sets.
| CompositeSet (Sq.Seq ValueSet)
-- | A set containing all sequences over the given set.
| AllSequences ValueSet
-- | A cartesian product of several sets.
| CartesianProduct [ValueSet] CartProductType
-- | The powerset of the given set
| Powerset ValueSet
-- | The set of all maps from the given domain to the given image.
| AllMaps ValueSet ValueSet
instance Hashable ValueSet where
hashWithSalt s Integers = s `hashWithSalt` (1 :: Int)
hashWithSalt s Processes = s `hashWithSalt` (2 :: Int)
hashWithSalt s (IntSetFrom lb) = s `hashWithSalt` (3 :: Int) `hashWithSalt` lb
hashWithSalt s (AllSequences vs) = s `hashWithSalt` (4 :: Int) `hashWithSalt` vs
-- All the above are the ONLY possible representations of the sets (as the
-- sets are infinite). However, other sets can be represented in multiple
-- ways so we have to normalise to an explicit set, essentially.
-- This is already guaranteed to be sorted
hashWithSalt s (ExplicitSet vs) = s `hashWithSalt` (5 :: Int) `hashWithSalt` (S.toList vs)
hashWithSalt s set = s `hashWithSalt` (sort $ toList set)
instance Eq ValueSet where
s1 == s2 = compare s1 s2 == EQ
instance Ord ValueSet where
-- Basic (possibly)-infinite cases
compare Integers Integers = EQ
compare Integers _ = GT
compare _ Integers = LT
compare Processes Processes = EQ
compare Processes _ = GT
compare _ Processes = LT
compare (IntSetFrom lb1) (IntSetFrom lb2) = compare lb1 lb2
compare (CartesianProduct vs1 cp1) (CartesianProduct vs2 cp2) =
compare cp1 cp2 `thenCmp` compare vs1 vs2
-- Mixed infinite cases
-- Explicitly finite cases
compare (CompositeSet s1) (CompositeSet s2) = compare s1 s2
compare (AllSequences s1) (AllSequences s2) = compare s1 s2
compare (ExplicitSet s1) (ExplicitSet s2) = compare s1 s2
compare (Powerset s1) (Powerset s2) = compare s1 s2
compare (AllMaps k1 v1) (AllMaps k2 v2) =
compare k1 k2 `thenCmp` compare v1 v2
-- Fallback to comparing the lists
compare s1 s2 = compare (sort $ toList s1) (sort $ toList s2)
flipOrder :: Maybe Ordering -> Maybe Ordering
flipOrder Nothing = Nothing
flipOrder (Just EQ) = Just EQ
flipOrder (Just LT) = Just GT
flipOrder (Just GT) = Just LT
-- | Compares two value sets using subseteq (as per the specification).
compareValueSets :: ValueSet -> ValueSet -> Maybe Ordering
-- Processes
compareValueSets Processes Processes = Just EQ
compareValueSets _ Processes = Just LT
compareValueSets Processes _ = Just GT
-- Integers
compareValueSets Integers Integers = Just EQ
compareValueSets _ Integers = Just LT
compareValueSets Integers _ = Just GT
-- IntSetFrom
compareValueSets (IntSetFrom lb1) (IntSetFrom lb2) = Just (compare lb1 lb2)
-- ExplicitSet
compareValueSets (ExplicitSet s1) (ExplicitSet s2) =
if s1 == s2 then Just EQ
else if S.isProperSubsetOf s1 s2 then Just LT
else if S.isProperSubsetOf s2 s1 then Just GT
else Nothing
-- IntSetFrom+ExplicitSet
compareValueSets (IntSetFrom lb1) (ExplicitSet s2) =
let
VInt lb2 = S.findMin s2
VInt ub2 = S.findMax s2
in if lb1 <= lb2 then Just GT else Nothing
compareValueSets (ExplicitSet s1) (IntSetFrom lb1) =
flipOrder (compareValueSets (IntSetFrom lb1) (ExplicitSet s1))
-- Composite Sets
compareValueSets (CompositeSet ss) s =
compareValueSets (fromList (toList (CompositeSet ss))) s
compareValueSets s (CompositeSet ss) =
flipOrder (compareValueSets (CompositeSet ss) s)
compareValueSets s1 s2 | empty s1 && empty s2 = Just EQ
compareValueSets s1 s2 | empty s1 && not (empty s2) = Just LT
compareValueSets s1 s2 | not (empty s1) && empty s2 = Just GT
-- AllSequences+ExplicitSet sets
compareValueSets (AllSequences vs1) (AllSequences vs2) = compareValueSets vs1 vs2
compareValueSets (ExplicitSet vs) (AllSequences vss) =
if and (map (flip member (AllSequences vss)) (S.toList vs)) then Just LT
-- Otherwise, there is some item in vs that is not in vss. However, unless
-- vss is empty there must be some value in the second set that is not in
-- the first, since (AllSequences vss) is infinite and, if the above
-- finishes, we know the first set is finite. Hence, they would be
-- incomparable.
else Nothing
compareValueSets (AllSequences vss) (ExplicitSet vs) =
flipOrder (compareValueSets (ExplicitSet vs) (AllSequences vss))
-- CartesianProduct+ExplicitSet sets
compareValueSets (CartesianProduct vss1 vc1) (CartesianProduct vss2 vc2) | vc1 == vc2 =
let os = zipWith compareValueSets vss1 vss2
order v [] = v
order (Just LT) (Just x : xs) | x /= GT = order (Just LT) xs
order (Just EQ) (Just x : xs) = order (Just x) xs
order (Just GT) (Just x : xs) | x /= LT = order (Just GT) xs
order _ _ = Nothing
in order (head os) os
compareValueSets (ExplicitSet vs) (CartesianProduct vsets vc) =
compareValueSets (ExplicitSet vs) (fromList (toList (CartesianProduct vsets vc)))
compareValueSets (CartesianProduct vsets vc) (ExplicitSet vs) =
flipOrder (compareValueSets (ExplicitSet vs) (CartesianProduct vsets vc))
compareValueSets (Powerset vs1) (Powerset vs2) = compareValueSets vs1 vs2
compareValueSets s1 (Powerset s2) =
compareValueSets s1 (fromList (toList (Powerset s2)))
compareValueSets (Powerset s1) s2 = flipOrder (compareValueSets s2 (Powerset s1))
compareValueSets s1 (AllMaps ks vs) =
compareValueSets s1 (fromList (toList (AllMaps ks vs)))
compareValueSets (AllMaps ks vs) s2 =
flipOrder (compareValueSets s2 (AllMaps ks vs))
-- Anything else is incomparable
compareValueSets _ _ = Nothing
-- | Produces a ValueSet of the carteisan product of several ValueSets,
-- using 'vc' to convert each sequence of values into a single value.
cartesianProduct :: CartProductType -> [ValueSet] -> ValueSet
cartesianProduct vc vss = CartesianProduct vss vc
powerset :: ValueSet -> ValueSet
powerset = Powerset
-- | Returns the set of all sequences over the input set. This is infinite
-- so we use a CompositeSet.
allSequences :: ValueSet -> ValueSet
allSequences s = AllSequences s
allMaps :: ValueSet -> ValueSet -> ValueSet
allMaps ks vs = AllMaps ks vs
-- | The empty set
emptySet :: ValueSet
emptySet = ExplicitSet S.empty
-- | Converts a list to a set
fromList :: [Value] -> ValueSet
fromList = ExplicitSet . S.fromList
-- | Constructs a singleton set
singleton :: Value -> ValueSet
singleton = ExplicitSet . S.singleton
-- | Converts a set to list.
toList :: ValueSet -> [Value]
toList (ExplicitSet s) = S.toList s
toList (IntSetFrom lb) = map VInt [lb..]
toList (CompositeSet ss) = F.msum (fmap toList ss)
toList Integers =
let merge (x:xs) ys = x:merge ys xs in map VInt $ merge [0..] [(-1),(-2)..]
toList Processes = throwSourceError [cannotConvertProcessesToListMessage]
toList (AllSequences vs) =
if empty vs then [] else
let
itemsAsList :: [Value]
itemsAsList = toList vs
list :: Integer -> [Value]
list 0 = [VList []]
list n = concatMap (\x -> map (app x) (list (n-1))) itemsAsList
where
app :: Value -> Value -> Value
app x (VList xs) = VList $ x:xs
allSequences :: [Value]
allSequences = concatMap list [0..]
in allSequences
toList (CartesianProduct vss ct) =
let cp = UL.cartesianProduct (map toList vss)
in case ct of
CartTuple -> map tupleFromList cp
CartDot -> map VDot cp
toList (Powerset vs) =
(map (VSet . fromList) . filterM (\x -> [True, False]) . toList) vs
toList (AllMaps ks' vs') =
let ks = toList (Powerset ks')
vs = toList vs'
-- | Creates all maps that have the given set as its domain
makeMaps :: [Value] -> [Value]
makeMaps [] = [VMap $ M.empty]
makeMaps (k:ks) =
map (\ [VMap m, v] -> VMap $ M.insert k v m)
(UL.cartesianProduct [makeMaps ks, vs])
in concatMap (\ (VSet s) -> makeMaps (toList s)) ks
toSeq :: ValueSet -> Sq.Seq Value
toSeq (ExplicitSet s) = F.foldMap Sq.singleton s
toSeq (IntSetFrom lb) = fmap VInt (Sq.fromList [lb..])
toSeq (CompositeSet ss) = F.msum (fmap toSeq ss)
toSeq (AllSequences vs) = Sq.fromList (toList (AllSequences vs))
toSeq (CartesianProduct vss ct) = Sq.fromList (toList (CartesianProduct vss ct))
toSeq (Powerset vs) = Sq.fromList (toList (Powerset vs))
toSeq (AllMaps ks vs) = Sq.fromList (toList (AllMaps ks vs))
toSeq Integers = throwSourceError [cannotConvertIntegersToListMessage]
toSeq Processes = throwSourceError [cannotConvertProcessesToListMessage]
-- | Returns the value iff the set contains one item only.
singletonValue :: ValueSet -> Maybe Value
singletonValue s = case toList s of
[x] -> Just x
_ -> Nothing
-- | Is the specified value a member of the set.
member :: Value -> ValueSet -> Bool
member v (ExplicitSet s) = S.member v s
member (VInt i) Integers = True
member (VInt i) (IntSetFrom lb) = i >= lb
member v (CompositeSet ss) = F.or (fmap (member v) ss)
-- FDR does actually try and given the correct value here.
member (VProc p) Processes = True
member (VList vs) (AllSequences s) = and (map (flip member s) vs)
member (VDot vs) (CartesianProduct vss CartDot) = and (zipWith member vs vss)
member (VTuple vs) (CartesianProduct vss CartTuple) =
and (zipWith member (elems vs) vss)
member (VSet s) (Powerset vs) = and (map (\v -> member v vs) (toList s))
member (VMap m) (AllMaps ks vs) =
and (map (flip member ks) (map fst (M.toList m)))
&& and (map (flip member vs) (map snd (M.toList m)))
member v s1 = throwSourceError [cannotCheckSetMembershipError v s1]
-- | The cardinality of the set. Throws an error if the set is infinite.
card :: ValueSet -> Integer
card (ExplicitSet s) = toInteger (S.size s)
card (CompositeSet ss) = F.sum (fmap card ss)
card (CartesianProduct vss _) = product (map card vss)
card (Powerset s) = 2^(card s)
card (AllMaps ks vs) =
-- For each key, we can either not map it to anything, or map it to one
-- of the values
(card vs + 1) ^ (card ks)
card s = throwSourceError [cardOfInfiniteSetMessage s]
-- | Is the specified set empty?
empty :: ValueSet -> Bool
empty (ExplicitSet s) = S.null s
empty (CompositeSet ss) = F.and (fmap empty ss)
empty (IntSetFrom lb) = False
empty (AllSequences s) = empty s
empty (CartesianProduct vss _) = or (map empty vss)
empty Processes = False
empty Integers = False
empty (Powerset s) = False
empty (AllMaps ks vs) = False
-- | Replicated union.
unions :: [ValueSet] -> ValueSet
unions [] = emptySet
unions vs = foldr1 union vs
infiniteUnions :: [ValueSet] -> ValueSet
infiniteUnions [vs] = vs
infiniteUnions vs =
let extract (CompositeSet s) = s
extract s = Sq.singleton s
in CompositeSet (F.msum (map extract vs))
-- | Replicated intersection.
intersections :: [ValueSet] -> ValueSet
intersections [] = emptySet
intersections (v:vs) = foldr1 intersection vs
-- | Union two sets throwing an error if it cannot be done in a way that will
-- terminate.
union :: ValueSet -> ValueSet -> ValueSet
-- Process unions
union _ Processes = Processes
union Processes _ = Processes
-- Integer unions
union (IntSetFrom lb1) (IntSetFrom lb2) = IntSetFrom (min lb1 lb2)
union _ Integers = Integers
union Integers _ = Integers
-- Explicit unions
union (ExplicitSet s1) (ExplicitSet s2) = ExplicitSet (S.union s1 s2)
union (CompositeSet s1) (CompositeSet s2) = CompositeSet (s1 Sq.>< s2)
union (CompositeSet s1) s2 = CompositeSet (s2 Sq.<| s1)
union s1 (CompositeSet s2) = CompositeSet (s1 Sq.<| s2)
union (IntSetFrom lb) s = CompositeSet (Sq.fromList [IntSetFrom lb, s])
union s (IntSetFrom lb) = CompositeSet (Sq.fromList [IntSetFrom lb, s])
union (AllSequences s1) s2 = CompositeSet (Sq.fromList [AllSequences s1, s2])
union s2 (AllSequences s1) = CompositeSet (Sq.fromList [AllSequences s1, s2])
union (AllMaps k v) s2 = CompositeSet (Sq.fromList [AllMaps k v, s2])
union s2 (AllMaps k v) = CompositeSet (Sq.fromList [AllMaps k v, s2])
-- Otherwise, we force to an explicit set (this has better performance than
-- always forming an explicit set)
union s1 s2 = ExplicitSet $ S.union (S.fromList (toList s1)) (S.fromList (toList s2))
-- | Intersects two sets throwing an error if it cannot be done in a way that
-- will terminate.
intersection :: ValueSet -> ValueSet -> ValueSet
-- Explicit intersections
intersection (ExplicitSet s1) (ExplicitSet s2) =
ExplicitSet (S.intersection s1 s2)
-- Integer intersections
intersection (IntSetFrom lb1) (IntSetFrom lb2) = IntSetFrom (max lb1 lb2)
intersection Integers Integers = Integers
intersection x Integers = x
intersection Integers x = x
-- Integer+ExplicitSet
intersection (ExplicitSet s1) (IntSetFrom lb1) =
let
VInt ubs = S.findMax s1
VInt lbs = S.findMin s1
in if lbs >= lb1 then ExplicitSet s1
else ExplicitSet (S.intersection (S.fromList (map VInt [lbs..ubs])) s1)
intersection (IntSetFrom lb1) (ExplicitSet s2) =
intersection (ExplicitSet s2) (IntSetFrom lb1)
-- Process intersection
intersection Processes Processes = Processes
intersection Processes x = x
intersection x Processes = x
-- Composite Sets
intersection (CompositeSet ss) s =
CompositeSet (fmap (intersection s) ss)
intersection s (CompositeSet ss) =
CompositeSet (fmap (intersection s) ss)
-- Cartesian product and all sequences - here we simpy convert to a list and
-- compare.
intersection (CartesianProduct vss vc) s =
intersection (fromList (toList (CartesianProduct vss vc))) s
intersection s (CartesianProduct vss vc) =
intersection (fromList (toList (CartesianProduct vss vc))) s
intersection (AllSequences vs) s =
intersection (fromList (toList (AllSequences vs))) s
intersection s (AllSequences vs) =
intersection (fromList (toList (AllSequences vs))) s
intersection (AllMaps ks vs) s =
intersection (fromList (toList (AllMaps ks vs))) s
intersection s (AllMaps ks vs) =
intersection (fromList (toList (AllMaps ks vs))) s
intersection (Powerset s1) (Powerset s2) = Powerset (intersection s1 s2)
intersection (Powerset s1) s2 = intersection (fromList (toList (Powerset s1))) s2
intersection s2 (Powerset s1) = intersection (fromList (toList (Powerset s1))) s2
difference :: ValueSet -> ValueSet -> ValueSet
difference (ExplicitSet s1) (ExplicitSet s2) = ExplicitSet (S.difference s1 s2)
difference (IntSetFrom lb1) (IntSetFrom lb2) = fromList (map VInt [lb1..(lb2-1)])
difference _ Integers = ExplicitSet S.empty
difference (IntSetFrom lb1) (ExplicitSet s1) =
let
VInt ubs = S.findMax s1
VInt lbs = S.findMin s1
card = S.size s1
rangeSize = 1+(ubs-lbs)
s1' = IntSetFrom lb1
s2' = ExplicitSet s1
in if fromIntegral rangeSize == card then
-- is contiguous
if lb1 == lbs then IntSetFrom (ubs+1)
else throwSourceError [cannotDifferenceSetsMessage s1' s2']
else
-- is not contiguous
throwSourceError [cannotDifferenceSetsMessage s1' s2']
difference (ExplicitSet s1) (IntSetFrom lb1) =
ExplicitSet (S.fromList [VInt i | VInt i <- S.toList s1, i < lb1])
difference (CompositeSet ss) s =
CompositeSet (fmap (\s1 -> difference s1 s) ss)
difference s (CompositeSet ss) = F.foldl difference s ss
difference s1 s2 = difference (fromList (toList s1)) (fromList (toList s2))
valueSetToEventSet :: ValueSet -> EventSet
valueSetToEventSet = eventSetFromList . map valueEventToEvent . toList
-- | Attempts to decompose the set into a cartesian product, returning Nothing
-- if it cannot.
unDotProduct :: ValueSet -> Maybe [ValueSet]
unDotProduct (CartesianProduct vs CartTuple) = return [CartesianProduct vs CartTuple]
unDotProduct (CartesianProduct (s1:ss) CartDot) =
-- This is reducible only if this set doesn't represent a set of datatype/
-- channel items. If this is the case recursively express as a CartDot
-- though
case singletonValue s1 of
Just (VDataType _) -> return [CartesianProduct (s1:ss) CartDot]
Just (VChannel _) -> return [CartesianProduct (s1:ss) CartDot]
_ -> return (s1:ss)
unDotProduct (AllSequences vs) = return [AllSequences vs]
unDotProduct (AllMaps ks vs) = return [AllMaps ks vs]
unDotProduct (IntSetFrom i1) = return [IntSetFrom i1]
unDotProduct (Powerset s) = return [Powerset s]
unDotProduct Integers = return [Integers]
unDotProduct Processes = return [Processes]
unDotProduct (CompositeSet ss) = do
vs <- T.mapM unDotProduct ss
let ok [_] = True
ok _ = False
ex [x] = x
if F.and (fmap ok vs) then Just [CompositeSet (fmap ex vs)]
else Nothing
unDotProduct (ExplicitSet s) | S.null s = return [ExplicitSet s]
unDotProduct (ExplicitSet s) =
case head (S.toList s) of
VDot _ -> Nothing
_ -> Just [ExplicitSet s]
fastUnDotCartProduct :: ValueSet -> Value -> Maybe [ValueSet]
fastUnDotCartProduct (CartesianProduct s CartDot) _ = Just s
fastUnDotCartProduct (CompositeSet ss) (VDot (h:vs)) =
let sq = Sq.filter isInteresting ss
isInteresting (CartesianProduct (hset:_) CartDot) =
case singletonValue hset of
Just h' | h == h' -> True
_ -> False
isInteresting _ = False
in if Sq.null sq then Nothing
else case Sq.index sq 0 of
CartesianProduct s CartDot -> Just s
_ -> Nothing
fastUnDotCartProduct _ _ = Nothing
| sashabu/libcspm | src/CSPM/Evaluator/ValueSet.hs | bsd-3-clause | 19,163 | 0 | 17 | 4,019 | 6,426 | 3,256 | 3,170 | 348 | 10 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances, TypeOperators, ScopedTypeVariables, NamedFieldPuns #-}
{-# LANGUAGE GADTs, GeneralizedNewtypeDeriving, DeriveDataTypeable, RecordWildCards #-}
-- | This module provides functions for calling command line programs, primarily
-- 'command' and 'cmd'. As a simple example:
--
-- @
-- 'command' [] \"gcc\" [\"-c\",myfile]
-- @
--
-- The functions from this module are now available directly from "Development.Shake".
-- You should only need to import this module if you are using the 'cmd' function in the 'IO' monad.
module Development.Shake.Command(
command, command_, cmd, cmd_, unit, CmdArgument(..), CmdArguments(..), IsCmdArgument(..), (:->),
Stdout(..), StdoutTrim(..), Stderr(..), Stdouterr(..), Exit(..), Process(..), CmdTime(..), CmdLine(..), FSATrace(..),
CmdResult, CmdString, CmdOption(..),
addPath, addEnv,
) where
import Data.Tuple.Extra
import Control.Monad.Extra
import Control.Monad.IO.Class
import Control.Exception.Extra
import Data.Char
import Data.Either.Extra
import Data.Foldable (toList)
import Data.List.Extra
import Data.List.NonEmpty (NonEmpty)
import qualified Data.HashSet as Set
import Data.Maybe
import Data.Data
import Data.Semigroup
import System.Directory
import qualified System.IO.Extra as IO
import System.Environment
import System.Exit
import System.IO.Extra hiding (withTempFile, withTempDir)
import System.Process
import System.Info.Extra
import System.Time.Extra
import System.IO.Unsafe (unsafeInterleaveIO)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import qualified Data.ByteString.UTF8 as UTF8
import General.Extra
import General.Process
import Prelude
import Development.Shake.Internal.CmdOption
import Development.Shake.Internal.Core.Action
import Development.Shake.Internal.Core.Types hiding (Result)
import Development.Shake.FilePath
import Development.Shake.Internal.Options
import Development.Shake.Internal.Rules.File
import Development.Shake.Internal.Derived
---------------------------------------------------------------------
-- ACTUAL EXECUTION
-- | /Deprecated:/ Use 'AddPath'. This function will be removed in a future version.
--
-- Add a prefix and suffix to the @$PATH@ environment variable. For example:
--
-- @
-- opt <- 'addPath' [\"\/usr\/special\"] []
-- 'cmd' opt \"userbinary --version\"
-- @
--
-- Would prepend @\/usr\/special@ to the current @$PATH@, and the command would pick
-- @\/usr\/special\/userbinary@, if it exists. To add other variables see 'addEnv'.
addPath :: MonadIO m => [String] -> [String] -> m CmdOption
addPath pre post = do
args <- liftIO getEnvironment
let (path,other) = partition ((== "PATH") . (if isWindows then upper else id) . fst) args
pure $ Env $
[("PATH",intercalate [searchPathSeparator] $ pre ++ post) | null path] ++
[(a,intercalate [searchPathSeparator] $ pre ++ [b | b /= ""] ++ post) | (a,b) <- path] ++
other
-- | /Deprecated:/ Use 'AddEnv'. This function will be removed in a future version.
--
-- Add a single variable to the environment. For example:
--
-- @
-- opt <- 'addEnv' [(\"CFLAGS\",\"-O2\")]
-- 'cmd' opt \"gcc -c main.c\"
-- @
--
-- Would add the environment variable @$CFLAGS@ with value @-O2@. If the variable @$CFLAGS@
-- was already defined it would be overwritten. If you wish to modify @$PATH@ see 'addPath'.
addEnv :: MonadIO m => [(String, String)] -> m CmdOption
addEnv extra = do
args <- liftIO getEnvironment
pure $ Env $ extra ++ filter (\(a,_) -> a `notElem` map fst extra) args
data Str = Str String | BS BS.ByteString | LBS LBS.ByteString | Unit deriving (Eq,Show)
strTrim :: Str -> Str
strTrim (Str x) = Str $ trim x
strTrim (BS x) = BS $ fst $ BS.spanEnd isSpace $ BS.dropWhile isSpace x
strTrim (LBS x) = LBS $ trimEnd $ LBS.dropWhile isSpace x
where
trimEnd x = case LBS.uncons x of
Just (c, x2) | isSpace c -> trimEnd x2
_ -> x
strTrim Unit = Unit
data Result
= ResultStdout Str
| ResultStderr Str
| ResultStdouterr Str
| ResultCode ExitCode
| ResultTime Double
| ResultLine String
| ResultProcess PID
| ResultFSATrace [FSATrace FilePath]
| ResultFSATraceBS [FSATrace BS.ByteString]
deriving (Eq,Show)
data PID = PID0 | PID ProcessHandle
instance Eq PID where _ == _ = True
instance Show PID where show PID0 = "PID0"; show _ = "PID"
data Params = Params
{funcName :: String
,opts :: [CmdOption]
,results :: [Result]
,prog :: String
,args :: [String]
} deriving Show
class MonadIO m => MonadTempDir m where
runWithTempDir :: (FilePath -> m a) -> m a
runWithTempFile :: (FilePath -> m a) -> m a
instance MonadTempDir IO where
runWithTempDir = IO.withTempDir
runWithTempFile = IO.withTempFile
instance MonadTempDir Action where
runWithTempDir = withTempDir
runWithTempFile = withTempFile
---------------------------------------------------------------------
-- DEAL WITH Shell
removeOptionShell
:: MonadTempDir m
=> Params -- ^ Given the parameter
-> (Params -> m a) -- ^ Call with the revised params, program name and command line
-> m a
removeOptionShell params@Params{..} call
| Shell `elem` opts = do
-- put our UserCommand first, as the last one wins, and ours is lowest priority
let userCmdline = unwords $ prog : args
params <- pure params{opts = UserCommand userCmdline : filter (/= Shell) opts}
prog <- liftIO $ if isFSATrace params then copyFSABinary prog else pure prog
let realCmdline = unwords $ prog : args
if not isWindows then
call params{prog = "/bin/sh", args = ["-c",realCmdline]}
else
-- On Windows the Haskell behaviour isn't that clean and is very fragile, so we try and do better.
runWithTempDir $ \dir -> do
let file = dir </> "s.bat"
writeFile' file realCmdline
call params{prog = "cmd.exe", args = ["/d/q/c",file]}
| otherwise = call params
---------------------------------------------------------------------
-- DEAL WITH FSATrace
isFSATrace :: Params -> Bool
isFSATrace Params{..} = any isResultFSATrace results || any isFSAOptions opts
-- Mac disables tracing on system binaries, so we copy them over, yurk
copyFSABinary :: FilePath -> IO FilePath
copyFSABinary prog
| not isMac = pure prog
| otherwise = do
progFull <- findExecutable prog
case progFull of
Just x | any (`isPrefixOf` x) ["/bin/","/usr/","/sbin/"] -> do
-- The file is one of the ones we can't trace, so we make a copy of it in $TMP and run that
-- We deliberately don't clean up this directory, since otherwise we spend all our time copying binaries over
tmpdir <- getTemporaryDirectory
let fake = tmpdir </> "fsatrace-fakes" ++ x -- x is absolute, so must use ++
unlessM (doesFileExist fake) $ do
createDirectoryRecursive $ takeDirectory fake
copyFile x fake
pure fake
_ -> pure prog
removeOptionFSATrace
:: MonadTempDir m
=> Params -- ^ Given the parameter
-> (Params -> m [Result]) -- ^ Call with the revised params, program name and command line
-> m [Result]
removeOptionFSATrace params@Params{..} call
| not $ isFSATrace params = call params
| ResultProcess PID0 `elem` results =
-- This is a bad state to get into, you could technically just ignore the tracing, but that's a bit dangerous
liftIO $ errorIO "Asyncronous process execution combined with FSATrace is not support"
| otherwise = runWithTempFile $ \file -> do
liftIO $ writeFile file "" -- ensures even if we fail before fsatrace opens the file, we can still read it
params <- liftIO $ fsaParams file params
res <- call params{opts = UserCommand (showCommandForUser2 prog args) : filter (not . isFSAOptions) opts}
fsaResBS <- liftIO $ parseFSA <$> BS.readFile file
let fsaRes = map (fmap UTF8.toString) fsaResBS
pure $ flip map res $ \case
ResultFSATrace [] -> ResultFSATrace fsaRes
ResultFSATraceBS [] -> ResultFSATraceBS fsaResBS
x -> x
where
fsaFlags = lastDef "rwmdqt" [x | FSAOptions x <- opts]
fsaParams file Params{..} = do
prog <- copyFSABinary prog
pure params{prog = "fsatrace", args = fsaFlags : file : "--" : prog : args }
isFSAOptions FSAOptions{} = True
isFSAOptions _ = False
isResultFSATrace ResultFSATrace{} = True
isResultFSATrace ResultFSATraceBS{} = True
isResultFSATrace _ = False
addFSAOptions :: String -> [CmdOption] -> [CmdOption]
addFSAOptions x opts | any isFSAOptions opts = map f opts
where f (FSAOptions y) = FSAOptions $ nubOrd $ y ++ x
f x = x
addFSAOptions x opts = FSAOptions x : opts
-- | The results produced by @fsatrace@. All files will be absolute paths.
-- You can get the results for a 'cmd' by requesting a value of type
-- @['FSATrace']@.
data FSATrace a
= -- | Writing to a file
FSAWrite a
| -- | Reading from a file
FSARead a
| -- | Deleting a file
FSADelete a
| -- | Moving, arguments destination, then source
FSAMove a a
| -- | Querying\/stat on a file
FSAQuery a
| -- | Touching a file
FSATouch a
deriving (Show,Eq,Ord,Data,Typeable,Functor)
-- | Parse the 'FSATrace' entries, ignoring anything you don't understand.
parseFSA :: BS.ByteString -> [FSATrace BS.ByteString]
parseFSA = mapMaybe (f . dropR) . BS.lines
where
-- deal with CRLF on Windows
dropR x = case BS.unsnoc x of
Just (x, '\r') -> x
_ -> x
f x
| Just (k, x) <- BS.uncons x
, Just ('|', x) <- BS.uncons x =
case k of
'w' -> Just $ FSAWrite x
'r' -> Just $ FSARead x
'd' -> Just $ FSADelete x
'm' | (xs, ys) <- BS.break (== '|') x, Just ('|',ys) <- BS.uncons ys ->
Just $ FSAMove xs ys
'q' -> Just $ FSAQuery x
't' -> Just $ FSATouch x
_ -> Nothing
| otherwise = Nothing
---------------------------------------------------------------------
-- ACTION EXPLICIT OPERATION
-- | Given explicit operations, apply the Action ones, like skip/trace/track/autodep
commandExplicitAction :: Partial => Params -> Action [Result]
commandExplicitAction oparams = do
ShakeOptions{shakeCommandOptions,shakeRunCommands,shakeLint,shakeLintInside} <- getShakeOptions
params@Params{..}<- pure $ oparams{opts = shakeCommandOptions ++ opts oparams}
let skipper act = if null results && not shakeRunCommands then pure [] else act
let verboser act = do
let cwd = listToMaybe $ reverse [x | Cwd x <- opts]
putVerbose $
maybe "" (\x -> "cd " ++ x ++ "; ") cwd ++
last (showCommandForUser2 prog args : [x | UserCommand x <- opts])
verb <- getVerbosity
-- run quietly to suppress the tracer (don't want to print twice)
(if verb >= Verbose then quietly else id) act
let tracer act = do
-- note: use the oparams - find a good tracing before munging it for shell stuff
let msg = lastDef (defaultTraced oparams) [x | Traced x <- opts]
if msg == "" then liftIO act else traced msg act
let async = ResultProcess PID0 `elem` results
let tracker act
| AutoDeps `elem` opts = if async then liftIO $ errorIO "Can't use AutoDeps and asyncronous execution" else autodeps act
| shakeLint == Just LintFSATrace && not async = fsalint act
| otherwise = act params
autodeps act = do
ResultFSATrace pxs : res <- act params{opts = addFSAOptions "rwm" opts, results = ResultFSATrace [] : results}
let written = Set.fromList $ [x | FSAMove x _ <- pxs] ++ [x | FSAWrite x <- pxs]
-- If something both reads and writes to a file, it isn't eligible to be an autodeps
xs <- liftIO $ filterM doesFileExist [x | FSARead x <- pxs, not $ x `Set.member` written]
cwd <- liftIO getCurrentDirectory
temp <- fixPaths cwd xs
unsafeAllowApply $ need temp
pure res
fixPaths cwd xs = liftIO $ do
xs<- pure $ map toStandard xs
xs<- pure $ filter (\x -> any (`isPrefixOf` x) shakeLintInside) xs
mapM (\x -> fromMaybe x <$> makeRelativeEx cwd x) xs
fsalint act = do
ResultFSATrace xs : res <- act params{opts = addFSAOptions "rwm" opts, results = ResultFSATrace [] : results}
let reader (FSARead x) = Just x; reader _ = Nothing
writer (FSAWrite x) = Just x; writer (FSAMove x _) = Just x; writer _ = Nothing
existing f = liftIO . filterM doesFileExist . nubOrd . mapMaybe f
cwd <- liftIO getCurrentDirectory
trackRead =<< fixPaths cwd =<< existing reader xs
trackWrite =<< fixPaths cwd =<< existing writer xs
pure res
skipper $ tracker $ \params -> verboser $ tracer $ commandExplicitIO params
defaultTraced :: Params -> String
defaultTraced Params{..} = takeBaseName $ if Shell `elem` opts then fst (word1 prog) else prog
---------------------------------------------------------------------
-- IO EXPLICIT OPERATION
-- | Given a very explicit set of CmdOption, translate them to a General.Process structure
commandExplicitIO :: Partial => Params -> IO [Result]
commandExplicitIO params = removeOptionShell params $ \params -> removeOptionFSATrace params $ \Params{..} -> do
let (grabStdout, grabStderr) = both or $ unzip $ flip map results $ \case
ResultStdout{} -> (True, False)
ResultStderr{} -> (False, True)
ResultStdouterr{} -> (True, True)
_ -> (False, False)
optEnv <- resolveEnv opts
let optCwd = mergeCwd [x | Cwd x <- opts]
let optStdin = flip mapMaybe opts $ \case
Stdin x -> Just $ SrcString x
StdinBS x -> Just $ SrcBytes x
FileStdin x -> Just $ SrcFile x
InheritStdin -> Just SrcInherit
_ -> Nothing
let optBinary = BinaryPipes `elem` opts
let optAsync = ResultProcess PID0 `elem` results
let optTimeout = listToMaybe $ reverse [x | Timeout x <- opts]
let optWithStdout = lastDef False [x | WithStdout x <- opts]
let optWithStderr = lastDef True [x | WithStderr x <- opts]
let optFileStdout = [x | FileStdout x <- opts]
let optFileStderr = [x | FileStderr x <- opts]
let optEchoStdout = lastDef (not grabStdout && null optFileStdout) [x | EchoStdout x <- opts]
let optEchoStderr = lastDef (not grabStderr && null optFileStderr) [x | EchoStderr x <- opts]
let optRealCommand = showCommandForUser2 prog args
let optUserCommand = lastDef optRealCommand [x | UserCommand x <- opts]
let optCloseFds = CloseFileHandles `elem` opts
let optProcessGroup = NoProcessGroup `notElem` opts
let bufLBS f = do (a,b) <- buf $ LBS LBS.empty; pure (a, (\(LBS x) -> f x) <$> b)
buf Str{} | optBinary = bufLBS (Str . LBS.unpack)
buf Str{} = do x <- newBuffer; pure ([DestString x | not optAsync], Str . concat <$> readBuffer x)
buf LBS{} = do x <- newBuffer; pure ([DestBytes x | not optAsync], LBS . LBS.fromChunks <$> readBuffer x)
buf BS {} = bufLBS (BS . BS.concat . LBS.toChunks)
buf Unit = pure ([], pure Unit)
(dStdout, dStderr, resultBuild) :: ([[Destination]], [[Destination]], [Double -> ProcessHandle -> ExitCode -> IO Result]) <-
fmap unzip3 $ forM results $ \case
ResultCode _ -> pure ([], [], \_ _ ex -> pure $ ResultCode ex)
ResultTime _ -> pure ([], [], \dur _ _ -> pure $ ResultTime dur)
ResultLine _ -> pure ([], [], \_ _ _ -> pure $ ResultLine optUserCommand)
ResultProcess _ -> pure ([], [], \_ pid _ -> pure $ ResultProcess $ PID pid)
ResultStdout s -> do (a,b) <- buf s; pure (a , [], \_ _ _ -> fmap ResultStdout b)
ResultStderr s -> do (a,b) <- buf s; pure ([], a , \_ _ _ -> fmap ResultStderr b)
ResultStdouterr s -> do (a,b) <- buf s; pure (a , a , \_ _ _ -> fmap ResultStdouterr b)
ResultFSATrace _ -> pure ([], [], \_ _ _ -> pure $ ResultFSATrace []) -- filled in elsewhere
ResultFSATraceBS _ -> pure ([], [], \_ _ _ -> pure $ ResultFSATraceBS []) -- filled in elsewhere
exceptionBuffer <- newBuffer
po <- resolvePath ProcessOpts
{poCommand = RawCommand prog args
,poCwd = optCwd, poEnv = optEnv, poTimeout = optTimeout
,poStdin = [SrcBytes LBS.empty | optBinary && not (null optStdin)] ++ optStdin
,poStdout = [DestEcho | optEchoStdout] ++ map DestFile optFileStdout ++ [DestString exceptionBuffer | optWithStdout && not optAsync] ++ concat dStdout
,poStderr = [DestEcho | optEchoStderr] ++ map DestFile optFileStderr ++ [DestString exceptionBuffer | optWithStderr && not optAsync] ++ concat dStderr
,poAsync = optAsync
,poCloseFds = optCloseFds
,poGroup = optProcessGroup
}
(dur,(pid,exit)) <- duration $ process po
if exit == ExitSuccess || ResultCode ExitSuccess `elem` results then
mapM (\f -> f dur pid exit) resultBuild
else do
exceptionBuffer <- readBuffer exceptionBuffer
let captured = ["Stderr" | optWithStderr] ++ ["Stdout" | optWithStdout]
cwd <- case optCwd of
Nothing -> pure ""
Just v -> do
v <- canonicalizePath v `catchIO` const (pure v)
pure $ "Current directory: " ++ v ++ "\n"
liftIO $ errorIO $
"Development.Shake." ++ funcName ++ ", system command failed\n" ++
"Command line: " ++ optRealCommand ++ "\n" ++
(if optRealCommand /= optUserCommand then "Original command line: " ++ optUserCommand ++ "\n" else "") ++
cwd ++
"Exit code: " ++ show (case exit of ExitFailure i -> i; _ -> 0) ++ "\n" ++
if null captured then "Stderr not captured because WithStderr False was used\n"
else if null exceptionBuffer then intercalate " and " captured ++ " " ++ (if length captured == 1 then "was" else "were") ++ " empty"
else intercalate " and " captured ++ ":\n" ++ unlines (dropWhile null $ lines $ concat exceptionBuffer)
mergeCwd :: [FilePath] -> Maybe FilePath
mergeCwd [] = Nothing
mergeCwd xs = Just $ foldl1 (</>) xs
-- | Apply all environment operations, to produce a new environment to use.
resolveEnv :: [CmdOption] -> IO (Maybe [(String, String)])
resolveEnv opts
| null env, null addEnv, null addPath, null remEnv = pure Nothing
| otherwise = Just . unique . tweakPath . (++ addEnv) . filter (flip notElem remEnv . fst) <$>
if null env then getEnvironment else pure (concat env)
where
env = [x | Env x <- opts]
addEnv = [(x,y) | AddEnv x y <- opts]
remEnv = [x | RemEnv x <- opts]
addPath = [(x,y) | AddPath x y <- opts]
newPath mid = intercalate [searchPathSeparator] $
concat (reverse $ map fst addPath) ++ [mid | mid /= ""] ++ concatMap snd addPath
isPath x = (if isWindows then upper else id) x == "PATH"
tweakPath xs | not $ any (isPath . fst) xs = ("PATH", newPath "") : xs
| otherwise = map (\(a,b) -> (a, if isPath a then newPath b else b)) xs
unique = reverse . nubOrdOn (if isWindows then upper . fst else fst) . reverse
-- | If the user specifies a custom $PATH, and not Shell, then try and resolve their prog ourselves.
-- Tricky, because on Windows it doesn't look in the $PATH first.
resolvePath :: ProcessOpts -> IO ProcessOpts
resolvePath po
| Just e <- poEnv po
, Just (_, path) <- find ((==) "PATH" . (if isWindows then upper else id) . fst) e
, RawCommand prog args <- poCommand po
= do
let progExe = if prog == prog -<.> exe then prog else prog <.> exe
-- use unsafeInterleaveIO to allow laziness to skip the queries we don't use
pathOld <- unsafeInterleaveIO $ fromMaybe "" <$> lookupEnv "PATH"
old <- unsafeInterleaveIO $ findExecutable prog
new <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath path) progExe
old2 <- unsafeInterleaveIO $ findExecutableWith (splitSearchPath pathOld) progExe
switch<- pure $ case () of
_ | path == pathOld -> False -- The state I can see hasn't changed
| Nothing <- new -> False -- I have nothing to offer
| Nothing <- old -> True -- I failed last time, so this must be an improvement
| Just old <- old, Just new <- new, equalFilePath old new -> False -- no different
| Just old <- old, Just old2 <- old2, equalFilePath old old2 -> True -- I could predict last time
| otherwise -> False
pure $ case new of
Just new | switch -> po{poCommand = RawCommand new args}
_ -> po
resolvePath po = pure po
-- | Given a list of directories, and a file name, return the complete path if you can find it.
-- Like findExecutable, but with a custom PATH.
findExecutableWith :: [FilePath] -> String -> IO (Maybe FilePath)
findExecutableWith path x = flip firstJustM (map (</> x) path) $ \s ->
ifM (doesFileExist s) (pure $ Just s) (pure Nothing)
---------------------------------------------------------------------
-- FIXED ARGUMENT WRAPPER
-- | Collect the @stdout@ of the process.
-- If used, the @stdout@ will not be echoed to the terminal, unless you include 'EchoStdout'.
-- The value type may be either 'String', or either lazy or strict 'ByteString'.
--
-- Note that most programs end their output with a trailing newline, so calling
-- @ghc --numeric-version@ will result in 'Stdout' of @\"6.8.3\\n\"@. If you want to automatically
-- trim the resulting string, see 'StdoutTrim'.
newtype Stdout a = Stdout {fromStdout :: a}
-- | Like 'Stdout' but remove all leading and trailing whitespaces.
newtype StdoutTrim a = StdoutTrim {fromStdoutTrim :: a}
-- | Collect the @stderr@ of the process.
-- If used, the @stderr@ will not be echoed to the terminal, unless you include 'EchoStderr'.
-- The value type may be either 'String', or either lazy or strict 'ByteString'.
newtype Stderr a = Stderr {fromStderr :: a}
-- | Collect the @stdout@ and @stderr@ of the process.
-- If used, the @stderr@ and @stdout@ will not be echoed to the terminal, unless you include 'EchoStdout' and 'EchoStderr'.
-- The value type may be either 'String', or either lazy or strict 'ByteString'.
newtype Stdouterr a = Stdouterr {fromStdouterr :: a}
-- | Collect the 'ExitCode' of the process.
-- If you do not collect the exit code, any 'ExitFailure' will cause an exception.
newtype Exit = Exit {fromExit :: ExitCode}
-- | Collect the 'ProcessHandle' of the process.
-- If you do collect the process handle, the command will run asyncronously and the call to 'cmd' \/ 'command'
-- will return as soon as the process is spawned. Any 'Stdout' \/ 'Stderr' captures will return empty strings.
newtype Process = Process {fromProcess :: ProcessHandle}
-- | Collect the time taken to execute the process. Can be used in conjunction with 'CmdLine' to
-- write helper functions that print out the time of a result.
--
-- @
-- timer :: ('CmdResult' r, MonadIO m) => (forall r . 'CmdResult' r => m r) -> m r
-- timer act = do
-- ('CmdTime' t, 'CmdLine' x, r) <- act
-- liftIO $ putStrLn $ \"Command \" ++ x ++ \" took \" ++ show t ++ \" seconds\"
-- pure r
--
-- run :: IO ()
-- run = timer $ 'cmd' \"ghc --version\"
-- @
newtype CmdTime = CmdTime {fromCmdTime :: Double}
-- | Collect the command line used for the process. This command line will be approximate -
-- suitable for user diagnostics, but not for direct execution.
newtype CmdLine = CmdLine {fromCmdLine :: String}
-- | The allowable 'String'-like values that can be captured.
class CmdString a where cmdString :: (Str, Str -> a)
instance CmdString () where cmdString = (Unit, \Unit -> ())
instance CmdString String where cmdString = (Str "", \(Str x) -> x)
instance CmdString BS.ByteString where cmdString = (BS BS.empty, \(BS x) -> x)
instance CmdString LBS.ByteString where cmdString = (LBS LBS.empty, \(LBS x) -> x)
class Unit a
instance {-# OVERLAPPING #-} Unit b => Unit (a -> b)
instance {-# OVERLAPPABLE #-} a ~ () => Unit (m a)
-- | A class for specifying what results you want to collect from a process.
-- Values are formed of 'Stdout', 'Stderr', 'Exit' and tuples of those.
class CmdResult a where
-- Return a list of results (with the right type but dummy data)
-- and a function to transform a populated set of results into a value
cmdResult :: ([Result], [Result] -> a)
instance CmdResult Exit where
cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> Exit x)
instance CmdResult ExitCode where
cmdResult = ([ResultCode ExitSuccess], \[ResultCode x] -> x)
instance CmdResult Process where
cmdResult = ([ResultProcess PID0], \[ResultProcess (PID x)] -> Process x)
instance CmdResult ProcessHandle where
cmdResult = ([ResultProcess PID0], \[ResultProcess (PID x)] -> x)
instance CmdResult CmdLine where
cmdResult = ([ResultLine ""], \[ResultLine x] -> CmdLine x)
instance CmdResult CmdTime where
cmdResult = ([ResultTime 0], \[ResultTime x] -> CmdTime x)
instance CmdResult [FSATrace FilePath] where
cmdResult = ([ResultFSATrace []], \[ResultFSATrace x] -> x)
instance CmdResult [FSATrace BS.ByteString] where
cmdResult = ([ResultFSATraceBS []], \[ResultFSATraceBS x] -> x)
instance CmdString a => CmdResult (Stdout a) where
cmdResult = let (a,b) = cmdString in ([ResultStdout a], \[ResultStdout x] -> Stdout $ b x)
instance CmdString a => CmdResult (StdoutTrim a) where
cmdResult = let (a,b) = cmdString in ([ResultStdout a], \[ResultStdout x] -> StdoutTrim $ b $ strTrim x)
instance CmdString a => CmdResult (Stderr a) where
cmdResult = let (a,b) = cmdString in ([ResultStderr a], \[ResultStderr x] -> Stderr $ b x)
instance CmdString a => CmdResult (Stdouterr a) where
cmdResult = let (a,b) = cmdString in ([ResultStdouterr a], \[ResultStdouterr x] -> Stdouterr $ b x)
instance CmdResult () where
cmdResult = ([], \[] -> ())
instance (CmdResult x1, CmdResult x2) => CmdResult (x1,x2) where
cmdResult = (a1++a2, \rs -> let (r1,r2) = splitAt (length a1) rs in (b1 r1, b2 r2))
where (a1,b1) = cmdResult
(a2,b2) = cmdResult
cmdResultWith :: forall b c. CmdResult b => (b -> c) -> ([Result], [Result] -> c)
cmdResultWith f = second (f .) cmdResult
instance (CmdResult x1, CmdResult x2, CmdResult x3) => CmdResult (x1,x2,x3) where
cmdResult = cmdResultWith $ \(a,(b,c)) -> (a,b,c)
instance (CmdResult x1, CmdResult x2, CmdResult x3, CmdResult x4) => CmdResult (x1,x2,x3,x4) where
cmdResult = cmdResultWith $ \(a,(b,c,d)) -> (a,b,c,d)
instance (CmdResult x1, CmdResult x2, CmdResult x3, CmdResult x4, CmdResult x5) => CmdResult (x1,x2,x3,x4,x5) where
cmdResult = cmdResultWith $ \(a,(b,c,d,e)) -> (a,b,c,d,e)
-- | Execute a system command. Before running 'command' make sure you 'Development.Shake.need' any files
-- that are used by the command.
--
-- This function takes a list of options (often just @[]@, see 'CmdOption' for the available
-- options), the name of the executable (either a full name, or a program on the @$PATH@) and
-- a list of arguments. The result is often @()@, but can be a tuple containg any of 'Stdout',
-- 'Stderr' and 'Exit'. Some examples:
--
-- @
-- 'command_' [] \"gcc\" [\"-c\",\"myfile.c\"] -- compile a file, throwing an exception on failure
-- 'Exit' c <- 'command' [] \"gcc\" [\"-c\",myfile] -- run a command, recording the exit code
-- ('Exit' c, 'Stderr' err) <- 'command' [] \"gcc\" [\"-c\",\"myfile.c\"] -- run a command, recording the exit code and error output
-- 'Stdout' out <- 'command' [] \"gcc\" [\"-MM\",\"myfile.c\"] -- run a command, recording the output
-- 'command_' ['Cwd' \"generated\"] \"gcc\" [\"-c\",myfile] -- run a command in a directory
-- @
--
-- Unless you retrieve the 'ExitCode' using 'Exit', any 'ExitFailure' will throw an error, including
-- the 'Stderr' in the exception message. If you capture the 'Stdout' or 'Stderr', that stream will not be echoed to the console,
-- unless you use the option 'EchoStdout' or 'EchoStderr'.
--
-- If you use 'command' inside a @do@ block and do not use the result, you may get a compile-time error about being
-- unable to deduce 'CmdResult'. To avoid this error, use 'command_'.
--
-- By default the @stderr@ stream will be captured for use in error messages, and also echoed. To only echo
-- pass @'WithStderr' 'False'@, which causes no streams to be captured by Shake, and certain programs (e.g. @gcc@)
-- to detect they are running in a terminal.
command :: (Partial, CmdResult r) => [CmdOption] -> String -> [String] -> Action r
command opts x xs = withFrozenCallStack $ b <$> commandExplicitAction (Params "command" opts a x xs)
where (a,b) = cmdResult
-- | A version of 'command' where you do not require any results, used to avoid errors about being unable
-- to deduce 'CmdResult'.
command_ :: Partial => [CmdOption] -> String -> [String] -> Action ()
command_ opts x xs = withFrozenCallStack $ void $ commandExplicitAction (Params "command_" opts [] x xs)
---------------------------------------------------------------------
-- VARIABLE ARGUMENT WRAPPER
-- | A type annotation, equivalent to the first argument, but in variable argument contexts,
-- gives a clue as to what return type is expected (not actually enforced).
type a :-> t = a
-- | Build or execute a system command. Before using 'cmd' to run a command, make sure you 'Development.Shake.need' any files
-- that are used by the command.
--
-- * @String@ arguments are treated as a list of whitespace separated arguments.
--
-- * @[String]@ arguments are treated as a list of literal arguments.
--
-- * 'CmdOption' arguments are used as options.
--
-- * 'CmdArgument' arguments, which can be built by 'cmd' itself, are spliced into the containing command.
--
-- Typically only string literals should be passed as @String@ arguments. When using variables
-- prefer @[myvar]@ so that if @myvar@ contains spaces they are properly escaped.
--
-- As some examples, here are some calls, and the resulting command string:
--
-- @
-- 'cmd_' \"git log --pretty=\" \"oneline\" -- git log --pretty= oneline
-- 'cmd_' \"git log --pretty=\" [\"oneline\"] -- git log --pretty= oneline
-- 'cmd_' \"git log\" (\"--pretty=\" ++ \"oneline\") -- git log --pretty=oneline
-- 'cmd_' \"git log\" (\"--pretty=\" ++ \"one line\") -- git log --pretty=one line
-- 'cmd_' \"git log\" [\"--pretty=\" ++ \"one line\"] -- git log "--pretty=one line"
-- @
--
-- More examples, including return values, see this translation of the examples given for the 'command' function:
--
-- @
-- 'cmd_' \"gcc -c myfile.c\" -- compile a file, throwing an exception on failure
-- 'Exit' c <- 'cmd' \"gcc -c\" [myfile] -- run a command, recording the exit code
-- ('Exit' c, 'Stderr' err) <- 'cmd' \"gcc -c myfile.c\" -- run a command, recording the exit code and error output
-- 'Stdout' out <- 'cmd' \"gcc -MM myfile.c\" -- run a command, recording the output
-- 'cmd' ('Cwd' \"generated\") \"gcc -c\" [myfile] :: 'Action' () -- run a command in a directory
--
-- let gccCommand = 'cmd' \"gcc -c\" :: 'CmdArgument' -- build a sub-command. 'cmd' can return 'CmdArgument' values as well as execute commands
-- cmd ('Cwd' \"generated\") gccCommand [myfile] -- splice that command into a greater command
-- @
--
-- If you use 'cmd' inside a @do@ block and do not use the result, you may get a compile-time error about being
-- unable to deduce 'CmdResult'. To avoid this error, use 'cmd_'. If you enable @OverloadedStrings@ or @OverloadedLists@
-- you may have to give type signatures to the arguments, or use the more constrained 'command' instead.
--
-- The 'cmd' function can also be run in the 'IO' monad, but then 'Traced' is ignored and command lines are not echoed.
-- As an example:
--
-- @
-- 'cmd' ('Cwd' \"generated\") 'Shell' \"gcc -c myfile.c\" :: IO ()
-- @
cmd :: (Partial, CmdArguments args) => args :-> Action r
cmd = withFrozenCallStack $ cmdArguments mempty
-- | See 'cmd'. Same as 'cmd' except with a unit result.
-- 'cmd' is to 'cmd_' as 'command' is to 'command_'.
cmd_ :: (Partial, CmdArguments args, Unit args) => args :-> Action ()
cmd_ = withFrozenCallStack cmd
-- | The arguments to 'cmd' - see 'cmd' for examples and semantics.
newtype CmdArgument = CmdArgument [Either CmdOption String]
deriving (Eq, Semigroup, Monoid, Show)
-- | The arguments to 'cmd' - see 'cmd' for examples and semantics.
class CmdArguments t where
-- | Arguments to cmd
cmdArguments :: Partial => CmdArgument -> t
instance (IsCmdArgument a, CmdArguments r) => CmdArguments (a -> r) where
cmdArguments xs x = cmdArguments $ xs `mappend` toCmdArgument x
instance CmdResult r => CmdArguments (Action r) where
cmdArguments (CmdArgument x) = case partitionEithers x of
(opts, x:xs) -> let (a,b) = cmdResult in b <$> commandExplicitAction (Params "cmd" opts a x xs)
_ -> error "Error, no executable or arguments given to Development.Shake.cmd"
instance CmdResult r => CmdArguments (IO r) where
cmdArguments (CmdArgument x) = case partitionEithers x of
(opts, x:xs) -> let (a,b) = cmdResult in b <$> commandExplicitIO (Params "cmd" opts a x xs)
_ -> error "Error, no executable or arguments given to Development.Shake.cmd"
instance CmdArguments CmdArgument where
cmdArguments = id
-- | Class to convert an a to a CmdArgument
class IsCmdArgument a where
-- | Conversion to a CmdArgument
toCmdArgument :: a -> CmdArgument
instance IsCmdArgument () where toCmdArgument = mempty
instance IsCmdArgument String where toCmdArgument = CmdArgument . map Right . words
instance IsCmdArgument [String] where toCmdArgument = CmdArgument . map Right
instance IsCmdArgument (NonEmpty String) where toCmdArgument = toCmdArgument . toList
instance IsCmdArgument CmdOption where toCmdArgument = CmdArgument . pure . Left
instance IsCmdArgument [CmdOption] where toCmdArgument = CmdArgument . map Left
instance IsCmdArgument CmdArgument where toCmdArgument = id
instance IsCmdArgument a => IsCmdArgument (Maybe a) where toCmdArgument = maybe mempty toCmdArgument
---------------------------------------------------------------------
-- UTILITIES
-- A better version of showCommandForUser, which doesn't escape so much on Windows
showCommandForUser2 :: FilePath -> [String] -> String
showCommandForUser2 cmd args = unwords $ map (\x -> if safe x then x else showCommandForUser x []) $ cmd : args
where
safe xs = xs /= "" && not (any bad xs)
bad x = isSpace x || (x == '\\' && not isWindows) || x `elem` ("\"\'" :: String)
| ndmitchell/shake | src/Development/Shake/Command.hs | bsd-3-clause | 35,626 | 0 | 26 | 8,400 | 8,964 | 4,734 | 4,230 | -1 | -1 |
{-# LINE 1 "Control.Concurrent.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, MagicHash
, UnboxedTuples
, ScopedTypeVariables
, RankNTypes
#-}
{-# OPTIONS_GHC -Wno-deprecations #-}
-- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN
-- and Control.Concurrent.SampleVar imports.
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (concurrency)
--
-- A common interface to a collection of useful concurrency
-- abstractions.
--
-----------------------------------------------------------------------------
module Control.Concurrent (
-- * Concurrent Haskell
-- $conc_intro
-- * Basic concurrency operations
ThreadId,
myThreadId,
forkIO,
forkFinally,
forkIOWithUnmask,
killThread,
throwTo,
-- ** Threads with affinity
forkOn,
forkOnWithUnmask,
getNumCapabilities,
setNumCapabilities,
threadCapability,
-- * Scheduling
-- $conc_scheduling
yield,
-- ** Blocking
-- $blocking
-- ** Waiting
threadDelay,
threadWaitRead,
threadWaitWrite,
threadWaitReadSTM,
threadWaitWriteSTM,
-- * Communication abstractions
module Control.Concurrent.MVar,
module Control.Concurrent.Chan,
module Control.Concurrent.QSem,
module Control.Concurrent.QSemN,
-- * Bound Threads
-- $boundthreads
rtsSupportsBoundThreads,
forkOS,
forkOSWithUnmask,
isCurrentThreadBound,
runInBoundThread,
runInUnboundThread,
-- * Weak references to ThreadIds
mkWeakThreadId,
-- * GHC's implementation of concurrency
-- |This section describes features specific to GHC's
-- implementation of Concurrent Haskell.
-- ** Haskell threads and Operating System threads
-- $osthreads
-- ** Terminating the program
-- $termination
-- ** Pre-emption
-- $preemption
-- ** Deadlock
-- $deadlock
) where
import Control.Exception.Base as Exception
import GHC.Conc hiding (threadWaitRead, threadWaitWrite,
threadWaitReadSTM, threadWaitWriteSTM)
import GHC.IO ( unsafeUnmask, catchException )
import GHC.IORef ( newIORef, readIORef, writeIORef )
import GHC.Base
import System.Posix.Types ( Fd )
import Foreign.StablePtr
import Foreign.C.Types
import qualified GHC.Conc
import Control.Concurrent.MVar
import Control.Concurrent.Chan
import Control.Concurrent.QSem
import Control.Concurrent.QSemN
{- $conc_intro
The concurrency extension for Haskell is described in the paper
/Concurrent Haskell/
<http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>.
Concurrency is \"lightweight\", which means that both thread creation
and context switching overheads are extremely low. Scheduling of
Haskell threads is done internally in the Haskell runtime system, and
doesn't make use of any operating system-supplied thread packages.
However, if you want to interact with a foreign library that expects your
program to use the operating system-supplied thread package, you can do so
by using 'forkOS' instead of 'forkIO'.
Haskell threads can communicate via 'MVar's, a kind of synchronised
mutable variable (see "Control.Concurrent.MVar"). Several common
concurrency abstractions can be built from 'MVar's, and these are
provided by the "Control.Concurrent" library.
In GHC, threads may also communicate via exceptions.
-}
{- $conc_scheduling
Scheduling may be either pre-emptive or co-operative,
depending on the implementation of Concurrent Haskell (see below
for information related to specific compilers). In a co-operative
system, context switches only occur when you use one of the
primitives defined in this module. This means that programs such
as:
> main = forkIO (write 'a') >> write 'b'
> where write c = putChar c >> write c
will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@,
instead of some random interleaving of @a@s and @b@s. In
practice, cooperative multitasking is sufficient for writing
simple graphical user interfaces.
-}
{- $blocking
Different Haskell implementations have different characteristics with
regard to which operations block /all/ threads.
Using GHC without the @-threaded@ option, all foreign calls will block
all other Haskell threads in the system, although I\/O operations will
not. With the @-threaded@ option, only foreign calls with the @unsafe@
attribute will block all other threads.
-}
-- | Fork a thread and call the supplied function when the thread is about
-- to terminate, with an exception or a returned value. The function is
-- called with asynchronous exceptions masked.
--
-- > forkFinally action and_then =
-- > mask $ \restore ->
-- > forkIO $ try (restore action) >>= and_then
--
-- This function is useful for informing the parent when a child
-- terminates, for example.
--
-- @since 4.6.0.0
forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally action and_then =
mask $ \restore ->
forkIO $ try (restore action) >>= and_then
-- ---------------------------------------------------------------------------
-- Bound Threads
{- $boundthreads
#boundthreads#
Support for multiple operating system threads and bound threads as described
below is currently only available in the GHC runtime system if you use the
/-threaded/ option when linking.
Other Haskell systems do not currently support multiple operating system threads.
A bound thread is a haskell thread that is /bound/ to an operating system
thread. While the bound thread is still scheduled by the Haskell run-time
system, the operating system thread takes care of all the foreign calls made
by the bound thread.
To a foreign library, the bound thread will look exactly like an ordinary
operating system thread created using OS functions like @pthread_create@
or @CreateThread@.
Bound threads can be created using the 'forkOS' function below. All foreign
exported functions are run in a bound thread (bound to the OS thread that
called the function). Also, the @main@ action of every Haskell program is
run in a bound thread.
Why do we need this? Because if a foreign library is called from a thread
created using 'forkIO', it won't have access to any /thread-local state/ -
state variables that have specific values for each OS thread
(see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some
libraries (OpenGL, for example) will not work from a thread created using
'forkIO'. They work fine in threads created using 'forkOS' or when called
from @main@ or from a @foreign export@.
In terms of performance, 'forkOS' (aka bound) threads are much more
expensive than 'forkIO' (aka unbound) threads, because a 'forkOS'
thread is tied to a particular OS thread, whereas a 'forkIO' thread
can be run by any OS thread. Context-switching between a 'forkOS'
thread and a 'forkIO' thread is many times more expensive than between
two 'forkIO' threads.
Note in particular that the main program thread (the thread running
@Main.main@) is always a bound thread, so for good concurrency
performance you should ensure that the main thread is not doing
repeated communication with other threads in the system. Typically
this means forking subthreads to do the work using 'forkIO', and
waiting for the results in the main thread.
-}
-- | 'True' if bound threads are supported.
-- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound'
-- will always return 'False' and both 'forkOS' and 'runInBoundThread' will
-- fail.
foreign import ccall rtsSupportsBoundThreads :: Bool
{- |
Like 'forkIO', this sparks off a new thread to run the 'IO'
computation passed as the first argument, and returns the 'ThreadId'
of the newly created thread.
However, 'forkOS' creates a /bound/ thread, which is necessary if you
need to call foreign (non-Haskell) libraries that make use of
thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads").
Using 'forkOS' instead of 'forkIO' makes no difference at all to the
scheduling behaviour of the Haskell runtime system. It is a common
misconception that you need to use 'forkOS' instead of 'forkIO' to
avoid blocking all the Haskell threads when making a foreign call;
this isn't the case. To allow foreign calls to be made without
blocking all the Haskell threads (with GHC), it is only necessary to
use the @-threaded@ option when linking your program, and to make sure
the foreign import is not marked @unsafe@.
-}
forkOS :: IO () -> IO ThreadId
foreign export ccall forkOS_entry
:: StablePtr (IO ()) -> IO ()
foreign import ccall "forkOS_entry" forkOS_entry_reimported
:: StablePtr (IO ()) -> IO ()
forkOS_entry :: StablePtr (IO ()) -> IO ()
forkOS_entry stableAction = do
action <- deRefStablePtr stableAction
action
foreign import ccall forkOS_createThread
:: StablePtr (IO ()) -> IO CInt
failNonThreaded :: IO a
failNonThreaded = fail $ "RTS doesn't support multiple OS threads "
++"(use ghc -threaded when linking)"
forkOS action0
| rtsSupportsBoundThreads = do
mv <- newEmptyMVar
b <- Exception.getMaskingState
let
-- async exceptions are masked in the child if they are masked
-- in the parent, as for forkIO (see #1048). forkOS_createThread
-- creates a thread with exceptions masked by default.
action1 = case b of
Unmasked -> unsafeUnmask action0
MaskedInterruptible -> action0
MaskedUninterruptible -> uninterruptibleMask_ action0
action_plus = catchException action1 childHandler
entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus)
err <- forkOS_createThread entry
when (err /= 0) $ fail "Cannot create OS thread."
tid <- takeMVar mv
freeStablePtr entry
return tid
| otherwise = failNonThreaded
-- | Like 'forkIOWithUnmask', but the child thread is a bound thread,
-- as with 'forkOS'.
forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId
forkOSWithUnmask io = forkOS (io unsafeUnmask)
-- | Returns 'True' if the calling thread is /bound/, that is, if it is
-- safe to use foreign libraries that rely on thread-local state from the
-- calling thread.
isCurrentThreadBound :: IO Bool
isCurrentThreadBound = IO $ \ s# ->
case isCurrentThreadBound# s# of
(# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #)
{- |
Run the 'IO' computation passed as the first argument. If the calling thread
is not /bound/, a bound thread is created temporarily. @runInBoundThread@
doesn't finish until the 'IO' computation finishes.
You can wrap a series of foreign function calls that rely on thread-local state
with @runInBoundThread@ so that you can use them without knowing whether the
current thread is /bound/.
-}
runInBoundThread :: IO a -> IO a
runInBoundThread action
| rtsSupportsBoundThreads = do
bound <- isCurrentThreadBound
if bound
then action
else do
ref <- newIORef undefined
let action_plus = Exception.try action >>= writeIORef ref
bracket (newStablePtr action_plus)
freeStablePtr
(\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>=
unsafeResult
| otherwise = failNonThreaded
{- |
Run the 'IO' computation passed as the first argument. If the calling thread
is /bound/, an unbound thread is created temporarily using 'forkIO'.
@runInBoundThread@ doesn't finish until the 'IO' computation finishes.
Use this function /only/ in the rare case that you have actually observed a
performance loss due to the use of bound threads. A program that
doesn't need its main thread to be bound and makes /heavy/ use of concurrency
(e.g. a web server), might want to wrap its @main@ action in
@runInUnboundThread@.
Note that exceptions which are thrown to the current thread are thrown in turn
to the thread that is executing the given computation. This ensures there's
always a way of killing the forked thread.
-}
runInUnboundThread :: IO a -> IO a
runInUnboundThread action = do
bound <- isCurrentThreadBound
if bound
then do
mv <- newEmptyMVar
mask $ \restore -> do
tid <- forkIO $ Exception.try (restore action) >>= putMVar mv
let wait = takeMVar mv `catchException` \(e :: SomeException) ->
Exception.throwTo tid e >> wait
wait >>= unsafeResult
else action
unsafeResult :: Either SomeException a -> IO a
unsafeResult = either Exception.throwIO return
-- ---------------------------------------------------------------------------
-- threadWaitRead/threadWaitWrite
-- | Block the current thread until data is available to read on the
-- given file descriptor (GHC only).
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitRead', use
-- 'GHC.Conc.closeFdWith'.
threadWaitRead :: Fd -> IO ()
threadWaitRead fd
= GHC.Conc.threadWaitRead fd
-- | Block the current thread until data can be written to the
-- given file descriptor (GHC only).
--
-- This will throw an 'IOError' if the file descriptor was closed
-- while this thread was blocked. To safely close a file descriptor
-- that has been used with 'threadWaitWrite', use
-- 'GHC.Conc.closeFdWith'.
threadWaitWrite :: Fd -> IO ()
threadWaitWrite fd
= GHC.Conc.threadWaitWrite fd
-- | Returns an STM action that can be used to wait for data
-- to read from a file descriptor. The second returned value
-- is an IO action that can be used to deregister interest
-- in the file descriptor.
--
-- @since 4.7.0.0
threadWaitReadSTM :: Fd -> IO (STM (), IO ())
threadWaitReadSTM fd
= GHC.Conc.threadWaitReadSTM fd
-- | Returns an STM action that can be used to wait until data
-- can be written to a file descriptor. The second returned value
-- is an IO action that can be used to deregister interest
-- in the file descriptor.
--
-- @since 4.7.0.0
threadWaitWriteSTM :: Fd -> IO (STM (), IO ())
threadWaitWriteSTM fd
= GHC.Conc.threadWaitWriteSTM fd
-- ---------------------------------------------------------------------------
-- More docs
{- $osthreads
#osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and
are managed entirely by the GHC runtime. Typically Haskell
threads are an order of magnitude or two more efficient (in
terms of both time and space) than operating system threads.
The downside of having lightweight threads is that only one can
run at a time, so if one thread blocks in a foreign call, for
example, the other threads cannot continue. The GHC runtime
works around this by making use of full OS threads where
necessary. When the program is built with the @-threaded@
option (to link against the multithreaded version of the
runtime), a thread making a @safe@ foreign call will not block
the other threads in the system; another OS thread will take
over running Haskell threads until the original call returns.
The runtime maintains a pool of these /worker/ threads so that
multiple Haskell threads can be involved in external calls
simultaneously.
The "System.IO" library manages multiplexing in its own way. On
Windows systems it uses @safe@ foreign calls to ensure that
threads doing I\/O operations don't block the whole runtime,
whereas on Unix systems all the currently blocked I\/O requests
are managed by a single thread (the /IO manager thread/) using
a mechanism such as @epoll@ or @kqueue@, depending on what is
provided by the host operating system.
The runtime will run a Haskell thread using any of the available
worker OS threads. If you need control over which particular OS
thread is used to run a given Haskell thread, perhaps because
you need to call a foreign library that uses OS-thread-local
state, then you need bound threads (see "Control.Concurrent#boundthreads").
If you don't use the @-threaded@ option, then the runtime does
not make use of multiple OS threads. Foreign calls will block
all other running Haskell threads until the call returns. The
"System.IO" library still does multiplexing, so there can be multiple
threads doing I\/O, and this is handled internally by the runtime using
@select@.
-}
{- $termination
In a standalone GHC program, only the main thread is
required to terminate in order for the process to terminate.
Thus all other forked threads will simply terminate at the same
time as the main thread (the terminology for this kind of
behaviour is \"daemonic threads\").
If you want the program to wait for child threads to
finish before exiting, you need to program this yourself. A
simple mechanism is to have each child thread write to an
'MVar' when it completes, and have the main
thread wait on all the 'MVar's before
exiting:
> myForkIO :: IO () -> IO (MVar ())
> myForkIO io = do
> mvar <- newEmptyMVar
> forkFinally io (\_ -> putMVar mvar ())
> return mvar
Note that we use 'forkFinally' to make sure that the
'MVar' is written to even if the thread dies or
is killed for some reason.
A better method is to keep a global list of all child
threads which we should wait for at the end of the program:
> children :: MVar [MVar ()]
> children = unsafePerformIO (newMVar [])
>
> waitForChildren :: IO ()
> waitForChildren = do
> cs <- takeMVar children
> case cs of
> [] -> return ()
> m:ms -> do
> putMVar children ms
> takeMVar m
> waitForChildren
>
> forkChild :: IO () -> IO ThreadId
> forkChild io = do
> mvar <- newEmptyMVar
> childs <- takeMVar children
> putMVar children (mvar:childs)
> forkFinally io (\_ -> putMVar mvar ())
>
> main =
> later waitForChildren $
> ...
The main thread principle also applies to calls to Haskell from
outside, using @foreign export@. When the @foreign export@ed
function is invoked, it starts a new main thread, and it returns
when this main thread terminates. If the call causes new
threads to be forked, they may remain in the system after the
@foreign export@ed function has returned.
-}
{- $preemption
GHC implements pre-emptive multitasking: the execution of
threads are interleaved in a random fashion. More specifically,
a thread may be pre-empted whenever it allocates some memory,
which unfortunately means that tight loops which do no
allocation tend to lock out other threads (this only seems to
happen with pathological benchmark-style code, however).
The rescheduling timer runs on a 20ms granularity by
default, but this may be altered using the
@-i\<n\>@ RTS option. After a rescheduling
\"tick\" the running thread is pre-empted as soon as
possible.
One final note: the
@aaaa@ @bbbb@ example may not
work too well on GHC (see Scheduling, above), due
to the locking on a 'System.IO.Handle'. Only one thread
may hold the lock on a 'System.IO.Handle' at any one
time, so if a reschedule happens while a thread is holding the
lock, the other thread won't be able to run. The upshot is that
the switch from @aaaa@ to
@bbbbb@ happens infrequently. It can be
improved by lowering the reschedule tick period. We also have a
patch that causes a reschedule whenever a thread waiting on a
lock is woken up, but haven't found it to be useful for anything
other than this example :-)
-}
{- $deadlock
GHC attempts to detect when threads are deadlocked using the garbage
collector. A thread that is not reachable (cannot be found by
following pointers from live objects) must be deadlocked, and in this
case the thread is sent an exception. The exception is either
'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM',
'NonTermination', or 'Deadlock', depending on the way in which the
thread is deadlocked.
Note that this feature is intended for debugging, and should not be
relied on for the correct operation of your program. There is no
guarantee that the garbage collector will be accurate enough to detect
your deadlock, and no guarantee that the garbage collector will run in
a timely enough manner. Basically, the same caveats as for finalizers
apply to deadlock detection.
There is a subtle interaction between deadlock detection and
finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the
functions in "System.Mem.Weak"): if a thread is blocked waiting for a
finalizer to run, then the thread will be considered deadlocked and
sent an exception. So preferably don't do this, but if you have no
alternative then it is possible to prevent the thread from being
considered deadlocked by making a 'StablePtr' pointing to it. Don't
forget to release the 'StablePtr' later with 'freeStablePtr'.
-}
| phischu/fragnix | builtins/base/Control.Concurrent.hs | bsd-3-clause | 21,926 | 0 | 21 | 4,993 | 1,300 | 723 | 577 | 133 | 3 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012-2014
--
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (TF,GNTD)
--
-- Provides key signature meta-data.
--
-------------------------------------------------------------------------------------
module Music.Score.Meta.Key (
-- * Key signature type
Fifths,
KeySignature,
key,
isMajorKey,
isMinorKey,
-- * Adding key signatures to scores
keySignature,
keySignatureDuring,
-- * Extracting key signatures
withKeySignature,
) where
import Control.Lens (view)
import Control.Monad.Plus
import Data.Foldable (Foldable)
import qualified Data.Foldable as F
import qualified Data.List as List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Semigroup
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String
import Data.Traversable (Traversable)
import qualified Data.Traversable as T
import Data.Typeable
import Music.Pitch.Literal
import Music.Score.Meta
import Music.Score.Part
import Music.Score.Pitch
import Music.Score.Internal.Util
import Music.Time
import Music.Time.Reactive
newtype Fifths = Fifths Integer
deriving (Eq, Ord, Num, Enum, Integral, Real)
instance IsPitch Fifths where
fromPitch (PitchL (d, fromMaybe 0 -> c, _)) = case (d,c) of
(0,-1) -> (-7)
(0, 0) -> 0
(0, 1) -> 7
(1,-1) -> (-5)
(1, 0) -> 2
(1, 1) -> 9
(2,-1) -> (-3)
(2, 0) -> 4
(2, 1) -> 11
(3,-1) -> (-8)
(3, 0) -> (-1)
(3, 1) -> 6
(4,-1) -> (-6)
(4, 0) -> 1
(4, 1) -> 8
(5,-1) -> (-4)
(5, 0) -> 3
(5, 1) -> 10
(6,-1) -> (-2)
(6, 0) -> 5
(6, 1) -> 12
_ -> error "Strange number of Fifths"
-- | A key signature, represented by number of fifths from C and mode.
newtype KeySignature = KeySignature (Fifths, Bool)
deriving (Eq, Ord, Typeable)
-- | Create a major or minor signature.
key :: Fifths -> Bool -> KeySignature
key fifths mode = KeySignature (fifths, mode)
isMajorKey :: KeySignature -> Bool
isMajorKey (KeySignature (_,x)) = x
isMinorKey :: KeySignature -> Bool
isMinorKey = not . isMajorKey
-- | Set the key signature of the given score.
keySignature :: (HasMeta a, HasPosition a) => KeySignature -> a -> a
keySignature c x = keySignatureDuring (_era x) c x
-- | Set the key signature of the given part of a score.
keySignatureDuring :: HasMeta a => Span -> KeySignature -> a -> a
keySignatureDuring s c = addMetaNote $ view event (s, (Option $ Just $ Last c))
-- | Extract all key signatures from the given score, using the given default key signature.
withKeySignature :: KeySignature -> (KeySignature -> Score a -> Score a) -> Score a -> Score a
withKeySignature def f = withMeta (f . fromMaybe def . fmap getLast . getOption)
| FranklinChen/music-score | src/Music/Score/Meta/Key.hs | bsd-3-clause | 3,917 | 0 | 11 | 1,212 | 920 | 541 | 379 | 83 | 1 |
{-# LANGUAGE LambdaCase #-}
{-|
Module : Lib
Description : Lib's main module
This is a haddock comment describing your library
For more information on how to write Haddock comments check the user guide:
<https://www.haskell.org/haddock/doc/html/index.html>
-}
module Lib
( slaskellbot
) where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.IO.Class
import Data.Maybe (isJust)
import qualified Data.Text as T
import Parser as P
import qualified Plugin.Dice as Dice
import qualified Plugin.Jira as Jira
import Text.Megaparsec (parseMaybe)
import Types
import Web.Slack hiding (Event)
import Web.Slack.Handle (SlackHandle, withSlackHandle)
import Web.Slack.Monad (monadicToHandled)
pluginHandlers :: [BotResponse]
pluginHandlers = [ Jira.respond, Dice.respond ]
pluginListeners :: [BotResponse]
pluginListeners = [ Jira.hear ]
slaskellbot :: Slack ()
slaskellbot = do
me <- _selfUserId . _slackSelf <$> getSession
conf <- getConfig
incomingCommand <- liftIO $ atomically newBroadcastTChan
incomingListen <- liftIO $ atomically newBroadcastTChan
outgoing <- liftIO $ atomically newTChan
_ <- mapM (liftIO . runPlugin incomingCommand) pluginHandlers
_ <- mapM (liftIO . runPlugin incomingListen) pluginListeners
_ <- liftIO $ withSlackHandle conf $ relayMessage outgoing
forever $ getNextEvent >>= \case
Message cid (UserComment uid) msg _ _ _ | uid /= me -> do
let parsedCmd = parseMaybe P.commandParser msg
case parsedCmd of
Just c -> liftIO $ print c
Nothing -> pure ()
let evt = Event msg uid cid parsedCmd
let response = OutputResponse outgoing evt NoMessage
let chan = if isJust parsedCmd then incomingCommand else incomingListen
liftIO $ atomically $ writeTChan chan (evt, response)
_ -> pure ()
runPlugin :: TChan BotInput -> BotResponse -> IO ThreadId
runPlugin chan f = do
myChan <- atomically $ dupTChan chan
forkIO $ forever $ do
msg <- atomically $ readTChan myChan
f msg
relayMessage :: TChan OutputResponse -> SlackHandle -> IO ThreadId
relayMessage chan h = do
forkIO $ forever $ do
resp <- atomically $ readTChan chan
monadicToHandled (publishMessage resp) h
publishMessage :: OutputResponse -> Slack ()
publishMessage resp = do
let cid = channel $ event resp
case (message resp) of
SimpleMessage txt -> slackSendMsg cid txt []
QuotedSimpleMessage txt -> slackSendMsg cid (T.concat ["`", txt, "`"]) []
RichMessage rmsg -> slackSendMsg cid "" [rmsg]
NoMessage -> pure ()
slackSendMsg :: ChannelId -> T.Text -> [Attachment] -> Slack ()
slackSendMsg cid msg att = do
send <- sendRichMessage cid msg att
either (liftIO . putStrLn . T.unpack) pure send
| wamaral/slaskellbot | src/Lib.hs | bsd-3-clause | 2,995 | 0 | 18 | 766 | 844 | 422 | 422 | 65 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Meadowstalk.Foundation
where
import Data.Text (Text)
import Text.Hamlet
import Database.Persist.Sql
import Yesod.Core
import Yesod.Persist
import Yesod.Form
import Yesod.Static
import Meadowstalk.Model
import Meadowstalk.Static
import Meadowstalk.Template
-------------------------------------------------------------------------------
data Meadowstalk =
Meadowstalk { siteStatic :: Static
, sitePool :: ConnectionPool
}
-------------------------------------------------------------------------------
mkYesodData "Meadowstalk" $(parseRoutesFile "config/routes")
mkMessage "Meadowstalk" "messages" "en"
-------------------------------------------------------------------------------
instance Yesod Meadowstalk where
defaultLayout widget = do
current <- getCurrentRoute
let isCurrent route = Just route == current
PageContent title htags btags <- widgetToPageContent $ do
$(lessFile "templates/bootstrap/bootstrap.less")
$(lessFile "templates/font-awesome/font-awesome.less")
$(lessFile "templates/layout/default-layout.less")
#ifndef YESOD_DEVEL
addScript (StaticR ga_js)
#endif
widget
withUrlRenderer $(hamletFile "templates/layout/default-layout.hamlet")
-------------------------------------------------------------------------------
instance YesodPersist Meadowstalk where
type YesodPersistBackend Meadowstalk = SqlBackend
runDB action = do
pool <- fmap sitePool getYesod
runSqlPool action pool
-------------------------------------------------------------------------------
instance RenderMessage Meadowstalk FormMessage where
renderMessage _ _ = defaultFormMessage
| HalfWayMan/meadowstalk | src/Meadowstalk/Foundation.hs | bsd-3-clause | 2,117 | 0 | 14 | 363 | 309 | 160 | 149 | 45 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Deviser.Parser
( readExpr
, readExprFile
) where
import Data.Array (listArray)
import Data.Complex
import Data.Functor.Identity (Identity)
import Data.Ratio ((%))
import qualified Data.Text as T
import Numeric (readFloat, readHex, readOct)
import Text.Parsec hiding (spaces)
import qualified Text.Parsec.Language as Language
import Text.Parsec.Text
import qualified Text.Parsec.Token as Token
import Deviser.Types
-- Lexer
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"
schemeDef :: Token.GenLanguageDef T.Text () Identity
schemeDef = Language.emptyDef
{ Token.commentStart = ""
, Token.commentEnd = ""
, Token.commentLine = ";"
, Token.opStart = Token.opLetter schemeDef
, Token.opLetter = symbol
, Token.identStart = letter <|> symbol
, Token.identLetter = letter <|> symbol <|> digit
, Token.reservedOpNames = ["'", "\"", ".", "+", "-"]
}
lexer :: Token.GenTokenParser T.Text () Identity
lexer = Token.makeTokenParser schemeDef
reservedOp :: T.Text -> Parser ()
reservedOp op = Token.reservedOp lexer (T.unpack op)
identifier :: Parser String
identifier = Token.identifier lexer
spaces :: Parser ()
spaces = Token.whiteSpace lexer
parens :: Parser a -> Parser a
parens = Token.parens lexer
stringLiteral :: Parser String
stringLiteral = Token.stringLiteral lexer
-- Atom
parseAtom :: Parser LispVal
parseAtom = identifier >>= \i -> return (Atom (T.pack i))
-- Lists
parseQuoted :: Parser LispVal
parseQuoted = do
_ <- char '\''
x <- parseExpr
return (List [Atom "quote", x])
parseQuasiquoted :: Parser LispVal
parseQuasiquoted = do
_ <- char '`'
x <- parseExpr
return (List [Atom "quasiquote", x])
parseUnquoted :: Parser LispVal
parseUnquoted = do
_ <- char ','
x <- parseExpr
return (List [Atom "unquote", x])
parseList :: Parser LispVal
parseList = List <$> (spaces *> many (parseExpr <* spaces))
parseDottedList :: Parser LispVal
parseDottedList = do
h <- endBy parseExpr spaces
t <- char '.' >> spaces >> parseExpr
return (DottedList h t)
parseListOrDottedList :: Parser LispVal
parseListOrDottedList =
parens (spaces *> (parseList <|> parseDottedList <* spaces))
-- Vector
parseVector :: Parser LispVal
parseVector = try $ do
_ <- string "#("
xs <- spaces *> many (parseExpr <* spaces)
_ <- char ')'
return (Vector (listArray (0, length xs - 1) xs))
-- Number
parseDigit1 :: Parser LispVal
parseDigit1 = (Number . read) <$> many1 digit
parseDigit2 :: Parser LispVal
parseDigit2 = do
_ <- try (string "#d")
x <- many1 digit
return (Number (read x))
hexDigitToNum :: (Num a, Eq a) => String -> a
hexDigitToNum = fst . head . readHex
parseHex :: Parser LispVal
parseHex = do
_ <- try (string "#x")
x <- many1 hexDigit
return (Number (hexDigitToNum x))
octDigitToNum :: (Num a, Eq a) => String -> a
octDigitToNum = fst . head . readOct
parseOct :: Parser LispVal
parseOct = do
_ <- try (string "#o")
x <- many1 octDigit
return (Number (octDigitToNum x))
binDigitsToNum :: String -> Integer
binDigitsToNum = binDigitsToNum' 0
where
binDigitsToNum' :: Num t => t -> String -> t
binDigitsToNum' digint xs =
case xs of
"" -> digint
(y:ys) -> binDigitsToNum' (2 * digint + (if y == '0' then 0 else 1)) ys
parseBin :: Parser LispVal
parseBin = do
_ <- try (string "#b")
x <- many1 (oneOf "10")
return (Number (binDigitsToNum x))
-- Float
floatDigitsToDouble :: String -> String -> Double
floatDigitsToDouble i d = fst (head (readFloat (i ++ "." ++ d)))
parseFloat :: Parser LispVal
parseFloat = do
i <- many1 digit
_ <- char '.'
d <- many1 digit
return (Float (floatDigitsToDouble i d))
-- Ratio
ratioDigitsToRational :: String -> String -> Rational
ratioDigitsToRational n d = read n % read d
parseRatio :: Parser LispVal
parseRatio = do
n <- many1 digit
_ <- char '/'
d <- many1 digit
return (Ratio (ratioDigitsToRational n d))
-- Complex
toDouble :: LispVal -> Double
toDouble (Float f) = realToFrac f
toDouble (Number n) = fromIntegral n
toDouble x = error ("toDouble not implemented for " ++ show x)
lispValsToComplex :: LispVal -> LispVal -> Complex Double
lispValsToComplex x y = toDouble x :+ toDouble y
parseComplex :: Parser LispVal
parseComplex = do
x <- try parseFloat <|> parseDigit1
_ <- char '+'
y <- try parseFloat <|> parseDigit1
_ <- char 'i'
return (Complex (lispValsToComplex x y))
-- String
parseString :: Parser LispVal
parseString = stringLiteral >>= \x -> return (String (T.pack x))
-- Character
parseCharacter :: Parser LispVal
parseCharacter = do
_ <- try (string "#\\")
value <- try (string "newline" <|> string "space") <|>
do x <- anyChar
_ <- notFollowedBy alphaNum
return [x]
return $ case value of
"space" -> Character ' '
"newline" -> Character '\n'
_ -> Character (T.head (T.pack value))
-- Boolean
parseBool :: Parser LispVal
parseBool =
char '#' *> ((char 't' *> return (Bool True)) <|> (char 'f' *> return (Bool False)))
-- Composed parsers
parseNumber :: Parser LispVal
parseNumber =
try parseComplex
<|> try parseRatio
<|> try parseFloat
<|> parseDigit1
<|> parseDigit2
<|> parseHex
<|> parseOct
<|> parseBin
parseExpr :: Parser LispVal
parseExpr =
parseAtom
<|> parseString
<|> try parseNumber
<|> try parseBool
<|> try parseCharacter
<|> parseQuoted
<|> parseListOrDottedList
<|> parseQuasiquoted
<|> parseUnquoted
<|> parseVector
withSpaces :: Parser a -> Parser a
withSpaces p = spaces *> p <* spaces
readExpr :: T.Text -> Either ParseError LispVal
readExpr = parse (withSpaces parseExpr) "<stdin>"
readExprFile :: T.Text -> Either ParseError LispVal
readExprFile = parse (withSpaces parseList) "<file>"
| henrytill/deviser | src/Deviser/Parser.hs | bsd-3-clause | 5,903 | 0 | 16 | 1,270 | 2,092 | 1,048 | 1,044 | 178 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module TW.CodeGen.PureScript
( makeFileName, makeModule
, libraryInfo
)
where
import TW.Ast
import TW.BuiltIn
import TW.JsonRepr
import TW.Types
import TW.Utils
import Data.Maybe
import Data.Monoid
import System.FilePath
import qualified Data.List as L
import qualified Data.Text as T
libraryInfo :: LibraryInfo
libraryInfo = LibraryInfo "Purescript" "purescript-typed-wire" "0.2.0"
makeFileName :: ModuleName -> FilePath
makeFileName (ModuleName parts) =
(L.foldl' (</>) "" $ map T.unpack parts) ++ ".purs"
makeModule :: Module -> T.Text
makeModule m =
T.unlines
[ "module " <> printModuleName (m_name m) <> " where"
, ""
, T.intercalate "\n" (map makeImport $ m_imports m)
, ""
, "import Data.TypedWire.Prelude"
, if not (null (m_apis m)) then "import Data.TypedWire.Api" else ""
, ""
, T.intercalate "\n" (map makeTypeDef $ m_typeDefs m)
, T.intercalate "\n" (map makeApiDef $ m_apis m)
]
makeApiDef :: ApiDef -> T.Text
makeApiDef ad =
T.unlines $
catMaybes
[ apiHeader
, Just $ T.intercalate "\n" (map makeEndPoint (ad_endpoints ad))
]
where
apiHeader =
case not (null (ad_headers ad)) of
True -> Just $ makeHeaderType apiHeaderType (ad_headers ad)
False -> Nothing
apiCapitalized = capitalizeText (unApiName $ ad_name ad)
handlerType = "ApiHandler" <> apiCapitalized
apiHeaderType = handlerType <> "Headers"
headerType ep = handlerType <> capitalizeText (unEndpointName (aed_name ep)) <> "Headers"
makeHeaderName hdr = uncapitalizeText $ makeSafePrefixedFieldName (ah_name hdr)
makeHeaderType ty headers =
T.unlines
[ "type " <> ty <> " = "
, " { " <> T.intercalate "\n , " (map makeHeaderField headers)
, " }"
]
makeHeaderField hdr =
makeHeaderName hdr <> " :: String"
makeEndPoint ep =
T.unlines $
catMaybes
[ epHeader
, Just $ funName <> " :: forall m. (Monad m) => "
<> (maybe "" (const $ apiHeaderType <> " -> ") apiHeader)
<> (maybe "" (const $ headerType ep <> " -> ") epHeader)
<> urlParamSig
<> (maybe "" (\t -> makeType t <> " -> ") $ aed_req ep)
<> "ApiCall m " <> (maybe "Unit" makeType $ aed_req ep) <> " " <> makeType (aed_resp ep)
, Just $ funName
<> " "
<> (maybe "" (const "apiHeaders ") apiHeader)
<> (maybe "" (const "endpointHeaders ") epHeader)
<> urlParams
<> (maybe "" (const "reqBody ") $ aed_req ep)
<> "runRequest = do"
, Just $ " let coreHeaders = [" <> T.intercalate ", " (map (headerPacker "apiHeaders") $ ad_headers ad) <> "]"
, Just $ " let fullHeaders = coreHeaders ++ [" <> T.intercalate ", " (map (headerPacker "endpointHeaders") $ aed_headers ep) <> "]"
, Just $ " let url = " <> T.intercalate " ++ \"/\" ++ " (map urlPacker routeInfo)
, Just $ " let method = " <> T.pack (show $ aed_verb ep)
, Just $ " let body = " <> (maybe "Nothing" (const "Just $ encodeJson reqBody") $ aed_req ep)
, Just $ " let req = { headers: fullHeaders, method: method, body: body, url: url }"
, Just $ " resp <- runRequest req"
, Just $ " return $ if (resp.statusCode /= 200) then Left \"Return code was not 200\" else decodeJson resp.body"
]
where
urlPacker (r, p) =
case r of
ApiRouteStatic t -> T.pack (show t)
ApiRouteDynamic _ -> "toPathPiece p" <> T.pack (show p) <> ""
headerPacker apiVar hdr =
"{ key: " <> T.pack (show $ ah_name hdr) <> ", value: " <> apiVar <> "." <> makeHeaderName hdr <> " }"
funName = unApiName (ad_name ad) <> capitalizeText (unEndpointName $ aed_name ep)
routeInfo = zip (aed_route ep) ([0..] :: [Int])
urlParams =
T.concat $ flip mapMaybe routeInfo $ \(r,p) ->
case r of
ApiRouteStatic _ -> Nothing
ApiRouteDynamic _ -> Just $ "p" <> T.pack (show p) <> " "
urlParamSig =
T.concat $ flip mapMaybe (aed_route ep) $ \r ->
case r of
ApiRouteStatic _ -> Nothing
ApiRouteDynamic ty -> Just (makeType ty <> " -> ")
epHeader =
case not (null (aed_headers ep)) of
True -> Just $ makeHeaderType (headerType ep) (aed_headers ep)
False -> Nothing
makeImport :: ModuleName -> T.Text
makeImport m =
"import qualified " <> printModuleName m <> " as " <> printModuleName m
makeTypeDef :: TypeDef -> T.Text
makeTypeDef td =
case td of
TypeDefEnum ed ->
makeEnumDef ed
TypeDefStruct sd ->
makeStructDef sd
decoderName :: TypeName -> T.Text
decoderName ty = "dec" <> unTypeName ty
encoderName :: TypeName -> T.Text
encoderName ty = "enc" <> unTypeName ty
eqName :: TypeName -> T.Text
eqName ty = "eq" <> unTypeName ty
showName :: TypeName -> T.Text
showName ty = "show" <> unTypeName ty
makeStructDef :: StructDef -> T.Text
makeStructDef sd =
T.unlines
[ "data " <> fullType
, " = " <> unTypeName (sd_name sd)
, " { " <> T.intercalate "\n , " (map makeStructField $ sd_fields sd)
, " }"
, ""
, "instance " <> eqName (sd_name sd) <> " :: "
<> tcPreds (sd_args sd) ["Eq"] <> "Eq (" <> fullType <> ") where "
<> "eq (" <> justType <> " a) (" <> justType <> " b) = "
<> T.intercalate " && " (map makeFieldEq (sd_fields sd))
, "instance " <> showName (sd_name sd) <> " :: "
<> tcPreds (sd_args sd) ["Show"] <> "Show (" <> fullType <> ") where "
<> "show (" <> justType <> " a) = " <> T.pack (show justType) <> " ++ \"{\" ++ "
<> T.intercalate " ++ \", \" ++ " (map makeFieldShow (sd_fields sd))
<> " ++ \"}\""
, "instance " <> encoderName (sd_name sd) <> " :: "
<> tcPreds (sd_args sd) ["EncodeJson"] <> "EncodeJson" <> " (" <> fullType <> ") where"
, " encodeJson (" <> unTypeName (sd_name sd) <> " objT) ="
, " " <> T.intercalate "\n ~> " (map makeToJsonFld $ sd_fields sd)
, " ~> jsonEmptyObject"
, "instance " <> decoderName (sd_name sd) <> " :: "
<> tcPreds (sd_args sd) ["DecodeJson"] <> "DecodeJson" <> " (" <> fullType <> ") where"
, " decodeJson jsonT = do"
, " objT <- decodeJson jsonT"
, " " <> T.intercalate "\n " (map makeFromJsonFld $ sd_fields sd)
, " pure $ " <> unTypeName (sd_name sd) <> " { " <> T.intercalate ", " (map makeFieldSetter $ sd_fields sd) <> " }"
]
where
makeFieldShow fld =
let name = unFieldName $ sf_name fld
in T.pack (show name) <> " ++ \": \" ++ show a." <> name
makeFieldEq fld =
let name = unFieldName $ sf_name fld
in "a." <> name <> " == " <> "b." <> name
makeFieldSetter fld =
let name = unFieldName $ sf_name fld
in name <> " : " <> "v" <> name
makeFromJsonFld fld =
let name = unFieldName $ sf_name fld
in case sf_type fld of
(TyCon q _) | q == bi_name tyMaybe ->
"v" <> name <> " <- objT .?? " <> T.pack (show name)
_ ->
"v" <> name <> " <- objT .? " <> T.pack (show name)
makeToJsonFld fld =
let name = unFieldName $ sf_name fld
in T.pack (show name) <> " " <> ":=" <> " objT." <> name
justType = unTypeName (sd_name sd)
fullType =
unTypeName (sd_name sd) <> " " <> T.intercalate " " (map unTypeVar $ sd_args sd)
makeStructField :: StructField -> T.Text
makeStructField sf =
unFieldName (sf_name sf) <> " :: " <> makeType (sf_type sf)
tcPreds :: [TypeVar] -> [T.Text] -> T.Text
tcPreds args tyClasses =
if null args
then ""
else let mkPred (TypeVar tv) =
T.intercalate "," $ flip map tyClasses $ \tyClass -> tyClass <> " " <> tv
in "(" <> T.intercalate "," (map mkPred args) <> ") => "
makeEnumDef :: EnumDef -> T.Text
makeEnumDef ed =
T.unlines
[ "data " <> fullType
, " = " <> T.intercalate "\n | " (map makeEnumChoice $ ed_choices ed)
, ""
, "instance " <> eqName (ed_name ed) <> " :: "
<> tcPreds (ed_args ed) ["Eq"] <> "Eq (" <> fullType <> ") where "
, " " <> T.intercalate "\n " (map makeChoiceEq $ ed_choices ed)
, " eq _ _ = false"
, "instance " <> showName (ed_name ed) <> " :: "
<> tcPreds (ed_args ed) ["Show"] <> "Show (" <> fullType <> ") where "
, " " <> T.intercalate "\n " (map makeChoiceShow $ ed_choices ed)
, "instance " <> encoderName (ed_name ed) <> " :: "
<> tcPreds (ed_args ed) ["EncodeJson"] <> "EncodeJson" <> " (" <> fullType <> ") where"
, " encodeJson x ="
, " case x of"
, " " <> T.intercalate "\n " (map mkToJsonChoice $ ed_choices ed)
, "instance " <> decoderName (ed_name ed) <> " :: "
<> tcPreds (ed_args ed) ["DecodeJson"] <> "DecodeJson" <> " (" <> fullType <> ") where"
, " decodeJson jsonT ="
, " decodeJson jsonT >>= \\objT -> "
, " " <> T.intercalate "\n <|> " (map mkFromJsonChoice $ ed_choices ed)
]
where
makeChoiceShow ec =
let constr = unChoiceName $ ec_name ec
in case ec_arg ec of
Nothing -> "show (" <> constr <> ") = " <> T.pack (show constr)
Just _ -> "show (" <> constr <> " a) = " <> T.pack (show constr) <> " ++ \" \" ++ show a"
makeChoiceEq ec =
let constr = unChoiceName $ ec_name ec
in case ec_arg ec of
Nothing -> "eq (" <> constr <> ") (" <> constr <> ") = true"
Just _ -> "eq (" <> constr <> " a) (" <> constr <> " b) = a == b"
mkFromJsonChoice ec =
let constr = unChoiceName $ ec_name ec
tag = camelTo2 '_' $ T.unpack constr
(op, opEnd) =
case ec_arg ec of
Nothing -> ("<$ (eatBool <$> (", "))")
Just _ -> ("<$>", "")
in "(" <> constr <> " " <> op <> " objT " <> ".?" <> " " <> T.pack (show tag) <> opEnd <> ")"
mkToJsonChoice ec =
let constr = unChoiceName $ ec_name ec
tag = camelTo2 '_' $ T.unpack constr
(argParam, argVal) =
case ec_arg ec of
Nothing -> ("", "true")
Just _ -> ("y", "y")
in constr <> " " <> argParam <> " -> "
<> " " <> T.pack (show tag) <> " " <> " := " <> " " <> argVal <> " ~> jsonEmptyObject"
fullType =
unTypeName (ed_name ed) <> " " <> T.intercalate " " (map unTypeVar $ ed_args ed)
makeEnumChoice :: EnumChoice -> T.Text
makeEnumChoice ec =
(unChoiceName $ ec_name ec) <> fromMaybe "" (fmap ((<>) " " . makeType) $ ec_arg ec)
makeType :: Type -> T.Text
makeType t =
case isBuiltIn t of
Nothing ->
case t of
TyVar (TypeVar x) -> x
TyCon qt args ->
let ty = makeQualTypeName qt
in case args of
[] -> ty
_ -> "(" <> ty <> " " <> T.intercalate " " (map makeType args) <> ")"
Just (bi, tvars)
| bi == tyString -> "String"
| bi == tyInt -> "Int"
| bi == tyBool -> "Boolean"
| bi == tyFloat -> "Number"
| bi == tyMaybe -> "(Maybe " <> T.intercalate " " (map makeType tvars) <> ")"
| bi == tyBytes -> "AsBase64"
| bi == tyList -> "(Array " <> T.intercalate " " (map makeType tvars) <> ")"
| bi == tyDateTime -> "DateTime"
| bi == tyTime -> "TimeOfDay"
| bi == tyDate -> "Day"
| otherwise ->
error $ "Haskell: Unimplemented built in type: " ++ show t
makeQualTypeName :: QualTypeName -> T.Text
makeQualTypeName qtn =
case unModuleName $ qtn_module qtn of
[] -> ty
_ -> printModuleName (qtn_module qtn) <> "." <> ty
where
ty = unTypeName $ qtn_type qtn
| agrafix/typed-wire | src/TW/CodeGen/PureScript.hs | mit | 12,260 | 0 | 22 | 4,012 | 3,955 | 1,963 | 1,992 | 264 | 6 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module Bead.Config.Parser where
import Control.Applicative
import Data.ByteString.Char8 (pack)
import Data.Maybe
import Data.String
import Data.Yaml
import Bead.Config.Configuration
#ifdef TEST
import Test.Tasty.TestSet
#endif
-- * JSON instances
instance FromJSON Config where
parseJSON (Object v) = Config
<$> v.: "user-actions-log"
<*> v.: "session-timeout"
#ifdef EmailEnabled
<*> v.: "hostname-for-emails"
<*> v.: "from-email-address"
#endif
<*> v.: "default-login-language"
<*> v.: "default-timezone"
<*> v.: "timezone-info-directory"
<*> v.: "max-upload-size"
<*> v.: "login-config"
#ifdef MYSQL
<*> v.: "mysql-config"
#else
<*> pure FilePersistConfig
#endif
parseJSON _ = error "Config is not parsed"
#ifdef SSO
instance FromJSON SSOLoginConfig where
parseJSON (Object v) = SSOLoginConfig
<$> (withDefault 5 <$> v .:? "timeout")
<*> (withDefault 4 <$> v .:? "threads")
<*> (withDefault "ldapsearch -Q -LLL" <$> v .:? "query-command")
<*> v .: "uid-key"
<*> v .: "name-key"
<*> v .: "email-key"
<*> (withDefault False <$> v .:? "developer")
where
withDefault = flip maybe id
parseJSON _ = error "SSO login config is not parsed"
#else
instance FromJSON StandaloneLoginConfig where
parseJSON (Object v) = StandaloneLoginConfig
<$> v .: "username-regexp"
<*> v .: "username-regexp-example"
parseJSON _ = error "Standalone login config is not parsed"
#endif
#ifdef MYSQL
instance FromJSON MySQLConfig where
parseJSON (Object v) = MySQLConfig
<$> v.: "database"
<*> v.: "hostname"
<*> v.: "port"
<*> v.: "username"
<*> v.: "password"
<*> v.: "pool-size"
parseJSON _ = error "MySQL config is not parsed"
#endif
parseYamlConfig :: String -> Either String Config
parseYamlConfig = decodeEither . pack
#ifdef TEST
parseTests = group "parserTests" $ do
#ifdef SSO
let sSOConfig1 = SSOLoginConfig 5 4 "ldapsearch -Q -LLL" "uid" "name" "email" False
assertEquals "SSO login config #1" (Right sSOConfig1)
(decodeEither $ fromString $ unlines [
"uid-key: 'uid'",
"name-key: 'name'",
"email-key: 'email'"
])
"SSO config is not parsed correctly"
let sSOConfig2 = SSOLoginConfig 5 4 "ldapsearch -Q" "uid" "name" "email" True
assertEquals "SSO login config #2" (Right sSOConfig2)
(decodeEither $ fromString $ unlines [
"timeout: 5",
"threads: 4",
"query-command: 'ldapsearch -Q'",
"uid-key: 'uid'",
"name-key: 'name'",
"email-key: 'email'",
"developer: yes"
])
"SSO config is not parsed correctly"
#else
let standaloneConfig1 = StandaloneLoginConfig "REGEXP" "REGEXP-EXAMPLE"
assertEquals "Standalone login config" (Right standaloneConfig1)
(decodeEither $ fromString $ unlines [
"username-regexp: 'REGEXP'",
"username-regexp-example: 'REGEXP-EXAMPLE'"
])
"Standalone config is not parsed correctly"
#endif
let configStr loginCfg persistCfg = unlines [
"user-actions-log: 'actions'",
"session-timeout: 10",
#ifdef EmailEnabled
"hostname-for-emails: 'www.google.com'",
"from-email-address: '[email protected]'",
#endif
"default-login-language: 'en'",
"default-timezone: 'Europe/Budapest'",
"timezone-info-directory: '/opt/some'",
"max-upload-size: 150",
"login-config:",
loginCfg,
#ifdef MYSQL
"mysql-config:",
persistCfg,
#endif
""
]
let config lcf pcfg = Config {
userActionLogFile = "actions"
, sessionTimeout = 10
#ifdef EmailEnabled
, emailHostname = "www.google.com"
, emailFromAddress = "[email protected]"
#endif
, defaultLoginLanguage = "en"
, defaultRegistrationTimezone = "Europe/Budapest"
, timeZoneInfoDirectory = "/opt/some"
, maxUploadSizeInKb = 150
, loginConfig = lcf
, persistConfig = pcfg
}
let persistConfig =
#ifdef MYSQL
MySQLConfig {
mySQLDbName = "bead-test-db"
, mySQLHost = "mysql.server.com"
, mySQLPort = 3308
, mySQLUser = "bead"
, mySQLPass = "secret"
, mySQLPoolSize = 30
}
#else
FilePersistConfig
#endif
let persistConfigStr =
#ifdef MYSQL
unlines [
" database: bead-test-db",
" hostname: mysql.server.com",
" port: 3308",
" username: bead",
" password: secret",
" pool-size: 30"
]
#else
""
#endif
#ifdef SSO
assertEquals "Config with SSO #1"
(Right $ config sSOConfig1 persistConfig)
(parseYamlConfig . fromString $ configStr (unlines [
" uid-key: 'uid'",
" name-key: 'name'",
" email-key: 'email'"
]) persistConfigStr)
"Config with SSO is not parsed correctly"
assertEquals "Config with SSO #2"
(Right $ config sSOConfig2 persistConfig)
(parseYamlConfig . fromString $ configStr (unlines [
" timeout: 5",
" threads: 4",
" query-command: 'ldapsearch -Q'",
" uid-key: 'uid'",
" name-key: 'name'",
" email-key: 'email'",
" developer: yes"
]) persistConfigStr)
"Config with SSO is not parsed correctly"
#else
assertEquals "Config with standalone"
(Right $ config standaloneConfig1 persistConfig)
(parseYamlConfig . fromString $ configStr
(unlines [
" username-regexp: 'REGEXP'",
" username-regexp-example: 'REGEXP-EXAMPLE'"])
persistConfigStr)
"Config with standalone is not parsed correctly"
#endif
#endif
| andorp/bead | src/Bead/Config/Parser.hs | bsd-3-clause | 5,778 | 0 | 25 | 1,532 | 928 | 513 | 415 | 27 | 1 |
module ShowRepoEvents where
import qualified Github.Issues.Events as Github
import Data.List (intercalate)
import Data.Maybe (fromJust)
main = do
possibleEvents <- Github.eventsForRepo "thoughtbot" "paperclip"
case possibleEvents of
(Left error) -> putStrLn $ "Error: " ++ show error
(Right events) -> do
putStrLn $ intercalate "\n" $ map formatEvent events
formatEvent event =
"Issue #" ++ issueNumber event ++ ": " ++
formatEvent' event (Github.eventType event)
where
formatEvent' event Github.Closed =
"closed on " ++ createdAt event ++ " by " ++ loginName event ++
withCommitId event (\commitId -> " in the commit " ++ commitId)
formatEvent' event Github.Reopened =
"reopened on " ++ createdAt event ++ " by " ++ loginName event
formatEvent' event Github.Subscribed =
loginName event ++ " is subscribed to receive notifications"
formatEvent' event Github.Unsubscribed =
loginName event ++ " is unsubscribed from notifications"
formatEvent' event Github.Merged =
"merged by " ++ loginName event ++ " on " ++ createdAt event ++
(withCommitId event $ \commitId -> " in the commit " ++ commitId)
formatEvent' event Github.Referenced =
withCommitId event $ \commitId ->
"referenced from " ++ commitId ++ " by " ++ loginName event
formatEvent' event Github.Mentioned =
loginName event ++ " was mentioned in the issue's body"
formatEvent' event Github.Assigned =
"assigned to " ++ loginName event ++ " on " ++ createdAt event
loginName = Github.githubOwnerLogin . Github.eventActor
createdAt = show . Github.fromDate . Github.eventCreatedAt
withCommitId event f = maybe "" f (Github.eventCommitId event)
issueNumber = show . Github.issueNumber . fromJust . Github.eventIssue
| jwiegley/github | samples/Issues/Events/ShowRepoEvents.hs | bsd-3-clause | 1,777 | 0 | 14 | 352 | 487 | 241 | 246 | 36 | 8 |
module Opaleye.Column (module Opaleye.Column,
Column,
Nullable,
unsafeCoerce,
unsafeCoerceColumn,
unsafeCompositeField) where
import Opaleye.Internal.Column (Column, Nullable, unsafeCoerce, unsafeCoerceColumn,
unsafeCompositeField)
import qualified Opaleye.Internal.Column as C
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.PGTypes as T
import Prelude hiding (null)
-- | A NULL of any type
null :: Column (Nullable a)
null = C.Column (HPQ.ConstExpr HPQ.NullLit)
isNull :: Column (Nullable a) -> Column T.PGBool
isNull = C.unOp HPQ.OpIsNull
-- | If the @Column (Nullable a)@ is NULL then return the @Column b@
-- otherwise map the underlying @Column a@ using the provided
-- function.
--
-- The Opaleye equivalent of the 'Data.Maybe.maybe' function.
matchNullable :: Column b -> (Column a -> Column b) -> Column (Nullable a)
-> Column b
matchNullable replacement f x = C.unsafeIfThenElse (isNull x) replacement
(f (unsafeCoerceColumn x))
-- | If the @Column (Nullable a)@ is NULL then return the provided
-- @Column a@ otherwise return the underlying @Column a@.
--
-- The Opaleye equivalent of the 'Data.Maybe.fromMaybe' function
fromNullable :: Column a -> Column (Nullable a) -> Column a
fromNullable = flip matchNullable id
-- | The Opaleye equivalent of 'Data.Maybe.Just'
toNullable :: Column a -> Column (Nullable a)
toNullable = unsafeCoerceColumn
-- | If the argument is 'Data.Maybe.Nothing' return NULL otherwise return the
-- provided value coerced to a nullable type.
maybeToNullable :: Maybe (Column a) -> Column (Nullable a)
maybeToNullable = maybe null toNullable
-- | Cast a column to any other type. This is safe for some conversions such as uuid to text.
unsafeCast :: String -> C.Column a -> Column b
unsafeCast = mapColumn . HPQ.CastExpr
where
mapColumn :: (HPQ.PrimExpr -> HPQ.PrimExpr) -> Column c -> Column a
mapColumn primExpr c = C.Column (primExpr (C.unColumn c))
| benkolera/haskell-opaleye | src/Opaleye/Column.hs | bsd-3-clause | 2,189 | 0 | 12 | 543 | 449 | 244 | 205 | 30 | 1 |
-- |
-- Module: Network.FastIRC.ServerSet
-- Copyright: (c) 2010 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
-- Stability: alpha
--
-- Functions for dealing with sets of IRC servers. Note that servers
-- are compared case-insensitively.
module Network.FastIRC.ServerSet
( -- * The server set type
ServerSet,
-- * Manipulation
addServer,
delServer,
emptyServers,
isServer,
-- * Conversion
serversFromList,
serversToList
)
where
import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S
import Data.Char
import Network.FastIRC.Types
-- | A set of servers. This data type uses 'S.Set' internally, but
-- the strings are handled case-insensitively.
newtype ServerSet = ServerSet (S.Set ServerName)
-- | Empty set of servers.
emptyServers :: ServerSet
emptyServers = ServerSet S.empty
-- | Add a server to a 'ServerSet'.
addServer :: ServerName -> ServerSet -> ServerSet
addServer s (ServerSet ss) = ServerSet $ S.insert (B.map toLower s) ss
-- | Remove a server from a 'ServerSet'.
delServer :: ServerName -> ServerSet -> ServerSet
delServer s (ServerSet ss) = ServerSet $ S.delete (B.map toLower s) ss
-- | Check whether specified server is in the set.
isServer :: ServerName -> ServerSet -> Bool
isServer s (ServerSet ss) = S.member (B.map toLower s) ss
-- | Build from list.
serversFromList :: [ServerName] -> ServerSet
serversFromList = ServerSet . S.fromList
-- | Convert to list.
serversToList :: ServerSet -> [ServerName]
serversToList (ServerSet ss) = S.toList ss
| chrisdone/hulk | fastirc-0.2.0/Network/FastIRC/ServerSet.hs | bsd-3-clause | 1,603 | 0 | 9 | 305 | 309 | 179 | 130 | 26 | 1 |
-- This is a modification of the calendar program described in section 4.5
-- of Bird and Wadler's ``Introduction to functional programming'', with
-- two ways of printing the calendar ... as in B+W, or like UNIX `cal':
-- Run using: calFor "1996"
-- or: putStr (calendar 1996)
-- or: putStr (cal 1996)
module Calendar( calendar, cal, calFor, calProg ) where
import Gofer
import List(zip4)
import IO(hPutStr,stderr)
import System( getArgs, getProgName, exitWith, ExitCode(..) )
import Char (digitToInt, isDigit)
-- Picture handling:
infixr 5 `above`, `beside`
type Picture = [[Char]]
height, width :: Picture -> Int
height p = length p
width p = length (head p)
above, beside :: Picture -> Picture -> Picture
above = (++)
beside = zipWith (++)
stack, spread :: [Picture] -> Picture
stack = foldr1 above
spread = foldr1 beside
empty :: (Int,Int) -> Picture
empty (h,w) = replicate h (replicate w ' ')
block, blockT :: Int -> [Picture] -> Picture
block n = stack . map spread . groupsOf n
blockT n = spread . map stack . groupsOf n
groupsOf :: Int -> [a] -> [[a]]
groupsOf n [] = []
groupsOf n xs = take n xs : groupsOf n (drop n xs)
lframe :: (Int,Int) -> Picture -> Picture
lframe (m,n) p = (p `beside` empty (h,n-w)) `above` empty (m-h,n)
where h = height p
w = width p
-- Information about the months in a year:
monthLengths year = [31,feb,31,30,31,30,31,31,30,31,30,31]
where feb | leap year = 29
| otherwise = 28
leap year = if year`mod`100 == 0 then year`mod`400 == 0
else year`mod`4 == 0
monthNames = ["January","February","March","April",
"May","June","July","August",
"September","October","November","December"]
jan1st year = (year + last`div`4 - last`div`100 + last`div`400) `mod` 7
where last = year - 1
firstDays year = take 12
(map (`mod`7)
(scanl (+) (jan1st year) (monthLengths year)))
-- Producing the information necessary for one month:
dates fd ml = map (date ml) [1-fd..42-fd]
where date ml d | d<1 || ml<d = [" "]
| otherwise = [rjustify 3 (show d)]
-- The original B+W calendar:
calendar :: Int -> String
calendar = unlines . block 3 . map picture . months
where picture (mn,yr,fd,ml) = title mn yr `above` table fd ml
title mn yr = lframe (2,25) [mn ++ " " ++ show yr]
table fd ml = lframe (8,25)
(daynames `beside` entries fd ml)
daynames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
entries fd ml = blockT 7 (dates fd ml)
months year = zip4 monthNames
(replicate 12 year)
(firstDays year)
(monthLengths year)
-- In a format somewhat closer to UNIX cal:
cal year = unlines (banner year `above` body year)
where banner yr = [cjustify 75 (show yr)] `above` empty (1,75)
body = block 3 . map (pad . pic) . months
pic (mn,fd,ml) = title mn `above` table fd ml
pad p = (side`beside`p`beside`side)`above`end
side = empty (8,2)
end = empty (1,25)
title mn = [cjustify 21 mn]
table fd ml = daynames `above` entries fd ml
daynames = [" Su Mo Tu We Th Fr Sa"]
entries fd ml = block 7 (dates fd ml)
months year = zip3 monthNames
(firstDays year)
(monthLengths year)
-- For a standalone calendar program:
--
-- To use this with "runhugs" on Unix:
--
-- cat >cal
-- #! /usr/local/bin/runhugs
--
-- > module Main( main ) where
-- > import Calendar
-- > main = calProg
-- <ctrl-D>
--
-- chmod 755 cal
--
-- ./cal 1997
calProg = do
args <- getArgs
case args of
[year] -> calFor year
_ -> do
putStr "Usage: "
getProgName >>= putStr
putStrLn " year"
exitWith (ExitFailure 1)
calFor year | illFormed = hPutStr stderr "Bad argument" >>
exitWith (ExitFailure 1)
| otherwise = putStr (cal yr)
where illFormed = null ds || not (null rs)
(ds,rs) = span isDigit year
yr = atoi ds
atoi s = foldl (\a d -> 10*a+d) 0 (map digitToInt s)
-- End of calendar program
| OS2World/DEV-UTIL-HUGS | demos/Calendar.hs | bsd-3-clause | 4,964 | 5 | 14 | 1,957 | 1,556 | 854 | 702 | 87 | 2 |
module C3 (module D, module C3) where
import D3 as D hiding (anotherFun)
anotherFun (x:xs) = sq x + anotherFun xs
anotherFun [] = 0
| RefactoringTools/HaRe | old/testing/duplication/C3_TokOut.hs | bsd-3-clause | 144 | 0 | 7 | 37 | 60 | 35 | 25 | 4 | 1 |
{-# LANGUAGE GADTs, TypeOperators, PolyKinds #-}
module T16074 where
import GHC.Types
data a :~: b where Refl :: a :~: a
foo :: TYPE a :~: TYPE b
foo = Refl
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/T16074.hs | bsd-3-clause | 161 | 0 | 6 | 35 | 46 | 27 | 19 | 6 | 1 |
module RecNat where
{- imports will be added for the PointlessP librasies -}
recNat :: Int -> (Int -> a -> a) -> a -> a
recNat 0 f z = z
recNat n f z = f (n-1) (recNat (n-1) f z)
--Programatica parser can't read:
-- recNat (n+1) f z = f n (recNat n f z)
-- the whole expression will be selected for translation.
-- note that recNat can be converted into a paramorphism because
-- the 2nd and 3rd arguments don't have free variables
double = \n -> recNat n (\pred rec -> succ (succ rec)) 0
| kmate/HaRe | old/testing/pointwiseToPointfree/RecNat.hs | bsd-3-clause | 511 | 0 | 11 | 124 | 127 | 70 | 57 | 5 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash, UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Word
-- Copyright : (c) The University of Glasgow, 1997-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Sized unsigned integral types: 'Word', 'Word8', 'Word16', 'Word32', and
-- 'Word64'.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
-- #hide
module GHC.Word (
Word(..), Word8(..), Word16(..), Word32(..), Word64(..),
uncheckedShiftL64#,
uncheckedShiftRL64#
) where
import Data.Bits
#if WORD_SIZE_IN_BITS < 64
import GHC.IntWord64
#endif
import GHC.HasteWordInt
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Show
import GHC.Err
import GHC.Float () -- for RealFrac methods
------------------------------------------------------------------------
-- type Word8
------------------------------------------------------------------------
-- Word8 is represented in the same way as Word. Operations may assume
-- and must ensure that it holds only values from its logical range.
#if __GLASGOW_HASKELL__ >= 706
data {-# CTYPE "HsWord8" #-} Word8 = W8# Word# deriving (Eq, Ord)
#else
data Word8 = W8# Word# deriving (Eq, Ord)
#endif
-- ^ 8-bit unsigned integer type
instance Show Word8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word8 where
(W8# x#) + (W8# y#) = W8# (narrow8Word# (x# `plusWord#` y#))
(W8# x#) - (W8# y#) = W8# (narrow8Word# (x# `minusWord#` y#))
(W8# x#) * (W8# y#) = W8# (narrow8Word# (x# `timesWord#` y#))
negate (W8# x#) = W8# (narrow8Word# (i2w (negateInt# (w2i x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W8# (narrow8Word# (integerToWord i))
instance Real Word8 where
toRational x = toInteger x % 1
instance Enum Word8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word8"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word8)
= W8# (i2w i#)
| otherwise = toEnumError "Word8" i (minBound::Word8, maxBound::Word8)
fromEnum (W8# x#) = I# (w2i x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word8 where
quot (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
div (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W8# x#) y@(W8# y#)
| y /= 0 = W8# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W8# x#) y@(W8# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W8# q, W8# r)
| otherwise = divZeroError
divMod (W8# x#) y@(W8# y#)
| y /= 0 = (W8# (x# `quotWord#` y#), W8# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W8# x#) = smallInteger (w2i x#)
instance Bounded Word8 where
minBound = 0
maxBound = 0xFF
instance Ix Word8 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word8 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W8# x#) .&. (W8# y#) = W8# (x# `and#` y#)
(W8# x#) .|. (W8# y#) = W8# (x# `or#` y#)
(W8# x#) `xor` (W8# y#) = W8# (x# `xor#` y#)
complement (W8# x#) = W8# (x# `xor#` mb#)
where !(W8# mb#) = maxBound
(W8# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W8# (narrow8Word# (x# `shiftL#` i#))
| otherwise = W8# (x# `shiftRL#` negateInt# i#)
(W8# x#) `shiftL` (I# i#) = W8# (narrow8Word# (x# `shiftL#` i#))
(W8# x#) `unsafeShiftL` (I# i#) =
W8# (narrow8Word# (x# `uncheckedShiftL#` i#))
(W8# x#) `shiftR` (I# i#) = W8# (x# `shiftRL#` i#)
(W8# x#) `unsafeShiftR` (I# i#) = W8# (x# `uncheckedShiftRL#` i#)
(W8# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W8# x#
| otherwise = W8# (narrow8Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (8# -# i'#))))
where
!i'# = w2i (i2w i# `and#` 7##)
bitSize _ = 8
isSigned _ = False
popCount (W8# x#) = I# (w2i (popCnt8# x#))
bit = bitDefault
testBit = testBitDefault
{-# RULES
"fromIntegral/Word8->Word8" fromIntegral = id :: Word8 -> Word8
"fromIntegral/Word8->Integer" fromIntegral = toInteger :: Word8 -> Integer
"fromIntegral/a->Word8" fromIntegral = \x -> case fromIntegral x of W# x# -> W8# (narrow8Word# x#)
"fromIntegral/Word8->a" fromIntegral = \(W8# x#) -> fromIntegral (W# x#)
#-}
{-# RULES
"properFraction/Float->(Word8,Float)"
forall x. properFraction (x :: Float) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y) }
"truncate/Float->Word8"
forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word8) (truncate x)
"floor/Float->Word8"
forall x. floor (x :: Float) = (fromIntegral :: Int -> Word8) (floor x)
"ceiling/Float->Word8"
forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word8) (ceiling x)
"round/Float->Word8"
forall x. round (x :: Float) = (fromIntegral :: Int -> Word8) (round x)
#-}
{-# RULES
"properFraction/Double->(Word8,Double)"
forall x. properFraction (x :: Double) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word8) n, y) }
"truncate/Double->Word8"
forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word8) (truncate x)
"floor/Double->Word8"
forall x. floor (x :: Double) = (fromIntegral :: Int -> Word8) (floor x)
"ceiling/Double->Word8"
forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word8) (ceiling x)
"round/Double->Word8"
forall x. round (x :: Double) = (fromIntegral :: Int -> Word8) (round x)
#-}
------------------------------------------------------------------------
-- type Word16
------------------------------------------------------------------------
-- Word16 is represented in the same way as Word. Operations may assume
-- and must ensure that it holds only values from its logical range.
#if __GLASGOW_HASKELL__ >= 706
data {-# CTYPE "HsWord16" #-} Word16 = W16# Word# deriving (Eq, Ord)
#else
data Word16 = W16# Word# deriving (Eq, Ord)
#endif
-- ^ 16-bit unsigned integer type
instance Show Word16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Word16 where
(W16# x#) + (W16# y#) = W16# (narrow16Word# (x# `plusWord#` y#))
(W16# x#) - (W16# y#) = W16# (narrow16Word# (x# `minusWord#` y#))
(W16# x#) * (W16# y#) = W16# (narrow16Word# (x# `timesWord#` y#))
negate (W16# x#) = W16# (narrow16Word# (i2w (negateInt# (w2i x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W16# (narrow16Word# (integerToWord i))
instance Real Word16 where
toRational x = toInteger x % 1
instance Enum Word16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word16"
toEnum i@(I# i#)
| i >= 0 && i <= fromIntegral (maxBound::Word16)
= W16# (i2w i#)
| otherwise = toEnumError "Word16" i (minBound::Word16, maxBound::Word16)
fromEnum (W16# x#) = I# (w2i x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Word16 where
quot (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
div (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W16# x#) y@(W16# y#)
| y /= 0 = W16# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W16# x#) y@(W16# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W16# q, W16# r)
| otherwise = divZeroError
divMod (W16# x#) y@(W16# y#)
| y /= 0 = (W16# (x# `quotWord#` y#), W16# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W16# x#) = smallInteger (w2i x#)
instance Bounded Word16 where
minBound = 0
maxBound = 0xFFFF
instance Ix Word16 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Word16 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W16# x#) .&. (W16# y#) = W16# (x# `and#` y#)
(W16# x#) .|. (W16# y#) = W16# (x# `or#` y#)
(W16# x#) `xor` (W16# y#) = W16# (x# `xor#` y#)
complement (W16# x#) = W16# (x# `xor#` mb#)
where !(W16# mb#) = maxBound
(W16# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W16# (narrow16Word# (x# `shiftL#` i#))
| otherwise = W16# (x# `shiftRL#` negateInt# i#)
(W16# x#) `shiftL` (I# i#) = W16# (narrow16Word# (x# `shiftL#` i#))
(W16# x#) `unsafeShiftL` (I# i#) =
W16# (narrow16Word# (x# `uncheckedShiftL#` i#))
(W16# x#) `shiftR` (I# i#) = W16# (x# `shiftRL#` i#)
(W16# x#) `unsafeShiftR` (I# i#) = W16# (x# `uncheckedShiftRL#` i#)
(W16# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W16# x#
| otherwise = W16# (narrow16Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (16# -# i'#))))
where
!i'# = w2i (i2w i# `and#` 15##)
bitSize _ = 16
isSigned _ = False
popCount (W16# x#) = I# (w2i (popCnt16# x#))
bit = bitDefault
testBit = testBitDefault
{-# RULES
"fromIntegral/Word8->Word16" fromIntegral = \(W8# x#) -> W16# x#
"fromIntegral/Word16->Word16" fromIntegral = id :: Word16 -> Word16
"fromIntegral/Word16->Integer" fromIntegral = toInteger :: Word16 -> Integer
"fromIntegral/a->Word16" fromIntegral = \x -> case fromIntegral x of W# x# -> W16# (narrow16Word# x#)
"fromIntegral/Word16->a" fromIntegral = \(W16# x#) -> fromIntegral (W# x#)
#-}
{-# RULES
"properFraction/Float->(Word16,Float)"
forall x. properFraction (x :: Float) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y) }
"truncate/Float->Word16"
forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word16) (truncate x)
"floor/Float->Word16"
forall x. floor (x :: Float) = (fromIntegral :: Int -> Word16) (floor x)
"ceiling/Float->Word16"
forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word16) (ceiling x)
"round/Float->Word16"
forall x. round (x :: Float) = (fromIntegral :: Int -> Word16) (round x)
#-}
{-# RULES
"properFraction/Double->(Word16,Double)"
forall x. properFraction (x :: Double) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word16) n, y) }
"truncate/Double->Word16"
forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word16) (truncate x)
"floor/Double->Word16"
forall x. floor (x :: Double) = (fromIntegral :: Int -> Word16) (floor x)
"ceiling/Double->Word16"
forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word16) (ceiling x)
"round/Double->Word16"
forall x. round (x :: Double) = (fromIntegral :: Int -> Word16) (round x)
#-}
------------------------------------------------------------------------
-- type Word32
------------------------------------------------------------------------
-- Word32 is represented in the same way as Word.
#if WORD_SIZE_IN_BITS > 32
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
-- We can use rewrite rules for the RealFrac methods
{-# RULES
"properFraction/Float->(Word32,Float)"
forall x. properFraction (x :: Float) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y) }
"truncate/Float->Word32"
forall x. truncate (x :: Float) = (fromIntegral :: Int -> Word32) (truncate x)
"floor/Float->Word32"
forall x. floor (x :: Float) = (fromIntegral :: Int -> Word32) (floor x)
"ceiling/Float->Word32"
forall x. ceiling (x :: Float) = (fromIntegral :: Int -> Word32) (ceiling x)
"round/Float->Word32"
forall x. round (x :: Float) = (fromIntegral :: Int -> Word32) (round x)
#-}
{-# RULES
"properFraction/Double->(Word32,Double)"
forall x. properFraction (x :: Double) =
case properFraction x of {
(n, y) -> ((fromIntegral :: Int -> Word32) n, y) }
"truncate/Double->Word32"
forall x. truncate (x :: Double) = (fromIntegral :: Int -> Word32) (truncate x)
"floor/Double->Word32"
forall x. floor (x :: Double) = (fromIntegral :: Int -> Word32) (floor x)
"ceiling/Double->Word32"
forall x. ceiling (x :: Double) = (fromIntegral :: Int -> Word32) (ceiling x)
"round/Double->Word32"
forall x. round (x :: Double) = (fromIntegral :: Int -> Word32) (round x)
#-}
#endif
#if __GLASGOW_HASKELL__ >= 706
data {-# CTYPE "HsWord32" #-} Word32 = W32# Word# deriving (Eq, Ord)
#else
data Word32 = W32# Word# deriving (Eq, Ord)
#endif
-- ^ 32-bit unsigned integer type
instance Num Word32 where
(W32# x#) + (W32# y#) = W32# (narrow32Word# (x# `plusWord#` y#))
(W32# x#) - (W32# y#) = W32# (narrow32Word# (x# `minusWord#` y#))
(W32# x#) * (W32# y#) = W32# (narrow32Word# (x# `timesWord#` y#))
negate (W32# x#) = W32# (narrow32Word# (i2w (negateInt# (w2i x#))))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W32# (narrow32Word# (integerToWord i))
instance Enum Word32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word32"
toEnum i@(I# i#)
| i >= 0
#if WORD_SIZE_IN_BITS > 32
&& i <= fromIntegral (maxBound::Word32)
#endif
= W32# (i2w i#)
| otherwise = toEnumError "Word32" i (minBound::Word32, maxBound::Word32)
#if WORD_SIZE_IN_BITS == 32
fromEnum x@(W32# x#)
| x <= fromIntegral (maxBound::Int)
= I# (w2i x#)
| otherwise = fromEnumError "Word32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
#else
fromEnum (W32# x#) = I# (w2i x#)
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
#endif
instance Integral Word32 where
quot (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
rem (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
div (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `quotWord#` y#)
| otherwise = divZeroError
mod (W32# x#) y@(W32# y#)
| y /= 0 = W32# (x# `remWord#` y#)
| otherwise = divZeroError
quotRem (W32# x#) y@(W32# y#)
| y /= 0 = case x# `quotRemWord#` y# of
(# q, r #) ->
(W32# q, W32# r)
| otherwise = divZeroError
divMod (W32# x#) y@(W32# y#)
| y /= 0 = (W32# (x# `quotWord#` y#), W32# (x# `remWord#` y#))
| otherwise = divZeroError
toInteger (W32# x#)
#if WORD_SIZE_IN_BITS == 32
| isTrue# (i# >=# 0#) = smallInteger i#
| otherwise = wordToInteger x#
where
!i# = w2i x#
#else
= smallInteger (w2i x#)
#endif
instance Bits Word32 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W32# x#) .&. (W32# y#) = W32# (x# `and#` y#)
(W32# x#) .|. (W32# y#) = W32# (x# `or#` y#)
(W32# x#) `xor` (W32# y#) = W32# (x# `xor#` y#)
complement (W32# x#) = W32# (x# `xor#` mb#)
where !(W32# mb#) = maxBound
(W32# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W32# (narrow32Word# (x# `shiftL#` i#))
| otherwise = W32# (x# `shiftRL#` negateInt# i#)
(W32# x#) `shiftL` (I# i#) = W32# (narrow32Word# (x# `shiftL#` i#))
(W32# x#) `unsafeShiftL` (I# i#) =
W32# (narrow32Word# (x# `uncheckedShiftL#` i#))
(W32# x#) `shiftR` (I# i#) = W32# (x# `shiftRL#` i#)
(W32# x#) `unsafeShiftR` (I# i#) = W32# (x# `uncheckedShiftRL#` i#)
(W32# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W32# x#
| otherwise = W32# (narrow32Word# ((x# `uncheckedShiftL#` i'#) `or#`
(x# `uncheckedShiftRL#` (32# -# i'#))))
where
!i'# = w2i (i2w i# `and#` 31##)
bitSize _ = 32
isSigned _ = False
popCount (W32# x#) = I# (w2i (popCnt32# x#))
bit = bitDefault
testBit = testBitDefault
{-# RULES
"fromIntegral/Word8->Word32" fromIntegral = \(W8# x#) -> W32# x#
"fromIntegral/Word16->Word32" fromIntegral = \(W16# x#) -> W32# x#
"fromIntegral/Word32->Word32" fromIntegral = id :: Word32 -> Word32
"fromIntegral/Word32->Integer" fromIntegral = toInteger :: Word32 -> Integer
"fromIntegral/a->Word32" fromIntegral = \x -> case fromIntegral x of W# x# -> W32# (narrow32Word# x#)
"fromIntegral/Word32->a" fromIntegral = \(W32# x#) -> fromIntegral (W# x#)
#-}
instance Show Word32 where
#if WORD_SIZE_IN_BITS < 33
showsPrec p x = showsPrec p (toInteger x)
#else
showsPrec p x = showsPrec p (fromIntegral x :: Int)
#endif
instance Real Word32 where
toRational x = toInteger x % 1
instance Bounded Word32 where
minBound = 0
maxBound = 0xFFFFFFFF
instance Ix Word32 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word32 where
#if WORD_SIZE_IN_BITS < 33
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
#else
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
#endif
------------------------------------------------------------------------
-- type Word64
------------------------------------------------------------------------
#if __GLASGOW_HASKELL__ >= 706
data {-# CTYPE "HsWord64" #-} Word64 = W64# Word64#
#else
data Word64 = W64# Word64#
#endif
-- ^ 64-bit unsigned integer type
instance Eq Word64 where
(W64# x#) == (W64# y#) = x# `eqWord64#` y#
(W64# x#) /= (W64# y#) = x# `neWord64#` y#
instance Ord Word64 where
(W64# x#) < (W64# y#) = x# `ltWord64#` y#
(W64# x#) <= (W64# y#) = x# `leWord64#` y#
(W64# x#) > (W64# y#) = x# `gtWord64#` y#
(W64# x#) >= (W64# y#) = x# `geWord64#` y#
instance Num Word64 where
(W64# x#) + (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `plusInt64#` word64ToInt64# y#))
(W64# x#) - (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `minusInt64#` word64ToInt64# y#))
(W64# x#) * (W64# y#) = W64# (int64ToWord64# (word64ToInt64# x# `timesInt64#` word64ToInt64# y#))
negate (W64# x#) = W64# (int64ToWord64# (negateInt64# (word64ToInt64# x#)))
abs x = x
signum 0 = 0
signum _ = 1
fromInteger i = W64# (integerToWord64 i)
instance Enum Word64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word64"
toEnum i@(I# i#)
| i >= 0 = W64# (wordToWord64# (i2w i#))
| otherwise = toEnumError "Word64" i (minBound::Word64, maxBound::Word64)
fromEnum x@(W64# x#)
| x <= fromIntegral (maxBound::Int)
= I# (w2i (word64ToWord# x#))
| otherwise = fromEnumError "Word64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Word64 where
quot (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
rem (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
div (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `quotWord64#` y#)
| otherwise = divZeroError
mod (W64# x#) y@(W64# y#)
| y /= 0 = W64# (x# `remWord64#` y#)
| otherwise = divZeroError
quotRem (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
| otherwise = divZeroError
divMod (W64# x#) y@(W64# y#)
| y /= 0 = (W64# (x# `quotWord64#` y#), W64# (x# `remWord64#` y#))
| otherwise = divZeroError
toInteger (W64# x#) = word64ToInteger x#
instance Bits Word64 where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W64# x#) .&. (W64# y#) = W64# (x# `and64#` y#)
(W64# x#) .|. (W64# y#) = W64# (x# `or64#` y#)
(W64# x#) `xor` (W64# y#) = W64# (x# `xor64#` y#)
complement (W64# x#) = W64# (not64# x#)
(W64# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W64# (x# `shiftL64#` i#)
| otherwise = W64# (x# `shiftRL64#` negateInt# i#)
(W64# x#) `shiftL` (I# i#) = W64# (x# `shiftL64#` i#)
(W64# x#) `unsafeShiftL` (I# i#) = W64# (x# `uncheckedShiftL64#` i#)
(W64# x#) `shiftR` (I# i#) = W64# (x# `shiftRL64#` i#)
(W64# x#) `unsafeShiftR` (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)
(W64# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W64# x#
| otherwise = W64# ((x# `uncheckedShiftL64#` i'#) `or64#`
(x# `uncheckedShiftRL64#` (64# -# i'#)))
where
!i'# = w2i (i2w i# `and#` 63##)
bitSize _ = 64
isSigned _ = False
popCount = popcnt
bit = bitDefault
testBit = testBitDefault
-- Count bits manually, since we don't have any appropriate primops available
-- when the host machine is 64 bit and we're compiling to 32. :(
popcnt :: Word64 -> Int
popcnt 0 = 0
popcnt x | x .&. 1 == 1 = 1 + popcnt (x `shiftR` 1)
| otherwise = popcnt (x `shiftR` 1)
-- give the 64-bit shift operations the same treatment as the 32-bit
-- ones (see GHC.Base), namely we wrap them in tests to catch the
-- cases when we're shifting more than 64 bits to avoid unspecified
-- behaviour in the C shift operations.
shiftL64#, shiftRL64# :: Word64# -> Int# -> Word64#
a `shiftL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0##
| otherwise = a `uncheckedShiftL64#` b
a `shiftRL64#` b | isTrue# (b >=# 64#) = wordToWord64# 0##
| otherwise = a `uncheckedShiftRL64#` b
{-# RULES
"fromIntegral/Int->Word64" fromIntegral = \(I# x#) -> W64# (int64ToWord64# (intToInt64# x#))
"fromIntegral/Word->Word64" fromIntegral = \(W# x#) -> W64# (wordToWord64# x#)
"fromIntegral/Word64->Int" fromIntegral = \(W64# x#) -> I# (w2i (word64ToWord# x#))
"fromIntegral/Word64->Word" fromIntegral = \(W64# x#) -> W# (word64ToWord# x#)
"fromIntegral/Word64->Word64" fromIntegral = id :: Word64 -> Word64
#-}
instance Show Word64 where
showsPrec p x = showsPrec p (toInteger x)
instance Real Word64 where
toRational x = toInteger x % 1
instance Bounded Word64 where
minBound = 0
maxBound = 0xFFFFFFFFFFFFFFFF
instance Ix Word64 where
range (m,n) = [m..n]
unsafeIndex (m,_) i = fromIntegral (i - m)
inRange (m,n) i = m <= i && i <= n
instance Read Word64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
| beni55/haste-compiler | libraries/ghc-7.8/base/GHC/Word.hs | bsd-3-clause | 26,222 | 0 | 15 | 8,340 | 7,088 | 3,689 | 3,399 | 457 | 1 |
-- | Functionality common to all repo kinds
module Distribution.Client.Mirror.Repo.Util (
readIndex
, provideAuthInfo
) where
-- stdlib
import Control.Exception
import Control.Monad
import Data.Time
import Data.Time.Clock.POSIX
import Network.URI hiding (authority)
import System.FilePath
import System.IO
import qualified Data.ByteString.Lazy as BS
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
-- Cabal
import Distribution.Package
-- hackage
import Distribution.Client hiding (provideAuthInfo)
import Distribution.Client.Index as PackageIndex (read)
import Distribution.Client.Mirror.Session
import Distribution.Server.Users.Types (UserId(..), UserName(UserName))
import qualified Distribution.Server.Util.GZip as GZip
readIndex :: String -- ^ Description of the repository (for error messages)
-> FilePath -- ^ Location of the downloaded index
-> MirrorSession [PkgIndexInfo]
readIndex repDescr indexFile = do
res <- liftIO $ withFile indexFile ReadMode $ \hnd ->
evaluate . PackageIndex.read selectDetails isCabalFile
. decompressIfNecessary
=<< BS.hGetContents hnd
case res of
Left err -> mirrorError (ParseEntityError EntityIndex repDescr err)
Right pkgs -> return pkgs
where
selectDetails :: PackageId -> Tar.Entry -> PkgIndexInfo
selectDetails pkgid entry =
PkgIndexInfo
pkgid
(Just time)
(if null username then Nothing else Just (UserName username))
(if userid == 0 then Nothing else Just (UserId userid))
where
time = epochTimeToUTC (Tar.entryTime entry)
username = Tar.ownerName (Tar.entryOwnership entry)
userid = Tar.ownerId (Tar.entryOwnership entry)
decompressIfNecessary :: BS.ByteString -> BS.ByteString
decompressIfNecessary =
if takeExtension indexFile == ".gz"
then GZip.decompressNamed indexFile
else id
epochTimeToUTC :: Tar.EpochTime -> UTCTime
epochTimeToUTC = posixSecondsToUTCTime . realToFrac
isCabalFile :: FilePath -> Bool
isCabalFile fp = takeExtension fp == ".cabal"
provideAuthInfo :: URI -> URI -> String -> IO (Maybe (String, String))
provideAuthInfo repoURI uri _realm = return go
where
go :: Maybe (String, String)
go = do
guard $ hostName uri == hostName repoURI
authority <- uriAuthority repoURI
let (username, ':':passwd0) = break (==':') (uriUserInfo authority)
passwd = takeWhile (/='@') passwd0
guard $ not (null username)
guard $ not (null passwd)
return (username, passwd)
hostName :: URI -> Maybe String
hostName = fmap uriRegName . uriAuthority
| ocharles/hackage-server | Distribution/Client/Mirror/Repo/Util.hs | bsd-3-clause | 2,747 | 0 | 14 | 619 | 719 | 392 | 327 | 62 | 5 |
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
-------------------------------------------------------------------------------
--
-- | Break Arrays in the IO monad
--
-- Entries in the array are Word sized Conceptually, a zero-indexed IOArray of
-- Bools, initially False. They're represented as Words with 0==False, 1==True.
-- They're used to determine whether GHCI breakpoints are on or off.
--
-- (c) The University of Glasgow 2007
--
-------------------------------------------------------------------------------
module BreakArray
(
BreakArray
#ifdef GHCI
(BA) -- constructor is exported only for ByteCodeGen
#endif
, newBreakArray
#ifdef GHCI
, getBreak
, setBreakOn
, setBreakOff
, showBreakArray
#endif
) where
import DynFlags
#ifdef GHCI
import Control.Monad
import ExtsCompat46
import GHC.IO ( IO(..) )
data BreakArray = BA (MutableByteArray# RealWorld)
breakOff, breakOn :: Word
breakOn = 1
breakOff = 0
showBreakArray :: DynFlags -> BreakArray -> IO ()
showBreakArray dflags array = do
forM_ [0 .. (size dflags array - 1)] $ \i -> do
val <- readBreakArray array i
putStr $ ' ' : show val
putStr "\n"
setBreakOn :: DynFlags -> BreakArray -> Int -> IO Bool
setBreakOn dflags array index
| safeIndex dflags array index = do
writeBreakArray array index breakOn
return True
| otherwise = return False
setBreakOff :: DynFlags -> BreakArray -> Int -> IO Bool
setBreakOff dflags array index
| safeIndex dflags array index = do
writeBreakArray array index breakOff
return True
| otherwise = return False
getBreak :: DynFlags -> BreakArray -> Int -> IO (Maybe Word)
getBreak dflags array index
| safeIndex dflags array index = do
val <- readBreakArray array index
return $ Just val
| otherwise = return Nothing
safeIndex :: DynFlags -> BreakArray -> Int -> Bool
safeIndex dflags array index = index < size dflags array && index >= 0
size :: DynFlags -> BreakArray -> Int
size dflags (BA array) = (I# (sizeofMutableByteArray# array)) `div` wORD_SIZE dflags
allocBA :: Int -> IO BreakArray
allocBA (I# sz) = IO $ \s1 ->
case newByteArray# sz s1 of { (# s2, array #) -> (# s2, BA array #) }
-- create a new break array and initialise elements to zero
newBreakArray :: DynFlags -> Int -> IO BreakArray
newBreakArray dflags entries@(I# sz) = do
BA array <- allocBA (entries * wORD_SIZE dflags)
case breakOff of
W# off -> do -- Todo: there must be a better way to write zero as a Word!
let loop n | n ==# sz = return ()
| otherwise = do
writeBA# array n off
loop (n +# 1#)
loop 0#
return $ BA array
writeBA# :: MutableByteArray# RealWorld -> Int# -> Word# -> IO ()
writeBA# array i word = IO $ \s ->
case writeWordArray# array i word s of { s -> (# s, () #) }
writeBreakArray :: BreakArray -> Int -> Word -> IO ()
writeBreakArray (BA array) (I# i) (W# word) = writeBA# array i word
readBA# :: MutableByteArray# RealWorld -> Int# -> IO Word
readBA# array i = IO $ \s ->
case readWordArray# array i s of { (# s, c #) -> (# s, W# c #) }
readBreakArray :: BreakArray -> Int -> IO Word
readBreakArray (BA array) (I# i) = readBA# array i
#else /* !GHCI */
-- stub implementation to make main/, etc., code happier.
-- IOArray and IOUArray are increasingly non-portable,
-- still don't have quite the same interface, and (for GHCI)
-- presumably have a different representation.
data BreakArray = Unspecified
newBreakArray :: DynFlags -> Int -> IO BreakArray
newBreakArray _ _ = return Unspecified
#endif /* GHCI */
| urbanslug/ghc | compiler/main/BreakArray.hs | bsd-3-clause | 3,723 | 0 | 20 | 901 | 987 | 495 | 492 | 9 | 1 |
{-# OPTIONS_GHC -fno-package-trust #-}
-- | Basic test to see if Safe flags compiles
-- test should fail as there shouldn't be a no-package-trust flag, only a
-- package-trust flag!
module SafeFlags19 where
f :: Int
f = 1
| sdiehl/ghc | testsuite/tests/safeHaskell/flags/SafeFlags19.hs | bsd-3-clause | 224 | 0 | 4 | 41 | 18 | 13 | 5 | 4 | 1 |
-- | Multicore code generation for 'SegMap'.
module Futhark.CodeGen.ImpGen.Multicore.SegMap
( compileSegMap,
)
where
import Control.Monad
import qualified Futhark.CodeGen.ImpCode.Multicore as Imp
import Futhark.CodeGen.ImpGen
import Futhark.CodeGen.ImpGen.Multicore.Base
import Futhark.IR.MCMem
import Futhark.Transform.Rename
writeResult ::
[VName] ->
PatElemT dec ->
KernelResult ->
MulticoreGen ()
writeResult is pe (Returns _ _ se) =
copyDWIMFix (patElemName pe) (map Imp.le64 is) se []
writeResult _ pe (WriteReturns _ (Shape rws) _ idx_vals) = do
let (iss, vs) = unzip idx_vals
rws' = map toInt64Exp rws
forM_ (zip iss vs) $ \(slice, v) -> do
let slice' = fmap toInt64Exp slice
when_in_bounds = copyDWIM (patElemName pe) (unSlice slice') v []
sWhen (inBounds slice' rws') when_in_bounds
writeResult _ _ res =
error $ "writeResult: cannot handle " ++ pretty res
compileSegMapBody ::
TV Int64 ->
Pat MCMem ->
SegSpace ->
KernelBody MCMem ->
MulticoreGen Imp.Code
compileSegMapBody flat_idx pat space (KernelBody _ kstms kres) = do
let (is, ns) = unzip $ unSegSpace space
ns' = map toInt64Exp ns
kstms' <- mapM renameStm kstms
collect $ do
emit $ Imp.DebugPrint "SegMap fbody" Nothing
dIndexSpace (zip is ns') $ tvExp flat_idx
compileStms (freeIn kres) kstms' $
zipWithM_ (writeResult is) (patElems pat) kres
compileSegMap ::
Pat MCMem ->
SegSpace ->
KernelBody MCMem ->
MulticoreGen Imp.Code
compileSegMap pat space kbody =
collect $ do
flat_par_idx <- dPrim "iter" int64
body <- compileSegMapBody flat_par_idx pat space kbody
free_params <- freeParams body [segFlat space, tvVar flat_par_idx]
let (body_allocs, body') = extractAllocations body
emit $ Imp.Op $ Imp.ParLoop "segmap" (tvVar flat_par_idx) body_allocs body' mempty free_params $ segFlat space
| HIPERFIT/futhark | src/Futhark/CodeGen/ImpGen/Multicore/SegMap.hs | isc | 1,876 | 0 | 16 | 367 | 642 | 317 | 325 | 51 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Homework.Week11.Assignment where
import Control.Monad.Random
------------------------------------------------------------
-- Die values
newtype DieValue = DV { unDV :: Int }
deriving (Eq, Ord, Show, Num)
first :: (a -> b) -> (a, c) -> (b, c)
first f (a, c) = (f a, c)
instance Random DieValue where
random = first DV . randomR (1, 6)
randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi))
die :: Rand StdGen DieValue
die = getRandom
------------------------------------------------------------
-- Risk
type Army = Int
data Battlefield = Battlefield { attackers :: Army, defenders :: Army }
-- #2 (there is no assignment #1, really)
battle :: Battlefield -> Rand StdGen Battlefield
battle = undefined
-- #3
invade :: Battlefield -> Rand StdGen Battlefield
invade = undefined
-- #4
successProb :: Battlefield -> Rand StdGen Double
successProb = undefined
-- #5
exactSuccessProb :: Battlefield -> Double
exactSuccessProb = undefined | jxv/cis-194-winter-2016 | src/Homework/Week11/Assignment.hs | mit | 1,030 | 0 | 11 | 182 | 305 | 174 | 131 | 22 | 1 |
module Main where
import Dom
import HTML.Parsec
import HTML.Parser
import CSS
--this is just here so cabal has a main to compile
main :: IO ()
main = print "This doesn't do anything yet" | Hrothen/Hubert | src/Main.hs | mit | 188 | 0 | 6 | 35 | 39 | 23 | 16 | 7 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.