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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- | Use persistent-mongodb the same way you would use other persistent
-- libraries and refer to the general persistent documentation.
-- There are some new MongoDB specific filters under the filters section.
-- These help extend your query into a nested document.
--
-- However, at some point you will find the normal Persistent APIs lacking.
-- and want lower level-level MongoDB access.
-- There are functions available to make working with the raw driver
-- easier: they are under the Entity conversion section.
-- You should still use the same connection pool that you are using for Persistent.
--
-- MongoDB is a schema-less database.
-- The MongoDB Persistent backend does not help perform migrations.
-- Unlike SQL backends, uniqueness constraints cannot be created for you.
-- You must place a unique index on unique fields.
{-# LANGUAGE CPP, PackageImports, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE RankNTypes, TypeFamilies #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE GADTs #-}
module Database.Persist.MongoDB
(
-- * Entity conversion
collectionName
, docToEntityEither
, docToEntityThrow
, entityToDocument
, recordToDocument
, documentFromEntity
, toInsertDoc
, entityToInsertDoc
, updatesToDoc
, filtersToDoc
, toUniquesDoc
-- * MongoDB specific queries
-- $nested
, (->.), (~>.), (?&->.), (?&~>.), (&->.), (&~>.)
-- ** Filters
-- $filters
, nestEq, nestNe, nestGe, nestLe, nestIn, nestNotIn
, anyEq, nestAnyEq, nestBsonEq, anyBsonEq, multiBsonEq
, inList, ninList
, (=~.)
-- non-operator forms of filters
, NestedField(..)
, MongoRegexSearchable
, MongoRegex
-- ** Updates
-- $updates
, nestSet, nestInc, nestDec, nestMul, push, pull, pullAll, addToSet, eachOp
-- * Key conversion helpers
, BackendKey(..)
, keyToOid
, oidToKey
, recordTypeFromKey
, readMayObjectId
, readMayMongoKey
, keyToText
-- * PersistField conversion
, fieldName
-- * using connections
, withConnection
, withMongoPool
, withMongoDBConn
, withMongoDBPool
, createMongoDBPool
, runMongoDBPool
, runMongoDBPoolDef
, ConnectionPool
, Connection
, MongoAuth (..)
-- * Connection configuration
, MongoConf (..)
, defaultMongoConf
, defaultHost
, defaultAccessMode
, defaultPoolStripes
, defaultConnectionIdleTime
, defaultStripeConnections
, applyDockerEnv
-- ** using raw MongoDB pipes
, PipePool
, createMongoDBPipePool
, runMongoDBPipePool
-- * network type
, HostName
, PortID
-- * MongoDB driver types
, Database
, DB.Action
, DB.AccessMode(..)
, DB.master
, DB.slaveOk
, (DB.=:)
, DB.ObjectId
, DB.MongoContext
-- * Database.Persist
, module Database.Persist
) where
import Database.Persist
import qualified Database.Persist.Sql as Sql
import qualified Control.Monad.IO.Class as Trans
import Control.Exception (throw, throwIO)
import Data.Acquire (mkAcquire)
import qualified Data.Traversable as Traversable
import Data.Bson (ObjectId(..))
import qualified Database.MongoDB as DB
import Database.MongoDB.Query (Database)
import Control.Applicative (Applicative, (<$>))
import Network (PortID (PortNumber))
import Network.Socket (HostName)
import Data.Maybe (mapMaybe, fromJust)
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as E
import qualified Data.Serialize as Serialize
import Web.PathPieces (PathPiece(..))
import Web.HttpApiData (ToHttpApiData(..), FromHttpApiData(..), parseUrlPieceMaybe, parseUrlPieceWithPrefix, readTextData)
import Data.Conduit
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (Value (Number), (.:), (.:?), (.!=), FromJSON(..), ToJSON(..), withText, withObject)
import Data.Aeson.Types (modifyFailure)
import Control.Monad (liftM, (>=>), forM_)
import qualified Data.Pool as Pool
import Data.Time (NominalDiffTime)
#ifdef HIGH_PRECISION_DATE
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
#endif
import Data.Time.Calendar (Day(..))
#if MIN_VERSION_aeson(0, 7, 0)
#else
import Data.Attoparsec.Number
#endif
import Data.Bits (shiftR)
import Data.Word (Word16)
import Data.Monoid (mappend)
import Control.Monad.Trans.Reader (ask, runReaderT)
import Control.Monad.Trans.Control (MonadBaseControl)
import Numeric (readHex)
import Unsafe.Coerce (unsafeCoerce)
#if MIN_VERSION_base(4,6,0)
import System.Environment (lookupEnv)
#else
import System.Environment (getEnvironment)
#endif
#ifdef DEBUG
import FileLocation (debug)
#endif
#if !MIN_VERSION_base(4,6,0)
lookupEnv :: String -> IO (Maybe String)
lookupEnv key = do
env <- getEnvironment
return $ lookup key env
#endif
instance HasPersistBackend DB.MongoContext DB.MongoContext where
persistBackend = id
recordTypeFromKey :: Key record -> record
recordTypeFromKey _ = error "recordTypeFromKey"
newtype NoOrphanNominalDiffTime = NoOrphanNominalDiffTime NominalDiffTime
deriving (Show, Eq, Num)
instance FromJSON NoOrphanNominalDiffTime where
#if MIN_VERSION_aeson(0, 7, 0)
parseJSON (Number x) = (return . NoOrphanNominalDiffTime . fromRational . toRational) x
#else
parseJSON (Number (I x)) = (return . NoOrphanNominalDiffTime . fromInteger) x
parseJSON (Number (D x)) = (return . NoOrphanNominalDiffTime . fromRational . toRational) x
#endif
parseJSON _ = fail "couldn't parse diff time"
newtype NoOrphanPortID = NoOrphanPortID PortID deriving (Show, Eq)
instance FromJSON NoOrphanPortID where
#if MIN_VERSION_aeson(0, 7, 0)
parseJSON (Number x) = (return . NoOrphanPortID . PortNumber . fromIntegral ) cnvX
where cnvX :: Word16
cnvX = round x
#else
parseJSON (Number (I x)) = (return . NoOrphanPortID . PortNumber . fromInteger) x
#endif
parseJSON _ = fail "couldn't parse port number"
data Connection = Connection DB.Pipe DB.Database
type ConnectionPool = Pool.Pool Connection
instance ToHttpApiData (BackendKey DB.MongoContext) where
toUrlPiece = keyToText
instance FromHttpApiData (BackendKey DB.MongoContext) where
parseUrlPiece input = do
s <- parseUrlPieceWithPrefix "o" input <!> return input
MongoKey <$> readTextData s
where
infixl 3 <!>
Left _ <!> y = y
x <!> _ = x
-- | ToPathPiece is used to convert a key to/from text
instance PathPiece (BackendKey DB.MongoContext) where
toPathPiece = toUrlPiece
fromPathPiece = parseUrlPieceMaybe
keyToText :: BackendKey DB.MongoContext -> Text
keyToText = T.pack . show . unMongoKey
-- | Convert a Text to a Key
readMayMongoKey :: Text -> Maybe (BackendKey DB.MongoContext)
readMayMongoKey = fmap MongoKey . readMayObjectId
readMayObjectId :: Text -> Maybe DB.ObjectId
readMayObjectId str =
case filter (null . snd) $ reads $ T.unpack str :: [(DB.ObjectId,String)] of
(parsed,_):[] -> Just parsed
_ -> Nothing
instance PersistField DB.ObjectId where
toPersistValue = oidToPersistValue
fromPersistValue oid@(PersistObjectId _) = Right $ persistObjectIdToDbOid oid
fromPersistValue (PersistByteString bs) = fromPersistValue (PersistObjectId bs)
fromPersistValue _ = Left $ T.pack "expected PersistObjectId"
instance Sql.PersistFieldSql DB.ObjectId where
sqlType _ = Sql.SqlOther "doesn't make much sense for MongoDB"
instance Sql.PersistFieldSql (BackendKey DB.MongoContext) where
sqlType _ = Sql.SqlOther "doesn't make much sense for MongoDB"
withConnection :: (Trans.MonadIO m, Applicative m)
=> MongoConf
-> (ConnectionPool -> m b) -> m b
withConnection mc =
withMongoDBPool (mgDatabase mc) (T.unpack $ mgHost mc) (mgPort mc) (mgAuth mc) (mgPoolStripes mc) (mgStripeConnections mc) (mgConnectionIdleTime mc)
withMongoDBConn :: (Trans.MonadIO m, Applicative m)
=> Database -> HostName -> PortID
-> Maybe MongoAuth -> NominalDiffTime
-> (ConnectionPool -> m b) -> m b
withMongoDBConn dbname hostname port mauth connectionIdleTime = withMongoDBPool dbname hostname port mauth 1 1 connectionIdleTime
createPipe :: HostName -> PortID -> IO DB.Pipe
createPipe hostname port = DB.connect (DB.Host hostname port)
createReplicatSet :: (DB.ReplicaSetName, [DB.Host]) -> Database -> Maybe MongoAuth -> IO Connection
createReplicatSet rsSeed dbname mAuth = do
pipe <- DB.openReplicaSet rsSeed >>= DB.primary
testAccess pipe dbname mAuth
return $ Connection pipe dbname
createRsPool :: (Trans.MonadIO m, Applicative m) => Database -> ReplicaSetConfig
-> Maybe MongoAuth
-> Int -- ^ pool size (number of stripes)
-> Int -- ^ stripe size (number of connections per stripe)
-> NominalDiffTime -- ^ time a connection is left idle before closing
-> m ConnectionPool
createRsPool dbname (ReplicaSetConfig rsName rsHosts) mAuth connectionPoolSize stripeSize connectionIdleTime = do
Trans.liftIO $ Pool.createPool
(createReplicatSet (rsName, rsHosts) dbname mAuth)
(\(Connection pipe _) -> DB.close pipe)
connectionPoolSize
connectionIdleTime
stripeSize
testAccess :: DB.Pipe -> Database -> Maybe MongoAuth -> IO ()
testAccess pipe dbname mAuth = do
_ <- case mAuth of
Just (MongoAuth user pass) -> DB.access pipe DB.UnconfirmedWrites dbname (DB.auth user pass)
Nothing -> return undefined
return ()
createConnection :: Database -> HostName -> PortID -> Maybe MongoAuth -> IO Connection
createConnection dbname hostname port mAuth = do
pipe <- createPipe hostname port
testAccess pipe dbname mAuth
return $ Connection pipe dbname
createMongoDBPool :: (Trans.MonadIO m, Applicative m) => Database -> HostName -> PortID
-> Maybe MongoAuth
-> Int -- ^ pool size (number of stripes)
-> Int -- ^ stripe size (number of connections per stripe)
-> NominalDiffTime -- ^ time a connection is left idle before closing
-> m ConnectionPool
createMongoDBPool dbname hostname port mAuth connectionPoolSize stripeSize connectionIdleTime = do
Trans.liftIO $ Pool.createPool
(createConnection dbname hostname port mAuth)
(\(Connection pipe _) -> DB.close pipe)
connectionPoolSize
connectionIdleTime
stripeSize
createMongoPool :: (Trans.MonadIO m, Applicative m) => MongoConf -> m ConnectionPool
createMongoPool c@MongoConf{mgReplicaSetConfig = Just (ReplicaSetConfig rsName hosts)} =
createRsPool
(mgDatabase c)
(ReplicaSetConfig rsName ((DB.Host (T.unpack $ mgHost c) (mgPort c)):hosts))
(mgAuth c)
(mgPoolStripes c) (mgStripeConnections c) (mgConnectionIdleTime c)
createMongoPool c@MongoConf{mgReplicaSetConfig = Nothing} =
createMongoDBPool
(mgDatabase c) (T.unpack (mgHost c)) (mgPort c)
(mgAuth c)
(mgPoolStripes c) (mgStripeConnections c) (mgConnectionIdleTime c)
type PipePool = Pool.Pool DB.Pipe
-- | A pool of plain MongoDB pipes.
-- The database parameter has not yet been applied yet.
-- This is useful for switching between databases (on the same host and port)
-- Unlike the normal pool, no authentication is available
createMongoDBPipePool :: (Trans.MonadIO m, Applicative m) => HostName -> PortID
-> Int -- ^ pool size (number of stripes)
-> Int -- ^ stripe size (number of connections per stripe)
-> NominalDiffTime -- ^ time a connection is left idle before closing
-> m PipePool
createMongoDBPipePool hostname port connectionPoolSize stripeSize connectionIdleTime =
Trans.liftIO $ Pool.createPool
(createPipe hostname port)
DB.close
connectionPoolSize
connectionIdleTime
stripeSize
withMongoPool :: (Trans.MonadIO m, Applicative m) => MongoConf -> (ConnectionPool -> m b) -> m b
withMongoPool conf connectionReader = createMongoPool conf >>= connectionReader
withMongoDBPool :: (Trans.MonadIO m, Applicative m) =>
Database -> HostName -> PortID -> Maybe MongoAuth -> Int -> Int -> NominalDiffTime -> (ConnectionPool -> m b) -> m b
withMongoDBPool dbname hostname port mauth poolStripes stripeConnections connectionIdleTime connectionReader = do
pool <- createMongoDBPool dbname hostname port mauth poolStripes stripeConnections connectionIdleTime
connectionReader pool
-- | run a pool created with 'createMongoDBPipePool'
runMongoDBPipePool :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.AccessMode -> Database -> DB.Action m a -> PipePool -> m a
runMongoDBPipePool accessMode db action pool =
Pool.withResource pool $ \pipe -> DB.access pipe accessMode db action
runMongoDBPool :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.AccessMode -> DB.Action m a -> ConnectionPool -> m a
runMongoDBPool accessMode action pool =
Pool.withResource pool $ \(Connection pipe db) -> DB.access pipe accessMode db action
-- | use default 'AccessMode'
runMongoDBPoolDef :: (Trans.MonadIO m, MonadBaseControl IO m) => DB.Action m a -> ConnectionPool -> m a
runMongoDBPoolDef = runMongoDBPool defaultAccessMode
queryByKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Key record -> DB.Query
queryByKey k = DB.select (keyToMongoDoc k) (collectionNameFromKey k)
selectByKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Key record -> DB.Selection
selectByKey k = DB.select (keyToMongoDoc k) (collectionNameFromKey k)
updatesToDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> [Update record] -> DB.Document
updatesToDoc upds = map updateToMongoField upds
updateToBson :: Text
-> PersistValue
-> Either PersistUpdate MongoUpdateOperation
-> DB.Field
updateToBson fname v up =
#ifdef DEBUG
debug (
#endif
opName DB.:= DB.Doc [fname DB.:= opValue]
#ifdef DEBUG
)
#endif
where
inc = "$inc"
mul = "$mul"
(opName, opValue) = case up of
Left pup -> case (pup, v) of
(Assign, PersistNull) -> ("$unset", DB.Int64 1)
(Assign,a) -> ("$set", DB.val a)
(Add, a) -> (inc, DB.val a)
(Subtract, PersistInt64 i) -> (inc, DB.Int64 (-i))
(Multiply, PersistInt64 i) -> (mul, DB.Int64 i)
(Multiply, PersistDouble d) -> (mul, DB.Float d)
(Subtract, _) -> error "expected PersistInt64 for a subtraction"
(Multiply, _) -> error "expected PersistInt64 or PersistDouble for a subtraction"
-- Obviously this could be supported for floats by multiplying with 1/x
(Divide, _) -> throw $ PersistMongoDBUnsupported "divide not supported"
(BackendSpecificUpdate bsup, _) -> throw $ PersistMongoDBError $
T.pack $ "did not expect BackendSpecificUpdate " ++ T.unpack bsup
Right mup -> case mup of
MongoEach op -> case op of
MongoPull -> ("$pullAll", DB.val v)
_ -> (opToText op, DB.Doc ["$each" DB.:= DB.val v])
MongoSimple x -> (opToText x, DB.val v)
updateToMongoField :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Update record -> DB.Field
updateToMongoField (Update field v up) = updateToBson (fieldName field) (toPersistValue v) (Left up)
updateToMongoField (BackendUpdate up) = mongoUpdateToDoc up
-- | convert a unique key into a MongoDB document
toUniquesDoc :: forall record. (PersistEntity record) => Unique record -> [DB.Field]
toUniquesDoc uniq = zipWith (DB.:=)
(map (unDBName . snd) $ persistUniqueToFieldNames uniq)
(map DB.val (persistUniqueToValues uniq))
-- | convert a PersistEntity into document fields.
-- for inserts only: nulls are ignored so they will be unset in the document.
-- 'entityToDocument' includes nulls
toInsertDoc :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> record -> DB.Document
toInsertDoc record = zipFilter (embeddedFields $ toEmbedEntityDef entDef)
(map toPersistValue $ toPersistFields record)
where
entDef = entityDef $ Just record
zipFilter :: [EmbedFieldDef] -> [PersistValue] -> DB.Document
zipFilter [] _ = []
zipFilter _ [] = []
zipFilter (fd:efields) (pv:pvs) =
if isNull pv then recur else
(fieldToLabel fd DB.:= embeddedVal (emFieldEmbed fd) pv):recur
where
recur = zipFilter efields pvs
isNull PersistNull = True
isNull (PersistMap m) = null m
isNull (PersistList l) = null l
isNull _ = False
-- make sure to removed nulls from embedded entities also
embeddedVal :: Maybe EmbedEntityDef -> PersistValue -> DB.Value
embeddedVal (Just emDef) (PersistMap m) = DB.Doc $
zipFilter (embeddedFields emDef) $ map snd m
embeddedVal je@(Just _) (PersistList l) = DB.Array $ map (embeddedVal je) l
embeddedVal _ pv = DB.val pv
entityToInsertDoc :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Entity record -> DB.Document
entityToInsertDoc (Entity key record) = keyToMongoDoc key ++ toInsertDoc record
collectionName :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> record -> Text
collectionName = unDBName . entityDB . entityDef . Just
-- | convert a PersistEntity into document fields.
-- unlike 'toInsertDoc', nulls are included.
recordToDocument :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> record -> DB.Document
recordToDocument record = zipToDoc (map fieldDB $ entityFields entity) (toPersistFields record)
where
entity = entityDef $ Just record
entityToDocument :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> record -> DB.Document
entityToDocument = recordToDocument
{-# DEPRECATED entityToDocument "use recordToDocument" #-}
documentFromEntity :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Entity record -> DB.Document
documentFromEntity (Entity key record) =
keyToMongoDoc key ++ entityToDocument record
zipToDoc :: PersistField a => [DBName] -> [a] -> [DB.Field]
zipToDoc [] _ = []
zipToDoc _ [] = []
zipToDoc (e:efields) (p:pfields) =
let pv = toPersistValue p
in (unDBName e DB.:= DB.val pv):zipToDoc efields pfields
fieldToLabel :: EmbedFieldDef -> Text
fieldToLabel = unDBName . emFieldDB
keyFrom_idEx :: (Trans.MonadIO m, PersistEntity record) => DB.Value -> m (Key record)
keyFrom_idEx idVal = case keyFrom_id idVal of
Right k -> return k
Left err -> liftIO $ throwIO $ PersistMongoDBError $ "could not convert key: "
`mappend` T.pack (show idVal)
`mappend` err
keyFrom_id :: (PersistEntity record) => DB.Value -> Either Text (Key record)
keyFrom_id idVal = case cast idVal of
(PersistMap m) -> keyFromValues $ map snd m
pv -> keyFromValues [pv]
-- | It would make sense to define the instance for ObjectId
-- and then use newtype deriving
-- however, that would create an orphan instance
instance ToJSON (BackendKey DB.MongoContext) where
toJSON (MongoKey (Oid x y)) = toJSON $ DB.showHexLen 8 x $ DB.showHexLen 16 y ""
instance FromJSON (BackendKey DB.MongoContext) where
parseJSON = withText "MongoKey" $ \t ->
maybe
(fail "Invalid base64")
(return . MongoKey . persistObjectIdToDbOid . PersistObjectId)
$ fmap (i2bs (8 * 12) . fst) $ headMay $ readHex $ T.unpack t
where
-- should these be exported from Types/Base.hs ?
headMay [] = Nothing
headMay (x:_) = Just x
-- taken from crypto-api
-- |@i2bs bitLen i@ converts @i@ to a 'ByteString' of @bitLen@ bits (must be a multiple of 8).
i2bs :: Int -> Integer -> BS.ByteString
i2bs l i = BS.unfoldr (\l' -> if l' < 0 then Nothing else Just (fromIntegral (i `shiftR` l'), l' - 8)) (l-8)
{-# INLINE i2bs #-}
-- | older versions versions of haddock (like that on hackage) do not show that this defines
-- @BackendKey DB.MongoContext = MongoKey { unMongoKey :: DB.ObjectId }@
instance PersistStore DB.MongoContext where
newtype BackendKey DB.MongoContext = MongoKey { unMongoKey :: DB.ObjectId }
deriving (Show, Read, Eq, Ord, PersistField)
insert record = DB.insert (collectionName record) (toInsertDoc record)
>>= keyFrom_idEx
insertMany [] = return []
insertMany records@(r:_) = mapM keyFrom_idEx =<<
DB.insertMany (collectionName r) (map toInsertDoc records)
insertEntityMany [] = return ()
insertEntityMany ents@(Entity _ r : _) =
DB.insertMany_ (collectionName r) (map entityToInsertDoc ents)
insertKey k record = DB.insert_ (collectionName record) $
entityToInsertDoc (Entity k record)
repsert k record = DB.save (collectionName record) $
documentFromEntity (Entity k record)
replace k record = do
DB.replace (selectByKey k) (recordToDocument record)
return ()
delete k =
DB.deleteOne DB.Select {
DB.coll = collectionNameFromKey k
, DB.selector = keyToMongoDoc k
}
get k = do
d <- DB.findOne (queryByKey k)
case d of
Nothing -> return Nothing
Just doc -> do
Entity _ ent <- fromPersistValuesThrow t doc
return $ Just ent
where
t = entityDefFromKey k
update _ [] = return ()
update key upds =
DB.modify
(DB.Select (keyToMongoDoc key) (collectionNameFromKey key))
$ updatesToDoc upds
updateGet key upds = do
result <- DB.findAndModify (DB.select (keyToMongoDoc key)
(collectionNameFromKey key)
) (updatesToDoc upds)
either err instantiate result
where
instantiate doc = do
Entity _ rec <- fromPersistValuesThrow t doc
return rec
err msg = Trans.liftIO $ throwIO $ KeyNotFound $ show key ++ msg
t = entityDefFromKey key
instance PersistUnique DB.MongoContext where
getBy uniq = do
mdoc <- DB.findOne $
DB.select (toUniquesDoc uniq) (collectionName rec)
case mdoc of
Nothing -> return Nothing
Just doc -> liftM Just $ fromPersistValuesThrow t doc
where
t = entityDef $ Just rec
rec = dummyFromUnique uniq
deleteBy uniq =
DB.delete DB.Select {
DB.coll = collectionName $ dummyFromUnique uniq
, DB.selector = toUniquesDoc uniq
}
upsert newRecord upds = do
uniq <- onlyUnique newRecord
let uniqueDoc = toUniquesDoc uniq
let uniqKeys = map DB.label uniqueDoc
let insDoc = DB.exclude uniqKeys $ toInsertDoc newRecord
let selection = DB.select uniqueDoc $ collectionName newRecord
if null upds
then DB.upsert selection ["$set" DB.=: insDoc]
else do
DB.upsert selection ["$setOnInsert" DB.=: insDoc]
DB.modify selection $ updatesToDoc upds
-- because findAndModify $setOnInsert is broken we do a separate get now
mdoc <- getBy uniq
maybe (err "possible race condition: getBy found Nothing")
return mdoc
where
err = Trans.liftIO . throwIO . UpsertError
{-
-- cannot use findAndModify
-- because $setOnInsert is crippled
-- https://jira.mongodb.org/browse/SERVER-2643
result <- DB.findAndModifyOpts
selection
(DB.defFamUpdateOpts ("$setOnInsert" DB.=: insDoc : ["$set" DB.=: insDoc]))
{ DB.famUpsert = True }
either err instantiate result
where
-- this is only possible when new is False
instantiate Nothing = error "upsert: impossible null"
instantiate (Just doc) =
fromPersistValuesThrow (entityDef $ Just newRecord) doc
-}
-- | It would make more sense to call this _id, but GHC treats leading underscore in special ways
id_ :: T.Text
id_ = "_id"
-- _id is always the primary key in MongoDB
-- but _id can contain any unique value
keyToMongoDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Key record -> DB.Document
keyToMongoDoc k = case entityPrimary $ entityDefFromKey k of
Nothing -> zipToDoc [DBName id_] values
Just pdef -> [id_ DB.=: zipToDoc (primaryNames pdef) values]
where
primaryNames = map fieldDB . compositeFields
values = keyToValues k
entityDefFromKey :: PersistEntity record => Key record -> EntityDef
entityDefFromKey = entityDef . Just . recordTypeFromKey
collectionNameFromKey :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext)
=> Key record -> Text
collectionNameFromKey = collectionName . recordTypeFromKey
instance PersistQuery DB.MongoContext where
updateWhere _ [] = return ()
updateWhere filts upds =
DB.modify DB.Select {
DB.coll = collectionName $ dummyFromFilts filts
, DB.selector = filtersToDoc filts
} $ updatesToDoc upds
deleteWhere filts = do
DB.delete DB.Select {
DB.coll = collectionName $ dummyFromFilts filts
, DB.selector = filtersToDoc filts
}
count filts = do
i <- DB.count query
return $ fromIntegral i
where
query = DB.select (filtersToDoc filts) $
collectionName $ dummyFromFilts filts
-- | uses cursor option NoCursorTimeout
-- If there is no sorting, it will turn the $snapshot option on
-- and explicitly closes the cursor when done
selectSourceRes filts opts = do
context <- ask
return (pullCursor context `fmap` mkAcquire (open context) (close context))
where
close :: DB.MongoContext -> DB.Cursor -> IO ()
close context cursor = runReaderT (DB.closeCursor cursor) context
open :: DB.MongoContext -> IO DB.Cursor
open = runReaderT (DB.find (makeQuery filts opts)
-- it is an error to apply $snapshot when sorting
{ DB.snapshot = noSort
, DB.options = [DB.NoCursorTimeout]
})
pullCursor context cursor = do
mdoc <- liftIO $ runReaderT (DB.nextBatch cursor) context
case mdoc of
[] -> return ()
docs -> do
forM_ docs $ fromPersistValuesThrow t >=> yield
pullCursor context cursor
t = entityDef $ Just $ dummyFromFilts filts
(_, _, orders) = limitOffsetOrder opts
noSort = null orders
selectFirst filts opts = DB.findOne (makeQuery filts opts)
>>= Traversable.mapM (fromPersistValuesThrow t)
where
t = entityDef $ Just $ dummyFromFilts filts
selectKeysRes filts opts = do
context <- ask
let make = do
cursor <- liftIO $ flip runReaderT context $ DB.find $ (makeQuery filts opts) {
DB.project = [id_ DB.=: (1 :: Int)]
}
pullCursor context cursor
return $ return make
where
pullCursor context cursor = do
mdoc <- liftIO $ runReaderT (DB.next cursor) context
case mdoc of
Nothing -> return ()
Just [_id DB.:= idVal] -> do
k <- liftIO $ keyFrom_idEx idVal
yield k
pullCursor context cursor
Just y -> liftIO $ throwIO $ PersistMarshalError $ T.pack $ "Unexpected in selectKeys: " ++ show y
orderClause :: PersistEntity val => SelectOpt val -> DB.Field
orderClause o = case o of
Asc f -> fieldName f DB.=: ( 1 :: Int)
Desc f -> fieldName f DB.=: (-1 :: Int)
_ -> error "orderClause: expected Asc or Desc"
makeQuery :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => [Filter record] -> [SelectOpt record] -> DB.Query
makeQuery filts opts =
(DB.select (filtersToDoc filts) (collectionName $ dummyFromFilts filts)) {
DB.limit = fromIntegral limit
, DB.skip = fromIntegral offset
, DB.sort = orders
}
where
(limit, offset, orders') = limitOffsetOrder opts
orders = map orderClause orders'
filtersToDoc :: (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => [Filter record] -> DB.Document
filtersToDoc filts =
#ifdef DEBUG
debug $
#endif
if null filts then [] else multiFilter AndDollar filts
filterToDocument :: (PersistEntity val, PersistEntityBackend val ~ DB.MongoContext) => Filter val -> DB.Document
filterToDocument f =
case f of
Filter field v filt -> [filterToBSON (fieldName field) v filt]
BackendFilter mf -> mongoFilterToDoc mf
-- The empty filter case should never occur when the user uses ||.
-- An empty filter list will throw an exception in multiFilter
--
-- The alternative would be to create a query which always returns true
-- However, I don't think an end user ever wants that.
FilterOr fs -> multiFilter OrDollar fs
-- Ignore an empty filter list instead of throwing an exception.
-- \$and is necessary in only a few cases, but it makes query construction easier
FilterAnd [] -> []
FilterAnd fs -> multiFilter AndDollar fs
data MultiFilter = OrDollar | AndDollar deriving Show
toMultiOp :: MultiFilter -> Text
toMultiOp OrDollar = orDollar
toMultiOp AndDollar = andDollar
multiFilter :: forall record. (PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => MultiFilter -> [Filter record] -> [DB.Field]
multiFilter _ [] = throw $ PersistMongoDBError "An empty list of filters was given"
multiFilter multi filters =
case (multi, filter (not . null) (map filterToDocument filters)) of
-- a $or must have at least 2 items
(OrDollar, []) -> orError
(AndDollar, []) -> []
(OrDollar, _:[]) -> orError
(AndDollar, doc:[]) -> doc
(_, doc) -> [toMultiOp multi DB.:= DB.Array (map DB.Doc doc)]
where
orError = throw $ PersistMongoDBError $
"An empty list of filters was given to one side of ||."
existsDollar, orDollar, andDollar :: Text
existsDollar = "$exists"
orDollar = "$or"
andDollar = "$and"
filterToBSON :: forall a. ( PersistField a)
=> Text
-> Either a [a]
-> PersistFilter
-> DB.Field
filterToBSON fname v filt = case filt of
Eq -> nullEq
Ne -> nullNeq
_ -> notEquality
where
dbv = toValue v
notEquality = fname DB.=: [showFilter filt DB.:= dbv]
nullEq = case dbv of
DB.Null -> orDollar DB.=:
[ [fname DB.:= DB.Null]
, [fname DB.:= DB.Doc [existsDollar DB.:= DB.Bool False]]
]
_ -> fname DB.:= dbv
nullNeq = case dbv of
DB.Null ->
fname DB.:= DB.Doc
[ showFilter Ne DB.:= DB.Null
, existsDollar DB.:= DB.Bool True
]
_ -> notEquality
showFilter Ne = "$ne"
showFilter Gt = "$gt"
showFilter Lt = "$lt"
showFilter Ge = "$gte"
showFilter Le = "$lte"
showFilter In = "$in"
showFilter NotIn = "$nin"
showFilter Eq = error "EQ filter not expected"
showFilter (BackendSpecificFilter bsf) = throw $ PersistMongoDBError $ T.pack $ "did not expect BackendSpecificFilter " ++ T.unpack bsf
mongoFilterToBSON :: forall typ. PersistField typ
=> Text
-> MongoFilterOperator typ
-> DB.Document
mongoFilterToBSON fname filt = case filt of
(PersistFilterOperator v op) -> [filterToBSON fname v op]
(MongoFilterOperator bval) -> [fname DB.:= bval]
mongoUpdateToBson :: forall typ. PersistField typ
=> Text
-> UpdateValueOp typ
-> DB.Field
mongoUpdateToBson fname upd = case upd of
UpdateValueOp (Left v) op -> updateToBson fname (toPersistValue v) op
UpdateValueOp (Right v) op -> updateToBson fname (PersistList $ map toPersistValue v) op
mongoUpdateToDoc :: PersistEntity record => MongoUpdate record -> DB.Field
mongoUpdateToDoc (NestedUpdate field op) = mongoUpdateToBson (nestedFieldName field) op
mongoUpdateToDoc (ArrayUpdate field op) = mongoUpdateToBson (fieldName field) op
mongoFilterToDoc :: PersistEntity record => MongoFilter record -> DB.Document
mongoFilterToDoc (NestedFilter field op) = mongoFilterToBSON (nestedFieldName field) op
mongoFilterToDoc (ArrayFilter field op) = mongoFilterToBSON (fieldName field) op
mongoFilterToDoc (NestedArrayFilter field op) = mongoFilterToBSON (nestedFieldName field) op
mongoFilterToDoc (RegExpFilter fn (reg, opts)) = [ fieldName fn DB.:= DB.RegEx (DB.Regex reg opts)]
nestedFieldName :: forall record typ. PersistEntity record => NestedField record typ -> Text
nestedFieldName = T.intercalate "." . nesFldName
where
nesFldName :: forall r1 r2. (PersistEntity r1) => NestedField r1 r2 -> [DB.Label]
nesFldName (nf1 `LastEmbFld` nf2) = [fieldName nf1, fieldName nf2]
nesFldName ( f1 `MidEmbFld` f2) = fieldName f1 : nesFldName f2
nesFldName ( f1 `MidNestFlds` f2) = fieldName f1 : nesFldName f2
nesFldName ( f1 `MidNestFldsNullable` f2) = fieldName f1 : nesFldName f2
nesFldName (nf1 `LastNestFld` nf2) = [fieldName nf1, fieldName nf2]
nesFldName (nf1 `LastNestFldNullable` nf2) = [fieldName nf1, fieldName nf2]
toValue :: forall a. PersistField a => Either a [a] -> DB.Value
toValue val =
case val of
Left v -> DB.val $ toPersistValue v
Right vs -> DB.val $ map toPersistValue vs
fieldName :: forall record typ. (PersistEntity record) => EntityField record typ -> DB.Label
fieldName f | fieldHaskell fd == HaskellName "Id" = id_
| otherwise = unDBName $ fieldDB $ fd
where
fd = persistFieldDef f
docToEntityEither :: forall record. (PersistEntity record) => DB.Document -> Either T.Text (Entity record)
docToEntityEither doc = entity
where
entDef = entityDef $ Just (getType entity)
entity = eitherFromPersistValues entDef doc
getType :: Either err (Entity ent) -> ent
getType = error "docToEntityEither/getType: never here"
docToEntityThrow :: forall m record. (Trans.MonadIO m, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => DB.Document -> m (Entity record)
docToEntityThrow doc =
case docToEntityEither doc of
Left s -> Trans.liftIO . throwIO $ PersistMarshalError $ s
Right entity -> return entity
fromPersistValuesThrow :: (Trans.MonadIO m, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => EntityDef -> [DB.Field] -> m (Entity record)
fromPersistValuesThrow entDef doc =
case eitherFromPersistValues entDef doc of
Left t -> Trans.liftIO . throwIO $ PersistMarshalError $
unHaskellName (entityHaskell entDef) `mappend` ": " `mappend` t
Right entity -> return entity
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft _ (Right r) = Right r
mapLeft f (Left l) = Left (f l)
eitherFromPersistValues :: (PersistEntity record) => EntityDef -> [DB.Field] -> Either T.Text (Entity record)
eitherFromPersistValues entDef doc = case mKey of
Nothing -> addDetail $ Left $ "could not find _id field: "
Just kpv -> do
body <- addDetail (fromPersistValues (map snd $ orderPersistValues (toEmbedEntityDef entDef) castDoc))
key <- keyFromValues [kpv]
return $ Entity key body
where
addDetail :: Either Text a -> Either Text a
addDetail = mapLeft (\msg -> msg `mappend` " for doc: " `mappend` T.pack (show doc))
castDoc = assocListFromDoc doc
-- normally _id is the first field
mKey = lookup id_ castDoc
-- | unlike many SQL databases, MongoDB makes no guarantee of the ordering
-- of the fields returned in the document.
-- Ordering might be maintained if persistent were the only user of the db,
-- but other tools may be using MongoDB.
--
-- Persistent creates a Haskell record from a list of PersistValue
-- But most importantly it puts all PersistValues in the proper order
orderPersistValues :: EmbedEntityDef -> [(Text, PersistValue)] -> [(Text, PersistValue)]
orderPersistValues entDef castDoc = reorder
where
castColumns = map nameAndEmbed (embeddedFields entDef)
nameAndEmbed fdef = (fieldToLabel fdef, emFieldEmbed fdef)
-- TODO: the below reasoning should be re-thought now that we are no longer inserting null: searching for a null column will look at every returned field before giving up
-- Also, we are now doing the _id lookup at the start.
--
-- we have an alist of fields that need to be the same order as entityColumns
--
-- this naive lookup is O(n^2)
-- reorder = map (fromJust . (flip Prelude.lookup $ castDoc)) castColumns
--
-- this is O(n * log(n))
-- reorder = map (\c -> (M.fromList castDoc) M.! c) castColumns
--
-- and finally, this is O(n * log(n))
-- * do an alist lookup for each column
-- * but once we found an item in the alist use a new alist without that item for future lookups
-- * so for the last query there is only one item left
--
reorder :: [(Text, PersistValue)]
reorder = match castColumns castDoc []
where
match :: [(Text, Maybe EmbedEntityDef)]
-> [(Text, PersistValue)]
-> [(Text, PersistValue)]
-> [(Text, PersistValue)]
-- when there are no more Persistent castColumns we are done
--
-- allow extra mongoDB fields that persistent does not know about
-- another application may use fields we don't care about
-- our own application may set extra fields with the raw driver
-- TODO: instead use a projection to avoid network overhead
match [] _ values = values
match (column:columns) fields values =
let (found, unused) = matchOne fields []
in match columns unused $ values ++
[(fst column, nestedOrder (snd column) (snd found))]
where
nestedOrder (Just em) (PersistMap m) =
PersistMap $ orderPersistValues em m
nestedOrder (Just em) (PersistList l) =
PersistList $ map (nestedOrder (Just em)) l
-- implied: nestedOrder Nothing found = found
nestedOrder _ found = found
matchOne (field:fs) tried =
if fst column == fst field
-- snd drops the name now that it has been used to make the match
-- persistent will add the field name later
then (field, tried ++ fs)
else matchOne fs (field:tried)
-- if field is not found, assume it was a Nothing
--
-- a Nothing could be stored as null, but that would take up space.
-- instead, we want to store no field at all: that takes less space.
-- Also, another ORM may be doing the same
-- Also, this adding a Maybe field means no migration required
matchOne [] tried = ((fst column, PersistNull), tried)
assocListFromDoc :: DB.Document -> [(Text, PersistValue)]
assocListFromDoc = Prelude.map (\f -> ( (DB.label f), cast (DB.value f) ) )
oidToPersistValue :: DB.ObjectId -> PersistValue
oidToPersistValue = PersistObjectId . Serialize.encode
oidToKey :: (ToBackendKey DB.MongoContext record) => DB.ObjectId -> Key record
oidToKey = fromBackendKey . MongoKey
persistObjectIdToDbOid :: PersistValue -> DB.ObjectId
persistObjectIdToDbOid (PersistObjectId k) = case Serialize.decode k of
Left msg -> throw $ PersistError $ T.pack $ "error decoding " ++ (show k) ++ ": " ++ msg
Right o -> o
persistObjectIdToDbOid _ = throw $ PersistInvalidField "expected PersistObjectId"
keyToOid :: ToBackendKey DB.MongoContext record => Key record -> DB.ObjectId
keyToOid = unMongoKey . toBackendKey
instance DB.Val PersistValue where
val (PersistInt64 x) = DB.Int64 x
val (PersistText x) = DB.String x
val (PersistDouble x) = DB.Float x
val (PersistBool x) = DB.Bool x
#ifdef HIGH_PRECISION_DATE
val (PersistUTCTime x) = DB.Int64 $ round $ 1000 * 1000 * 1000 * (utcTimeToPOSIXSeconds x)
#else
-- this is just millisecond precision: https://jira.mongodb.org/browse/SERVER-1460
val (PersistUTCTime x) = DB.UTC x
#endif
val (PersistDay d) = DB.Int64 $ fromInteger $ toModifiedJulianDay d
val (PersistNull) = DB.Null
val (PersistList l) = DB.Array $ map DB.val l
val (PersistMap m) = DB.Doc $ map (\(k, v)-> (DB.=:) k v) m
val (PersistByteString x) = DB.Bin (DB.Binary x)
val x@(PersistObjectId _) = DB.ObjId $ persistObjectIdToDbOid x
val (PersistTimeOfDay _) = throw $ PersistMongoDBUnsupported "PersistTimeOfDay not implemented for the MongoDB backend. only PersistUTCTime currently implemented"
val (PersistRational _) = throw $ PersistMongoDBUnsupported "PersistRational not implemented for the MongoDB backend"
val (PersistDbSpecific _) = throw $ PersistMongoDBUnsupported "PersistDbSpecific not implemented for the MongoDB backend"
cast' (DB.Float x) = Just (PersistDouble x)
cast' (DB.Int32 x) = Just $ PersistInt64 $ fromIntegral x
cast' (DB.Int64 x) = Just $ PersistInt64 x
cast' (DB.String x) = Just $ PersistText x
cast' (DB.Bool x) = Just $ PersistBool x
cast' (DB.UTC d) = Just $ PersistUTCTime d
cast' DB.Null = Just $ PersistNull
cast' (DB.Bin (DB.Binary b)) = Just $ PersistByteString b
cast' (DB.Fun (DB.Function f)) = Just $ PersistByteString f
cast' (DB.Uuid (DB.UUID uid)) = Just $ PersistByteString uid
cast' (DB.Md5 (DB.MD5 md5)) = Just $ PersistByteString md5
cast' (DB.UserDef (DB.UserDefined bs)) = Just $ PersistByteString bs
cast' (DB.RegEx (DB.Regex us1 us2)) = Just $ PersistByteString $ E.encodeUtf8 $ T.append us1 us2
cast' (DB.Doc doc) = Just $ PersistMap $ assocListFromDoc doc
cast' (DB.Array xs) = Just $ PersistList $ mapMaybe DB.cast' xs
cast' (DB.ObjId x) = Just $ oidToPersistValue x
cast' (DB.JavaScr _) = throw $ PersistMongoDBUnsupported "cast operation not supported for javascript"
cast' (DB.Sym _) = throw $ PersistMongoDBUnsupported "cast operation not supported for sym"
cast' (DB.Stamp _) = throw $ PersistMongoDBUnsupported "cast operation not supported for stamp"
cast' (DB.MinMax _) = throw $ PersistMongoDBUnsupported "cast operation not supported for minmax"
cast :: DB.Value -> PersistValue
-- since we have case analysys this won't ever be Nothing
-- However, unsupported types do throw an exception in pure code
-- probably should re-work this to throw in IO
cast = fromJust . DB.cast'
instance Serialize.Serialize DB.ObjectId where
put (DB.Oid w1 w2) = do Serialize.put w1
Serialize.put w2
get = do w1 <- Serialize.get
w2 <- Serialize.get
return (DB.Oid w1 w2)
dummyFromUnique :: Unique v -> v
dummyFromUnique _ = error "dummyFromUnique"
dummyFromFilts :: [Filter v] -> v
dummyFromFilts _ = error "dummyFromFilts"
data MongoAuth = MongoAuth DB.Username DB.Password deriving Show
-- | Information required to connect to a mongo database
data MongoConf = MongoConf
{ mgDatabase :: Text
, mgHost :: Text
, mgPort :: PortID
, mgAuth :: Maybe MongoAuth
, mgAccessMode :: DB.AccessMode
, mgPoolStripes :: Int
, mgStripeConnections :: Int
, mgConnectionIdleTime :: NominalDiffTime
-- | YAML fields for this are @rsName@ and @rsSecondaries@
-- mgHost is assumed to be the primary
, mgReplicaSetConfig :: Maybe ReplicaSetConfig
} deriving Show
defaultHost :: Text
defaultHost = "127.0.0.1"
defaultAccessMode :: DB.AccessMode
defaultAccessMode = DB.ConfirmWrites ["w" DB.:= DB.Int32 1]
defaultPoolStripes, defaultStripeConnections :: Int
defaultPoolStripes = 1
defaultStripeConnections = 10
defaultConnectionIdleTime :: NominalDiffTime
defaultConnectionIdleTime = 20
defaultMongoConf :: Text -> MongoConf
defaultMongoConf dbName = MongoConf
{ mgDatabase = dbName
, mgHost = defaultHost
, mgPort = DB.defaultPort
, mgAuth = Nothing
, mgAccessMode = defaultAccessMode
, mgPoolStripes = defaultPoolStripes
, mgStripeConnections = defaultStripeConnections
, mgConnectionIdleTime = defaultConnectionIdleTime
, mgReplicaSetConfig = Nothing
}
data ReplicaSetConfig = ReplicaSetConfig DB.ReplicaSetName [DB.Host]
deriving Show
instance FromJSON MongoConf where
parseJSON v = modifyFailure ("Persistent: error loading MongoDB conf: " ++) $
flip (withObject "MongoConf") v $ \o ->do
db <- o .: "database"
host <- o .:? "host" .!= defaultHost
NoOrphanPortID port <- o .:? "port" .!= NoOrphanPortID DB.defaultPort
poolStripes <- o .:? "poolstripes" .!= defaultPoolStripes
stripeConnections <- o .:? "connections" .!= defaultStripeConnections
NoOrphanNominalDiffTime connectionIdleTime <- o .:? "connectionIdleTime" .!= NoOrphanNominalDiffTime defaultConnectionIdleTime
mUser <- o .:? "user"
mPass <- o .:? "password"
accessString <- o .:? "accessMode" .!= confirmWrites
mRsName <- o .:? "rsName"
rsSecondaires <- o .:? "rsSecondaries" .!= []
mPoolSize <- o .:? "poolsize"
case mPoolSize of
Nothing -> return ()
Just (_::Int) -> fail "specified deprecated poolsize attribute. Please specify a connections. You can also specify a pools attribute which defaults to 1. Total connections opened to the db are connections * pools"
accessMode <- case accessString of
"ReadStaleOk" -> return DB.ReadStaleOk
"UnconfirmedWrites" -> return DB.UnconfirmedWrites
"ConfirmWrites" -> return defaultAccessMode
badAccess -> fail $ "unknown accessMode: " ++ T.unpack badAccess
let rs = case (mRsName, rsSecondaires) of
(Nothing, []) -> Nothing
(Nothing, _) -> error "found rsSecondaries key. Also expected but did not find a rsName key"
(Just rsName, hosts) -> Just $ ReplicaSetConfig rsName $ fmap DB.readHostPort hosts
return MongoConf {
mgDatabase = db
, mgHost = host
, mgPort = port
, mgAuth =
case (mUser, mPass) of
(Just user, Just pass) -> Just (MongoAuth user pass)
_ -> Nothing
, mgPoolStripes = poolStripes
, mgStripeConnections = stripeConnections
, mgAccessMode = accessMode
, mgConnectionIdleTime = connectionIdleTime
, mgReplicaSetConfig = rs
}
where
confirmWrites = "ConfirmWrites"
instance PersistConfig MongoConf where
type PersistConfigBackend MongoConf = DB.Action
type PersistConfigPool MongoConf = ConnectionPool
createPoolConfig = createMongoPool
runPool c = runMongoDBPool (mgAccessMode c)
loadConfig = parseJSON
-- | docker integration: change the host to the mongodb link
applyDockerEnv :: MongoConf -> IO MongoConf
applyDockerEnv mconf = do
mHost <- lookupEnv "MONGODB_PORT_27017_TCP_ADDR"
return $ case mHost of
Nothing -> mconf
Just h -> mconf { mgHost = T.pack h }
-- ---------------------------
-- * MongoDB specific Filters
-- $filters
--
-- You can find example usage for all of Persistent in our test cases:
-- <https://github.com/yesodweb/persistent/blob/master/persistent-test/EmbedTest.hs#L144>
--
-- These filters create a query that reaches deeper into a document with
-- nested fields.
type instance BackendSpecificFilter DB.MongoContext record = MongoFilter record
type instance BackendSpecificUpdate DB.MongoContext record = MongoUpdate record
data NestedField record typ
= forall emb. PersistEntity emb => EntityField record [emb] `LastEmbFld` EntityField emb typ
| forall emb. PersistEntity emb => EntityField record [emb] `MidEmbFld` NestedField emb typ
| forall nest. PersistEntity nest => EntityField record nest `MidNestFlds` NestedField nest typ
| forall nest. PersistEntity nest => EntityField record (Maybe nest) `MidNestFldsNullable` NestedField nest typ
| forall nest. PersistEntity nest => EntityField record nest `LastNestFld` EntityField nest typ
| forall nest. PersistEntity nest => EntityField record (Maybe nest) `LastNestFldNullable` EntityField nest typ
-- | A MongoRegex represents a Regular expression.
-- It is a tuple of the expression and the options for the regular expression, respectively
-- Options are listed here: <http://docs.mongodb.org/manual/reference/operator/query/regex/>
-- If you use the same options you may want to define a helper such as @r t = (t, "ims")@
type MongoRegex = (Text, Text)
-- | Mark the subset of 'PersistField's that can be searched by a mongoDB regex
-- Anything stored as PersistText or an array of PersistText would be valid
class PersistField typ => MongoRegexSearchable typ where
instance MongoRegexSearchable Text
instance MongoRegexSearchable rs => MongoRegexSearchable (Maybe rs)
instance MongoRegexSearchable rs => MongoRegexSearchable [rs]
-- | Filter using a Regular expression.
(=~.) :: forall record searchable. (MongoRegexSearchable searchable, PersistEntity record, PersistEntityBackend record ~ DB.MongoContext) => EntityField record searchable -> MongoRegex -> Filter record
fld =~. val = BackendFilter $ RegExpFilter fld val
data MongoFilterOperator typ = PersistFilterOperator (Either typ [typ]) PersistFilter
| MongoFilterOperator DB.Value
data UpdateValueOp typ =
UpdateValueOp
(Either typ [typ])
(Either PersistUpdate MongoUpdateOperation)
deriving Show
data MongoUpdateOperation = MongoEach MongoUpdateOperator
| MongoSimple MongoUpdateOperator
deriving Show
data MongoUpdateOperator = MongoPush
| MongoPull
| MongoAddToSet
deriving Show
opToText :: MongoUpdateOperator -> Text
opToText MongoPush = "$push"
opToText MongoPull = "$pull"
opToText MongoAddToSet = "$addToSet"
data MongoFilter record =
forall typ. PersistField typ =>
NestedFilter
(NestedField record typ)
(MongoFilterOperator typ)
| forall typ. PersistField typ =>
ArrayFilter
(EntityField record [typ])
(MongoFilterOperator typ)
| forall typ. PersistField typ =>
NestedArrayFilter
(NestedField record [typ])
(MongoFilterOperator typ)
| forall typ. MongoRegexSearchable typ =>
RegExpFilter
(EntityField record typ)
MongoRegex
data MongoUpdate record =
forall typ. PersistField typ =>
NestedUpdate
(NestedField record typ)
(UpdateValueOp typ)
| forall typ. PersistField typ =>
ArrayUpdate
(EntityField record [typ])
(UpdateValueOp typ)
-- | Point to an array field with an embedded object and give a deeper query into the embedded object.
-- Use with 'nestEq'.
(->.) :: forall record emb typ. PersistEntity emb => EntityField record [emb] -> EntityField emb typ -> NestedField record typ
(->.) = LastEmbFld
-- | Point to an array field with an embedded object and give a deeper query into the embedded object.
-- This level of nesting is not the final level.
-- Use '->.' or '&->.' to point to the final level.
(~>.) :: forall record typ emb. PersistEntity emb => EntityField record [emb] -> NestedField emb typ -> NestedField record typ
(~>.) = MidEmbFld
-- | Point to a nested field to query. This field is not an array type.
-- Use with 'nestEq'.
(&->.) :: forall record typ nest. PersistEntity nest => EntityField record nest -> EntityField nest typ -> NestedField record typ
(&->.) = LastNestFld
-- | Same as '&->.', but Works against a Maybe type
(?&->.) :: forall record typ nest. PersistEntity nest => EntityField record (Maybe nest) -> EntityField nest typ -> NestedField record typ
(?&->.) = LastNestFldNullable
-- | Point to a nested field to query. This field is not an array type.
-- This level of nesting is not the final level.
-- Use '->.' or '&>.' to point to the final level.
(&~>.) :: forall val nes nes1. PersistEntity nes1 => EntityField val nes1 -> NestedField nes1 nes -> NestedField val nes
(&~>.) = MidNestFlds
-- | Same as '&~>.', but works against a Maybe type
(?&~>.) :: forall val nes nes1. PersistEntity nes1 => EntityField val (Maybe nes1) -> NestedField nes1 nes -> NestedField val nes
(?&~>.) = MidNestFldsNullable
infixr 4 =~.
infixr 5 ~>.
infixr 5 &~>.
infixr 5 ?&~>.
infixr 6 &->.
infixr 6 ?&->.
infixr 6 ->.
infixr 4 `nestEq`
infixr 4 `nestNe`
infixr 4 `nestGe`
infixr 4 `nestLe`
infixr 4 `nestIn`
infixr 4 `nestNotIn`
infixr 4 `anyEq`
infixr 4 `nestAnyEq`
infixr 4 `nestBsonEq`
infixr 4 `multiBsonEq`
infixr 4 `anyBsonEq`
infixr 4 `nestSet`
infixr 4 `push`
infixr 4 `pull`
infixr 4 `pullAll`
infixr 4 `addToSet`
-- | The normal Persistent equality test '==.' is not generic enough.
-- Instead use this with the drill-down arrow operaters such as '->.'
--
-- using this as the only query filter is similar to the following in the mongoDB shell
--
-- > db.Collection.find({"object.field": item})
nestEq, nestNe, nestGe, nestLe, nestIn, nestNotIn :: forall record typ.
( PersistField typ , PersistEntityBackend record ~ DB.MongoContext)
=> NestedField record typ
-> typ
-> Filter record
nestEq = nestedFilterOp Eq
nestNe = nestedFilterOp Ne
nestGe = nestedFilterOp Ge
nestLe = nestedFilterOp Le
nestIn = nestedFilterOp In
nestNotIn = nestedFilterOp NotIn
nestedFilterOp :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => PersistFilter -> NestedField record typ -> typ -> Filter record
nestedFilterOp op nf v = BackendFilter $
NestedFilter nf $ PersistFilterOperator (Left v) op
-- | same as `nestEq`, but give a BSON Value
nestBsonEq :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => NestedField record typ -> DB.Value -> Filter record
nf `nestBsonEq` val = BackendFilter $
NestedFilter nf $ MongoFilterOperator val
-- | Like '(==.)' but for an embedded list.
-- Checks to see if the list contains an item.
--
-- In Haskell we need different equality functions for embedded fields that are lists or non-lists to keep things type-safe.
--
-- using this as the only query filter is similar to the following in the mongoDB shell
--
-- > db.Collection.find({arrayField: arrayItem})
anyEq :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => EntityField record [typ] -> typ -> Filter record
fld `anyEq` val = BackendFilter $
ArrayFilter fld $ PersistFilterOperator (Left val) Eq
-- | Like nestEq, but for an embedded list.
-- Checks to see if the nested list contains an item.
nestAnyEq :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => NestedField record [typ] -> typ -> Filter record
fld `nestAnyEq` val = BackendFilter $
NestedArrayFilter fld $ PersistFilterOperator (Left val) Eq
multiBsonEq :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => EntityField record [typ] -> DB.Value -> Filter record
multiBsonEq = anyBsonEq
{-# DEPRECATED multiBsonEq "Please use anyBsonEq instead" #-}
-- | same as `anyEq`, but give a BSON Value
anyBsonEq :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => EntityField record [typ] -> DB.Value -> Filter record
fld `anyBsonEq` val = BackendFilter $
ArrayFilter fld $ MongoFilterOperator val
nestSet, nestInc, nestDec, nestMul :: forall record typ.
( PersistField typ , PersistEntityBackend record ~ DB.MongoContext)
=> NestedField record typ
-> typ
-> Update record
nestSet = nestedUpdateOp Assign
nestInc = nestedUpdateOp Add
nestDec = nestedUpdateOp Subtract
nestMul = nestedUpdateOp Multiply
push, pull, addToSet :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => EntityField record [typ] -> typ -> Update record
fld `push` val = backendArrayOperation MongoPush fld val
fld `pull` val = backendArrayOperation MongoPull fld val
fld `addToSet` val = backendArrayOperation MongoAddToSet fld val
backendArrayOperation ::
forall record typ.
(PersistField typ, BackendSpecificUpdate (PersistEntityBackend record) record ~ MongoUpdate record)
=> MongoUpdateOperator -> EntityField record [typ] -> typ
-> Update record
backendArrayOperation op fld val = BackendUpdate $
ArrayUpdate fld $ UpdateValueOp (Left val) (Right $ MongoSimple op)
-- | equivalent to $each
--
-- > eachOp push field []
--
-- @eachOp pull@ will get translated to @$pullAll@
eachOp :: forall record typ.
( PersistField typ, PersistEntityBackend record ~ DB.MongoContext)
=> (EntityField record [typ] -> typ -> Update record)
-> EntityField record [typ] -> [typ]
-> Update record
eachOp haskellOp fld val = case haskellOp fld (error "eachOp: undefined") of
BackendUpdate (ArrayUpdate _ (UpdateValueOp (Left _) (Right (MongoSimple op)))) -> each op
BackendUpdate (ArrayUpdate{}) -> error "eachOp: unexpected ArrayUpdate"
BackendUpdate (NestedUpdate{}) -> error "eachOp: did not expect NestedUpdate"
Update{} -> error "eachOp: did not expect Update"
where
each op = BackendUpdate $ ArrayUpdate fld $
UpdateValueOp (Right val) (Right $ MongoEach op)
pullAll :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => EntityField record [typ] -> [typ] -> Update record
fld `pullAll` val = eachOp pull fld val
nestedUpdateOp :: forall record typ.
( PersistField typ
, PersistEntityBackend record ~ DB.MongoContext
) => PersistUpdate -> NestedField record typ -> typ -> Update record
nestedUpdateOp op nf v = BackendUpdate $
NestedUpdate nf $ UpdateValueOp (Left v) (Left op)
-- | Intersection of lists: if any value in the field is found in the list.
inList :: PersistField typ => EntityField v [typ] -> [typ] -> Filter v
f `inList` a = Filter (unsafeCoerce f) (Right a) In
infix 4 `inList`
-- | No intersection of lists: if no value in the field is found in the list.
ninList :: PersistField typ => EntityField v [typ] -> [typ] -> Filter v
f `ninList` a = Filter (unsafeCoerce f) (Right a) In
infix 4 `ninList`
| greydot/persistent | persistent-mongoDB/Database/Persist/MongoDB.hs | mit | 59,933 | 197 | 52 | 14,541 | 13,882 | 7,482 | 6,400 | -1 | -1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Config.Database where
import Control.Monad.Logger
import Control.Monad.Trans.Resource
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Database.Persist as DB
import qualified Database.Persist.Postgresql as DB
import System.Environment (lookupEnv)
import Web.Spock.Safe
import Config.Environment
runSQL :: (HasSpock m, SpockConn m ~ DB.SqlBackend) =>
DB.SqlPersistT (NoLoggingT (ResourceT IO)) a -> m a
runSQL action =
runQuery $ \conn ->
runResourceT $ runNoLoggingT $ DB.runSqlConn action conn
{-# INLINE runSQL #-}
parseDatabaseUrl = undefined
getPool :: Environment -> IO DB.ConnectionPool
getPool e = do
s <- getConnectionString e
let n = getConnectionSize e
case e of
Development -> runStdoutLoggingT (DB.createPostgresqlPool s n)
Production -> runStdoutLoggingT (DB.createPostgresqlPool s n)
Test -> runNoLoggingT (DB.createPostgresqlPool s n)
getConnectionString :: Environment -> IO DB.ConnectionString
getConnectionString e = do
m <- lookupEnv "DATABASE_URL"
let s = case m of
Nothing -> getDefaultConnectionString e
Just u -> createConnectionString (parseDatabaseUrl u)
return s
getDefaultConnectionString :: Environment -> DB.ConnectionString
getDefaultConnectionString e =
let n = case e of
Development -> "startapp_development"
Production -> "startapp_production"
Test -> "startapp_test"
in createConnectionString
[ ("host", "localhost")
, ("port", "5432")
, ("user", "folsen")
, ("dbname", n)
]
createConnectionString :: [(T.Text, T.Text)] -> DB.ConnectionString
createConnectionString l =
let f (k, v) = T.concat [k, "=", v]
in encodeUtf8 (T.unwords (map f l))
getConnectionSize :: Environment -> Int
getConnectionSize Development = 1
getConnectionSize Production = 8
getConnectionSize Test = 1
| folsen/haskell-startapp | src/Config/Database.hs | mit | 2,040 | 0 | 15 | 455 | 564 | 298 | 266 | 53 | 3 |
module Filter.Multicol (multicol) where
import Text.Pandoc.Definition
import Text.Pandoc.Walk
tex :: String -> Block
tex = RawBlock (Format "tex")
wrap :: Block -> Block
wrap b = Div ("",[],[])
[ tex $ "%--trim--%\n\\end{pppmulticol}"
, b
, tex $ "\\begin{pppmulticol}\n%--trim--%"
]
columnize :: Bool -> Block -> Block
columnize False b@(Header 1 _ _) = wrap b
columnize _ b = b
multicol :: Pandoc -> Pandoc
multicol doc@(Pandoc meta _) = walk (columnize b) doc
where b = case lookupMeta "documentclass" meta of
Just (MetaString "scrartcl") -> True
_ -> False
| Thhethssmuz/ppp | src/Filter/Multicol.hs | mit | 635 | 0 | 12 | 164 | 223 | 119 | 104 | 18 | 2 |
import BoardTests
import PieceTests
import GameTests
main :: IO ()
main = do pieceSpec
boardSpec
gameSpec
| nablaa/hquarto | test/Spec.hs | gpl-2.0 | 127 | 0 | 7 | 37 | 39 | 18 | 21 | 7 | 1 |
{-# LANGUAGE UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module Code.Class where
import Code.Type
import Code.Param
import Inter.Types
import Challenger.Partial
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Size
import Autolib.Reporter
import Data.Typeable
instance ( ToDoc c, Reader c, ToDoc a, Reader a, Coder c a b, Read b
)
=> Partial ( Encode c ) [ a ] b where
describe ( Encode c ) i = vcat
[ text "Gesucht ist das Ergebnis der Kodierung von"
, nest 4 $ toDoc i
, text "nach dem Verfahren"
, nest 4 $ toDoc c
]
initial ( Encode c ) i = encode c $ take 2 i
total ( Encode c ) i b = do
out <- silent $ encodeR c i
if ( b == out )
then inform $ text "Das Ergebnis ist korrekt."
else reject $ text "Die Antwort ist nicht korrekt."
instance BitSize b => Measure ( Encode c ) [ a ] b where
measure ( Encode c ) xs b = bitSize b
instance OrderScore ( Encode c ) where
scoringOrder _ = None
enc :: ( Reader c, Reader b, ToDoc c, Coder c Char b, Read b ) => c -> Make
enc c = direct (Encode c) "abracadabra"
instance ( ToDoc c, Reader c, ToDoc a, Reader a, Coder c a b, Read b
)
=> Partial ( Decode c ) b [ a ] where
describe ( Decode c ) i = vcat
[ text "Gesucht ist eine Eingabe,"
, text "aus der das Verfahren" <+> toDoc c
, text "diese Ausgabe erzeugt:"
, nest 4 $ toDoc i
]
initial ( Decode c ) i = decode_hint c i
total ( Decode c ) i b = do
out <- silent $ encodeR c b
if ( i == out )
then inform $ text "Die Eingabe ist korrekt."
else reject $ text "Die Antwort ist nicht korrekt."
dec :: (Reader b, Reader c, ToDoc c, ToDoc a, Reader a, Coder c a b , Show b, Read b
)
=> c -> b -> Make
dec c b = direct (Decode c) b
instance Measure ( Decode c ) b [ a ] where
measure ( Decode c ) b xs = fromIntegral $ length xs
instance OrderScore ( Decode c ) where
scoringOrder _ = None
| Erdwolf/autotool-bonn | src/Code/Class.hs | gpl-2.0 | 2,002 | 17 | 12 | 556 | 748 | 385 | 363 | 50 | 1 |
module HEP.Automation.MadGraph.Dataset.Set20110411set3 where
import HEP.Storage.WebDAV
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.ZpHFull
import HEP.Automation.MadGraph.Dataset.Common
import qualified Data.ByteString as B
processTZpLep :: [Char]
processTZpLep =
"\ngenerate P P > t zput QED=99, zput > b~ d, ( t > b w+, w+ > l+ vl ) @1 \nadd process P P > t~ zptu QED=99, (t~ > b~ w-, w- > l- vl~ ), zptu > b d~ @2 \n"
psetup_zphfull_TZpLep :: ProcessSetup ZpHFull
psetup_zphfull_TZpLep = PS {
mversion = MadGraph4
, model = ZpHFull
, process = processTZpLep
, processBrief = "TZpLep"
, workname = "411ZpH_TZpLep"
}
zpHFullParamSet :: [ModelParam ZpHFull]
zpHFullParamSet = [ ZpHFullParam m g (0.28)
| m <- [135.0, 140.0 .. 170.0 ] -- [160.0, 165.0, 170.0] -- [135.0, 140.0 .. 155.0]
, g <- [0.70, 0.75 .. 1.40] ]
psetuplist :: [ProcessSetup ZpHFull]
psetuplist = [ psetup_zphfull_TZpLep ]
sets :: [Int]
sets = [1]
zptasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
zptasklist ssetup csetup =
[ WS ssetup (psetup_zphfull_TZpLep)
(rsetupGen p NoMatch NoUserCutDef NoPGS 10000 num)
csetup
(WebDAVRemoteDir "mc/TeVatronFor3/ZpHFull0411ScanTZpLep")
| p <- zpHFullParamSet , num <- sets ]
totaltasklist :: ScriptSetup -> ClusterSetup ZpHFull -> [WorkSetup ZpHFull]
totaltasklist = zptasklist
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110411set3.hs | gpl-3.0 | 1,585 | 0 | 8 | 325 | 338 | 201 | 137 | 36 | 1 |
module FQuoter.Serialize.Serialize
(
SerializationF (..)
,SerializationT
,Serialization
,create
,associate
,associate2
,dissociate
,search
,lastInsert
,update
,delete
,commitAction
,rollbackAction
,process
,readSchema
,buildNewDB
)
where
import Data.List hiding (delete)
import Data.List.Split
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Free
import Control.Monad.Reader
import Database.HDBC
import Database.HDBC.Sqlite3
import FQuoter.Parser.ParserTypes
import FQuoter.Serialize.SerializedTypes
import FQuoter.Serialize.Grouping
import FQuoter.Serialize.Queries
data SerializationF next
= Create ParsedType next
| Associate PairOfTypes PairOfKeys next
| Associate2 PairOfKeys ParsedType next
| Dissociate PairOfTypes (Either PrimaryKey PairOfKeys) next
| Search DBType SearchTerm ([DBValue SerializedType] -> next)
| LastInsert (PrimaryKey -> next)
| Update PrimaryKey ParsedType next
| Delete DBType PrimaryKey next
| CommitAction next
| RollbackAction next
instance Functor SerializationF where
fmap f (Create st n) = Create st (f n)
fmap f (Associate pts pks n) = Associate pts pks (f n)
fmap f (Associate2 pks t n) = Associate2 pks t (f n)
fmap f (Search typ term n) = Search typ term (f . n)
fmap f (LastInsert n) = LastInsert (f . n)
fmap f (CommitAction n) = CommitAction (f n)
fmap f (RollbackAction n) = RollbackAction (f n)
fmap f (Delete t pk n) = Delete t pk (f n)
fmap f (Update pk st n) = Update pk st (f n)
fmap f (Dissociate pts pks n) = Dissociate pts pks (f n)
type Serialization = FreeF SerializationF
type SerializationT = FreeT SerializationF
associate :: (Monad m) => PairOfTypes -> PairOfKeys -> SerializationT m ()
associate pts pks = liftF $ Associate pts pks ()
dissociate :: (Monad m) => PairOfTypes -> Either PrimaryKey PairOfKeys -> SerializationT m ()
dissociate pts pks = liftF $ Dissociate pts pks ()
associate2 :: (Monad m) => PairOfKeys -> ParsedType -> SerializationT m ()
associate2 pks t = liftF $ Associate2 pks t ()
create :: (Monad m) => ParsedType -> SerializationT m ()
create t = liftF $ Create t ()
delete :: (Monad m) => DBType -> PrimaryKey -> SerializationT m ()
delete t k = liftF $ Delete t k ()
search :: (Monad m) => DBType -> SearchTerm -> SerializationT m [DBValue SerializedType]
search typ term = liftF $ Search typ term id
lastInsert :: (Monad m) => SerializationT m PrimaryKey
lastInsert = liftF $ LastInsert id
update :: (Monad m) => PrimaryKey -> ParsedType -> SerializationT m ()
update pk pt = liftF $ Update pk pt ()
commitAction :: (Monad m) => SerializationT m ()
commitAction = liftF $ CommitAction ()
rollbackAction :: (Monad m) => SerializationT m ()
rollbackAction = liftF $ RollbackAction ()
process :: (IConnection c, MonadIO m) => SerializationT (ReaderT c m) next -> ReaderT c m next
process fr = runFreeT fr >>= process'
process' :: (IConnection c, MonadIO m) => Serialization next (SerializationT (ReaderT c m) next) -> ReaderT c m next
process' (Pure r) = return r
process' (Free (Create t n)) = do c <- ask
liftIO $ c <~ t
process n
process' (Free (Search t s n)) = do c <- ask
v <- liftIO $ c ~> (t,s)
v' <- mapM (return . unsqlizeST t) (groupSql t v)
process (n v')
process' (Free (Associate pot pok n)) = do c <- ask
liftIO $ c <~> (pot, pok)
process n
process' (Free (Dissociate pot pok n)) = do c <- ask
liftIO $ c <~/> (pot, pok)
process n
process' (Free (Associate2 pks t n)) = do c <- ask
liftIO $ c <~~ (pks, t)
process n
process' (Free (LastInsert n)) = do c <- ask
l <- liftIO $ queryLastInsert c
process (n l)
process' (Free (CommitAction n)) = do c <- ask
liftIO $ commit c
process n
process' (Free (Delete t k n)) = do c <- ask
liftIO $ c </~ (t, k)
process n
process' (Free (RollbackAction n)) = do c <- ask
liftIO $ rollback c
process n
process' (Free (Update pk o n)) = do c <- ask
liftIO $ c <~* (o, pk)
process n
{- Insertion -}
(<~) :: (IConnection c) => c -> ParsedType -> IO ()
conn <~ s = void (run conn (getInsert s) (SqlNull:sqlize s) )
(</~) :: (IConnection c) => c -> (DBType, PrimaryKey) -> IO ()
conn </~ (t,k) = void $ run conn (getDelete t) [toSql k]
{- Search -}
(~>) :: (IConnection c) => c -> (DBType, SearchTerm) -> IO [[SqlValue]]
conn ~> (t,st) = uncurry (lookUp conn) (t,st)
{- Associate data in a many-to-many relation -}
(<~>) :: (IConnection c) => c -> (PairOfTypes, PairOfKeys) -> IO ()
conn <~> (ts, ks) = void(run conn query (SqlNull:sqlizePair ks))
where query = uncurry getAssociate ts
(<~/>) :: (IConnection c) => c -> (PairOfTypes, Either PrimaryKey PairOfKeys) -> IO ()
conn <~/> (ts, Left pk) = void(run conn query [toSql pk])
where query= uncurry getFullDissociate ts
conn <~/> (ts, Right pks) = void(run conn query $ sqlizePair pks)
where query = uncurry getDissociate ts
{- Associate data in a triple relationship -}
(<~~) :: (IConnection c) => c -> (PairOfKeys, ParsedType) -> IO ()
conn <~~ (p, t@(PMetadataValue s)) = void(run conn (getInsert t) (SqlNull:toSql s:sqlizePair p))
_ <~~ (_, _) = error "Unsupported type for Association2."
{- Update -}
(<~*) :: (IConnection c) => c -> (ParsedType, PrimaryKey) -> IO ()
conn <~* (st, pk) = void (run conn query (sqlize st ++ [toSql pk]))
where
query = getUpdate st
sqlizePair :: PairOfKeys -> [SqlValue]
sqlizePair (k1,k2) = [toSql k1, toSql k2]
--- IO methods
lookUp :: (IConnection c) => c
-> DBType
-> SearchTerm
-> IO [[SqlValue]]
lookUp conn t st = quickQuery' conn sQuery (searchArray sQuery st)
where sQuery = getSearch t st
-- Get the id of last insertion
queryLastInsert :: (IConnection c) => c -> IO Integer
queryLastInsert conn = do
result <- quickQuery' conn "select last_insert_rowid()" []
return $ fromSql . head . head $ result
-- For a given search, put as many "%<search_term>%" as needed by
-- the query
searchArray :: String -> SearchTerm -> [SqlValue]
searchArray query (ByName s) = replicate (paramNumber query)
$ toSql $ "%" ++ s ++ "%"
where
paramNumber = length . filter ('?' ==)
searchArray _ (ById i) = [toSql i]
searchArray _ (ByIn xs) = [toSql . intercalate "," $ xs]
searchArray _ (ByAssociation _ i) = [toSql i]
-- Convert an author to a list of SqlValue for insertion
-- Create a new database from a schema.sql file
buildNewDB :: FilePath -- Schema file
-> FilePath -- DB to create
-> IO ()
buildNewDB schemaF toCreate = do
conn <- connectSqlite3 toCreate
commands <- readSchema schemaF
mapM_ (flip (run conn) []) . init $ commands
commit conn
disconnect conn
return ()
readSchema :: FilePath -> IO [String]
readSchema schemaF = do
content <- readFile schemaF
return $ splitOn ";" content
| Raveline/FQuoter | lib/FQuoter/Serialize/Serialize.hs | gpl-3.0 | 8,005 | 0 | 13 | 2,602 | 2,853 | 1,454 | 1,399 | 162 | 1 |
module Types where
type VarType = String
data Lambda
= Var VarType
| App Lambda Lambda
| Abs VarType Lambda
deriving Show
data Definition = Def
{ name :: String
, expr :: Lambda
} deriving Show
type Source = [Definition]
| xkollar/lambda2js | src/Types.hs | gpl-3.0 | 255 | 0 | 8 | 75 | 69 | 43 | 26 | 12 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.IAM.GenerateCredentialReport
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Generates a credential report for the AWS account. For more information
-- about the credential report, see
-- <http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html Getting Credential Reports>
-- in the /Using IAM/ guide.
--
-- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_GenerateCredentialReport.html AWS API Reference> for GenerateCredentialReport.
module Network.AWS.IAM.GenerateCredentialReport
(
-- * Creating a Request
generateCredentialReport
, GenerateCredentialReport
-- * Destructuring the Response
, generateCredentialReportResponse
, GenerateCredentialReportResponse
-- * Response Lenses
, gcrrsState
, gcrrsDescription
, gcrrsResponseStatus
) where
import Network.AWS.IAM.Types
import Network.AWS.IAM.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'generateCredentialReport' smart constructor.
data GenerateCredentialReport =
GenerateCredentialReport'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GenerateCredentialReport' with the minimum fields required to make a request.
--
generateCredentialReport
:: GenerateCredentialReport
generateCredentialReport = GenerateCredentialReport'
instance AWSRequest GenerateCredentialReport where
type Rs GenerateCredentialReport =
GenerateCredentialReportResponse
request = postQuery iAM
response
= receiveXMLWrapper "GenerateCredentialReportResult"
(\ s h x ->
GenerateCredentialReportResponse' <$>
(x .@? "State") <*> (x .@? "Description") <*>
(pure (fromEnum s)))
instance ToHeaders GenerateCredentialReport where
toHeaders = const mempty
instance ToPath GenerateCredentialReport where
toPath = const "/"
instance ToQuery GenerateCredentialReport where
toQuery
= const
(mconcat
["Action" =:
("GenerateCredentialReport" :: ByteString),
"Version" =: ("2010-05-08" :: ByteString)])
-- | Contains the response to a successful GenerateCredentialReport request.
--
-- /See:/ 'generateCredentialReportResponse' smart constructor.
data GenerateCredentialReportResponse = GenerateCredentialReportResponse'
{ _gcrrsState :: !(Maybe ReportStateType)
, _gcrrsDescription :: !(Maybe Text)
, _gcrrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'GenerateCredentialReportResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gcrrsState'
--
-- * 'gcrrsDescription'
--
-- * 'gcrrsResponseStatus'
generateCredentialReportResponse
:: Int -- ^ 'gcrrsResponseStatus'
-> GenerateCredentialReportResponse
generateCredentialReportResponse pResponseStatus_ =
GenerateCredentialReportResponse'
{ _gcrrsState = Nothing
, _gcrrsDescription = Nothing
, _gcrrsResponseStatus = pResponseStatus_
}
-- | Information about the state of the credential report.
gcrrsState :: Lens' GenerateCredentialReportResponse (Maybe ReportStateType)
gcrrsState = lens _gcrrsState (\ s a -> s{_gcrrsState = a});
-- | Information about the credential report.
gcrrsDescription :: Lens' GenerateCredentialReportResponse (Maybe Text)
gcrrsDescription = lens _gcrrsDescription (\ s a -> s{_gcrrsDescription = a});
-- | The response status code.
gcrrsResponseStatus :: Lens' GenerateCredentialReportResponse Int
gcrrsResponseStatus = lens _gcrrsResponseStatus (\ s a -> s{_gcrrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-iam/gen/Network/AWS/IAM/GenerateCredentialReport.hs | mpl-2.0 | 4,447 | 0 | 13 | 877 | 553 | 332 | 221 | 74 | 1 |
module HLol.Network.Rest (
get,
getWithOpts,
sendAPIRequest,
sendAPIRequest',
sendAPIRequest_,
LolRequest,
LolError,
Region(..)
) where
import HLol.Data.Common
import HLol.Logging.Logger
import HLol.Utils
import Control.Monad
import Network.Curl
import Data.Aeson
import Data.List (intercalate)
import Data.ByteString.Lazy (ByteString)
tag :: String
tag = "HLol.Network.Rest"
api_key :: String
api_key = "0e27e5ee-0a34-4e08-abb3-7f8186b4f6d4"
base_url :: Region -> String
base_url r = let rs = show r in "https://" ++ rs ++ ".api.pvp.net/api/lol/" ++ rs
type LolRequest = String
get :: (FromJSON a) => String -> IO (Either LolError a)
get url = do
resp <- sendAPIRequest url []
return $ join $ mapR (liftError . eitherDecode) resp
getWithOpts :: (FromJSON a) => String -> [(String, String)] -> IO (Either LolError a)
getWithOpts url opts = do
resp <- sendAPIRequest url opts
return $ join $ mapR (liftError . eitherDecode) resp
sendAPIRequest' :: (Region -> String) -> LolRequest -> [(String, String)] -> IO (Either LolError ByteString)
sendAPIRequest' base_urlf url opts = do
let opts_str = intercalate "&" . map (\(x, y) -> x ++ "=" ++ y) $ ("api_key", api_key) : opts
let url_str = base_urlf EUW ++ url ++ "?" ++ opts_str
lolInfo tag $ "GET: " ++ url_str
resp <- curlGetResponse_ url_str [] :: IO (CurlResponse_ [(String, String)] ByteString)
case respCurlCode resp of
CurlOK -> return $ Right $ respBody resp
_ -> do
lolError tag $ "GET \"" ++ url_str ++ "\" gave response: " ++ show code
return $ Left code
where code = getErrorCode $ respStatus resp
sendAPIRequest :: LolRequest -> [(String, String)] -> IO (Either LolError ByteString)
sendAPIRequest = sendAPIRequest' base_url
sendAPIRequest_ :: LolRequest -> IO (Either LolError ByteString)
sendAPIRequest_ url_str = do
resp <- curlGetResponse_ url_str [] :: IO (CurlResponse_ [(String, String)] ByteString)
lolInfo tag $ "GET: " ++ url_str
case respCurlCode resp of
CurlOK -> return $ Right $ respBody resp
_ -> do
lolError tag $ "GET \"" ++ url_str ++ "\" gave response: " ++ show code
return $ Left code
where code = getErrorCode $ respStatus resp
getErrorCode :: Int -> LolError
getErrorCode i =
case i of
400 -> BadRequest
401 -> Unauthorized
404 -> NotFound
429 -> RateLimitExceeded
500 -> InternalServerError
503 -> ServiceUnavailable
e -> error $ "Unknown error code: " ++ show e
| tetigi/hlol | src/HLol/Network/Rest.hs | agpl-3.0 | 2,691 | 0 | 17 | 712 | 864 | 442 | 422 | 66 | 7 |
module Print3Broken where
printSecond :: String -> IO ()
printSecond greeting = do
putStrLn greeting
main :: IO ()
main = do
putStrLn greeting
printSecond greeting
where greeting = "Yarrrrr"
| aniketd/learn.haskell | haskellbook/printbroken.hs | unlicense | 209 | 0 | 7 | 48 | 66 | 32 | 34 | 9 | 1 |
module Main where
main :: IO ()
main = putStrLn "main"
| haroldcarr/learn-haskell-coq-ml-etc | haskell/topic/testing/2019-11-oskar-wickstrom-tt-and-fixing-bugs-with-property-based-testing/app/Main.hs | unlicense | 57 | 0 | 6 | 13 | 22 | 12 | 10 | 3 | 1 |
module RayCaster.Color where
data Color = Color Double Double Double deriving (Eq, Show)
red :: Color
red = Color 1 0 0
green :: Color
green = Color 0 1 0
blue :: Color
blue = Color 0 0 1
white :: Color
white = Color 1 1 1
black :: Color
black = Color 0 0 0
pink :: Color
pink = Color 1 0.5 0.5
colorMult :: Double -> Color -> Color
colorMult v (Color r g b) = Color (r * v) (g * v) (b * v)
colorSurfaceInteraction :: Color -> Color -> Color
colorSurfaceInteraction (Color surfR surfG surfB) (Color lightR lightG lightB) =
(Color (surfR * lightR / 255) (surfG * lightG / 255) (surfB * lightB / 255))
colorAdd :: Color -> Color -> Color
colorAdd (Color r1 g1 b1) (Color r2 g2 b2) = Color (r1 + r2) (g1 + g2) (b1 + b2)
| bkach/HaskellRaycaster | src/RayCaster/Color.hs | apache-2.0 | 731 | 0 | 9 | 165 | 350 | 185 | 165 | 21 | 1 |
module Activate where
import GLUTContext
import Transform
import qualified Display
import qualified Input
import qualified Idle
import qualified Time
import Control.Lens
import Control.Applicative
import Data.IORef
import Graphics.UI.GLUT
activate :: GLUTContext a -> Transform a -> Display.Displayer a -> IO ()
activate c t d = do
activateInput c
activateIdle c t
activateDisplay c d
activateDisplay :: GLUTContext a -> Display.Displayer a -> IO ()
activateDisplay c d = displayCallback $= Display.callback c d
activateIdle :: GLUTContext a -> Transform a -> IO ()
activateIdle c t = idleCallback $= Just (Idle.callback c t)
activateInput :: GLUTContext a -> IO ()
activateInput c = keyboardMouseCallback $= c ^. inputRef . to Input.callback. to Just
context :: a -> IO (GLUTContext a)
context init = pure GLUTContext <*> newIORef [] <*> Time.newTimeIORef <*> newIORef init
| epeld/zatacka | old/Activate.hs | apache-2.0 | 900 | 0 | 9 | 158 | 312 | 154 | 158 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
module BV
(
-- * BV Language
Program (..)
, Expr (..)
, Bin (..)
, Op1 (..)
, Op2 (..)
, ID
-- * Semantics
, Value
, Env
, eval
-- * Metadata
, Measureable (..)
, Op (..)
, isValidFor
-- * Pretty Printing
, Render (..)
-- * Parsing
, program
, parseProgram
, parseExpr
-- * User-friendly combinators
, var
, b0, b1
, if0
, fold
, not', shl1, shr1, shr4, shr16
, and', or', xor', plus
) where
import Control.Monad
import Data.Char
import Data.Bits
import Data.Char (toLower)
import Data.List (union, (\\))
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.Maybe
import Data.Word
import SExp
{--------------------------------------------------------------------
BV Language
--------------------------------------------------------------------}
data Program = Program ID Expr
deriving (Eq, Ord, Show)
data Expr
= Const Bin
| Var ID
| If0 Expr Expr Expr
| Fold Expr Expr ID ID Expr
| Op1 Op1 Expr
| Op2 Op2 Expr Expr
deriving (Eq, Ord, Show)
data Bin = Zero | One
deriving (Eq, Ord, Show, Bounded, Enum)
data Op1 = NOT | SHL1 | SHR1 | SHR4 | SHR16
deriving (Eq, Ord, Show, Bounded, Enum)
data Op2 = AND | OR | XOR | PLUS
deriving (Eq, Ord, Show, Bounded, Enum)
type ID = String
{--------------------------------------------------------------------
Semantics
--------------------------------------------------------------------}
type Value = Word64
type Env = Map ID Value
eval :: Program -> Value -> Value
eval (Program arg body) val = eval1 (Map.singleton arg val) body
eval1 :: Env -> Expr -> Value
eval1 env (Const b) =
case b of
One -> 1
Zero -> 0
eval1 env (Var id) = env Map.! id
eval1 env (If0 c t e) =
if eval1 env c == 0
then eval1 env t
else eval1 env e
eval1 env (Fold e0 e1 x y e2) = foldr phi v1 vs
where
v0 = eval1 env e0
v1 = eval1 env e1
vs = [(v0 `shiftR` s) .&. 0xFF | s <- [56,48..0]]
phi vx vy = eval1 env' e2
where
env' = Map.insert x vx $ Map.insert y vy env
eval1 env (Op1 op e) = evalOp1 op (eval1 env e)
eval1 env (Op2 op e1 e2) = evalOp2 op (eval1 env e1) (eval1 env e2)
evalOp1 :: Op1 -> Value -> Value
evalOp1 NOT = complement
evalOp1 SHL1 = (`shiftL` 1)
evalOp1 SHR1 = (`shiftR` 1)
evalOp1 SHR4 = (`shiftR` 4)
evalOp1 SHR16 = (`shiftR` 16)
evalOp2 :: Op2 -> Value -> Value -> Value
evalOp2 AND = (.&.)
evalOp2 OR = (.|.)
evalOp2 XOR = xor
evalOp2 PLUS = (+)
{--------------------------------------------------------------------
Metadata
--------------------------------------------------------------------}
-- | size is method as |.|
class Measureable a where
size :: a -> Int
instance Measureable Expr where
size (Const _) = 1
size (Var _) = 1
size (If0 e0 e1 e2) = 1 + size e0 + size e1 + size e2
size (Fold e0 e1 x y e2) = 2 + size e0 + size e1 + size e2
size (Op1 _ e0) = 1 + size e0
size (Op2 _ e0 e1) = 1 + size e0 + size e1
instance Measureable Program where
size (Program x e) = 1 + size e
class Op a where
op :: a -> Set String
instance Op Expr where
op (Const _) = Set.empty
op (Var _) = Set.empty
op (If0 e0 e1 e2) = Set.unions [Set.singleton "if0", op e0, op e1, op e2]
op (Fold e0 e1 x y e2) = Set.unions [Set.singleton "fold", op e0, op e1, op e2]
op (Op1 o e0) = Set.insert (render o) (op e0)
op (Op2 o e0 e1) = Set.unions [Set.singleton (render o), op e0, op e1]
-- for convienience
instance Op Program where
op (Program _ e) = op e
-- | Operators constraints
isValidFor :: Program -> [String] -> Bool
Program x e `isValidFor` ops
| "tfold" `elem` ops =
case e of
Fold (Var x') (Const Zero) x'' y e' -> x == x' && x == x'' && op e' == ops'
_ -> False
| otherwise = op e == ops'
where
ops' = Set.fromList ops `Set.difference` Set.fromList ["tfold", "bonus"]
{--------------------------------------------------------------------
Pretty Printing
--------------------------------------------------------------------}
class Render a where
render :: a -> String
instance Render Program where
render = renderSExp . toSExp
instance Render Expr where
render = renderSExp . toSExp
instance Render Op1 where
render = renderSExp . toSExp
instance Render Op2 where
render = renderSExp . toSExp
instance ToSExp Program where
toSExp (Program x body) =
SApply [ SAtom "lambda"
, SApply [SAtom x]
, toSExp body
]
instance ToSExp Expr where
toSExp (Const b) = toSExp b
toSExp (Var x) = toSExp x
toSExp (If0 c t e) = SApply [SAtom "if0", toSExp c, toSExp t, toSExp e]
toSExp (Fold e0 e1 x y e2) =
SApply [ SAtom "fold"
, toSExp e0
, toSExp e1
, SApply [ SAtom "lambda"
, SApply [SAtom x, SAtom y]
, toSExp e2
]
]
toSExp (Op1 op e) = SApply [toSExp op, toSExp e]
toSExp (Op2 op e1 e2) = SApply [toSExp op, toSExp e1, toSExp e2]
instance ToSExp Bin where
toSExp Zero = SAtom "0"
toSExp One = SAtom "1"
instance ToSExp ID where
toSExp v = SAtom v
instance ToSExp Op1 where
toSExp = SAtom . map toLower . show
instance ToSExp Op2 where
toSExp = SAtom . map toLower . show
{--------------------------------------------------------------------
Parsing
--------------------------------------------------------------------}
program :: String -> Program
program = fromJust . parseProgram
parseProgram :: String -> Maybe Program
parseProgram s = fromSExp =<< parseSExp s
parseExpr :: String -> Maybe Expr
parseExpr s = fromSExp =<< parseSExp s
instance FromSExp Program where
fromSExp (SApply [SAtom "lambda", SApply [SAtom x], body]) = do
e <- fromSExp body
return $ Program x e
fromSExp _ = mzero
instance FromSExp Expr where
fromSExp s =
msum
[ liftM Const (fromSExp s)
, case s of
SApply [SAtom "if0", c, t, e] -> do
c' <- fromSExp c
t' <- fromSExp t
e' <- fromSExp e
return $ If0 c' t' e'
_ -> mzero
, case s of
SApply [SAtom "fold", e0, e1, SApply [SAtom "lambda", SApply [SAtom x, SAtom y], e2]] -> do
e0' <- fromSExp e0
e1' <- fromSExp e1
e2' <- fromSExp e2
return $ Fold e0' e1' x y e2'
_ -> mzero
, case s of
SApply [op, e] -> do
op' <- fromSExp op
e' <- fromSExp e
return $ Op1 op' e'
_ -> mzero
, case s of
SApply [op, e1, e2] -> do
op' <- fromSExp op
e1' <- fromSExp e1
e2' <- fromSExp e2
return $ Op2 op' e1' e2'
_ -> mzero
, liftM Var (fromSExp s) -- IDはワイルドカード的になってしまうので意図的に最後に
]
instance FromSExp ID where
fromSExp (SAtom x) = return x
fromSExp _ = mzero
instance FromSExp Bin where
fromSExp (SAtom "0") = return Zero
fromSExp (SAtom "1") = return One
fromSExp _ = mzero
instance FromSExp Op1 where
fromSExp (SAtom x) = listToMaybe [op | op <- [minBound..maxBound], x == render op]
fromSExp _ = mzero
instance FromSExp Op2 where
fromSExp (SAtom x) = listToMaybe [op | op <- [minBound..maxBound], x == render op]
fromSExp _ = mzero
{--------------------------------------------------------------------
User-friendly combinators
--------------------------------------------------------------------}
var :: String -> Expr
var = Var
b0, b1 :: Expr
b0 = Const Zero
b1 = Const One
if0 :: Expr -> Expr -> Expr -> Expr
if0 = If0
fold :: Expr -> Expr -> ID -> ID -> Expr -> Expr
fold = Fold
not', shl1, shr1, shr4, shr16 :: Expr -> Expr
not' = Op1 NOT
shl1 = Op1 SHL1
shr1 = Op1 SHR1
shr4 = Op1 SHR4
shr16 = Op1 SHR16
and', or', xor', plus :: Expr -> Expr -> Expr
and' = Op2 AND
or' = Op2 OR
xor' = Op2 XOR
plus = Op2 PLUS
| msakai/icfpc2013 | src/BV.hs | bsd-2-clause | 8,075 | 0 | 17 | 2,160 | 3,006 | 1,564 | 1,442 | 230 | 3 |
module GameState (bestMove, GameState(GameState, token, board)) where
import Tree
import Board
import Token
import Minimax
import Data.Foldable
import Valuable
import Prelude
bestMove s@(GameState X _) = findMove s findMax minimize
bestMove s@(GameState O _) = findMove s findMin maximize
data GameState = GameState { token :: Token, board :: Board } deriving (Eq)
instance Valuable GameState where
value (GameState _ board) = boardValue board
instance Show GameState where
show (GameState _ board) = show board
instance Tree GameState where
isLeaf (GameState token board) = xWins board || oWins board || tie board
children (GameState X board) = map (GameState O) (movesFor board X)
children (GameState O board) = map (GameState X) (movesFor board O)
instance Ord GameState where
compare (GameState _ a) (GameState _ b) = compare a b
findMove state comparison strategy = fst $ foldl' comparison (head pairs) pairs
where moves = children state
values = map strategy moves
pairs = zip moves values
findMax = compareBoards xWins
findMin = compareBoards oWins
compareBoards shortCircuit a@(s, x) b@(_, y)
| shortCircuit newBoard = a
| x < y = a
| otherwise = b
where newBoard = board s
| MichaelBaker/haskell-tictactoe | src/GameState.hs | bsd-2-clause | 1,375 | 0 | 8 | 383 | 473 | 244 | 229 | 34 | 1 |
import Data.Array
import qualified Data.Map as M
import Data.Maybe
import System.IO.Unsafe
-- SegTree
data SegTree a = StLeaf Int a | StNode Int Int a (SegTree a) (SegTree a) deriving (Eq, Ord, Show)
buildrmq acc cs lvs x = acc'
where
updacc (lstseq, lstmap, ix) = (lstseq', lstmap', succ ix)
where
lstseq' = (ix, ((lvs ! x), x)) : lstseq
lstmap' = (x, ix) : lstmap
f acc c = updacc acc'
where
acc' = buildrmq acc cs lvs c
acc' = foldl f (updacc acc) (cs ! x)
buildst arrseq a b =
if a == b
then
let minx = arrseq ! a
in (minx, StLeaf a minx)
else
let midp = cmidp a b
(minl, lt) = buildst arrseq a (midp - 1)
(minr, rt) = buildst arrseq midp b
minx = min minl minr
in (minx, StNode a b minx lt rt)
lcast (StLeaf _ x) _ _ = x
lcast (StNode l r x lt rt) a b =
if a <= l && r <= b
then x
else minimum $ (\(_, t) -> lcast t a b) `map` rs
where
midp = cmidp l r
rs = (((a, b) `intersects`) . fst) `filter` [((l, midp - 1), lt), ((midp, r), rt)]
lca (st, lm, rm) a b =
if al <= bl && br <= ar
then a
else
if bl <= al && ar <= br
then b
else
if al < bl
then snd $ lcast st ar bl
else snd $ lcast st br al
where
al = lm ! a
ar = rm ! a
bl = lm ! b
br = rm ! b
-- PTree
data PTree = PtLeaf | PtNode (Int, Int) PTree PTree deriving (Eq, Ord, Show)
buildpt 0 acc = (acc, PtLeaf)
buildpt n acc = (acc'', PtNode x lt rt)
where
midp = cmidp 0 n
(x : acc', lt) = buildpt (pred midp) acc
(acc'', rt) = buildpt (n - midp) acc'
buildns cs lvs acc (n, accn) x = ((myn, myt), (x, myt) : acc')
where
accn' = (x, lvs ! x) : accn
mcs = cs ! x
f ((nn, t), acc) c = (if nn' < nn then (nn', t') else (nn, t), acc')
where
((nn', t'), acc') = buildns cs lvs acc (succ n, accn') c
(acc', myn, myt) =
if null mcs
then
let (_, t) = buildpt (succ n) accn'
in (acc, n, t)
else
let (mmc : mmcs) = mcs
init = buildns cs lvs acc (succ n, accn') mmc
((n', t'), acc') = foldl f init mmcs
in (acc', n', t')
jnl (Just (x', lv')) (x, lv) = if x' < x then Just (x', lv') else Just (x, lv)
ptfl PtLeaf acc _ = acc
ptfl (PtNode n@(x, lv) lt rt) Nothing tgt =
if x == tgt
then Just n
else
if x < tgt
then ptfl lt Nothing tgt
else ptfl rt (Just n) tgt
ptfl (PtNode n@(x, lv) lt rt) acc tgt =
if x == tgt
then Just n
else
if x < tgt
then acc
else ptfl rt (jnl acc n) tgt
jnr (Just (x', lv')) (x, lv) = if x' > x then Just (x', lv') else Just (x, lv)
ptfr PtLeaf acc _ = acc
ptfr (PtNode n@(x, lv) lt rt) Nothing tgt =
if x == tgt
then Just n
else
if x > tgt
then ptfr rt Nothing tgt
else ptfr lt (Just n) tgt
ptfr (PtNode n@(x, lv) lt rt) acc tgt =
if x == tgt
then Just n
else
if x > tgt
then acc
else ptfr lt (jnr acc n) tgt
cmp lvs t l r l' r' = if r < l' || r' < l then 0 else (rlv - llv + 1)
where
llv = if l <= l' && l' <= r then lvs ! l' else snd $ fromJust $ ptfl t Nothing l
rlv = if l <= r' && r' <= r then lvs ! r' else snd $ fromJust $ ptfr t Nothing r
-- Misc
(a1, b1) `intersects` (a2, b2) =
(a2 <= a1 && a1 <= b2) ||
(a2 <= b1 && b1 <= b2) ||
(a1 <= a2 && a2 <= b1)
cmidp a b = (a + b) `div` 2 + 1
buildlvs cs lv x = (x, lv) : ((cs ! x) >>= (buildlvs cs (succ lv)))
swap (x, y) = (y, x)
readLst = return . (read `map`) . words
--
tst _ 0 = return ()
tst pc@(arrlvs, arrns, lcas) m = do
(x : y : l : r : _) <- getLine >>= readLst
let xyLca = lca lcas x y
--putStrLn $ "LCA: " ++ show xyLca
putStrLn $ show (cmp arrlvs (arrns ! x) l r xyLca x + cmp arrlvs (arrns ! y) l r xyLca y - cmp arrlvs (arrns ! xyLca) l r xyLca xyLca)
tst pc (pred m)
main = do
(n : m : _) <- getLine >>= readLst
ps <- getLine >>= readLst
let lstcs = [1 .. n] `zip` [[] | _ <- [1 ..]] ++ ps `zip` ((: []) `map` [2 ..])
let mcs = M.fromListWith (flip (++)) lstcs
let arrcs = array (1, n) (M.toList mcs)
let lstlvs = buildlvs arrcs 1 1
let arrlvs = array (1, n) lstlvs
let (_, lstns) = buildns arrcs arrlvs [] (0, []) 1
let arrns = array (1, n) lstns
let (lstseq, lstmap, finalix) = buildrmq ([], [], 1) arrcs arrlvs 1
let arrseq = array (1, finalix - 1) lstseq
let leftmap = M.toList $ M.fromListWith min lstmap
let rightmap = M.toList $ M.fromListWith max lstmap
let arrlm = array (1, n) leftmap
let arrrm = array (1, n) rightmap
let (minn, lcast) = buildst arrseq 1 (pred finalix)
tst (arrlvs, arrns, (lcast, arrlm, arrrm)) m
--return ()
| pbl64k/HackerRank-Contests | 2014-09-05-FP/ApeWar/aw.pt.hs | bsd-2-clause | 5,290 | 0 | 16 | 2,095 | 2,525 | 1,364 | 1,161 | 122 | 5 |
import Data.Array
import qualified Data.Array.Unboxed as U
import qualified Data.Foldable as Fld
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Sequence as Seq
buildArr la a b f = res
where
res = la (a, b) (map (f (res !)) [a .. b])
merge [] xs = xs
merge xs [] = xs
merge xs@(x : xs') ys@(y : ys') = if x <= y then x : merge xs' ys else y : merge xs ys'
arrlst xs = map (xs !) (U.indices xs)
main = do
pstr <- getLine
let (n : q : _) = map read (words pstr)
es <- mapM (const readEdge) [1 .. pred n]
let mchildren = Map.fromListWith (Seq.><) (map (\(a, b) -> (b, Seq.singleton a)) es)
let children = buildArr listArray 1 n (\_ x -> Fld.toList $ if x `Map.member` mchildren then fromJust $ x `Map.lookup` mchildren else Seq.empty)
let ranks = buildArr U.listArray 1 n (\mem x -> Fld.foldl' (+) 0 ((\x -> succ $ mem x) `map` (children ! x)))
sstr <- getLine
let sals = U.listArray (1, n) (map (read :: String -> Int) (words sstr))
--let klst = buildArr 1 n (\mem x -> merge (sort $ (\x -> (sals ! x, x)) `map` (children ! x)) $ Fld.foldl' merge [] (mem `map` (children ! x)))
--let ks = buildArr 1 n (\_ x -> array (1, (ranks ! x)) (zip [1 ..] (klst ! x)))
let ks = buildArr listArray 1 n (\mem x -> U.listArray (1, ranks ! x) $ merge (sort $ (\x -> (sals ! x, x)) `map` (children ! x)) $ foldl' merge [] ((arrlst . mem) `map` (children ! x)))
tst q 0 ks
tst 0 _ _ = return ()
tst q d ks = do
qstr <- getLine
let (v : k : _) = map read (words qstr)
--let d' = snd $ (ks ! (v + d)) !! (pred k)
let d' = snd $ (ks ! (v + d)) ! k
putStrLn $ show d'
tst (pred q) d' ks
readEdge :: IO (Int, Int)
readEdge = do
estr <- getLine
let (a : b : _) = map read (words estr)
return (a, b)
| pbl64k/HackerRank-Contests | 2014-06-20-FP/BoleynSalary/bs.memo.hs | bsd-2-clause | 1,820 | 0 | 22 | 475 | 859 | 455 | 404 | 36 | 2 |
{-
Copyright (c) 2013, Markus Barenhoff <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Data.DEVS
( module Data.DEVS.Devs
, module Data.DEVS.Simulation
) where
import Data.DEVS.Devs
import Data.DEVS.Simulation
| alios/lambda-devs | Data/DEVS.hs | bsd-3-clause | 1,672 | 0 | 5 | 297 | 35 | 24 | 11 | 5 | 0 |
module RealWorld.Prelude
( module A
, failWith
, (??)
, failWithM
, (!?)
) where
import Prelude as A
import Control.Applicative as A (Alternative(..), optional)
import Control.Monad as A (MonadPlus(..), guard, mfilter, when)
import Control.Monad.Catch as A (MonadThrow(..), catch)
import Control.Monad.Except as A
(ExceptT(..), MonadError(..), mapExceptT, runExceptT, withExceptT)
import Control.Monad.IO.Class as A (MonadIO, liftIO)
import Control.Monad.Reader as A
(MonadReader(..), ReaderT(..), ask, asks, runReaderT)
import Control.Monad.State as A
(MonadState(..), get, gets, modify, modify, put)
import Control.Monad.Time as A (MonadTime(..))
import Data.Aeson as A (FromJSON, ToJSON, parseJSON, toJSON)
import Data.Foldable as A (fold)
import Data.Function as A ((&))
import Data.Hashable as A (Hashable(..))
import Data.HashMap.Lazy as A (HashMap)
import Data.Map as A (Map)
import Data.Maybe as A (isJust)
import Data.Monoid as A ((<>))
import Data.Proxy as A (Proxy(Proxy))
import Data.Set as A (Set)
import Data.Text as A (Text)
import Data.Time as A (UTCTime)
import Data.Traversable as A (for)
import Data.Vector as A (Vector)
import Data.Void as A (Void)
import GHC.Generics as A (Generic)
import GHC.TypeLits as A (KnownSymbol, Symbol, symbolVal)
import Numeric.Natural as A (Natural)
import Web.HttpApiData as A (FromHttpApiData(..), ToHttpApiData(..))
failWith :: MonadError e m => e -> Maybe a -> m a
failWith e = maybe (throwError e) pure
(??) :: MonadError e m => Maybe a -> e -> m a
(??) = flip failWith
failWithM :: MonadError e m => e -> m (Maybe a) -> m a
failWithM e m = m >>= failWith e
(!?) :: MonadError e m => m (Maybe a) -> e -> m a
(!?) = flip failWithM
| zudov/servant-realworld-example-app | src/RealWorld/Prelude.hs | bsd-3-clause | 1,932 | 0 | 10 | 503 | 680 | 432 | 248 | 45 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Text_Align where
import Graphics.Blank
import Wiki -- (578,200)
main :: IO ()
main = blankCanvas 3000 $ \ context -> do
send context $ do
let x = width context / 2
let y = height context / 2
font "30pt Calibri"
textAlign "center"
fillStyle "blue"
fillText("Hello World!", x, y)
wiki $ snapShot context "images/Text_Align.png"
wiki $ close context
| ku-fpg/blank-canvas | wiki-suite/Text_Align.hs | bsd-3-clause | 453 | 0 | 16 | 128 | 138 | 65 | 73 | 15 | 1 |
module SecondFront.Logging(
enableConsoleLogging
) where
import System.IO (stderr)
-- Logging utilities
import System.Log.Formatter (simpleLogFormatter)
import System.Log.Handler (setFormatter, LogHandler)
import System.Log.Handler.Simple
-- import System.Log.Handler.Syslog (Facility (..), Option (..), openlog)
import System.Log.Logger
-- | Activates logging to terminal
enableConsoleLogging :: IO ()
enableConsoleLogging = configureLoggingToConsole
configureLoggingToConsole :: IO ()
configureLoggingToConsole = do
s <- streamHandler stderr DEBUG >>=
\lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg")
setLoggerLevels s
-- configureLoggingToSyslog :: IO ()
-- configureLoggingToSyslog = do
-- s <- openlog "RehMimic" [PID] DAEMON INFO >>=
-- \lh -> return $ setFormatter lh (simpleLogFormatter "[$time : $loggername : $prio] $msg")
-- setLoggerLevels s
setLoggerLevels :: (LogHandler s) => s -> IO ()
setLoggerLevels s = do
updateGlobalLogger rootLoggerName removeHandler
updateGlobalLogger "2ndF" (
setHandlers [s] .
setLevel INFO
) | alcidesv/second-front | hs-src/SecondFront/Logging.hs | bsd-3-clause | 1,256 | 0 | 13 | 311 | 202 | 111 | 91 | 20 | 1 |
module Main where
import Control.Monad
import Data.List
import System.Environment
main = do
innm:outnm:_ <- getArgs
lns <- lines `fmap` readFile innm
writeFile outnm $ unlines $ f lns
f (l:ls) | "\\begin{tabbing}" `isPrefixOf` l =
f $ onHead (drop (length "\\end{tabbing}")) $ dropWhile (not . ("\\end{tabbing}" `isPrefixOf`)) ls
| otherwise = l:f ls
f [] = []
onHead :: (a-> a) -> [a] -> [a]
onHead f [] =[]
onHead f (x:xs) = f x : xs | glutamate/tnutils | StripCode.hs | bsd-3-clause | 479 | 0 | 12 | 120 | 232 | 120 | 112 | 15 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
module Fragment.TyAll.Rules.Type.Infer.Common (
) where
| dalaing/type-systems | src/Fragment/TyAll/Rules/Type/Infer/Common.hs | bsd-3-clause | 211 | 0 | 3 | 36 | 14 | 11 | 3 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Http where
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens (_String, key)
import qualified Data.ByteString.Lazy as BL
import Network.Wreq as WR (get, post, delete, put, customPayloadMethod,
responseBody, responseStatus, statusCode, responseHeaders)
import Network.Wreq.Types
import Data.Text (pack)
import Types
import FireLogic
import UriBuilder
--TODO possibly extract helper function of the last line which is reused in all HTTP operator functions
get :: FireRequest -> IO FireResponse
get (FireRequest url opts) = do
let validation = validateGet opts
let pars = buildParameters opts
response <- WR.get (url ++ "?" ++ pars)
return $ FireResponse (response ^. WR.responseBody) (response ^. WR.responseStatus . WR.statusCode) (response ^. WR.responseHeaders)
post :: FireRequest -> IO FireResponse
post (JSONFireRequest json url opts) = do
let validation = validatePost opts
let pars = buildParameters opts
response <- WR.post (url ++ "?" ++ pars) (toJSON json)
return $ FireResponse (response ^. WR.responseBody) (response ^. WR.responseStatus . WR.statusCode) (response ^. WR.responseHeaders)
delete :: FireRequest -> IO FireResponse
delete (FireRequest url opts) = do
let validation = validateDelete opts
let pars = buildParameters opts
response <- WR.delete (url ++ "?" ++ pars)
return $ FireResponse (response ^. WR.responseBody) (response ^. WR.responseStatus . WR.statusCode) (response ^. WR.responseHeaders)
patch :: FireRequest -> IO FireResponse
patch (JSONFireRequest json url opts) = do
let validation = validatePatch opts
let pars = buildParameters opts
response <- WR.customPayloadMethod "PATCH" (url ++ "?" ++ pars) (toJSON json)
return $ FireResponse (response ^. WR.responseBody) (response ^. WR.responseStatus . WR.statusCode) (response ^. WR.responseHeaders)
put :: FireRequest -> IO FireResponse
put (JSONFireRequest json url opts) = do
let validation = validatePut opts
let pars = buildParameters opts
response <- WR.put (url ++ "?" ++ pars) (toJSON json)
return $ FireResponse (response ^. WR.responseBody) (response ^. WR.responseStatus . WR.statusCode) (response ^. WR.responseHeaders) | sphaso/firebase-haskell-client | src/Http.hs | bsd-3-clause | 2,953 | 0 | 12 | 1,078 | 742 | 378 | 364 | -1 | -1 |
module Interpreter (interpret) where
import Prelude hiding (Left, Right)
import Tokens (tokenize)
import Parser
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Vector as V
import Data.Vector ((!))
import Data.Word
import Text.Printf
type InterpreterState = State (DataTape, String, FunTable, String) String
interpret :: String -> String -> String
interpret inp progcode = evalState (runProg . parse . tokenize $ progcode) (initState inp)
interpretDebug :: String -> String -> String
interpretDebug inp progcode = printf "Output: %s\n\nFinal Tape:\n%s\n\nUnconsumed Input: %s" out (drawTape 12 dt) inp
where
(out, (dt, inp, _, _)) = runState (runProg . parse . tokenize $ progcode) (initState inp)
runProg :: Prog -> InterpreterState
runProg (Join p1 p2) = runProg p1 >> runProg p2
runProg (CommandSequence c) = runCommand c
runProg (Loop l) = do
(dt, _, _, out) <- get
case focus dt of
0 -> return out
otherwise -> runProg l >> runProg (Loop l)
runProg (FunDef f) = do
(dt, inp, ft, out) <- get
let ft' = V.imap (\i v -> if i == fromEnum (focus dt) then Just f else v) ft
put (dt, inp, ft', out)
return out
runProg (Str s) = do
(dt, inp, ft, out) <- get
put (dt, inp ++ s ++ "\0", ft, out)
return out
runCommand :: Command -> InterpreterState
runCommand (Command n op) = do
out <- replicateM n $ runOp op
return $ last out
runOp :: Op -> InterpreterState
runOp Invoke = get >>= (\(dt, _, ft, _) -> runProg $ fromJust $ ft ! fromEnum (focus dt))
runOp op = do
(dt, inp, ft, out) <- get
case op of
Inc -> put (modFocus (+1) dt, inp, ft, out)
Dec -> put (modFocus (\x -> x-1) dt, inp, ft, out)
Left -> put (l dt, inp, ft, out)
Right -> put (r dt, inp, ft, out)
ReadChar -> doReadChar (dt, inp, ft, out)
WriteChar -> put (dt, inp, ft, out ++ [writeChar $ focus dt])
WriteInt -> put (dt, inp, ft, out ++ writeInt (focus dt))
(_, _, _, out') <- get
return out'
where
doReadChar (_, [], _, _) = return ()
doReadChar (dt, i:is, ft, out) = put (modFocus (const $ readChar i) dt, is, ft, out)
type FunTable = V.Vector (Maybe Prog)
initFunTable :: FunTable
initFunTable = V.replicate 256 Nothing
data Tape a = Tape [a] a [a] deriving (Eq)
focus :: Tape a -> a
focus (Tape _ f _) = f
modFocus :: (a -> a) -> Tape a -> Tape a
modFocus f (Tape a b c) = Tape a (f b) c
l :: Tape a -> Tape a
l (Tape [] _ _) = error "Reached end of tape"
l (Tape (a:as) b c) = Tape as a (b:c)
r :: Tape a -> Tape a
r (Tape _ _ []) = error "Reached end of tape"
r (Tape a b (c:cs)) = Tape (b:a) c cs
initTape :: [a] -> Tape a
initTape [] = error "Cannot initialise an empty tape"
initTape (x:xs) = Tape [] x xs
instance Functor Tape where
fmap f (Tape a b c) = Tape (map f a) (f b) (map f c)
drawTape :: Show a => Int -> Tape a -> String
drawTape n (Tape r v f) = printf "... %s [%s] %s ..." (drawList $ reverse $ take n r) (drawCell v) (drawList $ take n f)
where
drawList = intercalate " " . map drawCell
drawCell = show
type DataTape = Tape Word8
initDataTape :: DataTape
initDataTape = initTape $ repeat 0
readChar :: Char -> Word8
readChar = toEnum . fromEnum
writeChar :: Word8 -> Char
writeChar = toEnum . fromEnum
writeInt :: Word8 -> String
writeInt = filter isDigit . show
initState :: String -> (DataTape, String, FunTable, String)
initState inp = (initDataTape, inp, initFunTable, "")
| tcsavage/rumex | src/Interpreter.hs | bsd-3-clause | 3,423 | 0 | 17 | 712 | 1,659 | 876 | 783 | 90 | 8 |
module Input(InputState, isDown) where
import Data.Map(Map)
import qualified Data.Map as Map
type InputState = Map Char Bool
isDown ch m = maybe False id (Map.lookup ch m)
| Rotsor/wheeled-vehicle | Input.hs | bsd-3-clause | 175 | 0 | 8 | 30 | 68 | 39 | 29 | 5 | 1 |
{-# LANGUAGE DeriveFunctor, RankNTypes, GADTs #-}
module BinaryIndexedTree where
import Prelude hiding (sum)
import Control.Monad (forM_)
import Control.Monad.ST
import Control.Monad.Primitive (PrimState, PrimMonad)
import Data.Bits
import Data.Monoid
import qualified Data.Vector.Mutable as M
import qualified Data.Vector as V
-- サンプルコード用
import Control.Arrow (second)
import Data.List ((\\))
data BIT a = BIT { getN :: Int
, vec :: V.Vector a
}
deriving Show
{- |
construct BIT by maximum value n.
-}
new :: Monoid a => Int -> BIT a
new n = BIT n (V.replicate (n+1) mempty) -- we can use from 1-index.
{- |
increment the value at index i(1-base) by amount w. O(log n)
But this use immutable Vector.
-}
inc :: Monoid a => Int -> a -> BIT a -> BIT a
inc i w b | 1 <= i && i <= n = b { vec = V.accum (<>) v . zip xs . repeat $ w }
| otherwise = error $ "index must be between 1 to " ++ show n
where (n, v) = (getN b, vec b)
xs = takeWhile (<=n) . iterate (\x -> x + x .&. (-x)) $ i
{- |
increment the value at index i(1-base) by amount w. O(log n)
this use mutable Vector.
-}
inc' :: Monoid a => Int -> a -> BIT a -> BIT a
inc' i w b =
BIT n $ V.create $ do
mv <- V.thaw v
forM_ xs $ M.modify mv (<>w)
return mv
where
(n, v) = (getN b, vec b)
xs = takeWhile (<=n) . iterate (\x -> x + x .&. (-x)) $ i
{- |
lookup the sum of all values from index 1 to index i. O(log n)
-}
(!) :: Monoid a => BIT a -> Int -> a
b ! i | 1 <= i && i <= n = foldr (\i acc -> acc <> v V.! i) mempty xs
| otherwise = error $ "index must be between 1 to " ++ show n
where (n, v) = (getN b, vec b)
xs = takeWhile (>0) . iterate (\x -> x - x .&. (-x)) $ i
--------------------------------------------------------------------------------
{- | 転倒数
1-9 までの数だけでできたリストの転倒数をもとの数と組にして返す.
>>> inverse9 [4,1,5,2,6,3]
[(4,0),(1,1),(5,0),(2,2),(6,0),(3,3)]
-}
inverse9 :: [Int] -> [(Int, Int)]
inverse9 xs = map (second getSum) $ go xs b []
where n = maximum xs
b = new n :: BIT (Sum Int)
go [] b acc = zip xs (reverse acc)
go (x:xs) b acc = let acc' = b ! n - b ! x : acc
b' = inc' x 1 b
in go xs b' acc'
{- | 転倒対象リスト
1-9 までの数だけでできたリストの転倒している対象要素をリストアップ.
>>> inverse9' [4,1,5,2,6,3]
[(4,[]),(1,[4]),(5,[]),(2,[4,5]),(6,[]),(3,[4,5,6])]
-}
inverse9' :: [Int] -> [(Int, [Int])]
inverse9' xs = go xs b []
where n = maximum xs
b = new n :: BIT [Int]
go [] b acc = zip xs (reverse acc)
go (x:xs) b acc = let acc' = (b ! n \\ b ! x) : acc
b' = inc' x [x] b
in go xs b' acc'
{- | 転倒対象インデックスリスト
1-9 までの数だけでできたリストの転倒している対象要素をインデックス指定でリストアップ.
>>> inverse9'i [4,1,5,2,6,3]
[(4,[]),(1,[0]),(5,[]),(2,[0,2]),(6,[]),(3,[0,2,4])]
-}
inverse9'i :: [Int] -> [(Int, [Int])]
inverse9'i xs = go (zip [0..] xs) b []
where n = maximum xs
b = new n :: BIT [Int]
go [] b acc = zip xs (reverse acc)
go (ix@(i, x):xs) b acc = let acc' = (b ! n \\ b ! x) : acc
b' = inc' x [i] b
in go xs b' acc'
| cutsea110/aop | src/BinaryIndexedTree.hs | bsd-3-clause | 3,497 | 0 | 15 | 988 | 1,218 | 642 | 576 | 59 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Syncthing.Types.DeviceInfo
( DeviceInfo(..)
) where
import Control.Applicative ((<$>))
import Control.Monad (MonadPlus (mzero))
import Data.Aeson (FromJSON, Value (..), parseJSON, (.:))
import Data.Time.Clock (UTCTime)
import Network.Syncthing.Internal.Utils (toUTC)
-- | Contains information about a device.
data DeviceInfo = DeviceInfo {
getLastSeen :: Maybe UTCTime
} deriving (Eq, Show)
instance FromJSON DeviceInfo where
parseJSON (Object v) = DeviceInfo <$> (toUTC <$> v .: "lastSeen")
parseJSON _ = mzero
| jetho/syncthing-hs | Network/Syncthing/Types/DeviceInfo.hs | bsd-3-clause | 731 | 0 | 9 | 238 | 167 | 102 | 65 | 14 | 0 |
{-# LANGUAGE GADTs, RankNTypes #-}
module Options.Applicative.Internal
( P
, Context(..)
, MonadP(..)
, ParseError(..)
, uncons
, hoistMaybe
, hoistEither
, runP
, Completion
, runCompletion
, SomeParser(..)
, ComplError(..)
, ListT
, takeListT
, runListT
, NondetT
, cut
, (<!>)
, disamb
) where
import Control.Applicative (Applicative(..), Alternative(..), (<$>))
import Control.Monad (MonadPlus(..), liftM, ap, guard)
import Control.Monad.Trans.Class (MonadTrans, lift)
import Control.Monad.Trans.Except
(runExceptT, ExceptT(..), throwE, catchE)
import Control.Monad.Trans.Reader
(runReader, runReaderT, Reader, ReaderT, ask)
import Control.Monad.Trans.Writer (runWriterT, WriterT, tell)
import Control.Monad.Trans.State (StateT, get, put, evalStateT)
import Data.Maybe (maybeToList)
import Data.Monoid (Monoid(..))
import Options.Applicative.Types
class (Alternative m, MonadPlus m) => MonadP m where
setContext :: Maybe String -> ParserInfo a -> m ()
setParser :: Maybe String -> Parser a -> m ()
getPrefs :: m ParserPrefs
missingArgP :: ParseError -> Completer -> m a
tryP :: m a -> m (Either ParseError a)
errorP :: ParseError -> m a
exitP :: Parser b -> Maybe a -> m a
newtype P a = P (ExceptT ParseError (WriterT Context (Reader ParserPrefs)) a)
instance Functor P where
fmap f (P m) = P $ fmap f m
instance Applicative P where
pure a = P $ pure a
P f <*> P a = P $ f <*> a
instance Alternative P where
empty = P empty
P x <|> P y = P $ x <|> y
instance Monad P where
return a = P $ return a
P x >>= k = P $ x >>= \a -> case k a of P y -> y
instance MonadPlus P where
mzero = P mzero
mplus (P x) (P y) = P $ mplus x y
data Context where
Context :: [String] -> ParserInfo a -> Context
NullContext :: Context
contextNames :: Context -> [String]
contextNames (Context ns _) = ns
contextNames NullContext = []
instance Monoid Context where
mempty = NullContext
mappend c (Context ns i) = Context (contextNames c ++ ns) i
mappend c _ = c
instance MonadP P where
setContext name = P . lift . tell . Context (maybeToList name)
setParser _ _ = return ()
getPrefs = P . lift . lift $ ask
missingArgP e _ = errorP e
tryP (P p) = P $ lift $ runExceptT p
exitP _ = P . hoistMaybe
errorP = P . throwE
hoistMaybe :: MonadPlus m => Maybe a -> m a
hoistMaybe = maybe mzero return
hoistEither :: MonadP m => Either ParseError a -> m a
hoistEither = either errorP return
runP :: P a -> ParserPrefs -> (Either ParseError a, Context)
runP (P p) = runReader . runWriterT . runExceptT $ p
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x : xs) = Just (x, xs)
data SomeParser where
SomeParser :: Parser a -> SomeParser
data ComplError
= ComplParseError String
| ComplExit
data ComplResult a
= ComplParser SomeParser
| ComplOption Completer
| ComplResult a
instance Functor ComplResult where
fmap = liftM
instance Applicative ComplResult where
pure = ComplResult
(<*>) = ap
instance Monad ComplResult where
return = pure
m >>= f = case m of
ComplResult r -> f r
ComplParser p -> ComplParser p
ComplOption c -> ComplOption c
newtype Completion a =
Completion (ExceptT ParseError (ReaderT ParserPrefs ComplResult) a)
instance Functor Completion where
fmap f (Completion m) = Completion $ fmap f m
instance Applicative Completion where
pure a = Completion $ pure a
Completion f <*> Completion a = Completion $ f <*> a
instance Alternative Completion where
empty = Completion empty
Completion x <|> Completion y = Completion $ x <|> y
instance Monad Completion where
return a = Completion $ return a
Completion x >>= k = Completion $ x >>= \a -> case k a of Completion y -> y
instance MonadPlus Completion where
mzero = Completion mzero
mplus (Completion x) (Completion y) = Completion $ mplus x y
instance MonadP Completion where
setContext _ _ = return ()
setParser _ _ = return ()
getPrefs = Completion $ lift ask
missingArgP _ = Completion . lift . lift . ComplOption
tryP (Completion p) = Completion $ catchE (Right <$> p) (return . Left)
exitP p _ = Completion . lift . lift . ComplParser $ SomeParser p
errorP = Completion . throwE
runCompletion :: Completion r -> ParserPrefs -> Maybe (Either SomeParser Completer)
runCompletion (Completion c) prefs = case runReaderT (runExceptT c) prefs of
ComplResult _ -> Nothing
ComplParser p' -> Just $ Left p'
ComplOption compl -> Just $ Right compl
-- A "ListT done right" implementation
newtype ListT m a = ListT
{ stepListT :: m (TStep a (ListT m a)) }
data TStep a x
= TNil
| TCons a x
bimapTStep :: (a -> b) -> (x -> y) -> TStep a x -> TStep b y
bimapTStep _ _ TNil = TNil
bimapTStep f g (TCons a x) = TCons (f a) (g x)
hoistList :: Monad m => [a] -> ListT m a
hoistList = foldr (\x xt -> ListT (return (TCons x xt))) mzero
takeListT :: Monad m => Int -> ListT m a -> ListT m a
takeListT 0 = const mzero
takeListT n = ListT . liftM (bimapTStep id (takeListT (n - 1))) . stepListT
runListT :: Monad m => ListT m a -> m [a]
runListT xs = do
s <- stepListT xs
case s of
TNil -> return []
TCons x xt -> liftM (x :) (runListT xt)
instance Monad m => Functor (ListT m) where
fmap f = ListT
. liftM (bimapTStep f (fmap f))
. stepListT
instance Monad m => Applicative (ListT m) where
pure = hoistList . pure
(<*>) = ap
instance Monad m => Monad (ListT m) where
return = pure
xs >>= f = ListT $ do
s <- stepListT xs
case s of
TNil -> return TNil
TCons x xt -> stepListT $ f x `mplus` (xt >>= f)
instance Monad m => Alternative (ListT m) where
empty = mzero
(<|>) = mplus
instance MonadTrans ListT where
lift = ListT . liftM (`TCons` mzero)
instance Monad m => MonadPlus (ListT m) where
mzero = ListT (return TNil)
mplus xs ys = ListT $ do
s <- stepListT xs
case s of
TNil -> stepListT ys
TCons x xt -> return $ TCons x (xt `mplus` ys)
-- nondeterminism monad with cut operator
newtype NondetT m a = NondetT
{ runNondetT :: ListT (StateT Bool m) a }
instance Monad m => Functor (NondetT m) where
fmap f = NondetT . fmap f . runNondetT
instance Monad m => Applicative (NondetT m) where
pure = NondetT . pure
NondetT m1 <*> NondetT m2 = NondetT (m1 <*> m2)
instance Monad m => Monad (NondetT m) where
return = pure
NondetT m1 >>= f = NondetT $ m1 >>= runNondetT . f
instance Monad m => MonadPlus (NondetT m) where
mzero = NondetT mzero
NondetT m1 `mplus` NondetT m2 = NondetT (m1 `mplus` m2)
instance Monad m => Alternative (NondetT m) where
empty = mzero
(<|>) = mplus
instance MonadTrans NondetT where
lift = NondetT . lift . lift
(<!>) :: Monad m => NondetT m a -> NondetT m a -> NondetT m a
(<!>) m1 m2 = NondetT . mplus (runNondetT m1) $ do
s <- lift get
guard (not s)
runNondetT m2
cut :: Monad m => NondetT m ()
cut = NondetT $ lift (put True)
disamb :: Monad m => Bool -> NondetT m a -> m (Maybe a)
disamb allow_amb xs = do
xs' <- (`evalStateT` False)
. runListT
. takeListT (if allow_amb then 1 else 2)
. runNondetT $ xs
return $ case xs' of
[x] -> Just x
_ -> Nothing
| thielema/optparse-applicative | Options/Applicative/Internal.hs | bsd-3-clause | 7,210 | 0 | 15 | 1,681 | 3,033 | 1,555 | 1,478 | 211 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Digestive.Heist.Extras
( module E
, dfPath
, dfInputCheckboxMultiple
) where
import Data.Map.Syntax ((##))
import Data.Text (Text)
import Text.Digestive.View (View, absoluteRef, fieldInputChoice)
import Heist.Interpreted
import qualified Text.XmlHtml as X
import Text.Digestive.Heist.Extras.Plain as E
import Text.Digestive.Heist.Extras.Custom as E
import Text.Digestive.Heist.Extras.List as E (dfInputListStatic, dfInputListCustom, dfInputListSpan)
import Text.Digestive.Heist.Extras.GroupRadio as E
import Text.Digestive.Heist.Extras.Patch as E
import Text.Digestive.Heist.Extras.Internal.Attribute (getRefAttributes)
----------------------------------------------------------------------
-- basic text splice that provides the current path in the form,
-- handy when you have to manually create some form markup
-- (eg. form.subview)
dfPath :: Monad m => View Text -> Splice m
dfPath view = return [X.TextNode $ absoluteRef "" view]
----------------------------------------------------------------------
-- this splice is intended for use with choiceMultiple forms. it generates a
-- list of checkboxes, similar to dfInputRadio, but allows for some customization
{-# DEPRECATED dfInputCheckboxMultiple "Use Text.Digestive.Heist.Extras.Custom.dfCustomChoice instead" #-}
dfInputCheckboxMultiple :: Monad m => View Text -> Splice m
dfInputCheckboxMultiple view = do
(ref, _) <- getRefAttributes Nothing
let
ref' = absoluteRef ref view
choices = fieldInputChoice ref view
--value i = ref' <> "." <> i
checkboxSplice (i, c, sel) = do
let
defaultAttributes = [("type", "checkbox"), ("name", ref'), ("value", i)]
attrs = if sel then ("checked", "checked") : defaultAttributes else defaultAttributes
"checkbox" ## return [X.Element "input" attrs []]
"name" ## return [X.TextNode c]
mapSplices (runChildrenWith . checkboxSplice) choices
| cimmanon/digestive-functors-heist-extras | src/Text/Digestive/Heist/Extras.hs | bsd-3-clause | 1,923 | 4 | 17 | 263 | 412 | 245 | 167 | 32 | 2 |
module Main where
import Svg
import Data.Complex
import Dft
import Data.Foldable
import System.Environment
import Data.Maybe
import Util
import qualified Data.Vector as V
import Numeric.FFT.Vector.Invertible
_N = 256 :: Int
_N_Minus1 = _N - 1 :: Int
square :: (Enum a, Floating a) => Int -> [a]
square n = [sum [sin ((fromIntegral (2 * (k * 2 + 1) * x)) * pi / (fromIntegral _N)) / (fromIntegral (k * 2 + 1)) | k <- [0..n-1]] | x <- [0.._N_Minus1]]
sawtooth = 0 : [1 - (2 / (fromIntegral _N)) * (fromIntegral x) | x <- [1.._N_Minus1]]
approxSawtooth :: (Enum a, Floating a) => Int -> [a]
approxSawtooth n = [foldr1 (+) [sin (fromIntegral (2 * k * x) * pi / (fromIntegral _N)) / (fromIntegral k) | k <- [1..n]] | x <- [0.._N_Minus1]]
signal = approxSawtooth 10
realToComplex :: (Floating a) => a -> Complex a
realToComplex a = a :+ 0
freqDomain :: [Complex Double]
freqDomain = let timeDomain = (V.fromList signal) in
V.toList $ run dftR2C timeDomain
freqDomainAmp :: [Double]
freqDomainAmp = let (h : t) = freqDomain
(m, l) = splitAt (length t - 1) t in
(magnitude h / 2) : (map magnitude m) ++ (map ((/2) . magnitude) l)
prefix :: Maybe String
prefix = Nothing
main :: IO ()
main = do
args <- getArgs
let f = (read . head) args
graphStroke = Stroke (Just "black") (Just 0.03)
graphScale = 8 / (fromIntegral _N)
dasharray = fromMaybe "2" ((show . (*2)) <$> strokeWidthMaybe graphStroke) ++
fromMaybe " 1" (((' ' :) . show) <$> strokeWidthMaybe graphStroke)
helperStroke = strokeWidthMap (/4) graphStroke
signalGraphTransform = "translate(-4 3)"
writeFile "background.svg" (
prologue prefix "xlink" (Just (WidthHeight "600" "600")) (Just $ ViewBox "-5" "-5" "10" "10") ++
"<" ++ maybePrefix prefix ++ "g transform=\"" ++ signalGraphTransform ++ "\">" ++
foldr1 (++) (map (\i -> let x = fromIntegral (i * _N) / (fromIntegral f) in
"<" ++ maybePrefix prefix ++
"line" ++ strokeToString helperStroke ++
" stroke-dasharray=\"" ++
dasharray ++
"\" x1=\"0\" y1=\"1\" x2=\"0\" y2=\"-1\"" ++
" transform=\"translate(" ++ show (x * graphScale) ++ " 0)\" />") [0..f]) ++
"<" ++ maybePrefix prefix ++ "line" ++ strokeToString helperStroke ++
" stroke-dasharray=\"" ++ dasharray ++ "\" x1=\"" ++ show (-5 * graphScale) ++ "\" y1=\"0\"" ++
" x2=\"" ++ show ((fromIntegral (_N + 5)) * graphScale) ++ "\" y2=\"0\" " ++
" />" ++
drawGraph prefix graphScale 1.0 graphStroke (zip [0..(fromIntegral _N_Minus1)] signal) ++
"</" ++ maybePrefix prefix ++ "g>" ++
"<" ++ maybePrefix prefix ++ "g transform=\"translate(-4 -4)\">" ++
drawGraph prefix (graphScale * 2) freqDomainScale graphStroke (zip [0..(fromIntegral _N_Minus1)] freqDomainAmp) ++
"<" ++ maybePrefix prefix ++ "circle cx=\"" ++ show ((fromIntegral f) * graphScale * 2) ++ "\" cy=\"" ++
show ((freqDomainAmp !! f) * freqDomainScale) ++ "\" r=\"" ++
fromMaybe "1" (show <$> strokeWidthMaybe graphStroke) ++ "\"" ++
(fromMaybe "" ((\s -> " fill=\"" ++ s ++ "\"") <$> (strokeColorMaybe graphStroke))) ++ "/>" ++
"</" ++ maybePrefix prefix ++ "g>" ++
epilogue prefix
)
for_ (zip3 (animateFreq (map realToComplex signal) f (_N `div` f)) [0..] signal)
(\(content, num, s) ->
writeFile ("graph" ++ show num ++ ".svg") (
prologue prefix "xlink" (Just (WidthHeight "600" "600")) (Just $ ViewBox "-5" "-5" "10" "10") ++
content ++
"<" ++ maybePrefix prefix ++ "g transform=\"" ++ signalGraphTransform ++ "\">" ++
"<" ++ maybePrefix prefix ++ "circle cx=\"" ++ show ((fromIntegral num) * graphScale) ++ "\" cy=\"" ++ show s ++ "\" r=\"" ++
fromMaybe "1" (show <$> strokeWidthMaybe graphStroke) ++ "\"" ++
(fromMaybe "" ((\s -> " fill=\"" ++ s ++ "\"") <$> (strokeColorMaybe graphStroke))) ++ "/>" ++
"</" ++ maybePrefix prefix ++ "g>" ++
epilogue prefix))
freqDomainScale :: RealFloat a => a
freqDomainScale = 1 / (2 * sqrt (fromIntegral (length signal)))
animateFreq :: (RealFloat a, Show a) => [Complex a] -> Int -> Int -> [String]
animateFreq signal f sumTraceN = let
functionValues = ((map (\(s, wp, sum) -> (s, wp, sum * (freqDomainScale :+ 0)))) . tail . reverse) (correlateSignalAtFreq signal f)
lastN = lastNWindow sumTraceN functionValues in
map partToString (zip functionValues lastN) where
partToString ((s, wavePart, sum), lastNTuples) =
let opacities = [1.0 - (fromIntegral i) / (fromIntegral sumTraceN) | i <- [0..sumTraceN - 1]]
lastComplexes = zip lastNTuples opacities
lastComplexesDraws =
map
(\((_, _, a :+ b), opacity) ->
"<" ++ maybePrefix prefix ++ "circle fill=\"blue\" cx=\"" ++ show a ++
"\" cy=\"" ++ show b ++ "\" r=\"0.01\" opacity=\"" ++ show opacity ++
"\" />"
)
lastComplexes
in
drawComplex sum prefix (Stroke (Just "blue") (Just 0.03)) ++
foldr1 (++) lastComplexesDraws ++
drawComplex wavePart prefix (Stroke (Just "green") (Just 0.02)) ++
drawComplex s prefix (Stroke (Just "red") (Just 0.01))
| tilgalas/haskell-fourier | app/Main.hs | bsd-3-clause | 5,388 | 0 | 62 | 1,409 | 2,042 | 1,058 | 984 | 95 | 1 |
{-# language CPP #-}
-- | = Name
--
-- XR_MSFT_hand_tracking_mesh - instance extension
--
-- = Specification
--
-- See
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_MSFT_hand_tracking_mesh XR_MSFT_hand_tracking_mesh>
-- in the main specification for complete information.
--
-- = Registered Extension Number
--
-- 53
--
-- = Revision
--
-- 2
--
-- = Extension and Version Dependencies
--
-- - Requires OpenXR 1.0
--
-- - Requires @XR_EXT_hand_tracking@
--
-- = See Also
--
-- 'HandMeshIndexBufferMSFT', 'HandMeshMSFT',
-- 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT',
-- 'HandMeshVertexBufferMSFT', 'HandMeshVertexMSFT',
-- 'HandPoseTypeInfoMSFT', 'HandPoseTypeMSFT',
-- 'SystemHandTrackingMeshPropertiesMSFT', 'createHandMeshSpaceMSFT',
-- 'updateHandMeshMSFT'
--
-- = Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_MSFT_hand_tracking_mesh OpenXR Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module OpenXR.Extensions.XR_MSFT_hand_tracking_mesh ( createHandMeshSpaceMSFT
, withHandMeshSpaceMSFT
, updateHandMeshMSFT
, HandMeshSpaceCreateInfoMSFT(..)
, HandMeshUpdateInfoMSFT(..)
, HandMeshMSFT(..)
, HandMeshIndexBufferMSFT(..)
, HandMeshVertexBufferMSFT(..)
, HandMeshVertexMSFT(..)
, SystemHandTrackingMeshPropertiesMSFT(..)
, HandPoseTypeInfoMSFT(..)
, HandPoseTypeMSFT( HAND_POSE_TYPE_TRACKED_MSFT
, HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT
, ..
)
, MSFT_hand_tracking_mesh_SPEC_VERSION
, pattern MSFT_hand_tracking_mesh_SPEC_VERSION
, MSFT_HAND_TRACKING_MESH_EXTENSION_NAME
, pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME
, HandTrackerEXT(..)
) where
import OpenXR.Internal.Utils (enumReadPrec)
import OpenXR.Internal.Utils (enumShowsPrec)
import OpenXR.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import OpenXR.CStruct (FromCStruct)
import OpenXR.CStruct (FromCStruct(..))
import OpenXR.CStruct (ToCStruct)
import OpenXR.CStruct (ToCStruct(..))
import OpenXR.Zero (Zero)
import OpenXR.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Data.Int (Int32)
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import OpenXR.Core10.FundamentalTypes (bool32ToBool)
import OpenXR.Core10.FundamentalTypes (boolToBool32)
import OpenXR.Core10.Space (destroySpace)
import OpenXR.Core10.FundamentalTypes (Bool32)
import OpenXR.Extensions.Handles (HandTrackerEXT)
import OpenXR.Extensions.Handles (HandTrackerEXT(..))
import OpenXR.Extensions.Handles (HandTrackerEXT(HandTrackerEXT))
import OpenXR.Extensions.Handles (HandTrackerEXT_T)
import OpenXR.Dynamic (InstanceCmds(pXrCreateHandMeshSpaceMSFT))
import OpenXR.Dynamic (InstanceCmds(pXrUpdateHandMeshMSFT))
import OpenXR.Exception (OpenXrException(..))
import OpenXR.Core10.Space (Posef)
import OpenXR.Core10.Enums.Result (Result)
import OpenXR.Core10.Enums.Result (Result(..))
import OpenXR.Core10.Handles (Space)
import OpenXR.Core10.Handles (Space(Space))
import OpenXR.Core10.Handles (Space_T)
import OpenXR.Core10.Enums.StructureType (StructureType)
import OpenXR.Core10.FundamentalTypes (Time)
import OpenXR.Core10.Space (Vector3f)
import OpenXR.Core10.Enums.Result (Result(SUCCESS))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_MSFT))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_MESH_UPDATE_INFO_MSFT))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_HAND_POSE_TYPE_INFO_MSFT))
import OpenXR.Core10.Enums.StructureType (StructureType(TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT))
import OpenXR.Extensions.Handles (HandTrackerEXT(..))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrCreateHandMeshSpaceMSFT
:: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshSpaceCreateInfoMSFT -> Ptr (Ptr Space_T) -> IO Result
-- | xrCreateHandMeshSpaceMSFT - Create a space for hand mesh tracking
--
-- == Parameter Descriptions
--
-- = Description
--
-- A hand mesh space location is specified by runtime preference to
-- effectively represent hand mesh vertices without unnecessary
-- transformations. For example, an optical hand tracking system /can/
-- define the hand mesh space origin at the depth camera’s optical center.
--
-- An application should create separate hand mesh space handles for each
-- hand to retrieve the corresponding hand mesh data. The runtime /may/ use
-- the lifetime of this hand mesh space handle to manage the underlying
-- device resources. Therefore, the application /should/ destroy the hand
-- mesh handle after it is finished using the hand mesh.
--
-- The hand mesh space can be related to other spaces in the session, such
-- as view reference space, or grip action space from the
-- \/interaction_profiles\/khr\/simple_controller interaction profile. The
-- hand mesh space may be not locatable when the hand is outside of the
-- tracking range, or if focus is removed from the application. In these
-- cases, the runtime /must/ not set the
-- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT'
-- and
-- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT'
-- bits on calls to 'OpenXR.Core10.Space.locateSpace' with the hand mesh
-- space, and the application /should/ avoid using the returned poses or
-- query for hand mesh data.
--
-- If the underlying 'OpenXR.Extensions.Handles.HandTrackerEXT' is
-- destroyed, the runtime /must/ continue to support
-- 'OpenXR.Core10.Space.locateSpace' using the hand mesh space, and it
-- /must/ return space location with
-- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_POSITION_VALID_BIT'
-- and
-- 'OpenXR.Core10.Enums.SpaceLocationFlagBits.SPACE_LOCATION_ORIENTATION_VALID_BIT'
-- unset.
--
-- The application /may/ create a mesh space for the reference hand by
-- setting @handPoseType@ to 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT'.
-- Hand mesh spaces for the reference hand /must/ only be locatable in
-- reference to mesh spaces or joint spaces of the reference hand.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-xrCreateHandMeshSpaceMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- calling 'createHandMeshSpaceMSFT'
--
-- - #VUID-xrCreateHandMeshSpaceMSFT-handTracker-parameter# @handTracker@
-- /must/ be a valid 'OpenXR.Extensions.Handles.HandTrackerEXT' handle
--
-- - #VUID-xrCreateHandMeshSpaceMSFT-createInfo-parameter# @createInfo@
-- /must/ be a pointer to a valid 'HandMeshSpaceCreateInfoMSFT'
-- structure
--
-- - #VUID-xrCreateHandMeshSpaceMSFT-space-parameter# @space@ /must/ be a
-- pointer to an 'OpenXR.Core10.Handles.Space' handle
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SESSION_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_POSE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED'
--
-- = See Also
--
-- 'HandMeshSpaceCreateInfoMSFT',
-- 'OpenXR.Extensions.Handles.HandTrackerEXT',
-- 'OpenXR.Core10.Handles.Space'
createHandMeshSpaceMSFT :: forall io
. (MonadIO io)
=> -- | @handTracker@ is an 'OpenXR.Extensions.Handles.HandTrackerEXT' handle
-- previously created with the
-- 'OpenXR.Extensions.XR_EXT_hand_tracking.createHandTrackerEXT' function.
HandTrackerEXT
-> -- | @createInfo@ is the 'HandMeshSpaceCreateInfoMSFT' used to specify the
-- hand mesh space.
HandMeshSpaceCreateInfoMSFT
-> io (Result, Space)
createHandMeshSpaceMSFT handTracker createInfo = liftIO . evalContT $ do
let cmds = case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds
let xrCreateHandMeshSpaceMSFTPtr = pXrCreateHandMeshSpaceMSFT cmds
lift $ unless (xrCreateHandMeshSpaceMSFTPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrCreateHandMeshSpaceMSFT is null" Nothing Nothing
let xrCreateHandMeshSpaceMSFT' = mkXrCreateHandMeshSpaceMSFT xrCreateHandMeshSpaceMSFTPtr
createInfo' <- ContT $ withCStruct (createInfo)
pSpace <- ContT $ bracket (callocBytes @(Ptr Space_T) 8) free
r <- lift $ traceAroundEvent "xrCreateHandMeshSpaceMSFT" (xrCreateHandMeshSpaceMSFT' (handTrackerEXTHandle (handTracker)) createInfo' (pSpace))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
space <- lift $ peek @(Ptr Space_T) pSpace
pure $ (r, ((\h -> Space h cmds ) space))
-- | A convenience wrapper to make a compatible pair of calls to
-- 'createHandMeshSpaceMSFT' and 'destroySpace'
--
-- To ensure that 'destroySpace' is always called: pass
-- 'Control.Exception.bracket' (or the allocate function from your
-- favourite resource management library) as the last argument.
-- To just extract the pair pass '(,)' as the last argument.
--
withHandMeshSpaceMSFT :: forall io r . MonadIO io => HandTrackerEXT -> HandMeshSpaceCreateInfoMSFT -> (io (Result, Space) -> ((Result, Space) -> io ()) -> r) -> r
withHandMeshSpaceMSFT handTracker createInfo b =
b (createHandMeshSpaceMSFT handTracker createInfo)
(\(_, o1) -> destroySpace o1)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkXrUpdateHandMeshMSFT
:: FunPtr (Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result) -> Ptr HandTrackerEXT_T -> Ptr HandMeshUpdateInfoMSFT -> Ptr HandMeshMSFT -> IO Result
-- | xrUpdateHandMeshMSFT - Update hand mesh buffers
--
-- == Parameter Descriptions
--
-- = Description
--
-- The application /should/ preallocate the index buffer and vertex buffer
-- in 'HandMeshMSFT' using the @maxHandMeshIndexCount@ and
-- @maxHandMeshVertexCount@ from the 'SystemHandTrackingMeshPropertiesMSFT'
-- returned from the 'OpenXR.Core10.Device.getSystemProperties' function.
--
-- The application /should/ preallocate the 'HandMeshMSFT' structure and
-- reuse it for each frame so as to reduce the copies of data when
-- underlying tracking data is not changed. The application should use
-- @indexBufferChanged@ and @vertexBufferChanged@ in 'HandMeshMSFT' to
-- detect changes and avoid unnecessary data processing when there is no
-- changes.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-xrUpdateHandMeshMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- calling 'updateHandMeshMSFT'
--
-- - #VUID-xrUpdateHandMeshMSFT-handTracker-parameter# @handTracker@
-- /must/ be a valid 'OpenXR.Extensions.Handles.HandTrackerEXT' handle
--
-- - #VUID-xrUpdateHandMeshMSFT-updateInfo-parameter# @updateInfo@ /must/
-- be a pointer to a valid 'HandMeshUpdateInfoMSFT' structure
--
-- - #VUID-xrUpdateHandMeshMSFT-handMesh-parameter# @handMesh@ /must/ be
-- a pointer to an 'HandMeshMSFT' structure
--
-- == Return Codes
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-successcodes Success>]
--
-- - 'OpenXR.Core10.Enums.Result.SUCCESS'
--
-- - 'OpenXR.Core10.Enums.Result.SESSION_LOSS_PENDING'
--
-- [<https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#fundamentals-errorcodes Failure>]
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_INSTANCE_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SESSION_LOST'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_RUNTIME_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_HANDLE_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_TIME_INVALID'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FUNCTION_UNSUPPORTED'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT'
--
-- - 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED'
--
-- = See Also
--
-- 'HandMeshMSFT', 'HandMeshUpdateInfoMSFT',
-- 'OpenXR.Extensions.Handles.HandTrackerEXT'
updateHandMeshMSFT :: forall io
. (MonadIO io)
=> -- | @handTracker@ is an 'OpenXR.Extensions.Handles.HandTrackerEXT' handle
-- previously created with
-- 'OpenXR.Extensions.XR_EXT_hand_tracking.createHandTrackerEXT'.
HandTrackerEXT
-> -- | @updateInfo@ is a 'HandMeshUpdateInfoMSFT' which contains information to
-- query the hand mesh.
HandMeshUpdateInfoMSFT
-> io (Result, HandMeshMSFT)
updateHandMeshMSFT handTracker updateInfo = liftIO . evalContT $ do
let xrUpdateHandMeshMSFTPtr = pXrUpdateHandMeshMSFT (case handTracker of HandTrackerEXT{instanceCmds} -> instanceCmds)
lift $ unless (xrUpdateHandMeshMSFTPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for xrUpdateHandMeshMSFT is null" Nothing Nothing
let xrUpdateHandMeshMSFT' = mkXrUpdateHandMeshMSFT xrUpdateHandMeshMSFTPtr
updateInfo' <- ContT $ withCStruct (updateInfo)
pHandMesh <- ContT (withZeroCStruct @HandMeshMSFT)
r <- lift $ traceAroundEvent "xrUpdateHandMeshMSFT" (xrUpdateHandMeshMSFT' (handTrackerEXTHandle (handTracker)) updateInfo' (pHandMesh))
lift $ when (r < SUCCESS) (throwIO (OpenXrException r))
handMesh <- lift $ peekCStruct @HandMeshMSFT pHandMesh
pure $ (r, handMesh)
-- | XrHandMeshSpaceCreateInfoMSFT - The information to create a hand mesh
-- space
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshSpaceCreateInfoMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshSpaceCreateInfoMSFT'
--
-- - #VUID-XrHandMeshSpaceCreateInfoMSFT-type-type# @type@ /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT'
--
-- - #VUID-XrHandMeshSpaceCreateInfoMSFT-next-next# @next@ /must/ be
-- @NULL@ or a valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- - #VUID-XrHandMeshSpaceCreateInfoMSFT-handPoseType-parameter#
-- @handPoseType@ /must/ be a valid 'HandPoseTypeMSFT' value
--
-- = See Also
--
-- 'HandPoseTypeMSFT', 'OpenXR.Core10.Space.Posef',
-- 'OpenXR.Core10.Enums.StructureType.StructureType',
-- 'createHandMeshSpaceMSFT'
data HandMeshSpaceCreateInfoMSFT = HandMeshSpaceCreateInfoMSFT
{ -- | @handPoseType@ is an 'HandPoseTypeMSFT' used to specify the type of hand
-- this mesh is tracking. Indices and vertices returned from
-- 'updateHandMeshMSFT' for a hand type will be relative to the
-- corresponding space create with the same hand type.
handPoseType :: HandPoseTypeMSFT
, -- | @poseInHandMeshSpace@ is an 'OpenXR.Core10.Space.Posef' defining the
-- position and orientation of the new space’s origin within the natural
-- reference frame of the hand mesh space.
poseInHandMeshSpace :: Posef
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshSpaceCreateInfoMSFT)
#endif
deriving instance Show HandMeshSpaceCreateInfoMSFT
instance ToCStruct HandMeshSpaceCreateInfoMSFT where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshSpaceCreateInfoMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType)
poke ((p `plusPtr` 20 :: Ptr Posef)) (poseInHandMeshSpace)
f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_SPACE_CREATE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero)
poke ((p `plusPtr` 20 :: Ptr Posef)) (zero)
f
instance FromCStruct HandMeshSpaceCreateInfoMSFT where
peekCStruct p = do
handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT))
poseInHandMeshSpace <- peekCStruct @Posef ((p `plusPtr` 20 :: Ptr Posef))
pure $ HandMeshSpaceCreateInfoMSFT
handPoseType poseInHandMeshSpace
instance Storable HandMeshSpaceCreateInfoMSFT where
sizeOf ~_ = 48
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshSpaceCreateInfoMSFT where
zero = HandMeshSpaceCreateInfoMSFT
zero
zero
-- | XrHandMeshUpdateInfoMSFT - The information to update a hand mesh
--
-- == Member Descriptions
--
-- = Description
--
-- A runtime /may/ not maintain a full history of hand mesh data, therefore
-- the returned 'HandMeshMSFT' might return data that’s not exactly
-- corresponding to the @time@ input. If the runtime cannot return any
-- tracking data for the given @time@ at all, it /must/ set @isActive@ to
-- 'OpenXR.Core10.FundamentalTypes.FALSE' for the call to
-- 'updateHandMeshMSFT'. Otherwise, if the runtime returns @isActive@ as
-- 'OpenXR.Core10.FundamentalTypes.TRUE', the data in 'HandMeshMSFT' must
-- be valid to use.
--
-- An application can choose different @handPoseType@ values to query the
-- hand mesh data. The returned hand mesh /must/ be consistent to the hand
-- joint space location on the same
-- 'OpenXR.Extensions.Handles.HandTrackerEXT' when using the same
-- 'HandPoseTypeMSFT'.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshUpdateInfoMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshUpdateInfoMSFT'
--
-- - #VUID-XrHandMeshUpdateInfoMSFT-type-type# @type@ /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_HAND_MESH_UPDATE_INFO_MSFT'
--
-- - #VUID-XrHandMeshUpdateInfoMSFT-next-next# @next@ /must/ be @NULL@ or
-- a valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- - #VUID-XrHandMeshUpdateInfoMSFT-handPoseType-parameter#
-- @handPoseType@ /must/ be a valid 'HandPoseTypeMSFT' value
--
-- = See Also
--
-- 'HandPoseTypeMSFT', 'OpenXR.Core10.Enums.StructureType.StructureType',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrTime >,
-- 'updateHandMeshMSFT'
data HandMeshUpdateInfoMSFT = HandMeshUpdateInfoMSFT
{ -- | @time@ is the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrTime >
-- that describes the time for which the application wishes to query the
-- hand mesh state.
time :: Time
, -- | @handPoseType@ is an 'HandPoseTypeMSFT' which describes the type of hand
-- pose of the hand mesh to update.
handPoseType :: HandPoseTypeMSFT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshUpdateInfoMSFT)
#endif
deriving instance Show HandMeshUpdateInfoMSFT
instance ToCStruct HandMeshUpdateInfoMSFT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshUpdateInfoMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Time)) (time)
poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (handPoseType)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_UPDATE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Time)) (zero)
poke ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT)) (zero)
f
instance FromCStruct HandMeshUpdateInfoMSFT where
peekCStruct p = do
time <- peek @Time ((p `plusPtr` 16 :: Ptr Time))
handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 24 :: Ptr HandPoseTypeMSFT))
pure $ HandMeshUpdateInfoMSFT
time handPoseType
instance Storable HandMeshUpdateInfoMSFT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshUpdateInfoMSFT where
zero = HandMeshUpdateInfoMSFT
zero
zero
-- | XrHandMeshMSFT - The data of a hand mesh
--
-- == Member Descriptions
--
-- = Description
--
-- When the returned @isActive@ value is
-- 'OpenXR.Core10.FundamentalTypes.FALSE', the runtime indicates the hand
-- is not actively tracked, for example, the hand is outside of sensor’s
-- range, or the input focus is taken away from the application. When the
-- runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' to @isActive@, it
-- /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to
-- 'OpenXR.Core10.FundamentalTypes.FALSE', and /must/ not change the
-- content in @indexBuffer@ or @vertexBuffer@,
--
-- When the returned @isActive@ value is
-- 'OpenXR.Core10.FundamentalTypes.TRUE', the hand tracking mesh
-- represented in @indexBuffer@ and @vertexBuffer@ are updated to the
-- latest data of the @time@ given to the 'updateHandMeshMSFT' function.
-- The runtime /must/ set @indexBufferChanged@ and @vertexBufferChanged@ to
-- reflect whether the index or vertex buffer’s content are changed during
-- the update. In this way, the application can easily avoid unnecessary
-- processing of buffers when there’s no new data.
--
-- The hand mesh is represented in triangle lists and each triangle’s
-- vertices are in counter-clockwise order when looking from outside of the
-- hand. When hand tracking is active, i.e. when @isActive@ is returned as
-- 'OpenXR.Core10.FundamentalTypes.TRUE', the returned
-- @indexBuffer.indexCountOutput@ value /must/ be positive and multiple of
-- 3, and @vertexBuffer.vertexCountOutput@ value /must/ be equal to or
-- larger than 3.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshMSFT'
--
-- - #VUID-XrHandMeshMSFT-type-type# @type@ /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_HAND_MESH_MSFT'
--
-- - #VUID-XrHandMeshMSFT-next-next# @next@ /must/ be @NULL@ or a valid
-- pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- - #VUID-XrHandMeshMSFT-indexBuffer-parameter# @indexBuffer@ /must/ be
-- a valid 'HandMeshIndexBufferMSFT' structure
--
-- - #VUID-XrHandMeshMSFT-vertexBuffer-parameter# @vertexBuffer@ /must/
-- be a valid 'HandMeshVertexBufferMSFT' structure
--
-- = See Also
--
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >,
-- 'HandMeshIndexBufferMSFT', 'HandMeshVertexBufferMSFT',
-- 'OpenXR.Core10.Enums.StructureType.StructureType', 'updateHandMeshMSFT'
data HandMeshMSFT = HandMeshMSFT
{ -- | @isActive@ is an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >
-- indicating if the current hand tracker is active.
isActive :: Bool
, -- | @indexBufferChanged@ is an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >
-- indicating if the @indexBuffer@ content was changed during the update.
indexBufferChanged :: Bool
, -- | @vertexBufferChanged@ is an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >
-- indicating if the @vertexBuffer@ content was changed during the update.
vertexBufferChanged :: Bool
, -- | @indexBuffer@ is an 'HandMeshIndexBufferMSFT' returns the index buffer
-- of the tracked hand mesh.
indexBuffer :: HandMeshIndexBufferMSFT
, -- | @vertexBuffer@ is an 'HandMeshVertexBufferMSFT' returns the vertex
-- buffer of the tracked hand mesh.
vertexBuffer :: HandMeshVertexBufferMSFT
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshMSFT)
#endif
deriving instance Show HandMeshMSFT
instance ToCStruct HandMeshMSFT where
withCStruct x f = allocaBytes 80 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (isActive))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (indexBufferChanged))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (vertexBufferChanged))
poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (indexBuffer)
poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (vertexBuffer)
f
cStructSize = 80
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_MESH_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT)) (zero)
poke ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT)) (zero)
f
instance FromCStruct HandMeshMSFT where
peekCStruct p = do
isActive <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
indexBufferChanged <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
vertexBufferChanged <- peek @Bool32 ((p `plusPtr` 24 :: Ptr Bool32))
indexBuffer <- peekCStruct @HandMeshIndexBufferMSFT ((p `plusPtr` 32 :: Ptr HandMeshIndexBufferMSFT))
vertexBuffer <- peekCStruct @HandMeshVertexBufferMSFT ((p `plusPtr` 56 :: Ptr HandMeshVertexBufferMSFT))
pure $ HandMeshMSFT
(bool32ToBool isActive) (bool32ToBool indexBufferChanged) (bool32ToBool vertexBufferChanged) indexBuffer vertexBuffer
instance Storable HandMeshMSFT where
sizeOf ~_ = 80
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshMSFT where
zero = HandMeshMSFT
zero
zero
zero
zero
zero
-- | XrHandMeshIndexBufferMSFT - The index buffer of a hand mesh
--
-- == Member Descriptions
--
-- = Description
--
-- An application /should/ preallocate the indices array using the
-- @maxHandMeshIndexCount@ in 'SystemHandTrackingMeshPropertiesMSFT'
-- returned from 'OpenXR.Core10.Device.getSystemProperties'. In this way,
-- the application can avoid possible insufficient buffer sizees for each
-- query, and therefore avoid reallocating memory each frame.
--
-- The input @indexCapacityInput@ /must/ not be 0, and @indices@ /must/ not
-- be @NULL@, or else the runtime /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the
-- 'updateHandMeshMSFT' function.
--
-- If the input @indexCapacityInput@ is not sufficient to contain all
-- output indices, the runtime /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT' on calls to
-- 'updateHandMeshMSFT', not change the content in @indexBufferKey@ and
-- @indices@, and return 0 for @indexCountOutput@.
--
-- If the input @indexCapacityInput@ is equal to or larger than the
-- @maxHandMeshIndexCount@ in 'SystemHandTrackingMeshPropertiesMSFT'
-- returned from 'OpenXR.Core10.Device.getSystemProperties', the runtime
-- /must/ not return 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT'
-- error on 'updateHandMeshMSFT' because of insufficient index buffer size.
--
-- If the input @indexBufferKey@ is 0, the capacity of indices array is
-- sufficient, and hand mesh tracking is active, the runtime /must/ return
-- the latest non-zero @indexBufferKey@, and fill in @indexCountOutput@ and
-- @indices@.
--
-- If the input @indexBufferKey@ is not 0, the runtime /can/ either return
-- without changing @indexCountOutput@ or content in @indices@, and return
-- 'OpenXR.Core10.FundamentalTypes.FALSE' for @indexBufferChanged@
-- indicating the indices are not changed; or return a new non-zero
-- @indexBufferKey@ and fill in latest data in @indexCountOutput@ and
-- @indices@, and return 'OpenXR.Core10.FundamentalTypes.TRUE' for
-- @indexBufferChanged@ indicating the indices are updated to a newer
-- version.
--
-- An application /can/ keep the 'HandMeshIndexBufferMSFT' structure for
-- each frame in a frame loop and use the returned @indexBufferKey@ to
-- identify different triangle list topology described in @indices@. The
-- application can therefore avoid unnecessary processing of indices, such
-- as coping them to GPU memory.
--
-- The runtime /must/ return the same @indexBufferKey@ for the same
-- 'OpenXR.Extensions.Handles.HandTrackerEXT' at a given time, regardless
-- of the input 'HandPoseTypeMSFT' in 'HandMeshUpdateInfoMSFT'. This
-- ensures the index buffer has the same mesh topology and allows the
-- application to reason about vertices across different hand pose types.
-- For example, the application /can/ build a procedure to perform UV
-- mapping on vertices of a hand mesh using
-- 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT', and apply the resultant UV
-- data on vertices to the mesh returned from the same hand tracker using
-- 'HAND_POSE_TYPE_TRACKED_MSFT'.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshIndexBufferMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshIndexBufferMSFT'
--
-- - #VUID-XrHandMeshIndexBufferMSFT-indices-parameter# @indices@ /must/
-- be a pointer to an array of @indexCapacityInput@ @uint32_t@ values
--
-- - #VUID-XrHandMeshIndexBufferMSFT-indexCapacityInput-arraylength# The
-- @indexCapacityInput@ parameter /must/ be greater than @0@
--
-- = See Also
--
-- 'HandMeshMSFT'
data HandMeshIndexBufferMSFT = HandMeshIndexBufferMSFT
{ -- | @indexBufferKey@ is a @uint32_t@ serving as the key of the returned
-- index buffer content or 0 to indicate a request to retrieve the latest
-- indices regardless of existing content in @indices@.
indexBufferKey :: Word32
, -- | @indexCapacityInput@ is a positive @uint32_t@ describes the capacity of
-- the @indices@ array.
indexCapacityInput :: Word32
, -- | @indexCountOutput@ is a @uint32_t@ returned by the runtime with the
-- count of indices written in @indices@.
indexCountOutput :: Word32
, -- | @indices@ is an array of indices filled in by the runtime, specifying
-- the indices of the triangles list in the vertex buffer.
indices :: Ptr Word32
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshIndexBufferMSFT)
#endif
deriving instance Show HandMeshIndexBufferMSFT
instance ToCStruct HandMeshIndexBufferMSFT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshIndexBufferMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr Word32)) (indexBufferKey)
poke ((p `plusPtr` 4 :: Ptr Word32)) (indexCapacityInput)
poke ((p `plusPtr` 8 :: Ptr Word32)) (indexCountOutput)
poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (indices)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 4 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 16 :: Ptr (Ptr Word32))) (zero)
f
instance FromCStruct HandMeshIndexBufferMSFT where
peekCStruct p = do
indexBufferKey <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
indexCapacityInput <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32))
indexCountOutput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32))
indices <- peek @(Ptr Word32) ((p `plusPtr` 16 :: Ptr (Ptr Word32)))
pure $ HandMeshIndexBufferMSFT
indexBufferKey indexCapacityInput indexCountOutput indices
instance Storable HandMeshIndexBufferMSFT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshIndexBufferMSFT where
zero = HandMeshIndexBufferMSFT
zero
zero
zero
zero
-- | XrHandMeshVertexBufferMSFT - The vertex buffer of a hand mesh
--
-- == Member Descriptions
--
-- = Description
--
-- An application /should/ preallocate the vertices array using the
-- @maxHandMeshVertexCount@ in 'SystemHandTrackingMeshPropertiesMSFT'
-- returned from 'OpenXR.Core10.Device.getSystemProperties'. In this way,
-- the application can avoid possible insufficient buffer sizes for each
-- query, and therefore avoid reallocating memory each frame.
--
-- The input @vertexCapacityInput@ /must/ not be 0, and @vertices@ /must/
-- not be @NULL@, or else the runtime /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_VALIDATION_FAILURE' on calls to the
-- 'updateHandMeshMSFT' function.
--
-- If the input @vertexCapacityInput@ is not sufficient to contain all
-- output vertices, the runtime /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT' on calls to the
-- 'updateHandMeshMSFT', do not change content in @vertexUpdateTime@ and
-- @vertices@, and return 0 for @vertexCountOutput@.
--
-- If the input @vertexCapacityInput@ is equal to or larger than the
-- @maxHandMeshVertexCount@ in 'SystemHandTrackingMeshPropertiesMSFT'
-- returned from 'OpenXR.Core10.Device.getSystemProperties', the runtime
-- /must/ not return 'OpenXR.Core10.Enums.Result.ERROR_SIZE_INSUFFICIENT'
-- on calls to the 'updateHandMeshMSFT' because of insufficient vertex
-- buffer size.
--
-- If the input @vertexUpdateTime@ is 0, and the capacity of the vertices
-- array is sufficient, and hand mesh tracking is active, the runtime
-- /must/ return the latest non-zero @vertexUpdateTime@, and fill in the
-- @vertexCountOutput@ and @vertices@ fields.
--
-- If the input @vertexUpdateTime@ is not 0, the runtime /can/ either
-- return without changing @vertexCountOutput@ or the content in
-- @vertices@, and return 'OpenXR.Core10.FundamentalTypes.FALSE' for
-- @vertexBufferChanged@ indicating the vertices are not changed; or return
-- a new non-zero @vertexUpdateTime@ and fill in latest data in
-- @vertexCountOutput@ and @vertices@ and return
-- 'OpenXR.Core10.FundamentalTypes.TRUE' for @vertexBufferChanged@
-- indicating the vertices are updated to a newer version.
--
-- An application /can/ keep the 'HandMeshVertexBufferMSFT' structure for
-- each frame in frame loop and use the returned @vertexUpdateTime@ to
-- detect the changes of the content in @vertices@. The application can
-- therefore avoid unnecessary processing of vertices, such as coping them
-- to GPU memory.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshVertexBufferMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshVertexBufferMSFT'
--
-- - #VUID-XrHandMeshVertexBufferMSFT-vertices-parameter# @vertices@
-- /must/ be a pointer to an array of @vertexCapacityInput@
-- 'HandMeshVertexMSFT' structures
--
-- - #VUID-XrHandMeshVertexBufferMSFT-vertexCapacityInput-arraylength#
-- The @vertexCapacityInput@ parameter /must/ be greater than @0@
--
-- = See Also
--
-- 'HandMeshMSFT', 'HandMeshVertexMSFT',
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrTime >
data HandMeshVertexBufferMSFT = HandMeshVertexBufferMSFT
{ -- | @vertexUpdateTime@ is an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrTime >
-- representing the time when the runtime receives the vertex buffer
-- content or 0 to indicate a request to retrieve latest vertices
-- regardless of existing content in @vertices@.
vertexUpdateTime :: Time
, -- | @vertexCapacityInput@ is a positive @uint32_t@ describes the capacity of
-- the @vertices@ array.
vertexCapacityInput :: Word32
, -- | @vertexCountOutput@ is a @uint32_t@ filled in by the runtime with the
-- count of vertices written in @vertices@.
vertexCountOutput :: Word32
, -- | @vertices@ is an array of 'HandMeshVertexMSFT' filled in by the runtime,
-- specifying the vertices of the hand mesh including the position and
-- normal vector in the hand mesh space.
vertices :: Ptr HandMeshVertexMSFT
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshVertexBufferMSFT)
#endif
deriving instance Show HandMeshVertexBufferMSFT
instance ToCStruct HandMeshVertexBufferMSFT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshVertexBufferMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr Time)) (vertexUpdateTime)
poke ((p `plusPtr` 8 :: Ptr Word32)) (vertexCapacityInput)
poke ((p `plusPtr` 12 :: Ptr Word32)) (vertexCountOutput)
poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (vertices)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 8 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT))) (zero)
f
instance FromCStruct HandMeshVertexBufferMSFT where
peekCStruct p = do
vertexUpdateTime <- peek @Time ((p `plusPtr` 0 :: Ptr Time))
vertexCapacityInput <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32))
vertexCountOutput <- peek @Word32 ((p `plusPtr` 12 :: Ptr Word32))
vertices <- peek @(Ptr HandMeshVertexMSFT) ((p `plusPtr` 16 :: Ptr (Ptr HandMeshVertexMSFT)))
pure $ HandMeshVertexBufferMSFT
vertexUpdateTime vertexCapacityInput vertexCountOutput vertices
instance Storable HandMeshVertexBufferMSFT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshVertexBufferMSFT where
zero = HandMeshVertexBufferMSFT
zero
zero
zero
zero
-- | XrHandMeshVertexMSFT - The vertex of hand mesh
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandMeshVertexMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandMeshVertexMSFT'
--
-- = See Also
--
-- 'HandMeshVertexBufferMSFT', 'OpenXR.Core10.Space.Vector3f'
data HandMeshVertexMSFT = HandMeshVertexMSFT
{ -- | @position@ is an 'OpenXR.Core10.Space.Vector3f' structure representing
-- the position of the vertex in the hand mesh space, measured in meters.
position :: Vector3f
, -- | @normal@ is an 'OpenXR.Core10.Space.Vector3f' structure representing the
-- unweighted normal of the triangle surface at the vertex as a unit vector
-- in hand mesh space.
normal :: Vector3f
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandMeshVertexMSFT)
#endif
deriving instance Show HandMeshVertexMSFT
instance ToCStruct HandMeshVertexMSFT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandMeshVertexMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr Vector3f)) (position)
poke ((p `plusPtr` 12 :: Ptr Vector3f)) (normal)
f
cStructSize = 24
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr Vector3f)) (zero)
poke ((p `plusPtr` 12 :: Ptr Vector3f)) (zero)
f
instance FromCStruct HandMeshVertexMSFT where
peekCStruct p = do
position <- peekCStruct @Vector3f ((p `plusPtr` 0 :: Ptr Vector3f))
normal <- peekCStruct @Vector3f ((p `plusPtr` 12 :: Ptr Vector3f))
pure $ HandMeshVertexMSFT
position normal
instance Storable HandMeshVertexMSFT where
sizeOf ~_ = 24
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandMeshVertexMSFT where
zero = HandMeshVertexMSFT
zero
zero
-- | XrSystemHandTrackingMeshPropertiesMSFT - System property for hand
-- tracking mesh
--
-- == Member Descriptions
--
-- = Description
--
-- If a runtime returns 'OpenXR.Core10.FundamentalTypes.FALSE' for
-- @supportsHandTrackingMesh@, the system does not support hand tracking
-- mesh input, and therefore /must/ return
-- 'OpenXR.Core10.Enums.Result.ERROR_FEATURE_UNSUPPORTED' from
-- 'createHandMeshSpaceMSFT' and 'updateHandMeshMSFT'. The application
-- /should/ avoid using hand mesh functionality when
-- @supportsHandTrackingMesh@ is 'OpenXR.Core10.FundamentalTypes.FALSE'.
--
-- If a runtime returns 'OpenXR.Core10.FundamentalTypes.TRUE' for
-- @supportsHandTrackingMesh@, the system supports hand tracking mesh
-- input. In this case, the runtime /must/ return a positive number for
-- @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@. An application
-- /should/ use @maxHandMeshIndexCount@ and @maxHandMeshVertexCount@ to
-- preallocate hand mesh buffers and reuse them in their render loop when
-- calling 'updateHandMeshMSFT' every frame.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrSystemHandTrackingMeshPropertiesMSFT-extension-notenabled#
-- The @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior
-- to using 'SystemHandTrackingMeshPropertiesMSFT'
--
-- - #VUID-XrSystemHandTrackingMeshPropertiesMSFT-type-type# @type@
-- /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT'
--
-- - #VUID-XrSystemHandTrackingMeshPropertiesMSFT-next-next# @next@
-- /must/ be @NULL@ or a valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- = See Also
--
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >,
-- 'OpenXR.Core10.Enums.StructureType.StructureType'
data SystemHandTrackingMeshPropertiesMSFT = SystemHandTrackingMeshPropertiesMSFT
{ -- | @supportsHandTrackingMesh@ is an
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XrBool32 >,
-- indicating if current system is capable of hand tracking mesh input.
supportsHandTrackingMesh :: Bool
, -- | @maxHandMeshIndexCount@ is a @uint32_t@ returns the maximum count of
-- indices that will be returned from the hand tracker.
maxHandMeshIndexCount :: Word32
, -- | @maxHandMeshVertexCount@ is a @uint32_t@ returns the maximum count of
-- vertices that will be returned from the hand tracker.
maxHandMeshVertexCount :: Word32
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SystemHandTrackingMeshPropertiesMSFT)
#endif
deriving instance Show SystemHandTrackingMeshPropertiesMSFT
instance ToCStruct SystemHandTrackingMeshPropertiesMSFT where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SystemHandTrackingMeshPropertiesMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (supportsHandTrackingMesh))
poke ((p `plusPtr` 20 :: Ptr Word32)) (maxHandMeshIndexCount)
poke ((p `plusPtr` 24 :: Ptr Word32)) (maxHandMeshVertexCount)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_SYSTEM_HAND_TRACKING_MESH_PROPERTIES_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 24 :: Ptr Word32)) (zero)
f
instance FromCStruct SystemHandTrackingMeshPropertiesMSFT where
peekCStruct p = do
supportsHandTrackingMesh <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
maxHandMeshIndexCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32))
maxHandMeshVertexCount <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32))
pure $ SystemHandTrackingMeshPropertiesMSFT
(bool32ToBool supportsHandTrackingMesh) maxHandMeshIndexCount maxHandMeshVertexCount
instance Storable SystemHandTrackingMeshPropertiesMSFT where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SystemHandTrackingMeshPropertiesMSFT where
zero = SystemHandTrackingMeshPropertiesMSFT
zero
zero
zero
-- | XrHandPoseTypeInfoMSFT - Describes what hand pose type for the hand
-- joint tracking.
--
-- == Valid Usage (Implicit)
--
-- - #VUID-XrHandPoseTypeInfoMSFT-extension-notenabled# The
-- @XR_MSFT_hand_tracking_mesh@ extension /must/ be enabled prior to
-- using 'HandPoseTypeInfoMSFT'
--
-- - #VUID-XrHandPoseTypeInfoMSFT-type-type# @type@ /must/ be
-- 'OpenXR.Core10.Enums.StructureType.TYPE_HAND_POSE_TYPE_INFO_MSFT'
--
-- - #VUID-XrHandPoseTypeInfoMSFT-next-next# @next@ /must/ be @NULL@ or a
-- valid pointer to the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#valid-usage-for-structure-pointer-chains next structure in a structure chain>
--
-- - #VUID-XrHandPoseTypeInfoMSFT-handPoseType-parameter# @handPoseType@
-- /must/ be a valid 'HandPoseTypeMSFT' value
--
-- = See Also
--
-- 'HandPoseTypeMSFT', 'OpenXR.Core10.Enums.StructureType.StructureType'
data HandPoseTypeInfoMSFT = HandPoseTypeInfoMSFT
{ -- | @handPoseType@ is an 'HandPoseTypeMSFT' that describes the type of hand
-- pose of the hand tracking.
handPoseType :: HandPoseTypeMSFT }
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (HandPoseTypeInfoMSFT)
#endif
deriving instance Show HandPoseTypeInfoMSFT
instance ToCStruct HandPoseTypeInfoMSFT where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p HandPoseTypeInfoMSFT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (handPoseType)
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (TYPE_HAND_POSE_TYPE_INFO_MSFT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT)) (zero)
f
instance FromCStruct HandPoseTypeInfoMSFT where
peekCStruct p = do
handPoseType <- peek @HandPoseTypeMSFT ((p `plusPtr` 16 :: Ptr HandPoseTypeMSFT))
pure $ HandPoseTypeInfoMSFT
handPoseType
instance Storable HandPoseTypeInfoMSFT where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero HandPoseTypeInfoMSFT where
zero = HandPoseTypeInfoMSFT
zero
-- | XrHandPoseTypeMSFT - Describe type of input hand pose
--
-- == Enumerant Descriptions
--
-- The 'HAND_POSE_TYPE_TRACKED_MSFT' input provides best fidelity to the
-- user’s actual hand motion. When the hand tracking input requires the
-- user to be holding a controller in their hand, the hand tracking input
-- will appear as the user virtually holding the controller. This input can
-- be used to render the hand shape together with the controller in hand.
--
-- The 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT' input does not move with
-- the user’s actual hand. Through this reference hand pose, an application
-- /can/ get a stable hand joint and mesh that has the same mesh topology
-- as the tracked hand mesh using the same
-- 'OpenXR.Extensions.Handles.HandTrackerEXT', so that the application can
-- apply the data computed from a reference hand pose to the corresponding
-- tracked hand.
--
-- Although a reference hand pose does not move with user’s hand motion,
-- the bone length and hand thickness /may/ be updated, for example when
-- tracking result refines, or a different user’s hand is detected. The
-- application /should/ update reference hand joints and meshes when the
-- tracked mesh’s @indexBufferKey@ is changed or when the @isActive@ value
-- returned from 'updateHandMeshMSFT' changes from
-- 'OpenXR.Core10.FundamentalTypes.FALSE' to
-- 'OpenXR.Core10.FundamentalTypes.TRUE'. It can use the returned
-- @indexBufferKey@ and @vertexUpdateTime@ from 'updateHandMeshMSFT' to
-- avoid unnecessary CPU or GPU work to process the neutral hand inputs.
--
-- = See Also
--
-- 'HandMeshSpaceCreateInfoMSFT', 'HandMeshUpdateInfoMSFT',
-- 'HandPoseTypeInfoMSFT'
newtype HandPoseTypeMSFT = HandPoseTypeMSFT Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'HAND_POSE_TYPE_TRACKED_MSFT' represents a hand pose provided by actual
-- tracking of the user’s hand.
pattern HAND_POSE_TYPE_TRACKED_MSFT = HandPoseTypeMSFT 0
-- | 'HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT' represents a stable reference
-- hand pose in a relaxed open hand shape.
pattern HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT = HandPoseTypeMSFT 1
{-# complete HAND_POSE_TYPE_TRACKED_MSFT,
HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT :: HandPoseTypeMSFT #-}
conNameHandPoseTypeMSFT :: String
conNameHandPoseTypeMSFT = "HandPoseTypeMSFT"
enumPrefixHandPoseTypeMSFT :: String
enumPrefixHandPoseTypeMSFT = "HAND_POSE_TYPE_"
showTableHandPoseTypeMSFT :: [(HandPoseTypeMSFT, String)]
showTableHandPoseTypeMSFT =
[(HAND_POSE_TYPE_TRACKED_MSFT, "TRACKED_MSFT"), (HAND_POSE_TYPE_REFERENCE_OPEN_PALM_MSFT, "REFERENCE_OPEN_PALM_MSFT")]
instance Show HandPoseTypeMSFT where
showsPrec = enumShowsPrec enumPrefixHandPoseTypeMSFT
showTableHandPoseTypeMSFT
conNameHandPoseTypeMSFT
(\(HandPoseTypeMSFT x) -> x)
(showsPrec 11)
instance Read HandPoseTypeMSFT where
readPrec = enumReadPrec enumPrefixHandPoseTypeMSFT showTableHandPoseTypeMSFT conNameHandPoseTypeMSFT HandPoseTypeMSFT
type MSFT_hand_tracking_mesh_SPEC_VERSION = 2
-- No documentation found for TopLevel "XR_MSFT_hand_tracking_mesh_SPEC_VERSION"
pattern MSFT_hand_tracking_mesh_SPEC_VERSION :: forall a . Integral a => a
pattern MSFT_hand_tracking_mesh_SPEC_VERSION = 2
type MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh"
-- No documentation found for TopLevel "XR_MSFT_HAND_TRACKING_MESH_EXTENSION_NAME"
pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern MSFT_HAND_TRACKING_MESH_EXTENSION_NAME = "XR_MSFT_hand_tracking_mesh"
| expipiplus1/vulkan | openxr/src/OpenXR/Extensions/XR_MSFT_hand_tracking_mesh.hs | bsd-3-clause | 53,294 | 1 | 17 | 9,471 | 7,433 | 4,329 | 3,104 | -1 | -1 |
module TeamSelect
( interactiveTeamSelection
)
where
import Prelude ()
import Prelude.MH
import Brick
import Brick.Widgets.Border
import Brick.Widgets.Center
import Brick.Widgets.List
import qualified Data.Function as F
import Data.List ( sortBy )
import qualified Data.Vector as V
import Graphics.Vty
import System.Exit ( exitSuccess )
import Network.Mattermost.Types
import Markdown
import Types.Common
type State = List () Team
interactiveTeamSelection :: [Team] -> IO Team
interactiveTeamSelection teams = do
let state = list () (V.fromList sortedTeams) 1
sortedTeams = sortBy (compare `F.on` teamName) teams
finalSt <- defaultMain app state
let Just (_, t) = listSelectedElement finalSt
return t
app :: App State e ()
app = App
{ appDraw = teamSelectDraw
, appChooseCursor = neverShowCursor
, appHandleEvent = onEvent
, appStartEvent = return
, appAttrMap = const colorTheme
}
colorTheme :: AttrMap
colorTheme = attrMap defAttr
[ (listSelectedFocusedAttr, black `on` yellow)
]
teamSelectDraw :: State -> [Widget ()]
teamSelectDraw st =
[ teamSelect st
]
teamSelect :: State -> Widget ()
teamSelect st =
center $ hLimit 50 $ vLimit 15 $
vBox [ hCenter $ txt "Welcome to Mattermost. Please select a team:"
, txt " "
, border theList
, txt " "
, renderText "Press Enter to select a team and connect or Esc to exit."
]
where
theList = renderList renderTeamItem True st
renderTeamItem :: Bool -> Team -> Widget ()
renderTeamItem _ t =
padRight Max $ txt $ sanitizeUserText $ teamName t
onEvent :: State -> BrickEvent () e -> EventM () (Next State)
onEvent _ (VtyEvent (EvKey KEsc [])) = liftIO exitSuccess
onEvent st (VtyEvent (EvKey KEnter [])) = halt st
onEvent st (VtyEvent e) = continue =<< handleListEvent e st
onEvent st _ = continue st
| aisamanra/matterhorn | src/TeamSelect.hs | bsd-3-clause | 2,010 | 0 | 13 | 545 | 600 | 317 | 283 | 54 | 1 |
{- Testing definitiosn in no-role-annots package.
Copyright 2014 Richard Eisenberg
https://github.com/goldfirere/no-role-annots/
-}
{-# LANGUAGE TemplateHaskell, GADTs #-}
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-warnings-deprecations #-}
module Test.Defns (MyMap1, MyMap2, mkMap2, MyPtr1, MyPtr2, MyMap3, MyMap4) where
import Language.Haskell.RoleAnnots
data MyMap1 k v = MkMyMap1 [(k,v)]
data (Nominal k, Representational v) => MyMap2 k v = MkMyMap2 [(k,v)]
data MyPtr1 a = MkMyPtr1 Int
data Representational a => MyPtr2 a = MkMyPtr2 Int
roleAnnot [NominalR, RepresentationalR]
[d| newtype MyMap3 k v = MkMyMap3 [(k,v)] |]
newtype (Nominal k, Representational v) => MyMap4 k v = MkMyMap4 [(k,v)]
-- check that compilation works:
mkMap2 :: k -> v -> MyMap2 k v
mkMap2 k v = MkMyMap2 [(k,v)]
matchMap2 :: MyMap2 k v -> ()
matchMap2 (MkMyMap2 _) = ()
| goldfirere/no-role-annots | Test/Defns.hs | bsd-3-clause | 875 | 0 | 8 | 141 | 245 | 145 | 100 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.RBB.Crawler.MetaCombinerSpec
where
import Control.Applicative
import Control.Lens hiding (elements)
import qualified Data.IxSet as IxSet
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text as T (Text, length, pack)
import Data.Time
import System.FilePath ((</>))
import Web.RBB.Crawler.MetaCombiner as M
import Web.RBB.Crawler.MetaParser as M
import Web.RBB.Types.Entry
import Web.RBB.Types.FileType
import Test.Hspec as Test
import Test.QuickCheck
noNewline c = c `notElem` ("\n\r" :: String)
instance Arbitrary Text where
arbitrary = do
r <- pack . filter noNewline <$> arbitrary
return $ case T.length r of
0 -> "foo"
_ -> r
instance Arbitrary Day where
arbitrary = ModifiedJulianDay . getNonNegative <$> arbitrary
instance Arbitrary DiffTime where
arbitrary = picosecondsToDiffTime . getNonNegative <$> arbitrary
instance Arbitrary UTCTime where
arbitrary = UTCTime <$> arbitrary <*> arbitrary
instance Arbitrary EntryUpdate where
arbitrary = EntryUpdate <$> arbitrary <*> (getNonEmpty <$> arbitrary)
instance Arbitrary Entry where
arbitrary = do
i <- getNonNegative <$> arbitrary
t <- arbitrary
a <- arbitrary
m <- arbitrary
ts <- arbitrary
ft <- arbitraryBoundedEnum
u <- arbitrary
(fp,rp) <- (\fp rp -> ("" </> getNonEmpty fp </> getNonEmpty rp, getNonEmpty rp))
<$> arbitrary <*> arbitrary
return $ Entry
{ _entryId = i
, _title = t
, _author = a
, _authorEmail = m
, _tags = ts
, _fileType = ft
, _relativePath = rp
, _fullPath = fp
, _updates = IxSet.fromList [u]
, _lastUpdate = u
}
instance Arbitrary TagQuantifier where
arbitrary = arbitraryBoundedEnum
instance Arbitrary Meta where
arbitrary = do
i <- elements [0..3] :: Gen Int
case () of
_ | i == 0 -> M.Tags <$> arbitrary
_ | i == 1 -> M.Title <$> arbitrary
_ | i == 2 -> M.Context . filter noNewline <$> arbitrary
_ -> return None
spec :: Spec
spec = do
let t = UTCTime (ModifiedJulianDay 1337) (picosecondsToDiffTime 42)
let eu = EntryUpdate t "foo"
let mdMock = Entry
{ _entryId = 7
, _title = "title"
, _author = "me"
, _authorEmail = "[email protected]"
, _tags = mempty
, _fileType = PandocMarkdown
, _relativePath = "some/path"
, _fullPath = "/root/for/some/path"
, _updates = IxSet.fromList [eu]
, _lastUpdate = eu
}
md1 = mdMock & title .~ "Foo Bar"
& tags .~ Set.fromList ["foo", "bar", "quz"]
md2 = mdMock & title .~ "Quz"
& tags .~ Set.fromList ["one", "two"]
md3 = mdMock & tags .~ Set.fromList ["only one"]
describe "updateTags" $ do
it "should remain unchanged for an empty tag list" $ property $ do
\x -> updateTags [] x `shouldBe` x
it "should ovewrite any previous value if at least one tag is without\
\ a prefix" $ property $ do
\x ts -> (not . null . filter ((== TagReplace) . fst)) ts
==> updateTags ts x `shouldBe` updateTags ts mempty
Test.context "unit tests" $ do
it "1)" $ do
updateTags [(TagAdd, "added")] (md1^.tags)
`shouldBe` Set.insert "added" (md1^.tags)
it "2)" $ do
updateTags [(TagReplace, "replaced")] (md1^.tags)
`shouldBe` Set.singleton "replaced"
it "3)" $ do
updateTags [(TagRemove, "foo"),(TagRemove, "bar")] (md1^.tags)
`shouldBe` Set.singleton "quz"
it "4)" $ do
updateTags [(TagRemove, "only one")] (md3^.tags)
`shouldBe` mempty
describe "contract" $ do
let notContext m = case m of
(M.Context _) -> False
_ -> True
it "should create an empy map if no context is given" $ property $ do
\x -> let meta = filter notContext x
in contract Nothing meta mempty `shouldBe` mempty
it "should match the case 1" $ do
let p = md1^.relativePath
meta = [ M.Context p
, M.Tags [(TagReplace, "foo"), (TagAdd, "quz")]
, M.Title "Foo Bar"
, M.Tags [(TagAdd, "bar")]
]
contract Nothing meta (IxSet.fromList [mdMock])
`shouldBe` IxSet.fromList [md1]
it "should match the case 2" $ do
let p = md2^.relativePath
md = mdMock & relativePath .~ p
meta = [ M.Title "Quz"
, M.Tags [(TagAdd, "three")]
, M.Tags [(TagAdd, "one")]
, M.Tags [(TagAdd, "two")]
, M.Tags [(TagRemove, "three")]
]
contract (Just p) meta (IxSet.fromList [md])
`shouldBe` IxSet.fromList [md2]
it "should match the case 3" $ do
let p = md3^.relativePath
md = mdMock & relativePath .~ p
meta = [ M.Title "bar"
, M.Tags [(TagReplace, "only one")]
, M.Title "title"
]
contract (Just p) meta (IxSet.fromList [md])
`shouldBe` IxSet.fromList [md3]
| saep/repo-based-blog | test-suite/Web/RBB/Crawler/MetaCombinerSpec.hs | bsd-3-clause | 6,017 | 0 | 22 | 2,426 | 1,671 | 889 | 782 | 137 | 2 |
{- chris
WBL0.hs:37:5:
"WBL0.hs" (line 37, column 10):
[lq| data Heap a <q :: a -> a -> Prop> =
^
unexpected reserved word "data"
expecting variable identifier
-}
{-# LANGUAGE QuasiQuotes #-}
-----------------------------------------------------------------------
-- Weight-Biased Leftist Heap, verified using LiquidHaskell -----------
-----------------------------------------------------------------------
-- ORIGINAL SOURCE ----------------------------------------------------
-----------------------------------------------------------------------
-- Copyright: 2014, Jan Stolarek, Politechnika Łódzka --
-- --
-- License: See LICENSE file in root of the repo --
-- Repo address: https://github.com/jstolarek/dep-typed-wbl-heaps-hs --
-- --
-- Basic implementation of weight-biased leftist heap. No proofs --
-- and no dependent types. Uses a two-pass merging algorithm. --
-----------------------------------------------------------------------
{-@ LIQUID "--no-termination "@-}
import LiquidHaskell
type Priority = Int
type Rank = Int
type Nat = Int
data Heap a = Empty | Node { pri :: a
, rnk :: Rank
, left :: Heap a
, right :: Heap a
}
[lq| data Heap a <q :: a -> a -> Prop> =
Empty | Node { pri :: a
, rnk :: Nat
, left :: {v: Heap<q> (a<q pri>) | ValidRank v}
, right :: {v: Heap<q> (a<q pri>) | ValidRank v}
}
|]
[lq| predicate ValidRank V = okRank V && realRank V = rank V |]
[lq| type PHeap a = {v:OHeap a | ValidRank v} |]
[lq| type OHeap a = Heap <{\root v -> root <= v}> a |]
[lq| measure okRank |]
okRank :: Heap a -> Bool
okRank (Empty) = True
okRank (Node p k l r) = realRank l >= realRank r && k == 1 + realRank l + realRank r
[lq| measure realRank |]
realRank :: Heap a -> Int
realRank (Empty) = 0
realRank (Node p k l r) = 1 + realRank l + realRank r
[lq| measure rank |]
[lq| rank :: h:PHeap a -> {v:Nat | v = realRank h} |]
rank Empty = 0
rank (Node _ r _ _) = r
-- Creates heap containing a single element with a given Priority
[lq| singleton :: a -> PHeap a |]
singleton p = Node p 1 Empty Empty
-- Note [Two-pass merging algorithm]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- We use a two-pass implementation of merging algorithm. One pass,
-- implemented by merge, performs merging in a top-down manner. Second
-- one, implemented by makeT, ensures that rank invariant of weight
-- biased leftist tree is not violated after merging.
--
-- Notation:
--
-- h1, h2 - heaps being merged
-- p1, p2 - priority of root element in h1 and h2
-- l1 - left subtree in the first heap
-- r1 - right subtree in the first heap
-- l2 - left subtree in the second heap
-- r2 - right subtree in the second heap
--
-- Merge function analyzes four cases. Two of them are base cases:
--
-- a) h1 is empty - return h2
--
-- b) h2 is empty - return h1
--
-- The other two cases form the inductive definition of merge:
--
-- c) priority p1 is higher than p2 - p1 becomes new root, l1
-- becomes its one child and result of merging r1 with h2
-- becomes the other child:
--
-- p1
-- / \
-- / \
-- l1 r1+h2 -- here "+" denotes merging
--
-- d) priority p2 is higher than p2 - p2 becomes new root, l2
-- becomes its one child and result of merging r2 with h1
-- becomes the other child.
--
-- p2
-- / \
-- / \
-- l2 r2+h1
--
-- Note that there is no guarantee that rank of r1+h2 (or r2+h1) will
-- be smaller than rank of l1 (or l2). To ensure that merged heap
-- maintains the rank invariant we pass both childred - ie. either l1
-- and r1+h2 or l2 and r2+h1 - to makeT, which creates a new node by
-- inspecting sizes of children and swapping them if necessary.
-- makeT takes an element (Priority) and two heaps (trees). It
-- constructs a new heap with element at the root and two heaps as
-- children. makeT ensures that WBL heap rank invariant is maintained
-- in the newly created tree by reversing left and right subtrees when
-- necessary (note the inversed r and l in the False alternative of
-- case expression).
[lq| makeT :: p:a -> h1:PHeap {v:a | p <= v} -> h2:PHeap {v:a | p <= v}
-> {v:PHeap a | realRank v = 1 + realRank h1 + realRank h2} |]
makeT p l r = case rank l >= rank r of
True -> Node p (1 + rank l + rank r) l r
False -> Node p (1 + rank l + rank r) r l
-- merge combines two heaps into one. There are two base cases and two
-- recursive cases - see [Two-pass Merging algorithm]. Recursive cases
-- call makeT to ensure that rank invariant is maintained after
-- merging.
[lq| merge :: (Ord a) => h1:PHeap a -> h2:PHeap a -> {v:PHeap a | realRank v = realRank h1 + realRank h2} |]
merge Empty h2 = h2
merge h1 Empty = h1
merge h1@(Node p1 k1 l1 r1) h2@(Node p2 k2 l2 r2) = case p1 < p2 of
True -> makeT p1 l1 (merge r1 (Node p2 k2 l2 r2))
False -> makeT p2 l2 (merge (Node p1 k1 l1 r1) r2)
-- Inserting into a heap is performed by merging that heap with newly
-- created singleton heap.
[lq| insert :: (Ord a) => a -> PHeap a -> PHeap a |]
insert p h = merge (singleton p) h
-- findMin returns element with highest priority, ie. root
-- element. Here we encounter first serious problem: we can't return
-- anything sensible for empty node.
[lq| findMin :: PHeap a -> a |]
findMin Empty = undefined
findMin (Node p _ _ _) = p
-- and write a safer version of findMinM
[lq| findMinM :: PHeap a -> Maybe a |]
findMinM Empty = Nothing
findMinM (Node p _ _ _) = Just p
-- deleteMin removes the element with the highest priority by merging
-- subtrees of a root element. Again the case of empty heap is
-- problematic. We could give it semantics by returning Empty, but
-- this just doesn't feel right. Why should we be able to remove
-- elements from an empty heap?
[lq| deleteMin :: (Ord a) => PHeap a -> PHeap a |]
deleteMin Empty = undefined -- should we insert empty?
deleteMin (Node _ _ l r) = merge l r
-- As a quick sanity check let's construct some examples. Here's a
-- heap constructed by inserting following priorities into an empty
-- heap: 3, 0, 1, 2.
[lq| heap :: PHeap Int |]
heap = insert (2 :: Int)
(insert 1
(insert 0
(insert 3 Empty)))
-- Example usage of findMin
findMinInHeap :: Priority
findMinInHeap = findMin heap
-- Example usage of deleteMin
deleteMinFromHeap :: Heap Int
deleteMinFromHeap = deleteMin heap
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/WBL0.hs | bsd-3-clause | 6,935 | 0 | 12 | 1,957 | 852 | 498 | 354 | 57 | 2 |
module Tests.Operations.RunSpec
( spec
) where
import Test.Hspec
import Test.QuickCheck
import Tests.Common (assertFa)
import Operations.Regular (charsToSymbols, run)
spec :: Spec
spec =
describe "FA" $ do
describe "oneStateFa.txt" $ do
it "accepts empty language" $
assertFa "oneStateFa.txt" (\fa -> run fa [])
it "doesn't accept non-empty string" $
assertFa "oneStateFa.txt" (\fa -> not $ run fa (charsToSymbols "Hello World!"))
describe "0.txt" $ do
it "accepts 'a17 a18 a18 a2'" $
assertFa "0.txt" (\fa -> run fa ["a17", "a18", "a18", "a2"])
it "doesn't accept 'a18 a18 a2'" $
assertFa "0.txt" (\fa -> not $ run fa ["a18", "a18", "a2"])
| jakubriha/automata | tests/Tests/Operations/RunSpec.hs | bsd-3-clause | 720 | 0 | 18 | 177 | 231 | 119 | 112 | 19 | 1 |
main = "hello
world"
| roberth/uu-helium | test/parser/NewlineInString.hs | gpl-3.0 | 21 | 4 | 5 | 4 | 11 | 6 | 5 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-|
Journal entries report, used by the print command.
-}
module Hledger.Reports.EntriesReport (
EntriesReport,
EntriesReportItem,
entriesReport,
-- * Tests
tests_EntriesReport
)
where
import Data.List (sortBy)
import Data.Ord (comparing)
import Data.Time (fromGregorian)
import Hledger.Data
import Hledger.Query (Query(..))
import Hledger.Reports.ReportOptions
import Hledger.Utils
-- | A journal entries report is a list of whole transactions as
-- originally entered in the journal (mostly). This is used by eg
-- hledger's print command and hledger-web's journal entries view.
type EntriesReport = [EntriesReportItem]
type EntriesReportItem = Transaction
-- | Select transactions for an entries report.
entriesReport :: ReportSpec -> Journal -> EntriesReport
entriesReport rspec@ReportSpec{_rsReportOpts=ropts} =
sortBy (comparing $ transactionDateFn ropts) . jtxns
. journalApplyValuationFromOpts (setDefaultConversionOp NoConversionOp rspec)
. filterJournalTransactions (_rsQuery rspec)
tests_EntriesReport = testGroup "EntriesReport" [
testGroup "entriesReport" [
testCase "not acct" $ (length $ entriesReport defreportspec{_rsQuery=Not . Acct $ toRegex' "bank"} samplejournal) @?= 1
,testCase "date" $ (length $ entriesReport defreportspec{_rsQuery=Date $ DateSpan (Just $ fromGregorian 2008 06 01) (Just $ fromGregorian 2008 07 01)} samplejournal) @?= 3
]
]
| adept/hledger | hledger-lib/Hledger/Reports/EntriesReport.hs | gpl-3.0 | 1,524 | 0 | 20 | 228 | 317 | 177 | 140 | 26 | 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="bs-BA">
<title>Export Report | 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/exportreport/src/main/javahelp/org/zaproxy/zap/extension/exportreport/resources/help_bs_BA/helpset_bs_BA.hs | apache-2.0 | 975 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
#if __GLASGOW_HASKELL__ >= 710
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Data.Text.Strict.Lens
-- Copyright : (C) 2012-2015 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
----------------------------------------------------------------------------
module Data.Text.Strict.Lens
( packed, unpacked
, builder
, text
, utf8
, _Text
#if __GLASGOW_HASKELL__ >= 710
, pattern Text
#endif
) where
import Control.Lens.Type
import Control.Lens.Getter
import Control.Lens.Fold
import Control.Lens.Iso
import Control.Lens.Prism
#if __GLASGOW_HASKELL__ >= 710
import Control.Lens.Review
#endif
import Control.Lens.Setter
import Control.Lens.Traversal
import Data.ByteString (ByteString)
import Data.Monoid
import Data.Text as Strict
import Data.Text.Encoding
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import Control.Lens
-- | This isomorphism can be used to 'pack' (or 'unpack') strict 'Text'.
--
--
-- >>> "hello"^.packed -- :: Text
-- "hello"
--
-- @
-- 'pack' x ≡ x '^.' 'packed'
-- 'unpack' x ≡ x '^.' 'from' 'packed'
-- 'packed' ≡ 'from' 'unpacked'
-- 'packed' ≡ 'iso' 'pack' 'unpack'
-- @
packed :: Iso' String Text
packed = iso pack unpack
{-# INLINE packed #-}
-- | This isomorphism can be used to 'unpack' (or 'pack') lazy 'Text'.
--
-- >>> "hello"^.unpacked -- :: String
-- "hello"
--
-- This 'Iso' is provided for notational convenience rather than out of great need, since
--
-- @
-- 'unpacked' ≡ 'from' 'packed'
-- @
--
-- @
-- 'pack' x ≡ x '^.' 'from' 'unpacked'
-- 'unpack' x ≡ x '^.' 'packed'
-- 'unpacked' ≡ 'iso' 'unpack' 'pack'
-- @
unpacked :: Iso' Text String
unpacked = iso unpack pack
{-# INLINE unpacked #-}
-- | This is an alias for 'unpacked' that makes it more obvious how to use it with '#'
--
-- >> _Text # "hello" -- :: Text
-- "hello"
_Text :: Iso' Text String
_Text = unpacked
{-# INLINE _Text #-}
-- | Convert between strict 'Text' and 'Builder' .
--
-- @
-- 'fromText' x ≡ x '^.' 'builder'
-- 'toStrict' ('toLazyText' x) ≡ x '^.' 'from' 'builder'
-- @
builder :: Iso' Text Builder
builder = iso fromText (toStrict . toLazyText)
{-# INLINE builder #-}
-- | Traverse the individual characters in strict 'Text'.
--
-- >>> anyOf text (=='o') "hello"
-- True
--
-- When the type is unambiguous, you can also use the more general 'each'.
--
-- @
-- 'text' ≡ 'unpacked' . 'traversed'
-- 'text' ≡ 'each'
-- @
--
-- Note that when just using this as a 'Setter', @'setting' 'Data.Text.map'@ can
-- be more efficient.
text :: IndexedTraversal' Int Text Char
text = unpacked . traversed
{-# INLINE [0] text #-}
{-# RULES
"strict text -> map" text = sets Strict.map :: ASetter' Text Char;
"strict text -> imap" text = isets imapStrict :: AnIndexedSetter' Int Text Char;
"strict text -> foldr" text = foldring Strict.foldr :: Getting (Endo r) Text Char;
"strict text -> ifoldr" text = ifoldring ifoldrStrict :: IndexedGetting Int (Endo r) Text Char;
#-}
imapStrict :: (Int -> Char -> Char) -> Text -> Text
imapStrict f = snd . Strict.mapAccumL (\i a -> i `seq` (i + 1, f i a)) 0
{-# INLINE imapStrict #-}
ifoldrStrict :: (Int -> Char -> a -> a) -> a -> Text -> a
ifoldrStrict f z xs = Strict.foldr (\ x g i -> i `seq` f i x (g (i+1))) (const z) xs 0
{-# INLINE ifoldrStrict #-}
-- | Encode/Decode a strict 'Text' to/from strict 'ByteString', via UTF-8.
--
-- >>> utf8 # "☃"
-- "\226\152\131"
utf8 :: Prism' ByteString Text
utf8 = prism' encodeUtf8 (preview _Right . decodeUtf8')
{-# INLINE utf8 #-}
#if __GLASGOW_HASKELL__ >= 710
pattern Text a <- (view _Text -> a) where
Text a = review _Text a
#endif
| omefire/lens | src/Data/Text/Strict/Lens.hs | bsd-3-clause | 3,974 | 0 | 13 | 711 | 558 | 351 | 207 | 50 | 1 |
{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-2002
Various types used during typechecking, please see TcRnMonad as well for
operations on these types. You probably want to import it, instead of this
module.
All the monads exported here are built on top of the same IOEnv monad. The
monad functions like a Reader monad in the way it passes the environment
around. This is done to allow the environment to be manipulated in a stack
like fashion when entering expressions... ect.
For state that is global and should be returned at the end (e.g not part
of the stack mechanism), you should use an TcRef (= IORef) to store them.
-}
{-# LANGUAGE CPP, ExistentialQuantification #-}
module ETA.TypeCheck.TcRnTypes(
TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
TcRef,
-- The environment types
Env(..),
TcGblEnv(..), TcLclEnv(..),
IfGblEnv(..), IfLclEnv(..),
-- Ranamer types
ErrCtxt, RecFieldEnv(..),
ImportAvails(..), emptyImportAvails, plusImportAvails,
WhereFrom(..), mkModDeps,
-- Typechecker types
TcTypeEnv, TcIdBinder(..), TcTyThing(..), PromotionErr(..),
pprTcTyThingCategory, pprPECategory,
-- Desugaring types
DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
DsMetaEnv, DsMetaVal(..),
-- Template Haskell
ThStage(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage,
ThLevel, impLevel, outerLevel, thLevel,
-- Arrows
ArrowCtxt(..),
-- Canonical constraints
Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
isEmptyCts, isCTyEqCan, isCFunEqCan,
isCDictCan_Maybe, isCFunEqCan_maybe,
isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
isGivenCt, isHoleCt, isTypedHoleCt, isPartialTypeSigCt,
ctEvidence, ctLoc, ctPred, ctFlavour, ctEqRel,
mkNonCanonical, mkNonCanonicalCt,
ctEvPred, ctEvLoc, ctEvEqRel,
ctEvTerm, ctEvCoercion, ctEvId, ctEvCheckDepth,
WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
dropDerivedWC,
Implication(..),
SubGoalCounter(..),
SubGoalDepth, initialSubGoalDepth, maxSubGoalDepth,
bumpSubGoalDepth, subGoalCounterValue, subGoalDepthExceeded,
CtLoc(..), ctLocSpan, ctLocEnv, ctLocOrigin,
ctLocDepth, bumpCtLocDepth,
setCtLocOrigin, setCtLocEnv, setCtLocSpan,
CtOrigin(..), pprCtOrigin,
pushErrCtxt, pushErrCtxtSameOrigin,
SkolemInfo(..),
CtEvidence(..),
mkGivenLoc,
isWanted, isGiven, isDerived,
ctEvRole,
-- Constraint solver plugins
TcPlugin(..), TcPluginResult(..), TcPluginSolver,
TcPluginM, runTcPluginM, unsafeTcPluginTcM,
CtFlavour(..), ctEvFlavour,
-- Pretty printing
pprEvVarTheta,
pprEvVars, pprEvVarWithType,
pprArising, pprArisingAt,
-- Misc other types
TcId, TcIdSet, HoleSort(..)
) where
import ETA.HsSyn.HsSyn
import ETA.Core.CoreSyn
import ETA.Main.HscTypes
import ETA.TypeCheck.TcEvidence
import ETA.Types.Type
import ETA.Types.CoAxiom ( Role )
import ETA.Types.Class ( Class )
import ETA.Types.TyCon ( TyCon )
import ETA.BasicTypes.ConLike ( ConLike(..) )
import ETA.BasicTypes.DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
import ETA.BasicTypes.PatSyn ( PatSyn, patSynType )
import ETA.Prelude.TysWiredIn ( coercibleClass )
import ETA.TypeCheck.TcType
import ETA.Main.Annotations
import ETA.Types.InstEnv
import ETA.Types.FamInstEnv
import ETA.Utils.IOEnv
import ETA.BasicTypes.RdrName
import ETA.BasicTypes.Name
import ETA.BasicTypes.NameEnv
import ETA.BasicTypes.NameSet
import ETA.BasicTypes.Avail
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.Module
import ETA.BasicTypes.SrcLoc
import ETA.BasicTypes.VarSet
import ETA.Main.ErrUtils
import ETA.Utils.UniqFM
import ETA.BasicTypes.UniqSupply
import ETA.BasicTypes.BasicTypes
import ETA.Utils.Bag
import ETA.Main.DynFlags
import ETA.Utils.Outputable
import ETA.Utils.ListSetOps
import ETA.Utils.FastString
import GHC.Fingerprint
import Data.Set (Set)
import Control.Monad (ap, liftM)
#ifdef GHCI
import Data.Map ( Map )
import Data.Dynamic ( Dynamic )
import Data.Typeable ( TypeRep )
import qualified Language.Haskell.TH as TH
#endif
{-
************************************************************************
* *
Standard monad definition for TcRn
All the combinators for the monad can be found in TcRnMonad
* *
************************************************************************
The monad itself has to be defined here, because it is mentioned by ErrCtxt
-}
type TcRnIf a b = IOEnv (Env a b)
type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
type IfG = IfM () -- Top level
type IfL = IfM IfLclEnv -- Nested
type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
-- TcRn is the type-checking and renaming monad: the main monad that
-- most type-checking takes place in. The global environment is
-- 'TcGblEnv', which tracks all of the top-level type-checking
-- information we've accumulated while checking a module, while the
-- local environment is 'TcLclEnv', which tracks local information as
-- we move inside expressions.
-- | Historical "renaming monad" (now it's just 'TcRn').
type RnM = TcRn
-- | Historical "type-checking monad" (now it's just 'TcRn').
type TcM = TcRn
-- We 'stack' these envs through the Reader like monad infastructure
-- as we move into an expression (although the change is focused in
-- the lcl type).
data Env gbl lcl
= Env {
env_top :: HscEnv, -- Top-level stuff that never changes
-- Includes all info about imported things
env_us :: {-# UNPACK #-} !(IORef UniqSupply),
-- Unique supply for local varibles
env_gbl :: gbl, -- Info about things defined at the top level
-- of the module being compiled
env_lcl :: lcl -- Nested stuff; changes as we go into
}
instance ContainsDynFlags (Env gbl lcl) where
extractDynFlags env = hsc_dflags (env_top env)
replaceDynFlags env dflags
= env {env_top = replaceDynFlags (env_top env) dflags}
instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
extractModule env = extractModule (env_gbl env)
{-
************************************************************************
* *
The interface environments
Used when dealing with IfaceDecls
* *
************************************************************************
-}
data IfGblEnv
= IfGblEnv {
-- The type environment for the module being compiled,
-- in case the interface refers back to it via a reference that
-- was originally a hi-boot file.
-- We need the module name so we can test when it's appropriate
-- to look in this env.
if_rec_types :: Maybe (Module, IfG TypeEnv)
-- Allows a read effect, so it can be in a mutable
-- variable; c.f. handling the external package type env
-- Nothing => interactive stuff, no loops possible
}
data IfLclEnv
= IfLclEnv {
-- The module for the current IfaceDecl
-- So if we see f = \x -> x
-- it means M.f = \x -> x, where M is the if_mod
if_mod :: Module,
-- The field is used only for error reporting
-- if (say) there's a Lint error in it
if_loc :: SDoc,
-- Where the interface came from:
-- .hi file, or GHCi state, or ext core
-- plus which bit is currently being examined
if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
-- (and coercions)
if_id_env :: UniqFM Id -- Nested id binding
}
{-
************************************************************************
* *
Desugarer monad
* *
************************************************************************
Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
a @UniqueSupply@ and some annotations, which
presumably include source-file location information:
-}
-- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
-- variables found in 'Data.Array.Parallel'.
--
data PArrBuiltin
= PArrBuiltin
{ lengthPVar :: Var -- ^ lengthP
, replicatePVar :: Var -- ^ replicateP
, singletonPVar :: Var -- ^ singletonP
, mapPVar :: Var -- ^ mapP
, filterPVar :: Var -- ^ filterP
, zipPVar :: Var -- ^ zipP
, crossMapPVar :: Var -- ^ crossMapP
, indexPVar :: Var -- ^ (!:)
, emptyPVar :: Var -- ^ emptyP
, appPVar :: Var -- ^ (+:+)
, enumFromToPVar :: Var -- ^ enumFromToP
, enumFromThenToPVar :: Var -- ^ enumFromThenToP
}
data DsGblEnv
= DsGblEnv
{ ds_mod :: Module -- For SCC profiling
, ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
, ds_unqual :: PrintUnqualified
, ds_msgs :: IORef Messages -- Warning messages
, ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
-- possibly-imported things
, ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
-- iff '-fvectorise' flag was given as well as
-- exported entities of 'Data.Array.Parallel' iff
-- '-XParallelArrays' was given; otherwise, empty
, ds_parr_bi :: PArrBuiltin -- desugarar names for '-XParallelArrays'
, ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
-- ^ Bindings resulted from floating static forms
}
instance ContainsModule DsGblEnv where
extractModule = ds_mod
data DsLclEnv = DsLclEnv {
dsl_meta :: DsMetaEnv, -- Template Haskell bindings
dsl_loc :: SrcSpan -- to put in pattern-matching error msgs
}
-- Inside [| |] brackets, the desugarer looks
-- up variables in the DsMetaEnv
type DsMetaEnv = NameEnv DsMetaVal
data DsMetaVal
= DsBound Id -- Bound by a pattern inside the [| |].
-- Will be dynamically alpha renamed.
-- The Id has type THSyntax.Var
| DsSplice (HsExpr Id) -- These bindings are introduced by
-- the PendingSplices on a HsBracketOut
{-
************************************************************************
* *
Global typechecker environment
* *
************************************************************************
-}
-- | 'TcGblEnv' describes the top-level of the module at the
-- point at which the typechecker is finished work.
-- It is this structure that is handed on to the desugarer
-- For state that needs to be updated during the typechecking
-- phase and returned at end, use a 'TcRef' (= 'IORef').
data TcGblEnv
= TcGblEnv {
tcg_mod :: Module, -- ^ Module being compiled
tcg_src :: HscSource,
-- ^ What kind of module (regular Haskell, hs-boot, ext-core)
tcg_sig_of :: Maybe Module,
-- ^ Are we being compiled as a signature of an implementation?
tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
-- ^ Environment used only during -sig-of for resolving top level
-- bindings. See Note [Signature parameters in TcGblEnv and DynFlags]
tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
tcg_default :: Maybe [Type],
-- ^ Types used for defaulting. @Nothing@ => no @default@ decl
tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
-- See Note [The interactive package] in HscTypes
tcg_type_env :: TypeEnv,
-- ^ Global type env for the module we are compiling now. All
-- TyCons and Classes (for this module) end up in here right away,
-- along with their derived constructors, selectors.
--
-- (Ids defined in this module start in the local envt, though they
-- move to the global envt during zonking)
--
-- NB: for what "things in this module" means, see
-- Note [The interactive package] in HscTypes
tcg_type_env_var :: TcRef TypeEnv,
-- Used only to initialise the interface-file
-- typechecker in initIfaceTcRn, so that it can see stuff
-- bound in this module when dealing with hi-boot recursions
-- Updated at intervals (e.g. after dealing with types and classes)
tcg_inst_env :: InstEnv,
-- ^ Instance envt for all /home-package/ modules;
-- Includes the dfuns in tcg_insts
tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
tcg_ann_env :: AnnEnv, -- ^ And for annotations
tcg_visible_orphan_mods :: ModuleSet,
-- ^ The set of orphan modules which transitively reachable from
-- direct imports. We use this to figure out if an orphan instance
-- in the global InstEnv should be considered visible.
-- See Note [Instance lookup and orphan instances] in InstEnv
-- Now a bunch of things about this module that are simply
-- accumulated, but never consulted until the end.
-- Nevertheless, it's convenient to accumulate them along
-- with the rest of the info from this module.
tcg_exports :: [AvailInfo], -- ^ What is exported
tcg_imports :: ImportAvails,
-- ^ Information about what was imported from where, including
-- things bound in this module. Also store Safe Haskell info
-- here about transative trusted packaage requirements.
tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
tcg_used_rdrnames :: TcRef (Set RdrName),
-- See Note [Tracking unused binding and imports]
tcg_keep :: TcRef NameSet,
-- ^ Locally-defined top-level names to keep alive.
--
-- "Keep alive" means give them an Exported flag, so that the
-- simplifier does not discard them as dead code, and so that they
-- are exposed in the interface file (but not to export to the
-- user).
--
-- Some things, like dict-fun Ids and default-method Ids are "born"
-- with the Exported flag on, for exactly the above reason, but some
-- we only discover as we go. Specifically:
--
-- * The to/from functions for generic data types
--
-- * Top-level variables appearing free in the RHS of an orphan
-- rule
--
-- * Top-level variables appearing free in a TH bracket
tcg_th_used :: TcRef Bool,
-- ^ @True@ <=> Template Haskell syntax used.
--
-- We need this so that we can generate a dependency on the
-- Template Haskell package, because the desugarer is going
-- to emit loads of references to TH symbols. The reference
-- is implicit rather than explicit, so we have to zap a
-- mutable variable.
tcg_th_splice_used :: TcRef Bool,
-- ^ @True@ <=> A Template Haskell splice was used.
--
-- Splices disable recompilation avoidance (see #481)
tcg_dfun_n :: TcRef OccSet,
-- ^ Allows us to choose unique DFun names.
-- The next fields accumulate the payload of the module
-- The binds, rules and foreign-decl fields are collected
-- initially in un-zonked form and are finally zonked in tcRnSrcDecls
tcg_rn_exports :: Maybe [Located (IE Name)],
tcg_rn_imports :: [LImportDecl Name],
-- Keep the renamed imports regardless. They are not
-- voluminous and are needed if you want to report unused imports
tcg_rn_decls :: Maybe (HsGroup Name),
-- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
-- decls.
tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
#ifdef GHCI
tcg_th_topdecls :: TcRef [LHsDecl RdrName],
-- ^ Top-level declarations from addTopDecls
tcg_th_topnames :: TcRef NameSet,
-- ^ Exact names bound in top-level declarations in tcg_th_topdecls
tcg_th_modfinalizers :: TcRef [TH.Q ()],
-- ^ Template Haskell module finalizers
tcg_th_state :: TcRef (Map TypeRep Dynamic),
-- ^ Template Haskell state
#endif /* GHCI */
tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
-- Things defined in this module, or (in GHCi)
-- in the declarations for a single GHCi command.
-- For the latter, see Note [The interactive package] in HscTypes
tcg_binds :: LHsBinds Id, -- Value bindings in this module
tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
tcg_warns :: Warnings, -- ...Warnings and deprecations
tcg_anns :: [Annotation], -- ...Annotations
tcg_tcs :: [TyCon], -- ...TyCons and Classes
tcg_insts :: [ClsInst], -- ...Instances
tcg_fam_insts :: [FamInst], -- ...Family instances
tcg_rules :: [LRuleDecl Id], -- ...Rules
tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
-- prog uses hpc instrumentation.
tcg_main :: Maybe Name, -- ^ The Name of the main
-- function, if this module is
-- the main module.
tcg_safeInfer :: TcRef Bool, -- Has the typechecker
-- inferred this module
-- as -XSafe (Safe Haskell)
-- | A list of user-defined plugins for the constraint solver.
tcg_tc_plugins :: [TcPluginSolver],
tcg_static_wc :: TcRef WantedConstraints
-- ^ Wanted constraints of static forms.
}
-- Note [Signature parameters in TcGblEnv and DynFlags]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- When compiling signature files, we need to know which implementation
-- we've actually linked against the signature. There are three seemingly
-- redundant places where this information is stored: in DynFlags, there
-- is sigOf, and in TcGblEnv, there is tcg_sig_of and tcg_impl_rdr_env.
-- Here's the difference between each of them:
--
-- * DynFlags.sigOf is global per invocation of GHC. If we are compiling
-- with --make, there may be multiple signature files being compiled; in
-- which case this parameter is a map from local module name to implementing
-- Module.
--
-- * HscEnv.tcg_sig_of is global per the compilation of a single file, so
-- it is simply the result of looking up tcg_mod in the DynFlags.sigOf
-- parameter. It's setup in TcRnMonad.initTc. This prevents us
-- from having to repeatedly do a lookup in DynFlags.sigOf.
--
-- * HscEnv.tcg_impl_rdr_env is a RdrEnv that lets us look up names
-- according to the sig-of module. It's setup in TcRnDriver.tcRnSignature.
-- Here is an example showing why we need this map:
--
-- module A where
-- a = True
--
-- module ASig where
-- import B
-- a :: Bool
--
-- module B where
-- b = False
--
-- When we compile ASig --sig-of main:A, the default
-- global RdrEnv (tcg_rdr_env) has an entry for b, but not for a
-- (we never imported A). So we have to look in a different environment
-- to actually get the original name.
--
-- By the way, why do we need to do the lookup; can't we just use A:a
-- as the name directly? Well, if A is reexporting the entity from another
-- module, then the original name needs to be the real original name:
--
-- module C where
-- a = True
--
-- module A(a) where
-- import C
instance ContainsModule TcGblEnv where
extractModule env = tcg_mod env
data RecFieldEnv
= RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
-- to the fields for that constructor
NameSet -- Set of all fields declared *in this module*;
-- used to suppress name-shadowing complaints
-- when using record wild cards
-- E.g. let fld = e in C {..}
-- This is used when dealing with ".." notation in record
-- construction and pattern matching.
-- The FieldEnv deals *only* with constructors defined in *this*
-- module. For imported modules, we get the same info from the
-- TypeEnv
{-
Note [Tracking unused binding and imports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We gather two sorts of usage information
* tcg_dus (defs/uses)
Records *defined* Names (local, top-level)
and *used* Names (local or imported)
Used (a) to report "defined but not used"
(see RnNames.reportUnusedNames)
(b) to generate version-tracking usage info in interface
files (see MkIface.mkUsedNames)
This usage info is mainly gathered by the renamer's
gathering of free-variables
* tcg_used_rdrnames
Records used *imported* (not locally-defined) RdrNames
Used only to report unused import declarations
Notice that they are RdrNames, not Names, so we can
tell whether the reference was qualified or unqualified, which
is esssential in deciding whether a particular import decl
is unnecessary. This info isn't present in Names.
************************************************************************
* *
The local typechecker environment
* *
************************************************************************
Note [The Global-Env/Local-Env story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During type checking, we keep in the tcg_type_env
* All types and classes
* All Ids derived from types and classes (constructors, selectors)
At the end of type checking, we zonk the local bindings,
and as we do so we add to the tcg_type_env
* Locally defined top-level Ids
Why? Because they are now Ids not TcIds. This final GlobalEnv is
a) fed back (via the knot) to typechecking the
unfoldings of interface signatures
b) used in the ModDetails of this module
-}
data TcLclEnv -- Changes as we move inside an expression
-- Discarded after typecheck/rename; not passed on to desugarer
= TcLclEnv {
tcl_loc :: RealSrcSpan, -- Source span
tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
tcl_th_ctxt :: ThStage, -- Template Haskell context
tcl_th_bndrs :: ThBindEnv, -- Binding level of in-scope Names
-- defined in this module (not imported)
tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
tcl_rdr :: LocalRdrEnv, -- Local name envt
-- Maintained during renaming, of course, but also during
-- type checking, solely so that when renaming a Template-Haskell
-- splice we have the right environment for the renamer.
--
-- Does *not* include global name envt; may shadow it
-- Includes both ordinary variables and type variables;
-- they are kept distinct because tyvar have a different
-- occurrence contructor (Name.TvOcc)
-- We still need the unsullied global name env so that
-- we can look up record field names
tcl_env :: TcTypeEnv, -- The local type environment:
-- Ids and TyVars defined in this module
tcl_bndrs :: [TcIdBinder], -- Stack of locally-bound Ids, innermost on top
-- Used only for error reporting
tcl_tidy :: TidyEnv, -- Used for tidying types; contains all
-- in-scope type variables (but not term variables)
tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
-- Namely, the in-scope TyVars bound in tcl_env,
-- plus the tyvars mentioned in the types of Ids bound
-- in tcl_lenv.
-- Why mutable? see notes with tcGetGlobalTyVars
tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
tcl_errs :: TcRef Messages -- Place to accumulate errors
}
type TcTypeEnv = NameEnv TcTyThing
type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
-- Domain = all Ids bound in this module (ie not imported)
-- The TopLevelFlag tells if the binding is syntactically top level.
-- We need to know this, because the cross-stage persistence story allows
-- cross-stage at arbitrary types if the Id is bound at top level.
--
-- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
-- bound at top level! See Note [Template Haskell levels] in TcSplice
data TcIdBinder
= TcIdBndr
TcId
TopLevelFlag -- Tells whether the bindind is syntactically top-level
-- (The monomorphic Ids for a recursive group count
-- as not-top-level for this purpose.)
{- Note [Given Insts]
~~~~~~~~~~~~~~~~~~
Because of GADTs, we have to pass inwards the Insts provided by type signatures
and existential contexts. Consider
data T a where { T1 :: b -> b -> T [b] }
f :: Eq a => T a -> Bool
f (T1 x y) = [x]==[y]
The constructor T1 binds an existential variable 'b', and we need Eq [b].
Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
pass it inwards.
-}
-- | Type alias for 'IORef'; the convention is we'll use this for mutable
-- bits of data in 'TcGblEnv' which are updated during typechecking and
-- returned at the end.
type TcRef a = IORef a
-- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
type TcId = Id
type TcIdSet = IdSet
---------------------------
-- Template Haskell stages and levels
---------------------------
data ThStage -- See Note [Template Haskell state diagram] in TcSplice
= Splice -- Inside a top-level splice splice
-- This code will be run *at compile time*;
-- the result replaces the splice
-- Binding level = 0
Bool -- True if in a typed splice, False otherwise
| Comp -- Ordinary Haskell code
-- Binding level = 1
| Brack -- Inside brackets
ThStage -- Enclosing stage
PendingStuff
data PendingStuff
= RnPendingUntyped -- Renaming the inside of an *untyped* bracket
(TcRef [PendingRnSplice]) -- Pending splices in here
| RnPendingTyped -- Renaming the inside of a *typed* bracket
| TcPending -- Typechecking the inside of a typed bracket
(TcRef [PendingTcSplice]) -- Accumulate pending splices here
(TcRef WantedConstraints) -- and type constraints here
topStage, topAnnStage, topSpliceStage :: ThStage
topStage = Comp
topAnnStage = Splice False
topSpliceStage = Splice False
instance Outputable ThStage where
ppr (Splice _) = text "Splice"
ppr Comp = text "Comp"
ppr (Brack s _) = text "Brack" <> parens (ppr s)
type ThLevel = Int
-- NB: see Note [Template Haskell levels] in TcSplice
-- Incremented when going inside a bracket,
-- decremented when going inside a splice
-- NB: ThLevel is one greater than the 'n' in Fig 2 of the
-- original "Template meta-programming for Haskell" paper
impLevel, outerLevel :: ThLevel
impLevel = 0 -- Imported things; they can be used inside a top level splice
outerLevel = 1 -- Things defined outside brackets
thLevel :: ThStage -> ThLevel
thLevel (Splice _) = 0
thLevel Comp = 1
thLevel (Brack s _) = thLevel s + 1
---------------------------
-- Arrow-notation context
---------------------------
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In arrow notation, a variable bound by a proc (or enclosed let/kappa)
is not in scope to the left of an arrow tail (-<) or the head of (|..|).
For example
proc x -> (e1 -< e2)
Here, x is not in scope in e1, but it is in scope in e2. This can get
a bit complicated:
let x = 3 in
proc y -> (proc z -> e1) -< e2
Here, x and z are in scope in e1, but y is not.
We implement this by
recording the environment when passing a proc (using newArrowScope),
and returning to that (using escapeArrowScope) on the left of -< and the
head of (|..|).
All this can be dealt with by the *renamer*. But the type checker needs
to be involved too. Example (arrowfail001)
class Foo a where foo :: a -> ()
data Bar = forall a. Foo a => Bar a
get :: Bar -> ()
get = proc x -> case x of Bar a -> foo -< a
Here the call of 'foo' gives rise to a (Foo a) constraint that should not
be captured by the pattern match on 'Bar'. Rather it should join the
constraints from further out. So we must capture the constraint bag
from further out in the ArrowCtxt that we push inwards.
-}
data ArrowCtxt -- Note [Escaping the arrow scope]
= NoArrowCtxt
| ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
---------------------------
-- TcTyThing
---------------------------
data TcTyThing
= AGlobal TyThing -- Used only in the return type of a lookup
| ATcId { -- Ids defined in this module; may not be fully zonked
tct_id :: TcId,
tct_closed :: TopLevelFlag } -- See Note [Bindings with closed types]
| ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
-- variable is bound. We only need the Name
-- for error-message purposes; it is the corresponding
-- Name in the domain of the envt
| AThing TcKind -- Used temporarily, during kind checking, for the
-- tycons and clases in this recursive group
-- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
-- Note [Type checking recursive type and class declarations]
| APromotionErr PromotionErr
data PromotionErr
= TyConPE -- TyCon used in a kind before we are ready
-- data T :: T -> * where ...
| ClassPE -- Ditto Class
| FamDataConPE -- Data constructor for a data family
-- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
| RecDataConPE -- Data constructor in a recursive loop
-- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
| NoDataKinds -- -XDataKinds not enabled
instance Outputable TcTyThing where -- Debugging only
ppr (AGlobal g) = pprTyThing g
ppr elt@(ATcId {}) = text "Identifier" <>
brackets (ppr (tct_id elt) <> dcolon
<> ppr (varType (tct_id elt)) <> comma
<+> ppr (tct_closed elt))
ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
ppr (AThing k) = text "AThing" <+> ppr k
ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
instance Outputable PromotionErr where
ppr ClassPE = text "ClassPE"
ppr TyConPE = text "TyConPE"
ppr FamDataConPE = text "FamDataConPE"
ppr RecDataConPE = text "RecDataConPE"
ppr NoDataKinds = text "NoDataKinds"
pprTcTyThingCategory :: TcTyThing -> SDoc
pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
pprPECategory :: PromotionErr -> SDoc
pprPECategory ClassPE = ptext (sLit "Class")
pprPECategory TyConPE = ptext (sLit "Type constructor")
pprPECategory FamDataConPE = ptext (sLit "Data constructor")
pprPECategory RecDataConPE = ptext (sLit "Data constructor")
pprPECategory NoDataKinds = ptext (sLit "Data constructor")
{-
Note [Bindings with closed types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f x = let g ys = map not ys
in ...
Can we generalise 'g' under the OutsideIn algorithm? Yes,
because all g's free variables are top-level; that is they themselves
have no free type variables, and it is the type variables in the
environment that makes things tricky for OutsideIn generalisation.
Definition:
A variable is "closed", and has tct_closed set to TopLevel,
iff
a) all its free variables are imported, or are themselves closed
b) generalisation is not restricted by the monomorphism restriction
Under OutsideIn we are free to generalise a closed let-binding.
This is an extension compared to the JFP paper on OutsideIn, which
used "top-level" as a proxy for "closed". (It's not a good proxy
anyway -- the MR can make a top-level binding with a free type
variable.)
Note that:
* A top-level binding may not be closed, if it suffer from the MR
* A nested binding may be closed (eg 'g' in the example we started with)
Indeed, that's the point; whether a function is defined at top level
or nested is orthogonal to the question of whether or not it is closed
* A binding may be non-closed because it mentions a lexically scoped
*type variable* Eg
f :: forall a. blah
f x = let g y = ...(y::a)...
-}
type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
-- Monadic so that we have a chance
-- to deal with bound type variables just before error
-- message construction
-- Bool: True <=> this is a landmark context; do not
-- discard it when trimming for display
{-
************************************************************************
* *
Operations over ImportAvails
* *
************************************************************************
-}
-- | 'ImportAvails' summarises what was imported from where, irrespective of
-- whether the imported things are actually used or not. It is used:
--
-- * when processing the export list,
--
-- * when constructing usage info for the interface file,
--
-- * to identify the list of directly imported modules for initialisation
-- purposes and for optimised overlap checking of family instances,
--
-- * when figuring out what things are really unused
--
data ImportAvails
= ImportAvails {
imp_mods :: ImportedMods,
-- = ModuleEnv [(ModuleName, Bool, SrcSpan, Bool)],
-- ^ Domain is all directly-imported modules
-- The 'ModuleName' is what the module was imported as, e.g. in
-- @
-- import Foo as Bar
-- @
-- it is @Bar@.
--
-- The 'Bool' means:
--
-- - @True@ => import was @import Foo ()@
--
-- - @False@ => import was some other form
--
-- Used
--
-- (a) to help construct the usage information in the interface
-- file; if we import something we need to recompile if the
-- export version changes
--
-- (b) to specify what child modules to initialise
--
-- We need a full ModuleEnv rather than a ModuleNameEnv here,
-- because we might be importing modules of the same name from
-- different packages. (currently not the case, but might be in the
-- future).
imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
-- ^ Home-package modules needed by the module being compiled
--
-- It doesn't matter whether any of these dependencies
-- are actually /used/ when compiling the module; they
-- are listed if they are below it at all. For
-- example, suppose M imports A which imports X. Then
-- compiling M might not need to consult X.hi, but X
-- is still listed in M's dependencies.
imp_dep_pkgs :: [InstalledUnitId],
-- ^ Packages needed by the module being compiled, whether directly,
-- or via other modules in this package, or via modules imported
-- from other packages.
imp_trust_pkgs :: [InstalledUnitId],
-- ^ This is strictly a subset of imp_dep_pkgs and records the
-- packages the current module needs to trust for Safe Haskell
-- compilation to succeed. A package is required to be trusted if
-- we are dependent on a trustworthy module in that package.
-- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
-- where True for the bool indicates the package is required to be
-- trusted is the more logical design, doing so complicates a lot
-- of code not concerned with Safe Haskell.
-- See Note [RnNames . Tracking Trust Transitively]
imp_trust_own_pkg :: Bool,
-- ^ Do we require that our own package is trusted?
-- This is to handle efficiently the case where a Safe module imports
-- a Trustworthy module that resides in the same package as it.
-- See Note [RnNames . Trust Own Package]
imp_orphs :: [Module],
-- ^ Orphan modules below us in the import tree (and maybe including
-- us for imported modules)
imp_finsts :: [Module]
-- ^ Family instance modules below us in the import tree (and maybe
-- including us for imported modules)
}
mkModDeps :: [(ModuleName, IsBootInterface)]
-> ModuleNameEnv (ModuleName, IsBootInterface)
mkModDeps deps = foldl add emptyUFM deps
where
add env elt@(m,_) = addToUFM env m elt
emptyImportAvails :: ImportAvails
emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
imp_dep_mods = emptyUFM,
imp_dep_pkgs = [],
imp_trust_pkgs = [],
imp_trust_own_pkg = False,
imp_orphs = [],
imp_finsts = [] }
-- | Union two ImportAvails
--
-- This function is a key part of Import handling, basically
-- for each import we create a separate ImportAvails structure
-- and then union them all together with this function.
plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
plusImportAvails
(ImportAvails { imp_mods = mods1,
imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
imp_orphs = orphs1, imp_finsts = finsts1 })
(ImportAvails { imp_mods = mods2,
imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
imp_orphs = orphs2, imp_finsts = finsts2 })
= ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
imp_trust_pkgs = tpkgs1 `unionLists` tpkgs2,
imp_trust_own_pkg = tself1 || tself2,
imp_orphs = orphs1 `unionLists` orphs2,
imp_finsts = finsts1 `unionLists` finsts2 }
where
plus_mod_dep (m1, boot1) (_, boot2)
= --WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
-- Check mod-names match
(m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
{-
************************************************************************
* *
\subsection{Where from}
* *
************************************************************************
The @WhereFrom@ type controls where the renamer looks for an interface file
-}
data WhereFrom
= ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
| ImportBySystem -- Non user import.
| ImportByPlugin -- Importing a plugin;
-- See Note [Care with plugin imports] in LoadIface
instance Outputable WhereFrom where
ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
| otherwise = empty
ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
ppr ImportByPlugin = ptext (sLit "{- PLUGIN -}")
{-
************************************************************************
* *
* Canonical constraints *
* *
* These are the constraints the low-level simplifier works with *
* *
************************************************************************
-}
-- The syntax of xi types:
-- xi ::= a | T xis | xis -> xis | ... | forall a. tau
-- Two important notes:
-- (i) No type families, unless we are under a ForAll
-- (ii) Note that xi types can contain unexpanded type synonyms;
-- however, the (transitive) expansions of those type synonyms
-- will not contain any type functions, unless we are under a ForAll.
-- We enforce the structure of Xi types when we flatten (TcCanonical)
type Xi = Type -- In many comments, "xi" ranges over Xi
type Cts = Bag Ct
data Ct
-- Atomic canonical constraints
= CDictCan { -- e.g. Num xi
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_class :: Class,
cc_tyargs :: [Xi] -- cc_tyargs are function-free, hence Xi
}
| CIrredEvCan { -- These stand for yet-unusable predicates
cc_ev :: CtEvidence -- See Note [Ct/evidence invariant]
-- The ctev_pred of the evidence is
-- of form (tv xi1 xi2 ... xin)
-- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
-- or (F tys ~ ty) where the CFunEqCan kind invariant fails
-- See Note [CIrredEvCan constraints]
}
| CTyEqCan { -- tv ~ rhs
-- Invariants:
-- * See Note [Applying the inert substitution] in TcFlatten
-- * tv not in tvs(rhs) (occurs check)
-- * If tv is a TauTv, then rhs has no foralls
-- (this avoids substituting a forall for the tyvar in other types)
-- * typeKind ty `subKind` typeKind tv
-- See Note [Kind orientation for CTyEqCan]
-- * rhs is not necessarily function-free,
-- but it has no top-level function.
-- E.g. a ~ [F b] is fine
-- but a ~ F b is not
-- * If the equality is representational, rhs has no top-level newtype
-- See Note [No top-level newtypes on RHS of representational
-- equalities] in TcCanonical
-- * If rhs is also a tv, then it is oriented to give best chance of
-- unification happening; eg if rhs is touchable then lhs is too
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_tyvar :: TcTyVar,
cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
-- See invariants above
cc_eq_rel :: EqRel
}
| CFunEqCan { -- F xis ~ fsk
-- Invariants:
-- * isTypeFamilyTyCon cc_fun
-- * typeKind (F xis) = tyVarKind fsk
-- * always Nominal role
-- * always Given or Wanted, never Derived
cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
cc_fun :: TyCon, -- A type function
cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
-- Either under-saturated or exactly saturated
-- *never* over-saturated (because if so
-- we should have decomposed)
cc_fsk :: TcTyVar -- [Given] always a FlatSkol skolem
-- [Wanted] always a FlatMetaTv unification variable
-- See Note [The flattening story] in TcFlatten
}
| CNonCanonical { -- See Note [NonCanonical Semantics]
cc_ev :: CtEvidence
}
| CHoleCan { -- Treated as an "insoluble" constraint
-- See Note [Insoluble constraints]
cc_ev :: CtEvidence,
cc_occ :: OccName, -- The name of this hole
cc_hole :: HoleSort -- The sort of this hole (expr, type, ...)
}
-- | Used to indicate which sort of hole we have.
data HoleSort = ExprHole -- ^ A hole in an expression (TypedHoles)
| TypeHole -- ^ A hole in a type (PartialTypeSignatures)
{-
Note [Kind orientation for CTyEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Given an equality (t:* ~ s:Open), we can't solve it by updating t:=s,
ragardless of how touchable 't' is, because the kinds don't work.
Instead we absolutely must re-orient it. Reason: if that gets into the
inert set we'll start replacing t's by s's, and that might make a
kind-correct type into a kind error. After re-orienting,
we may be able to solve by updating s:=t.
Hence in a CTyEqCan, (t:k1 ~ xi:k2) we require that k2 is a subkind of k1.
If the two have incompatible kinds, we just don't use a CTyEqCan at all.
See Note [Equalities with incompatible kinds] in TcCanonical
We can't require *equal* kinds, because
* wanted constraints don't necessarily have identical kinds
eg alpha::? ~ Int
* a solved wanted constraint becomes a given
Note [Kind orientation for CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For (F xis ~ rhs) we require that kind(lhs) is a subkind of kind(rhs).
This really only maters when rhs is an Open type variable (since only type
variables have Open kinds):
F ty ~ (a:Open)
which can happen, say, from
f :: F a b
f = undefined -- The a:Open comes from instantiating 'undefined'
Note that the kind invariant is maintained by rewriting.
Eg wanted1 rewrites wanted2; if both were compatible kinds before,
wanted2 will be afterwards. Similarly givens.
Caveat:
- Givens from higher-rank, such as:
type family T b :: * -> * -> *
type instance T Bool = (->)
f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
flop = f (...) True
Whereas we would be able to apply the type instance, we would not be able to
use the given (T Bool ~ (->)) in the body of 'flop'
Note [CIrredEvCan constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CIrredEvCan constraints are used for constraints that are "stuck"
- we can't solve them (yet)
- we can't use them to solve other constraints
- but they may become soluble if we substitute for some
of the type variables in the constraint
Example 1: (c Int), where c :: * -> Constraint. We can't do anything
with this yet, but if later c := Num, *then* we can solve it
Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
We don't want to use this to substitute 'b' for 'a', in case
'k' is subequently unifed with (say) *->*, because then
we'd have ill-kinded types floating about. Rather we want
to defer using the equality altogether until 'k' get resolved.
Note [Ct/evidence invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
This holds by construction; look at the unique place where CDictCan is
built (in TcCanonical).
In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
the evidence may *not* be fully zonked; we are careful not to look at it
during constraint solving. See Note [Evidence field of CtEvidence]
-}
mkNonCanonical :: CtEvidence -> Ct
mkNonCanonical ev = CNonCanonical { cc_ev = ev }
mkNonCanonicalCt :: Ct -> Ct
mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
ctEvidence :: Ct -> CtEvidence
ctEvidence = cc_ev
ctLoc :: Ct -> CtLoc
ctLoc = ctEvLoc . ctEvidence
ctPred :: Ct -> PredType
-- See Note [Ct/evidence invariant]
ctPred ct = ctEvPred (cc_ev ct)
-- | Get the flavour of the given 'Ct'
ctFlavour :: Ct -> CtFlavour
ctFlavour = ctEvFlavour . ctEvidence
-- | Get the equality relation for the given 'Ct'
ctEqRel :: Ct -> EqRel
ctEqRel = ctEvEqRel . ctEvidence
dropDerivedWC :: WantedConstraints -> WantedConstraints
-- See Note [Dropping derived constraints]
dropDerivedWC wc@(WC { wc_simple = simples })
= wc { wc_simple = filterBag isWantedCt simples }
-- The wc_impl implications are already (recursively) filtered
{-
Note [Dropping derived constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In general we discard derived constraints at the end of constraint solving;
see dropDerivedWC. For example
* If we have an unsolved (Ord a), we don't want to complain about
an unsolved (Eq a) as well.
But we keep Derived *insoluble* constraints because they indicate a solid,
comprehensible error. Particularly:
* Insolubles Givens indicate unreachable code
* Insoluble kind equalities (e.g. [D] * ~ (* -> *)) may arise from
a type equality a ~ Int#, say
* Insoluble derived wanted equalities (e.g. [D] Int ~ Bool) may
arise from functional dependency interactions. We are careful
to keep a good CtOrigin on such constraints (FunDepOrigin1, FunDepOrigin2)
so that we can produce a good error message (Trac #9612)
Since we leave these Derived constraints in the residual WantedConstraints,
we must filter them out when we re-process the WantedConstraint,
in TcSimplify.solve_wanteds.
************************************************************************
* *
CtEvidence
The "flavor" of a canonical constraint
* *
************************************************************************
-}
isWantedCt :: Ct -> Bool
isWantedCt = isWanted . cc_ev
isGivenCt :: Ct -> Bool
isGivenCt = isGiven . cc_ev
isDerivedCt :: Ct -> Bool
isDerivedCt = isDerived . cc_ev
isCTyEqCan :: Ct -> Bool
isCTyEqCan (CTyEqCan {}) = True
isCTyEqCan (CFunEqCan {}) = False
isCTyEqCan _ = False
isCDictCan_Maybe :: Ct -> Maybe Class
isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
isCDictCan_Maybe _ = Nothing
isCIrredEvCan :: Ct -> Bool
isCIrredEvCan (CIrredEvCan {}) = True
isCIrredEvCan _ = False
isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
isCFunEqCan_maybe _ = Nothing
isCFunEqCan :: Ct -> Bool
isCFunEqCan (CFunEqCan {}) = True
isCFunEqCan _ = False
isCNonCanonical :: Ct -> Bool
isCNonCanonical (CNonCanonical {}) = True
isCNonCanonical _ = False
isHoleCt:: Ct -> Bool
isHoleCt (CHoleCan {}) = True
isHoleCt _ = False
isTypedHoleCt :: Ct -> Bool
isTypedHoleCt (CHoleCan { cc_hole = ExprHole }) = True
isTypedHoleCt _ = False
isPartialTypeSigCt :: Ct -> Bool
isPartialTypeSigCt (CHoleCan { cc_hole = TypeHole }) = True
isPartialTypeSigCt _ = False
instance Outputable Ct where
ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
where ct_sort = case ct of
CTyEqCan {} -> "CTyEqCan"
CFunEqCan {} -> "CFunEqCan"
CNonCanonical {} -> "CNonCanonical"
CDictCan {} -> "CDictCan"
CIrredEvCan {} -> "CIrredEvCan"
CHoleCan {} -> "CHoleCan"
singleCt :: Ct -> Cts
singleCt = unitBag
andCts :: Cts -> Cts -> Cts
andCts = unionBags
listToCts :: [Ct] -> Cts
listToCts = listToBag
ctsElts :: Cts -> [Ct]
ctsElts = bagToList
consCts :: Ct -> Cts -> Cts
consCts = consBag
snocCts :: Cts -> Ct -> Cts
snocCts = snocBag
extendCtsList :: Cts -> [Ct] -> Cts
extendCtsList cts xs | null xs = cts
| otherwise = cts `unionBags` listToBag xs
andManyCts :: [Cts] -> Cts
andManyCts = unionManyBags
emptyCts :: Cts
emptyCts = emptyBag
isEmptyCts :: Cts -> Bool
isEmptyCts = isEmptyBag
pprCts :: Cts -> SDoc
pprCts cts = vcat (map ppr (bagToList cts))
{-
************************************************************************
* *
Wanted constraints
These are forced to be in TcRnTypes because
TcLclEnv mentions WantedConstraints
WantedConstraint mentions CtLoc
CtLoc mentions ErrCtxt
ErrCtxt mentions TcM
* *
v%************************************************************************
-}
data WantedConstraints
= WC { wc_simple :: Cts -- Unsolved constraints, all wanted
, wc_impl :: Bag Implication
, wc_insol :: Cts -- Insoluble constraints, can be
-- wanted, given, or derived
-- See Note [Insoluble constraints]
}
emptyWC :: WantedConstraints
emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
mkSimpleWC :: [Ct] -> WantedConstraints
mkSimpleWC cts
= WC { wc_simple = listToBag cts, wc_impl = emptyBag, wc_insol = emptyBag }
isEmptyWC :: WantedConstraints -> Bool
isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_insol = n })
= isEmptyBag f && isEmptyBag i && isEmptyBag n
insolubleWC :: WantedConstraints -> Bool
-- True if there are any insoluble constraints in the wanted bag. Ignore
-- constraints arising from PartialTypeSignatures to solve as much of the
-- constraints as possible before reporting the holes.
insolubleWC wc = not (isEmptyBag (filterBag (not . isPartialTypeSigCt)
(wc_insol wc)))
|| anyBag ic_insol (wc_impl wc)
andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
andWC (WC { wc_simple = f1, wc_impl = i1, wc_insol = n1 })
(WC { wc_simple = f2, wc_impl = i2, wc_insol = n2 })
= WC { wc_simple = f1 `unionBags` f2
, wc_impl = i1 `unionBags` i2
, wc_insol = n1 `unionBags` n2 }
unionsWC :: [WantedConstraints] -> WantedConstraints
unionsWC = foldr andWC emptyWC
addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
addSimples wc cts
= wc { wc_simple = wc_simple wc `unionBags` cts }
addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
addInsols wc cts
= wc { wc_insol = wc_insol wc `unionBags` cts }
instance Outputable WantedConstraints where
ppr (WC {wc_simple = s, wc_impl = i, wc_insol = n})
= ptext (sLit "WC") <+> braces (vcat
[ ppr_bag (ptext (sLit "wc_simple")) s
, ppr_bag (ptext (sLit "wc_insol")) n
, ppr_bag (ptext (sLit "wc_impl")) i ])
ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
ppr_bag doc bag
| isEmptyBag bag = empty
| otherwise = hang (doc <+> equals)
2 (foldrBag (($$) . ppr) empty bag)
{-
************************************************************************
* *
Implication constraints
* *
************************************************************************
-}
data Implication
= Implic {
ic_tclvl :: TcLevel, -- TcLevel: unification variables
-- free in the environment
ic_skols :: [TcTyVar], -- Introduced skolems
ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
-- See Note [Shadowing in a constraint]
ic_given :: [EvVar], -- Given evidence variables
-- (order does not matter)
-- See Invariant (GivenInv) in TcType
ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
-- False <=> ic_givens might have equalities
ic_env :: TcLclEnv, -- Gives the source location and error context
-- for the implicatdion, and hence for all the
-- given evidence variables
ic_wanted :: WantedConstraints, -- The wanted
ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
ic_binds :: EvBindsVar -- Points to the place to fill in the
-- abstraction and bindings
}
instance Outputable Implication where
ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
, ic_given = given, ic_no_eqs = no_eqs
, ic_wanted = wanted, ic_insol = insol
, ic_binds = binds, ic_info = info })
= hang (ptext (sLit "Implic") <+> lbrace)
2 (sep [ ptext (sLit "TcLevel =") <+> ppr tclvl
, ptext (sLit "Skolems =") <+> pprTvBndrs skols
, ptext (sLit "No-eqs =") <+> ppr no_eqs
, ptext (sLit "Insol =") <+> ppr insol
, hang (ptext (sLit "Given =")) 2 (pprEvVars given)
, hang (ptext (sLit "Wanted =")) 2 (ppr wanted)
, ptext (sLit "Binds =") <+> ppr binds
, pprSkolInfo info ] <+> rbrace)
{-
Note [Shadowing in a constraint]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We assume NO SHADOWING in a constraint. Specifically
* The unification variables are all implicitly quantified at top
level, and are all unique
* The skolem varibles bound in ic_skols are all freah when the
implication is created.
So we can safely substitute. For example, if we have
forall a. a~Int => ...(forall b. ...a...)...
we can push the (a~Int) constraint inwards in the "givens" without
worrying that 'b' might clash.
Note [Skolems in an implication]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The skolems in an implication are not there to perform a skolem escape
check. That happens because all the environment variables are in the
untouchables, and therefore cannot be unified with anything at all,
let alone the skolems.
Instead, ic_skols is used only when considering floating a constraint
outside the implication in TcSimplify.floatEqualities or
TcSimplify.approximateImplications
Note [Insoluble constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some of the errors that we get during canonicalization are best
reported when all constraints have been simplified as much as
possible. For instance, assume that during simplification the
following constraints arise:
[Wanted] F alpha ~ uf1
[Wanted] beta ~ uf1 beta
When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
we will simply see a message:
'Can't construct the infinite type beta ~ uf1 beta'
and the user has no idea what the uf1 variable is.
Instead our plan is that we will NOT fail immediately, but:
(1) Record the "frozen" error in the ic_insols field
(2) Isolate the offending constraint from the rest of the inerts
(3) Keep on simplifying/canonicalizing
At the end, we will hopefully have substituted uf1 := F alpha, and we
will be able to report a more informative error:
'Can't construct the infinite type beta ~ F alpha beta'
Insoluble constraints *do* include Derived constraints. For example,
a functional dependency might give rise to [D] Int ~ Bool, and we must
report that. If insolubles did not contain Deriveds, reportErrors would
never see it.
************************************************************************
* *
Pretty printing
* *
************************************************************************
-}
pprEvVars :: [EvVar] -> SDoc -- Print with their types
pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
pprEvVarTheta :: [EvVar] -> SDoc
pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
pprEvVarWithType :: EvVar -> SDoc
pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
{-
************************************************************************
* *
CtEvidence
* *
************************************************************************
Note [Evidence field of CtEvidence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
During constraint solving we never look at the type of ctev_evtm, or
ctev_evar; instead we look at the cte_pred field. The evtm/evar field
may be un-zonked.
-}
data CtEvidence
= CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
, ctev_evtm :: EvTerm -- See Note [Evidence field of CtEvidence]
, ctev_loc :: CtLoc }
-- Truly given, not depending on subgoals
-- NB: Spontaneous unifications belong here
| CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
, ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
, ctev_loc :: CtLoc }
-- Wanted goal
| CtDerived { ctev_pred :: TcPredType
, ctev_loc :: CtLoc }
-- A goal that we don't really have to solve and can't immediately
-- rewrite anything other than a derived (there's no evidence!)
-- but if we do manage to solve it may help in solving other goals.
ctEvPred :: CtEvidence -> TcPredType
-- The predicate of a flavor
ctEvPred = ctev_pred
ctEvLoc :: CtEvidence -> CtLoc
ctEvLoc = ctev_loc
-- | Get the equality relation relevant for a 'CtEvidence'
ctEvEqRel :: CtEvidence -> EqRel
ctEvEqRel = predTypeEqRel . ctEvPred
-- | Get the role relevant for a 'CtEvidence'
ctEvRole :: CtEvidence -> Role
ctEvRole = eqRelRole . ctEvEqRel
ctEvTerm :: CtEvidence -> EvTerm
ctEvTerm (CtGiven { ctev_evtm = tm }) = tm
ctEvTerm (CtWanted { ctev_evar = ev }) = EvId ev
ctEvTerm ctev@(CtDerived {}) = pprPanic "ctEvTerm: derived constraint cannot have id"
(ppr ctev)
ctEvCoercion :: CtEvidence -> TcCoercion
-- ctEvCoercion ev = evTermCoercion (ctEvTerm ev)
ctEvCoercion (CtGiven { ctev_evtm = tm }) = evTermCoercion tm
ctEvCoercion (CtWanted { ctev_evar = v }) = mkTcCoVarCo v
ctEvCoercion ctev@(CtDerived {}) = pprPanic "ctEvCoercion: derived constraint cannot have id"
(ppr ctev)
ctEvId :: CtEvidence -> TcId
ctEvId (CtWanted { ctev_evar = ev }) = ev
ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
instance Outputable CtEvidence where
ppr fl = case fl of
CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evtm fl) <+> ppr_pty
CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
where ppr_pty = dcolon <+> ppr (ctEvPred fl)
isWanted :: CtEvidence -> Bool
isWanted (CtWanted {}) = True
isWanted _ = False
isGiven :: CtEvidence -> Bool
isGiven (CtGiven {}) = True
isGiven _ = False
isDerived :: CtEvidence -> Bool
isDerived (CtDerived {}) = True
isDerived _ = False
{-
%************************************************************************
%* *
CtFlavour
%* *
%************************************************************************
Just an enum type that tracks whether a constraint is wanted, derived,
or given, when we need to separate that info from the constraint itself.
-}
data CtFlavour = Given | Wanted | Derived
deriving Eq
instance Outputable CtFlavour where
ppr Given = text "[G]"
ppr Wanted = text "[W]"
ppr Derived = text "[D]"
ctEvFlavour :: CtEvidence -> CtFlavour
ctEvFlavour (CtWanted {}) = Wanted
ctEvFlavour (CtGiven {}) = Given
ctEvFlavour (CtDerived {}) = Derived
{-
************************************************************************
* *
SubGoalDepth
* *
************************************************************************
Note [SubGoalDepth]
~~~~~~~~~~~~~~~~~~~
The 'SubGoalCounter' takes care of stopping the constraint solver from looping.
Because of the different use-cases of regular constaints and type function
applications, there are two independent counters. Therefore, this datatype is
abstract. See Note [WorkList]
Each counter starts at zero and increases.
* The "dictionary constraint counter" counts the depth of type class
instance declarations. Example:
[W] d{7} : Eq [Int]
That is d's dictionary-constraint depth is 7. If we use the instance
$dfEqList :: Eq a => Eq [a]
to simplify it, we get
d{7} = $dfEqList d'{8}
where d'{8} : Eq Int, and d' has dictionary-constraint depth 8.
For civilised (decidable) instance declarations, each increase of
depth removes a type constructor from the type, so the depth never
gets big; i.e. is bounded by the structural depth of the type.
The flag -fcontext-stack=n (not very well named!) fixes the maximium
level.
* The "type function reduction counter" does the same thing when resolving
* qualities involving type functions. Example:
Assume we have a wanted at depth 7:
[W] d{7} : F () ~ a
If thre is an type function equation "F () = Int", this would be rewritten to
[W] d{8} : Int ~ a
and remembered as having depth 8.
Again, without UndecidableInstances, this counter is bounded, but without it
can resolve things ad infinitum. Hence there is a maximum level. But we use a
different maximum, as we expect possibly many more type function reductions
in sensible programs than type class constraints.
The flag -ftype-function-depth=n fixes the maximium level.
-}
data SubGoalCounter = CountConstraints | CountTyFunApps
data SubGoalDepth -- See Note [SubGoalDepth]
= SubGoalDepth
{-# UNPACK #-} !Int -- Dictionary constraints
{-# UNPACK #-} !Int -- Type function reductions
deriving (Eq, Ord)
instance Outputable SubGoalDepth where
ppr (SubGoalDepth c f) = angleBrackets $
char 'C' <> colon <> int c <> comma <>
char 'F' <> colon <> int f
initialSubGoalDepth :: SubGoalDepth
initialSubGoalDepth = SubGoalDepth 0 0
maxSubGoalDepth :: DynFlags -> SubGoalDepth
maxSubGoalDepth dflags = SubGoalDepth (ctxtStkDepth dflags) (tyFunStkDepth dflags)
bumpSubGoalDepth :: SubGoalCounter -> SubGoalDepth -> SubGoalDepth
bumpSubGoalDepth CountConstraints (SubGoalDepth c f) = SubGoalDepth (c+1) f
bumpSubGoalDepth CountTyFunApps (SubGoalDepth c f) = SubGoalDepth c (f+1)
subGoalCounterValue :: SubGoalCounter -> SubGoalDepth -> Int
subGoalCounterValue CountConstraints (SubGoalDepth c _) = c
subGoalCounterValue CountTyFunApps (SubGoalDepth _ f) = f
subGoalDepthExceeded :: SubGoalDepth -> SubGoalDepth -> Maybe SubGoalCounter
subGoalDepthExceeded (SubGoalDepth mc mf) (SubGoalDepth c f)
| c > mc = Just CountConstraints
| f > mf = Just CountTyFunApps
| otherwise = Nothing
-- | Checks whether the evidence can be used to solve a goal with the given minimum depth
-- See Note [Preventing recursive dictionaries]
ctEvCheckDepth :: Class -> CtLoc -> CtEvidence -> Bool
ctEvCheckDepth cls target ev
| isWanted ev
, cls == coercibleClass -- The restriction applies only to Coercible
= ctLocDepth target <= ctLocDepth (ctEvLoc ev)
| otherwise = True
{-
Note [Preventing recursive dictionaries]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NB: this will go away when we start treating Coercible as an equality.
We have some classes where it is not very useful to build recursive
dictionaries (Coercible, at the moment). So we need the constraint solver to
prevent that. We conservatively ensure this property using the subgoal depth of
the constraints: When solving a Coercible constraint at depth d, we do not
consider evidence from a depth <= d as suitable.
Therefore we need to record the minimum depth allowed to solve a CtWanted. This
is done in the SubGoalDepth field of CtWanted. Most code now uses mkCtWanted,
which initializes it to initialSubGoalDepth (i.e. 0); but when requesting a
Coercible instance (requestCoercible in TcInteract), we bump the current depth
by one and use that.
There are two spots where wanted contraints attempted to be solved
using existing constraints: lookupInertDict and lookupSolvedDict in
TcSMonad. Both use ctEvCheckDepth to make the check. That function
ensures that a Given constraint can always be used to solve a goal
(i.e. they are at depth infinity, for our purposes)
************************************************************************
* *
CtLoc
* *
************************************************************************
The 'CtLoc' gives information about where a constraint came from.
This is important for decent error message reporting because
dictionaries don't appear in the original source code.
type will evolve...
-}
data CtLoc = CtLoc { ctl_origin :: CtOrigin
, ctl_env :: TcLclEnv
, ctl_depth :: !SubGoalDepth }
-- The TcLclEnv includes particularly
-- source location: tcl_loc :: RealSrcSpan
-- context: tcl_ctxt :: [ErrCtxt]
-- binder stack: tcl_bndrs :: [TcIdBinders]
-- level: tcl_tclvl :: TcLevel
mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
mkGivenLoc tclvl skol_info env
= CtLoc { ctl_origin = GivenOrigin skol_info
, ctl_env = env { tcl_tclvl = tclvl }
, ctl_depth = initialSubGoalDepth }
ctLocEnv :: CtLoc -> TcLclEnv
ctLocEnv = ctl_env
ctLocDepth :: CtLoc -> SubGoalDepth
ctLocDepth = ctl_depth
ctLocOrigin :: CtLoc -> CtOrigin
ctLocOrigin = ctl_origin
ctLocSpan :: CtLoc -> RealSrcSpan
ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
bumpCtLocDepth :: SubGoalCounter -> CtLoc -> CtLoc
bumpCtLocDepth cnt loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth cnt d }
setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
setCtLocEnv ctl env = ctl { ctl_env = env }
pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
= loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
-- Just add information w/o updating the origin!
pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
= loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
pprArising :: CtOrigin -> SDoc
-- Used for the main, top-level error message
-- We've done special processing for TypeEq and FunDep origins
pprArising (TypeEqOrigin {}) = empty
pprArising orig = pprCtOrigin orig
pprArisingAt :: CtLoc -> SDoc
pprArisingAt (CtLoc { ctl_origin = o, ctl_env = lcl})
= sep [ pprCtOrigin o
, text "at" <+> ppr (tcl_loc lcl)]
{-
************************************************************************
* *
SkolemInfo
* *
************************************************************************
-}
-- SkolemInfo gives the origin of *given* constraints
-- a) type variables are skolemised
-- b) an implication constraint is generated
data SkolemInfo
= SigSkol UserTypeCtxt -- A skolem that is created by instantiating
Type -- a programmer-supplied type signature
-- Location of the binding site is on the TyVar
-- The rest are for non-scoped skolems
| ClsSkol Class -- Bound at a class decl
| InstSkol -- Bound at an instance decl
| DataSkol -- Bound at a data type declaration
| FamInstSkol -- Bound at a family instance decl
| PatSkol -- An existential type variable bound by a pattern for
ConLike -- a data constructor with an existential type.
(HsMatchContext Name)
-- e.g. data T = forall a. Eq a => MkT a
-- f (MkT x) = ...
-- The pattern MkT x will allocate an existential type
-- variable for 'a'.
| ArrowSkol -- An arrow form (see TcArrows)
| IPSkol [HsIPName] -- Binding site of an implicit parameter
| RuleSkol RuleName -- The LHS of a RULE
| InferSkol [(Name,TcType)]
-- We have inferred a type for these (mutually-recursivive)
-- polymorphic Ids, and are now checking that their RHS
-- constraints are satisfied.
| BracketSkol -- Template Haskell bracket
| UnifyForAllSkol -- We are unifying two for-all types
[TcTyVar] -- The instantiated skolem variables
TcType -- The instantiated type *inside* the forall
| UnkSkol -- Unhelpful info (until I improve it)
instance Outputable SkolemInfo where
ppr = pprSkolInfo
pprSkolInfo :: SkolemInfo -> SDoc
-- Complete the sentence "is a rigid type variable bound by..."
pprSkolInfo (SigSkol (FunSigCtxt f) ty)
= hang (ptext (sLit "the type signature for"))
2 (pprPrefixOcc f <+> dcolon <+> ppr ty)
pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
2 (ppr ty)
pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter binding") <> plural ips <+> ptext (sLit "for")
<+> pprWithCommas ppr ips
pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
pprSkolInfo (PatSkol cl mc) = case cl of
RealDataCon dc -> sep [ ptext (sLit "a pattern with constructor")
, nest 2 $ ppr dc <+> dcolon
<+> pprType (dataConUserType dc) <> comma
-- pprType prints forall's regardless of -fprint-explict-foralls
-- which is what we want here, since we might be saying
-- type variable 't' is bound by ...
, ptext (sLit "in") <+> pprMatchContext mc ]
PatSynCon ps -> sep [ ptext (sLit "a pattern with pattern synonym")
, nest 2 $ ppr ps <+> dcolon
<+> pprType (patSynType ps) <> comma
, ptext (sLit "in") <+> pprMatchContext mc ]
pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
, vcat [ ppr name <+> dcolon <+> ppr ty
| (name,ty) <- ids ]]
pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
-- UnkSkol
-- For type variables the others are dealt with by pprSkolTvBinding.
-- For Insts, these cases should not happen
pprSkolInfo UnkSkol = {-WARN( True, text "pprSkolInfo: UnkSkol" )-} ptext (sLit "UnkSkol")
{-
************************************************************************
* *
CtOrigin
* *
************************************************************************
-}
data CtOrigin
= GivenOrigin SkolemInfo
-- All the others are for *wanted* constraints
| OccurrenceOf Name -- Occurrence of an overloaded identifier
| AppOrigin -- An application of some kind
| SpecPragOrigin Name -- Specialisation pragma for identifier
| TypeEqOrigin { uo_actual :: TcType
, uo_expected :: TcType }
| KindEqOrigin
TcType TcType -- A kind equality arising from unifying these two types
CtOrigin -- originally arising from this
| CoercibleOrigin TcType TcType -- a Coercible constraint
| IPOccOrigin HsIPName -- Occurrence of an implicit parameter
| LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
| NegateOrigin -- Occurrence of syntactic negation
| ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
| PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
| SectionOrigin
| TupleOrigin -- (..,..)
| ExprSigOrigin -- e :: ty
| PatSigOrigin -- p :: ty
| PatOrigin -- Instantiating a polytyped pattern at a constructor
| RecordUpdOrigin
| ViewPatOrigin
| ScOrigin -- Typechecking superclasses of an instance declaration
| DerivOrigin -- Typechecking deriving
| DerivOriginDC DataCon Int
-- Checking constraints arising from this data con and field index
| DerivOriginCoerce Id Type Type
-- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
-- `ty1` to `ty2`.
| StandAloneDerivOrigin -- Typechecking stand-alone deriving
| DefaultOrigin -- Typechecking a default decl
| DoOrigin -- Arising from a do expression
| MCompOrigin -- Arising from a monad comprehension
| IfOrigin -- Arising from an if statement
| ProcOrigin -- Arising from a proc expression
| AnnOrigin -- An annotation
| FunDepOrigin1 -- A functional dependency from combining
PredType CtLoc -- This constraint arising from ...
PredType CtLoc -- and this constraint arising from ...
| FunDepOrigin2 -- A functional dependency from combining
PredType CtOrigin -- This constraint arising from ...
PredType SrcSpan -- and this instance
-- We only need a CtOrigin on the first, because the location
-- is pinned on the entire error message
| HoleOrigin
| UnboundOccurrenceOf RdrName
| ListOrigin -- An overloaded list
| StaticOrigin -- A static form
ctoHerald :: SDoc
ctoHerald = ptext (sLit "arising from")
pprCtOrigin :: CtOrigin -> SDoc
pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
= hang (ctoHerald <+> ptext (sLit "a functional dependency between constraints:"))
2 (vcat [ hang (quotes (ppr pred1)) 2 (pprArisingAt loc1)
, hang (quotes (ppr pred2)) 2 (pprArisingAt loc2) ])
pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
= hang (ctoHerald <+> ptext (sLit "a functional dependency between:"))
2 (vcat [ hang (ptext (sLit "constraint") <+> quotes (ppr pred1))
2 (pprArising orig1 )
, hang (ptext (sLit "instance") <+> quotes (ppr pred2))
2 (ptext (sLit "at") <+> ppr loc2) ])
pprCtOrigin (KindEqOrigin t1 t2 _)
= hang (ctoHerald <+> ptext (sLit "a kind equality arising from"))
2 (sep [ppr t1, char '~', ppr t2])
pprCtOrigin (UnboundOccurrenceOf name)
= ctoHerald <+> ptext (sLit "an undeclared identifier") <+> quotes (ppr name)
pprCtOrigin (DerivOriginDC dc n)
= hang (ctoHerald <+> ptext (sLit "the") <+> speakNth n
<+> ptext (sLit "field of") <+> quotes (ppr dc))
2 (parens (ptext (sLit "type") <+> quotes (ppr ty)))
where
ty = dataConOrigArgTys dc !! (n-1)
pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
= hang (ctoHerald <+> ptext (sLit "the coercion of the method") <+> quotes (ppr meth))
2 (sep [ text "from type" <+> quotes (ppr ty1)
, nest 2 $ text "to type" <+> quotes (ppr ty2) ])
pprCtOrigin (CoercibleOrigin ty1 ty2)
= hang (ctoHerald <+> text "trying to show that the representations of")
2 (quotes (ppr ty1) <+> text "and" $$
quotes (ppr ty2) <+> text "are the same")
pprCtOrigin simple_origin
= ctoHerald <+> pprCtO simple_origin
----------------
pprCtO :: CtOrigin -> SDoc -- Ones that are short one-liners
pprCtO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
pprCtO AppOrigin = ptext (sLit "an application")
pprCtO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
pprCtO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
pprCtO RecordUpdOrigin = ptext (sLit "a record update")
pprCtO ExprSigOrigin = ptext (sLit "an expression type signature")
pprCtO PatSigOrigin = ptext (sLit "a pattern type signature")
pprCtO PatOrigin = ptext (sLit "a pattern")
pprCtO ViewPatOrigin = ptext (sLit "a view pattern")
pprCtO IfOrigin = ptext (sLit "an if statement")
pprCtO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
pprCtO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
pprCtO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
pprCtO SectionOrigin = ptext (sLit "an operator section")
pprCtO TupleOrigin = ptext (sLit "a tuple")
pprCtO NegateOrigin = ptext (sLit "a use of syntactic negation")
pprCtO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
pprCtO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
pprCtO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
pprCtO DefaultOrigin = ptext (sLit "a 'default' declaration")
pprCtO DoOrigin = ptext (sLit "a do statement")
pprCtO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
pprCtO ProcOrigin = ptext (sLit "a proc expression")
pprCtO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
pprCtO AnnOrigin = ptext (sLit "an annotation")
pprCtO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
pprCtO ListOrigin = ptext (sLit "an overloaded list")
pprCtO StaticOrigin = ptext (sLit "a static form")
pprCtO _ = panic "pprCtOrigin"
{-
Constraint Solver Plugins
-------------------------
-}
type TcPluginSolver = [Ct] -- given
-> [Ct] -- derived
-> [Ct] -- wanted
-> TcPluginM TcPluginResult
newtype TcPluginM a = TcPluginM (TcM a)
instance Functor TcPluginM where
fmap = liftM
instance Applicative TcPluginM where
pure = return
(<*>) = ap
instance Monad TcPluginM where
return x = TcPluginM (return x)
fail x = TcPluginM (fail x)
TcPluginM m >>= k =
TcPluginM (do a <- m
let TcPluginM m1 = k a
m1)
runTcPluginM :: TcPluginM a -> TcM a
runTcPluginM (TcPluginM m) = m
-- | This function provides an escape for direct access to
-- the 'TcM` monad. It should not be used lightly, and
-- the provided 'TcPluginM' API should be favoured instead.
unsafeTcPluginTcM :: TcM a -> TcPluginM a
unsafeTcPluginTcM = TcPluginM
data TcPlugin = forall s. TcPlugin
{ tcPluginInit :: TcPluginM s
-- ^ Initialize plugin, when entering type-checker.
, tcPluginSolve :: s -> TcPluginSolver
-- ^ Solve some constraints.
-- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
, tcPluginStop :: s -> TcPluginM ()
-- ^ Clean up after the plugin, when exiting the type-checker.
}
data TcPluginResult
= TcPluginContradiction [Ct]
-- ^ The plugin found a contradiction.
-- The returned constraints are removed from the inert set,
-- and recorded as insoluable.
| TcPluginOk [(EvTerm,Ct)] [Ct]
-- ^ The first field is for constraints that were solved.
-- These are removed from the inert set,
-- and the evidence for them is recorded.
-- The second field contains new work, that should be processed by
-- the constraint solver.
| pparkkin/eta | compiler/ETA/TypeCheck/TcRnTypes.hs | bsd-3-clause | 88,586 | 0 | 16 | 26,441 | 10,603 | 6,106 | 4,497 | 848 | 2 |
{-
Teak synthesiser for the Balsa language
Copyright (C) 2007-2010 The University of Manchester
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Andrew Bardsley <[email protected]> (and others, see AUTHORS)
School of Computer Science, The University of Manchester
Oxford Road, MANCHESTER, M13 9PL, UK
-}
module SimPN (
makePartPN,
makeTopLevelPartPN,
runPN,
runMkPNMonad0,
stepPN,
teakR,
showUntypedSimValue,
PN (..),
Place (..),
pnToDot,
pnTestCard,
dotGraphGroupNodesByLabel,
writeHLNet,
showMarkingElem,
showPNExpr,
PNExpr (..),
MkPNMonad,
MkPN (..),
ReqAckPair,
Chan,
Marking,
PlaceNo,
TransNo,
Trans (..),
PlaceType (..),
testPNs
) where
import Misc
import SimTypes
import SimBuiltin
import ParseTree hiding (Chan)
import NetParts
import Bits
import Dot
import Show
import State
import GuiSupport (colours, black)
import qualified Data.Map as DM
import Data.List
import Data.Bits
import Control.Monad.State
import Data.Maybe
import Data.Char
import System.IO
type PlaceNo = Int
type TransNo = Int
data Place = Place {
placeLabel :: [String],
placeType :: PlaceType }
data Trans m value = Trans {
transLabel :: [String],
transInPlaces :: [PlaceNo],
transOutPlaces :: [PlaceNo],
transCondition :: Maybe PNExpr,
transExprs :: [PNExpr],
transReport :: ([value] -> m ()) }
data PlaceType = BlackPlaceType | NumericPlaceType Int
deriving (Show, Eq)
instance Show Place where
showsPrec prec (Place label typ) =
showParen (prec > 10) $ showString "Place " . shows label . space . shows typ
instance Show (Trans m value) where
showsPrec prec (Trans label inPlaces outPlace cond exprs _) =
showParen (prec > 10) $ showString "Trans " . shows label . space .
shows inPlaces . space . shows outPlace . space . shows cond . shows exprs
type Marking value = DM.Map PlaceNo [value]
joinLabel :: [String] -> String
joinLabel = joinWith "." . reverse
showMarkingElem :: PN SimFlow SimValue -> (PlaceNo, [SimValue]) -> ShowS
showMarkingElem pn (placeNo, tokens) = showString "Place " . shows placeNo . space . showString label .
showString ": " . shows (length tokens) . (if length tokens > 1 then showString "!!!" else id) .
space . showString (plural "token" tokens) . showString " [" .
showListWithSep (showString ", ") (showString . showUntypedSimValue) tokens .
showString "]"
where label = joinLabel $ placeLabel $ (pnPlaces pn) DM.! placeNo
data {- Monad m => -} PN m value = PN {
pnPlaces :: DM.Map PlaceNo Place,
pnTrans :: DM.Map TransNo (Trans m value),
pnInitialMarking :: Marking value }
deriving Show
data {- Monad m => -} MkPN m value = MkPN {
mkpnLabelStack :: [String],
mkpnPlaceCount :: Int,
mkpnTransCount :: Int,
mkpnPlaces :: DM.Map PlaceNo Place,
mkpnTrans :: DM.Map TransNo (Trans m value),
mkpnMarking :: DM.Map PlaceNo [value] }
type MkPNMonad m value a = State (MkPN m value) a
data PNExpr =
PNLiteral SimValue
| PNBool Bool
| PNInput Int
| PNBitfield (Slice Int) PNExpr
| PNInsertBitfield (Slice Int) PNExpr PNExpr
| PNOp [(Int, TeakOTerm)] PNExpr
| PNAppend [Int] [PNExpr]
| PNMatch (Slice Int) [Implicant] PNExpr
deriving Show
space :: ShowS
space = showChar ' '
pnExprPrec :: PNExpr -> Int
pnExprPrec (PNOp terms _) = prettyPrintOTermPrec $ snd $ last terms
pnExprPrec (PNLiteral {}) = 11
pnExprPrec (PNBool {}) = 11
pnExprPrec (PNInput {}) = 11
pnExprPrec _ = 10
showPNExpr :: Int -> PNExpr -> ShowS
showPNExpr prec expr = showParen (prec > thisPrec) $ body expr
where
body (PNLiteral NoSimValue) = showString "token"
body (PNLiteral (SimValue int [])) = shows int
body (PNBool bool) = shows bool
body (PNInput inp) = showString "i" . shows inp
body (PNBitfield slice expr) = showPNExpr (thisPrec + 1) expr . verilogShowSlice slice
body (PNInsertBitfield slice expr1 expr2) = showString "insert " . paren (verilogShowSlice slice .
showString "," . showPNExpr 0 expr1 . showString "," . showPNExpr 0 expr2)
body (PNOp terms expr) = if listAtLeastLength 2 termStrs
then showString "let " . showListWithSep (showString ";") showString (init termStrs) .
showString " in " . showString (last termStrs)
else showString (last termStrs)
where
termStrs = prettyPrintOTerms 0 (\prec -> showPNExpr prec expr) terms
body (PNAppend widths exprs) = case exprs' of
[] -> showString "token"
[expr] -> showPNExpr prec expr
_ -> showChar '{' . showListWithSep (showString ", ") (showPNExpr 0) exprs' .
showChar '}'
where
exprs' = map fst $ filter nonZeroWidth $ zip exprs widths
nonZeroWidth (_, 0) = False
nonZeroWidth _ = True
body (PNMatch slice imps expr) = showString "match " . paren (verilogShowSlice slice . showString "," .
showString "[" .
showString (joinWith "," $ map (showImp True True 4) imps) .
showString "]," .
showPNExpr 0 expr)
body expr = showString "?" . shows expr
thisPrec = pnExprPrec expr
paren = showParen True
hlShowOTerms :: [(Int, TeakOTerm)] -> PNExpr -> ShowS
hlShowOTerms terms expr = snd $ last termShows
where
getTerm :: Int -> TeakOTerm
getTerm termNo = fromJust $ lookup termNo terms
termShows :: [(Int, ShowS)]
termShows = (0, hlShowPNExpr expr) : mapSnd showTerm terms
subTerm :: TeakOSlice -> ShowS
subTerm (termNo, slice)
| termNo /= 0 && isConstant rawTerm = shows $
extractBitfield slice constValue
| termNo /= 0 && sliceWidth slice == resultWidth = hlShr term $ sliceOffset slice
| otherwise = hlBitfield slice term
where
isConstant (TeakOConstant {}) = True
isConstant _ = False
TeakOConstant _ constValue = rawTerm
term = fromJust $ lookup termNo termShows
rawTerm = getTerm termNo
resultWidth = oTermResultWidth rawTerm
showTerm :: TeakOTerm -> ShowS
showTerm (TeakOConstant _ int) = shows int
showTerm (TeakOAppend count slices) = hlAppend
(concat $ replicate count $ map oSliceWidth slices)
(concat $ replicate count $ map subTerm slices)
showTerm term@(TeakOBuiltin {}) -- FIXME
| oTermResultWidth term == 0 = showString "dot"
| otherwise = shows (0 :: Integer)
showTerm (TeakOp op slices) = case (op, slices) of
(TeakOpAdd, [l, r]) -> clip "+" l r
(TeakOpSub, [l, r]) -> clip "-" l r
(TeakOpAnd, [l, r]) -> logical "&" l r
(TeakOpOr, [l, r]) -> logical "|" l r
(TeakOpXor, [l, r]) -> logical "#" l r
(TeakOpNot, [r]) -> hlInfixOp "-" (shows ((bit (oSliceWidth r) :: Integer) - 1)) (subTerm r)
(TeakOpSignedGT, [l, r]) -> signedInEq ">" l r
(TeakOpSignedGE, [l, r]) -> signedInEq ">=" l r
(TeakOpUnsignedGT, [l, r]) -> hlBoolToBit $ bin ">" l r
(TeakOpUnsignedGE, [l, r]) -> hlBoolToBit $ bin ">=" l r
(TeakOpEqual, [l, r]) -> bin "=" l r
(TeakOpNotEqual, [l, r]) -> bin "#" l r
_ -> error $ "hlShowOTerms.showTerm: bad TeakOp `" ++ show op ++ "' with slices `" ++ show slices ++ "'"
where
width = oSliceWidth $ head slices
signedInEq op l r = hlBoolToBit $ hlInfixOp op (padSigned l) (padSigned r)
bin op l r = hlInfixOp op (subTerm l) (subTerm r)
clip op l r = hlInfixOp "%" (hlInfixOp op
(hlInfixOp "+" (showsBit (oSliceWidth l)) (subTerm l))
(subTerm r)) (showsBit $ oSliceWidth l)
logical op l r = foldl1' (hlInfixOp "+") $ map bitOp [0..width-1]
where
lStr = subTerm l
rStr = subTerm r
bitOp i = hlIf (hlInfixOp op (bitBool lStr i) (bitBool rStr i))
(showsBit i) (shows (0::Int))
-- padSigned : add 2^width to positive numbers to keep numbers is order and
-- nice and positive for signed comparisons
padSigned slice = hlInfixOp "+" (hlIf (bitBool str (width - 1))
(shows (0::Int)) (showsBit width)) str
where str = subTerm slice
bitBool expr i = hlInfixOp ">="
(hlInfixOp "%" expr (showsBit (i + 1))) (showsBit i)
showTerm (TeakOMux spec (choiceSlice:slices)) =
foldr ($) (shows (0::Int)) $ zipWith makeMatch spec slices
where
makeMatch imps inSlice = hlIf (hlImpsMatch choiceWidth imps choiceStr) (subTerm inSlice)
choiceWidth = oSliceWidth choiceSlice
choiceStr = subTerm choiceSlice
showTerm term = error $ "hlShowOTerms.showTerm: bad TeakOTerm `" ++ show term ++ "'"
hlShowPNExpr :: PNExpr -> ShowS
hlShowPNExpr expr = body expr
where
body (PNLiteral NoSimValue) = showString "dot"
body (PNLiteral (SimValue int [])) = shows int
body (PNBool True) = showString "tt"
body (PNBool False) = showString "ff"
body (PNInput inp) = showChar 'i' . shows inp
body (PNBitfield slice expr) = hlBitfield slice (subExpr expr)
body (PNInsertBitfield slice expr1 expr2) = foldl1' (hlInfixOp "+") $ catMaybes [
if offset == 0 then Nothing else Just $ hlBitfield (0 +: offset) shows1,
Just $ hlInfixOp "-" shows1 $ hlInfixOp "%" shows1 $ showsBit $ sliceHigh slice + 1,
Just $ hlShl shows2 offset ]
where
shows1 = subExpr expr1
shows2 = subExpr expr2
offset = sliceOffset slice
body (PNAppend widths exprs) = hlAppend widths $ map subExpr exprs
body (PNMatch slice imps expr) = hlImpsMatch (sliceWidth slice) imps $ hlBitfield slice $ subExpr expr
body (PNOp terms expr) = hlShowOTerms terms expr
body expr = error $ "body: can't show PNExpr `" ++ show expr ++ "'"
subExpr expr = hlShowPNExpr expr
hlImpsMatch :: Width -> [Implicant] -> ShowS -> ShowS
hlImpsMatch width imps exprStr = foldl1' (hlInfixOp "|") $ concatMap makeMatch imps
where
makeMatch (Imp v 0) = [hlInfixOp "=" exprStr (shows v)]
makeMatch (Imp v dc) = map (testSubSlice v) $ bitmaskToIntervals $ bitNot width dc
testSubSlice v careSlice = hlInfixOp "=" (hlBitfield careSlice exprStr)
(shows (extractBitfield careSlice v))
showsBit :: Int -> ShowS
showsBit dist = shows (bit dist :: Integer)
hlInfixOp :: String -> ShowS -> ShowS -> ShowS
hlInfixOp op l r = showParen True $ l . space . showString op . space . r
hlBoolToBit :: ShowS -> ShowS
hlBoolToBit cond = hlIf cond (shows (1::Int)) (shows (0::Int))
hlIf :: ShowS -> ShowS -> ShowS -> ShowS
hlIf cond then_ else_ = showString "if(" . cond . showChar ',' . then_ . showChar ',' . else_ . showChar ')'
hlAppend :: [Int] -> [ShowS] -> ShowS
hlAppend _ [] = shows (0::Int)
hlAppend widths exprs
| null exprStrs = showString "dot"
| otherwise = foldl1' (hlInfixOp "+") exprStrs
where
offsets = scanl (+) 0 widths
exprStrs = mapMaybe maybeInsert $ zip3 exprs offsets widths
maybeInsert (_, _, 0) = Nothing
maybeInsert (expr, offset, _) = Just $ hlShl expr offset
hlShl :: ShowS -> Int -> ShowS
hlShl l 0 = l
hlShl l dist = hlInfixOp "*" l (showsBit dist)
hlShr :: ShowS -> Int -> ShowS
hlShr l 0 = l
hlShr l dist = hlInfixOp "/" l (showsBit dist)
hlBitfield :: Slice Int -> ShowS -> ShowS
hlBitfield slice inp = hlInfixOp "%"
(hlShr inp (sliceOffset slice))
(shows (bit (sliceWidth slice) :: Integer))
evalPNExpr :: [SimValue] -> PNExpr -> SimFlow SimValue
evalPNExpr inputs expr = body expr
where
body (PNLiteral value) = return value
body (PNBool True) = return $ SimValue 1 []
body (PNBool False) = return $ SimValue 0 []
body (PNInput i) = return $ inputs !! i
body (PNBitfield slice expr) = subExpr expr >>= return . getBitfield slice
body (PNInsertBitfield slice expr1 expr2) = do
val1 <- subExpr expr1
val2 <- subExpr expr2
return $ simInsertBitfield slice val1 val2
body (PNOp terms expr) = do
v <- subExpr expr
results <- evalOTerms terms v
let (_, result) = last results
return result
body (PNAppend widths exprs) = do
vs <- mapM subExpr exprs
return $ simAppendValues widths vs
body (PNMatch slice imps expr) = do
v <- subExpr expr
case v of
SimValue {} -> do
let SimValue guard _ = simExtractBitfield slice v
return $ SimValue (
if any (impIsCoveredByImp (sliceWidth slice) (Imp guard 0)) imps
then 1
else 0) []
_ -> return NoSimValue
subExpr expr = evalPNExpr inputs expr
runMkPNMonad0 :: Monad m => MkPNMonad m value a -> (a, PN m value)
runMkPNMonad0 m = (ret, PN places trans marking)
where
trans = mkpnTrans pn'
places = mkpnPlaces pn'
marking = mkpnMarking pn'
pn0 = MkPN [] 0 0 DM.empty DM.empty DM.empty
(ret, pn') = runState m pn0
newPlace :: Monad m => PlaceType -> [value] -> MkPNMonad m value PlaceNo
newPlace typ initValues = do
label <- getLabel
let op mkpn = (placeNo, mkpn')
where
placeNo = mkpnPlaceCount mkpn + 1
mkpn' = mkpn { mkpnPlaceCount = placeNo,
mkpnPlaces = DM.insert placeNo (Place label typ) (mkpnPlaces mkpn),
mkpnMarking = DM.insert placeNo initValues (mkpnMarking mkpn)
}
state op
newBlackPlace :: Monad m => [value] -> MkPNMonad m value PlaceNo
newBlackPlace = newPlace BlackPlaceType
newNumericPlace :: Monad m => Width -> [value] -> MkPNMonad m value PlaceNo
newNumericPlace 0 = newBlackPlace
newNumericPlace width = newPlace (NumericPlaceType width)
addTrans :: Monad m => Trans m value -> MkPNMonad m value TransNo
addTrans trans
| length (transExprs trans) /= length (transOutPlaces trans) = error $
"addTrans: must be one expr per out place `" ++ show (transExprs trans) ++ "', for "
++ show (length (transOutPlaces trans)) ++ " out places"
| otherwise = state op
where op mkpn = (transNo, mkpn')
where
transNo = mkpnTransCount mkpn + 1
mkpn' = mkpn { mkpnTransCount = transNo, mkpnTrans = DM.insert transNo trans (mkpnTrans mkpn) }
newTrans :: Monad m => [PlaceNo] -> [PlaceNo] -> [PNExpr] ->
MkPNMonad m value TransNo
newTrans inPlaces outPlaces exprs = do
label <- getLabel
addTrans $ Trans label inPlaces outPlaces Nothing exprs $ const $ return ()
newReportTrans :: Monad m => [PlaceNo] -> [PlaceNo] -> [PNExpr] ->
([value] -> m ()) -> MkPNMonad m value TransNo
newReportTrans inPlaces outPlaces exprs report = do
label <- getLabel
addTrans $ Trans label inPlaces outPlaces Nothing exprs report
newCondTrans :: Monad m => PNExpr -> [PlaceNo] -> [PlaceNo] -> [PNExpr] ->
MkPNMonad m value TransNo
newCondTrans cond inPlaces outPlaces exprs = do
label <- getLabel
addTrans $ Trans label inPlaces outPlaces (Just cond) exprs $ const $ return ()
popPlaces :: Marking value -> [PlaceNo] -> (Marking value, [value])
popPlaces marking placeNos = mapAccumL adjust marking placeNos
where adjust marking placeNo = (DM.insert placeNo values marking, value)
where value:values = marking DM.! placeNo
pushPlaces :: Marking value -> [(PlaceNo, value)] -> Marking value
pushPlaces marking placeNoValuePairs = foldl' adjust marking placeNoValuePairs
where adjust marking (placeNo, value) = DM.adjust (++ [value]) placeNo marking
pushLabel :: Monad m => String -> MkPNMonad m value ()
pushLabel label = state op
where op mkpn = ((), mkpn')
where mkpn' = mkpn { mkpnLabelStack = label : mkpnLabelStack mkpn }
popLabel :: Monad m => MkPNMonad m value ()
popLabel = state op
where op mkpn = ((), mkpn')
where mkpn' = mkpn { mkpnLabelStack = tail $ mkpnLabelStack mkpn }
getLabel :: Monad m => MkPNMonad m value [String]
getLabel = state op
where op mkpn = (mkpnLabelStack mkpn, mkpn)
withLabel :: String -> MkPNMonad SimFlow SimValue a -> MkPNMonad SimFlow SimValue a
withLabel label m = do
pushLabel label
ret <- m
popLabel
return ret
type ReqAckPair = (PlaceNo, PlaceNo)
type Chan = (ReqAckPair, ReqAckPair)
-- FIXME Needs fairness for choice places
-- stepPN :: (Show value, Monad m) => PN m value -> Marking value -> m (Bool, Marking value)
stepPN :: PN SimFlow SimValue -> Marking SimValue -> SimFlow (Bool, Marking SimValue)
stepPN (PN _ trans _) marking = do
(progress, marking') <- foldM tryTrans (False, marking) $ DM.elems trans
let unsafePlaces = filter (listAtLeastLength 2) $ DM.elems marking'
when (not (null unsafePlaces)) $ do
fail $ "Not safe " ++ show unsafePlaces
return (progress, marking')
where
tryTrans (prevProgress, updatedMarking) trans
| all inpCanFire inPlaces = do
fire <- case transCondition trans of
Nothing -> return True
Just cond -> do
v <- evalPNExpr inValues cond
let ret = case v of
SimValue 1 [] -> True
_ -> False
return ret
if fire
then do
-- outValues <- transAction trans trans inValues
outValues <- mapM (evalPNExpr inValues) $ transExprs trans
transReport trans inValues
when (length outValues /= length outPlaces) $ error $
"stepPN: transition `" ++ joinLabel (transLabel trans) ++ "' out token length mismatch"
return (True, pushPlaces poppedPlaces $ zip outPlaces outValues)
else return (prevProgress, updatedMarking)
| otherwise = return (prevProgress, updatedMarking)
where
inPlaces = transInPlaces trans
outPlaces = transOutPlaces trans
(poppedPlaces, inValues) = popPlaces updatedMarking inPlaces
-- can I take a token now (to cover choice places), and before this step (to cover places
-- which had a token added earlier this step)
inpCanFire placeNo = listAtLeastLength 1 (marking DM.! placeNo) &&
listAtLeastLength 1 (updatedMarking DM.! placeNo)
-- Use this for faster, not cycle number correct results
-- inpCanFire placeNo = listAtLeastLength 1 (updatedMarking DM.! placeNo)
type Width = Int
token :: SimValue
token = NoSimValue -- SimValue 0 []
-- chan :: Monad m => Int -> value -> MkPNMonad m value Chan
chan :: Width -> Int -> MkPNMonad SimFlow SimValue Chan
chan width depth = do
inp <- pair
out <- if depth == 0
then return inp
else foldM makeLatch inp [1..depth]
return (out, inp)
where
makeLatch inp i = withLabel (show i) $ do
out <- pair
latch inp out
return out
pair = do
req <- withLabel "r" $ newNumericPlace width []
ack <- withLabel "a" $ newBlackPlace []
return (req, ack)
teakLink :: String -> NetworkLink -> MkPNMonad SimFlow SimValue Chan
teakLink partName link
| depth == 0 = withLabel linkName $ do
inp <- withLabel "a" $ pair
out <- withLabel "p" $ pair
withLabel "L" $ linkTrans "L" inp out
return (out, inp)
| otherwise = withLabel linkName $ do
inp <- withLabel "a" $ pair
out <- withLabel "p" $ pair
internalLinks <- mapM (\i -> withLabel ("i" ++ show i) $ pair) [0..depth]
withLabel "A" $ linkTrans "A" inp (head internalLinks)
withLabel "P" $ linkTrans "P" (last internalLinks) out
mapM_ (\(i, inp, out) -> withLabel (show i) $ latch inp out) $ zip3
[(1::Int)..] (init internalLinks) (tail internalLinks)
return (out, inp)
where
HalfBuffer depth = nwLinkLatching link
ref = refLink link
width = nwLinkWidth link
linkName = show ref
linkTrans end (inpR, inpA) (outR, outA) = do
reqPlace <- withLabel "r" $ newBlackPlace [token]
ackPlace <- withLabel "a" $ newBlackPlace []
withLabel "r" $ trans "R" [inpR, reqPlace] [outR, ackPlace]
withLabel "a" $ trans "SPACER" [outA, ackPlace] [inpA, reqPlace]
where
trans event inp out = newReportTrans inp out
[PNInput 0, PNLiteral token]
$ \[v, _] -> do
TimeState time <- simFlowGet TimeRef
FileState handle <- simFlowGet LogFileRef
lift $ hPutStrLn handle $ "#" ++ show time ++ " " ++ partName ++ "."
++ linkName ++ "." ++ end ++ " " ++ event
++ case v of
SimValue int [] -> " " ++ show int
_ -> ""
return ()
pair = do
req <- withLabel "r" $ newNumericPlace width []
ack <- withLabel "a" $ newBlackPlace []
return (req, ack)
latch :: ReqAckPair -> ReqAckPair -> MkPNMonad SimFlow SimValue ()
latch (inpR, inpA) (outR, outA) = withLabel "L" $ do
ackPlace <- withLabel "a" $ newBlackPlace [token]
withLabel "r" $ newTrans [inpR, ackPlace] [outR, inpA] [PNInput 0, PNLiteral token]
withLabel "a" $ newTrans [outA] [ackPlace] [PNLiteral token]
return ()
-- type MkPNMonad m value a = State (MkPN m value) a
showUntypedSimValue :: SimValue -> String
showUntypedSimValue NoSimValue = "token"
showUntypedSimValue (SimValue int specials) = show int ++ if null specials
then "" else " " ++ (joinWith " " $ map showSpecial specials)
where
showSpecial (i, StringSimValue str) = "\"" ++ str ++ "\"@" ++ show i
showSpecial _ = "???"
getBitfield :: Slice Int -> SimValue -> SimValue
getBitfield _ NoSimValue = NoSimValue
getBitfield slice value
| isEmptySlice slice = token
| otherwise = simExtractBitfield slice value
pnBitfield :: Slice Int -> PNExpr -> PNExpr
pnBitfield slice expr
| isEmptySlice slice = PNLiteral NoSimValue
| otherwise = PNBitfield slice expr
teakR :: Chan -> MkPNMonad SimFlow SimValue ()
teakR (_, (outR, _outA)) = withLabel "R" $ do
initPlace <- withLabel "init" $ newBlackPlace [token]
withLabel "or" $ newTrans [initPlace] [outR] [PNLiteral token]
return ()
teakI :: Chan -> Chan -> MkPNMonad SimFlow SimValue ()
teakI ((inpR, inpA), _) (_, (outR, outA)) = withLabel "I" $ do
reqPlace <- withLabel "r" $ newBlackPlace [token]
withLabel "ir" $ newTrans [inpR, outA] [reqPlace, inpA] [PNInput 0, PNLiteral token]
withLabel "or" $ newTrans [reqPlace] [outR] [PNLiteral token]
return ()
teakM :: Width -> [Chan] -> Chan -> MkPNMonad SimFlow SimValue ()
teakM width inp (_, (outR, outA)) = withLabel "M" $ do
reqPlace <- withLabel "r" $ newNumericPlace width []
ackPlace <- withLabel "a" $ newBlackPlace []
choicePlace <- withLabel "choice" $ newBlackPlace [token]
withLabel "or" $ newTrans [reqPlace] [outR] [PNInput 0]
withLabel "oa" $ newTrans [outA] [ackPlace] [PNLiteral token]
let
makeInp i ((inpR, inpA), _) = withLabel ("i" ++ show i) $ do
inpAPlace <- withLabel "a" $ newBlackPlace []
withLabel "r" $ newTrans [inpR, choicePlace] [inpAPlace, reqPlace] [PNLiteral token, PNInput 0]
withLabel "a" $ newTrans [inpAPlace, ackPlace] [inpA, choicePlace] [PNLiteral token, PNLiteral token]
zipWithM_ makeInp [(0::Int)..] inp
teakS :: Width -> Slice Int -> [Slice Int] -> [[Implicant]] -> Chan -> [Chan] ->
MkPNMonad SimFlow SimValue ()
teakS inpWidth guardSlice outSlices impss ((inpR, inpA),_) out = withLabel "S" $ do
reqPlace <- withLabel "r" $ newNumericPlace inpWidth []
ackPlace <- withLabel "a" $ newBlackPlace []
withLabel "ir" $ newTrans [inpR] [reqPlace] [PNInput 0]
withLabel "ia" $ newTrans [ackPlace] [inpA] [PNLiteral token]
let
makeOut (_, (outR, outA)) (i, outSlice, imps) = withLabel ("o" ++ show i) $ do
withLabel "r" $ newCondTrans canFire [reqPlace] [outR] [pnBitfield outSlice (PNInput 0)]
withLabel "a" $ newTrans [outA] [ackPlace] [PNLiteral token]
where
-- canFire inp = any (impIsCoveredByImp (sliceWidth guardSlice) (Imp guard 0)) imps
canFire = PNMatch guardSlice imps $ PNInput 0
zipWithM makeOut out $ zip3 [(0::Int)..] outSlices impss
return ()
teakF :: [Slice Int] -> Chan -> [Chan] -> MkPNMonad SimFlow SimValue ()
teakF outSlices ((inpR, inpA), _) out = withLabel "F" $ do
withLabel "r" $ newTrans [inpR] outR (map (\slice -> pnBitfield slice (PNInput 0)) outSlices)
withLabel "a" $ newTrans outA [inpA] [PNLiteral token]
return ()
where
(_, outActive) = unzip out
(outR, outA) = unzip outActive
teakJ :: [Width] -> [Chan] -> Chan -> MkPNMonad SimFlow SimValue ()
teakJ inpWidths inp (_, (outR, outA)) = withLabel "J" $ do
withLabel "r" $ newTrans inpR [outR] [PNAppend inpWidths (map PNInput [0..inpCount - 1])]
withLabel "a" $ newTrans [outA] inpA (replicate (length inpA) (PNLiteral token))
return ()
where
inpCount = length inp
(inpPassive, _) = unzip inp
(inpR, inpA) = unzip inpPassive
teakA :: Width -> [Chan] -> Chan -> MkPNMonad SimFlow SimValue ()
teakA width inp (_, (outR, outA)) = withLabel "A" $ do
reqPlace <- withLabel "r" $ newNumericPlace width []
ackPlace <- withLabel "a" $ newBlackPlace []
choicePlace <- withLabel "choice" $ newBlackPlace [token]
withLabel "or" $ newTrans [reqPlace] [outR] [PNInput 0]
withLabel "oa" $ newTrans [outA] [ackPlace] [PNLiteral token]
let
makeInp i ((inpR, inpA), _) = withLabel ("i" ++ show i) $ do
inpAPlace <- newBlackPlace []
withLabel "r" $ newTrans [inpR, choicePlace] [inpAPlace, reqPlace] [PNLiteral token, PNInput 0]
withLabel "a" $ newTrans [inpAPlace, ackPlace] [inpA, choicePlace] [PNLiteral token, PNLiteral token]
zipWithM makeInp [(0::Int)..] inp
return ()
teakO :: [(Int, TeakOTerm)] -> Chan -> Chan -> MkPNMonad SimFlow SimValue ()
teakO terms ((inpR, inpA), _) (_, (outR, outA)) = withLabel "O" $ do
when (not isStop) $ do
withLabel "r" $ newTrans [inpR] [outR] [PNOp terms (PNInput 0)]
return ()
withLabel "a" $ newTrans [outA] [inpA] [PNLiteral token]
return ()
where
isStop = case last terms of
(_, TeakOBuiltin { teakOBuiltin = "BalsaSimulationStop" }) -> True
_ -> False
teakV :: Width -> [Slice Int] -> [Slice Int] -> [Chan] -> [Chan] -> [Chan] -> [Chan] ->
MkPNMonad SimFlow SimValue ()
teakV width wSlices rSlices wg wd rg rd = withLabel "V" $ do
idlePlaces <- mapM read $ zip4 [(0::Int)..] rSlices rg rd
mapM_ (write idlePlaces) $ zip4 [(0::Int)..] wSlices wg wd
where
write idlePlaces (i, slice, ((goR, goA), _), (_, (doneR, doneA))) = withLabel ("w" ++ show i) $ do
withLabel "r" $ newTrans (goR : idlePlaces) (doneR : idlePlaces)
((PNLiteral token) : replicate readCount writeExpr)
withLabel "a" $ newTrans [doneA] [goA] [PNLiteral token]
where
writeExpr
| slice == 0 +: width = PNInput 0
| otherwise = PNInsertBitfield slice (PNInput 1) (PNInput 0)
read (i, slice, ((goR, goA), _), (_, (doneR, doneA))) = withLabel ("r" ++ show i) $ do
idlePlace <- withLabel "idle" $ newNumericPlace width [initValue]
busyPlace <- withLabel "busy" $ newNumericPlace width []
withLabel "r" $ newTrans [goR, idlePlace] [doneR, busyPlace] [pnBitfield slice (PNInput 1), PNInput 1]
withLabel "a" $ newTrans [doneA, busyPlace] [goA, idlePlace] [PNLiteral token, PNInput 1]
return idlePlace
readCount = length rg
initValue = SimValue 0 []
evalOTerms :: [(Int, TeakOTerm)] -> SimValue -> SimFlow [(Int, SimValue)]
evalOTerms terms inp = do
values <- foldM evalTerm [(0, inp)] terms
return $ reverse values
where
getOSliceValue values (i, slice) = getBitfield slice $ fromJust $ lookup i values
evalTerm :: [(Int, SimValue)] -> (Int, TeakOTerm) -> SimFlow [(Int, SimValue)]
evalTerm values (i, term) = case term of
TeakOBuiltin name _ params slices -> do
value <- simBuiltinCall (map (getOSliceValue values) slices) (BuiltinCallExpr undefined name
(map teakParamToFuncActual params) undefined undefined)
return $ (i, value):values
_ -> return $ (i, evalPureTerm values term) : values
evalPureTerm _ (TeakOConstant _ value) = SimValue value []
evalPureTerm values (TeakOAppend count slices) = simAppendValues
(concat (replicate count widths)) (concat (replicate count inValues))
where
widths = map oSliceWidth slices
inValues = map (getOSliceValue values) slices
evalPureTerm values (TeakOp op slices) = opFunc sliceValues
where
binOp op [SimValue l _, SimValue r _] = SimValue (cropInt width (l `op` r)) []
binOp _ _ = error "binOp: bad args"
unsignedInEq op [SimValue l _, SimValue r _] = SimValue (boolToBit $ l `op` r) []
unsignedInEq _ _ = error "unsignedInEq: bad args"
signedInEq op [SimValue l _, SimValue r _] = SimValue
(boolToBit $ (recoverSign width l) `op` (recoverSign width r)) []
signedInEq _ _ = error "signedInEq: bad args"
slice:_ = slices
width = oSliceWidth slice
sliceValues = map (getOSliceValue values) slices
opFunc = case op of
TeakOpAdd -> binOp (+)
TeakOpSub -> binOp (-)
TeakOpAnd -> binOp (.&.)
TeakOpOr -> binOp (.|.)
TeakOpNot -> \[SimValue l _] -> SimValue (bitNot width l) []
TeakOpXor -> binOp xor
TeakOpUnsignedGT -> unsignedInEq (>)
TeakOpUnsignedGE -> unsignedInEq (>=)
TeakOpEqual -> unsignedInEq (==)
TeakOpNotEqual -> unsignedInEq (/=)
TeakOpSignedGT -> signedInEq (>)
TeakOpSignedGE -> signedInEq (>=)
evalPureTerm values (TeakOMux impss slices@(choiceSlice:_)) = fromMaybe (SimValue 0 []) $
liftM snd $ find match $ zip impss sliceValues
where
match (imps, _) = any (impIsCoveredByImp choiceWidth (Imp choiceValue 0)) imps
(SimValue choiceValue _):sliceValues = map (getOSliceValue values) slices
choiceWidth = oSliceWidth choiceSlice
evalPureTerm _ term = error $ "putEvalTerm: unrecognised term `" ++ show term ++ "'"
makeComp :: NetworkIF network => [Part network] -> Part network -> DM.Map NetworkLinkRef Chan ->
NetworkComp -> MkPNMonad SimFlow SimValue ()
makeComp _ part chans (TeakComp compNo teakTyp links _) = do
let
chanLinks = map (fmap (chans DM.!)) links
linkWidths = tryPart part $ mapM' (mapM' nwGetLinkWidth . flattenSome) links
partName = networkName part
withLabel partName $ withLabel ("C" ++ show compNo) $ do
case (teakTyp, chanLinks, linkWidths) of
(TeakR, [One out], _) -> teakR out
(TeakI, [One inp, One out], _) -> teakI inp out
(TeakM, [Many inp, One out], [_, [width]]) -> teakM width inp out
(TeakS guardSlice impsXOffsets, [One inp, Many out], [[inpWidth], outWidths]) -> let
(impss, offsets) = unzip impsXOffsets
outSlices = zipWith (+:) offsets outWidths
in teakS inpWidth guardSlice outSlices impss inp out
(TeakF offsets, [One inp, Many out], [_, outWidths]) ->
teakF (zipWith (+:) offsets outWidths) inp out
(TeakJ, [Many inp, One out], [inpWidths, _]) -> teakJ inpWidths inp out
(TeakA, [Many inp, One out], [_, [width]]) -> teakA width inp out
(TeakO terms, [One inp, One out], _) -> teakO terms inp out
(TeakV _ width _ wOffsets rOffsets, [Many wg, Many wd, Many rg, Many rd],
[wWidths, _, _, rWidths]) -> teakV width
(zipWith (+:) wOffsets wWidths)
(zipWith (+:) rOffsets rWidths) wg wd rg rd
(_, _, _) -> error $ "makeComp: unrecognised component " ++ show teakTyp
makeComp parts _ chans (InstanceComp _compNo partName ports links _) = do
let
parentLinks :: [Chan]
parentLinks = flattenSome $ Some $ map (fmap (chans DM.!)) links
Just part = nwFindPart parts partName
connectLink port parentLink instanceLink = withLabel (nwPortName port) $ body
(directionToSense $ nwPortDirection port) parentLink instanceLink
where
body Passive ((chanLinkPR, chanLinkPA), _) (_, (portLinkAR, portLinkAA)) = do
withLabel "r" $ newTrans [chanLinkPR] [portLinkAR] [PNInput 0]
withLabel "a" $ newTrans [portLinkAA] [chanLinkPA] [PNLiteral token]
body Active (_, (chanLinkAR, chanLinkAA)) ((portLinkPR, portLinkPA), _) = do
withLabel "r" $ newTrans [portLinkPR] [chanLinkAR] [PNInput 0]
withLabel "a" $ newTrans [chanLinkAA] [portLinkPA] [PNLiteral token]
instanceLinks <- makePartPN parts part
withLabel (networkName part) $ withLabel "port" $ do
mapM_ (uncurry3 connectLink) $ zip3 ports parentLinks instanceLinks
makePartPN :: NetworkIF network => [Part network] -> Part network -> MkPNMonad SimFlow SimValue [Chan]
makePartPN parts part = do
let partName = networkName part
linkChans <- withLabel partName $ liftM DM.fromList $ sequence $ tryPart part $ do
nwMapLinks $ \link -> return $ do
linkChan <- teakLink partName link
return (refLink link, linkChan)
let portChans = tryPart part $ do
portLinks <- liftM concat $ mapM' (nwGetPortAccess . fromJust . nwPortRef) $ networkPorts part
return $ map (linkChans DM.!) portLinks
let comps = tryPart part $ nwMapComps return
mapM' (makeComp parts part linkChans) comps
return portChans
-- makeTopLevelPartPN : make a PN for a Part and connect the go port upto an R component
makeTopLevelPartPN :: NetworkIF network => [Part network] -> Part network -> PN SimFlow SimValue
makeTopLevelPartPN parts part = pn
where
(_, pn) = runMkPNMonad0 $ do
portChans <- makePartPN parts part
case (goPort, donePort) of
(Just go, Nothing) -> teakR (portChans !! go)
(Just go, Just _done) -> teakR (portChans !! go)
_ -> return ()
ports = networkPorts part
goPort = findIndex (fromMaybe False . liftM (== GoAccess) . nwPortRef) ports
donePort = findIndex (fromMaybe False . liftM (== DoneAccess) . nwPortRef) ports
-- runPN :: (Show value, Monad m) => (a -> m ()) -> PN m value -> Marking value -> [a] -> m (Marking value)
runPN :: (a -> SimFlow ()) -> PN SimFlow SimValue -> Marking SimValue -> [a] -> SimFlow (Marking SimValue)
runPN setTime pn marking times = run pn marking times
where
step pn marking time = do
setTime time
-- simFlowSet TimeRef $ TimeState time
(progress, marking') <- stepPN pn marking
return (not progress, marking')
run _ marking [] = return marking
run pn marking (time:times) = do
(stop, marking') <- step pn marking time
if stop
then return marking'
else run pn marking' times
dotGraphGroupNodesByLabel :: Maybe Int -> [String] -> DotGraph -> DotGraph
dotGraphGroupNodesByLabel maybeMaxDepth prefix graph@(DotGraph nvs name nodes edges subGraphs)
| isNothing maybeMaxDepth || maxDepth > 0 = DotGraph nvs name nonSubNodes edges subGraphs'
| otherwise = graph
where
Just maxDepth = maybeMaxDepth
nextDepth = maybeMaxDepth >>= return . (+ (-1))
level = length prefix
subGraphs' = subGraphs ++ map (uncurry (dotGraphGroupNodesByLabel nextDepth)) newSubgraphs
newSubgraphs = mapMaybe makeSubgraph groupedNodes
nonSubNodes = fromMaybe [] $ lookup "" groupedNodes
makeSubgraph ("", _) = Nothing
makeSubgraph (label, nodes) = Just (prefix', DotGraph ("cluster_" ++ escGraphName prefixLabel)
[("label", prefixLabel)] nodes [] [])
where
prefix' = prefix ++ [label]
prefixLabel = joinWith "." prefix'
groupedNodes = groupByName (nthNameElem level . getLabel) nodes
groupByName f nodes = map cleanUp $ sortAndGroupByElem fst prefices
where
cleanUp (name, elems) = (name, map snd elems)
prefices = map (\thing -> (f thing, thing)) nodes
getLabel node = fromMaybe "" $ liftM snd $ find ((== "label") . fst) $ dotNodeNVs node
nthNameElem :: Int -> String -> String
nthNameElem n name
| n >= (nameLength - 1) = "" -- last or further component
| otherwise = nameParts !! n
where
nameParts = splitWith "." name
nameLength = length nameParts
escGraphName :: String -> String
escGraphName name = concatMap escChar name
where
escChar c | isAlphaNum c = [c]
escChar _ = "_" -- X" ++ show (toEnum c :: Int)
pnToDot :: Monad m => Maybe (Marking value) -> String -> PN m value -> DotGraph
pnToDot maybeMarking name pn = DotGraph name
[("size", "7x10"), {- ("ratio", "0.7"), -} ("pagedir", "TL"), ("fontname", "Helvetica")] ([
DotNode "node" [("fontname", "Helvetica")],
DotNode "edge" [("fontname", "Helvetica"), ("fontsize", "8")]] ++
mapMaybe (uncurry makePlaceNode) (DM.assocs allPlaces) ++
map (uncurry makeTransNode) (DM.assocs allTrans)
)
edges []
where
marking = if isJust maybeMarking
then fromJust maybeMarking
else pnInitialMarking pn
showPlace placeNo = "P" ++ show placeNo
showTrans transNo = "T" ++ show transNo
isReducablePlace placeNo = fromMaybe False $ do
(ins, outs) <- DM.lookup placeNo placesToTrans
return $ case (ins, outs) of
([_], [_]) -> null $ marking DM.! placeNo
_ -> False
makePlaceNode placeNo place
| isReducablePlace placeNo = Nothing
| otherwise = Just $ DotNode (showPlace placeNo) [
("label", joinLabel (placeLabel place) ++ (case initialMarking of
0 -> ""
1 -> ""
_ -> " " ++ show initialMarking)),
("style", if initialMarking > 0
then "solid"
else case DM.lookup placeNo placesToTrans of
Just ([], _) -> "dotted"
Just (_, []) -> "dotted"
Nothing -> "dotted"
Just _ -> "solid"),
("shape", "ellipse"),
("penwidth", case initialMarking of
1 -> "3"
_ -> "1")]
where
initialMarking = length $ marking DM.! placeNo
escapeLabel = escapeString "|{}<>"
makeTransNode transNo trans = DotNode (showTrans transNo)
[("label", escapeLabel label), ("shape", "rectangle")]
where
label
| null exprLabels = joinLabel $ transLabel trans
| otherwise = joinLabel (transLabel trans) ++ ": " ++ exprLabels
exprLabels = (case transCondition trans of
Just cond -> "if " ++ showPNExpr 0 cond "" ++
(if null assignments then "" else " then ")
_ -> "")
++ showListWithSep (showString ",") id assignments ""
assignments = mapMaybe showExpr $ zip [(0::Int)..] $ transExprs trans
showExpr (_, PNLiteral NoSimValue) = Nothing
showExpr (i, expr) = Just $ showChar 'o' . shows i . showString "=" . showPNExpr 0 expr
allPlaces = pnPlaces pn
allTrans = pnTrans pn
placesToTrans = pnPlacesToTrans pn
edges = concatMap makeEdge $ DM.assocs placesToTrans
where
getPlaceArcIndex getPlaces placeNo transNo = fromJust $ findIndex (== placeNo) $
getPlaces (allTrans DM.! transNo)
inLabel placeNo transNo = "i" ++ show (getPlaceArcIndex transInPlaces placeNo transNo)
outLabel placeNo transNo = "o" ++ show (getPlaceArcIndex transOutPlaces placeNo transNo)
colour placeNo = case placeType (allPlaces DM.! placeNo) of
BlackPlaceType -> colourToRGB black
NumericPlaceType width -> colourToRGB $ colours !! (min (intWidth width) 9)
colourToRGB (r, g, b) = "#" ++ component r ++ component g ++ component b
where component c = numberToString (Bits 8) (floor (c * 0xFF)) 16 0 True
makeEdge (placeNo, (inTrans, outTrans))
| isReducablePlace placeNo = [DotEdge
(showTrans (head inTrans)) (showTrans (head outTrans))
[("label", joinLabel (placeLabel (allPlaces DM.! placeNo))),
("headlabel", inLabel placeNo (head outTrans)),
("taillabel", outLabel placeNo (head inTrans)),
("color", colour placeNo)]]
| otherwise =
(map (\from -> DotEdge (showTrans from) (showPlace placeNo)
[("taillabel", outLabel placeNo from), ("color", colour placeNo)])
inTrans) ++
(map (\to -> DotEdge (showPlace placeNo) (showTrans to)
[("headlabel", inLabel placeNo to), ("color", colour placeNo)])
outTrans)
pnPlacesToTrans :: Monad m => PN m value -> DM.Map PlaceNo ([TransNo], [TransNo])
pnPlacesToTrans pn = DM.fromList $ map combine $ sortAndGroupByElem fst $
concatMap transToIOPlaces $ DM.assocs $ pnTrans pn
where
combine (placeNo, trans) = (placeNo, (concat ins, concat outs))
where (ins, outs) = unzip $ map snd trans
transToIOPlaces (transNo, trans) =
(map (\placeNo -> (placeNo, ([], [transNo]))) $ transInPlaces trans) ++
(map (\placeNo -> (placeNo, ([transNo], []))) $ transOutPlaces trans)
pnTestCard :: FilePath -> IO ()
pnTestCard file = writeGraphsToFile file $ map (dotGraphGroupNodesByLabel Nothing [] . uncurry (pnToDot Nothing))
testPNs
testPNs :: [(String, PN SimFlow SimValue)]
testPNs = map runGraph graphs
where
runGraph (name, mk) = (name, snd $ runMkPNMonad0 mk)
slice08 = 0 +: 8
graphs = [
("A2", do
i0 <- withLabel "inp0" $ chan 8 0
i1 <- withLabel "inp1" $ chan 8 0
o <- withLabel "out" $ chan 8 0
teakA 8 [i0, i1] o),
("M2", do
i0 <- withLabel "inp0" $ chan 8 0
i1 <- withLabel "inp1" $ chan 8 0
o <- withLabel "out" $ chan 8 0
teakM 8 [i0, i1] o),
("J2", do
i0 <- withLabel "inp0" $ chan 8 0
i1 <- withLabel "inp1" $ chan 8 0
o <- withLabel "out" $ chan 16 0
teakJ [8, 8] [i0, i1] o),
("V23", do
wg0 <- withLabel "wg0" $ chan 8 0
wd0 <- withLabel "wd0" $ chan 0 0
wg1 <- withLabel "wg1" $ chan 8 0
wd1 <- withLabel "wd1" $ chan 0 0
rg0 <- withLabel "rg0" $ chan 0 0
rd0 <- withLabel "rd0" $ chan 8 0
rg1 <- withLabel "rg1" $ chan 0 0
rd1 <- withLabel "rd1" $ chan 8 0
rg2 <- withLabel "rg2" $ chan 0 0
rd2 <- withLabel "rd2" $ chan 8 0
teakV 8 [slice08, slice08] [slice08, slice08, slice08]
[wg0,wg1] [wd0,wd1] [rg0,rg1,rg2] [rd0,rd1,rd2]),
("V11", do
wg0 <- withLabel "wg0" $ chan 8 0
wd0 <- withLabel "wd0" $ chan 0 0
rg0 <- withLabel "rg0" $ chan 0 0
rd0 <- withLabel "rd0" $ chan 8 0
teakV 8 [slice08] [slice08] [wg0] [wd0] [rg0] [rd0]),
("S2", do
i <- withLabel "inp" $ chan 8 0
o0 <- withLabel "out0" $ chan 8 0
o1 <- withLabel "out1" $ chan 8 0
teakS 8 slice08 [slice08, slice08] [[Imp 0 0], [Imp 0 0]] i [o0, o1]),
("F2", do
i <- withLabel "inp" $ chan 8 0
o0 <- withLabel "out0" $ chan 8 0
o1 <- withLabel "out1" $ chan 8 0
teakF [slice08, slice08] i [o0, o1]),
("R", do
c <- withLabel "out" $ chan 0 0
teakR c),
("I", do
inp <- withLabel "inp" $ chan 0 0
out <- withLabel "out" $ chan 0 0
teakI inp out),
("O", do
inp <- withLabel "inp" $ chan 0 0
out <- withLabel "out" $ chan 8 0
teakO [(1, TeakOConstant 8 0)] inp out),
("C", do
withLabel "C0" $ teakLink "C" $ NetworkLink 0 8 $ HalfBuffer 0
withLabel "C1" $ teakLink "C" $ NetworkLink 0 8 $ HalfBuffer 1
withLabel "C2" $ teakLink "C" $ NetworkLink 0 8 $ HalfBuffer 2
return ())
]
writeHLNet :: Monad m => FilePath -> String -> PN m SimValue -> IO ()
writeHLNet file _partName pn = do
handle <- openFile file WriteMode
hPutStrLn handle "PEP"
hPutStrLn handle "HLNet"
hPutStrLn handle "FORMAT_N"
hPutStrLn handle "PL"
mapM_ (hPutStrLn handle . (flip showPlace) "") $ DM.assocs $ pnPlaces pn
hPutStrLn handle "TR"
mapM_ (hPutStrLn handle . (flip showTrans) "") $ DM.assocs $ pnTrans pn
hPutStrLn handle "TP"
mapM_ (\(transNo, trans) -> mapM' (\(pos, placeNo) ->
hPutStrLn handle $ showTtoP pos transNo placeNo "") $ zip [0..] $ transOutPlaces trans
) $ DM.assocs $ pnTrans pn
hPutStrLn handle "PT"
mapM_ (\(transNo, trans) -> mapM' (\(pos, placeNo) ->
hPutStrLn handle $ showPtoT pos placeNo transNo "") $ zip [0..] $ transInPlaces trans
) $ DM.assocs $ pnTrans pn
hClose handle
where
showPlace (placeNo, place) = shows placeNo . shows (joinLabel (placeLabel place)) .
showString "0@0" .
showString "Z\"" .
(case placeType place of
BlackPlaceType -> showString "{dot}"
NumericPlaceType width -> showString "{0.." . shows ((bit width :: Integer) - 1) . showChar '}'
) .
showString "\"" .
initMarking
where
initMarking = case marking DM.! placeNo of
[] -> id
[value] -> let
markingShows = showChar '"' . showChar '{' . showSimValue value . showChar '}' .
showChar '"'
in showChar 'z' . markingShows . showChar 'y' . markingShows
_ -> error "writeHLNet: can't handle initial marking with >1 token"
showTrans (transNo, trans) = shows transNo . shows (joinLabel (transLabel trans)) .
showString "0@0" .
showString "g\"" . -- tt & " .
(case transCondition trans of
Just cond -> hlShowPNExpr cond . showString " & "
_ -> id) .
(showListWithSep (showString " & ") showExpr $ zip [(0::Int)..] (transExprs trans)) .
showString "\""
where showExpr (i, expr) = showChar 'o' . shows i . showString " = " . hlShowPNExpr expr
showTtoP pos transNo placeNo = shows transNo . showChar '<' . shows placeNo .
showString "p\"o" . shows (pos :: Int) . showString "\""
showPtoT pos placeNo transNo = shows placeNo . showChar '>' . shows transNo .
showString "p\"i" . shows (pos :: Int) . showString "\""
showSimValue NoSimValue = showString "dot"
showSimValue (SimValue int []) = shows int
showSimValue simValue = error $ "writeHLNet: can't print SimValue `" ++ show simValue ++ "'"
marking = pnInitialMarking pn
-- placesToTrans = pnPlacesToTrans pn
| Mahdi89/eTeak | src/SimPN.hs | bsd-3-clause | 54,565 | 0 | 25 | 19,937 | 17,107 | 8,571 | 8,536 | 920 | 20 |
module Main where
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit ((@=?))
import Test.QuickCheck hiding ((.&.))
import PTS.Syntax.Substitution.Tests
import PTS.Syntax.Parser.Tests
import PTS.Syntax.Pretty.Tests
import PTS.File.Tests (testFile)
main = defaultMain Main.tests
tests =
[ PTS.Syntax.Parser.Tests.tests
, PTS.Syntax.Pretty.Tests.tests
, PTS.Syntax.Substitution.Tests.tests
, testFile True ["examples"] "Arithmetics.lpts"
, testFile True ["examples"] "ChurchNumbers.lpts"
, testFile True ["examples"] "Functions.lpts"
, testFile True ["examples"] "Inference.lpts"
, testFile True ["examples"] "Syntax.lpts"
]
| Blaisorblade/pts | src-test/tests.hs | bsd-3-clause | 780 | 0 | 7 | 98 | 205 | 129 | 76 | 20 | 1 |
module QuadraticInterpolation where
import Data.Array.Repa as R
import Data.Array.Repa.Unsafe as R
import qualified Data.Vector.Unboxed as VU
-- Internal Modules
import CommonTypes
import LinearAlgebra
import ReactionCoordinate
-- ==================> <==================
type DeltaQ = Array U DIM2 Double
type GradMtx = Array U DIM2 Double
type HessMtx = Array U DIM2 Double
-- =============> <=================
calcgradQuadratic :: Molecule -> Molecule
calcgradQuadratic mol = undefined
{- let [state1,state2] = getDervEn mol
EnergyDerivatives e1 grad1 hess1 = state1
EnergyDerivatives e2 grad2 hess2 = state2
(Z:.dim) = extent grad1
[gmtx1,gmtx2] = fmap (\x -> R.computeUnboxedS $ reshape (Z:.dim :.1) x) [grad1,grad2]
currentX = R.toUnboxed $ getCoord mol
FC geomFC conex = getFCStruc mol
currentQ = calculateInternalsFC geomFC conex currentX
dq = R.fromUnboxed (Z:.dim :.1) $ VU.zipWith (-) currentQ geomFC
(energy1,gradQ1) = calcQuadraticEnergy dq e1 gmtx1 hess1
(energy2,_gradQ2) = calcQuadraticEnergy dq e2 gmtx2 hess2
newForce = VU.fromUnboxed (extent gradQ1) $ VU.map () $ R.toUnboxed gradQ1
in mol{getForce = newForce, getEnergy = [energy1,energy2]} -}
calcQuadraticEnergy :: DeltaQ -> Energy -> GradMtx -> HessMtx -> (Double,Grad)
calcQuadraticEnergy deltaQ e0 grad0 hess =
let energy = e0+ termGrad + 0.5*termHess
calcgrad = R.zipWith (+) grad0 gradInt
grad = computeUnboxedS $ R.reshape (Z:. dim) calcgrad
in (energy,grad)
where gradInt = mmultS hess deltaQ
termGrad = sumAllS $ mmultS deltaT grad0
termHess = sumAllS $ mmultS deltaT $ gradInt
(Z:.dim:.1) = extent deltaQ
deltaT = computeUnboxedS $ reshape (Z:.1:.dim) deltaQ | felipeZ/Dynamics | src/QuadraticInterpolation.hs | bsd-3-clause | 1,789 | 0 | 12 | 378 | 295 | 165 | 130 | 23 | 1 |
--
-- Copyright (c) 2015 Assured Information Security, Inc. <[email protected]>
-- Copyright (c) 2014 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards, ViewPatterns #-}
-- description: ac97 is now supported in windows guests with latest openxt tools
-- date: 04/30/2015
module Migrations.M_24 (migration) where
import UpgradeEngine
import Data.List (foldl')
import ShellTools
import Control.Monad
import Directory
migration = Migration {
sourceVersion = 24
, targetVersion = 25
, actions = act
}
act :: IO ()
act = updateAudioBackend
updateAudioBackend = xformVmJSON xform where
xform tree = case jsGet "/os" tree of
Just (jsUnboxString -> s)
| ( s == "windows"
|| s == "windows8" ) -> jsSet "/config/sound" (jsBoxString "ac97") tree
_ -> tree
| eric-ch/manager | upgrade-db/Migrations/M_24.hs | gpl-2.0 | 1,558 | 0 | 16 | 333 | 179 | 107 | 72 | 19 | 2 |
import System.Plugins
import API
src = "../Plugin.hs"
wrap = "../Wrapper.hs"
apipath = "../api"
main = do status <- make src ["-i"++apipath]
case status of
MakeSuccess _ _ -> f
MakeFailure e -> mapM_ putStrLn e
where f = do v <- pdynload "../Plugin.o" ["../api"] [] "API.Interface" "resource"
case v of
LoadSuccess _ a -> let fn = function a in putStrLn $ show $ 1 `fn` 2
_ -> putStrLn "wrong types"
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/testsuite/pdynload/spj3/prog/Main.hs | bsd-3-clause | 523 | 0 | 16 | 195 | 165 | 81 | 84 | 13 | 3 |
{-|
Module : Unicorn.Hook
Description : Unicorn hooks.
Copyright : (c) Adrian Herrera, 2016
License : GPL-2
Insert hook points into the Unicorn emulator engine.
-}
module Unicorn.Hook
( -- * Hook types
Hook
, MemoryHookType(..)
, MemoryEventHookType(..)
, MemoryAccess(..)
-- * Hook callbacks
, CodeHook
, InterruptHook
, BlockHook
, InHook
, OutHook
, SyscallHook
, MemoryHook
, MemoryReadHook
, MemoryWriteHook
, MemoryEventHook
-- * Hook callback management
, codeHookAdd
, interruptHookAdd
, blockHookAdd
, inHookAdd
, outHookAdd
, syscallHookAdd
, memoryHookAdd
, memoryEventHookAdd
, hookDel
) where
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Either (hoistEither, left, right)
import Foreign
import Unicorn.Internal.Core
import Unicorn.Internal.Hook
import qualified Unicorn.CPU.X86 as X86
-------------------------------------------------------------------------------
-- Hook callback management (registration and deletion)
-------------------------------------------------------------------------------
-- | Register a callback for a code hook event.
codeHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> CodeHook a -- ^ Code hook callback
-> a -- ^ User-defined data. This will be passed to
-- the callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error'
-- on failure
codeHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalCodeHook callback
getResult $ ucHookAdd uc HookCode funPtr userDataPtr begin end
hoistEither result
-- | Register a callback for an interrupt hook event.
interruptHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> InterruptHook a -- ^ Interrupt callback
-> a -- ^ User-defined data. This will be passed
-- to the callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or 'Error'
-- on failure
interruptHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalInterruptHook callback
getResult $ ucHookAdd uc HookIntr funPtr userDataPtr begin end
hoistEither result
-- | Register a callback for a block hook event.
blockHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> BlockHook a -- ^ Block callback
-> a -- ^ User-defined data. This will be passed to
-- the callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error'
-- on failure
blockHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalBlockHook callback
getResult $ ucHookAdd uc HookBlock funPtr userDataPtr begin end
hoistEither result
-- | Register a callback for an IN instruction hook event (X86).
inHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> InHook a -- ^ IN instruction callback
-> a -- ^ User-defined data. This will be passed to the
-- callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error' on
-- failure
inHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalInHook callback
getResult $ ucInsnHookAdd uc HookInsn funPtr userDataPtr begin end
X86.In
hoistEither result
-- | Register a callback for an OUT instruction hook event (X86).
outHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> OutHook a -- ^ OUT instruction callback
-> a -- ^ User-defined data. This will be passed to the
-- callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error' on
-- failure
outHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalOutHook callback
getResult $ ucInsnHookAdd uc HookInsn funPtr userDataPtr begin end
X86.Out
hoistEither result
-- | Register a callback for a SYSCALL instruction hook event (X86).
syscallHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> SyscallHook a -- ^ SYSCALL instruction callback
-> a -- ^ User-defined data. This will be passed to
-- the callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error'
-- on failure
syscallHookAdd uc callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalSyscallHook callback
getResult $ ucInsnHookAdd uc HookInsn funPtr userDataPtr begin end
X86.Syscall
hoistEither result
-- | Register a callback for a valid memory access event.
memoryHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> MemoryHookType -- ^ A valid memory access (e.g. read, write,
-- etc.) to trigger the callback on
-> MemoryHook a -- ^ Memory access callback
-> a -- ^ User-defined data. This will be passed to
-- the callback function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or an 'Error'
-- on failure
memoryHookAdd uc memHookType callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalMemoryHook callback
getResult $ ucHookAdd uc memHookType funPtr userDataPtr begin end
hoistEither result
-- | Register a callback for an invalid memory access event.
memoryEventHookAdd :: Storable a
=> Engine -- ^ 'Unicorn' engine handle
-> MemoryEventHookType -- ^ An invalid memory access (e.g.
-- read, write, etc.) to trigger
-- the callback on
-> MemoryEventHook a -- ^ Invalid memory access callback
-> a -- ^ User-defined data. This will
-- be passed to the callback
-- function
-> Word64 -- ^ Start address
-> Word64 -- ^ End address
-> Emulator Hook -- ^ The hook handle on success, or
-- an 'Error' on failure
memoryEventHookAdd uc memEventHookType callback userData begin end = do
result <- lift . alloca $ \userDataPtr -> do
poke userDataPtr userData
funPtr <- marshalMemoryEventHook callback
getResult $ ucHookAdd uc memEventHookType funPtr userDataPtr begin end
hoistEither result
-- | Unregister (remove) a hook callback.
hookDel :: Engine -- ^ 'Unicorn' engine handle
-> Hook -- ^ 'Hook' handle
-> Emulator () -- ^ 'ErrOk' on success, or other value on failure
hookDel uc hook = do
err <- lift $ ucHookDel uc hook
if err == ErrOk then
right ()
else
left err
-------------------------------------------------------------------------------
-- Helper functions
-------------------------------------------------------------------------------
-- Takes the tuple returned by `ucHookAdd`, an IO (Error, Hook), and
-- returns either a `Right Hook` if no error occurred or a `Left Error` if an
-- error occurred
getResult :: IO (Error, Hook)
-> IO (Either Error Hook)
getResult =
liftM (uncurry checkResult)
where checkResult err hook =
if err == ErrOk then
Right hook
else
Left err
| eltongo/unicorn | bindings/haskell/src/Unicorn/Hook.hs | gpl-2.0 | 9,500 | 0 | 14 | 3,546 | 1,346 | 705 | 641 | 157 | 2 |
{-|
Module : Util.Net
Description : Utilities for Network IO.
License : BSD3
Maintainer : The Idris Community.
-}
module Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) where
import Control.Exception (bracketOnError)
import Network.Socket
-- Copied from upstream impl of listenOn
-- bound to localhost interface instead of iNADDR_ANY
listenOnLocalhost :: PortNumber -> IO Socket
listenOnLocalhost port = do
let hints = defaultHints { addrSocketType = Stream }
localhost:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just $ show port)
bracketOnError
(socket AF_INET Stream defaultProtocol)
(close)
(\sock -> do
setSocketOption sock ReuseAddr 1
bind sock (addrAddress localhost)
listen sock maxListenQueue
return sock
)
listenOnLocalhostAnyPort :: IO (Socket, PortNumber)
listenOnLocalhostAnyPort = do
let hints = defaultHints { addrSocketType = Stream }
localhost:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "0")
bracketOnError
(socket AF_INET Stream defaultProtocol)
(close)
(\sock -> do
setSocketOption sock ReuseAddr 1
bind sock (addrAddress localhost)
listen sock maxListenQueue
port <- socketPort sock
return (sock, port)
)
| kojiromike/Idris-dev | src/Util/Net.hs | bsd-3-clause | 1,325 | 0 | 14 | 326 | 335 | 166 | 169 | 28 | 1 |
{-# OPTIONS_GHC -fwarn-redundant-constraints #-}
module T9973 where
duplicateDecl :: (Eq t) => t -> IO ()
-- #9973 was a bogus "redundant constraint" here
duplicateDecl sigs
= do { newSpan <- return typeSig
-- **** commenting out the next three lines causes the original warning to disappear
; let rowOffset = case typeSig of { _ -> 1 }
; undefined }
where
typeSig = definingSigsNames sigs
definingSigsNames :: (Eq t) => t -> ()
definingSigsNames x = undefined
where
_ = x == x -- Suppress the complaint on this
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T9973.hs | bsd-3-clause | 561 | 0 | 12 | 140 | 127 | 69 | 58 | 11 | 1 |
main :: IO ()
main = main' ()
where
main' _ = main >> main' ()
| wxwxwwxxx/ghc | testsuite/tests/rts/T9579/StackOverflow.hs | bsd-3-clause | 69 | 0 | 9 | 22 | 40 | 19 | 21 | 3 | 1 |
{-# LANGUAGE DoRec #-}
module Main where
main = do { x <- foo; print x }
foo :: IO Int
foo = do rec
a1 <- return a2
a2 <- return a3
a3 <- return a4
a4 <- return a5
a5 <- return b1
b1 <- return b2
b2 <- return b3
b3 <- return b4
b4 <- return b5
b5 <- return c1
c1 <- return c2
c2 <- return c3
c3 <- return c4
c4 <- return c5
c5 <- return d1
d1 <- return d2
d2 <- return d3
d3 <- return d4
d4 <- return d5
d5 <- return a1x
a1x <- return a2x
a2x <- return a3x
a3x <- return a4x
a4x <- return a5x
a5x <- return b1x
b1x <- return b2x
b2x <- return b3x
b3x <- return b4x
b4x <- return b5x
b5x <- return c1x
c1x <- return c2x
c2x <- return c3x
c3x <- return c4x
c4x <- return c5x
c5x <- return d1x
d1x <- return d2x
d2x <- return d3x
d3x <- return d4x
d4x <- return d5x
d5x <- return a1y
a1y <- return a2y
a2y <- return a3y
a3y <- return a4y
a4y <- return a5y
a5y <- return b1y
b1y <- return b2y
b2y <- return b3y
b3y <- return b4y
b4y <- return b5y
b5y <- return c1y
c1y <- return c2y
c2y <- return c3y
c3y <- return c4y
c4y <- return c5y
c5y <- return d1y
d1y <- return d2y
d2y <- return d3y
d3y <- return d4y
d4y <- return d5y
d5y <- return a1z
a1z <- return a2z
a2z <- return a3z
a3z <- return a4z
a4z <- return a5z
a5z <- return b1z
b1z <- return b2z
b2z <- return b3z
b3z <- return b4z
b4z <- return b5z
b5z <- return c1z
c1z <- return c2z
c2z <- return c3z
c3z <- return c4z
c4z <- return c5z
c5z <- return d1z
d1z <- return d2z
d2z <- return d3z
d3z <- return d4z
d4z <- return d5z
d5z <- return 1
return a4
| wxwxwwxxx/ghc | testsuite/tests/deSugar/should_run/T5742.hs | bsd-3-clause | 2,578 | 0 | 10 | 1,416 | 848 | 345 | 503 | 86 | 1 |
module ShouldFail where
class A a where
op1 :: a -> a
instance A (a,(b,c)) where
op1 a = a
| urbanslug/ghc | testsuite/tests/typecheck/should_fail/tcfail047.hs | bsd-3-clause | 95 | 0 | 7 | 24 | 50 | 28 | 22 | 5 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Tests.Sodium.Hash.Sha512 where
import Tests.Sodium.Hash.Common
import Crypto.Sodium.Hash.Sha512
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.TH
case_digestBytes :: Assertion
case_digestBytes = 64 @=? digestBytes
case_test_vector_1 :: Assertion
case_test_vector_1 = testVector sha512
-- corresponding to tests/hash.c, tests/hash2.cpp,
-- tests/hash3.c and tests/hash4.cpp from NaCl
[ 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0xa ]
[ 0x24, 0xf9, 0x50, 0xaa, 0xc7, 0xb9, 0xea, 0x9b
,0x3c, 0xb7, 0x28, 0x22, 0x8a, 0x0c, 0x82, 0xb6
,0x7c, 0x39, 0xe9, 0x6b, 0x4b, 0x34, 0x47, 0x98
,0x87, 0x0d, 0x5d, 0xae, 0xe9, 0x3e, 0x3a, 0xe5
,0x93, 0x1b, 0xaa, 0xe8, 0xc7, 0xca, 0xcf, 0xea
,0x4b, 0x62, 0x94, 0x52, 0xc3, 0x80, 0x26, 0xa8
,0x1d, 0x13, 0x8b, 0xc7, 0xaa, 0xd1, 0xaf, 0x3e
,0xf7, 0xbf, 0xd5, 0xec, 0x64, 0x6d, 0x6c, 0x28]
case_SHA512ShortMsg :: Assertion
case_SHA512ShortMsg = testNistVectors sha512
"test/testvectors/SHA512ShortMsg.rsp"
case_SHA512LongMsg :: Assertion
case_SHA512LongMsg = testNistVectors sha512
"test/testvectors/SHA512LongMsg.rsp"
tests :: TestTree
tests = $(testGroupGenerator)
| dnaq/crypto-sodium | test/Tests/Sodium/Hash/Sha512.hs | mit | 1,557 | 0 | 6 | 483 | 335 | 217 | 118 | 30 | 1 |
import FPPrac
import RoseTree
data Tree1c = Leaf1c | Node1c Number Tree1c Tree1c
pp1c :: Tree1c -> RoseTree
pp1c (Node1c i t1 t2) = RoseNode (show i) [(pp1c t1), (pp1c t2)]
pp1c Leaf1c = RoseNode "" []
isBalanced :: Tree1c -> Bool
isBalanced (Node1c _ t1 t2) = (isBalanced t1) && (isBalanced t2) && abs(depth t1 - depth t2) <= 1
isBalanced Leaf1c = True
depth :: Tree1c -> Int
depth (Node1c _ t1 t2) = 1 + maximum [(depth t1), (depth t2)]
depth Leaf1c = 1
-- unbalanced: Node1c 10 (Leaf1c) (Node1c 5 (Node1c 8 Leaf1c Leaf1c) Leaf1c)
-- balanced: Node1c 10 (Node1c 3 Leaf1c Leaf1c) (Node1c 5 (Node1c 8 Leaf1c Leaf1c) Leaf1c)
makeList :: Tree1c -> [Number]
makeList (Node1c i t1 t2) = (makeList t1) ++ [i] ++ (makeList t2)
makeList (Leaf1c) = []
treeToBalancedTree :: Tree1c -> Tree1c
treeToBalancedTree tree = treeToBalancedTree'(makeList tree)
treeToBalancedTree' :: [Number] -> Tree1c
treeToBalancedTree' (x:xs) = Node1c x (treeToBalancedTree' (take (1 + ((length xs) `quot` 2)) xs)) (treeToBalancedTree' (drop (1 + ((length xs) `quot` 2)) xs))
treeToBalancedTree' [] = Leaf1c
| tcoenraad/functioneel-programmeren | practica/serie3/8.balance-tree.hs | mit | 1,087 | 0 | 15 | 187 | 439 | 230 | 209 | 20 | 1 |
-- | Types and functions for dealing with the API client itself.
module Strive.Client
( Client (..)
, buildClient
) where
import Data.ByteString.Lazy (ByteString)
import Data.Text (Text, unpack)
import Network.HTTP.Client.Conduit (newManager)
import Network.HTTP.Conduit (Request, Response, httpLbs)
-- | Strava V3 API client.
data Client = Client
{ client_accessToken :: String
, client_requester :: Request -> IO (Response ByteString)
}
instance Show Client where
show client = concat
[ "Client {client_accessToken = "
, show (client_accessToken client)
, "}"
]
-- | Build a new client using the default HTTP manager to make requests.
buildClient :: Maybe Text -> IO Client
buildClient accessToken = do
manager <- newManager
return Client
{ client_accessToken = maybe "" unpack accessToken
, client_requester = flip httpLbs manager
}
| bitemyapp/strive | library/Strive/Client.hs | mit | 888 | 0 | 12 | 175 | 207 | 117 | 90 | 21 | 1 |
module AI.Funn.CL.DSL.AST where
import Data.List.Split
import Data.List
type Name = String
type TypeDecl = String
data Expr = ExprLit String
| ExprVar Name
| ExprIndex Name Expr
| ExprCall Name [Expr]
| ExprOp Expr Name Expr
| ExprCond Expr Expr Expr
deriving (Show)
data Decl = Decl TypeDecl Name
deriving (Show)
data Stmt = StmtAssign Expr Expr
| StmtDeclare Decl
| StmtDeclareAssign Decl Expr
| StmtForEach Name Expr Expr Block
deriving (Show)
data Block = Block [Stmt]
deriving (Show)
data Kernel = Kernel Name [Decl] Block
deriving (Show)
indent :: Int -> String -> String
indent n str = intercalate "\n" (fmap go ls)
where
ls = splitOn "\n" str
go line
| null line = line
| otherwise = replicate n ' ' ++ line
printExpr :: Expr -> String
printExpr (ExprLit s) = s
printExpr (ExprVar v) = v
printExpr (ExprIndex v i) = v ++ "[" ++ printExpr i ++ "]"
printExpr (ExprCall f args) = f ++ "(" ++ intercalate ", " (map printExpr args) ++ ")"
printExpr (ExprOp a x b) = "(" ++ printExpr a ++ " " ++ x ++ " " ++ printExpr b ++ ")"
printExpr (ExprCond e a b) = "(" ++ printExpr e ++ " ? " ++ printExpr a ++ " : " ++ printExpr b ++ ")"
printDecl :: Decl -> String
printDecl (Decl t n) = t ++ " " ++ n
printStmt :: Stmt -> String
printStmt (StmtAssign v e) = printExpr v ++ " = " ++ printExpr e ++ ";"
printStmt (StmtDeclare d) = printDecl d ++ ";"
printStmt (StmtDeclareAssign d e) = printDecl d ++ " = " ++ printExpr e ++ ";"
printStmt (StmtForEach name start end body) = "for ("
++ name ++ " = " ++ printExpr start ++ "; "
++ name ++ " < " ++ printExpr end ++ "; "
++ name ++ "++) {\n"
++ indent 2 (printBlock body)
++ "}"
printBlock :: Block -> String
printBlock (Block statements) = unlines (map printStmt statements)
printKernel :: Kernel -> String
printKernel (Kernel name args body) =
"__kernel void " ++ name
++ "(" ++ intercalate ", " (map printDecl args) ++ ") {\n"
++ indent 2 (printBlock body)
++ "}"
| nshepperd/funn | AI/Funn/CL/DSL/AST.hs | mit | 2,277 | 0 | 16 | 742 | 805 | 410 | 395 | 56 | 1 |
{-# LANGUAGE NoImplicitPrelude, DataKinds, FlexibleContexts,
TypeFamilies, DeriveDataTypeable, TemplateHaskell #-}
{-# OPTIONS_GHC -Wall #-}
module LLVM.General.Util.Module (
ModuleBuilder(),
ModuleAST,
moduleFromAST, moduleFromBitcode, moduleFromLLVMAssembly,
moduleFromLLVMAssemblyFile, moduleFromBitcodeFile, linkModules,
transformModule,
studyModule,
moduleAST, moduleBitcode, moduleTargetAssembly, moduleObject,
writeLLVMAssemblyToFile, writeBitcodeToFile, writeTargetAssemblyToFile,
writeObjectToFile,
ExecutableModule(),
jitCompile, jitGetFunction
) where
import ClassyPrelude
import Data.Data(Data)
import Foreign.Ptr(FunPtr)
import qualified LLVM.General.Analysis as LL
import qualified LLVM.General.AST as AST
import qualified LLVM.General.ExecutionEngine as LL
import qualified LLVM.General.Module as LL
import qualified LLVM.General.PassManager as LL
import LLVM.General.Util.Internal.Diagnostic
import LLVM.General.Util.Internal.L
import LLVM.General.Util.PassSetSpec
import LLVM.General.Util.Platform
import LLVM.General.Util.Settings
import qualified LLVM.General.CodeGenOpt as CG
import qualified System.IO as IO
import Control.Monad.Base(MonadBase(..))
import Control.Monad.Trans.Control(MonadBaseControl(..), liftBaseOp)
type ModuleIO = LL.Module
type ModuleAST = AST.Module
data ModuleBuilder = MBAST ModuleAST
| MBBitcode String ByteString
| MBVerifiedBitcode ByteString
| MBAssembly String
| MBAssemblyFile IO.FilePath
| MBBitcodeFile IO.FilePath
| MBLink ModuleBuilder ModuleBuilder
| MBTransform PassSetSpec ModuleBuilder
deriving (Eq,Show,Typeable,Data)
moduleFromAST :: ModuleAST -> ModuleBuilder
moduleFromAST = MBAST
moduleFromBitcode :: String -> ByteString -> ModuleBuilder
moduleFromBitcode = MBBitcode
moduleFromLLVMAssembly :: String -> ModuleBuilder
moduleFromLLVMAssembly = MBAssembly
moduleFromLLVMAssemblyFile :: IO.FilePath -> ModuleBuilder
moduleFromLLVMAssemblyFile = MBAssemblyFile
moduleFromBitcodeFile :: IO.FilePath -> ModuleBuilder
moduleFromBitcodeFile = MBBitcodeFile
linkModules :: ModuleBuilder -> ModuleBuilder -> ModuleBuilder
linkModules = MBLink
transformModule :: PassSetSpec -> ModuleBuilder -> ModuleBuilder
transformModule = MBTransform
pss :: (MonadBaseControl IO m) => PassSetSpec -> L b m LL.PassSetSpec
pss spec =
do c <- getC
let dl = fromBackendMaybe (lDataLayout c)
let tli = Just $ lLibraryInfo c
let tm = fromBackendMaybe (lTargetMachine c)
case spec of
(PassSetSpec t) ->
return $ LL.PassSetSpec t dl tli tm
(CuratedPassSetSpec ol sl uaat slc uiwt) ->
return $ LL.CuratedPassSetSpec ol sl uaat slc uiwt tli
withModule :: (MonadBaseControl IO m)
=> ModuleBuilder -> (ModuleIO -> L b m a) -> L b m a
withModule builder f =
do ctx <- getContext
case builder of
MBAST ast ->
liftBaseOp
(catchCallerError 'LL.withModuleFromAST $
LL.withModuleFromAST ctx ast)
(\moduleIO -> do liftBase $ errorToIO 'LL.verify $ LL.verify moduleIO
f moduleIO)
MBBitcode s bs ->
liftBaseOp
(catchCallerError 'LL.withModuleFromBitcode $
LL.withModuleFromBitcode ctx (s,bs))
(\moduleIO -> do liftBase $ errorToIO 'LL.verify $ LL.verify moduleIO
f moduleIO)
MBVerifiedBitcode bs ->
liftBaseOp
(catchCallerError 'LL.withModuleFromBitcode $
LL.withModuleFromBitcode ctx ("",bs)) f
MBAssembly asm ->
liftBaseOp
(catchCallerDiag 'LL.withModuleFromLLVMAssembly $
LL.withModuleFromLLVMAssembly ctx asm)
(\moduleIO -> do liftBase $ errorToIO 'LL.verify $ LL.verify moduleIO
f moduleIO)
MBAssemblyFile file ->
liftBaseOp
(catchCallerDiag 'LL.withModuleFromLLVMAssembly $
LL.withModuleFromLLVMAssembly ctx (LL.File file))
(\moduleIO -> do liftBase $ errorToIO 'LL.verify $ LL.verify moduleIO
f moduleIO)
MBBitcodeFile file ->
liftBaseOp
(catchCallerError 'LL.withModuleFromBitcode $
LL.withModuleFromBitcode ctx (LL.File file))
(\moduleIO -> do liftBase $ errorToIO 'LL.verify $ LL.verify moduleIO
f moduleIO)
MBLink mb1 mb2 ->
withModule mb1
(\mod1 ->
withModule mb2
(\mod2 ->
do liftBase $ errorToIO 'LL.linkModules $
LL.linkModules False mod1 mod2
f mod1))
MBTransform spec mb ->
withModule mb
(\mod1 ->
do spec' <- pss spec
liftBaseOp
(catchCaller 'LL.withPassManager $ LL.withPassManager spec')
(\pm ->
do _ <- catchInternal 'LL.runPassManager $
liftBase $ LL.runPassManager pm mod1
f mod1))
studyModule :: (MonadBaseControl IO m)
=> ModuleBuilder -> L b m ModuleBuilder
studyModule builder =
withModule builder (liftBase . liftM MBVerifiedBitcode . LL.moduleBitcode)
moduleAST :: (MonadBaseControl IO m) => ModuleBuilder -> L b m ModuleAST
moduleAST builder = withModule builder (liftBase . LL.moduleAST)
moduleBitcode :: (MonadBaseControl IO m) => ModuleBuilder -> L b m ByteString
moduleBitcode builder = withModule builder (liftBase . LL.moduleBitcode)
moduleTargetAssembly :: (MonadBaseControl IO m, IsBackendVoid b ~ False)
=> ModuleBuilder -> L b m String
moduleTargetAssembly builder =
do tm <- getTargetMachine
withModule builder $
liftBase . errorToIO 'LL.moduleTargetAssembly .
LL.moduleTargetAssembly tm
moduleObject :: (MonadBaseControl IO m, IsBackendVoid b ~ False)
=> ModuleBuilder -> L b m ByteString
moduleObject builder =
do tm <- getTargetMachine
withModule builder $
liftBase . errorToIO 'LL.moduleObject . LL.moduleObject tm
writeLLVMAssemblyToFile :: (MonadBaseControl IO m)
=> IO.FilePath -> ModuleBuilder -> L b m ()
writeLLVMAssemblyToFile path builder =
withModule builder $
liftBase . errorToIO 'LL.writeLLVMAssemblyToFile .
LL.writeLLVMAssemblyToFile (LL.File path)
writeBitcodeToFile :: (MonadBaseControl IO m)
=> IO.FilePath -> ModuleBuilder -> L b m ()
writeBitcodeToFile path builder =
withModule builder $
liftBase . errorToIO 'LL.writeBitcodeToFile .
LL.writeBitcodeToFile (LL.File path)
writeTargetAssemblyToFile :: (MonadBaseControl IO m, IsBackendVoid b ~ False)
=> IO.FilePath -> ModuleBuilder -> L b m ()
writeTargetAssemblyToFile path builder =
do tm <- getTargetMachine
withModule builder $
liftBase . errorToIO 'LL.writeTargetAssemblyToFile .
LL.writeTargetAssemblyToFile tm (LL.File path)
writeObjectToFile :: (MonadBaseControl IO m, IsBackendVoid b ~ False)
=> IO.FilePath -> ModuleBuilder -> L b m ()
writeObjectToFile path builder =
do tm <- getTargetMachine
withModule builder $
liftBase . errorToIO 'LL.writeObjectToFile .
LL.writeObjectToFile tm (LL.File path)
newtype ExecutableModule = ExecutableModule (LL.ExecutableModule LL.MCJIT)
optNum :: OptimizationLevel -> Word
-- Using llvm-general original constructors rather than
-- llvm-general-util's preferred synonyms in order to prevent a spurious
-- warning about inexhaustive patterns. See GHC ticket #8779.
optNum CG.None = 0
optNum CG.Less = 1
optNum CG.Default = 2
optNum CG.Aggressive = 3
jitCompile :: (MonadBaseControl IO m)
=> ModuleBuilder -> (ExecutableModule -> L b m a) -> L b m a
jitCompile mb f =
do maybeSettings <- getSettingsMaybe
context <- getContext
let (optLevel, model, noFpe, enableFis) =
case maybeSettings of
Just settings ->
(Just $ optNum $ settingsOptimizationLevel settings,
Just $ settingsCodeModel settings,
Just $ noFramePointerElimination $ settingsOptions settings,
Just $ enableFastInstructionSelection $
settingsOptions settings)
Nothing -> (Nothing, Nothing, Nothing, Nothing)
withModule mb
(\mod1 ->
liftBaseOp
(catchCaller 'LL.withMCJIT $
LL.withMCJIT context optLevel model noFpe enableFis)
(\mcjit ->
liftBaseOp
(catchCaller 'LL.withModuleInEngine $
LL.withModuleInEngine mcjit mod1)
(f . ExecutableModule)))
jitGetFunction :: (MonadBaseControl IO m)
=> ExecutableModule -> AST.Name -> L b m (Maybe (FunPtr ()))
jitGetFunction (ExecutableModule e) name =
liftBase $ catchInternal 'LL.getFunction $ LL.getFunction e name
| dfoxfranke/llvm-general-util | LLVM/General/Util/Module.hs | mit | 9,013 | 0 | 24 | 2,330 | 2,358 | 1,220 | 1,138 | 211 | 8 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{- |
Types used in generating and solving contact constraints.
-}
module Physics.Constraints.Types where
import Control.Lens
import Data.Monoid
import Data.Vector.Unboxed (Unbox)
import Data.Vector.Unboxed.Deriving
import Physics.Constraint
import Physics.Contact.Types
import Physics.Linear
import Utils.Utils
-- TODO: experiment unbox/monomorphise 'Processed'
{- |
Used by "solution processors", which take a cached solution and a new solution
and decide what the new incremental solution should be.
-}
data Processed a =
Processed { _processedToCache :: !a -- ^ the old cached solution + the new incremental solution
, _processedToApply :: !a -- ^ the new incremental solution to apply
}
{- |
Some 'SolutionProcessor's use contextual information.
e.g. The 'SolutionProcessor' for friction needs to know the coefficient of friction and the normal force.
(Normal force is the solution to the non-penetration constraint.)
-}
type SolutionProcessor a b = a -> b -> b -> Processed b
-- | This isn't a proper constraint but actually part of the "b" term in the nonpenetration constraint.
data RestitutionConstraint = RestitutionConstraint
{ _rcRadiusA :: V2
, _rcRadiusB :: V2
, _rcNormal :: V2
}
data ContactConstraint = ContactConstraint
{ _ccNonPen :: Constraint
, _ccRestitution :: RestitutionConstraint
, _ccFriction :: Constraint
}
data ContactLagrangian = ContactLagrangian
{ _clNonPen :: Lagrangian
, _clFriction :: Lagrangian
}
derivingUnbox
"RestitutionConstraint"
[t|RestitutionConstraint -> (V2, V2, V2)|]
[|\RestitutionConstraint {..} -> (_rcRadiusA, _rcRadiusB, _rcNormal)|]
[|\(ra, rb, n) ->
RestitutionConstraint {_rcRadiusA = ra, _rcRadiusB = rb, _rcNormal = n}|]
derivingUnbox
"ContactConstraint"
[t|ContactConstraint -> (Constraint, RestitutionConstraint, Constraint)|]
[|\ContactConstraint {..} -> (_ccNonPen, _ccRestitution, _ccFriction)|]
[|\(nonPen, restitution, friction) ->
ContactConstraint
{_ccNonPen = nonPen, _ccRestitution = restitution, _ccFriction = friction}|]
derivingUnbox
"ContactLagrangian"
[t|ContactLagrangian -> (Lagrangian, Lagrangian)|]
[|\ContactLagrangian {..} -> (_clNonPen, _clFriction)|]
[|uncurry ContactLagrangian|]
instance Functor Processed where
fmap f (Processed a b) = Processed (f a) (f b)
{-# INLINE fmap #-}
instance Applicative Processed where
pure x = Processed x x
Processed f g <*> Processed x y = Processed (f x) (g y)
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
| ublubu/shapes | shapes/src/Physics/Constraints/Types.hs | mit | 2,830 | 0 | 9 | 590 | 361 | 218 | 143 | 59 | 0 |
-- |
-- Module : Elrond.Core.Types
-- Description :
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created December 22 2015
-- TODO | -
-- -
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC Pragmas
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
module Elrond.Core.Types where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import qualified Data.ByteString.Lazy as BS
import Data.Word
import Data.Functor
import Data.Convertible
import Data.DateTime
import Data.Time.Clock
import Text.Printf
import Network.HTTP.Server
import Network.HTTP.Server.Logger
import Network.URL
-- import Database.HDBC
-- import Database.Sqlite3
import qualified Data.Aeson as JSON
-- import Data.Aeson (toJSON, fromJSON)
--------------------------------------------------------------------------------------------------------------------------------------------
-- Types
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
data Person = Person {}
-- |
data Message = Message { _sender :: Person,
_timestamp :: UTCTime,
_payload :: BS.ByteString,
_recipients :: [Person] }
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
newtype IP = IP (Word8, Word8, Word8, Word8)
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
instance Show IP where
show (IP (a, b, c, d)) = printf "%d.%d.%d.%d" a b c d
| SwiftsNamesake/Elrond | src/Elrond/Core/Types.hs | mit | 2,778 | 14 | 9 | 375 | 232 | 154 | 78 | 20 | 0 |
perpPoint (p, q) (a, b, c) = (x, y)
where
x = (a * c + b * d) / (a * a + b * b)
y = (b * c - a * d) / (a * a + b * b)
d = b * p - a * q
main = do
print $ perpPoint (0, 2) (1, -1, 0)
| shigemk2/haskell_abc | perppoint.hs | mit | 199 | 0 | 11 | 81 | 163 | 90 | 73 | 6 | 1 |
module Rebase.Foreign.Marshal.Utils
(
module Foreign.Marshal.Utils
)
where
import Foreign.Marshal.Utils
| nikita-volkov/rebase | library/Rebase/Foreign/Marshal/Utils.hs | mit | 107 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
-- Solutions for the "Reverse a List" excercise at shuklan.com
-- http://shuklan.com/haskell
--
-- Description:
-- http://shuklan.com/haskell/lec02.html#/0/14
--
-- Author: Tamas Gal
rev [] = []
rev xs = last xs : rev (init xs)
| tamasgal/haskell_exercises | shuklan.com/myfunction.hs | mit | 232 | 0 | 8 | 39 | 44 | 24 | 20 | 2 | 1 |
module Rebase.Data.Profunctor.Unsafe
(
module Data.Profunctor.Unsafe
)
where
import Data.Profunctor.Unsafe
| nikita-volkov/rebase | library/Rebase/Data/Profunctor/Unsafe.hs | mit | 110 | 0 | 5 | 12 | 23 | 16 | 7 | 4 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCSessionDescriptionCallback
(newRTCSessionDescriptionCallback,
newRTCSessionDescriptionCallbackSync,
newRTCSessionDescriptionCallbackAsync,
RTCSessionDescriptionCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescriptionCallback Mozilla RTCSessionDescriptionCallback documentation>
newRTCSessionDescriptionCallback ::
(MonadIO m) =>
(Maybe RTCSessionDescription -> IO ()) ->
m RTCSessionDescriptionCallback
newRTCSessionDescriptionCallback callback
= liftIO
(RTCSessionDescriptionCallback <$>
syncCallback1 ThrowWouldBlock
(\ sdp -> fromJSValUnchecked sdp >>= \ sdp' -> callback sdp'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescriptionCallback Mozilla RTCSessionDescriptionCallback documentation>
newRTCSessionDescriptionCallbackSync ::
(MonadIO m) =>
(Maybe RTCSessionDescription -> IO ()) ->
m RTCSessionDescriptionCallback
newRTCSessionDescriptionCallbackSync callback
= liftIO
(RTCSessionDescriptionCallback <$>
syncCallback1 ContinueAsync
(\ sdp -> fromJSValUnchecked sdp >>= \ sdp' -> callback sdp'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCSessionDescriptionCallback Mozilla RTCSessionDescriptionCallback documentation>
newRTCSessionDescriptionCallbackAsync ::
(MonadIO m) =>
(Maybe RTCSessionDescription -> IO ()) ->
m RTCSessionDescriptionCallback
newRTCSessionDescriptionCallbackAsync callback
= liftIO
(RTCSessionDescriptionCallback <$>
asyncCallback1
(\ sdp -> fromJSValUnchecked sdp >>= \ sdp' -> callback sdp')) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCSessionDescriptionCallback.hs | mit | 2,830 | 0 | 13 | 663 | 532 | 316 | 216 | 47 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude
import qualified Data.Configurator as Conf
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.MarkovChain as MC
import System.Random (RandomGen, getStdGen)
import System.Environment (getArgs)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.Trans.Resource (ResourceT)
import Data.ByteString (ByteString)
import Data.Conduit (ResumableSource)
import Network.HTTP.Conduit (parseUrl, withManager, http, urlEncodedBody, Request, Response)
import Web.Authenticate.OAuth (OAuth(..), Credential, newOAuth, newCredential, signOAuth)
statusesUrl :: String
statusesUrl = "https://api.twitter.com/1.1/statuses/update.json"
main :: IO ()
main = do
[confFile] <- getArgs
conf <- Conf.load [Conf.Required confFile]
oauth <- makeOAuth conf
cred <- makeCredential conf
rnd <- getStdGen
_ <- postTweet oauth cred . T.pack . generateTweet rnd =<< getLine
return ()
where
makeOAuth conf = do
key <- Conf.lookupDefault "" conf "oauthConsumerKey"
secret <- Conf.lookupDefault "" conf "oauthConsumerSecret"
return $ newOAuth {
oauthConsumerKey = key,
oauthConsumerSecret = secret
}
makeCredential conf = do
token <- Conf.lookupDefault "" conf "accessToken"
secret <- Conf.lookupDefault "" conf "accessSecret"
return $ newCredential token secret
postTweet :: OAuth -> Credential -> T.Text -> IO (Response (ResumableSource (ResourceT IO) ByteString))
postTweet oauth cred tweet = do
let params = [("status", TE.encodeUtf8 tweet)]
req <- makeRequest statusesUrl params
-- Error handling?
executeOAuthRequest oauth cred req
makeRequest :: MonadThrow m => String -> [(ByteString, ByteString)] -> m Request
makeRequest url params = do
req <- parseUrl url
return $ urlEncodedBody params req
executeOAuthRequest :: OAuth -> Credential -> Request -> IO (Response (ResumableSource (ResourceT IO) ByteString))
executeOAuthRequest oauth cred request =
withManager $ \manager -> do
signed <- signOAuth oauth cred request
http signed manager
generateTweet :: (Ord a, RandomGen g) => g -> [a] -> [a]
generateTweet rnd input =
take 140 $ MC.run 4 input 0 rnd
| passy/Horse.hs | Main.hs | mit | 2,370 | 0 | 14 | 503 | 703 | 368 | 335 | 53 | 1 |
module PGParseCheck.QQ (psql) where
import qualified Language.Haskell.TH as TH
import Language.Haskell.TH.Quote
import qualified PGParseCheck.Bindings as B
psql :: QuasiQuoter
psql = QuasiQuoter
{ quoteExp = quoteExpParser
, quotePat = undefined
, quoteDec = undefined
, quoteType = undefined
}
quoteExpParser :: String -> TH.ExpQ
quoteExpParser s = do
TH.runIO B.initParser
r <- TH.runIO (B.parseQuery s)
case B.success r of
1 -> (TH.litE . TH.stringL) s
_ -> error "no parse"
| teh/pgparsecheck | lib/PGParseCheck/QQ.hs | mit | 523 | 0 | 13 | 115 | 161 | 90 | 71 | 17 | 2 |
module SFML.Audio.Listener
(
setGlobalVolume
, getGlobalVolume
, setListenerPosition
, getListenerPosition
, setListenerDirection
, getListenerDirection
, setListenerUpVector
, getListenerUpVector
)
where
import SFML.System.Vector3
import Control.Monad ((>=>))
import Foreign.C.Types
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr)
import Foreign.Storable (peek)
-- | Change the global volume of all the sounds and musics.
--
-- The volume is a number between 0 and 100; it is combined with
-- the individual volume of each sound or music.
--
-- The default value for the volume is 100 (maximum).
setGlobalVolume
:: Float -- ^ New global volume, in the range [0, 100]
-> IO ()
setGlobalVolume = sfListener_setGlobalVolume . realToFrac
foreign import ccall unsafe "sfListener_setGlobalVolume"
sfListener_setGlobalVolume :: CFloat -> IO ()
--CSFML_AUDIO_API void sfListener_setGlobalVolume(float volume);
-- | Get the current value of the global volume.
getGlobalVolume :: IO Float -- ^ Current global volume, in the range [0, 100]
getGlobalVolume = fmap realToFrac sfListener_getGlobalVolume
foreign import ccall unsafe "sfListener_getGlobalVolume"
sfListener_getGlobalVolume :: IO CFloat
--CSFML_AUDIO_API float sfListener_getGlobalVolume(void);
-- | Set the position of the listener in the scene.
--
-- The default listener's position is (0, 0, 0).
setListenerPosition :: Vec3f -> IO ()
setListenerPosition pos = with pos sfListener_setPosition_helper
foreign import ccall unsafe "sfListener_setPosition_helper"
sfListener_setPosition_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API void sfListener_setPosition(sfVector3f position);
-- | Get the current position of the listener in the scene.
getListenerPosition :: IO Vec3f
getListenerPosition = alloca $ \ptr -> sfListener_getPosition_helper ptr >> peek ptr
foreign import ccall unsafe "sfListener_getPosition_helper"
sfListener_getPosition_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API sfVector3f sfListener_getPosition();
-- | Set the orientation of the forward vector in the scene.
--
-- The direction (also called "at vector") is the vector
-- pointing forward from the listener's perspective. Together
-- with the up vector, it defines the 3D orientation of the
-- listener in the scene. The direction vector doesn't
-- have to be normalized.
--
-- The default listener's direction is (0, 0, -1).
setListenerDirection :: Vec3f -> IO ()
setListenerDirection dir = with dir sfListener_setDirection_helper
foreign import ccall unsafe "sfListener_setDirection_helper"
sfListener_setDirection_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API void sfListener_setDirection(sfVector3f orientation);
-- | Get the current orientation of the listener in the scene.
getListenerDirection :: IO Vec3f
getListenerDirection = alloca $ \ptr -> sfListener_getDirection_helper ptr >> peek ptr
foreign import ccall unsafe "sfListener_getDirection_helper"
sfListener_getDirection_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API sfVector3f sfListener_getDirection();
-- | Set the upward vector of the listener in the scene
--
-- The up vector is the vector that points upward from the
-- listener's perspective. Together with the direction, it
-- defines the 3D orientation of the listener in the scene.
-- The up vector doesn't have to be normalized.
-- The default listener's up vector is (0, 1, 0). It is usually
-- not necessary to change it, especially in 2D scenarios.
setListenerUpVector :: Vec3f -> IO ()
setListenerUpVector dir = with dir sfListener_setUpVector_helper
foreign import ccall unsafe "sfListener_setUpVector_helper"
sfListener_setUpVector_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API void sfListener_setUpVector(sfVector3f upVector);
-- | Get the current upward vector (unnormalised) of the listener in the scene.
getListenerUpVector :: IO Vec3f
getListenerUpVector = alloca $ \ptr -> sfListener_getUpVector_helper ptr >> peek ptr
foreign import ccall unsafe "sfListener_getUpVector_helper"
sfListener_getUpVector_helper :: Ptr Vec3f -> IO ()
--CSFML_AUDIO_API sfVector3f sfListener_getUpVector();
| SFML-haskell/SFML | src/SFML/Audio/Listener.hs | mit | 4,200 | 0 | 8 | 633 | 553 | 311 | 242 | 51 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Drool.Types
-- Copyright : 2012, Tobias Fuchs
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : POSIX
--
-- |
--
-----------------------------------------------------------------------------
{-# OPTIONS -O2 -Wall #-}
module Drool.Types (
RotationVector(..),
Signal(..),
-- SignalBuffer(..),
SignalList(..),
SignalSource(..),
RenderPerspective(..),
rvector_x, rvector_y, rvector_z,
newSignal,
-- newSignalBuffer,
newSignalList,
getSignal,
getRecentSignal,
getLastSignal,
getBufferSample,
getSignalSample
) where
import Data.Array.IO
import Graphics.Rendering.OpenGL
import Drool.Utils.SigGen ( SValue )
-- A signal is an array of samples (sample type is GLfloat):
newtype Signal = CSignal { signalArray :: IOUArray Int Float }
-- A signal buffer is an array of signals, signal[t] = signal_t
-- In effect, a two-dimensional matrix over samples.
-- newtype SignalBuffer = CSignalBuffer { signalBufferArray :: IOArray Int Signal }
-- Would perform better in case a list of Signal is too slow:
-- newtype SignalQueue = CSignalQueue { signalQueueArray :: MFifoQOf IO Signal }
newtype SignalList = CSignalList { signalList :: [Signal] }
data SignalSource = Microphone | TestSignal | File
deriving ( Eq, Show, Read )
-- Type for translation vector
-- newtype TVector = TVector (Vector3 GLfloat GLfloat GLfloat)
-- Type for rotation vector
data RotationVector = CRotationVector { rotX :: GLfloat, rotY :: GLfloat, rotZ :: GLfloat }
deriving ( Show, Read )
data RenderPerspective = Top | Side | Front | Isometric
deriving ( Show, Read )
rvector_x :: (a,a,a) -> a
rvector_x (x,_,_) = x
rvector_y :: (a,a,a) -> a
rvector_y (_,y,_) = y
rvector_z :: (a,a,a) -> a
rvector_z (_,_,z) = z
newSignal :: IO Signal
newSignal = fmap CSignal $ newArray(0,10) (0::Float) :: IO Signal
{-
newSignalBuffer :: Int -> IO SignalBuffer
newSignalBuffer size = do
blankSignal <- newSignal
fmap CSignalBuffer $ newArray(0,size) (blankSignal) :: IO SignalBuffer
-}
newSignalList :: Int -> Signal -> [Signal]
newSignalList size el = if size > 0 then (el::Signal) : (newSignalList (size-1) el) else []
-- getSignal signalBuf time_idx = readArray (signalBufferArray signalBuf) time_idx
getSignal :: SignalList -> Int -> Signal
getSignal signals time_idx = (signalList signals) !! time_idx
-- Using !! here is okay as signal buffer passed is supposed to be really short (<= 3 signals).
getRecentSignal :: SignalList -> Maybe Signal
getRecentSignal signals@(CSignalList (_:_)) = Just $ sigList !! 0
where sigList = signalList signals
getRecentSignal (CSignalList []) = Nothing
getLastSignal :: SignalList -> Maybe Signal
getLastSignal signals@(CSignalList (_:_)) = Just $ last sigList
where sigList = signalList signals
getLastSignal (CSignalList []) = Nothing
{-
getBufferSample signalBuf time_idx sample_idx = do
signal <- getSignal signalBuf time_idx
sample <- readArray (signalArray signal) sample_idx
return sample
-}
getBufferSample :: SignalList -> Int -> Int -> IO Float
getBufferSample signals time_idx sample_idx = do
let signal = getSignal signals time_idx
sample <- readArray (signalArray signal) sample_idx
return sample
getSignalSample :: Signal -> Int -> IO SValue
getSignalSample signal sample_idx = do
sample <- readArray (signalArray signal) sample_idx
return sample
| fuchsto/drool | src/Drool/Types.hs | mit | 3,504 | 0 | 10 | 595 | 757 | 436 | 321 | 55 | 2 |
{-# LANGUAGE TupleSections #-}
module PureScript.Ide.Reexports where
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Data.List (union)
import PureScript.Ide.Types
getReexports :: Module -> [ExternDecl]
getReexports (mn, decls)= mapMaybe getExport decls
where getExport e@(Export mn')
| mn /= mn' = Just e
| otherwise = Nothing
getExport _ = Nothing
replaceReexport :: ExternDecl -> Module -> Module -> Module
replaceReexport e@(Export _) (m, decls) (_, newDecls) =
(m, filter (/= e) decls `union` newDecls)
replaceReexport _ _ _ = error "Should only get Exports here."
emptyModule :: Module
emptyModule = ("Empty", [])
isExport :: ExternDecl -> Bool
isExport (Export _) = True
isExport _ = False
removeExportDecls :: Module -> Module
removeExportDecls = fmap (filter (not . isExport))
replaceReexports :: Module -> Map ModuleIdent [ExternDecl] -> Module
replaceReexports m db = result
where reexports = getReexports m
result = foldl go (removeExportDecls m) reexports
go :: Module -> ExternDecl -> Module
go m' re@(Export name) = replaceReexport re m' (getModule name)
getModule :: ModuleIdent -> Module
getModule name = clean res
where res = fromMaybe emptyModule $ (name , ) <$> Map.lookup name db
-- we have to do this because keeping self exports in will result in
-- infinite loops
clean (mn, decls) = (mn,) (filter (/= Export mn) decls)
| nwolverson/psc-ide | src/PureScript/Ide/Reexports.hs | mit | 1,516 | 0 | 13 | 354 | 483 | 262 | 221 | 34 | 2 |
module PoetryDiagramsSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
| myw/poetry-diagrams | test/PoetryDiagramsSpec.hs | gpl-2.0 | 211 | 0 | 13 | 49 | 74 | 39 | 35 | 9 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, GADTs, PackageImports #-}
module MarXup.MultiRef where
import Control.Monad.Fix
import Control.Monad.RWS.Lazy
import Data.Map.Strict (Map,insert)
import qualified Data.Map.Strict as M
import Graphics.Diagrams.Core (BoxSpec, nilBoxSpec)
type MetaData key = Map key String
type BoxSpecs = Map Int BoxSpec
-- FIXME: Move boxspecs to the Read part.
newtype Multi config key a = Multi {fromMulti :: RWS config String (References,BoxSpecs,MetaData key) a }
deriving (Functor, Monad, MonadReader config, Applicative, MonadWriter String, MonadState (References,BoxSpecs,MetaData key), MonadFix)
-----------------------------------
-- Basic datatype and semantics
type Label = Int
raw :: String -> Multi config key ()
raw s = tell s
getBoxSpec :: Int -> Multi config key BoxSpec
getBoxSpec bxId = do
(_,bs,_) <- get
return $ case M.lookup bxId bs of
Nothing -> nilBoxSpec -- TODO: log this error somehow
Just b -> b
-- | allocate a new label
newLabel :: Multi key config Label -- create a new label
newLabel = do (r,bx,m) <- get
put (r+1,bx,m)
return r
-- | output some meta data
metaData :: Ord key => key -> String -> Multi config key ()
metaData k val = do
(r,bx,m) <- get
put (r,bx,insert k val m)
return ()
getMetaData :: Multi config key (MetaData key)
getMetaData = gets (\(_,_,m) -> m)
type References = Int -- how many labels have been allocated
emptyRefs :: References
emptyRefs = 0
| jyp/MarXup | MarXup/MultiRef.hs | gpl-2.0 | 1,489 | 0 | 11 | 287 | 484 | 269 | 215 | 34 | 2 |
greet :: String -> String
greet = catstr "Hello " | hmemcpy/milewski-ctfp-pdf | src/content/1.9/code/haskell/snippet05.hs | gpl-3.0 | 49 | 0 | 5 | 9 | 18 | 9 | 9 | 2 | 1 |
alpha :: forall x. (Int -> x) -> [x]
alpha h = map h [12] | hmemcpy/milewski-ctfp-pdf | src/content/2.4/code/haskell/snippet10.hs | gpl-3.0 | 57 | 0 | 8 | 14 | 41 | 22 | 19 | -1 | -1 |
--16-9 Create a Sudoku solver
--this version is taken from Richard Bird's "Pearls of Functional Algorithm Design"
import Data.List ((\\))
type Matrix a = [Row a]
type Row a = [a]
type Grid = Matrix Digit
type Digit = Char
type Choices = [Digit]
digits = ['1'..'9']
blank = (=='0')
solve = filter valid . expand . prune . prune . prune . prune . prune . choices
choices :: Grid -> Matrix Choices
choices = map (map choice)
choice d = if blank d then digits else [d]
expand :: Matrix Choices -> [Grid]
expand = cp . map cp
cp :: [[a]] -> [[a]]
cp [] = [[]]
cp (xs : xss) = do
x <- xs
ys <- cp xss
return (x : ys)
valid :: Grid -> Bool
valid g = (all nodups (rows g)) && (all nodups (cols g)) && (all nodups (boxes g))
nodups :: Eq a => [a] -> Bool
nodups [] = True
nodups (x:xs) = all (/= x) xs && nodups xs
rows :: Matrix a -> Matrix a
rows = id
cols :: Matrix a -> Matrix a
cols [a] = [[x] | x <- a]
cols (xs : xss) = zipWith (:) xs (cols xss)
boxes :: Matrix a -> Matrix a
boxes = map ungroup . ungroup . map cols . group . map group
group :: [a] -> [[a]]
group [] = []
group l = x : group xs where (x,xs) = splitAt 3 l
ungroup :: [[a]] -> [a]
ungroup = concat
prune :: Matrix Choices -> Matrix Choices
prune = pruneBy boxes . pruneBy cols . pruneBy rows
pruneBy f = f . map pruneRow . f
pruneRow :: Row Choices -> Row Choices
pruneRow row = map (remove fixed) row
where fixed = [d | [d] <- row]
remove xs ds = if singleton ds then ds else ds \\ xs
singleton ds = length ds == 1
showGrid g = concat $ map (++ "\n") g
board :: Grid
board = [['5','3','0','0','7','0','0','0','0'],
['6','0','0','1','9','5','0','0','0'],
['0','9','8','0','0','0','0','6','0'],
['8','0','0','0','6','0','0','0','3'],
['4','0','0','8','0','3','0','0','1'],
['7','0','0','0','2','0','0','0','6'],
['0','6','0','0','0','0','2','8','0'],
['0','0','0','4','1','9','0','0','5'],
['0','0','0','0','8','0','0','7','9']]
main :: IO ()
main = do
putStr (showGrid board)
putStr "\n"
putStr (showGrid $ head $ solve board)
| cem3394/EPI-Haskell | 16-09_sudokuSolver2.hs | gpl-3.0 | 2,120 | 0 | 12 | 496 | 1,127 | 627 | 500 | 61 | 2 |
#!/usr/bin/runhaskell
-- |This program checks the length of lines and trailing whitespaces
-- in a file.
module SourceCheck.CheckFormat
where
import Data.Char
import System.Environment
import System.Exit
import Data.Maybe
type LineNumber = Integer
data CheckError = LineTooLong | TrailingWhitespaces
lengthOk :: String -> Bool
lengthOk s =
length s < 80
whitespaceOk :: String -> Bool
whitespaceOk s =
if length s > 0
then (not . isSpace . last) s
else True
putIndentLn :: String -> IO ()
putIndentLn s = putStrLn ("\t"++s)
renderCheckError :: (Show a) => a -> CheckError -> IO ()
renderCheckError lineNo LineTooLong =
putIndentLn $ show lineNo ++": Line too long"
renderCheckError lineNo TrailingWhitespaces =
putIndentLn $ show lineNo ++": Trailing whitespaces"
putResult :: LineNumber -> [CheckError] -> IO ()
putResult lineNo errs =
(mapM_ (renderCheckError lineNo)) errs
checkText :: [String] -> IO Bool
checkText strings =
let results = map checkLine strings
resultsOk = all null results
in sequence_ ( zipWith putResult [1..] results) >> return resultsOk
checkLine :: String -> [CheckError]
checkLine str =
foldl prependJust [] [ checkLength
, checkWhitespaces
]
where prependJust list mfun | isJust mval = (fromJust mval):list
| otherwise = list
where mval = mfun str
checkLength :: [a] -> Maybe CheckError
checkLength str | length str < 80 = Nothing
| otherwise = Just LineTooLong
checkWhitespaces :: String -> Maybe CheckError
checkWhitespaces str | whitespaceOk str = Nothing
| otherwise = Just TrailingWhitespaces
checkFiles :: [FilePath] -> IO Bool
checkFiles filenames =
(fmap (all id).mapM checkFile) filenames
checkFile :: FilePath -> IO Bool
checkFile filename =
putStrLn ("Checking file \'"++filename++"\'...") >>
fmap lines (readFile filename) >>=
checkText >>= \result ->
renderResult filename result >>
return result
renderResult :: FilePath -> Bool -> IO ()
renderResult filename False = putStrLn ("...false formatting ("++filename++")")
renderResult filename True = putStrLn ("...Ok ("++filename++")")
exit :: Bool -> IO a
exit b =
if b
then exitSuccess
else exitFailure
main :: IO a
main =
getArgs >>= \filenames ->
checkFiles filenames >>=
exit
| seppeljordan/checkformat | SourceCheck/CheckFormat.hs | gpl-3.0 | 2,451 | 0 | 11 | 611 | 747 | 375 | 372 | 66 | 2 |
import Pipes
main :: IO()
main = putStrLn "foo"
| Toeplitz/haskell | HvtPipes.hs | gpl-3.0 | 50 | 0 | 6 | 11 | 22 | 11 | 11 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Hledger.Cli.Commands.Equity (
equitymode
,equity
)
where
import Data.Maybe
import Data.String.Here
import Data.Time.Calendar
import Hledger
import Hledger.Cli.CliOptions
equitymode = hledgerCommandMode
[here| equity
Print a "closing balances" transaction that brings all accounts (or with
query arguments, just the matched accounts) to a zero balance, followed by an
opposite "opening balances" transaction that restores the balances from zero.
Such transactions can be useful, eg, for bringing account balances across
file boundaries.
FLAGS
The opening balances transaction is useful to carry over
asset/liability balances if you choose to start a new journal file,
eg at the beginning of the year.
The closing balances transaction is useful to zero out balances in
the old file, which gives you the option of reporting on both files
at once while still seeing correct balances.
Balances are calculated, and the opening transaction is dated, as of
the report end date, which you should specify with -e or date: (and
the closing transaction is dated one day earlier). If a report end
date is not specified, it defaults to today.
Example:
```shell
$ hledger equity -f 2015.journal -e 2016/1/1 assets liabilities >>2015.journal
# move the opening balances transaction to 2016.journal
$ hledger -f 2015.journal bal assets liabilities not:desc:closing # shows correct 2015 balances
$ hledger -f 2016.journal bal assets liabilities # shows correct 2016 balances
$ hledger -f 2015.journal -f 2016.journal bal assets liabilities # still shows correct 2016 balances
```
Open question: how to handle txns spanning a file boundary ? Eg:
```journal
2015/12/30 * food
expenses:food:dining $10
assets:bank:checking -$10 ; date:2016/1/4
```
This command might or might not have some connection to the concept of
"closing the books" in accounting.
|]
[]
[generalflagsgroup1]
[]
([], Just $ argsFlag "[QUERY]")
equity CliOpts{reportopts_=ropts} j = do
today <- getCurrentDay
let ropts_ = ropts{accountlistmode_=ALFlat}
q = queryFromOpts today ropts_
(acctbals,_) = balanceReport ropts_ q j
balancingamt = negate $ sum $ map (\(_,_,_,b) -> normaliseMixedAmountSquashPricesForDisplay b) acctbals
ps = [posting{paccount=a
,pamount=mixed [b]
,pbalanceassertion=Just (b,nullsourcepos)
}
|(a,_,_,mb) <- acctbals
,b <- amounts $ normaliseMixedAmountSquashPricesForDisplay mb
]
++ [posting{paccount="equity:opening balances", pamount=balancingamt}]
enddate = fromMaybe today $ queryEndDate (date2_ ropts_) q
nps = [posting{paccount=a
,pamount=mixed [negate b]
,pbalanceassertion=Just (b{aquantity=0}, nullsourcepos)
}
|(a,_,_,mb) <- acctbals
,b <- amounts $ normaliseMixedAmountSquashPricesForDisplay mb
]
++ [posting{paccount="equity:closing balances", pamount=negate balancingamt}]
putStr $ showTransaction (nulltransaction{tdate=addDays (-1) enddate, tdescription="closing balances", tpostings=nps})
putStr $ showTransaction (nulltransaction{tdate=enddate, tdescription="opening balances", tpostings=ps})
| ony/hledger | hledger/Hledger/Cli/Commands/Equity.hs | gpl-3.0 | 3,362 | 0 | 17 | 705 | 510 | 291 | 219 | 37 | 1 |
module Expires (expiresTests) where
import Util
-- 5.1.1.
timeParseTest valid n xs = sessionTest ("Time parsing: " ++ xs) $ do
recv (time $ n - 1) e $ cs ++ "; Expires=" ++ xs
send (time $ n - 1) e cs
if valid
then noSend (time n) e
-- An invalid date doesn't invalidate the whole-cookie, so it becomes
-- a non-persistent cookie with no particular expiration.
else send (time n) e cs >> send (time $ n + year) e cs
where
cs = "x=y"
e = ep host1 path1 True True
expiresTests =
-- strange field-orderings
[ timeParseTest True 1 "01 70 0:0:1 Janbearpig"
, timeParseTest True 1 "1970 1 00:00:01 jan"
, timeParseTest True 1 "01 0:00:1 JANU 1970"
-- valid delimiters
, timeParseTest True 1 "1970 Jan\t01!00:00:01"
, timeParseTest True 1 "1970\"Jan#01$00:00:01"
, timeParseTest True 1 "1970%Jan&01'00:00:01"
, timeParseTest True 1 "1970(Jan)01*00:00:01"
, timeParseTest True 1 "1970+Jan,01-00:00:01"
, timeParseTest True 1 "1970.Jan/01.00:00:01"
, timeParseTest True 1 " !\"#$%&'()*+,-./1970 Jan 01 00:00:01 !\"#$%&'()*+,-./"
-- years
, timeParseTest True year "1971 Jan 01 00:00:00"
, timeParseTest True (2 * year) "1972 Jan 01 00:00:00"
-- months
, timeParseTest True (31 * day) "1970 Feb 01 00:00:00"
, timeParseTest True ((31 + 28) * day) "1970 Mar 01 00:00:00"
, timeParseTest True (year - 31 * day) "1970 Dec 01 00:00:00"
-- days of the month
, timeParseTest True day "1970 Jan 02 00:00:00"
, timeParseTest True (2 * day) "1970 Jan 03 00:00:00"
-- hours
, timeParseTest True hour "1970 Jan 01 01:00:00"
, timeParseTest True (2 * hour) "1970 Jan 01 02:00:00"
, timeParseTest True (day - hour) "1970 Jan 01 23:00:00"
-- minutes
, timeParseTest True minute "1970 Jan 01 00:01:00"
, timeParseTest True (2 * minute) "1970 Jan 01 00:02:00"
, timeParseTest True (hour - minute) "1970 Jan 01 00:59:00"
-- seconds
, timeParseTest True second "1970 Jan 01 00:00:01"
, timeParseTest True (2 * second) "1970 Jan 01 00:00:02"
, timeParseTest True (minute - second) "1970 Jan 01 00:00:59"
-- recent years
, timeParseTest True year2000 "Jan 01, 00 00:00:00"
, timeParseTest True (year2000 - second) "Dec 31, 99 23:59:59"
, timeParseTest True (year2000 + second) "Jan 01, 00 00:00:01"
-- leap years
, timeParseTest True (year2000 + year + day) "Jan 01, 01 00:00:00"
, timeParseTest True (year2000 - 3 * year) "Jan 01, 97 00:00:00"
, timeParseTest True (year2000 - 4 * year - day) "Jan 01, 96 00:00:00"
-- invalid times
, timeParseTest False 0 "Ja 01, 1970 00:00:00"
, timeParseTest False 0 "Ajan 01, 1970 00:00:00"
, timeParseTest False 0 "Jan 001, 1970 00:00:00"
, timeParseTest False 0 "70 Jan 01, 00:00:00"
, timeParseTest False 0 "01970 Jan 01, 00:00:00"
, timeParseTest False (-200 * year) "1600 Jan 01, 00:00:00"
, timeParseTest False day "1970 Jan 01, 24:00:00"
, timeParseTest False 0 "1970 Jan 00, 00:00:00"
, timeParseTest False (32 * day) "1970 Jan 32, 00:00:00"
, timeParseTest False hour "1970 Jan 01, 00:60:00"
, timeParseTest False minute "1970 Jan 01, 00:00:60"
, timeParseTest False ((31 + 29) * day) "1970 Feb 29, 00:00:00"
, timeParseTest False ((31 + 30) * day) "1970 Feb 30, 00:00:00"
]
| ktvoelker/cookie-jar | test/Expires.hs | gpl-3.0 | 3,243 | 0 | 14 | 680 | 820 | 430 | 390 | 56 | 2 |
-- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
-- What is the 10001st prime number?
main :: IO ()
main = putStrLn $ show $ (filter isPrime [1..]) !! 10001
divides :: Int -> Int -> Bool
divides x d = (mod x d) == 0
isPrime :: Int -> Bool
isPrime x = not $ any (divides x) [2,3..(floor $ sqrt (fromIntegral x))]
| peri4n/projecteuler | haskell/problem7.hs | gpl-3.0 | 370 | 0 | 12 | 83 | 132 | 69 | 63 | 6 | 1 |
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN"
"http://java.sun.com/products/javahelp/helpset_1_0.dtd">
<helpset version="1.0">
<!-- title -->
<title>Xena - Help</title>
<!-- maps -->
<maps>
<homeID>top</homeID>
<mapref location="xena/plugin/html/Map.jhm"/>
</maps>
<view mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Table Of Contents</label>
<type>javax.help.TOCView</type>
<data>xena/plugin/html/TOC.xml</data>
</view>
</helpset> | srnsw/xena | plugins/html/doc/HtmlHelp.hs | gpl-3.0 | 610 | 43 | 35 | 111 | 227 | 115 | 112 | -1 | -1 |
module Main where
import System.Environment
import Text.Parsec (parse)
import Types
import Parser
import Interpreter
main = do
args <- getArgs
if length args == 0
then putStrLn $ "Usage: " ++ "<program> <input>"
else do
progText <- readFile $ args!!0
let (Right prog) = parse program (args!!0) progText
inputText <- readFile $ args!!1
let (Right inp) = parse inputData (args!!1) inputText
print $ run prog inp
| gltronred/braidf-ck | braidf-ck.hs | gpl-3.0 | 448 | 0 | 15 | 104 | 168 | 84 | 84 | 16 | 2 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Database.Design.Ampersand.FSpec.ShowMeatGrinder
(makeMetaPopulationFile,MetaType(..))
where
import Data.List
import Data.Char
import Data.Ord
import Data.Hashable (hash) -- a not good enouqh function, but used for the time being.
import Data.Typeable
import Database.Design.Ampersand.FSpec.FSpec
import Database.Design.Ampersand.FSpec.FSpecAux
import Database.Design.Ampersand.FSpec.Motivations
import Database.Design.Ampersand.FSpec.SQL
import Database.Design.Ampersand.FSpec.ToFSpec.NormalForms (conjNF)
import Database.Design.Ampersand.Basics
import Database.Design.Ampersand.Misc
import Database.Design.Ampersand.FSpec.ShowADL
import Database.Design.Ampersand.Core.AbstractSyntaxTree hiding (RuleType(..))
import Database.Design.Ampersand.Classes.ConceptStructure
--import Data.Hashable
import Data.Maybe
fatal :: Int -> String -> a
fatal = fatalMsg "ShowMeatGrinder"
makeMetaPopulationFile :: MetaType -> FSpec -> (FilePath,String)
makeMetaPopulationFile mType fSpec
= ("MetaPopulationFile"++show mType++".adl", content popKind mType fSpec)
where popKind = case mType of
Generics -> generics fSpec
AST -> metaPops fSpec
content :: (FSpec -> [Pop]) -> MetaType -> FSpec -> String
content popKind mType fSpec = unlines
([ "{- Do not edit manually. This code has been generated!!!"
, " Generated with "++ampersandVersionStr
, " Generated at "++show (genTime (getOpts fSpec))
, " "
, "The populations defined in this file are the populations from the user's"
, "model named '"++name fSpec++"'."
, ""
, "The order in which these populations are defined correspond with the order "
, "in which Ampersand is defined in itself. Currently (Feb. 2015), this is hard-"
, "coded. This means, that whenever Formal Ampersand changes, it might have "
, "impact on the generator of this file. "
, ""
, "-}"
, ""
, "CONTEXT "++show mType++" IN ENGLISH -- (the language is chosen arbitrary, for it is mandatory but irrelevant."]
++ (concat.intersperse []) (map (lines . showADL ) (popKind fSpec))
++
[ ""
, "ENDCONTEXT"
])
instance GenericPopulations FSpec where
generics _ fSpec =
filter (not.nullContent)
(
[ Pop "versionInfo" "Context" "AmpersandVersion"
[(uri fSpec, ampersandVersionStr)]
, Pop "contextName" "Context" "ContextName"
[(uri fSpec, name fSpec)]
, Pop "dbName" "Context" "DatabaseName"
[(uri fSpec, dbName (getOpts fSpec))]
]
++[ Comment " ", Comment $ "[Relations]--: (count="++(show.length.allDecls) fSpec++")"]
++ concatMap (generics fSpec) (allDecls fSpec)
++[ Comment " ", Comment $ "[Concepts]--: (count="++(show.length) [c | c <- allConcepts fSpec, c /= ONE]++")"]
++ concatMap (generics fSpec) [c | c <- allConcepts fSpec, c /= ONE]
++[ Comment " ", Comment $ "[TableColumnInfo]--: (count="++(show.length) allSqlPlugs++")"]
++ concatMap (generics fSpec) allSqlPlugs
++[ Comment " ", Comment $ "[Rules]--: (count="++(show.length.fallRules) fSpec++")"]
++ concatMap (generics fSpec) (fallRules fSpec)
++[ Comment " ", Comment $ "[Conjuncts]--: (count="++(show.length.vconjs) fSpec++")"]
++ concatMap (generics fSpec) (vconjs fSpec)
++[ Comment " ", Comment $ "[Roles]--: (count="++(show.length.fRoles) fSpec++")"]
++ concatMap (generics fSpec) (fRoles fSpec)
)
where
allSqlPlugs = [plug | InternalPlug plug <- plugInfos fSpec]
instance MetaPopulations FSpec where
metaPops _ fSpec =
filter (not.nullContent)
(
[Comment " ", Comment $ "PATTERN Context: ('"++name fSpec++"')"]
++[ Pop "name" "Context" "ContextIdentifier"
[(uri fSpec,name fSpec)]]
++[ Comment " ", Comment $ "PATTERN Patterns: (count="++(show.length.vpatterns) fSpec++")"]
++ concatMap (metaPops fSpec) ((sortBy (comparing name).vpatterns) fSpec)
++[ Comment " ", Comment $ "PATTERN Specialization: (count="++(show.length.vgens) fSpec++")"]
++ concatMap (metaPops fSpec) (vgens fSpec)
++[ Comment " ", Comment $ "PATTERN Concept: (count="++(show.length.allConcepts) fSpec++")"]
++ concatMap (metaPops fSpec) ((sortBy (comparing name).allConcepts) fSpec)
-- ++[ Comment " ", Comment $ "PATTERN Atoms: (count="++(show.length) (allAtoms fSpec)++")"]
-- ++ concatMap (metaPops fSpec) (allAtoms fSpec)
++[ Comment " ", Comment $ "PATTERN Signature: (count="++(show.length.allSigns) fSpec++")"]
++ concatMap (metaPops fSpec) (allSigns fSpec)
++[ Comment " ", Comment $ "PATTERN Declaration: (count="++(show.length.allDecls) fSpec++")"]
++ concatMap (metaPops fSpec) (allDecls fSpec)
++[ Comment " ", Comment $ "PATTERN Expression: (count="++(show.length.allExprs) fSpec++")"]
++ concatMap (metaPops fSpec) (allExprs fSpec)
++[ Comment " ", Comment $ "PATTERN Rules: (count="++(show.length.fallRules) fSpec++")"]
++ concatMap (metaPops fSpec) ((sortBy (comparing name).fallRules) fSpec)
++[ Comment " ", Comment $ "PATTERN Plugs: (count="++(show.length.plugInfos) fSpec++")"]
++ concatMap (metaPops fSpec) ((sortBy (comparing name).plugInfos) fSpec)
-- ++[ Comment " ", Comment $ "[Initial pairs]--: (count="++(show.length.allLinks) fSpec++")"]
-- ++ concatMap (metaPops fSpec) (allLinks fSpec)
)
where
instance MetaPopulations Pattern where
metaPops fSpec pat =
[ Comment " "
, Comment $ " Pattern `"++name pat++"` "
, Pop "patterns" "Context" "Pattern"
[(uri fSpec,uri pat)]
, Pop "name" "Pattern" "PatternIdentifier"
[(uri pat, name pat)]
, Pop "rules" "Pattern" "Rule"
[(uri pat,uri x) | x <- ptrls pat]
, Pop "declarations" "Pattern" "Declaration"
[(uri pat,uri x) | x <- ptdcs pat]
, Pop "purpose" "Pattern" "Purpose"
[(uri pat,uri x) | x <- ptxps pat]
]
instance MetaPopulations A_Gen where
metaPops fSpec gen =
[ Pop "gens" "Context" "Gen"
[(uri fSpec,uri gen)]
, Pop "genspc" "Gen" "Concept"
[(uri gen,uri(genspc gen))]
, Pop "gengen" "Gen" "Concept"
[(uri gen,uri c) | c<- case gen of
Isa{} -> [gengen gen]
IsE{} -> genrhs gen
]
]
instance GenericPopulations A_Concept where
generics fSpec cpt =
case cpt of
PlainConcept{} ->
[ Comment " "
, Comment $ " Concept `"++name cpt++"` "
, Pop "allConcepts" "Context" "Concept"
[(uri fSpec,uri cpt)]
, Pop "name" "Concept" "Identifier"
[(uri cpt, name cpt)]
, Pop "affectedInvConjunctIds" "Concept" "ConjunctID"
[(uri cpt, uri conj) | conj <- filterFrontEndInvConjuncts affConjs]
, Pop "affectedSigConjunctIds" "Concept" "ConjunctID"
[(uri cpt, uri conj) | conj <- filterFrontEndSigConjuncts affConjs]
, Pop "conceptTableFields" "Concept" "TableColumn"
[(uri cpt, uri fld) | fld <- tablesAndFields]
]
ONE ->
[ Comment " "
, Comment $ " Concept ONE "
, Pop "allConcepts" "Context" "Concept"
[(uri fSpec,uri cpt)]
, Pop "name" "Concept" "Identifier"
[(uri cpt, name cpt)]
, Pop "conceptTableFields" "Concept" "TableColumn"
[(uri cpt, uri fld) | fld <- tablesAndFields]
]
where
affConjs = nub [ conj
| Just conjs<-[lookup cpt (allConjsPerConcept fSpec)]
, conj<-conjs
]
largerConcs = largerConcepts (vgens fSpec) cpt++[cpt]
tablesAndFields = nub . concatMap (lookupCpt fSpec) $ largerConcs
instance MetaPopulations A_Concept where
metaPops fSpec cpt =
case cpt of
PlainConcept{} ->
[ Comment " "
, Comment $ " Concept `"++name cpt++"` "
, Pop "concs" "Context" "Concept"
[(uri fSpec,uri cpt)]
, Pop "name" "Concept" "Identifier"
[(uri cpt, name cpt)]
-- , Pop "cptdf" "Concept" "ConceptDefinition"
-- [(uri cpt,showADL cdef) | cdef <- conceptDefs fSpec, name cdef == name cpt]
-- , Pop "cptpurpose" "Concept" "Purpose"
-- [(uri cpt,showADL x) | lang <- allLangs, x <- fromMaybe [] (purposeOf fSpec lang cpt) ]
]
ONE -> [
]
instance GenericPopulations PlugSQL where
generics fSpec plug =
[ Comment " "
, Comment $ "Plug: '"++name plug++"'"
, Pop "tableInfo" "Context" "DBTable"
[(uri fSpec, uri plug)]
] ++ concatMap (generics fSpec) [(plug,fld) | fld <- plugFields plug]
instance GenericPopulations (PlugSQL,SqlField) where
generics _ (plug,fld) =
[ Pop "columninfo" "DBTable" "TableColumn"
[(uri plug, uri (plug,fld)) ]
, Pop "concept" "TableColumn" "Concept"
[(uri (plug,fld), uri.target.fldexpr $ fld)]
, Pop "unique" "TableColumn" "BOOLEAN"
[(uri (plug,fld), uri.flduniq $ fld)]
, Pop "null" "TableColumn" "BOOLEAN"
[(uri (plug,fld), uri.fldnull $ fld)]
]
instance GenericPopulations Role where
generics fSpec rol =
[ Comment $ "Role: '"++name rol++"'"
, Pop "allRoles" "Context" "Role"
[(uri fSpec, uri rol) ]
, Pop "name" "Role" "TEXT"
[(uri rol, name rol) ]
, Pop "maintains" "Role" "Rule"
[(uri rol, uri rul) | (rol',rul) <- fRoleRuls fSpec, rol==rol' ]
]
instance MetaPopulations Atom where
metaPops _ atm =
[ Pop "pop" "Atom" "Concept"
[(uri atm, uri cpt)
|cpt <- atmRoots atm]
, Pop "repr" "Atom" "Representation"
[(uri atm, (showValADL.atmVal) atm)]
]
instance MetaPopulations Signature where
metaPops _ sgn =
[ Pop "src" "Signature" "Concept"
[(uri sgn, uri (source sgn))]
, Pop "tgt" "Signature" "Concept"
[(uri sgn, uri (target sgn))]
]
instance GenericPopulations Declaration where
generics fSpec dcl =
case dcl of
Sgn{} ->
[ Comment " "
, Comment $ " Relation '"++name dcl++showSign (sign dcl)++"'"
, Pop "allRelations" "Context" "Relation"
[(uri fSpec, uri dcl)]
, Pop "name" "Relation" "RelationName"
[(uri dcl,name dcl)]
, Pop "srcConcept" "Relation" "Concept"
[(uri dcl,uri (source dcl))]
, Pop "tgtConcept" "Relation" "Concept"
[(uri dcl,uri (target dcl))]
, Pop "table" "Relation" "DBTable"
[(uri dcl,uri table)]
, Pop "srcCol" "Relation" "DBTableColumn"
[(uri dcl,uri (table,srcCol))]
, Pop "tgtCol" "Relation" "DBTableColumn"
[(uri dcl,uri (table,tgtCol))]
, Pop "affectedInvConjunctIds" "Relation" "ConjunctID"
[(uri dcl,uri conj) | conj <- filterFrontEndInvConjuncts affConjs ]
, Pop "affectedSigConjunctIds" "Relation" "ConjunctID"
[(uri dcl,uri conj) | conj <- filterFrontEndSigConjuncts affConjs ]
]
Isn{} -> fatal 157 "Isn is not implemented yet"
Vs{} -> fatal 158 "Vs is not implemented yet"
where
(table,srcCol,tgtCol) = getDeclarationTableInfo fSpec dcl
affConjs = fromMaybe [] (lookup dcl $ allConjsPerDecl fSpec)
instance MetaPopulations Declaration where
metaPops fSpec dcl =
case dcl of
Sgn{} ->
[ Comment " "
, Comment $ " Declaration `"++name dcl++" ["++(name.source.decsgn) dcl++" * "++(name.target.decsgn) dcl++"]"++"` "
, Pop "allDeclarations" "Context" "Relation"
[(uri fSpec,uri dcl)]
, Pop "name" "Relation" "Identifier"
[(uri dcl, name dcl)]
-- , Pop "sign" "Declaration" "Signature"
-- [(uri dcl,uri (sign dcl))]
, Pop "source" "Relation" "Concept"
[(uri dcl,uri (source dcl))]
, Pop "target" "Relation" "Concept"
[(uri dcl,uri (target dcl))]
-- , Pop "decprL" "Declaration" "String"
-- [(uri dcl,decprL dcl)]
-- , Pop "decprM" "Declaration" "String"
-- [(uri dcl,decprM dcl)]
-- , Pop "decprR" "Declaration" "String"
-- [(uri dcl,decprR dcl)]
-- , Pop "decmean" "Declaration" "Meaning"
-- [(uri dcl, show(decMean dcl))]
-- , Pop "decpurpose" "Declaration" "Purpose"
-- [(uri dcl, showADL x) | x <- explanations dcl]
]
Isn{} ->
[ Comment " "
, Comment $ " Declaration `I["++name (source dcl)++"]`"
-- , Pop "sign" "Declaration" "Signature"
-- [(uri dcl,uri (sign dcl))]
, Pop "source" "Relation" "Concept"
[(uri dcl,uri (source dcl))]
, Pop "target" "Relation" "Concept"
[(uri dcl,uri (target dcl))]
]
Vs{} -> fatal 158 "Vs is not implemented yet"
instance MetaPopulations A_Pair where
metaPops _ pair =
[ Pop "in" "Pair" "Relation"
[(uri pair, uri (lnkDcl pair))]
, Pop "l" "Pair" "Atom"
[(uri pair, uri(lnkLeft pair))]
, Pop "r" "Pair" "Atom"
[(uri pair, uri(lnkRight pair))]
]
instance MetaPopulations Expression where
metaPops fSpec expr =
case expr of
EBrk e -> metaPops fSpec e
_ ->
[ Pop "src" "Term" "Concept"
[(uri expr, uri (source expr))]
, Pop "tgt" "Term" "Concept"
[(uri expr, uri (target expr))]
]++
( case expr of
(EEqu (l,r)) -> makeBinaryTerm Equivalence l r
(EImp (l,r)) -> makeBinaryTerm Implication l r
(EIsc (l,r)) -> makeBinaryTerm Intersection l r
(EUni (l,r)) -> makeBinaryTerm Union l r
(EDif (l,r)) -> makeBinaryTerm Difference l r
(ELrs (l,r)) -> makeBinaryTerm LeftResidu l r
(ERrs (l,r)) -> makeBinaryTerm RightResidu l r
(EDia (l,r)) -> makeBinaryTerm Diamond l r
(ECps (l,r)) -> makeBinaryTerm Composition l r
(ERad (l,r)) -> makeBinaryTerm RelativeAddition l r
(EPrd (l,r)) -> makeBinaryTerm CartesionProduct l r
-- (EKl0 e) ->
-- (EKl1 e) ->
-- (EFlp e) ->
-- (ECpl e) ->
(EBrk _) -> fatal 348 "This should not happen, because EBrk has been handled before"
(EDcD dcl) -> [Pop "bind" "Term" "Relation" [(uri expr,uri dcl)]
]
-- EDcI{} ->
-- EEps{} ->
-- EDcV{} ->
-- EMp1{} ->
_ -> [Comment $ "TODO: "++showADL expr]
-- TODO: Work on the rest of the expressions (get rid of the statement above)
)
where
makeBinaryTerm :: BinOp -> Expression -> Expression -> [Pop]
makeBinaryTerm bop lhs rhs =
[ Pop "lhs" "BinaryTerm" "Term"
[(uri expr,uri lhs)]
, Pop "rhs" "BinaryTerm" "Term"
[(uri expr,uri rhs)]
, Pop "operator" "BinaryTerm" "Operator"
[(uri expr,uri bop)]
]++metaPops fSpec lhs
++metaPops fSpec rhs
data BinOp = CartesionProduct
| Composition
| Diamond
| Difference
| Equivalence
| Implication
| Intersection
| LeftResidu
| RightResidu
| RelativeAddition
| Union deriving (Eq, Show, Typeable)
instance Unique BinOp where
showUnique = show
instance GenericPopulations Rule where
generics fSpec rul =
[ Comment " "
, Comment $ " Rule `"++name rul++"` "
, Pop "allRules" "Context" "Rule"
[(uri fSpec, uri rul)]
, Pop "name" "Rule" "RuleID"
[(uri rul,name rul)]
, Pop "ruleAdl" "Rule" "Adl"
[(uri rul,(showADL.rrexp) rul)]
, Pop "origin" "Rule" "Origin"
[(uri rul,(show.origin) rul)]
, Pop "meaning" "Rule" "Meaning"
[(uri rul,aMarkup2String ReST m) | m <- (maybeToList . meaning (fsLang fSpec)) rul ]
, Pop "message" "Rule" "Message"
[(uri rul,aMarkup2String ReST m) | m <- rrmsg rul, amLang m == fsLang fSpec ]
, Pop "srcConcept" "Rule" "Concept"
[(uri rul,(uri.source.rrexp) rul)]
, Pop "tgtConcept" "Rule" "Concept"
[(uri rul,(uri.target.rrexp) rul)]
, Pop "conjunctIds" "Rule" "ConjunctID"
[(uri rul,uri conj) | (rule,conjs)<-allConjsPerRule fSpec, rule==rul,conj <- conjs]
]++case rrviol rul of
Nothing -> []
Just pve ->
[ Pop "pairView" "Rule" "PairView"
[(uri rul, uri pve)]
]++generics fSpec pve
instance GenericPopulations (PairView Expression) where
generics fSpec pve =
[ Comment " "
]++concatMap makeSegment (zip [0..] (ppv_segs pve))
where
makeSegment :: (Int,PairViewSegment Expression) -> [Pop]
makeSegment (i,pvs) =
[ Pop "segment" "PairView" "PairViewSegment"
[(uri pve,uri pvs)]
, Pop "sequenceNr" "PairViewSegment" "Int"
[(uri pvs,show i)]
, Pop "segmentType" "PairViewSegment" "PairViewSegmentType"
[(uri pvs, case pvs of
PairViewText{} -> "Text"
PairViewExp{} -> "Exp")
]
]++
case pvs of
PairViewText{} ->
[Pop "text" "PairViewSegment" "String"
[(uri pvs, pvsStr pvs)]
]
PairViewExp{} ->
[Pop "srcOrTgt" "PairViewSegment" "SourceOrTarget"
[(uri pvs, show (pvsSoT pvs))]
,Pop "expTgt" "PairViewSegment" "Concept"
[(uri pvs, uri (case pvsSoT pvs of
Src -> source (pvsExp pvs)
Tgt -> target (pvsExp pvs)
))]
,Pop "expSQL" "PairViewSegment" "MySQLQuery"
[(uri pvs, prettySQLQuery fSpec 0 (pvsExp pvs))]
]
instance MetaPopulations Rule where
metaPops _ rul =
[ Comment " "
, Comment $ " Rule `"++name rul++"` "
, Pop "name" "Rule" "RuleName"
[(uri rul,name rul)]
, Pop "term" "Rule" "Term"
[(uri rul,uri (rrexp rul))]
, Pop "rrexp" "Rule" "ExpressionID"
[(uri rul,uri (rrexp rul))]
, Pop "rrmean" "Rule" "Meaning"
[(uri rul,show(rrmean rul))]
, Pop "rrpurpose" "Rule" "Purpose"
[(uri rul,showADL x) | x <- explanations rul]
, -- The next population is from the adl pattern 'Plugs':
Pop "sign" "Rule" "Signature"
[(uri rul,uri (sign rul))]
, Pop "declaredthrough" "PropertyRule" "Property"
[(uri rul,show prp) | Just(prp,_) <- [rrdcl rul]]
, Pop "decprps" "Declaration" "PropertyRule"
[(uri dcl, uri rul) | Just(_,dcl) <- [rrdcl rul]]
]
instance MetaPopulations PlugInfo where
metaPops _ plug =
[ Comment $ " Plug `"++name plug++"` "
, Pop "maintains" "Plug" "Rule" [{-STILL TODO. -}] --HJO, 20150205: Waar halen we deze info vandaan??
, Pop "in" "Concept" "Plug"
[(uri cpt,uri plug)| cpt <- concs plug]
, Pop "in" "Declaration" "Plug"
[(uri dcl,uri plug)| dcl <- relsMentionedIn plug]
]
instance MetaPopulations a => MetaPopulations [a] where
metaPops fSpec = concatMap $ metaPops fSpec
instance GenericPopulations Conjunct where
generics fSpec conj =
[ Comment $ "Conjunct: '"++rc_id conj++"'."
, Pop "allConjuncts" "Context" "Conjunct"
[(uri fSpec, uri conj)]
, Pop "signalRuleNames" "Conjunct" "Rule"
[(uri conj,uri r) | r <- rc_orgRules conj, isFrontEndSignal r]
, Pop "invariantRuleNames" "Conjunct" "Rule"
[(uri conj,uri r) | r <- rc_orgRules conj, isFrontEndInvariant r]
, Pop "violationsSQL" "Conjunct" "MySQLQuery"
[(uri conj , prettySQLQuery fSpec 0 (conjNF (getOpts fSpec) (notCpl (rc_conjunct conj)))
)]
]
-----------------------------------------------------
data Pop = Pop { popName ::String
, popSource :: String
, popTarget :: String
, popPairs :: [(String,String)]
}
| Comment { comment :: String -- Not-so-nice way to get comments in a list of populations. Since it is local to this module, it is not so bad, I guess...
}
instance ShowADL Pop where
showADL pop =
case pop of
Pop{} -> "POPULATION "++ popName pop++
" ["++popSource pop++" * "++popTarget pop++"] CONTAINS"
++
if null (popPairs pop)
then "[]"
else "\n"++indentA++"[ "++intercalate ("\n"++indentA++"; ") showContent++indentA++"]"
Comment{} -> intercalate "\n" (map prepend (lines (comment pop)))
where indentA = " "
showContent = map showPaire (popPairs pop)
showPaire (s,t) = "( "++show s++" , "++show t++" )"
prepend str = "-- " ++ str
class Unique a => AdlId a where
uri :: a -> String
uri = camelCase . uniqueShow False
-- All 'things' that are relevant in the meta-environment (RAP),
-- must be an instance of AdlId:
instance AdlId A_Concept
instance AdlId A_Gen
instance AdlId Atom
instance AdlId ConceptDef
instance AdlId Declaration
instance AdlId Expression
instance AdlId BinOp
instance AdlId FSpec
instance AdlId A_Pair
instance AdlId Pattern
instance AdlId PlugInfo
instance AdlId PlugSQL
instance AdlId (PlugSQL,SqlField)
instance AdlId Purpose
instance AdlId Rule
instance AdlId Role
instance AdlId Signature
instance AdlId Conjunct
instance AdlId (PairView Expression)
where uri x = show (typeOf x)++show (hash x)
instance AdlId (PairViewSegment Expression)
where uri x = show (typeOf x)++show (hash (show (hash x) ++ show (origin x)))
instance AdlId Bool where
uri = showUnique
instance AdlId a => AdlId [a] where
--instance AdlId (Declaration,Paire)
-- | remove spaces and make camelCase
camelCase :: String -> String
camelCase str = concatMap capitalize (words str)
where
capitalize [] = []
capitalize (s:ss) = toUpper s : ss
nullContent :: Pop -> Bool
nullContent (Pop _ _ _ []) = True
nullContent _ = False
class MetaPopulations a where
metaPops :: FSpec -> a -> [Pop]
class GenericPopulations a where
generics :: FSpec -> a -> [Pop]
--------- Below here are some functions copied from Generate.hs TODO: Clean up.
-- Because the signal/invariant condition appears both in generateConjuncts and generateInterface, we use
-- two abstractions to guarantee the same implementation.
isFrontEndInvariant :: Rule -> Bool
isFrontEndInvariant r = not (isSignal r) && not (ruleIsInvariantUniOrInj r)
isFrontEndSignal :: Rule -> Bool
isFrontEndSignal r = isSignal r
-- NOTE that results from filterFrontEndInvConjuncts and filterFrontEndSigConjuncts may overlap (conjunct appearing in both invariants and signals)
-- and that because of extra condition in isFrontEndInvariant (not (ruleIsInvariantUniOrInj r)), some parameter conjuncts may not be returned
-- as either inv or sig conjuncts (i.e. conjuncts that appear only in uni or inj rules)
filterFrontEndInvConjuncts :: [Conjunct] -> [Conjunct]
filterFrontEndInvConjuncts conjs = filter (\c -> any isFrontEndInvariant $ rc_orgRules c) conjs
filterFrontEndSigConjuncts :: [Conjunct] -> [Conjunct]
filterFrontEndSigConjuncts conjs = filter (\c -> any isFrontEndSignal $ rc_orgRules c) conjs
| guoy34/ampersand | src/Database/Design/Ampersand/FSpec/ShowMeatGrinder.hs | gpl-3.0 | 23,635 | 0 | 30 | 6,610 | 7,076 | 3,664 | 3,412 | 469 | 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.ServiceManagement.Services.Rollouts.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 new service configuration rollout. Based on rollout, the
-- Google Service Management will roll out the service configurations to
-- different backend services. For example, the logging configuration will
-- be pushed to Google Cloud Logging. Please note that any previous pending
-- and running Rollouts and associated Operations will be automatically
-- cancelled so that the latest Rollout will not be blocked by previous
-- Rollouts. Only the 100 most recent (in any state) and the last 10
-- successful (if not already part of the set of 100 most recent) rollouts
-- are kept for each service. The rest will be deleted eventually.
-- Operation
--
-- /See:/ <https://cloud.google.com/service-management/ Service Management API Reference> for @servicemanagement.services.rollouts.create@.
module Network.Google.Resource.ServiceManagement.Services.Rollouts.Create
(
-- * REST Resource
ServicesRolloutsCreateResource
-- * Creating a Request
, servicesRolloutsCreate
, ServicesRolloutsCreate
-- * Request Lenses
, srcXgafv
, srcUploadProtocol
, srcAccessToken
, srcUploadType
, srcPayload
, srcServiceName
, srcCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceManagement.Types
-- | A resource alias for @servicemanagement.services.rollouts.create@ method which the
-- 'ServicesRolloutsCreate' request conforms to.
type ServicesRolloutsCreateResource =
"v1" :>
"services" :>
Capture "serviceName" Text :>
"rollouts" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Rollout :> Post '[JSON] Operation
-- | Creates a new service configuration rollout. Based on rollout, the
-- Google Service Management will roll out the service configurations to
-- different backend services. For example, the logging configuration will
-- be pushed to Google Cloud Logging. Please note that any previous pending
-- and running Rollouts and associated Operations will be automatically
-- cancelled so that the latest Rollout will not be blocked by previous
-- Rollouts. Only the 100 most recent (in any state) and the last 10
-- successful (if not already part of the set of 100 most recent) rollouts
-- are kept for each service. The rest will be deleted eventually.
-- Operation
--
-- /See:/ 'servicesRolloutsCreate' smart constructor.
data ServicesRolloutsCreate =
ServicesRolloutsCreate'
{ _srcXgafv :: !(Maybe Xgafv)
, _srcUploadProtocol :: !(Maybe Text)
, _srcAccessToken :: !(Maybe Text)
, _srcUploadType :: !(Maybe Text)
, _srcPayload :: !Rollout
, _srcServiceName :: !Text
, _srcCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesRolloutsCreate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'srcXgafv'
--
-- * 'srcUploadProtocol'
--
-- * 'srcAccessToken'
--
-- * 'srcUploadType'
--
-- * 'srcPayload'
--
-- * 'srcServiceName'
--
-- * 'srcCallback'
servicesRolloutsCreate
:: Rollout -- ^ 'srcPayload'
-> Text -- ^ 'srcServiceName'
-> ServicesRolloutsCreate
servicesRolloutsCreate pSrcPayload_ pSrcServiceName_ =
ServicesRolloutsCreate'
{ _srcXgafv = Nothing
, _srcUploadProtocol = Nothing
, _srcAccessToken = Nothing
, _srcUploadType = Nothing
, _srcPayload = pSrcPayload_
, _srcServiceName = pSrcServiceName_
, _srcCallback = Nothing
}
-- | V1 error format.
srcXgafv :: Lens' ServicesRolloutsCreate (Maybe Xgafv)
srcXgafv = lens _srcXgafv (\ s a -> s{_srcXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
srcUploadProtocol :: Lens' ServicesRolloutsCreate (Maybe Text)
srcUploadProtocol
= lens _srcUploadProtocol
(\ s a -> s{_srcUploadProtocol = a})
-- | OAuth access token.
srcAccessToken :: Lens' ServicesRolloutsCreate (Maybe Text)
srcAccessToken
= lens _srcAccessToken
(\ s a -> s{_srcAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
srcUploadType :: Lens' ServicesRolloutsCreate (Maybe Text)
srcUploadType
= lens _srcUploadType
(\ s a -> s{_srcUploadType = a})
-- | Multipart request metadata.
srcPayload :: Lens' ServicesRolloutsCreate Rollout
srcPayload
= lens _srcPayload (\ s a -> s{_srcPayload = a})
-- | Required. The name of the service. See the
-- [overview](\/service-management\/overview) for naming requirements. For
-- example: \`example.googleapis.com\`.
srcServiceName :: Lens' ServicesRolloutsCreate Text
srcServiceName
= lens _srcServiceName
(\ s a -> s{_srcServiceName = a})
-- | JSONP
srcCallback :: Lens' ServicesRolloutsCreate (Maybe Text)
srcCallback
= lens _srcCallback (\ s a -> s{_srcCallback = a})
instance GoogleRequest ServicesRolloutsCreate where
type Rs ServicesRolloutsCreate = Operation
type Scopes ServicesRolloutsCreate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesRolloutsCreate'{..}
= go _srcServiceName _srcXgafv _srcUploadProtocol
_srcAccessToken
_srcUploadType
_srcCallback
(Just AltJSON)
_srcPayload
serviceManagementService
where go
= buildClient
(Proxy :: Proxy ServicesRolloutsCreateResource)
mempty
| brendanhay/gogol | gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Rollouts/Create.hs | mpl-2.0 | 6,595 | 0 | 18 | 1,417 | 806 | 478 | 328 | 116 | 1 |
-- | An example program that simply connects to the first available
-- MTP device and printing the device's firmware version.
import MTP
import MTP.Handle
main = do
h <- getFirstDevice
print =<< getDeviceVersion h
releaseDevice h
closed <- isClosed h
print closed
print =<< getDeviceVersion h
| joachifm/hsmtp | examples/Connect.hs | lgpl-2.1 | 319 | 0 | 8 | 73 | 65 | 29 | 36 | 9 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-
Network.Lifx - A Library to interact with Lifx light bulbs. (lifx.co)
Copyright (C) 2014 Josh Proehl <[email protected]>
***************************************************************************
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
***************************************************************************
-}
module Network.Lifx.Core (
Lifx
) where
import Network.Lifx.Core.Datatypes
import Network.Socket
import qualified Network.Socket.ByteString as BS
import Control.Monad.Reader -- (ReaderT(..), ask)
import Control.Monad.State --(StateT, MonadIO(..))
import System.IO (Handle, hPutStrLn)
import Data.Binary
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC (pack, getLine, putStrLn)
import qualified Data.ByteString.Lazy as BL (copy, toStrict, fromStrict)
newtype Lifx a = Lifx { runLifx :: StateT LifxState IO a }
deriving (Functor, Monad, MonadIO)
-- | The inner state. Contains the connection to the master bulb.
data LifxState = LifxState { controllerSock :: Socket
, controllerSite :: [Word8]
}
-- | Find the master bulb and get the connection to it set up.
{-
openLifx :: Lifx ()
openLifx = Lifx $ withSocketsDo $ do
-- Set up the "request master bulb" packet
let p = Packet 36 13312 ([0,0,0,0,0,0]::[Word8]) ([0,0,0,0,0,0]::[Word8]) 0 2 None
-- Set up a UDP socket to listen for results
-- (Listens on all interfaces.)
s <- socket AF_INET Datagram defaultProtocol
bindAddr <- inet_addr "0.0.0.0"
setSocketOption s Broadcast 1
bindSocket s (SockAddrInet 56700 bindAddr)
connect s (SockAddrInet 56700 (-1))
BS.sendAll s (BL.toStrict (encode p))
-- Get the master bulb response. TODO: Should loop until it gets the right packet type...
(msg, addr) <- BS.recvFrom s 1024
let r = (decode (BL.fromStrict msg)) :: Packet
let site = getSite r
modify (\st -> st { controllerSock = s, controllerSite = site })
return ()
-}
| joshproehl/lifx-haskell | src/Network/Lifx/Core.hs | lgpl-3.0 | 2,833 | 0 | 9 | 685 | 178 | 119 | 59 | 17 | 0 |
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
import Control.Monad
import qualified Data.Map as Map
import Numeric
import Data.Char hiding (isSymbol, isNumber)
import Control.Monad.Error
import System.IO hiding (try)
import Data.IORef
main = do args <- getArgs
case length args of
0 -> runRepl
1 -> runOne $ args !! 0
otherwise -> putStrLn "Program takes only 0 or 1 argument"
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: Env -> String -> IO String
evalString env expr = runIOThrows $ liftM show $ (liftThrows $ readExpr expr) >>= eval env
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env expr = evalString env expr >>= putStrLn
until_ :: Monad m => (a -> Bool) -> m a -> (a -> m ()) -> m ()
until_ pred prompt action = do
result <- prompt
if pred result
then return ()
else action result >> until_ pred prompt action
runOne :: String -> IO ()
runOne expr = primitiveBindings >>= flip evalAndPrint expr
runRepl :: IO ()
runRepl = primitiveBindings >>= until_ (== "quit") (readPrompt "Lisp>>> ") . evalAndPrint
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
| Character Char
| Array [LispVal]
| PrimitiveFunc ([LispVal] -> ThrowsError LispVal)
| Func {
params :: [String],
vararg :: (Maybe String),
body :: [LispVal],
closure :: Env
}
instance Show LispVal where
show (String contents) = "\"" ++ contents ++ "\""
show (Atom name) = name
show (Number contents) = show contents
show (Bool True) = "#t"
show (Bool False) = "#f"
show (List contents) = "(" ++ unwordsList contents ++ ")"
show (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ show tail ++ ")"
show (PrimitiveFunc _) = "<primitive>"
show (Func {params = args, vararg = varargs, body = body, closure = env}) =
"(lambda (" ++ unwords (map show args) ++
(case varargs of
Nothing -> ""
Just arg -> " . " ++ arg) ++ ") ...)"
unwordsList :: [LispVal] -> String
unwordsList = unwords . map show
data LispError = NumArgs Integer [LispVal]
| TypeMismatch String LispVal
| Parser ParseError
| BadSpecialForm String LispVal
| NotFunction String String
| UnboundVar String String
| Default String
instance Show LispError where
show (UnboundVar message varname) = message ++ ": " ++ varname
show (BadSpecialForm message form) = message ++ ": " ++ show form
show (NotFunction message func) = message ++ ": " ++ show func
show (NumArgs expected found) = "Expected " ++ show expected
++ " args; found values " ++ unwordsList found
show (TypeMismatch expected found) = "Invalid type: expected " ++ expected
++ ", found " ++ show found
show (Parser parseErr) = "Parse error at " ++ show parseErr
instance Error LispError where
noMsg = Default "An error has occurred"
strMsg = Default
type ThrowsError = Either LispError
type IOThrowsError = ErrorT LispError IO
trapError :: IOThrowsError String -> IOThrowsError String
trapError action = catchError action (return . show)
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
liftThrows :: ThrowsError a -> IOThrowsError a
liftThrows (Left err) = throwError err
liftThrows (Right val) = return val
runIOThrows :: IOThrowsError String -> IO String
runIOThrows action = runErrorT (trapError action) >>= return . extractValue
-- | Parse input as an Lisp expression.
readExpr :: String -> ThrowsError LispVal
readExpr input = case parse parseExpr "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString -- begin with "
<|> do char '#'
parseBool <|> parseNumber <|> parseCharacter <|> parseArray
<|> parseDecNumber -- begin with a digit
<|> parseQuoted -- begin with '
<|> parseBackquoted -- begin with `
<|> do char '('
x <- (try parseList) <|> parseDottedList
char ')'
return x
parseString :: Parser LispVal
parseString = do char '"'
x <- many parseChar
char '"'
return $ String x
parseChar :: Parser Char
parseChar = do c <- noneOf "\""
if c == '\\'
then parseEscapedChar -- escaped char
else return c -- other chars
escapedChars :: Map.Map Char Char
escapedChars = Map.fromList [
('\"', '\"'),
('n', '\n'),
('r', '\r'),
('t', '\t'),
('\\', '\\')
]
parseEscapedChar :: Parser Char
parseEscapedChar = do c <- satisfy (`Map.member` escapedChars);
case Map.lookup c escapedChars of
Just x -> return x -- always match
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = [first] ++ rest
return $ Atom atom
parseBool :: Parser LispVal
parseBool = do c <- choice $ map char "tf"
return $ case c of
't' -> Bool True
'f' -> Bool False
parseNumber :: Parser LispVal
parseNumber = do base <- choice $ map char "bodx"
liftM (Number . fst . head) $
case base of
'b' -> many1 binDigit >>= return . readBin
'o' -> many1 octDigit >>= return . readOct
'd' -> many1 digit >>= return . readDec
'x' -> many1 hexDigit >>= return . readHex
parseDecNumber :: Parser LispVal
parseDecNumber = liftM (Number . read) $ many1 digit
parseCharacter :: Parser LispVal
parseCharacter = do char '\\'
c <- anyChar
s <- many letter
case map toLower (c:s) of
[a] -> return $ Character a
"space" -> return $ Character ' '
"newline" -> return $ Character '\n'
x -> (unexpected $ "Invalid character name: " ++ x) <?> "\"newline\" or \"space\""
parseArray :: Parser LispVal
parseArray = do char '('
x <- sepBy parseExpr spaces
char ')'
return $ Array x
binDigit :: Parser Char
binDigit = satisfy (`elem` "01")
readBin :: ReadS Integer
readBin = readInt 2 (`elem` "01") digitToInt
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do head <- endBy parseExpr spaces
tail <- char '.' >> spaces >> parseExpr
return $ DottedList head tail
parseQuoted :: Parser LispVal
parseQuoted = do char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseBackquoted :: Parser LispVal
parseBackquoted = do char '`'
x <- parseExpr
return $ List [Atom "quasiquote", x]
-- | The Lisp Evaluator
eval :: Env -> LispVal -> IOThrowsError LispVal
eval env val@(String _) = return val
eval env val@(Number _) = return val
eval env val@(Bool _) = return val
eval env val@(Character _) = return val
eval env (Atom id) = getVar env id
eval env (List [Atom "quote", val]) = return val
eval env (List [Atom "if", pred, conseq, alt]) = do result <- eval env pred
case result of
Bool False -> eval env alt
otherwise -> eval env conseq
eval env (List [Atom "set!", Atom var, form]) =
eval env form >>= setVar env var
eval env (List [Atom "define", Atom var, form]) =
eval env form >>= defineVar env var
eval env (List (Atom "define" : List (Atom var : params) : body)) =
makeNormalFunc env params body >>= defineVar env var
eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) =
makeVarargs varargs env params body >>= defineVar env var
eval env badform@(List (Atom "define" : _)) = throwError $ BadSpecialForm "Bad define form" badform
eval env (List (Atom "lambda" : List params : body)) =
makeNormalFunc env params body
eval env (List (Atom "lambda" : DottedList params varargs : body)) =
makeVarargs varargs env params body
eval env (List (Atom "lambda" : varargs@(Atom _) : body)) =
makeVarargs varargs env [] body
eval env (List (function : args)) = do
func <- eval env function
argVals <- mapM (eval env) args
apply func argVals
makeFunc varargs env params body = return $ Func (map show params) varargs body env
makeNormalFunc = makeFunc Nothing
makeVarargs = makeFunc . Just . show
apply :: LispVal -> [LispVal] -> IOThrowsError LispVal
apply (PrimitiveFunc func) args = liftThrows $ func args
apply (Func params varargs body closure) args =
if num params /= num args && varargs == Nothing
then throwError $ NumArgs (num params) args
else (liftIO $ bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody
where remainingArgs = drop (length params) args
num = toInteger . length
evalBody env = liftM last $ mapM (eval env) body
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List $ remainingArgs)]
Nothing -> return env
-- | Primitive functions.
primitiveBindings :: IO Env
primitiveBindings = nullEnv >>= (flip bindVars $ map makePrimitiveFunc primitives)
where makePrimitiveFunc (var, func) = (var, PrimitiveFunc func)
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [("+", numericBinop (+)),
("-", numericBinop (-)),
("*", numericBinop (*)),
("/", numericBinop div),
("mod", numericBinop mod),
("quotient", numericBinop quot),
("remainder", numericBinop rem),
("symbol?", isSymbol),
("string?", isString),
("number?", isNumber),
("symbol->string", symbolToString),
("=", numBoolBinop (==)),
("<", numBoolBinop (<)),
(">", numBoolBinop (>)),
("/=", numBoolBinop (/=)),
(">=", numBoolBinop (>=)),
("<=", numBoolBinop (<=)),
("&&", boolBoolBinop (&&)),
("||", boolBoolBinop (||)),
("string=?", strBoolBinop (==)),
("string?", strBoolBinop (>)),
("string<=?", strBoolBinop (<=)),
("string>=?", strBoolBinop (>=)),
("car", car),
("cdr", cdr),
("cons", cons),
("eq?", eqv),
("eqv?", eqv),
("equal?", equal)]
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
boolBinop :: (LispVal -> ThrowsError a) -> (a -> a -> Bool) -> [LispVal] -> ThrowsError LispVal
boolBinop unpacker op args = if length args /= 2
then throwError $ NumArgs 2 args
else do left <- unpacker $ args !! 0
right <- unpacker $ args !! 1
return $ Bool $ left `op` right
numBoolBinop = boolBinop unpackNum
strBoolBinop = boolBinop unpackStr
boolBoolBinop = boolBinop unpackBool
isSymbol :: [LispVal] -> ThrowsError LispVal
isSymbol [Atom _] = return $ Bool True
isSymbol [(List [Atom "quote", Atom _])] = return $ Bool True
isSymbol _ = return $ Bool False
isString :: [LispVal] -> ThrowsError LispVal
isString [String _] = return $ Bool True
isString _ = return $ Bool False
isNumber :: [LispVal] -> ThrowsError LispVal
isNumber [Number _] = return $ Bool True
isNumber _ = return $ Bool False
symbolToString :: [LispVal] -> ThrowsError LispVal
symbolToString emptyVal@[] = throwError $ NumArgs 1 emptyVal
symbolToString [Atom s] = return $ String s
symbolToString [(List [Atom "quote", Atom val])] = return $ String val
symbolToString [notSymbol] = throwError $ TypeMismatch "symbol" notSymbol
symbolToString x@(a:b:bs) = throwError $ NumArgs 1 x
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number n) = return n
unpackNum notNum = throwError $ TypeMismatch "number" notNum
unpackStr :: LispVal -> ThrowsError String
unpackStr (String s) = return s
unpackStr (Number s) = return $ show s
unpackStr (Bool s) = return $ show s
unpackStr notString = throwError $ TypeMismatch "string" notString
unpackBool :: LispVal -> ThrowsError Bool
unpackBool (Bool b) = return b
unpackBool notBool = throwError $ TypeMismatch "boolean" notBool
-- | Implementing 'car'.
-- Rules:
-- (car (a b c)) = a
-- (car (a)) = a
-- (car (a b . c)) = a
-- (car a) = error (not a list)
-- (car a b) = error (car takes only one argument)
car :: [LispVal] -> ThrowsError LispVal
car [List (x : xs)] = return x
car [DottedList (x : xs) _] = return x
car [badArg] = throwError $ TypeMismatch "pair" badArg
car badArgList = throwError $ NumArgs 1 badArgList
-- | Implementing 'cdr'.
-- Rules:
-- (cdr (a b c)) = (b c)
-- (cdr (a b)) = (b)
-- (cdr (a)) = NIL
-- (cdr (a b . c)) = (b . c)
-- (cdr (a . b)) = b
-- (cdr a) = error (not list)
-- (cdr a b) = error (too many args)
cdr :: [LispVal] -> ThrowsError LispVal
cdr [List (x : xs)] = return $ List xs
cdr [DottedList [xs] x] = return x
cdr [DottedList (_ : xs@(a:as)) x] = return $ DottedList xs x
cdr [badArg] = throwError $ TypeMismatch "pair" badArg
cdr badArgList = throwError $ NumArgs 1 badArgList
-- | Implementing 'cons'.
-- Rules:
-- (cons x '()) = (x)
-- (cons x '(a b c ...)) = (x a b c ...)
-- (cons x '(a b c . d)) = (x a b c . d)
-- (cons x y) = (x . y)
-- (cons x) => error
cons :: [LispVal] -> ThrowsError LispVal
cons [x1, List []] = return $ List [x1]
cons [x, List xs] = return $ List $ [x] ++ xs
cons [x, DottedList xs xlast] = return $ DottedList (x:xs) xlast
cons [x1, x2] = return $ DottedList [x1] x2
cons badArgList = throwError $ NumArgs 2 badArgList
eqv :: [LispVal] -> ThrowsError LispVal
eqv [(Bool arg1), (Bool arg2)] = return $ Bool $ arg1 == arg2
eqv [(Number arg1), (Number arg2)] = return $ Bool $ arg1 == arg2
eqv [(String arg1), (String arg2)] = return $ Bool $ arg1 == arg2
eqv [(Atom arg1), (Atom arg2)] = return $ Bool $ arg1 == arg2
eqv [(DottedList xs x), (DottedList ys y)] = eqv [List $ xs ++ [x], List $ ys ++ [y]]
eqv [(List arg1), (List arg2)] = return $ Bool $ (length arg1 == length arg2) &&
(and $ map eqvPair $ zip arg1 arg2)
where eqvPair (x1, x2) = case eqv [x1, x2] of
Left err -> False
Right (Bool val) -> val
eqv [_, _] = return $ Bool False
eqv badArgList = throwError $ NumArgs 2 badArgList
data Unpacker = forall a. Eq a => AnyUnpacker (LispVal -> ThrowsError a)
unpackEquals :: LispVal -> LispVal -> Unpacker -> ThrowsError Bool
unpackEquals arg1 arg2 (AnyUnpacker unpacker) =
do{ unpacked1 <- unpacker arg1;
unpacked2 <- unpacker arg2;
return $ unpacked1 == unpacked2
} `catchError` (const $ return False)
equal :: [LispVal] -> ThrowsError LispVal
equal [arg1, arg2] = do
primitiveEquals <- liftM or $ mapM (unpackEquals arg1 arg2)
[AnyUnpacker unpackNum, AnyUnpacker unpackStr, AnyUnpacker unpackBool]
eqvEquals <- eqv [arg1, arg2]
return $ Bool $ (primitiveEquals || let (Bool x) = eqvEquals in x)
equal badArgList = throwError $ NumArgs 2 badArgList
-- | Environment implementation.
type Env = IORef [(String, IORef LispVal)]
nullEnv :: IO Env
nullEnv = newIORef []
isBound :: Env -> String -> IO Bool
isBound envRef var = readIORef envRef >>= return . maybe False (const True) . lookup var
getVar :: Env -> String -> IOThrowsError LispVal
getVar envRef var = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Getting an unbound variable" var)
(liftIO . readIORef)
(lookup var env)
setVar :: Env -> String -> LispVal -> IOThrowsError LispVal
setVar envRef var value = do env <- liftIO $ readIORef envRef
maybe (throwError $ UnboundVar "Setting an unbound variable" var)
(liftIO . (flip writeIORef value))
(lookup var env)
return value
defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal
defineVar envRef var value = do
alreadyDefined <- liftIO $ isBound envRef var
if alreadyDefined
then setVar envRef var value >> return value
else liftIO $ do
valueRef <- newIORef value
env <- readIORef envRef
writeIORef envRef ((var, valueRef) : env)
return value
bindVars :: Env -> [(String, LispVal)] -> IO Env
bindVars envRef bindings = readIORef envRef >>= extendEnv bindings >>= newIORef
where extendEnv bindings env = liftM (++ env) (mapM addBinding bindings)
addBinding (var, value) = do ref <- newIORef value
return (var, ref)
| spockwangs/scheme.in.haskell | list9.hs | unlicense | 18,213 | 0 | 15 | 5,601 | 6,057 | 3,085 | 2,972 | -1 | -1 |
module Prob where
import Data.Ratio
newtype Prob a = Prob { getProb :: [(a, Rational)] } deriving Show
instance Functor Prob where
fmap f (Prob xs) = Prob $ map (\(x, p) -> (f x, p)) xs
instance Monad Prob where
return x = Prob [(x, 1 % 1)]
-- [(x, p)] >>= f = Prob [(f x, p)]
-- (x, p):xs >>= f = Prob ((f x, p):(xs >>= f))
-- fail _ = Prob []
m >>= f = flatten (fmap f m)
fail _ = Prob []
thisSituation :: Prob (Prob Char)
thisSituation = Prob
[(Prob [('a', 1%2),('b', 1%2)], 1%4)
,(Prob [('c', 1%2),('d', 1%2)], 3%4)
]
flatten :: Prob (Prob a) -> Prob a
flatten (Prob xs) = Prob $ concat $ map multAll xs
where multAll (Prob innerxs, p) = map (\(x, r) -> (x, p*r)) innerxs
data Coin = Heads | Tails deriving (Show, Eq)
coin :: Prob Coin
coin = Prob [(Heads, 1 % 2), (Tails, 1 % 2)]
loadedCoin :: Prob Coin
loadedCoin = Prob [(Heads, 1%10), (Tails, 9%10)]
flipThree :: Prob Bool
flipThree = do
a <- coin
b <- coin
c <- loadedCoin
return (all (== Tails) [a, b, c])
| alexliew/learn_you_a_haskell | code/prob.hs | unlicense | 1,002 | 0 | 11 | 235 | 529 | 292 | 237 | 27 | 1 |
-- Copyright 2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import Control.Exception (evaluate, try)
import Data.Bifunctor (first)
import Data.Functor (void)
import Data.Proxy (Proxy(..))
import GHC.Exception (ErrorCall)
import GHC.TypeNats (SomeNat(..), someNatVal, natVal)
import Numeric.Natural (Natural)
import Test.Framework (defaultMain)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
( (===), (==>), forAll, Gen, arbitrary, ioProperty, scale
, Positive(..), Negative(..), Property
)
import Data.SInt
maxInt :: Natural
maxInt = fromIntegral (maxBound @Int)
naturals :: Gen Natural
naturals = fromInteger . getPositive <$> arbitrary
raisesError :: a -> Property
raisesError x = ioProperty $ do
r <- try @ErrorCall $ evaluate x
return $ void (first (const ()) r) === Left ()
main :: IO ()
main = defaultMain
[ testProperty "trySIntVal in bounds" $ forAll naturals $
\x -> x <= maxInt ==> case someNatVal x of
SomeNat (Proxy :: Proxy n) ->
fmap (fromIntegral . unSInt) (trySIntVal @n) === Just x
, testProperty "trySIntVal out of bounds" $ forAll naturals $
\x -> case someNatVal (maxInt + x) of
SomeNat (Proxy :: Proxy n) ->
void (trySIntVal @n) === Nothing
, testProperty "withSInt negative raises" $ \ (Negative x) ->
raisesError $ withSInt x $ const ()
, testProperty "withSInt positive" $ \ (Positive x) ->
withSInt x unSInt === x
, testProperty "addSInt" $
\ (Positive x) (Positive y) ->
withSInt x $ \x' ->
withSInt y $ \y' ->
let xy = fromIntegral x + fromIntegral y :: Natural
in if xy > maxInt
then raisesError $ addSInt x' y'
else fromIntegral (unSInt (addSInt x' y')) === xy
, testProperty "addSInt out of range" $
raisesError $ withSInt maxBound $ \x -> withSInt 1 (unSInt . addSInt x)
, testProperty "subSInt" $
\ (Positive x) (Positive y) ->
withSInt x $ \x' ->
withSInt y $ \y' ->
if x < y
then raisesError $ subSInt x' y'
else unSInt (subSInt x' y') === x - y
, testProperty "mulSInt" $
forAll (scale (*1000000000) arbitrary) $ \ (Positive x) ->
forAll (scale (*1000000000) arbitrary) $ \ (Positive y) ->
withSInt x $ \x' ->
withSInt y $ \y' ->
let xy = fromIntegral x * fromIntegral y :: Natural
in if xy > maxInt
then raisesError $ mulSInt x' y'
else fromIntegral (unSInt (mulSInt x' y')) === xy
, testProperty "reifySInt" $
\ (Positive x) ->
withSInt x $ \ (x' :: SInt n) ->
fromIntegral x === reifySInt x' (natVal @n Proxy)
]
| google/hs-fin-vec | sint/test/Main.hs | apache-2.0 | 3,372 | 0 | 23 | 871 | 1,015 | 535 | 480 | 68 | 4 |
module Main where
import BasePrelude
import Tsds.Prim.Types
import Tsds.Prim.Unbox
import Tsds.SQL
main :: IO ()
main = putStrLn "Hello World"
| buckie/tsds | src/Main.hs | apache-2.0 | 186 | 0 | 6 | 63 | 42 | 25 | 17 | 7 | 1 |
module Util where
import Data.Set ( Set )
import Data.Set as Set ( fromList, member, filter )
type Point = (Int, Int)
-- | Generate a list of Point (r, c) according to the width and height
-- of the layout in the game, with r is the index of row
-- and c is the index of column.
gridPoints :: Int -> Int -> [Point]
gridPoints w h = [(r, c) | r <- [0 .. h - 1], c <- [0 .. w - 1]]
-- | Get tuple (width, height) from a two dimension list.
dimension :: [[Int]] -> (Int, Int)
dimension a = (length $ head a, length a)
rows = ['A'..'Z']
-- | Get neighbours of a Point in a Set.
neighboursOf :: Int -> Int -> Point -> Set Point
neighboursOf w h (r, c) = Set.filter (`member` gridPs) possibleNeighbours
where gridPs = fromList $ gridPoints w h
possibleNeighbours = fromList [(r, c - 1), (r, c + 1),
(r + 1, c), (r + 1, c + 1), (r + 1, c - 1),
(r - 1, c), (r - 1, c + 1), (r - 1, c - 1)]
numAtPoint nums (r, c) = nums !! r !! c | ljishen/Minesweeper | src/Util.hs | apache-2.0 | 1,042 | 0 | 10 | 328 | 394 | 230 | 164 | 16 | 1 |
-- | Simple parallel genetic algorithm implementation.
--
-- > import AI.GeneticAlgorithm.Simple
-- > import System.Random
-- > import Text.Printf
-- > import Data.List as L
-- > import Control.DeepSeq
-- >
-- > newtype SinInt = SinInt [Double]
-- >
-- > instance NFData SinInt where
-- > rnf (SinInt xs) = rnf xs `seq` ()
-- >
-- > instance Show SinInt where
-- > show (SinInt []) = "<empty SinInt>"
-- > show (SinInt (x:xs)) =
-- > let start = printf "%.5f" x
-- > end = concat $ zipWith (\c p -> printf "%+.5f" c ++ "X^" ++ show p) xs [1 :: Int ..]
-- > in start ++ end
-- >
-- > polynomialOrder = 4 :: Int
-- >
-- > err :: SinInt -> Double
-- > err (SinInt xs) =
-- > let f x = snd $ L.foldl' (\(mlt,s) coeff -> (mlt*x, s + coeff*mlt)) (1,0) xs
-- > in maximum [ abs $ sin x - f x | x <- [0.0,0.001 .. pi/2]]
-- >
-- > instance Chromosome SinInt where
-- > crossover g (SinInt xs) (SinInt ys) =
-- > ( [ SinInt (L.zipWith (\x y -> (x+y)/2) xs ys) ], g)
-- >
-- > mutation g (SinInt xs) =
-- > let (idx, g') = randomR (0, length xs - 1) g
-- > (dx, g'') = randomR (-10.0, 10.0) g'
-- > t = xs !! idx
-- > xs' = take idx xs ++ [t + t*dx] ++ drop (idx+1) xs
-- > in (SinInt xs', g'')
-- >
-- > fitness int =
-- > let max_err = 1000.0 in
-- > max_err - (min (err int) max_err)
-- >
-- > randomSinInt gen =
-- > let (lst, gen') =
-- > L.foldl'
-- > (\(xs, g) _ -> let (x, g') = randomR (-10.0,10.0) g in (x:xs,g') )
-- > ([], gen) [0..polynomialOrder]
-- > in (SinInt lst, gen')
-- >
-- > stopf :: SinInt -> Int -> IO Bool
-- > stopf best gnum = do
-- > let e = err best
-- > _ <- printf "Generation: %02d, Error: %.8f\n" gnum e
-- > return $ e < 0.0002 || gnum > 20
-- >
-- > main = do
-- > int <- runGAIO 64 0.1 randomSinInt stopf
-- > putStrLn ""
-- > putStrLn $ "Result: " ++ show int
module AI.GeneticAlgorithm.Simple (
Chromosome(..),
runGA,
runGAIO,
zeroGeneration,
nextGeneration
) where
import System.Random
import qualified Data.List as L
import Control.Parallel.Strategies
-- | Chromosome interface
class NFData a => Chromosome a where
-- | Crossover function
crossover :: RandomGen g => g -> a -> a -> ([a],g)
-- | Mutation function
mutation :: RandomGen g => g -> a -> (a,g)
-- | Fitness function. fitness x > fitness y means that x is better than y
fitness :: a -> Double
-- | Pure GA implementation.
runGA :: (RandomGen g, Chromosome a)
=> g -- ^ Random number generator
-> Int -- ^ Population size
-> Double -- ^ Mutation probability [0, 1]
-> (g -> (a, g)) -- ^ Random chromosome generator (hint: use currying or closures)
-> (a -> Int -> Bool) -- ^ Stopping criteria, 1st arg - best chromosome, 2nd arg - generation number
-> a -- ^ Best chromosome
runGA gen ps mp rnd stopf =
let (pop, gen') = zeroGeneration gen rnd ps in
runGA' gen' pop ps mp stopf 0
runGA' gen pop ps mp stopf gnum =
let best = head pop in
if stopf best gnum
then best
else
let (pop', gen') = nextGeneration gen pop ps mp in
runGA' gen' pop' ps mp stopf (gnum+1)
-- | Non-pure GA implementation.
runGAIO :: Chromosome a
=> Int -- ^ Population size
-> Double -- ^ Mutation probability [0, 1]
-> (StdGen -> (a, StdGen)) -- ^ Random chromosome generator (hint: use currying or closures)
-> (a -> Int -> IO Bool) -- ^ Stopping criteria, 1st arg - best chromosome, 2nd arg - generation number
-> IO a -- ^ Best chromosome
runGAIO ps mp rnd stopf = do
gen <- newStdGen
let (pop, gen') = zeroGeneration gen rnd ps
runGAIO' gen' pop ps mp stopf 0
runGAIO' gen pop ps mp stopf gnum = do
let best = head pop
stop <- stopf best gnum
if stop
then return best
else do
let (pop', gen') = nextGeneration gen pop ps mp
runGAIO' gen' pop' ps mp stopf (gnum+1)
-- | Generate zero generation. Use this function only if you are going to implement your own runGA.
zeroGeneration :: (RandomGen g)
=> g -- ^ Random number generator
-> (g -> (a, g)) -- ^ Random chromosome generator (hint: use closures)
-> Int -- ^ Population size
-> ([a],g) -- ^ Zero generation and new RNG
zeroGeneration initGen rnd ps =
L.foldl'
(\(xs,gen) _ -> let (c, gen') = rnd gen in ((c:xs),gen'))
([], initGen) [1..ps]
-- | Generate next generation (in parallel) using mutation and crossover.
-- Use this function only if you are going to implement your own runGA.
nextGeneration :: (RandomGen g, Chromosome a)
=> g -- ^ Random number generator
-> [a] -- ^ Current generation
-> Int -- ^ Population size
-> Double -- ^ Mutation probability
-> ([a], g) -- ^ Next generation ordered by fitness (best - first) and new RNG
nextGeneration gen pop ps mp =
let (gen':gens) = L.unfoldr (Just . split) gen
chunks = L.zip gens $ init $ L.tails pop
results = map (\(g, (x:ys)) -> [ (t, fitness t) | t <- nextGeneration' [ (x, y) | y <- ys ] g mp [] ]) chunks
`using` parList rdeepseq
lst = take ps $ L.sortBy (\(_, fx) (_, fy) -> fy `compare` fx) $ concat results
in ( map fst lst, gen' )
nextGeneration' [] _ _ acc = acc
nextGeneration' ((p1,p2):ps) g0 mp acc =
let (children0, g1) = crossover g0 p1 p2
(children1, g2) = L.foldl'
(\(xs, g) x -> let (x', g') = mutate g x mp in (x':xs, g'))
([],g1) children0
in
nextGeneration' ps g2 mp (children1 ++ acc)
mutate :: (RandomGen g, Chromosome a) => g -> a -> Double -> (a, g)
mutate gen x mp =
let (r, gen') = randomR (0.0, 1.0) gen in
if r <= mp then mutation gen' x
else (x, gen')
| octopuscabbage/simple-genetic-algorithm | src/AI/GeneticAlgorithm/Simple.hs | bsd-2-clause | 6,341 | 0 | 19 | 2,151 | 1,318 | 738 | 580 | 81 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDirModel.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.QDirModel (
Roles, eFileIconRole, eFilePathRole, eFileNameRole
)
where
import Foreign.C.Types
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CRoles a = CRoles a
type Roles = QEnum(CRoles Int)
ieRoles :: Int -> Roles
ieRoles x = QEnum (CRoles x)
instance QEnumC (CRoles Int) where
qEnum_toInt (QEnum (CRoles x)) = x
qEnum_fromInt x = QEnum (CRoles 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 -> Roles -> 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 ()
eFileIconRole :: Roles
eFileIconRole
= ieRoles $ 1
eFilePathRole :: Roles
eFilePathRole
= ieRoles $ 33
eFileNameRole :: Roles
eFileNameRole
= ieRoles $ 34
| keera-studios/hsQt | Qtc/Enums/Gui/QDirModel.hs | bsd-2-clause | 2,368 | 0 | 18 | 532 | 612 | 313 | 299 | 55 | 1 |
{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
module Network.SearchEngine where
import qualified Data.Text as T
import qualified Data.Vector as V
import Network.HTTP.Types
import Network.URL
class SearchEngine a where
-- I think I'd just rather have a type synonym here, but I run into injectivity stuff
data Config a :: *
data Results a :: *
maxResultsPerSearch :: a -> Int
shortName :: a -> String
messages :: a -> Messages
mkRequest :: Config a -> Int -> String -> (URL, [Header])
allowMultiSearch :: Config a -> Bool -- ^ user explicitly allows us to do multishot searches
-- | results from a search
items :: Results a -> V.Vector Result
-- | total results (if the search engine tells us)
-- This includes results that have not been returned in this query,
-- so it's not the same as (@length . items@)
totalResults :: Results a -> Maybe Int
data Result = Result
{ snippet :: T.Text
, url :: T.Text
}
data Messages = Messages
{ configFileNotFound :: FilePath -> T.Text
, configParseError :: FilePath -> T.Text
, configInstructions :: FilePath -> T.Text
, dareNotMultiSearch :: FilePath -> Int -> T.Text
}
| kowey/customsearch | Network/SearchEngine.hs | bsd-3-clause | 1,276 | 0 | 11 | 356 | 249 | 146 | 103 | 24 | 0 |
{-# LANGUAGE TemplateHaskell, LambdaCase, RecordWildCards, RankNTypes #-}
module AbstractInterpretation.LiveVariable.CodeGenBase where
import Data.Int
import Data.Word
import Data.Set (Set)
import Data.Map (Map)
import Data.Vector (Vector)
import qualified Data.Bimap as Bimap
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Vector as Vec
import Control.Monad.State
import Lens.Micro.Platform
import Grin.Grin
import Grin.TypeEnvDefs
import AbstractInterpretation.IR (Instruction(..), Reg(..))
import qualified AbstractInterpretation.IR as IR
import AbstractInterpretation.EffectTracking.Result
data CGState
= CGState
{ _sMemoryCounter :: Word32
, _sRegisterCounter :: Word32
, _sInstructions :: [Instruction]
-- mapping
, _sRegisterMap :: Map.Map Name Reg
, _sFunctionArgMap :: Map.Map Name (Reg, [Reg])
, _sTagMap :: Bimap.Bimap Tag IR.Tag
, _sExternalMap :: Map.Map Name External
}
deriving (Show)
concat <$> mapM makeLenses [''CGState]
emptyCGState :: CGState
emptyCGState = CGState
{ _sMemoryCounter = 0
, _sRegisterCounter = 0
, _sInstructions = []
-- mapping
, _sRegisterMap = mempty
, _sFunctionArgMap = mempty
, _sTagMap = Bimap.empty
, _sExternalMap = mempty
}
type CG = State CGState
data Result
= R IR.Reg
| Z
| A CPat (CG Result)
emit :: IR.Instruction -> CG ()
emit inst = modify' $ \s@CGState{..} -> s {_sInstructions = inst : _sInstructions}
addExternal :: External -> CG ()
addExternal e = modify' $ \s@CGState{..} -> s {_sExternalMap = Map.insert (eName e) e _sExternalMap}
getExternal :: Name -> CG (Maybe External)
getExternal name = Map.lookup name <$> gets _sExternalMap
-- creates regsiters for function arguments and result
getOrAddFunRegs :: Name -> Int -> CG (IR.Reg, [IR.Reg])
getOrAddFunRegs name arity = do
funMap <- gets _sFunctionArgMap
case Map.lookup name funMap of
Just x -> pure x
Nothing -> do
resReg <- newReg
argRegs <- replicateM arity newReg
let funRegs = (resReg, argRegs)
modify' $ \s@CGState{..} -> s {_sFunctionArgMap = Map.insert name funRegs _sFunctionArgMap}
pure funRegs
newReg :: CG IR.Reg
newReg = state $ \s@CGState{..} -> (IR.Reg _sRegisterCounter, s {_sRegisterCounter = succ _sRegisterCounter})
newMem :: CG IR.Mem
newMem = state $ \s@CGState{..} -> (IR.Mem _sMemoryCounter, s {_sMemoryCounter = succ _sMemoryCounter})
addReg :: Name -> IR.Reg -> CG ()
addReg name reg = modify' $ \s@CGState{..} -> s {_sRegisterMap = Map.insert name reg _sRegisterMap}
getReg :: Name -> CG IR.Reg
getReg name = do
regMap <- gets _sRegisterMap
case Map.lookup name regMap of
Nothing -> error $ "unknown variable " ++ unpackName name
Just reg -> pure reg
getTag :: Tag -> CG IR.Tag
getTag tag = do
tagMap <- gets _sTagMap
case Bimap.lookup tag tagMap of
Just t -> pure t
Nothing -> do
let t = IR.Tag . fromIntegral $ Bimap.size tagMap
modify' $ \s -> s {_sTagMap = Bimap.insert tag t tagMap}
pure t
codeGenBlock :: CG a -> CG (a,[IR.Instruction])
codeGenBlock genM = do
instructions <- state $ \s@CGState{..} -> (_sInstructions, s {_sInstructions = []})
ret <- genM
blockInstructions <- state $ \s@CGState{..} -> (reverse _sInstructions, s {_sInstructions = instructions})
pure (ret, blockInstructions)
codeGenBlock_ :: CG a -> CG [IR.Instruction]
codeGenBlock_ = fmap snd . codeGenBlock
codeGenSimpleType :: SimpleType -> CG IR.Reg
codeGenSimpleType = \case
T_Unit -> newRegWithSimpleType (-1)
T_Int64 -> newRegWithSimpleType (-2)
T_Word64 -> newRegWithSimpleType (-3)
T_Float -> newRegWithSimpleType (-4)
T_Bool -> newRegWithSimpleType (-5)
T_String -> newRegWithSimpleType (-6)
T_Char -> newRegWithSimpleType (-7)
T_UnspecifiedLocation -> newRegWithSimpleType (-8)
T_Location locs -> do
r <- newReg
let locs' = map fromIntegral locs
mapM_ (`extendSimpleType` r) locs'
pure r
t -> newReg
where
-- TODO: rename simple type to something more generic,
newRegWithSimpleType :: IR.SimpleType -> CG IR.Reg
newRegWithSimpleType irTy = newReg >>= extendSimpleType irTy
-- TODO: rename simple type to something more generic,
extendSimpleType :: IR.SimpleType -> IR.Reg -> CG IR.Reg
extendSimpleType irTy r = do
emit IR.Set
{ dstReg = r
, constant = IR.CSimpleType irTy
}
pure r
codeGenNodeSetWith :: (Tag -> Vector SimpleType -> CG IR.Reg) ->
NodeSet -> CG IR.Reg
codeGenNodeSetWith cgNodeTy ns = do
let (tags, argss) = unzip . Map.toList $ ns
dst <- newReg
nodeRegs <- zipWithM cgNodeTy tags argss
forM_ nodeRegs $ \src -> emit IR.Move { srcReg = src, dstReg = dst }
pure dst
-- Generate a node type from type information,
-- but preserve the first field for tag information.
codeGenTaggedNodeType :: Tag -> Vector SimpleType -> CG IR.Reg
codeGenTaggedNodeType tag ts = do
let ts' = Vec.toList ts
r <- newReg
irTag <- getTag tag
argRegs <- mapM codeGenSimpleType ts'
emit IR.Set {dstReg = r, constant = IR.CNodeType irTag (length argRegs + 1)}
forM_ (zip [1..] argRegs) $ \(idx, argReg) ->
emit IR.Extend {srcReg = argReg, dstSelector = IR.NodeItem irTag idx, dstReg = r}
pure r
-- FIXME: the following type signature is a bad oman ; it's not intuitive ; no-go ; refactor!
codeGenType :: (SimpleType -> CG IR.Reg) ->
(NodeSet -> CG IR.Reg) ->
Type -> CG IR.Reg
codeGenType cgSimpleTy cgNodeTy = \case
T_SimpleType t -> cgSimpleTy t
T_NodeSet ns -> cgNodeTy ns
isPointer :: IR.Predicate
isPointer = IR.ValueIn (IR.Range 0 (maxBound :: Int32))
ptrLowerBound :: Int32
ptrLowerBound = 0
live :: Int32
live = -1
sideEffecting :: Int32
sideEffecting = -2
-- NOTE: Exclusive upper bound
isLivenessInfo :: IR.Predicate
isLivenessInfo = IR.ValueIn (IR.Range live ptrLowerBound)
-- NOTE: Exclusive upper bound
isEffectInfo :: IR.Predicate
isEffectInfo = IR.ValueIn (IR.Range sideEffecting live)
-- For simple types, copies only pointer information
-- For nodes, copies the structure and the pointer information in the fields
copyStructureWithPtrInfo :: IR.Reg -> IR.Reg -> IR.Instruction
copyStructureWithPtrInfo srcReg dstReg = IR.ConditionalMove
{ srcReg = srcReg
, predicate = isPointer
, dstReg = dstReg
}
-- For simple types, copies only non-pointer information.
-- For nodes, copies the structure and the non-pointer information in the fields.
-- In the case of LVA, no literal type info is propagated,
-- so any non-pointer info is liveness info (the value of -1).
copyStructureWithLivenessInfo :: IR.Reg -> IR.Reg -> IR.Instruction
copyStructureWithLivenessInfo srcReg dstReg = IR.ConditionalMove
{ srcReg = srcReg
, predicate = isLivenessInfo
, dstReg = dstReg
}
copyStructureWithEffectInfo :: IR.Reg -> IR.Reg -> IR.Instruction
copyStructureWithEffectInfo srcReg dstReg = IR.ConditionalMove
{ srcReg = srcReg
, predicate = isEffectInfo
, dstReg = dstReg
}
| andorp/grin | grin/src/AbstractInterpretation/LiveVariable/CodeGenBase.hs | bsd-3-clause | 7,164 | 0 | 17 | 1,525 | 2,179 | 1,150 | 1,029 | 164 | 10 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
-- | <http://www.libtorrent.org/reference-Core.html#torrent_status torrent_status> for "Libtorrent"
module Network.Libtorrent.TorrentHandle.TorrentStatus (TorrentState(..)
, TorrentStatus(..)
, getError
, getSavePath
, getName
, getTorrentStatusNextAnnounce
, getCurrentTracker
, getTotalDownload
, getTotalUpload
, getTotalPayloadDownload
, getTotalPayloadUpload
, getTotalFailedBytes
, getTotalRedundantBytes
, getPieces
, getVerifiedPieces
, getTotalDone
, getTotalWantedDone
, getTotalWanted
, getAllTimeUpload
, getAllTimeDownload
, getAddedTime
, getCompletedTime
, getLastSeenComplete
, getProgress
, getProgressPpm
, getQueuePosition
, getDownloadRate
, getUploadRate
, getDownloadPayloadRate
, getUploadPayloadRate
, getNumSeeds
, getNumPeers
, getNumComplete
, getNumIncomplete
, getListSeeds
, getListPeers
, getConnectCandidates
, getNumPieces
, getDistributedFullCopies
, getDistributedFraction
, getDistributedCopies
, getBlockSize
, getNumUploads
, getNumConnections
, getUploadsLimit
, getConnectionsLimit
, getUpBandwidthQueue
, getDownBandwidthQueue
, getTimeSinceUpload
, getTimeSinceDownload
, getActiveTime
, getFinishedTime
, getSeedingTime
, getSeedRank
, getLastScrape
, getPriority
, getState
, getNeedSaveResume
, getIpFilterApplies
, getUploadMode
, getShareMode
, getSuperSeeding
, getPaused
, getAutoManaged
, getSequentialDownload
, getIsSeeding
, getIsFinished
, getHasMetadata
, getHasIncoming
, getSeedMode
, getMovingStorage
, getTorrentStatusInfoHash
) where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Array.BitArray (BitArray)
import Data.Int (Int64)
import Data.Text (Text)
import Foreign.C.Types (CInt)
import Foreign.ForeignPtr (ForeignPtr, withForeignPtr)
import Foreign.Marshal.Utils (toBool)
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Unsafe as CU
import Network.Libtorrent.Bitfield
import Network.Libtorrent.Inline
import Network.Libtorrent.Internal
import Network.Libtorrent.Sha1Hash (Sha1Hash)
import Network.Libtorrent.String
import Network.Libtorrent.Types
C.context libtorrentCtx
C.include "<libtorrent/torrent_handle.hpp>"
C.include "torrent_handle.hpp"
C.using "namespace libtorrent"
C.using "namespace std"
data TorrentState =
QueuedForChecking
| CheckingFiles
| DownloadingMetadata
| Downloading
| Finished
| Seeding
| Allocating
| CheckingResumeData
deriving (Show, Enum, Bounded, Eq, Ord)
newtype TorrentStatus = TorrentStatus { unTorrentStatus :: ForeignPtr (CType TorrentStatus)}
instance Show TorrentStatus where
show _ = "TorrentStatus"
instance Inlinable TorrentStatus where
type (CType TorrentStatus) = C'TorrentStatus
instance FromPtr TorrentStatus where
fromPtr = objFromPtr TorrentStatus $ \ptr ->
[CU.exp| void { delete $(torrent_status * ptr); } |]
instance WithPtr TorrentStatus where
withPtr (TorrentStatus fptr) = withForeignPtr fptr
getError :: MonadIO m => TorrentStatus -> m Text
getError ho =
liftIO . withPtr ho $ \hoPtr -> do
res <- fromPtr [CU.exp| string * { new std::string($(torrent_status * hoPtr)->error) } |]
stdStringToText res
getSavePath :: MonadIO m => TorrentStatus -> m Text
getSavePath ho =
liftIO . withPtr ho $ \hoPtr -> do
res <- fromPtr [CU.exp| string * { new std::string($(torrent_status * hoPtr)->save_path) } |]
stdStringToText res
getName :: MonadIO m => TorrentStatus -> m Text
getName ho =
liftIO . withPtr ho $ \hoPtr -> do
res <- fromPtr [CU.exp| string * { new std::string($(torrent_status * hoPtr)->name) } |]
stdStringToText res
getTorrentStatusNextAnnounce :: MonadIO m => TorrentStatus -> m C.CLong
getTorrentStatusNextAnnounce ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| long { $(torrent_status * hoPtr)->next_announce.total_seconds() } |]
getCurrentTracker :: MonadIO m => TorrentStatus -> m Text
getCurrentTracker ho =
liftIO . withPtr ho $ \hoPtr -> do
res <- fromPtr [CU.exp| string * { new std::string($(torrent_status * hoPtr)->current_tracker) } |]
stdStringToText res
getTotalDownload :: MonadIO m => TorrentStatus -> m Int64
getTotalDownload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_download } |]
getTotalUpload :: MonadIO m => TorrentStatus -> m Int64
getTotalUpload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_upload } |]
getTotalPayloadDownload :: MonadIO m => TorrentStatus -> m Int64
getTotalPayloadDownload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_payload_download } |]
getTotalPayloadUpload :: MonadIO m => TorrentStatus -> m Int64
getTotalPayloadUpload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_payload_upload } |]
getTotalFailedBytes :: MonadIO m => TorrentStatus -> m Int64
getTotalFailedBytes ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_failed_bytes } |]
getTotalRedundantBytes :: MonadIO m => TorrentStatus -> m Int64
getTotalRedundantBytes ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_redundant_bytes } |]
getPieces :: MonadIO m => TorrentStatus -> m (BitArray Int)
getPieces ho =
liftIO . withPtr ho $ \hoPtr -> do
bf <- fromPtr [CU.exp| bitfield * { new bitfield($(torrent_status * hoPtr)->pieces) } |]
bitfieldToBitArray bf
getVerifiedPieces :: MonadIO m => TorrentStatus -> m (BitArray Int)
getVerifiedPieces ho =
liftIO . withPtr ho $ \hoPtr -> do
bf <- fromPtr [CU.exp| bitfield * { new bitfield($(torrent_status * hoPtr)->verified_pieces) } |]
bitfieldToBitArray bf
getTotalDone :: MonadIO m => TorrentStatus -> m Int64
getTotalDone ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_done } |]
getTotalWantedDone :: MonadIO m => TorrentStatus -> m Int64
getTotalWantedDone ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_wanted_done } |]
getTotalWanted :: MonadIO m => TorrentStatus -> m Int64
getTotalWanted ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->total_wanted } |]
getAllTimeUpload :: MonadIO m => TorrentStatus -> m Int64
getAllTimeUpload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->all_time_upload } |]
getAllTimeDownload :: MonadIO m => TorrentStatus -> m Int64
getAllTimeDownload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int64_t { $(torrent_status * hoPtr)->all_time_download } |]
getAddedTime :: MonadIO m => TorrentStatus -> m C.CTime
getAddedTime ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| time_t { $(torrent_status * hoPtr)->added_time } |]
getCompletedTime :: MonadIO m => TorrentStatus -> m C.CTime
getCompletedTime ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| time_t { $(torrent_status * hoPtr)->completed_time } |]
getLastSeenComplete :: MonadIO m => TorrentStatus -> m C.CTime
getLastSeenComplete ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| time_t { $(torrent_status * hoPtr)->last_seen_complete } |]
getProgress :: MonadIO m => TorrentStatus -> m C.CFloat
getProgress ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| float { $(torrent_status * hoPtr)->progress } |]
getProgressPpm :: MonadIO m => TorrentStatus -> m CInt
getProgressPpm ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->progress_ppm } |]
getQueuePosition :: MonadIO m => TorrentStatus -> m CInt
getQueuePosition ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->queue_position } |]
getDownloadRate :: MonadIO m => TorrentStatus -> m CInt
getDownloadRate ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->download_rate } |]
getUploadRate :: MonadIO m => TorrentStatus -> m CInt
getUploadRate ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->upload_rate } |]
getDownloadPayloadRate :: MonadIO m => TorrentStatus -> m CInt
getDownloadPayloadRate ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->download_payload_rate } |]
getUploadPayloadRate :: MonadIO m => TorrentStatus -> m CInt
getUploadPayloadRate ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->upload_payload_rate } |]
getNumSeeds :: MonadIO m => TorrentStatus -> m CInt
getNumSeeds ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_seeds } |]
getNumPeers :: MonadIO m => TorrentStatus -> m CInt
getNumPeers ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_peers } |]
getNumComplete :: MonadIO m => TorrentStatus -> m CInt
getNumComplete ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_complete } |]
getNumIncomplete :: MonadIO m => TorrentStatus -> m CInt
getNumIncomplete ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_incomplete } |]
getListSeeds :: MonadIO m => TorrentStatus -> m CInt
getListSeeds ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->list_seeds } |]
getListPeers :: MonadIO m => TorrentStatus -> m CInt
getListPeers ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->list_peers } |]
getConnectCandidates :: MonadIO m => TorrentStatus -> m CInt
getConnectCandidates ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->connect_candidates } |]
getNumPieces :: MonadIO m => TorrentStatus -> m CInt
getNumPieces ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_pieces } |]
getDistributedFullCopies :: MonadIO m => TorrentStatus -> m CInt
getDistributedFullCopies ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->distributed_full_copies } |]
getDistributedFraction :: MonadIO m => TorrentStatus -> m CInt
getDistributedFraction ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->distributed_fraction } |]
getDistributedCopies :: MonadIO m => TorrentStatus -> m C.CFloat
getDistributedCopies ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| float { $(torrent_status * hoPtr)->distributed_copies } |]
getBlockSize :: MonadIO m => TorrentStatus -> m CInt
getBlockSize ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->block_size } |]
getNumUploads :: MonadIO m => TorrentStatus -> m CInt
getNumUploads ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_uploads } |]
getNumConnections :: MonadIO m => TorrentStatus -> m CInt
getNumConnections ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->num_connections } |]
getUploadsLimit :: MonadIO m => TorrentStatus -> m CInt
getUploadsLimit ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->uploads_limit } |]
getConnectionsLimit :: MonadIO m => TorrentStatus -> m CInt
getConnectionsLimit ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->connections_limit } |]
getUpBandwidthQueue :: MonadIO m => TorrentStatus -> m CInt
getUpBandwidthQueue ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->up_bandwidth_queue } |]
getDownBandwidthQueue :: MonadIO m => TorrentStatus -> m CInt
getDownBandwidthQueue ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->down_bandwidth_queue } |]
getTimeSinceUpload :: MonadIO m => TorrentStatus -> m CInt
getTimeSinceUpload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->time_since_upload } |]
getTimeSinceDownload :: MonadIO m => TorrentStatus -> m CInt
getTimeSinceDownload ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->time_since_download } |]
getActiveTime :: MonadIO m => TorrentStatus -> m CInt
getActiveTime ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->active_time } |]
getFinishedTime :: MonadIO m => TorrentStatus -> m CInt
getFinishedTime ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->finished_time } |]
getSeedingTime :: MonadIO m => TorrentStatus -> m CInt
getSeedingTime ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->seeding_time } |]
getSeedRank :: MonadIO m => TorrentStatus -> m CInt
getSeedRank ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->seed_rank } |]
getLastScrape :: MonadIO m => TorrentStatus -> m CInt
getLastScrape ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->last_scrape } |]
getPriority :: MonadIO m => TorrentStatus -> m CInt
getPriority ho =
liftIO . withPtr ho $ \hoPtr ->
[CU.exp| int { $(torrent_status * hoPtr)->priority } |]
getState :: MonadIO m => TorrentStatus -> m TorrentState
getState ho =
liftIO . withPtr ho $ \hoPtr ->
toEnum . fromIntegral <$> [CU.exp| int { $(torrent_status * hoPtr)->state } |]
getNeedSaveResume :: MonadIO m => TorrentStatus -> m Bool
getNeedSaveResume ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->need_save_resume } |]
getIpFilterApplies :: MonadIO m => TorrentStatus -> m Bool
getIpFilterApplies ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->ip_filter_applies } |]
getUploadMode :: MonadIO m => TorrentStatus -> m Bool
getUploadMode ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->upload_mode } |]
getShareMode :: MonadIO m => TorrentStatus -> m Bool
getShareMode ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->share_mode } |]
getSuperSeeding :: MonadIO m => TorrentStatus -> m Bool
getSuperSeeding ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->super_seeding } |]
getPaused :: MonadIO m => TorrentStatus -> m Bool
getPaused ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->paused } |]
getAutoManaged :: MonadIO m => TorrentStatus -> m Bool
getAutoManaged ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->auto_managed } |]
getSequentialDownload :: MonadIO m => TorrentStatus -> m Bool
getSequentialDownload ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->sequential_download } |]
getIsSeeding :: MonadIO m => TorrentStatus -> m Bool
getIsSeeding ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->is_seeding } |]
getIsFinished :: MonadIO m => TorrentStatus -> m Bool
getIsFinished ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->is_finished } |]
getHasMetadata :: MonadIO m => TorrentStatus -> m Bool
getHasMetadata ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->has_metadata } |]
getHasIncoming :: MonadIO m => TorrentStatus -> m Bool
getHasIncoming ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->has_incoming } |]
getSeedMode :: MonadIO m => TorrentStatus -> m Bool
getSeedMode ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->seed_mode } |]
getMovingStorage :: MonadIO m => TorrentStatus -> m Bool
getMovingStorage ho =
liftIO . withPtr ho $ \hoPtr ->
toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->moving_storage } |]
-- TODO: Will be available in libtorrent 1.1.0
-- getIsLoaded :: MonadIO m => TorrentStatus -> m Bool
-- getIsLoaded ho =
-- liftIO . withPtr ho $ \hoPtr ->
-- toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->is_loaded } |]
-- getAnnouncingToTrackers :: MonadIO m => TorrentStatus -> m Bool
-- getAnnouncingToTrackers ho =
-- liftIO . withPtr ho $ \hoPtr ->
-- toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->announcing_to_trackers } |]
-- getAnnouncingToLsd :: MonadIO m => TorrentStatus -> m Bool
-- getAnnouncingToLsd ho =
-- liftIO . withPtr ho $ \hoPtr ->
-- toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->announcing_to_lsd } |]
-- getAnnouncingToDht :: MonadIO m => TorrentStatus -> m Bool
-- getAnnouncingToDht ho =
-- liftIO . withPtr ho $ \hoPtr ->
-- toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->announcing_to_dht } |]
-- getStopWhenReady :: MonadIO m => TorrentStatus -> m Bool
-- getStopWhenReady ho =
-- liftIO . withPtr ho $ \hoPtr ->
-- toBool <$> [CU.exp| bool { $(torrent_status * hoPtr)->stop_when_ready } |]
getTorrentStatusInfoHash :: MonadIO m => TorrentStatus -> m Sha1Hash
getTorrentStatusInfoHash ho =
liftIO . withPtr ho $ \hoPtr ->
fromPtr [CU.exp| sha1_hash * { new sha1_hash($(torrent_status * hoPtr)->info_hash) } |]
| eryx67/haskell-libtorrent | src/Network/Libtorrent/TorrentHandle/TorrentStatus.hs | bsd-3-clause | 20,908 | 0 | 11 | 6,558 | 4,235 | 2,293 | 1,942 | 404 | 1 |
{-# LANGUAGE RecursiveDo, BangPatterns #-}
module Main where
import Control.StartStop.Gloss
import Control.StartStop.Run (runACoreBehavior)
import Control.StartStop.Class
import Control.Monad
import Graphics.Gloss
import Graphics.Gloss.Data.Extent
import Graphics.Gloss.Interface.IO.Game as Gloss
import Data.Foldable hiding(toList)
import Data.Monoid hiding (Sum(..), Product(..))
import Buttons
reallySeqList :: [a] -> b -> b
reallySeqList [] = seq []
reallySeqList (x:xs) = reallySeqList xs
rseq :: [a] -> [a]
rseq xs = reallySeqList xs xs
holdLastNSecs :: (StartStop t) => Float -> EvStream t Float -> Reactive t a -> Behavior t (Reactive t [(Float, a)])
holdLastNSecs holdTime clock b = foldEs (\vs (t, v) -> rseq $ (t, v) : filter ((> t - holdTime) . fst) vs) [] (flip (,) <$> sampleR b <@> clock)
decayColorLine :: [(Float, (Float, Float))] -> Picture
decayColorLine vs = foldl' (flip (<>)) mempty $ fmap (\(t, (x, y)) -> color (timeColor t) $ translate x y $ circleSolid 10) $ vs
where
minTime = minimum $ fmap fst vs
maxTime = maximum $ fmap fst vs
timeDif = maxTime - minTime
timeRed t = (t - minTime - 0.1) / (timeDif + 0.1)
timeBlue t = (maxTime - t) / (timeDif + 0.05)
timeColor t = makeColor (timeRed t) (timeBlue t) 0 1
pair = zipWith (\(t, pos1) (_, pos2) -> (t, [pos1, pos2])) vs (drop 1 vs)
data Screen t = Screen { bPic :: Reactive t Picture, bChange :: EvStream t (Screen t) }
main :: IO ()
main = runGlossHoldIO (InWindow "Examples" (500, 500) (10, 10)) white 60 $ \tick ev -> sampleB $ do
bTime <- foldEs (+) 0 tick
let clock = changes bTime
(Screen bm buttonPress) <- mainMenu clock ev
rec
let stream = switch $ sampleR active
active <- holdEs buttonPress (fmap bChange stream)
switcher bm $ fmap bPic stream
extentClick :: Extent
extentClick = makeExtent 35 5 (-60) (-200)
extentMouseTracker :: Extent
extentMouseTracker = makeExtent 35 5 (200-60) (200-200)
extentMouseTrail :: Extent
extentMouseTrail = makeExtent (negate 10) (negate 40) (negate 60) (negate 200)
isMouseClickEvent :: Event -> Maybe (Float, Float)
isMouseClickEvent (EventKey (MouseButton LeftButton) Down _ pos) = Just pos
isMouseClickEvent _ = Nothing
isMouseChange :: Event -> Maybe (Float, Float)
isMouseChange (EventMotion (dx, dy)) = Just (dx, dy)
isMouseChange _ = Nothing
mainMenu :: (StartStop t) => EvStream t Float -> EvStream t [Event] -> Behavior t (Screen t)
mainMenu clock ev = do
let clickButton = renderButton extentClick "Click Example"
clickButtonEvent = void $ ffilter (any (isClickedBy extentClick)) ev
enterClick = samples ((exampleToScreen clock ev =<< (clickExample ev)) <$ clickButtonEvent)
mouseTrackButton = renderButton extentMouseTracker "Mouse Tracker"
mouseButtonEvent = void $ ffilter (any (isClickedBy extentMouseTracker)) ev
enterMouse = samples ((exampleToScreen clock ev =<< (mouseTrackerExample clock ev)) <$ mouseButtonEvent)
mouseTrailButton = renderButton extentMouseTrail "Mouse Trail"
mouseTrailEvent = void $ ffilter (any (isClickedBy extentMouseTrail)) ev
enterTrail = samples ((exampleToScreen clock ev =<< (mouseTrailExample clock ev)) <$ mouseTrailEvent)
return $ Screen (return $ clickButton <> mouseTrackButton <> mouseTrailButton) (leftmost [enterClick, enterMouse, enterTrail])
clickExample :: (StartStop t) => EvStream t [Event] -> Behavior t (Reactive t Picture)
clickExample ev = do
-- filter ev down to only the first mouse click event.
let mouseClickEvs = filterMap (\xs -> case filterMap isMouseClickEvent xs of
[] -> Nothing
(x:_) -> Just x) ev
-- creates a behavior with a value of the last clicks position
bLastMouseClick <- holdEs (0,0) mouseClickEvs
-- Takes a position and makes a Picture of text with the value of the position
let positionToText = translate (negate 240) (negate 240) . scale 0.4 0.4 . text . show
-- return a behavior whos current value is the current screen to draw.
return $ fmap positionToText bLastMouseClick
mouseTrackerExample :: (StartStop t) => EvStream t Float -> EvStream t [Event] -> Behavior t (Reactive t Picture)
mouseTrackerExample clock ev = do
bMousePos <- holdEs (0, 0) (filterMap (\xs -> case filterMap isMouseChange xs of
[] -> Nothing
(x:_) -> Just x) ev)
bMousePosData <- holdLastNSecs 5 clock (fmap snd bMousePos)
return $ fmap (translate 0 0 . scale 50 1 . drawPlot) bMousePosData
mouseTrailExample :: (StartStop t) => EvStream t Float -> EvStream t [Event] -> Behavior t (Reactive t Picture)
mouseTrailExample clock ev = do
bMousePos <- holdEs (0,0) (filterMap (\xs -> case filterMap isMouseChange xs of
[] -> Nothing
(x:_) -> Just x) ev)
bTrail <- holdLastNSecs 1.2 clock bMousePos
return $ fmap decayColorLine bTrail
exampleToScreen :: (StartStop t) => EvStream t Float -> EvStream t [Event] -> Reactive t Picture -> Behavior t (Screen t)
exampleToScreen clock ev bPic = do
let extentBack = makeExtent (negate 250 + 35) (negate 250 + 5) (250 - 10) (250 - 90)
backButton = renderButton extentBack "Back"
backEvent = samples (mainMenu clock ev <$ ffilter (any (isClickedBy extentBack)) ev)
return $ Screen (fmap (<> backButton) bPic) backEvent
drawPlot :: [(Float, Float)] -> Picture
drawPlot points = color (Gloss.black) . (Gloss.line) $ shiftedPoints
where
max_x = maximum $ fmap fst points
min_x = minimum $ fmap fst points
shiftedPoints = fmap (\(x,y) -> (x - max_x, y)) points
constant :: (StartStop t) => a -> Reactive t a
constant = return
main2 = do
action <- runACoreBehavior $ \tick -> do
rTime <- foldEs (\(!a) (!b) -> a + b) 0 tick
return rTime
mapM_ (\_ -> action) [0..1000000]
| tylerwx51/StartStopFRP | main.hs | bsd-3-clause | 5,986 | 0 | 17 | 1,367 | 2,246 | 1,165 | 1,081 | 102 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
#endif
module Text.RE.TDFA.Sequence
(
-- * Tutorial
-- $tutorial
-- * The Match Operators
(*=~)
, (?=~)
, (=~)
, (=~~)
-- * The Toolkit
-- $toolkit
, module Text.RE
-- * The 'RE' Type
-- $re
, module Text.RE.TDFA.RE
) where
import Prelude.Compat
import qualified Data.Sequence as S
import Data.Typeable
import Text.Regex.Base
import Text.RE
import Text.RE.Internal.AddCaptureNames
import Text.RE.TDFA.RE
import qualified Text.Regex.TDFA as TDFA
-- | find all matches in text
(*=~) :: (S.Seq Char)
-> RE
-> Matches (S.Seq Char)
(*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs
-- | find first match in text
(?=~) :: (S.Seq Char)
-> RE
-> Match (S.Seq Char)
(?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base polymorphic match operator
(=~) :: ( Typeable a
, RegexContext TDFA.Regex (S.Seq Char) a
, RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String
)
=> (S.Seq Char)
-> RE
-> a
(=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base monadic, polymorphic match operator
(=~~) :: ( Monad m
, Functor m
, Typeable a
, RegexContext TDFA.Regex (S.Seq Char) a
, RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String
)
=> (S.Seq Char)
-> RE
-> m a
(=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs
instance IsRegex RE (S.Seq Char) where
matchOnce = flip (?=~)
matchMany = flip (*=~)
regexSource = reSource
-- $tutorial
-- We have a regex tutorial at <http://tutorial.regex.uk>. These API
-- docs are mainly for reference.
-- $toolkit
--
-- Beyond the above match operators and the regular expression type
-- below, "Text.RE" contains the toolkit for replacing captures,
-- specifying options, etc.
-- $re
--
-- "Text.RE.TDFA.RE" contains the toolkit specific to the 'RE' type,
-- the type generated by the gegex compiler.
| cdornan/idiot | Text/RE/TDFA/Sequence.hs | bsd-3-clause | 2,514 | 0 | 10 | 669 | 538 | 314 | 224 | 50 | 1 |
module Text.Authoring (
module Text.Authoring.Class,
module Text.Authoring.Combinator,
module Text.Authoring.Bibliography,
module Text.Authoring.Label,
)
where
import Text.Authoring.Bibliography
import Text.Authoring.Class
import Text.Authoring.Combinator
import Text.Authoring.Label | nushio3/authoring | src/Text/Authoring.hs | bsd-3-clause | 310 | 0 | 5 | 47 | 61 | 42 | 19 | 9 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.