code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
----------------------------------------------------------------------------- -- | -- Module : ForSyDe.Atom.Skel.Vector.Matrix -- Copyright : (c) George Ungureanu, KTH/EECS/ESY 2019-2020 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ugeorge@kth.se -- Stability : experimental -- Portability : portable -- -- This module exports an alias 'Matrix' and a couple of patterns and utilities to -- work with matrices constructed as 2D vectors. Since names might overlap, this -- library is recommended to be imported qualified. ----------------------------------------------------------------------------- module ForSyDe.Atom.Skel.Vector.Matrix where import Prelude hiding (take, drop) import qualified Data.List as L import ForSyDe.Atom.Skel.Vector (Vector(..), vector, fromVector, (<++>)) import qualified ForSyDe.Atom.Skel.Vector as V -- | 'Matrix' is a type synonym for vector of vectors. This means that /any/ function -- on 'Vector' works also on 'Matrix'. type Matrix a = Vector (Vector a) -- | Prints out to the terminal a matrix in a readable format, where -- all elements are right-aligned and separated by a custom separator. -- -- >>> let m = matrix 3 3 [1,2,3,3,100,4,12,32,67] -- >>> pretty "|" m -- 1| 2| 3 -- 3|100| 4 -- 12| 32|67 pretty :: Show a => String -- ^ separator string -> Matrix a -- ^ input matrix -> IO () pretty sep mat = mapM_ putStrLn $ fromVector $ printMat maxWdt strMat where maxWdt = V.reduce (V.farm21 max) $ farm11 length strMat strMat = farm11 show mat printMat w = V.farm11 (printRow w) printRow w = L.intercalate sep . fromVector . V.farm21 align w align n str = replicate (n - length str) ' ' ++ str -- | Checks if a matrix is null. @<>@ and @<<>>@ are both null matrices. isNull :: Matrix a -> Bool isNull Null = True isNull (Null:>Null) = True isNull _ = False -- | Returns the X and Y dimensions of matrix and checks if it is well formed. size :: Matrix a -> (Int,Int) size m = (x,y) where y = V.length m x = (V.length . V.first) (m) -- | Checks if a matrix is well-formed, meaning that all its rows are of equal -- length. Returns the same matrix in case it is well-formed or throws an exception if -- it is ill-formed. wellFormed :: Matrix a -> Matrix a wellFormed Null = Null wellFormed m@(_:>Null) = m wellFormed m@(x:>xs) | V.reduce (&&) (V.farm11 (\r -> V.length r == V.length x) xs) = m | otherwise = error "matrix ill-formed: rows are of unequal lengths" -- | Converts a list into a 'Matrix'. See example from 'pretty'. matrix :: Int -- ^ number of columns (X dimension) @= x@ -> Int -- ^ number of rows (Y dimension) @= y@ -> [a] -- ^ list of values; /length/ = @x * y@ -> Matrix a -- ^ 'Matrix' of values; /size/ = @(x,y)@ matrix x y = vector . map vector . groupEvery x . check where check l | length l == x * y = l | otherwise = error $ "matrix: cannot form matrix (" ++ show x ++ "," ++ show y ++ ") from a list with " ++ show (length l) ++ " elements" groupEvery :: Int -> [a] -> [[a]] groupEvery _ [] = [] groupEvery n l | n < 0 = error $ "matrix: cannot group list by negative n: " ++ show n | length l < n = error "matrix: input list cannot be split into all-equal parts" | otherwise = L.take n l : groupEvery n (L.drop n l) -- | Converts a matrix back to a list. fromMatrix :: Matrix a -- ^ /size/ = @(x,y)@ -> [a] -- ^ /length/ = @x * y@ fromMatrix = concatMap fromVector . fromVector -- | Creates a unit (i.e. singleton) matrix, which is a matrix with only one element. unit :: a -> Matrix a -- ^ /size/ = @(1,1)@ unit a = (a:>Null):>Null -- | Creates an /infinite matrix/ which repeats one element fanout :: a -> Matrix a fanout n = V.fanout $ V.fanout n -- | Returns an /infinite matrix/ with (X,Y) index pairs. You need to zip it against -- another (finite) matrix or to extract a finite subset in order to be useful (see -- example below). -- -- >>> pretty " " $ take 3 4 indexes -- (0,0) (1,0) (2,0) -- (0,1) (1,1) (2,1) -- (0,2) (1,2) (2,2) -- (0,3) (1,3) (2,3) indexes :: Matrix (Int, Int) indexes = farm21 (,) colix rowix where colix = vector $ repeat $ vector [0..] rowix = transpose colix -- | Maps a function on every value of a matrix. -- -- __OBS:__ this function does not check if the output matrix is well-formed. farm11 :: (a -> b) -> Matrix a -- ^ /size/ = @(xa,ya)@ -> Matrix b -- ^ /size/ = @(xa,ya)@ farm11 = V.farm11 . V.farm11 -- | Applies a binary function pair-wise on each element in two matrices. -- -- __OBS:__ this function does not check if the output matrix is well-formed. farm21 :: (a -> b -> c) -> Matrix a -- ^ /size/ = @(xa,ya)@ -> Matrix b -- ^ /size/ = @(xb,yb)@ -> Matrix c -- ^ /size/ = @(minimum [xa,xb], minimum [ya,yb])@ farm21 f = V.farm21 (V.farm21 f) -- | Applies a function 3-tuple-wise on each element in three matrices. -- -- __OBS:__ this function does not check if the output matrix is well-formed. farm31 :: (a -> b -> c -> d) -> Matrix a -- ^ /size/ = @(xa,ya)@ -> Matrix b -- ^ /size/ = @(xb,yb)@ -> Matrix c -- ^ /size/ = @(xc,yc)@ -> Matrix d -- ^ /size/ = @(minimum [xa,xb,xc], minimum [ya,yb,yc])@ farm31 f = V.farm31 (V.farm31 f) -- | Reduces all the elements of a matrix to one element based on a -- binary function. -- -- >>> let m = matrix 3 3 [1,2,3,11,12,13,21,22,23] -- >>> reduce (+) m -- 108 reduce :: (a -> a -> a) -> Matrix a -> a reduce f = V.reduce f . V.farm11 (V.reduce f) -- | Pattern implementing the template for a dot operation between a -- vector and a matrix. -- -- >>> let mA = matrix 4 4 [1,-1,1,1, 1,-1,-1,-1, 1,1,-1,1, 1,1,1,-1] -- >>> let y = vector[1,0,0,0] -- >>> dotV (+) (*) mA y -- <1,1,1,1> dotV :: (a -> a -> a) -- ^ kernel function for a row/column reduction, e.g. @(+)@ for dot product -> (b -> a -> a) -- ^ binary operation for pair-wise elements, e.g. @(*)@ for dot product -> Matrix b -- ^ /size/ = @(xa,ya)@ -> Vector a -- ^ /length/ = @xa@ -> Vector a -- ^ /length/ = @xa@ dotV f g mA y = V.farm11 (\x -> V.reduce f $ V.farm21 g x y) mA -- | Pattern implementing the template for a dot operation between two -- matrices. -- -- >>> let mA = matrix 4 4 [1,-1,1,1, 1,-1,-1,-1, 1,1,-1,1, 1,1,1,-1] -- >>> pretty " " $ dot (+) (*) mA mA -- 2 -2 2 2 -- 2 -2 -2 -2 -- 2 2 2 -2 -- 2 2 -2 2 dot :: (a -> a -> a) -- ^ kernel function for a row/column reduction, e.g. @(+)@ for dot product -> (b -> a -> a) -- ^ binary operation for pair-wise elements, e.g. @(*)@ for dot product -> Matrix b -- ^ /size/ = @(xa,ya)@ -> Matrix a -- ^ /size/ = @(ya,xa)@ -> Matrix a -- ^ /size/ = @(xa,xa)@ dot f g m = V.farm11 (dotV f g m) . transpose -- | Returns the element of a matrix at a certain position. -- -- >>> let m = matrix 3 3 [1,2,3,11,12,13,21,22,23] -- >>> at 2 1 m -- 13 get :: Int -- ^ X index starting from zero -> Int -- ^ Y index starting from zero -> Matrix a -> Maybe a get x y mat = getMaybe (V.get y mat) where getMaybe Nothing = Nothing getMaybe (Just a) = V.get x a -- | Returns the upper-left part of a matrix until a specific -- position. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ take 2 2 m -- 1 2 -- 11 12 take :: Int -- ^ X index starting from zero -> Int -- ^ Y index starting from zero -> Matrix a -> Matrix a take x y = V.farm11 (V.take x) . V.take y -- | Returns the upper-left part of a matrix until a specific -- position. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ drop 2 2 m -- 23 24 -- 33 34 drop :: Int -- ^ X index starting from zero -> Int -- ^ Y index starting from zero -> Matrix a -> Matrix a drop x y = V.farm11 (V.drop x) . V.drop y -- | Crops a section of a matrix. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " m -- 1 2 3 4 -- 11 12 13 14 -- 21 22 23 24 -- 31 32 33 34 -- >>> pretty " " $ cropMat 2 3 1 1 m -- 12 13 -- 22 23 -- 32 33 crop :: Int -- ^ crop width = @w@ -> Int -- ^ crop height = @h@ -> Int -- ^ X start position = @x0@ -> Int -- ^ Y start position = @y0@ -> Matrix a -- ^ /size/ = @(xa,ya)@ -> Matrix a -- ^ /size/ = @(minimum [w,xa-x0], minimum [h,xa-x0])@ crop w h pX pY = take w h . drop pX pY -- cropMat w h pX pY = V.farm11 (crop w pX) . crop h pY -- where crop size pos = V.drop pos . V.take (pos + size) -- | Groups a matrix into smaller equallly-shaped matrices. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ group 2 2 m -- <<1,2>,<11,12>> <<3,4>,<13,14>> -- <<21,22>,<31,32>> <<23,24>,<33,34>> group :: Int -- ^ width of groups = @w@ -> Int -- ^ height of groups = @h@ -> Matrix a -- ^ /size/ = @(xa,ya)@ -> Matrix (Matrix a) -- ^ /size/ = @(xa `div` w,ya `div` h)@ group w h = V.farm11 transpose . V.group h . V.farm11 (V.group w) -- | Returns a stencil of neighboring elements for each possible -- element in a vector. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ stencil 2 2 m -- <<1,2>,<11,12>> <<2,3>,<12,13>> <<3,4>,<13,14>> -- <<11,12>,<21,22>> <<12,13>,<22,23>> <<13,14>,<23,24>> -- <<21,22>,<31,32>> <<22,23>,<32,33>> <<23,24>,<33,34>> stencil :: Int -> Int -> Matrix a -> Matrix (Matrix a) stencil r c = arrange . groupCols . groupRows where groupRows = V.farm11 (V.take r) . dropFromEnd r . V.tails groupCols = farm11 (V.farm11 (V.take c) . dropFromEnd c . V.tails) arrange = V.farm11 transpose dropFromEnd n v = V.take (V.length v - n) v -- | Reverses the order of elements in a matrix -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ reverse m -- 34 33 32 31 -- 24 23 22 21 -- 14 13 12 11 -- 4 3 2 1 reverse :: Matrix a -> Matrix a reverse = V.reverse . V.farm11 V.reverse -- | Pattern which "rotates" a matrix. The rotation is controled with -- the /x/ and /y/ index arguments as following: -- -- * @(> 0)@ : rotates the matrix right/down with the corresponding -- number of positions. -- -- * @(= 0)@ : does not modify the position for that axis. -- -- * @(< 0)@ : rotates the matrix left/up with the corresponding -- number of positions. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ rotate (-1) 1 m -- 32 33 34 31 -- 2 3 4 1 -- 12 13 14 11 -- 22 23 24 21 rotate :: Int -- ^ index on X axis -> Int -- ^ index on Y axis -> Matrix a -> Matrix a rotate x y = V.rotate y . V.farm11 (V.rotate x) -- | Transposes a matrix -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> pretty " " $ transpose m -- 1 11 21 31 -- 2 12 22 32 -- 3 13 23 33 -- 4 14 24 34 transpose :: Matrix a -- ^ @X:Y@ orientation -> Matrix a -- ^ @Y:X@ orientation transpose Null = Null transpose (Null:>xss) = transpose xss transpose rows = (V.farm11 V.first rows) :> transpose (V.farm11 V.tail rows) -- transpose = V.reduce (V.farm21 (<++>)) . farm11 V.unit -- stack overflow! -- | Replaces a part of matrix with another (smaller) part, starting -- from an arbitrary position. -- -- >>> let m = matrix 4 4 [1,2,3,4,11,12,13,14,21,22,23,24,31,32,33,34] -- >>> let m1 = matrix 2 2 [101,202,303,404] -- >>> pretty " " $ replace 1 1 m1 m -- 1 2 3 4 -- 11 101 202 14 -- 21 303 404 24 -- 31 32 33 34 replace :: Int -> Int -> Matrix a -> Matrix a -> Matrix a replace x y mask = replace y h (V.farm21 (\m o -> replace x w (const m) o) mask) where (w,h) = size mask replace start size replaceF vec = let begin = V.take start vec middle = replaceF $ V.drop start $ V.take (start + size) vec end = V.drop (start + size) vec in begin <++> middle <++> end
forsyde/forsyde-atom
src/ForSyDe/Atom/Skel/Vector/Matrix.hs
bsd-3-clause
12,222
0
15
3,073
2,327
1,263
1,064
141
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RecordWildCards #-} import Data.String (fromString) import System.Environment (getArgs) import System.IO (withFile,IOMode(ReadMode,WriteMode)) import System.Posix.Signals (installHandler,sigINT,sigTERM,Handler(Catch)) import qualified Network.Wai.Handler.Warp as Warp import qualified Network.Wai as Wai import qualified Network.Wai.Application.Static as Static import Data.FileEmbed (embedDir) import WaiAppStatic.Types (toPieces) import Network.Wai.Handler.WebSockets (websocketsOr) import qualified Network.HTTP.Types as H import qualified Network.Wai.Parse as Parse import qualified Network.WebSockets as WS import Control.Concurrent (ThreadId,forkIO,threadDelay) import Data.Typeable (Typeable) import Control.Exception (Exception,catch,throwIO,throwTo,finally) import Control.Monad (forever,void) import qualified Data.ByteString.Char8 as BS -- use for input import qualified Data.ByteString.Lazy.Char8 as LBS -- use for output import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import qualified Data.Map as Map import Data.Maybe (fromJust) import Network.HTTP.Types.URI (parseSimpleQuery) import Data.Aeson.Types (ToJSON,toJSON,object,(.=)) import qualified Data.Aeson as AE import Control.Applicative ((<$>),(<*>)) import qualified Control.Concurrent.STM as STM import Control.Concurrent.Async(race) import qualified System.Random as R import Server import qualified Bingo as B --import JSON main :: IO () main = do host:port:_ <- getArgs server <- newServer -- host:port:backupPath:_ <- getArgs -- server <- restoreServer backupPath -- threadBackup <- forkIO $ backupServer server backupPath -- fork backup thread Warp.runSettings ( Warp.setHost (fromString host) $ Warp.setPort (read port) $ -- Warp.setInstallShutdownHandler (installShutdownHandler threadBackup) $ Warp.defaultSettings ) $ websocketsOr WS.defaultConnectionOptions (websocketApp server) (plainOldHttpApp server) -- [TODO] change to UserInterrupt {-- data StopException = StopException deriving (Show,Typeable) instance Exception StopException installShutdownHandler :: ThreadId -> IO () -> IO () installShutdownHandler threadBackup close = do void $ installHandler sigINT (Catch shutdown) Nothing void $ installHandler sigTERM (Catch shutdown) Nothing where shutdown = do -- [TODO] last backup before shutdown close throwTo threadBackup StopException restoreServer :: String -> IO Server restoreServer path = do putStrLn "restore: " json <- withFile path ReadMode BS.hGetContents case AE.decodeStrict json of Nothing -> newServer Just jo -> STM.atomically $ serverFromJO jo backupServer :: Server -> String -> IO () backupServer server path = -- [TODO] mask exception loop `catch` onException where loop = do putStrLn "backup: " jo <- serverToJO server withFile path WriteMode ( \h -> LBS.hPutStrLn h $ AE.encode jo ) threadDelay $ 30 * 1000 * 1000 loop onException :: StopException -> IO () onException e = return () --} data BingoException = BingoException Error deriving (Show,Typeable) instance Exception BingoException throwErrorIO :: Error -> IO a throwErrorIO error = throwIO $ BingoException error throwErrorSTM :: Error -> STM.STM a throwErrorSTM error = STM.throwSTM $ BingoException error contentTypeJsonHeader :: H.Header contentTypeJsonHeader = ("Content-Type","application/json") plainOldHttpApp :: Server -> Wai.Application plainOldHttpApp server req respond | (["draw_game"] == path) = (drawGameProc server req respond) `catch` onError | (["reset_game"] == path) = (resetGameProc server req respond) `catch` onError | (["add_game"] == path) = (addGameProc server req respond) `catch` onError | (["get_game"] == path) = (getGameProc server req respond) `catch` onError | otherwise = staticHttpApp req respond -- static html/js/css files where path = Wai.pathInfo req onError :: BingoException -> IO Wai.ResponseReceived onError (BingoException error) = -- [TODO] log respond $ Wai.responseLBS H.status200 [contentTypeJsonHeader] (AE.encode error) staticHttpApp :: Wai.Application staticHttpApp = Static.staticApp $ settings { Static.ssIndices = indices } where settings = Static.embeddedSettings $(embedDir "static") -- embed contents as ByteString indices = fromJust $ toPieces ["admin.html"] -- default content lookupParams :: BS.ByteString -> [(BS.ByteString,BS.ByteString)] -> Maybe String lookupParams key params = do b <- Map.lookup key $ Map.fromList params return $ T.unpack $ decodeUtf8 b data Response = ResponseGame GameSecretKey GamePublicKey GameCaption | ResponseDraw | ResponseReset deriving (Show) instance ToJSON Response where toJSON (ResponseGame sk pk ca) = object ["success" .= True ,"type" .= ("game" :: String) ,"content" .= object ["secret_key" .= sk ,"public_key" .= pk ,"caption" .= ca ] ] toJSON (ResponseDraw) = object ["success" .= True ,"type" .= ("draw" :: String) ,"content" .= ("ok" :: String) ] toJSON (ResponseReset) = object ["success" .= True ,"type" .= ("reset" :: String) ,"content" .= ("ok" :: String) ] drawGameProc :: Server -> Wai.Application drawGameProc server req respond = do (params, _) <- Parse.parseRequestBody Parse.lbsBackEnd req -- parse post parameters secretKey <- case lookupParams "secret_key" params of Nothing -> throwErrorIO GameSecretKeyNotSpecified Just sk -> return sk g <- R.newStdGen STM.atomically $ do mgame <- getGameFromSecretKey server secretKey case mgame of Nothing -> throwErrorSTM GameFromSecretKeyNotFound Just game -> draw g game respond $ Wai.responseLBS H.status200 [contentTypeJsonHeader] ( AE.encode $ ResponseDraw ) resetGameProc :: Server -> Wai.Application resetGameProc server req respond = do (params, _) <- Parse.parseRequestBody Parse.lbsBackEnd req -- parse post parameters secretKey <- case lookupParams "secret_key" params of Nothing -> throwErrorIO GameSecretKeyNotSpecified Just sk -> return sk g <- R.newStdGen STM.atomically $ do mgame <- getGameFromSecretKey server secretKey case mgame of Nothing -> throwErrorSTM GameFromSecretKeyNotFound Just game -> reset g game respond $ Wai.responseLBS H.status200 [contentTypeJsonHeader] ( AE.encode $ ResponseReset ) addGameProc :: Server -> Wai.Application addGameProc server req respond = do (params, _) <- Parse.parseRequestBody Parse.lbsBackEnd req -- parse post parameters publicKey <- case lookupParams "public_key" params of Nothing -> throwErrorIO GamePublicKeyNotSpecified Just pk -> return pk caption <- case lookupParams "caption" params of Nothing -> throwErrorIO GameCaptionNotSpecified Just ca -> return ca egame <- addGameIO server publicKey caption game <- case egame of Left error -> throwErrorIO error Right game -> return game putStrLn $ "Server.addGameIO: secretKey: " ++ (gameSecretKey game) ++ " publicKey: " ++ publicKey ++ " caption: " ++ caption respond $ Wai.responseLBS H.status200 [contentTypeJsonHeader] (AE.encode $ ResponseGame (gameSecretKey game) publicKey caption) getGameProc :: Server -> Wai.Application getGameProc server req respond = do (params, _) <- Parse.parseRequestBody Parse.lbsBackEnd req -- parse post parameters secretKey <- case lookupParams "secret_key" params of Nothing -> throwErrorIO GameSecretKeyNotSpecified Just sk -> return sk mgame <- STM.atomically $ getGameFromSecretKey server secretKey game <- case mgame of Nothing -> throwErrorIO GameFromSecretKeyNotFound Just game -> return game respond $ Wai.responseLBS H.status200 [contentTypeJsonHeader] ( AE.encode $ ResponseGame secretKey (gamePublicKey game) (gameCaption game)) websocketApp :: Server -> WS.ServerApp websocketApp server pconn | ("/viewer" == path) = (viewerServer server pconn) `catch` onError | ("/participant" == path) = (participantServer server pconn) `catch` onError | otherwise = WS.rejectRequest pconn "endpoint not found" where requestPath = WS.requestPath $ WS.pendingRequest pconn path = BS.takeWhile (/='?') requestPath onError :: BingoException -> IO() onError (BingoException error) = do -- [TODO] log WS.rejectRequest pconn (BS.pack $ show error) onCloseError :: WS.Connection -> BingoException -> IO() onCloseError conn (BingoException error) = do -- [TODO] log WS.sendClose conn (BS.pack $ show error) data WSMessage = WSMessageGame GamePublicKey GameCaption [Int] | WSMessageParticipant ParticipantKey GamePublicKey GameCaption [Int] B.Card [Bool] B.CardStatus deriving (Show) instance ToJSON WSMessage where toJSON (WSMessageGame pk ca sd) = object ["type" .= ("game" :: String) ,"content" .= object ["public_key" .= pk ,"caption" .= ca ,"selected" .= sd ] ] toJSON (WSMessageParticipant pk gpk ca sd cd ev st) = object ["type" .= ("participant" :: String) ,"content" .= object ["participant_key" .= pk ,"game_public_key" .= gpk ,"game_caption" .= ca ,"game_selected" .= sd ,"card" .= cd ,"eval" .= ev ,"state" .= st ] ] viewerServer :: Server -> WS.ServerApp viewerServer server pconn = do putStrLn $ "viewerServer: " ++ BS.unpack(requestPath) -- debug publicKey <- case lookupParams "public_key" query of Nothing -> throwErrorIO GamePublicKeyNotSpecified Just pk -> return pk mgame <- STM.atomically $ getGameFromPublicKey server publicKey game <- case mgame of Nothing -> throwErrorIO GameFromPublicKeyNotFound Just game -> return game conn <- WS.acceptRequest pconn WS.forkPingThread conn 30 st <- STM.atomically $ STM.readTVar (gameState game) let (_,sd) = st WS.sendTextData conn $ AE.encode $ WSMessageGame publicKey (gameCaption game) sd chan <- STM.atomically $ STM.dupTChan $ gameChan game (loop conn chan) `catch` (onCloseError conn) where requestPath = WS.requestPath $ WS.pendingRequest pconn query = parseSimpleQuery $ BS.dropWhile (/='?') requestPath loop :: WS.Connection -> STM.TChan Message -> IO() loop conn chan = do msg <- STM.atomically $ STM.readTChan chan case msg of MessageResetGame -> WS.sendTextData conn $ AE.encode msg MessageDrawGame _ _ -> WS.sendTextData conn $ AE.encode msg otherwise -> return () loop conn chan participantServer :: Server -> WS.ServerApp participantServer server pconn = do putStrLn $ "participantServer: " ++ BS.unpack(requestPath) -- debug publicKey <- case lookupParams "game_public_key" query of Nothing -> throwErrorIO GamePublicKeyNotSpecified Just bpk -> return bpk mgame <- STM.atomically $ getGameFromPublicKey server publicKey game <- case mgame of Nothing -> throwErrorIO GameFromPublicKeyNotFound Just game -> return game participant <- case lookupParams "participant_key" query of Nothing -> addParticipant' game Just (pk) -> do mparticipant <- STM.atomically $ getParticipant game pk case mparticipant of Nothing -> addParticipant' game -- [TODO] must be an error ? Just participant -> return participant conn <- WS.acceptRequest pconn WS.forkPingThread conn 30 (gst,cd) <- STM.atomically $ (,) <$> STM.readTVar (gameState game) <*> STM.readTVar (participantCard participant) let (_,sd) = gst let ev = B.processCard cd sd let st = B.evalCard ev WS.sendTextData conn $ AE.encode $ WSMessageParticipant (participantKey participant) (gamePublicKey game) (gameCaption game) sd cd ev st chan <- STM.atomically $ STM.dupTChan $ participantChan participant (loop conn chan) `catch` (onCloseError conn) where requestPath = WS.requestPath $ WS.pendingRequest pconn query = parseSimpleQuery $ BS.dropWhile (/='?') requestPath addParticipant' game = do mparticipant <- addParticipantIO game case mparticipant of Left error -> throwErrorIO error Right participant -> return participant loop :: WS.Connection -> STM.TChan Message -> IO() loop conn chan = do msg <- STM.atomically $ STM.readTChan chan case msg of MessageResetParticipant _ -> WS.sendTextData conn $ AE.encode msg MessageDrawParticipant _ _ _ _ -> WS.sendTextData conn $ AE.encode msg otherwise -> return () loop conn chan
mitsuji/bingo
app/Main.hs
bsd-3-clause
13,391
0
16
3,168
3,477
1,779
1,698
259
8
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} #ifdef GLADE_DIR #else #define GLADE_DIR "./" #endif {-| Module : Numeric.AERN.IVP.Plot.PicardView Description : UI for controlling and visualising Picard iterations Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable UI for controlling and visualising Picard iterations. NOT COMPLETED, CURRENTLY STALLED -} module Numeric.AERN.IVP.Plot.PicardView ( new ) where import Numeric.AERN.IVP.Plot.PicardView.State import Numeric.AERN.IVP.Plot.PicardView.Layout import qualified Numeric.AERN.RmToRn.Plot.FnView as FV import Numeric.AERN.RmToRn.Plot.Params import Numeric.AERN.RmToRn.Plot.CairoDrawable (CairoDrawableFn(..)) import Numeric.AERN.RmToRn.New import Numeric.AERN.RmToRn.Domain import Numeric.AERN.RmToRn.Evaluation import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut --import Numeric.AERN.RealArithmetic.RefinementOrderRounding.OpsImplicitEffort --import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn import qualified Numeric.AERN.RefinementOrder as RefOrd --import Numeric.AERN.RefinementOrder.OpsImplicitEffort import Graphics.Rendering.Cairo as Cairo import qualified Graphics.UI.Gtk as Gtk import Graphics.UI.Gtk (AttrOp((:=))) import qualified Graphics.UI.Gtk.Gdk.EventM as GdkEv import Control.Concurrent (forkIO) import Control.Concurrent.STM -- as STM import Data.IORef import qualified System.FilePath as FilePath {-| Create a new Picard IVP simulation widget. -} new :: (CairoDrawableFn f, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasEvalOps f (Domain f), HasConstFns f, RefOrd.PartialComparison (Domain f), Show f, Show (Domain f)) => f {-^ sample value -} -> (CairoDrawFnEffortIndicator f) -> ArithInOut.RoundedRealEffortIndicator (Domain f) -> EvalOpsEffortIndicator f (Domain f) -> IVP f -> (Maybe Gtk.Window) {- ^ parent window -} -> IO Gtk.Window new (sampleF :: f) effDraw effReal effEval ivp maybeParentWindow = do -- create initial state objects: (stateTV, fnTV) <- atomically $ do let (fns, state) = initState sampleF effReal ivp stateTV <- newTVar state fnTV <- newTVar fns return (stateTV, fnTV) dynWidgetsRef <- newIORef initPicardViewDynWidgets -- create most widgets: widgets <- loadGlade (FilePath.combine GLADE_DIR "PicardView.glade") -- create a function view: -- TODO -- add dynamic function label widgets: -- updateSegmentInfoWidgets widgets dynWidgetsRef stateTV -- attach handlers to widgets Gtk.onDestroy (window widgets) $ do Gtk.mainQuit -- setHandlers sampleF effDraw effReal effEval widgets dynWidgetsRef stateTV Gtk.widgetShowAll $ window widgets return $ window widgets where initialValues = ivpInitialValues ivp sampleDom = getSampleDomValue sampleF --setHandlers :: -- (CairoDrawableFn f, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- HasEvalOps f (Domain f), -- Show f, Show (Domain f)) -- => -- f {-^ sample value -} -> -- (CairoDrawFnEffortIndicator f) -> -- ArithInOut.RoundedRealEffortIndicator (Domain f) -> -- EvalOpsEffortIndicator f (Domain f) -> -- Widgets -> -- IORef PicardViewDynWidgets -> -- TVar (PicardViewState f) -> -- IO () --setHandlers (sampleF :: f) effDraw effReal effEval widgets dynWidgetsRef fndataTVs@(fndataTV, fnmetaTV) stateTV = -- do -- setHandlerCoordSystem -- setHandlerZoomAndPanEntries -- setHandlerPanByMouse -- setHandlerZoomByMouse -- setHandlerDefaultEvalPointButton -- setHandlerEvalPointEntry -- setHandlerPrintTXTButton -- setHandlerExportPDFButton -- setHandlerExportSVGButton -- setHandlerExportPNGButton -- -- state <- atomically $ readTVar stateTV -- updateZoomWidgets toDbl widgets state ---- putStrLn $ "setHandlers: " ++ (show $ cnvprmCoordSystem $ favstCanvasParams state) -- return () -- where -- toDbl :: (Domain f) -> Double -- toDbl a = d -- where -- (Just d) = ArithUpDn.convertUpEff effToDouble a -- effToDouble = ArithInOut.rrEffortToDouble sampleDom effReal -- effFromDouble = ArithInOut.rrEffortFromDouble sampleDom effReal -- sampleDom = getSampleDomValue sampleF -- -- setHandlerCoordSystem = -- do -- Gtk.on (coorSystemCombo widgets) Gtk.changed resetZoomPanFromCoordSystem -- Gtk.onClicked (defaultZoomPanButton widgets) resetZoomPanFromCoordSystem -- where -- resetZoomPanFromCoordSystem = -- do -- maybeCSysIx <- Gtk.comboBoxGetActive (coorSystemCombo widgets) ---- putStrLn $ "resetZoomPanFromCoordSystem: maybeCSysIx = " ++ show maybeCSysIx -- case maybeCSysIx of -- -1 -> return () -- ix -> -- do -- state <- -- atomically $ -- do -- fnmeta <- readTVar fnmetaTV -- let coordSystem = case ix of -- 0 -> CoordSystemLogSqueeze sampleDom -- 1 -> -- linearCoordsWithZoom effReal defaultZoom (getFnExtents fnmeta) -- state <- modifyTVar stateTV $ -- updatePanCentreCoordSystem (getDefaultCentre effReal fnmeta) coordSystem -- return state -- Gtk.widgetQueueDraw (canvas widgets) -- updateZoomWidgets toDbl widgets state -- -- setHandlerZoomAndPanEntries = -- do -- Gtk.onEntryActivate (zoomEntry widgets) (zoomHandler ()) -- Gtk.onFocusOut (zoomEntry widgets) (\ e -> zoomHandler False) -- Gtk.onEntryActivate (centreXEntry widgets) (zoomHandler ()) -- Gtk.onFocusOut (centreXEntry widgets) (\ e -> zoomHandler False) -- Gtk.onEntryActivate (centreYEntry widgets) (zoomHandler ()) -- Gtk.onFocusOut (centreYEntry widgets) (\ e -> zoomHandler False) -- where -- zoomHandler returnValue = -- do -- zoomS <- Gtk.entryGetText (zoomEntry widgets) -- centreXS <- Gtk.entryGetText (centreXEntry widgets) -- centreYS <- Gtk.entryGetText (centreYEntry widgets) -- case (reads zoomS, reads centreXS, reads centreYS) of -- ([(zoomPercent,"")], [(centreXD,"")], [(centreYD,"")]) -> -- atomically $ -- do -- fnmeta <- readTVar fnmetaTV -- modifyTVar stateTV $ -- updateZoomPanCentreCoordSystem zoomPercent (centreX, centreY) $ -- linearCoordsWithZoomAndCentre effReal zoomPercent (centreX, centreY) $ -- getFnExtents fnmeta -- return () -- where -- centreX = ArithInOut.convertOutEff effFromDouble (centreXD :: Double) -- centreY = ArithInOut.convertOutEff effFromDouble (centreYD :: Double) -- wrongParseResults -> -- do -- putStrLn $ "zoomHandler: parse error: " ++ show wrongParseResults -- return () ---- putStrLn $ "zoomHandler" -- Gtk.widgetQueueDraw (canvas widgets) -- return returnValue -- -- setHandlerPanByMouse = -- do -- -- a variable to keep track of position before each drag movement: -- panOriginTV <- atomically $ newTVar Nothing -- -- setup the canvas to receive various mouse events: -- Gtk.widgetAddEvents (canvas widgets) -- [Gtk.ButtonPressMask, Gtk.ButtonReleaseMask, Gtk.PointerMotionMask] -- -- what to do when the left mouse button is pressed: -- Gtk.on (canvas widgets) Gtk.buttonPressEvent $ -- do -- button <- GdkEv.eventButton -- coords <- GdkEv.eventCoordinates -- case button of -- GdkEv.LeftButton -> -- liftIO $ -- do -- -- remember the position and indicate that dragging is underway: -- atomically $ writeTVar panOriginTV (Just coords) -- return () -- _ -> return () -- return False -- -- what to do when the left mouse button is released: -- Gtk.on (canvas widgets) Gtk.buttonReleaseEvent $ -- do -- button <- GdkEv.eventButton -- case button of -- GdkEv.LeftButton -> -- liftIO $ -- do -- -- indicate no dragging is underway: -- atomically $ writeTVar panOriginTV Nothing -- return () -- _ -> return () -- return False -- -- what to do when mouse moves: -- Gtk.on (canvas widgets) Gtk.motionNotifyEvent $ -- do -- coords@(x,y) <- GdkEv.eventCoordinates -- liftIO $ -- do -- -- update the dragging information variable: -- maybePanOrigin <- atomically $ -- do -- maybePanOrigin <- readTVar panOriginTV -- case maybePanOrigin of -- Nothing -> -- return maybePanOrigin -- Just _ -> -- do -- writeTVar panOriginTV (Just coords) -- return maybePanOrigin -- -- check whether dragging or not: -- case maybePanOrigin of -- Nothing -> return () -- Just panOrigin@(oX,oY) -> -- yes, dragging occurred -- do -- -- find out the size of the canvas: -- (canvasX, canvasY) <- Gtk.widgetGetSize (canvas widgets) -- -- recalculate the centre and coordinate bounds -- -- based on the drag amount relative to the size fo the canvas: -- state <- atomically $ modifyTVar stateTV $ -- updateCentreByRatio -- effReal -- ((x - oX) / (int2dbl canvasX), -- (y - oY) / (int2dbl canvasY)) ---- putStrLn $ "motionNotifyEvent: coords = " ++ show coords ---- ++ "; panOrigin = " ++ show panOrigin ---- ++ "; (canvasX,canvasY) = " ++ show (canvasX,canvasY) -- return () -- -- make sure the text in the zoom and pan entries are updated: -- updateZoomWidgets toDbl widgets state -- -- schedule the canvas for redraw: -- Gtk.widgetQueueDraw (canvas widgets) -- where -- int2dbl :: Int -> Double -- int2dbl = realToFrac -- return False -- return () -- -- setHandlerZoomByMouse = -- do -- IO -- Gtk.widgetAddEvents (canvas widgets) [Gtk.ScrollMask] -- Gtk.on (canvas widgets) Gtk.scrollEvent $ -- do -- ReaderTV -- scrollDirection <- GdkEv.eventScrollDirection -- liftIO $ -- do -- IO -- state <- atomically $ -- do -- STM -- state <- readTVar stateTV -- let zoomPercent = favstZoomPercent state -- let newZoomPercent = case scrollDirection of -- GdkEv.ScrollUp -> 1.25 * zoomPercent -- GdkEv.ScrollDown -> 0.8 * zoomPercent -- _ -> zoomPercent -- fnmeta <- readTVar fnmetaTV -- state <- modifyTVar stateTV $ -- updateZoomPercentAndFnExtents effReal newZoomPercent $ getFnExtents fnmeta -- return state -- updateZoomWidgets toDbl widgets state -- Gtk.widgetQueueDraw (canvas widgets) -- return False -- return () -- TODO -- -- setHandlerDefaultEvalPointButton = -- Gtk.onClicked (defaultEvalPointButton widgets) $ -- do -- (state, fnmeta) <- -- atomically $ -- do -- state <- readTVar stateTV -- fnmeta <- readTVar fnmetaTV -- return (state, fnmeta) -- case favstTrackingDefaultEvalPt state of -- False -> -- do -- Gtk.entrySetText (evalPointEntry widgets) $ -- show $ dataDefaultEvalPoint fnmeta -- atomically $ modifyTVar stateTV $ -- \ st -> st { favstTrackingDefaultEvalPt = True } -- updateValueDisplayTV effFromDouble effEval widgets dynWidgetsRef fndataTVs stateTV -- True -> -- already tracking the default -- return () -- setHandlerEvalPointEntry = -- do -- Gtk.onEntryActivate (evalPointEntry widgets) $ -- do -- updateEvalPointHandler -- Gtk.onFocusOut (evalPointEntry widgets) $ \ _ -> -- do -- updateEvalPointHandler -- return False -- where -- updateEvalPointHandler = -- do -- -- indicate that we no longer wish to track the default point: -- atomically $ modifyTVar stateTV $ -- \ st -> st { favstTrackingDefaultEvalPt = False } -- -- update the values for the new point: -- updateValueDisplayTV effFromDouble effEval widgets dynWidgetsRef fndataTVs stateTV -- -- setHandlerPrintTXTButton = -- Gtk.onClicked (printTXTButton widgets) $ -- do -- (state, FnData fns) <- -- atomically $ -- do -- state <- readTVar stateTV -- fns <- readTVar fndataTV -- return (state, fns) -- putStrLn $ -- unlines $ map show $ fns -- -- setHandlerExportPDFButton = -- Gtk.onClicked (exportPDFButton widgets) $ -- do -- (state, FnData fns, fnmeta) <- -- atomically $ -- do -- state <- readTVar stateTV -- fndata <- readTVar fndataTV -- fnmeta <- readTVar fnmetaTV -- return (state, fndata, fnmeta) -- let fnsActive = concat $ favstActiveFns state -- let canvasParams = favstCanvasParams state -- let fnsStyles = concat $ dataFnStyles fnmeta -- maybeFilepath <- letUserChooseFileToSaveInto "PDF" "pdf" -- case maybeFilepath of -- Just filepath -> -- withPDFSurface filepath w h $ \ surface -> -- renderWith surface $ -- drawFunctions sampleF effDraw effReal canvasParams state w h fnsActive (concat fns) fnsStyles -- _ -> return () -- where -- w = 360 :: Double -- in 1/72 inch TODO: ask user -- h = 360 :: Double -- in 1/72 inch TODO: ask user -- -- setHandlerExportSVGButton = -- Gtk.onClicked (exportSVGButton widgets) $ -- do -- (state, FnData fns, fnmeta) <- -- atomically $ -- do -- state <- readTVar stateTV -- fndata <- readTVar fndataTV -- fnmeta <- readTVar fnmetaTV -- return (state, fndata, fnmeta) -- let fnsActive = concat $ favstActiveFns state -- let canvasParams = favstCanvasParams state -- let fnsStyles = concat $ dataFnStyles fnmeta -- maybeFilepath <- letUserChooseFileToSaveInto "SVG" "svg" -- case maybeFilepath of -- Just filepath -> -- withSVGSurface filepath w h $ \ surface -> -- renderWith surface $ -- drawFunctions sampleF effDraw effReal canvasParams state w h fnsActive (concat fns) fnsStyles -- _ -> return () -- where -- w = 360 :: Double -- in 1/72 inch TODO: ask user -- h = 360 :: Double -- in 1/72 inch TODO: ask user -- -- setHandlerExportPNGButton = -- Gtk.onClicked (exportPNGButton widgets) $ -- do -- (state, FnData fns, fnmeta) <- -- atomically $ -- do -- state <- readTVar stateTV -- fndata <- readTVar fndataTV -- fnmeta <- readTVar fnmetaTV -- return (state, fndata, fnmeta) -- let fnsActive = concat $ favstActiveFns state -- let canvasParams = favstCanvasParams state -- let fnsStyles = concat $ dataFnStyles fnmeta -- maybeFilepath <- letUserChooseFileToSaveInto "PNG" "png" -- case maybeFilepath of -- Just filepath -> -- withImageSurface FormatARGB32 wI hI $ \ surface -> -- do -- renderWith surface $ -- drawFunctions sampleF effDraw effReal canvasParams state wD hD fnsActive (concat fns) fnsStyles -- surfaceWriteToPNG surface filepath -- _ -> return () -- where -- wI = 1024 :: Int -- in pixels TODO: ask user -- hI = 1024 :: Int -- in pixels TODO: ask user -- wD = realToFrac wI -- hD = realToFrac hI -- {- initial plans for the GUI: controller ODE IVP: fields showing and allowing editing of maxDeg and maxSize label showing the list of numbers of picard iterations in each segment plotting the best enclosure for each segment black for previous segments red or green for current segment button to perform another Picard iteration on the current segment indicator whether inclusion within the previous enclosure has been detected if inclusion detected, plot in green, otherwise in red when inclusion is detected, plot also the improvement button to jump to the next segment active only when inclusion within the previous enclosure has been detected undo button controller hybrid/ODE IVP: indicator of the current segment button to perform another Picard iteration on the current segment indicator whether inclusion within the previous enclosure has been detected indicator of the possible sequences of events that have been dealt with indicator of the possible types of the next event (including the type "none") button to jump to the next segment active only when inclusion within the previous enclosure has been detected and all events have been dealt with either explicitly or by recursion button to refocus on a small segment around the first event not active if it is clear that there is no event in this segment button to add another event into the event sequence not active if it is clear that there is no further event in this small segment undo button -}
michalkonecny/aern
aern-ivp/src/Numeric/AERN/IVP/Plot/PicardView.hs
bsd-3-clause
20,283
0
14
7,365
892
660
232
59
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} -- | The Sunroof server module provides infrastructure to use -- Sunroof together with kansas-comet. -- -- It supports setting up a simple server with 'sunroofServer' -- and provides basic functions for serverside communication -- with the connected website ('syncJS', 'asyncJS' and 'rsyncJS'). -- -- This module also provides the abstractions for 'Downlink' -- and 'Uplink'. They represent directed channels for sending data -- from the server to the website and the other way aroun. -- The sent data is queued and operations block properly if there -- is no data available. module Language.Sunroof.Server ( -- * Basic Comet Server syncJS , asyncJS , rsyncJS , SunroofResult(..) , SunroofEngine(..) , jsonToJS , sunroofServer , SunroofServerOptions(..) , SunroofApp , debugSunroofEngine -- * Downlink , Downlink , newDownlink , getDownlink , putDownlink -- * Uplink , Uplink , newUplink , getUplink , putUplink -- * Timing , Timings(..) , newTimings , resetTimings , getTimings ) where import Data.Aeson.Types ( Value(..), Object, Array ) import Data.List ( intercalate ) import Data.Text ( unpack, pack ) import Data.Proxy ( Proxy(..) ) import Data.Default.Class ( Default(..) ) import Data.Semigroup import Data.Time.Clock import Data.Scientific ( toRealFloat ) import qualified Data.Vector as V import qualified Data.HashMap.Strict as M import System.FilePath((</>)) import Control.Concurrent.STM import Network.Wai.Handler.Warp ( Port, setPort ) import Network.Wai.Middleware.Static import qualified Web.Scotty as SC import Web.Scotty.Comet ( send, connect , Document, Options , kCometPlugin ) import qualified Web.Scotty.Comet as KC import Language.Sunroof import Language.Sunroof.JS.Args import Language.Sunroof.JavaScript ( Expr , literal, showExpr , scopeForEffect ) import Language.Sunroof.Classes ( Uniq ) import Language.Sunroof.Compiler ( compileJS ) -- ------------------------------------------------------------- -- Communication and Compilation -- ------------------------------------------------------------- -- | The 'SunroofEngine' provides the verbosity level and -- kansas comet document to the 'SunroofApp'. data SunroofEngine = SunroofEngine { cometDocument :: Document -- ^ The document comet uses to manage the connected website. , uVar :: TVar Uniq -- ^ Unique number supply for our engine , engineVerbose :: Int -- ^ @0@ for none, @1@ for initializations, -- @2@ for commands done and @3@ for a complete log. , compilerOpts :: CompilerOpts -- ^ The options used to setup the compiler. , timings :: Maybe (TVar (Timings NominalDiffTime)) -- ^ Performance timings of the compiler and communication. } -- | Generate one unique integer from the document. docUniq :: SunroofEngine -> IO Int docUniq = docUniqs 1 -- | Generate n unique integers from the document. docUniqs :: Int -> SunroofEngine -> IO Int docUniqs n doc = atomically $ do u <- readTVar (uVar doc) writeTVar (uVar doc) (u + n) return u -- | The number of uniques allocated for the first try of a compilation. compileUniqAlloc :: Uniq compileUniqAlloc = 32 -- | Log the given message on the given level sunroofLog :: SunroofEngine -> Int -> String -> IO () sunroofLog engine level msg = if (engineVerbose engine >= level) then do putStr "Sunroof> " putStrLn msg else return () -- | Log the compilation result and return it compileLog :: SunroofEngine -> String -> IO () compileLog engine src = do sequence_ $ fmap (sunroofLog engine 3) $ [ "Compiled:", src] return () -- | Compile js using unique variables each time. compileRequestJS :: SunroofEngine -> JS t () -> IO String compileRequestJS engine jsm = do -- Allocate a standard amount of uniq for compilation uq <- docUniqs compileUniqAlloc engine -- Compile (stmts, uq') <- compileJS (compilerOpts engine) uq return jsm -- Check if the allocated amount was sufficient let txt = showExpr False $ scopeForEffect stmts if (uq' < uq + compileUniqAlloc) -- It was sufficient we are finished then do compileLog engine txt return txt -- It wasn't sufficient else do -- Allocate all that are needed newUq <- docUniqs (uq' - uq) engine -- Compile again (stmts', _) <- compileJS (compilerOpts engine) newUq return jsm let txt' = showExpr False $ scopeForEffect stmts' compileLog engine txt' return txt' -- | Executes the Javascript in the browser without waiting for a result. asyncJS :: SunroofEngine -> JS t () -> IO () asyncJS engine jsm = do t0 <- getCurrentTime src <- compileRequestJS engine jsm addCompileTime engine t0 t1 <- getCurrentTime send (cometDocument engine) (pack src) -- send it, and forget it addSendTime engine t1 return () -- | Executes the Javascript in the browser and waits for the result value. -- The result value is given the corresponding Haskell type, -- if possible (see 'SunroofResult'). syncJS :: forall a t . (SunroofResult a) => SunroofEngine -> JS t a -> IO (ResultOf a) {- syncJS engine jsm | typesOf (Proxy :: Proxy a) == [Unit] = do _ <- syncJS engine (jsm >> return (0 :: JSNumber)) return $ jsonToValue (Proxy :: Proxy a) Null -} syncJS engine jsm = do up <- newUplink engine t0 <- getCurrentTime src <- compileRequestJS engine $ do v <- jsm up # putUplink v addCompileTime engine t0 t1 <- getCurrentTime send (cometDocument engine) (pack src) addSendTime engine t1 t2 <- getCurrentTime -- There is *no* race condition in here. If no-one is listening, -- then the numbered event gets queued up. r <- getUplink up addWaitTime engine t2 return r -- | Executes the Javascript in the browser and waits for the result. -- The returned value is just a reference to the computed value. -- This allows to precompile values like function in the browser. rsyncJS :: forall a t . (Sunroof a) => SunroofEngine -> JS t a -> IO a rsyncJS engine jsm = do uq <- docUniq engine -- uniq for the value let uq_lab = label ("remote_" <> cast (js uq)) up :: Uplink JSNumber <- newUplink engine t0 <- getCurrentTime src <- compileRequestJS engine $ do v <- jsm -- Store the value inside the window object object "window" # uq_lab := v up # putUplink 0 addCompileTime engine t0 t1 <- getCurrentTime send (cometDocument engine) (pack src) addSendTime engine t1 t2 <- getCurrentTime -- There is *no* race condition in here. If no-one is listening, -- then the numbered event gets queued up. _ <- getUplink up addWaitTime engine t2 return $ object "window" ! uq_lab -- ----------------------------------------------------------------------- -- Default Server Instance -- ----------------------------------------------------------------------- -- | A comet application takes the engine/document we are currently communicating -- with and delivers the IO action to be executed as server application. type SunroofApp = SunroofEngine -> IO () -- | The 'SunroofServerOptions' specify the configuration of the -- sunroof comet server infrastructure. -- -- See 'sunroofServer' and 'SunroofServerOptions' for further information. data SunroofServerOptions = SunroofServerOptions { cometPort :: Port -- ^ The port the server is reachable from. , cometResourceBaseDir :: FilePath -- ^ Will be used as base directory to search for all static files. -- Make this path absolute to run the server from anywhere. , cometIndexFile :: FilePath -- ^ The file to be used as index file (or landing page). -- This path is given relative to the 'cometResourceBaseDir'. , cometPolicy :: Policy -- ^ The default policy is to allow the @css@, @img@ and @js@ -- folders to be used by the server, as well as the noDots policy. -- This policy can be overwritten to allow delivery of other files. , cometOptions :: Options -- ^ Provides the kansas comet options to use. -- Default options are provided with the 'Data.Default.def' instance. , sunroofVerbose :: Int -- ^ @0@ for none, @1@ for initializations, -- @2@ for commands done and @3@ for a complete log. , sunroofCompilerOpts :: CompilerOpts -- ^ The set of options to configure the Sunroof compiler. -- Default options are provided with the 'Data.Default.def' instance. } -- | Sets up a comet server ready to use with sunroof. -- -- @sunroofServer opts app@: -- The @opts@ give various configuration for the comet server. -- See 'SunroofServerOptions' for further information on this. -- The application to run is given by @app@. It takes the current -- engine/document as parameter. The document is needed for calls to 'syncJS', -- 'asyncJS' and 'rsyncJS'. -- -- The server provides the kansas comet Javascript on the path -- @js/kansas-comet.js@. -- -- Since @kansas-comet.js@ is a JQuery plugin you have to also -- load a decent version of @jquery.js@ (or @jquery.min.js@) -- and also @jquery-json.js@. They are available at: -- -- * <http://jquery.com/> -- -- * <https://code.google.com/p/jquery-json/> -- -- For the index file to setup the communication correctly with the comet -- server it has to load the @kansas-comet.js@ after the JQuery code -- inside the @head@ (assuming you placed the JQuery code under @js/@): -- -- > <script type="text/javascript" src="js/jquery.js"></script> -- > <script type="text/javascript" src="js/jquery-json.js"></script> -- > <script type="text/javascript" src="js/kansas-comet.js"></script> -- -- It also has to execute the following Javascript at the end of the -- index file to initialize the communication: -- -- > <script type="text/javascript"> -- > $(document).ready(function() { -- > $.kc.connect("/ajax"); -- > }); -- > </script> -- -- The string @/ajax@ has to be set to whatever the comet prefix -- in the 'Options' provided by the 'SunroofServerOptions' is. -- These snippits will work for the 'def' instance. -- -- Additional debug information can be displayed in the browser when -- adding the following element to the index file: -- -- > <div id="debug-log"></div> -- -- Look into the example folder to see all of this in action. sunroofServer :: SunroofServerOptions -> SunroofApp -> IO () sunroofServer opts cometApp = do let warpSettings = setPort (cometPort opts) (SC.settings def) -- Be quiet scotty! ... and beam me up! let scottyOptions = def { SC.verbose = 0 , SC.settings = warpSettings } kcomet <- kCometPlugin connectApp <- connect (cometOptions opts) $ wrapDocument opts cometApp SC.scottyOpts scottyOptions $ do let rootFile = cometResourceBaseDir opts </> cometIndexFile opts let custom_policy = cometPolicy opts let pol = only [("", rootFile) ,("js/kansas-comet.js", kcomet)] <|> (custom_policy >-> addBase (cometResourceBaseDir opts)) SC.middleware $ staticPolicy pol connectApp -- | Wrap the document into the sunroof engine. wrapDocument :: SunroofServerOptions -> SunroofApp -> (Document -> IO ()) wrapDocument opts cometApp doc = do uqVar <- atomically $ newTVar 0 cometApp $ SunroofEngine { cometDocument = doc , uVar = uqVar , engineVerbose = sunroofVerbose opts , compilerOpts = sunroofCompilerOpts opts , timings = Nothing } -- | Default options to use for the sunroof comet server. -- -- [@cometPort@] Default port is @3000@. -- -- [@cometResourceBaseDir@] Default resource location is @"."@. -- -- [@cometIndexFile@] Default index file is @"index.html"@. -- -- [@cometOptions@] Uses the server path @/ajax@ for the -- comet JSON communication. Sets verbosity to @0@ (quiet). -- -- [@sunroofVerbose@] Is set to @0@ (quiet). -- defaultServerOpts :: SunroofServerOptions defaultServerOpts = SunroofServerOptions { cometPort = 3000 , cometResourceBaseDir = "." , cometIndexFile = "index.html" , cometPolicy = defaultPolicy , cometOptions = def { KC.prefix = "/ajax", KC.verbose = 0 } , sunroofVerbose = 0 , sunroofCompilerOpts = def } defaultPolicy :: Policy defaultPolicy = noDots >-> (hasPrefix "css/" <|> hasPrefix "js/" <|> hasPrefix "img/") -- | The 'defaultServerOpts'. instance Default SunroofServerOptions where def = defaultServerOpts -- ------------------------------------------------------------- -- Downlink API -- ------------------------------------------------------------- -- | 'Downlink's are an abstraction provided for sending -- Javascript data from the server to the website. -- The type parameter describes the elements -- that are transmited through the downlink. data Downlink a = Downlink SunroofEngine (JSChan a) -- | Create a new downlink. newDownlink :: forall a . (SunroofArgument a) => SunroofEngine -> IO (Downlink a) newDownlink eng = do chan <- rsyncJS eng (newChan :: JSA (JSChan a)) return $ Downlink eng chan -- | Send data to the website. putDownlink :: (SunroofArgument a) => Downlink a -> JSA a -> IO () putDownlink (Downlink eng chan) val = asyncJS eng $ do v <- val writeChan v chan -- | Request data in the downlink. This may block until -- data is available. getDownlink :: (SunroofArgument a) => Downlink a -> JSB a getDownlink (Downlink _eng chan) = readChan chan -- ------------------------------------------------------------- -- Uplink API -- ------------------------------------------------------------- -- | 'Uplink's are an abstraction provided for sending -- Javascript data from the website back to the server. -- Only data that can be translated back to a Haskell -- value can be sent back. -- The type parameter describes the elements -- that are transmited through the uplink. data Uplink a = Uplink SunroofEngine Uniq -- | Create a new uplink. newUplink :: SunroofEngine -> IO (Uplink a) newUplink eng = do u <- docUniq eng return $ Uplink eng u -- | Send Javascript data back to the server. putUplink :: (SunroofArgument a) => a -> Uplink a -> JS t () putUplink a (Uplink _ u) = do o :: JSArgs a <- toJSArgs a kc_reply (js u) o -- | Request data in the uplink. This may block until -- data is available. getUplink :: forall a . (SunroofResult a) => Uplink a -> IO (ResultOf a) getUplink (Uplink eng u) = do val <- KC.getReply (cometDocument eng) u -- TODO: make this throw an exception if it goes wrong (I supose error does this already) return $ jsonToValue (Proxy :: Proxy (JSArgs a)) val {- case val of (Array ss) -> return $ jsonToValue' (Proxy :: Proxy a) $ V.toList ss _ -> error $ "getUplink: expecting Array, found " ++ show val -} -- ------------------------------------------------------------- -- Comet Javascript API -- ------------------------------------------------------------- -- | Binding for the Javascript function to send replies to the -- server. kc_reply :: (Sunroof a) => JSNumber -> a -> JS t () kc_reply n a = fun "$.kc.reply" `apply` (n,a) -- ----------------------------------------------------------------------- -- JSON Value to Haskell/Sunroof conversion -- ----------------------------------------------------------------------- -- | Provides correspondant Haskell types for certain Sunroof types. class (SunroofArgument a) => SunroofResult a where -- | The Haskell value type associated with this 'Sunroof' type. type ResultOf a -- | Converts the given JSON value to the corresponding -- Haskell value. A error is thrown if the JSON value can -- not be converted. jsonToValue :: Proxy a -> Value -> ResultOf a jsonToValue' :: Proxy a -> [Value] -> ResultOf a jsonToValue' _ [s] = jsonToValue (Proxy :: Proxy a) s jsonToValue' _ ss = error $ "jsonToValue': JSON value is not a single element array : " ++ show ss -- | @null@ can be translated to @()@. instance SunroofResult () where type ResultOf () = () jsonToValue _ (Null) = () jsonToValue _ v = error $ "jsonToValue: JSON value is not unit: " ++ show v jsonToValue' _ [] = () jsonToValue' _ [Null] = () -- not quite right yet jsonToValue' _ ss = error $ "jsonToValue': JSON value is not a empty array : " ++ show ss -- | 'JSBool' can be translated to 'Bool'. instance SunroofResult JSBool where type ResultOf JSBool = Bool jsonToValue _ (Bool b) = b jsonToValue _ v = error $ "jsonToValue: JSON value is not a boolean: " ++ show v -- | 'JSNumber' can be translated to 'Double'. instance SunroofResult JSNumber where type ResultOf JSNumber = Double jsonToValue _ (Number scientific) = toRealFloat scientific jsonToValue _ v = error $ "jsonToValue: JSON value is not a number: " ++ show v -- | 'JSString' can be translated to 'String'. instance SunroofResult JSString where type ResultOf JSString = String jsonToValue _ (String s) = unpack s jsonToValue _ v = error $ "jsonToValue: JSON value is not a string: " ++ show v -- | 'JSArray' can be translated to a list of the 'ResultOf' the values. instance forall a . (Sunroof a, SunroofResult a) => SunroofResult (JSArray a) where type ResultOf (JSArray a) = [ResultOf a] jsonToValue _ (Array ss) = map (jsonToValue (Proxy :: Proxy a)) $ V.toList ss jsonToValue _ v = error $ "jsonToValue: JSON value is not an array : " ++ show v -- ResultOf a ~ ResultOf (JSArgs a)) instance forall a . SunroofResult a => SunroofResult (JSArgs a) where type ResultOf (JSArgs a) = ResultOf a jsonToValue _ (Array ss) = jsonToValue' (Proxy :: Proxy a) $ V.toList ss jsonToValue _ v = error $ "jsonToValue: JSON value is not an array : " ++ show v instance forall a b . (Sunroof a, SunroofResult a, Sunroof b, SunroofResult b) => SunroofResult (a,b) where type ResultOf (a,b) = (ResultOf a,ResultOf b) jsonToValue _ (Array ss) = case V.toList ss of [x1,x2] -> (jsonToValue (Proxy :: Proxy a) x1, jsonToValue (Proxy :: Proxy b) x2) xs -> error $ "sonToValue: JSON value is not a 2-tuple : " ++ show xs jsonToValue _ v = error $ "jsonToValue: JSON value is not an array : " ++ show v -- | Converts a JSON value to a Sunroof Javascript expression. jsonToJS :: Value -> Expr jsonToJS (Bool b) = unbox $ js b jsonToJS (Number scientific) = unbox $ js scientific jsonToJS (String s) = unbox $ js $ unpack s jsonToJS (Null) = unbox $ nullJS jsonToJS (Array arr) = jsonArrayToJS arr jsonToJS (Object obj) = jsonObjectToJS obj -- | Converts a JSON object to a Sunroof expression. jsonObjectToJS :: Object -> Expr jsonObjectToJS obj = literal $ let literalMap = M.toList $ fmap (show . jsonToJS) obj convertKey k = "\"" ++ unpack k ++ "\"" keyValues = fmap (\(k,v) -> convertKey k ++ ":" ++ v) literalMap in "{" ++ intercalate "," keyValues ++ "}" -- | Converts a JSON array to a Sunroof expression. jsonArrayToJS :: Array -> Expr jsonArrayToJS arr = literal $ "(new Array(" ++ (intercalate "," $ V.toList $ fmap (show . jsonToJS) arr) ++ "))" {- Orphans: instance SunroofValue Value where type ValueOf Value = JSObject js = box . jsonToJS instance SunroofValue Text where type ValueOf Text = JSString js = string . unpack -} -- ------------------------------------------------------------- -- Debugging -- ------------------------------------------------------------- -- | Setup a 'SunroofEngine' for debugging. debugSunroofEngine :: IO SunroofEngine debugSunroofEngine = do doc <- KC.debugDocument uqVar <- atomically $ newTVar 0 return $ SunroofEngine doc uqVar 3 def Nothing -- | Timings for communication and compilation. data Timings a = Timings { compileTime :: !a -- ^ How long spent compiling. , sendTime :: !a -- ^ How long spent sending. , waitTime :: !a -- ^ How long spent waiting for a response. } deriving Show -- | Apply a function by applying it to each timing. instance Functor Timings where fmap f (Timings t1 t2 t3) = Timings (f t1) (f t2) (f t3) -- | Combine timings by combining each single timing. instance Semigroup a => Semigroup (Timings a) where (Timings t1 t2 t3) <> (Timings u1 u2 u3) = Timings (t1<>u1) (t2<>u2) (t3<>u3) -- | Create timings in the 'SunroofEngine'. newTimings :: SunroofEngine -> IO SunroofEngine newTimings e = do v <- atomically $ newTVar $ Timings 0 0 0 return $ e { timings = Just v } -- | Reset all timings. resetTimings :: SunroofEngine -> IO () resetTimings (SunroofEngine { timings = Nothing }) = return () resetTimings (SunroofEngine { timings = Just t }) = atomically $ writeTVar t $ Timings 0 0 0 -- | Get timings from the 'SunroofEngine'. getTimings :: SunroofEngine -> IO (Timings NominalDiffTime) getTimings (SunroofEngine { timings = Nothing }) = return $ Timings 0 0 0 getTimings (SunroofEngine { timings = Just t }) = atomically $ readTVar t -- | Add a timing for compilation. addCompileTime :: SunroofEngine -> UTCTime -> IO () addCompileTime (SunroofEngine { timings = Nothing }) _start = return () addCompileTime (SunroofEngine { timings = Just t }) start = do end <- getCurrentTime atomically $ modifyTVar t $ \ ts -> ts { compileTime = compileTime ts + diffUTCTime end start} return () -- | Add a timing for sending. addSendTime :: SunroofEngine -> UTCTime -> IO () addSendTime (SunroofEngine { timings = Nothing }) _start = return () addSendTime (SunroofEngine { timings = Just t }) start = do end <- getCurrentTime atomically $ modifyTVar t $ \ ts -> ts { sendTime = sendTime ts + diffUTCTime end start} return () -- | Add a timing for waiting for a response. addWaitTime :: SunroofEngine -> UTCTime -> IO () addWaitTime (SunroofEngine { timings = Nothing }) _start = return () addWaitTime (SunroofEngine { timings = Just t }) start = do end <- getCurrentTime atomically $ modifyTVar t $ \ ts -> ts { waitTime = waitTime ts + diffUTCTime end start} return ()
ku-fpg/sunroof-server
Language/Sunroof/Server.hs
bsd-3-clause
22,364
0
18
4,814
4,474
2,374
2,100
319
2
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-} module Language.GDL.Parser ( parse, parseMaybe , parseQuery, parseTerm, parseSexp , sexpToTerm, sexpsToDatabase ) where import Control.Applicative ((<$>), (<*), (*>)) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import Data.List (foldl', sortBy, groupBy) import Data.Function (on) import qualified Data.Map as M import Text.Parsec.ByteString import Text.Parsec hiding (parse) import qualified Text.Parsec as P import Language.GDL.Syntax -- | Parse logic database from a string. parse :: ByteString -> Either ParseError Database parse s = case parseSexp s of Left e -> Left e Right sexps -> Right $ sexpsToDatabase sexps -- | A variant of 'parse' that returns 'Nothing' if the parse fails. parseMaybe :: ByteString -> Maybe Database parseMaybe s = either (const Nothing) Just $ parse s -- | Parse a single query from a string. parseQuery :: ByteString -> Maybe Query parseQuery s = case parseSexp s of Right [sexp] -> Just $ sexpToQuery sexp _ -> Nothing -- | Parse a single term from a string (used for GGP protocol). parseTerm :: ByteString -> Maybe Term parseTerm s = case parseSexp s of Right [sexp] -> Just $ sexpToTerm sexp _ -> Nothing -- | Convert a single S-exp to a term. sexpToTerm :: Sexp -> Term sexpToTerm (SAtom "_") = Wild sexpToTerm (SAtom s) = case B.splitAt 1 s of ("?", sub) -> Var sub ("$", sub) -> AntiVar sub _ -> Atom s sexpToTerm (SList ss) = Compound $ map sexpToTerm ss -- | Convert a list of S-exps to a logic database. sexpsToDatabase :: [Sexp] -> Database sexpsToDatabase = M.fromList . map (\cs -> (fst $ head cs, map snd cs)) . groupBy ((==) `on` fst) . sortBy (compare `on` fst) . reverse . foldl' (\db s -> convert s : db) [] where convert :: Sexp -> (ByteString, Clause) convert (SList (SAtom "<=" : ss)) = case ss of [h] -> (termName h, (sexpToTerm h, Pass)) [h, t] -> (termName h, (sexpToTerm h, sexpToQuery t)) (h:ts) -> (termName h, (sexpToTerm h, And $ map sexpToQuery ts)) [] -> error "Free-standing implication symbol" convert s = (termName s, (sexpToTerm s, Pass)) termName (SAtom s) = s termName (SList ((SAtom s) : _)) = s termName _ = error "termName!" sexpToQuery :: Sexp -> Query sexpToQuery (SList [SAtom "not", t]) = Not $ Query $ sexpToTerm t sexpToQuery (SList [SAtom "distinct", t1, t2]) = Distinct (sexpToTerm t1) (sexpToTerm t2) sexpToQuery (SList (SAtom "and" : ts)) = And $ map sexpToQuery ts sexpToQuery (SList (SAtom "or" : ts)) = Or $ map sexpToQuery ts sexpToQuery (SList []) = Pass sexpToQuery t = Query $ sexpToTerm t -- | Parse S-Expressions from a String. If the parse was successful, -- @Right sexps@ is returned; otherwise, @Left (errorMsg, leftover)@ -- is returned. parseSexp :: ByteString -> Either ParseError [Sexp] parseSexp = P.parse (whiteSpace *> many sexpParser) "" -- | A parser for S-Expressions. Ignoring whitespace, we follow the -- following EBNF: -- -- SEXP ::= '(' ATOM* ')' | ATOM -- ATOM ::= '"' ESCAPED_STRING* '"' | [^ \t\n()]+ -- ESCAPED_STRING ::= ... -- sexpParser :: Parser Sexp sexpParser = choice [ list <?> "list", atom <?> "atom" ] where list = SList <$> (char '(' *> whiteSpace *> many sexpParser <* char ')') <* whiteSpace atom = SAtom . unescape . B.pack <$> (choice [str, anything]) <* whiteSpace str = char '"' *> many (noneOf "\"") <* char '"' anything = many1 (noneOf " \t\n()") -- | A parser for conventional ASCII whitespace and ";" line comments. whiteSpace :: Parser () whiteSpace = many space >> many comment >> return () where comment = char ';' >> many (noneOf "\n") >> many space
ian-ross/ggp
Language/GDL/Parser.hs
bsd-3-clause
3,878
0
15
902
1,248
662
586
72
7
{-# language CPP #-} -- | = Name -- -- VK_EXT_validation_features - instance extension -- -- == VK_EXT_validation_features -- -- [__Name String__] -- @VK_EXT_validation_features@ -- -- [__Extension Type__] -- Instance extension -- -- [__Registered Extension Number__] -- 248 -- -- [__Revision__] -- 5 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- [__Special Use__] -- -- - <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#extendingvulkan-compatibility-specialuse Debugging tools> -- -- [__Contact__] -- -- - Karl Schultz -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_validation_features] @karl-lunarg%0A<<Here describe the issue or question you have about the VK_EXT_validation_features extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2018-11-14 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Karl Schultz, LunarG -- -- - Dave Houlton, LunarG -- -- - Mark Lobodzinski, LunarG -- -- - Camden Stocker, LunarG -- -- - Tony Barbour, LunarG -- -- - John Zulauf, LunarG -- -- == Description -- -- This extension provides the 'ValidationFeaturesEXT' struct that can be -- included in the @pNext@ chain of the -- 'Vulkan.Core10.DeviceInitialization.InstanceCreateInfo' structure passed -- as the @pCreateInfo@ parameter of -- 'Vulkan.Core10.DeviceInitialization.createInstance'. The structure -- contains an array of 'ValidationFeatureEnableEXT' enum values that -- enable specific validation features that are disabled by default. The -- structure also contains an array of 'ValidationFeatureDisableEXT' enum -- values that disable specific validation layer features that are enabled -- by default. -- -- Note -- -- The @VK_EXT_validation_features@ extension subsumes all the -- functionality provided in the @VK_EXT_validation_flags@ extension. -- -- == New Structures -- -- - Extending 'Vulkan.Core10.DeviceInitialization.InstanceCreateInfo': -- -- - 'ValidationFeaturesEXT' -- -- == New Enums -- -- - 'ValidationFeatureDisableEXT' -- -- - 'ValidationFeatureEnableEXT' -- -- == New Enum Constants -- -- - 'EXT_VALIDATION_FEATURES_EXTENSION_NAME' -- -- - 'EXT_VALIDATION_FEATURES_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_VALIDATION_FEATURES_EXT' -- -- == Version History -- -- - Revision 1, 2018-11-14 (Karl Schultz) -- -- - Initial revision -- -- - Revision 2, 2019-08-06 (Mark Lobodzinski) -- -- - Add Best Practices enable -- -- - Revision 3, 2020-03-04 (Tony Barbour) -- -- - Add Debug Printf enable -- -- - Revision 4, 2020-07-29 (John Zulauf) -- -- - Add Synchronization Validation enable -- -- - Revision 5, 2021-05-18 (Tony Barbour) -- -- - Add Shader Validation Cache disable -- -- == See Also -- -- 'ValidationFeatureDisableEXT', 'ValidationFeatureEnableEXT', -- 'ValidationFeaturesEXT' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_validation_features Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_validation_features ( ValidationFeaturesEXT(..) , ValidationFeatureEnableEXT( VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT , VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT , VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT , VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT , VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT , .. ) , ValidationFeatureDisableEXT( VALIDATION_FEATURE_DISABLE_ALL_EXT , VALIDATION_FEATURE_DISABLE_SHADERS_EXT , VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT , VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT , VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT , VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT , VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT , VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT , .. ) , EXT_VALIDATION_FEATURES_SPEC_VERSION , pattern EXT_VALIDATION_FEATURES_SPEC_VERSION , EXT_VALIDATION_FEATURES_EXTENSION_NAME , pattern EXT_VALIDATION_FEATURES_EXTENSION_NAME ) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import Foreign.Marshal.Alloc (allocaBytes) 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 Data.Vector (generateM) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import GHC.Generics (Generic) import Data.Int (Int32) 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 Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_VALIDATION_FEATURES_EXT)) -- | VkValidationFeaturesEXT - Specify validation features to enable or -- disable for a Vulkan instance -- -- == Valid Usage -- -- - #VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02967# If -- the @pEnabledValidationFeatures@ array contains -- 'VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT', -- then it /must/ also contain -- 'VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT' -- -- - #VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-02968# If -- the @pEnabledValidationFeatures@ array contains -- 'VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT', then it /must/ not -- contain 'VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT' -- -- == Valid Usage (Implicit) -- -- - #VUID-VkValidationFeaturesEXT-sType-sType# @sType@ /must/ be -- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_VALIDATION_FEATURES_EXT' -- -- - #VUID-VkValidationFeaturesEXT-pEnabledValidationFeatures-parameter# -- If @enabledValidationFeatureCount@ is not @0@, -- @pEnabledValidationFeatures@ /must/ be a valid pointer to an array -- of @enabledValidationFeatureCount@ valid -- 'ValidationFeatureEnableEXT' values -- -- - #VUID-VkValidationFeaturesEXT-pDisabledValidationFeatures-parameter# -- If @disabledValidationFeatureCount@ is not @0@, -- @pDisabledValidationFeatures@ /must/ be a valid pointer to an array -- of @disabledValidationFeatureCount@ valid -- 'ValidationFeatureDisableEXT' values -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_validation_features VK_EXT_validation_features>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', -- 'ValidationFeatureDisableEXT', 'ValidationFeatureEnableEXT' data ValidationFeaturesEXT = ValidationFeaturesEXT { -- | @pEnabledValidationFeatures@ is a pointer to an array of -- 'ValidationFeatureEnableEXT' values specifying the validation features -- to be enabled. enabledValidationFeatures :: Vector ValidationFeatureEnableEXT , -- | @pDisabledValidationFeatures@ is a pointer to an array of -- 'ValidationFeatureDisableEXT' values specifying the validation features -- to be disabled. disabledValidationFeatures :: Vector ValidationFeatureDisableEXT } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (ValidationFeaturesEXT) #endif deriving instance Show ValidationFeaturesEXT instance ToCStruct ValidationFeaturesEXT where withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p) pokeCStruct p ValidationFeaturesEXT{..} f = evalContT $ do lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_VALIDATION_FEATURES_EXT) lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (enabledValidationFeatures)) :: Word32)) pPEnabledValidationFeatures' <- ContT $ allocaBytes @ValidationFeatureEnableEXT ((Data.Vector.length (enabledValidationFeatures)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPEnabledValidationFeatures' `plusPtr` (4 * (i)) :: Ptr ValidationFeatureEnableEXT) (e)) (enabledValidationFeatures) lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr ValidationFeatureEnableEXT))) (pPEnabledValidationFeatures') lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (disabledValidationFeatures)) :: Word32)) pPDisabledValidationFeatures' <- ContT $ allocaBytes @ValidationFeatureDisableEXT ((Data.Vector.length (disabledValidationFeatures)) * 4) lift $ Data.Vector.imapM_ (\i e -> poke (pPDisabledValidationFeatures' `plusPtr` (4 * (i)) :: Ptr ValidationFeatureDisableEXT) (e)) (disabledValidationFeatures) lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr ValidationFeatureDisableEXT))) (pPDisabledValidationFeatures') lift $ f cStructSize = 48 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_VALIDATION_FEATURES_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) f instance FromCStruct ValidationFeaturesEXT where peekCStruct p = do enabledValidationFeatureCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32)) pEnabledValidationFeatures <- peek @(Ptr ValidationFeatureEnableEXT) ((p `plusPtr` 24 :: Ptr (Ptr ValidationFeatureEnableEXT))) pEnabledValidationFeatures' <- generateM (fromIntegral enabledValidationFeatureCount) (\i -> peek @ValidationFeatureEnableEXT ((pEnabledValidationFeatures `advancePtrBytes` (4 * (i)) :: Ptr ValidationFeatureEnableEXT))) disabledValidationFeatureCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32)) pDisabledValidationFeatures <- peek @(Ptr ValidationFeatureDisableEXT) ((p `plusPtr` 40 :: Ptr (Ptr ValidationFeatureDisableEXT))) pDisabledValidationFeatures' <- generateM (fromIntegral disabledValidationFeatureCount) (\i -> peek @ValidationFeatureDisableEXT ((pDisabledValidationFeatures `advancePtrBytes` (4 * (i)) :: Ptr ValidationFeatureDisableEXT))) pure $ ValidationFeaturesEXT pEnabledValidationFeatures' pDisabledValidationFeatures' instance Zero ValidationFeaturesEXT where zero = ValidationFeaturesEXT mempty mempty -- | VkValidationFeatureEnableEXT - Specify validation features to enable -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_validation_features VK_EXT_validation_features>, -- 'ValidationFeaturesEXT' newtype ValidationFeatureEnableEXT = ValidationFeatureEnableEXT Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT' specifies that GPU-assisted -- validation is enabled. Activating this feature instruments shader -- programs to generate additional diagnostic data. This feature is -- disabled by default. pattern VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT = ValidationFeatureEnableEXT 0 -- | 'VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT' -- specifies that the validation layers reserve a descriptor set binding -- slot for their own use. The layer reports a value for -- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxBoundDescriptorSets@ -- that is one less than the value reported by the device. If the device -- supports the binding of only one descriptor set, the validation layer -- does not perform GPU-assisted validation. This feature is disabled by -- default. pattern VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT = ValidationFeatureEnableEXT 1 -- | 'VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT' specifies that Vulkan -- best-practices validation is enabled. Activating this feature enables -- the output of warnings related to common misuse of the API, but which -- are not explicitly prohibited by the specification. This feature is -- disabled by default. pattern VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT = ValidationFeatureEnableEXT 2 -- | 'VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT' specifies that the layers -- will process @debugPrintfEXT@ operations in shaders and send the -- resulting output to the debug callback. This feature is disabled by -- default. pattern VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT = ValidationFeatureEnableEXT 3 -- | 'VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT' specifies -- that Vulkan synchronization validation is enabled. This feature reports -- resource access conflicts due to missing or incorrect synchronization -- operations between actions (Draw, Copy, Dispatch, Blit) reading or -- writing the same regions of memory. This feature is disabled by default. pattern VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT = ValidationFeatureEnableEXT 4 {-# complete VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT, VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT, VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT, VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT, VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT :: ValidationFeatureEnableEXT #-} conNameValidationFeatureEnableEXT :: String conNameValidationFeatureEnableEXT = "ValidationFeatureEnableEXT" enumPrefixValidationFeatureEnableEXT :: String enumPrefixValidationFeatureEnableEXT = "VALIDATION_FEATURE_ENABLE_" showTableValidationFeatureEnableEXT :: [(ValidationFeatureEnableEXT, String)] showTableValidationFeatureEnableEXT = [ (VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT , "GPU_ASSISTED_EXT") , (VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT, "GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT") , (VALIDATION_FEATURE_ENABLE_BEST_PRACTICES_EXT , "BEST_PRACTICES_EXT") , (VALIDATION_FEATURE_ENABLE_DEBUG_PRINTF_EXT , "DEBUG_PRINTF_EXT") , (VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT , "SYNCHRONIZATION_VALIDATION_EXT") ] instance Show ValidationFeatureEnableEXT where showsPrec = enumShowsPrec enumPrefixValidationFeatureEnableEXT showTableValidationFeatureEnableEXT conNameValidationFeatureEnableEXT (\(ValidationFeatureEnableEXT x) -> x) (showsPrec 11) instance Read ValidationFeatureEnableEXT where readPrec = enumReadPrec enumPrefixValidationFeatureEnableEXT showTableValidationFeatureEnableEXT conNameValidationFeatureEnableEXT ValidationFeatureEnableEXT -- | VkValidationFeatureDisableEXT - Specify validation features to disable -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_validation_features VK_EXT_validation_features>, -- 'ValidationFeaturesEXT' newtype ValidationFeatureDisableEXT = ValidationFeatureDisableEXT Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'VALIDATION_FEATURE_DISABLE_ALL_EXT' specifies that all validation -- checks are disabled. pattern VALIDATION_FEATURE_DISABLE_ALL_EXT = ValidationFeatureDisableEXT 0 -- | 'VALIDATION_FEATURE_DISABLE_SHADERS_EXT' specifies that shader -- validation is disabled. This feature is enabled by default. pattern VALIDATION_FEATURE_DISABLE_SHADERS_EXT = ValidationFeatureDisableEXT 1 -- | 'VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT' specifies that thread -- safety validation is disabled. This feature is enabled by default. pattern VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT = ValidationFeatureDisableEXT 2 -- | 'VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT' specifies that stateless -- parameter validation is disabled. This feature is enabled by default. pattern VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT = ValidationFeatureDisableEXT 3 -- | 'VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT' specifies that object -- lifetime validation is disabled. This feature is enabled by default. pattern VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT = ValidationFeatureDisableEXT 4 -- | 'VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT' specifies that core -- validation checks are disabled. This feature is enabled by default. If -- this feature is disabled, the shader validation and GPU-assisted -- validation features are also disabled. pattern VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT = ValidationFeatureDisableEXT 5 -- | 'VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT' specifies that -- protection against duplicate non-dispatchable object handles is -- disabled. This feature is enabled by default. pattern VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT = ValidationFeatureDisableEXT 6 -- | 'VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT' specifies that -- there will be no caching of shader validation results and every shader -- will be validated on every application execution. Shader validation -- caching is enabled by default. pattern VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT = ValidationFeatureDisableEXT 7 {-# complete VALIDATION_FEATURE_DISABLE_ALL_EXT, VALIDATION_FEATURE_DISABLE_SHADERS_EXT, VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT, VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT, VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT, VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT, VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT, VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT :: ValidationFeatureDisableEXT #-} conNameValidationFeatureDisableEXT :: String conNameValidationFeatureDisableEXT = "ValidationFeatureDisableEXT" enumPrefixValidationFeatureDisableEXT :: String enumPrefixValidationFeatureDisableEXT = "VALIDATION_FEATURE_DISABLE_" showTableValidationFeatureDisableEXT :: [(ValidationFeatureDisableEXT, String)] showTableValidationFeatureDisableEXT = [ (VALIDATION_FEATURE_DISABLE_ALL_EXT , "ALL_EXT") , (VALIDATION_FEATURE_DISABLE_SHADERS_EXT , "SHADERS_EXT") , (VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT , "THREAD_SAFETY_EXT") , (VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT , "API_PARAMETERS_EXT") , (VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT , "OBJECT_LIFETIMES_EXT") , (VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT , "CORE_CHECKS_EXT") , (VALIDATION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT , "UNIQUE_HANDLES_EXT") , (VALIDATION_FEATURE_DISABLE_SHADER_VALIDATION_CACHE_EXT, "SHADER_VALIDATION_CACHE_EXT") ] instance Show ValidationFeatureDisableEXT where showsPrec = enumShowsPrec enumPrefixValidationFeatureDisableEXT showTableValidationFeatureDisableEXT conNameValidationFeatureDisableEXT (\(ValidationFeatureDisableEXT x) -> x) (showsPrec 11) instance Read ValidationFeatureDisableEXT where readPrec = enumReadPrec enumPrefixValidationFeatureDisableEXT showTableValidationFeatureDisableEXT conNameValidationFeatureDisableEXT ValidationFeatureDisableEXT type EXT_VALIDATION_FEATURES_SPEC_VERSION = 5 -- No documentation found for TopLevel "VK_EXT_VALIDATION_FEATURES_SPEC_VERSION" pattern EXT_VALIDATION_FEATURES_SPEC_VERSION :: forall a . Integral a => a pattern EXT_VALIDATION_FEATURES_SPEC_VERSION = 5 type EXT_VALIDATION_FEATURES_EXTENSION_NAME = "VK_EXT_validation_features" -- No documentation found for TopLevel "VK_EXT_VALIDATION_FEATURES_EXTENSION_NAME" pattern EXT_VALIDATION_FEATURES_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_VALIDATION_FEATURES_EXTENSION_NAME = "VK_EXT_validation_features"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_validation_features.hs
bsd-3-clause
22,089
2
18
4,674
2,297
1,403
894
-1
-1
module Main (main) where import Distribution.Simple ( defaultMainWithHooks, simpleUserHooks , UserHooks(runTests)) import System.Cmd (system) main :: IO () main = defaultMainWithHooks hooks where hooks = simpleUserHooks { runTests = runTests' } -- Runs the testsuite runTests' _ _ _ _ = system cmd >> return () where testdir = "tests" testcmd = "runhaskell ./Main.hs" cmd = "cd " ++ testdir ++ " && " ++ testcmd
cornell-pl/HsAdapton
syb-with-class-and-effects/Setup.hs
bsd-3-clause
477
0
9
131
128
72
56
11
1
import Types import Graphics.GL.Pal someCubes2 :: Float -> [Cube] someCubes2 = \t -> [ newCube { cubeColor = colorHSL (x*0.01+t*0.3) 0.8 0.4 , cubeRotation = axisAngle (V3 0 1 0) (t*1) , cubePosition = V3 (sin (t+x*0.11) * 0.1) (x*0.1-1.5) 4 , cubeScale = V3 (x*0.01) 0.1 0.1 } | x <- [0..50] ]
lukexi/cubensis
defs/Cubes2.hs
bsd-3-clause
412
0
15
171
171
94
77
12
1
{-# LANGUAGE RecordWildCards #-} -- | -- Module : Database.LevelDB.IO -- Copyright : (c) Austin Seipp 2012 -- License : BSD3 -- -- Maintainer : mad.one@gmail.com -- Stability : experimental -- Portability : portable -- -- This module provides a mid level interface to Google's -- LevelDB (<http://leveldb.googlecode.com>). -- -- It's based on the C API, and thus doesn't quite offer the entire -- interface, but it gets close. -- -- This binding is based on LevelDB v1.5.0. -- -- Currently missing from the API: -- -- * Support for @leveldb_writebatch_iterate@ -- -- * Iterator support -- -- * Comparators -- -- * Custom environment support (needs C library support) -- -- * Custom filter policies besides bloom filters -- -- TODO: -- -- * Back Iterators/writebatches by 'ForeignPtr's with finalizers. Maybe snapshots too, -- but normally you may want to control that more. -- -- * More safety in 'close': it shouldn't double-free when you call it twice on the same object. -- Perhaps make 'DB' instead contain an 'MVar DBState' -- module Database.LevelDB.IO ( -- * Types DB , Snapshot , Writebatch , Iterator , Compression(..) , DBOptions(..) , ReadOptions(..) , WriteOptions(..) , Range(..) , Err -- * Default options , defaultDBOptions , defaultReadOptions , defaultWriteOptions -- * Opening/closing databases , open -- :: FilePath -> DBOptions -> IO (Either Err DB) , close -- :: DB -> IO () -- * Basic interface , put -- :: DB -> WriteOptions -> ByteString -> ByteString -> IO (Maybe Err) , get -- :: DB -> ReadOptions -> ByteString -> IO (Either Err ByteString) , delete -- :: DB -> WriteOptions -> ByteString -> IO (Maybe Err) -- * Batched writes , write -- :: DB -> WriteOptions -> Writebatch -> IO (Maybe Err) , createWritebatch -- :: IO Writebatch , clearWritebatch -- :: Writebatch -> IO () , writebatchPut -- :: Writebatch -> ByteString -> ByteString -> IO () , writebatchDelete -- :: Writebatch -> ByteString -> IO () , destroyWritebatch -- :: Writebatch -> IO () -- * Comparators -- Custom comparators are not yet implemented -- * Filter policies -- Custom filter policies are not yet implemented -- * Iterators -- Iterators are not yet implemented -- * Snapshots , createSnapshot -- :: DB -> IO Snapshot , releaseSnapshot -- :: Snapshot -> IO DB -- * Destroying/Repairing databases , destroy -- :: FilePath -> DBOptions -> IO (Maybe String) , repair -- :: FilePath -> DBOptions -> IO (Maybe String) -- * Approximate sizes of filesystem data , approxSizes -- :: DB -> [Range] -> IO [Word64] -- * Database compaction , compactRange -- :: DB -> Maybe Range -> Maybe Range -> IO () , compactAll -- :: DB -> IO () -- * Database properties , Property(..) -- :: * , property -- :: DB -> Property -> IO (Maybe String) -- * Re-exports , Default, def ) where import Data.Word import Control.Monad (liftM) import Control.Applicative import Foreign.Ptr import Foreign.C.String import Foreign.Storable import Foreign.Marshal.Alloc import Data.ByteString as S import Data.ByteString.Unsafe as S import Control.Concurrent as Conc import Data.Default import Database.LevelDB.FFI as C -- -- Types -- -- | 'DBState' encapsulates the state associated with a -- database connection. data DBState = DBState { _dbOptsPtr :: !(Ptr LevelDB_Options_t) , _dbCachePtr :: !(Maybe (Ptr LevelDB_Cache_t)) , _dbFPolicyPtr :: !(Maybe (Ptr LevelDB_FilterPolicy_t)) } deriving (Eq, Show) -- | Handle to an opened database. data DB = DB { _dbPtr :: !(Ptr LevelDB_t) , _dbState :: !DBState } deriving (Eq, Show) -- | Handle to a database snapshot data Snapshot = Snapshot !(Ptr LevelDB_t) !(Ptr LevelDB_Snapshot_t) -- | Handle to a batched write object newtype Writebatch = Writebatch (Conc.MVar (Ptr LevelDB_Writebatch_t)) -- | Handle to a database iterator newtype Iterator = Iterator (Conc.MVar (Ptr LevelDB_Iterator_t)) -- | Compression modes data Compression = Snappy | None deriving (Eq, Show) -- | Because of the way leveldb data is organized on disk, a single -- 'get' call may involve multiple reads from disk. The optional -- 'FilterPolicy' mechanism can be used to reduce the number of disk -- reads substantially. -- -- While custom filters can be set, right now only the included bloom -- filter interface is available. data FilterPolicy = Bloom {-# UNPACK #-} !Int -- ^ Bloom filter, with integer specifying how many bits per key to keep in memory. deriving (Eq, Show) -- | Options for creating a database. data DBOptions = DBOptions { -- dbComparator :: ... dbCreateIfMissing :: Bool -- ^ Create database if it doesn't exist when calling 'open'. Default: 'False'. , dbErrorIfExists :: Bool -- ^ Error if the database exists when calling 'open'. Default: 'False'. , dbParanoidChecks :: Bool -- ^ Do aggressive checking of data integrity and report errors early. Default: 'False' , dbFilterPolicy :: Maybe FilterPolicy -- ^ Set a filter policy for the database to reduce disk seeks. -- Currently only a bloom filter can be set. Default: 'Nothing' --, dbInfoLog :: ... , dbWriteBufferSize :: Int -- ^ Amount of data to buffer in memory before writing to disk. Default: 4MB. , dbMaxOpenFiles :: Int -- ^ Max amount of files allowed to be open at one time. Default: 1000. , dbCacheCapacity :: Maybe Int -- ^ Capacity of LRU cache. If 'Nothing', a default internal 8MB cache is used. , dbBlockSize :: Int -- ^ Size of on disk blocks, not taking compression into account. -- Can change dynamically. Default: 4K. , dbBlockResizeInterval :: Int -- ^ Number of keys between restart points. Most should leave this alone. Default: 16. , dbCompression :: Compression -- ^ Compression mode. Default: 'Snappy'. } deriving (Show) -- | Default 'DBOptions'. defaultDBOptions :: DBOptions defaultDBOptions = DBOptions { -- dbComparator = ... dbCreateIfMissing = False , dbErrorIfExists = False , dbParanoidChecks = False , dbFilterPolicy = Nothing --, dbInfoLog = ... , dbWriteBufferSize = 4194304 , dbMaxOpenFiles = 1000 , dbCacheCapacity = Nothing , dbBlockSize = 4096 , dbBlockResizeInterval = 16 , dbCompression = Snappy } instance Default DBOptions where def = defaultDBOptions -- | Options for issuing reads from the database. data ReadOptions = ReadOptions { readVerifyChecksums :: Bool -- ^ If set, then reads will verify checksum data. Default: false. , readFillCache :: Bool -- ^ Should data read be cached in memory? Default: true , readSnapshot :: Maybe Snapshot -- ^ If set, reads will use this snapshot of the Database state. } defaultReadOptions :: ReadOptions defaultReadOptions = ReadOptions { readVerifyChecksums = False , readFillCache = True , readSnapshot = Nothing } instance Default ReadOptions where def = defaultReadOptions -- | Options specified when issuing writes on the database. -- Right now, you can just control whether or not you should -- sync the filesystem after every write via @fsync@ et al. data WriteOptions = WriteOptions { writeWithSync :: Bool -- ^ Sync data after writes with @fsync@ et al. Default: False. } defaultWriteOptions :: WriteOptions defaultWriteOptions = WriteOptions { writeWithSync = False } instance Default WriteOptions where def = defaultWriteOptions -- | The LevelDB C API uses Strings for an error interface. type Err = String -- -- Interface -- -- | Open a database at a specified path. -- May fail if database doesn't exist unless 'dbCreateIfMissing' is @True@. -- Will fail if 'dbErrorIfExists' is set and the database exists. open :: FilePath -- ^ Path to database -> DBOptions -- ^ Database options -> IO (Either Err DB) open dbname dbopts = withCString dbname $ \str -> do st <- dbOptsToDBState dbopts r <- wrapErr (C.c_leveldb_open (_dbOptsPtr st) str) case r of Left e -> return $ Left e Right db -> return $ Right $ DB db st -- | Close a database handle. close :: DB -- ^ Database -> IO () close (DB db st) = do C.c_leveldb_close db freeDBState st -- | Put a value into a database. put :: DB -- ^ Database -> WriteOptions -- ^ Write options -> ByteString -- ^ Key -> ByteString -- ^ Value -> IO (Maybe Err) put (DB db _) woptions key value = S.unsafeUseAsCStringLen key $ \(kptr,klen) -> do S.unsafeUseAsCStringLen value $ \(vptr,vlen) -> do opts <- writeOptsToPtr woptions r <- wrapErr (C.c_leveldb_put db opts kptr (fromIntegral klen) vptr (fromIntegral vlen)) C.c_leveldb_writeoptions_destroy opts case r of Left e -> return $ Just e Right _ -> return Nothing -- | Look up a value in a database. May return 'Right Data.ByteString.empty' -- if the key does not exist. get :: DB -- ^ Database -> ReadOptions -- ^ Read options -> ByteString -- ^ Key -> IO (Either Err ByteString) get (DB db _) roptions key = S.unsafeUseAsCStringLen key $ \(kptr, klen) -> alloca $ \vallen -> do opts <- readOptsToPtr roptions r <- wrapErr (C.c_leveldb_get db opts kptr (fromIntegral klen) vallen) C.c_leveldb_readoptions_destroy opts case r of Left e -> return $ Left e Right p -> do if p == nullPtr then return $ Right S.empty else do vlen <- peek vallen bs <- S.packCStringLen (p, fromIntegral vlen) return $ Right bs -- | Remove a database entry. Returns 'Nothing' in case of success, -- or 'Just e' where 'e' is an error if not. delete :: DB -- ^ Database -> WriteOptions -- ^ Write options -> ByteString -- ^ Key -> IO (Maybe Err) delete (DB db _) woptions key = S.unsafeUseAsCStringLen key $ \(kptr,klen) -> do opts <- writeOptsToPtr woptions r <- wrapErr (C.c_leveldb_delete db opts kptr (fromIntegral klen)) C.c_leveldb_writeoptions_destroy opts case r of Left e -> return $ Just e Right _ -> return Nothing -- | Apply a 'WriteBatch' and all its updates to the database -- atomically. write :: DB -- ^ Database -> WriteOptions -- ^ Write options -> Writebatch -- ^ Batch of writes to issue -> IO (Maybe Err) write (DB db _) woptions (Writebatch m) = do opts <- writeOptsToPtr woptions r <- Conc.withMVar m $ \wb -> wrapErr (C.c_leveldb_write db opts wb) C.c_leveldb_writeoptions_destroy opts case r of Left e -> return $ Just e Right _ -> return Nothing -- | Create a 'Writebatch', which can be used to make multiple atomic updates createWritebatch :: IO Writebatch createWritebatch = Writebatch <$> (C.c_leveldb_writebatch_create >>= Conc.newMVar) -- | Clear all the update operations from the specified 'Writebatch' object clearWritebatch :: Writebatch -> IO () clearWritebatch (Writebatch m) = Conc.withMVar m C.c_leveldb_writebatch_clear -- | Issue a 'put' operation to take place as part of a write batch. writebatchPut :: Writebatch -- ^ Write batch -> ByteString -- ^ Key -> ByteString -- ^ Value -> IO () writebatchPut (Writebatch m) key val = S.unsafeUseAsCStringLen key $ \(kptr, klen) -> S.unsafeUseAsCStringLen val $ \(vptr, vlen) -> Conc.withMVar m $ \wb -> C.c_leveldb_writebatch_put wb kptr (fromIntegral klen) vptr (fromIntegral vlen) -- | Issue a 'delete' operation to take place as part of a write batch. writebatchDelete :: Writebatch -- ^ Write batch -> ByteString -- ^ Key -> IO () writebatchDelete (Writebatch m) key = S.unsafeUseAsCStringLen key $ \(kptr, klen) -> Conc.withMVar m $ \wb -> C.c_leveldb_writebatch_delete wb kptr (fromIntegral klen) -- | Destroy a 'Writebatch' object after you're done with it. destroyWritebatch :: Writebatch -- ^ Writebatch object -> IO () destroyWritebatch (Writebatch m) = Conc.withMVar m C.c_leveldb_writebatch_destroy -- | Return a handle to the current DB state. Iterators created with -- this handle or reads issued with 'readSnapshot' set to this value will -- observe a stable snapshot of the current DB state. The caller must -- call 'releaseSnapshot' when the snapshot is no longer needed. createSnapshot :: DB -- ^ Database -> IO Snapshot createSnapshot (DB db _) = do snap <- C.c_leveldb_create_snapshot db return $! Snapshot db snap -- | Release a previously acquired snapshot. The caller must not -- use the 'Snapshot' again after this call. releaseSnapshot :: Snapshot -- ^ Snapshot -> IO () releaseSnapshot (Snapshot db s) = do C.c_leveldb_release_snapshot db s -- | Destroy the contents of the specified database. -- Be very careful using this method. -- -- Returns 'Nothing' if successful. Otherwise, returns -- an error. destroy :: FilePath -- ^ Path to database -> DBOptions -- ^ Database options -> IO (Maybe String) destroy dbname dbopts = withCString dbname $ \str -> do st <- dbOptsToDBState dbopts r <- wrapErr (C.c_leveldb_destroy_db (_dbOptsPtr st) str) freeDBState st case r of Left e -> return (Just e) Right _ -> return Nothing -- | If a DB cannot be opened, you may attempt to call this method to -- resurrect as much of the contents of the database as possible. -- Some data may be lost, so be careful when calling this function -- on a database that contains important information. -- -- Returns 'Nothing' if there was no error. Otherwise, it returns -- the error string. repair :: FilePath -- ^ Path to database -> DBOptions -- ^ Database options -> IO (Maybe Err) repair dbname dbopts = withCString dbname $ \str -> do st <- dbOptsToDBState dbopts r <- wrapErr (C.c_leveldb_repair_db (_dbOptsPtr st) str) freeDBState st case r of Left e -> return (Just e) Right _ -> return Nothing -- | A range represents a range of keys in the database. data Range = Range {-# UNPACK #-} !ByteString {-# UNPACK #-} !ByteString deriving (Eq, Show) -- | Approximate the size of a range of values in the database. approxSizes :: DB -> [Range] -> IO [Word64] approxSizes _ _ = return [] -- | Compact a range of keys in the database. Deleted and overwritten -- versions of old data are discarded and is rearranged to avoid -- seeks/fragmentation. -- -- The first parameter is the starting key, and the second is the -- ending key. 'Nothing' represents a key before/after all the other -- keys in the database. -- -- Therefore, to compact the whole database, use @compactRange db -- Nothing Nothing@ or 'compactAll' below. compactRange :: DB -> Maybe ByteString -- ^ Start range -> Maybe ByteString -- ^ End range -> IO () compactRange (DB db _) r1 r2 = toRange r1 $ \(r1p, r1l) -> toRange r2 $ \(r2p, r2l) -> C.c_leveldb_compact_range db r1p (fromIntegral r1l) r2p (fromIntegral r2l) where toRange Nothing f = f (nullPtr, 0) toRange (Just x) f = S.unsafeUseAsCStringLen x f -- | Compact the entire database. Defined as: -- -- > compactAll db = compactRange db Nothing Nothing compactAll :: DB -> IO () compactAll db = compactRange db Nothing Nothing -- | Database properties. Currently offered properties are: -- -- * \"leveldb.num-files-at-level\<N\>\" - return the number of files at level \<N\>, -- where \<N\> is an ASCII representation of a level number (e.g. \"0\"). -- -- * \"leveldb.stats\" - returns a multi-line string that describes statistics -- about the internal operation of the DB. -- -- * \"leveldb.sstables\" - returns a multi-line string that describes all -- of the sstables that make up the db contents. data Property = NumFilesAtLevel {-# UNPACK #-} !Int | DBStats | SSTables deriving (Eq, Show) -- | Retrieve a property about the database. property :: DB -> Property -- ^ Property -> IO (Maybe String) property db (NumFilesAtLevel n) | n >= 0 = property' db $ "leveldb.num-files-at-level" ++ show n | otherwise = return Nothing property db DBStats = property' db "leveldb.stats" property db SSTables = property' db "leveldb.sstables" property' :: DB -> String -> IO (Maybe String) property' (DB db _) prop = withCString prop $ \str -> do p <- C.c_leveldb_property_value db str if p == nullPtr then return Nothing else do x <- Just `liftM` peekCString p free p return x -- -- Utils -- writeOptsToPtr :: WriteOptions -> IO (Ptr LevelDB_Writeoptions_t) writeOptsToPtr WriteOptions{..} = do woptions <- C.c_leveldb_writeoptions_create C.c_leveldb_writeoptions_set_sync woptions (boolToNum writeWithSync) return woptions readOptsToPtr :: ReadOptions -> IO (Ptr LevelDB_Readoptions_t) readOptsToPtr ReadOptions{..} = do roptions <- C.c_leveldb_readoptions_create C.c_leveldb_readoptions_set_verify_checksums roptions (boolToNum readVerifyChecksums) C.c_leveldb_readoptions_set_fill_cache roptions (boolToNum readFillCache) case readSnapshot of Nothing -> C.c_leveldb_readoptions_set_snapshot roptions nullPtr Just (Snapshot _ s) -> C.c_leveldb_readoptions_set_snapshot roptions s return roptions freeDBState :: DBState -> IO () freeDBState DBState{..} = do C.c_leveldb_options_destroy _dbOptsPtr maybe (return ()) C.c_leveldb_cache_destroy _dbCachePtr maybe (return ()) C.c_leveldb_filterpolicy_destroy _dbFPolicyPtr dbOptsToDBState :: DBOptions -> IO DBState dbOptsToDBState dbopts@DBOptions{..} = do -- First set cache and policy options since they're -- delt with a little out of line. opts <- dbOptsToPtr dbopts cache <- case dbCacheCapacity of Just x -> do c <- C.c_leveldb_cache_create_lru (fromIntegral x) C.c_leveldb_options_set_cache opts c return $ Just c _ -> return Nothing fpolicy <- case dbFilterPolicy of Just (Bloom x) -> do fp <- C.c_leveldb_filterpolicy_create_bloom (fromIntegral x) C.c_leveldb_options_set_filter_policy opts fp return $ Just fp _ -> return Nothing -- Done return $! DBState opts cache fpolicy -- NB: does not set cache! dbOptsToPtr :: DBOptions -> IO (Ptr LevelDB_Options_t) dbOptsToPtr DBOptions{..} = do options <- C.c_leveldb_options_create C.c_leveldb_options_set_create_if_missing options (boolToNum dbCreateIfMissing) C.c_leveldb_options_set_error_if_exists options (boolToNum dbErrorIfExists) C.c_leveldb_options_set_paranoid_checks options (boolToNum dbParanoidChecks) C.c_leveldb_options_set_write_buffer_size options (fromIntegral dbWriteBufferSize) C.c_leveldb_options_set_max_open_files options (fromIntegral dbMaxOpenFiles) C.c_leveldb_options_set_block_size options (fromIntegral dbBlockSize) C.c_leveldb_options_set_block_restart_interval options (fromIntegral dbBlockResizeInterval) C.c_leveldb_options_set_compression options (toCompression dbCompression) return options where toCompression Snappy = C.c_leveldb_snappy_compression toCompression None = C.c_leveldb_no_compression boolToNum :: Num b => Bool -> b boolToNum True = fromIntegral (1 :: Int) boolToNum False = fromIntegral (0 :: Int) wrapErr :: (Ptr CString -> IO a) -> IO (Either Err a) wrapErr f = do alloca $ \ptr -> do poke ptr nullPtr r <- f ptr x <- peek ptr if (x /= nullPtr) then do str <- peekCString x free x return $ Left str else do return $ Right r
thoughtpolice/hs-leveldb
src/Database/LevelDB/IO.hs
bsd-3-clause
20,918
0
22
5,620
3,792
2,008
1,784
359
3
module Lift ( lambdaLiftProgram ) where import Data.List (sort, nub) import Control.Monad.State import Control.Monad.Writer import Syntax import Type without :: Eq a => [a] -> [a] -> [a] without = foldr (filter . (/=)) free :: Expression Typed -> [Typed] free (Quote _) = [] free (Quasiquote x) = free' x free (BinOp _ e1 e2) = free e1 ++ free e2 free (Variable x) = [x] free (Lambda x e) = free e `without` x free (Let binds e2) = concatMap free es ++ free e2 `without` xs where (xs, es) = unzip binds free (If cond tr fl) = free cond ++ free tr ++ free fl free (Call e1 e2) = free e1 ++ concatMap free e2 free (Fix _ e) = free e free' :: Quasisexp Typed -> [Typed] free' (Quasiatom _) = [] free' (Quasicons car cdr) = free' car ++ free' cdr free' (Unquote e) = free e free' (UnquoteSplicing e) = free e convert' :: [Typed] -> [Typed] -> Quasisexp Typed -> Quasisexp Typed convert' env fvs expr = case expr of (Quasiatom x) -> Quasiatom x (Quasicons car cdr) -> Quasicons (convert' env fvs car) (convert' env fvs cdr) (Unquote e) -> Unquote $ convert env fvs e (UnquoteSplicing e) -> UnquoteSplicing $ convert env fvs e convert :: [Typed] -> [Typed] -> Expression Typed -> Expression Typed convert env fvs expr = case expr of (Quote x) -> Quote x (Quasiquote x) -> Quasiquote $ convert' env fvs x (BinOp op e1 e2) -> BinOp op (convert env fvs e1) (convert env fvs e2) (Variable x) -> Variable x (Lambda x e) -> Lambda (x ++ fvs') (convert env fvs' e) where x' = head x fvs' = sort $ nub $ free e `without` (x' : env) (Let b e2) -> Let [(x, convert env' fvs' e1)] (convert env' fvs' e2) where (x, e1) = head b env' = x : env fvs' = fvs `without` [x] (If cond tr fl) -> If (convert env fvs cond) (convert env fvs tr) (convert env fvs fl) (Call e1 e2) -> Call (convert env fvs e1) (map (convert env fvs) e2) (Fix name e) -> Fix name (convert env fvs e) type Lift a = WriterT [Top Typed] (State Word) a fresh :: Lift String fresh = do count <- lift get lift $ put (count + 1) return $ show count qqLambdaLift :: Quasisexp Typed -> Lift (Quasisexp Typed) qqLambdaLift x@(Quasiatom _) = return x qqLambdaLift (Quasicons car cdr) = do car' <- qqLambdaLift car cdr' <- qqLambdaLift cdr return $ Quasicons car' cdr' qqLambdaLift (Unquote e) = do e' <- lambdaLift e return $ Unquote e' qqLambdaLift (UnquoteSplicing e) = do e' <- lambdaLift e return $ UnquoteSplicing e' lambdaLift :: Expression Typed -> Lift (Expression Typed) lambdaLift (Quote x) = return $ Quote x lambdaLift (Quasiquote x) = do x' <- qqLambdaLift x return $ Quasiquote x' lambdaLift (BinOp op e1 e2) = do e1' <- lambdaLift e1 e2' <- lambdaLift e2 return $ BinOp op e1' e2' lambdaLift (Variable x) = return $ Variable x lambdaLift (Lambda x e) = do let (_, ty) = head x name <- fresh e' <- lambdaLift e let def = Define (name, ty) (Lambda x e') tell [def] return $ Variable (name, ty) lambdaLift (Let b e2) = do let (x, e1) = head b e1' <- lambdaLift e1 e2' <- lambdaLift e2 return $ Let [(x, e1')] e2' lambdaLift (If cond tr fl) = do cond' <- lambdaLift cond tr' <- lambdaLift tr fl' <- lambdaLift fl return $ If cond' tr' fl' lambdaLift (Call e1 e2) = do e1' <- lambdaLift e1 e2' <- mapM lambdaLift e2 return $ Call e1' e2' lambdaLift (Fix name e) = do e' <- lambdaLift e return $ Fix name e' lambdaLiftTop :: Word -> [Typed] -> Top Typed -> (Program Typed, Word) lambdaLiftTop count globals top = case top of (Define _ body) -> (defs, count') where ((_, defs), count') = flip runState count . runWriterT . lambdaLift $ convert globals [] body (Command body) -> (defs ++ [Command body'], count') where ((body', defs), count') = flip runState count . runWriterT . lambdaLift $ convert globals [] body _ -> ([top], count) lambdaLiftProgram :: Word -> [Typed] -> Program Typed -> (Program Typed, Word) lambdaLiftProgram count _ [] = ([], count) lambdaLiftProgram count globals (top@Define {}:rest) = (rest', count'') where (rest', count'') = lambdaLiftProgram count' globals rest (_, count') = lambdaLiftTop count globals top lambdaLiftProgram count globals (top@Command {}:rest) = (cmd ++ rest', count'') where (rest', count'') = lambdaLiftProgram count' globals rest (cmd, count') = lambdaLiftTop count globals top lambdaLiftProgram count globals (top@Declare {}:rest) = (decl ++ rest', count'') where (rest', count'') = lambdaLiftProgram count' globals rest (decl, count') = lambdaLiftTop count globals top
jjingram/satori
src/Lift.hs
bsd-3-clause
4,695
0
13
1,126
2,195
1,092
1,103
128
9
module RPS.Game ( Hand(..), Result(..), whoWins, whatToDo ) where data Hand = Rock | Paper | Scissors deriving (Show, Eq) data Result = Win | Lose | Tie instance Show Result where show Win = "You won! :)" show Lose = "You lost! :(" show Tie = "Tie -.-" whoWins :: Hand -> Hand -> Result whoWins player computer = case (player, computer) of (Paper, Rock) -> Win (Rock, Scissors) -> Win (Scissors, Paper) -> Win (x, y) | x == y -> Tie (_, _) -> Lose whatToDo :: Hand whatToDo = do Rock
cjw-charleswu/Wizard
RockPaperScissors/src/RPS/Game.hs
bsd-3-clause
536
0
11
147
213
121
92
22
5
-- (c) The University of Glasgow 2006 -- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -- -- Storage manager representation of closures {-# LANGUAGE CPP,GeneralizedNewtypeDeriving #-} module GHC.Runtime.Layout ( -- * Words and bytes WordOff, ByteOff, wordsToBytes, bytesToWordsRoundUp, roundUpToWords, roundUpTo, StgWord, fromStgWord, toStgWord, StgHalfWord, fromStgHalfWord, toStgHalfWord, halfWordSize, halfWordSizeInBits, -- * Closure representation SMRep(..), -- CmmInfo sees the rep; no one else does IsStatic, ClosureTypeInfo(..), ArgDescr(..), Liveness, ConstrDescription, -- ** Construction mkHeapRep, blackHoleRep, indStaticRep, mkStackRep, mkRTSRep, arrPtrsRep, smallArrPtrsRep, arrWordsRep, -- ** Predicates isStaticRep, isConRep, isThunkRep, isFunRep, isStaticNoCafCon, isStackRep, -- ** Size-related things heapClosureSizeW, fixedHdrSizeW, arrWordsHdrSize, arrWordsHdrSizeW, arrPtrsHdrSize, arrPtrsHdrSizeW, profHdrSize, thunkHdrSize, nonHdrSize, nonHdrSizeW, smallArrPtrsHdrSize, smallArrPtrsHdrSizeW, hdrSize, hdrSizeW, fixedHdrSize, -- ** RTS closure types rtsClosureType, rET_SMALL, rET_BIG, aRG_GEN, aRG_GEN_BIG, -- ** Arrays card, cardRoundUp, cardTableSizeB, cardTableSizeW ) where import GhcPrelude import BasicTypes( ConTagZ ) import DynFlags import Outputable import GHC.Platform import FastString import Data.Word import Data.Bits import Data.ByteString (ByteString) {- ************************************************************************ * * Words and bytes * * ************************************************************************ -} -- | Word offset, or word count type WordOff = Int -- | Byte offset, or byte count type ByteOff = Int -- | Round up the given byte count to the next byte count that's a -- multiple of the machine's word size. roundUpToWords :: DynFlags -> ByteOff -> ByteOff roundUpToWords dflags n = roundUpTo n (wORD_SIZE dflags) -- | Round up @base@ to a multiple of @size@. roundUpTo :: ByteOff -> ByteOff -> ByteOff roundUpTo base size = (base + (size - 1)) .&. (complement (size - 1)) -- | Convert the given number of words to a number of bytes. -- -- This function morally has type @WordOff -> ByteOff@, but uses @Num -- a@ to allow for overloading. wordsToBytes :: Num a => DynFlags -> a -> a wordsToBytes dflags n = fromIntegral (wORD_SIZE dflags) * n {-# SPECIALIZE wordsToBytes :: DynFlags -> Int -> Int #-} {-# SPECIALIZE wordsToBytes :: DynFlags -> Word -> Word #-} {-# SPECIALIZE wordsToBytes :: DynFlags -> Integer -> Integer #-} -- | First round the given byte count up to a multiple of the -- machine's word size and then convert the result to words. bytesToWordsRoundUp :: DynFlags -> ByteOff -> WordOff bytesToWordsRoundUp dflags n = (n + word_size - 1) `quot` word_size where word_size = wORD_SIZE dflags -- StgWord is a type representing an StgWord on the target platform. -- A Word64 is large enough to hold a Word for either a 32bit or 64bit platform newtype StgWord = StgWord Word64 deriving (Eq, Bits) fromStgWord :: StgWord -> Integer fromStgWord (StgWord i) = toInteger i toStgWord :: DynFlags -> Integer -> StgWord toStgWord dflags i = case platformWordSize (targetPlatform dflags) of -- These conversions mean that things like toStgWord (-1) -- do the right thing PW4 -> StgWord (fromIntegral (fromInteger i :: Word32)) PW8 -> StgWord (fromInteger i) instance Outputable StgWord where ppr (StgWord i) = integer (toInteger i) -- -- A Word32 is large enough to hold half a Word for either a 32bit or -- 64bit platform newtype StgHalfWord = StgHalfWord Word32 deriving Eq fromStgHalfWord :: StgHalfWord -> Integer fromStgHalfWord (StgHalfWord w) = toInteger w toStgHalfWord :: DynFlags -> Integer -> StgHalfWord toStgHalfWord dflags i = case platformWordSize (targetPlatform dflags) of -- These conversions mean that things like toStgHalfWord (-1) -- do the right thing PW4 -> StgHalfWord (fromIntegral (fromInteger i :: Word16)) PW8 -> StgHalfWord (fromInteger i :: Word32) instance Outputable StgHalfWord where ppr (StgHalfWord w) = integer (toInteger w) -- | Half word size in bytes halfWordSize :: DynFlags -> ByteOff halfWordSize dflags = platformWordSizeInBytes (targetPlatform dflags) `div` 2 halfWordSizeInBits :: DynFlags -> Int halfWordSizeInBits dflags = platformWordSizeInBits (targetPlatform dflags) `div` 2 {- ************************************************************************ * * \subsubsection[SMRep-datatype]{@SMRep@---storage manager representation} * * ************************************************************************ -} -- | A description of the layout of a closure. Corresponds directly -- to the closure types in includes/rts/storage/ClosureTypes.h. data SMRep = HeapRep -- GC routines consult sizes in info tbl IsStatic !WordOff -- # ptr words !WordOff -- # non-ptr words INCLUDING SLOP (see mkHeapRep below) ClosureTypeInfo -- type-specific info | ArrayPtrsRep !WordOff -- # ptr words !WordOff -- # card table words | SmallArrayPtrsRep !WordOff -- # ptr words | ArrayWordsRep !WordOff -- # bytes expressed in words, rounded up | StackRep -- Stack frame (RET_SMALL or RET_BIG) Liveness | RTSRep -- The RTS needs to declare info tables with specific Int -- type tags, so this form lets us override the default SMRep -- tag for an SMRep. -- | True <=> This is a static closure. Affects how we garbage-collect it. -- Static closure have an extra static link field at the end. -- Constructors do not have a static variant; see Note [static constructors] type IsStatic = Bool -- From an SMRep you can get to the closure type defined in -- includes/rts/storage/ClosureTypes.h. Described by the function -- rtsClosureType below. data ClosureTypeInfo = Constr ConTagZ ConstrDescription | Fun FunArity ArgDescr | Thunk | ThunkSelector SelectorOffset | BlackHole | IndStatic type ConstrDescription = ByteString -- result of dataConIdentity type FunArity = Int type SelectorOffset = Int ------------------------- -- We represent liveness bitmaps as a Bitmap (whose internal -- representation really is a bitmap). These are pinned onto case return -- vectors to indicate the state of the stack for the garbage collector. -- -- In the compiled program, liveness bitmaps that fit inside a single -- word (StgWord) are stored as a single word, while larger bitmaps are -- stored as a pointer to an array of words. type Liveness = [Bool] -- One Bool per word; True <=> non-ptr or dead -- False <=> ptr ------------------------- -- An ArgDescr describes the argument pattern of a function data ArgDescr = ArgSpec -- Fits one of the standard patterns !Int -- RTS type identifier ARG_P, ARG_N, ... | ArgGen -- General case Liveness -- Details about the arguments ----------------------------------------------------------------------------- -- Construction mkHeapRep :: DynFlags -> IsStatic -> WordOff -> WordOff -> ClosureTypeInfo -> SMRep mkHeapRep dflags is_static ptr_wds nonptr_wds cl_type_info = HeapRep is_static ptr_wds (nonptr_wds + slop_wds) cl_type_info where slop_wds | is_static = 0 | otherwise = max 0 (minClosureSize dflags - (hdr_size + payload_size)) hdr_size = closureTypeHdrSize dflags cl_type_info payload_size = ptr_wds + nonptr_wds mkRTSRep :: Int -> SMRep -> SMRep mkRTSRep = RTSRep mkStackRep :: [Bool] -> SMRep mkStackRep liveness = StackRep liveness blackHoleRep :: SMRep blackHoleRep = HeapRep False 0 0 BlackHole indStaticRep :: SMRep indStaticRep = HeapRep True 1 0 IndStatic arrPtrsRep :: DynFlags -> WordOff -> SMRep arrPtrsRep dflags elems = ArrayPtrsRep elems (cardTableSizeW dflags elems) smallArrPtrsRep :: WordOff -> SMRep smallArrPtrsRep elems = SmallArrayPtrsRep elems arrWordsRep :: DynFlags -> ByteOff -> SMRep arrWordsRep dflags bytes = ArrayWordsRep (bytesToWordsRoundUp dflags bytes) ----------------------------------------------------------------------------- -- Predicates isStaticRep :: SMRep -> IsStatic isStaticRep (HeapRep is_static _ _ _) = is_static isStaticRep (RTSRep _ rep) = isStaticRep rep isStaticRep _ = False isStackRep :: SMRep -> Bool isStackRep StackRep{} = True isStackRep (RTSRep _ rep) = isStackRep rep isStackRep _ = False isConRep :: SMRep -> Bool isConRep (HeapRep _ _ _ Constr{}) = True isConRep _ = False isThunkRep :: SMRep -> Bool isThunkRep (HeapRep _ _ _ Thunk) = True isThunkRep (HeapRep _ _ _ ThunkSelector{}) = True isThunkRep (HeapRep _ _ _ BlackHole) = True isThunkRep (HeapRep _ _ _ IndStatic) = True isThunkRep _ = False isFunRep :: SMRep -> Bool isFunRep (HeapRep _ _ _ Fun{}) = True isFunRep _ = False isStaticNoCafCon :: SMRep -> Bool -- This should line up exactly with CONSTR_NOCAF below -- See Note [Static NoCaf constructors] isStaticNoCafCon (HeapRep _ 0 _ Constr{}) = True isStaticNoCafCon _ = False ----------------------------------------------------------------------------- -- Size-related things fixedHdrSize :: DynFlags -> ByteOff fixedHdrSize dflags = wordsToBytes dflags (fixedHdrSizeW dflags) -- | Size of a closure header (StgHeader in includes/rts/storage/Closures.h) fixedHdrSizeW :: DynFlags -> WordOff fixedHdrSizeW dflags = sTD_HDR_SIZE dflags + profHdrSize dflags -- | Size of the profiling part of a closure header -- (StgProfHeader in includes/rts/storage/Closures.h) profHdrSize :: DynFlags -> WordOff profHdrSize dflags | gopt Opt_SccProfilingOn dflags = pROF_HDR_SIZE dflags | otherwise = 0 -- | The garbage collector requires that every closure is at least as -- big as this. minClosureSize :: DynFlags -> WordOff minClosureSize dflags = fixedHdrSizeW dflags + mIN_PAYLOAD_SIZE dflags arrWordsHdrSize :: DynFlags -> ByteOff arrWordsHdrSize dflags = fixedHdrSize dflags + sIZEOF_StgArrBytes_NoHdr dflags arrWordsHdrSizeW :: DynFlags -> WordOff arrWordsHdrSizeW dflags = fixedHdrSizeW dflags + (sIZEOF_StgArrBytes_NoHdr dflags `quot` wORD_SIZE dflags) arrPtrsHdrSize :: DynFlags -> ByteOff arrPtrsHdrSize dflags = fixedHdrSize dflags + sIZEOF_StgMutArrPtrs_NoHdr dflags arrPtrsHdrSizeW :: DynFlags -> WordOff arrPtrsHdrSizeW dflags = fixedHdrSizeW dflags + (sIZEOF_StgMutArrPtrs_NoHdr dflags `quot` wORD_SIZE dflags) smallArrPtrsHdrSize :: DynFlags -> ByteOff smallArrPtrsHdrSize dflags = fixedHdrSize dflags + sIZEOF_StgSmallMutArrPtrs_NoHdr dflags smallArrPtrsHdrSizeW :: DynFlags -> WordOff smallArrPtrsHdrSizeW dflags = fixedHdrSizeW dflags + (sIZEOF_StgSmallMutArrPtrs_NoHdr dflags `quot` wORD_SIZE dflags) -- Thunks have an extra header word on SMP, so the update doesn't -- splat the payload. thunkHdrSize :: DynFlags -> WordOff thunkHdrSize dflags = fixedHdrSizeW dflags + smp_hdr where smp_hdr = sIZEOF_StgSMPThunkHeader dflags `quot` wORD_SIZE dflags hdrSize :: DynFlags -> SMRep -> ByteOff hdrSize dflags rep = wordsToBytes dflags (hdrSizeW dflags rep) hdrSizeW :: DynFlags -> SMRep -> WordOff hdrSizeW dflags (HeapRep _ _ _ ty) = closureTypeHdrSize dflags ty hdrSizeW dflags (ArrayPtrsRep _ _) = arrPtrsHdrSizeW dflags hdrSizeW dflags (SmallArrayPtrsRep _) = smallArrPtrsHdrSizeW dflags hdrSizeW dflags (ArrayWordsRep _) = arrWordsHdrSizeW dflags hdrSizeW _ _ = panic "SMRep.hdrSizeW" nonHdrSize :: DynFlags -> SMRep -> ByteOff nonHdrSize dflags rep = wordsToBytes dflags (nonHdrSizeW rep) nonHdrSizeW :: SMRep -> WordOff nonHdrSizeW (HeapRep _ p np _) = p + np nonHdrSizeW (ArrayPtrsRep elems ct) = elems + ct nonHdrSizeW (SmallArrayPtrsRep elems) = elems nonHdrSizeW (ArrayWordsRep words) = words nonHdrSizeW (StackRep bs) = length bs nonHdrSizeW (RTSRep _ rep) = nonHdrSizeW rep -- | The total size of the closure, in words. heapClosureSizeW :: DynFlags -> SMRep -> WordOff heapClosureSizeW dflags (HeapRep _ p np ty) = closureTypeHdrSize dflags ty + p + np heapClosureSizeW dflags (ArrayPtrsRep elems ct) = arrPtrsHdrSizeW dflags + elems + ct heapClosureSizeW dflags (SmallArrayPtrsRep elems) = smallArrPtrsHdrSizeW dflags + elems heapClosureSizeW dflags (ArrayWordsRep words) = arrWordsHdrSizeW dflags + words heapClosureSizeW _ _ = panic "SMRep.heapClosureSize" closureTypeHdrSize :: DynFlags -> ClosureTypeInfo -> WordOff closureTypeHdrSize dflags ty = case ty of Thunk -> thunkHdrSize dflags ThunkSelector{} -> thunkHdrSize dflags BlackHole -> thunkHdrSize dflags IndStatic -> thunkHdrSize dflags _ -> fixedHdrSizeW dflags -- All thunks use thunkHdrSize, even if they are non-updatable. -- this is because we don't have separate closure types for -- updatable vs. non-updatable thunks, so the GC can't tell the -- difference. If we ever have significant numbers of non- -- updatable thunks, it might be worth fixing this. -- --------------------------------------------------------------------------- -- Arrays -- | The byte offset into the card table of the card for a given element card :: DynFlags -> Int -> Int card dflags i = i `shiftR` mUT_ARR_PTRS_CARD_BITS dflags -- | Convert a number of elements to a number of cards, rounding up cardRoundUp :: DynFlags -> Int -> Int cardRoundUp dflags i = card dflags (i + ((1 `shiftL` mUT_ARR_PTRS_CARD_BITS dflags) - 1)) -- | The size of a card table, in bytes cardTableSizeB :: DynFlags -> Int -> ByteOff cardTableSizeB dflags elems = cardRoundUp dflags elems -- | The size of a card table, in words cardTableSizeW :: DynFlags -> Int -> WordOff cardTableSizeW dflags elems = bytesToWordsRoundUp dflags (cardTableSizeB dflags elems) ----------------------------------------------------------------------------- -- deriving the RTS closure type from an SMRep #include "../includes/rts/storage/ClosureTypes.h" #include "../includes/rts/storage/FunTypes.h" -- Defines CONSTR, CONSTR_1_0 etc -- | Derives the RTS closure type from an 'SMRep' rtsClosureType :: SMRep -> Int rtsClosureType rep = case rep of RTSRep ty _ -> ty -- See Note [static constructors] HeapRep _ 1 0 Constr{} -> CONSTR_1_0 HeapRep _ 0 1 Constr{} -> CONSTR_0_1 HeapRep _ 2 0 Constr{} -> CONSTR_2_0 HeapRep _ 1 1 Constr{} -> CONSTR_1_1 HeapRep _ 0 2 Constr{} -> CONSTR_0_2 HeapRep _ 0 _ Constr{} -> CONSTR_NOCAF -- See Note [Static NoCaf constructors] HeapRep _ _ _ Constr{} -> CONSTR HeapRep False 1 0 Fun{} -> FUN_1_0 HeapRep False 0 1 Fun{} -> FUN_0_1 HeapRep False 2 0 Fun{} -> FUN_2_0 HeapRep False 1 1 Fun{} -> FUN_1_1 HeapRep False 0 2 Fun{} -> FUN_0_2 HeapRep False _ _ Fun{} -> FUN HeapRep False 1 0 Thunk -> THUNK_1_0 HeapRep False 0 1 Thunk -> THUNK_0_1 HeapRep False 2 0 Thunk -> THUNK_2_0 HeapRep False 1 1 Thunk -> THUNK_1_1 HeapRep False 0 2 Thunk -> THUNK_0_2 HeapRep False _ _ Thunk -> THUNK HeapRep False _ _ ThunkSelector{} -> THUNK_SELECTOR HeapRep True _ _ Fun{} -> FUN_STATIC HeapRep True _ _ Thunk -> THUNK_STATIC HeapRep False _ _ BlackHole -> BLACKHOLE HeapRep False _ _ IndStatic -> IND_STATIC _ -> panic "rtsClosureType" -- We export these ones rET_SMALL, rET_BIG, aRG_GEN, aRG_GEN_BIG :: Int rET_SMALL = RET_SMALL rET_BIG = RET_BIG aRG_GEN = ARG_GEN aRG_GEN_BIG = ARG_GEN_BIG {- Note [static constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to have a CONSTR_STATIC closure type, and each constructor had two info tables: one with CONSTR (or CONSTR_1_0 etc.), and one with CONSTR_STATIC. This distinction was removed, because when copying a data structure into a compact region, we must copy static constructors into the compact region too. If we didn't do this, we would need to track the references from the compact region out to the static constructors, because they might (indirectly) refer to CAFs. Since static constructors will be copied to the heap, if we wanted to use different info tables for static and dynamic constructors, we would have to switch the info pointer when copying the constructor into the compact region, which means we would need an extra field of the static info table to point to the dynamic one. However, since the distinction between static and dynamic closure types is never actually needed (other than for assertions), we can just drop the distinction and use the same info table for both. The GC *does* need to distinguish between static and dynamic closures, but it does this using the HEAP_ALLOCED() macro which checks whether the address of the closure resides within the dynamic heap. HEAP_ALLOCED() doesn't read the closure's info table. Note [Static NoCaf constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we know that a top-level binding 'x' is not Caffy (ie no CAFs are reachable from 'x'), then a statically allocated constructor (Just x) is also not Caffy, and the garbage collector need not follow its argument fields. Exploiting this would require two static info tables for Just, for the two cases where the argument was Caffy or non-Caffy. Currently we don't do this; instead we treat nullary constructors as non-Caffy, and the others as potentially Caffy. ************************************************************************ * * Pretty printing of SMRep and friends * * ************************************************************************ -} instance Outputable ClosureTypeInfo where ppr = pprTypeInfo instance Outputable SMRep where ppr (HeapRep static ps nps tyinfo) = hang (header <+> lbrace) 2 (ppr tyinfo <+> rbrace) where header = text "HeapRep" <+> if static then text "static" else empty <+> pp_n "ptrs" ps <+> pp_n "nonptrs" nps pp_n :: String -> Int -> SDoc pp_n _ 0 = empty pp_n s n = int n <+> text s ppr (ArrayPtrsRep size _) = text "ArrayPtrsRep" <+> ppr size ppr (SmallArrayPtrsRep size) = text "SmallArrayPtrsRep" <+> ppr size ppr (ArrayWordsRep words) = text "ArrayWordsRep" <+> ppr words ppr (StackRep bs) = text "StackRep" <+> ppr bs ppr (RTSRep ty rep) = text "tag:" <> ppr ty <+> ppr rep instance Outputable ArgDescr where ppr (ArgSpec n) = text "ArgSpec" <+> ppr n ppr (ArgGen ls) = text "ArgGen" <+> ppr ls pprTypeInfo :: ClosureTypeInfo -> SDoc pprTypeInfo (Constr tag descr) = text "Con" <+> braces (sep [ text "tag:" <+> ppr tag , text "descr:" <> text (show descr) ]) pprTypeInfo (Fun arity args) = text "Fun" <+> braces (sep [ text "arity:" <+> ppr arity , ptext (sLit ("fun_type:")) <+> ppr args ]) pprTypeInfo (ThunkSelector offset) = text "ThunkSel" <+> ppr offset pprTypeInfo Thunk = text "Thunk" pprTypeInfo BlackHole = text "BlackHole" pprTypeInfo IndStatic = text "IndStatic"
sdiehl/ghc
compiler/GHC/Runtime/Layout.hs
bsd-3-clause
20,181
0
14
4,791
3,705
1,944
1,761
316
26
------------------------------------------------------------------------------ -- | -- Module : Data.Datamining.Clustering.Gsom.Input -- Copyright : (c) 2009 Stephan Günther -- License : BSD3 -- -- Maintainer : gnn.github@gmail.com -- Stability : experimental -- Portability : portable -- -- The GSOM algorithm works on numerical input vectors. These input vectors -- are internally represented as lists of @'Double'@s and this module contains -- the functions working on these. ------------------------------------------------------------------------------ module Data.Datamining.Clustering.Gsom.Input( Bounds, Input, Inputs , bounds, dimension, normalize, unnormalize , distance, (*.), (.*), (<+>), (<->) ) where ------------------------------------------------------------------------------ -- Standard modules ------------------------------------------------------------------------------ import Data.List ------------------------------------------------------------------------------ -- Utility functions on lists of inputvectors ------------------------------------------------------------------------------ -- | Input vectors are represented as lists of Doubles. type Input = [Double] type Inputs = [Input] -- | The bounds of a list of inputs. Having the tuple @(a,b)@ at index @i@ -- in @bounds@ means that the value at index @i@ of each of the input vectors -- from the inputs which where used to calculate @bounds@ is from the -- intervall @[a,b]@. type Bounds = [(Double, Double)] -- | Normalizes input vectors. -- @'normalize' inputs@ takes the given list of input vectors @inputs@ and -- returns a list of input vectors where each component is in @[0,1]@. -- If you want to unnormalize the input vectors use @'bounds'@ and -- @'unnormalize'@. normalize :: Bounds -> Inputs -> Inputs normalize bs is = map (normalizeVector bs) is where normalizeVector bs = map normalizeValue . zip bs normalizeValue ((a,b),v) = if a == b then 0 else (v - a)/(b - a) -- | Calculates the bounds of the input vector components. bounds :: Inputs -> Bounds bounds [] = [] bounds (i:is) = foldl' f (dz i) is where dz x = zip x x f ps [] = ps f [] xs = dz xs f ((a,b):ps) (x:xs) = let a' = min a x; b' = max b x; t = f ps xs in a' `seq` b' `seq` t `seq` (a',b') : t -- | Unnormalizes the given input vectors @inputs@ assuming that it's bounds -- previously where @bounds@. unnormalize :: Bounds -> Inputs -> Inputs unnormalize bounds inputs = map (map f . zip bounds) inputs where f ((min',max'), n) = if min' == max' then min' else n*(max' - min')+min' -- | Calculating the dimension of a given set of inputs just means finding -- the length of the longest input vector. dimension :: Inputs -> Int dimension = maximum . map length ------------------------------------------------------------------------------ -- Utility functions working on single inputvectors ------------------------------------------------------------------------------ -- | @'distance' i1 i2@ calculates the euclidean distance between -- @i1@ and @i2@. If @i1@ and @i2@ have different lengths, excess -- values are ignored. distance :: Input -> Input -> Double distance i1 i2 = sqrt . sum . map (\x -> x*x) $! (i1 <-> i2) -- | Multiplication of an input vector with a scalar. infixr 7 .* (.*) :: Double -> Input -> Input (.*) d = (force . map ((d*) $!) $!) infixl 7 *. (*.) :: Input -> Double -> Input (*.) = flip (.*) -- | Subtraction and addition of vectors between each other. infixl 6 <->, <+> (<+>) :: Input -> Input -> Input (<+>) i1 i2 = let front = zipWith (+) i1 i2 l1 = length i1 l2 = length i2 in case signum $ l1 - l2 of 0 -> front -1 -> front ++ drop l1 i2 1 -> front ++ drop l2 i1 (<->) :: Input -> Input -> Input (<->) i1 i2 = i1 <+> (-1) .* i2 ------------------------------------------------------------------------------ -- Processing functions. Not exported. ------------------------------------------------------------------------------ -- | Zips two lists, but instead of truncating the longer one to the length -- of the shortert one the shorter one is padded with elements from the -- suffix of the longer one which is exceeding the length of the shorter one. padZip :: [a] -> [a] -> [(a, a)] padZip xs ys = let (lx, ly) = (length xs, length ys) in uncurry zip $ case compare lx ly of EQ -> (xs,ys) GT -> (xs, ys ++ drop ly xs) LT -> (xs ++ drop lx ys, ys) -- | Forces a whole list. If it wasn't for this function, @'bounds'@ -- would blow the stack because only the @'head'@ of the bounds would be fully -- evaluated while the @'tail'@ would consist of huge thunks of @'min'@ and -- @'max'@ applcations. force :: [a] -> [a] force [] = [] force (x:xs) = let tail = force xs in x `seq` tail `seq` x:tail
gnn/hsgsom
Data/Datamining/Clustering/Gsom/input.hs
bsd-3-clause
4,787
0
13
854
1,057
609
448
53
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} import Control.Applicative import Control.Arrow (first) import Control.Monad (mzero) import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import qualified Data.ByteString.Char8 as BC import Data.Char (isSpace) import Data.Function (on) import Data.List import qualified Data.Map as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.Ratio import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Vector as V import Numeric import System.Environment import System.FilePath import Data.Csv import Web.Zennit import Debug.Trace data Item = Item { pUser :: T.Text , pType :: ItemType , pLink :: T.Text , pScore :: Int } deriving (Show, Eq, Ord) data ItemType = Comment | Submission deriving (Show, Eq, Ord) instance FromField ItemType where parseField s | s == "comment" = pure Comment | s == "submission" = pure Submission | otherwise = mzero instance FromRecord Item where parseRecord v | V.length v == 4 = Item <$> v .!! 0 -- user <*> v .!! 1 -- type <*> v .!! 2 -- link <*> v .!! 3 -- score | otherwise = mzero where v .!! idx = parseField (BC.dropWhile isSpace (v V.! idx)) -- --------------------------------------------------------------------- -- -- --------------------------------------------------------------------- isComment p = pType p == Comment isSubmission p = pType p == Submission byPost :: [Item] -> [(Maybe Item, [Item])] byPost items = map (first getSubmission) $ buckets post items where (comments, submissions) = partition isComment items smap = Map.fromList [ (pLink s, s) | s <- submissions ] post = T.pack . takeDirectory . T.unpack . pLink getSubmission k = Map.lookup (k <> "/") smap -- may not be known about :: V.Vector Item -> T.Text about res = T.unlines $ [ "Comments" , "--------" , commentHistogram pUser comments , "" , "Posts" , "-----" , "Number of posts: " <> tshow totalPosts , "…where ewk comments: " <> outOf numCommentedEwk totalPosts , "…by ewk: " <> outOf numByEwk totalPosts ] where tshow = T.pack . show outOf l t = tshow l <> " " <> showPercent (fromIntegral l % fromIntegral t) comments = V.filter isComment res posts = byPost (V.toList res) byEwk i = pUser i == "ewk" hasEwk = any byEwk . snd totalPosts = length posts numCommentedEwk = length $ filter (any byEwk . snd) posts numByEwk = length $ filter (maybe False byEwk . fst) posts commentHistogram f v = T.unlines $ showPercentages (percentages total core) : map (broadbrush total) rest where broadbrush t (n,h) = T.intercalate "\t" [ k, T.pack (show v), showPercent pcent ] where pcent = fromIntegral v % fromIntegral t k = "… at least " <> T.pack (show n) <> " comments" v = sum (Map.elems h) hgram = histogram . V.toList $ V.map f v (core, rest) = case walk [100, 50, 10, 2] hgram of [] -> error "No comments?!" (x:xs) -> (snd x, xs) total = V.length v -- gah, I recognise this is some kind of fold, but brain not working walk [] m = [(0,m)] walk (b:bs) m = (b, wanted) : walk bs rest where (wanted, rest) = Map.partition (> b) m -- --------------------------------------------------------------------- -- -- --------------------------------------------------------------------- main = do [f] <- getArgs mp <- decode HasHeader <$> BL.readFile f case mp of Left err -> fail err Right res -> T.putStrLn $ about res
kowey/zennit
userstats.hs
bsd-3-clause
4,155
0
14
1,318
1,238
661
577
101
3
module Staller where import Control.Arrow.Flow import Control.Monad produce1 :: Monad m => Flow m a Int produce1 = stall $ Flow $ \_ -> return (finished 1, produce1) incr :: Monad m => Flow m Int Int incr = stall $ Flow $ \i -> return (finished (i + 1),incr) simulate :: (Show s) => Flow IO () s -> IO () simulate flow = do (res, new) <- deFlow flow () putStrLn $ "Result: " ++ (show res) putStrLn "<Enter> to continue" getLine simulate new main = simulate (produce1 </> incr)
igraves/flow-arrow
examples/Staller.hs
bsd-3-clause
596
0
11
211
227
115
112
15
1
{-# LANGUAGE NegativeLiterals #-} {-# LANGUAGE ScopedTypeVariables #-} module TextRow where import Control.Applicative import Data.Time.Calendar (fromGregorian) import Data.Time.LocalTime (LocalTime (..), TimeOfDay (..)) import Database.MySQL.Base import qualified System.IO.Streams as Stream import Test.Tasty.HUnit import qualified Data.Vector as V tests :: MySQLConn -> Assertion tests c = do (f, is) <- query_ c "SELECT * FROM test" assertEqual "decode Field types" (columnType <$> f) [ mySQLTypeLong , mySQLTypeBit , mySQLTypeTiny , mySQLTypeTiny , mySQLTypeShort , mySQLTypeShort , mySQLTypeInt24 , mySQLTypeInt24 , mySQLTypeLong , mySQLTypeLong , mySQLTypeLongLong , mySQLTypeLongLong , mySQLTypeNewDecimal , mySQLTypeFloat , mySQLTypeDouble , mySQLTypeDate , mySQLTypeDateTime , mySQLTypeTimestamp , mySQLTypeTime , mySQLTypeYear , mySQLTypeString , mySQLTypeVarString , mySQLTypeString , mySQLTypeVarString , mySQLTypeBlob , mySQLTypeBlob , mySQLTypeBlob , mySQLTypeBlob , mySQLTypeString , mySQLTypeString ] Just v <- Stream.read is assertEqual "decode NULL values" v [ MySQLInt32 0 , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull , MySQLNull ] Stream.skipToEof is let bitV = 57514 -- 0b1110000010101010 execute_ c "UPDATE test SET \ \__bit = b'1110000010101010' ,\ \__tinyInt = -128 ,\ \__tinyIntU = 255 ,\ \__smallInt = -32768 ,\ \__smallIntU = 65535 ,\ \__mediumInt = -8388608 ,\ \__mediumIntU = 16777215 ,\ \__int = -2147483648 ,\ \__intU = 4294967295 ,\ \__bigInt = -9223372036854775808 ,\ \__bigIntU = 18446744073709551615 ,\ \__decimal = 1234567890.0123456789 ,\ \__float = 3.14159 ,\ \__double = 3.1415926535 ,\ \__date = '2016-08-08' ,\ \__datetime = '2016-08-08 17:25:59' ,\ \__timestamp = '2016-08-08 17:25:59' ,\ \__time = '-199:59:59' ,\ \__year = 1999 ,\ \__char = '12345678' ,\ \__varchar = '韩冬真赞' ,\ \__binary = '12345678' ,\ \__varbinary = '12345678' ,\ \__tinyblob = '12345678' ,\ \__tinytext = '韩冬真赞' ,\ \__blob = '12345678' ,\ \__text = '韩冬真赞' ,\ \__enum = 'foo' ,\ \__set = 'foo,bar' WHERE __id=0" (_, is) <- query_ c "SELECT * FROM test" Just v <- Stream.read is assertEqual "decode text protocol" v [ MySQLInt32 0 , MySQLBit bitV , MySQLInt8 (-128) , MySQLInt8U 255 , MySQLInt16 (-32768) , MySQLInt16U 65535 , MySQLInt32 (-8388608) , MySQLInt32U 16777215 , MySQLInt32 (-2147483648) , MySQLInt32U 4294967295 , MySQLInt64 (-9223372036854775808) , MySQLInt64U 18446744073709551615 , MySQLDecimal 1234567890.0123456789 , MySQLFloat 3.14159 , MySQLDouble 3.1415926535 , MySQLDate (fromGregorian 2016 08 08) , MySQLDateTime (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTimeStamp (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTime 1 (TimeOfDay 199 59 59) , MySQLYear 1999 , MySQLText "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLText "foo" , MySQLText "foo,bar" ] Stream.skipToEof is (_, is') <- queryVector_ c "SELECT * FROM test" Just v' <- Stream.read is' Stream.skipToEof is' assertEqual "decode text protocol(queryVector_)" v (V.toList v') execute c "UPDATE test SET \ \__bit = ? ,\ \__tinyInt = ? ,\ \__tinyIntU = ? ,\ \__smallInt = ? ,\ \__smallIntU = ? ,\ \__mediumInt = ? ,\ \__mediumIntU = ? ,\ \__int = ? ,\ \__intU = ? ,\ \__bigInt = ? ,\ \__bigIntU = ? ,\ \__decimal = ? ,\ \__float = ? ,\ \__double = ? ,\ \__date = ? ,\ \__datetime = ? ,\ \__timestamp = ? ,\ \__time = ? ,\ \__year = ? ,\ \__char = ? ,\ \__varchar = ? ,\ \__binary = ? ,\ \__varbinary = ? ,\ \__tinyblob = ? ,\ \__tinytext = ? ,\ \__blob = ? ,\ \__text = ? ,\ \__enum = ? ,\ \__set = ? WHERE __id=0" [ MySQLBit bitV , MySQLInt8 (-128) , MySQLInt8U 255 , MySQLInt16 (-32768) , MySQLInt16U 65535 , MySQLInt32 (-8388608) , MySQLInt32U 16777215 , MySQLInt32 (-2147483648) , MySQLInt32U 4294967295 , MySQLInt64 (-9223372036854775808) , MySQLInt64U 18446744073709551615 , MySQLDecimal 1234567890.0123456789 , MySQLFloat 3.14159 , MySQLDouble 3.1415926535 , MySQLDate (fromGregorian 2016 08 08) , MySQLDateTime (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTimeStamp (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTime 1 (TimeOfDay 199 59 59) , MySQLYear 1999 , MySQLText "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLText "foo" , MySQLText "foo,bar" ] (_, is) <- query_ c "SELECT * FROM test" Just v <- Stream.read is assertEqual "roundtrip text protocol" v [ MySQLInt32 0 , MySQLBit bitV , MySQLInt8 (-128) , MySQLInt8U 255 , MySQLInt16 (-32768) , MySQLInt16U 65535 , MySQLInt32 (-8388608) , MySQLInt32U 16777215 , MySQLInt32 (-2147483648) , MySQLInt32U 4294967295 , MySQLInt64 (-9223372036854775808) , MySQLInt64U 18446744073709551615 , MySQLDecimal 1234567890.0123456789 , MySQLFloat 3.14159 , MySQLDouble 3.1415926535 , MySQLDate (fromGregorian 2016 08 08) , MySQLDateTime (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTimeStamp (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTime 1 (TimeOfDay 199 59 59) , MySQLYear 1999 , MySQLText "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLText "foo" , MySQLText "foo,bar" ] Stream.skipToEof is execute_ c "UPDATE test SET \ \__mediumInt = null ,\ \__double = null ,\ \__text = null WHERE __id=0" (_, is) <- query_ c "SELECT * FROM test" Just v <- Stream.read is assertEqual "decode text protocol with null" v [ MySQLInt32 0 , MySQLBit bitV , MySQLInt8 (-128) , MySQLInt8U 255 , MySQLInt16 (-32768) , MySQLInt16U 65535 , MySQLNull , MySQLInt32U 16777215 , MySQLInt32 (-2147483648) , MySQLInt32U 4294967295 , MySQLInt64 (-9223372036854775808) , MySQLInt64U 18446744073709551615 , MySQLDecimal 1234567890.0123456789 , MySQLFloat 3.14159 , MySQLNull , MySQLDate (fromGregorian 2016 08 08) , MySQLDateTime (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTimeStamp (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLTime 1 (TimeOfDay 199 59 59) , MySQLYear 1999 , MySQLText "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLNull , MySQLText "foo" , MySQLText "foo,bar" ] Stream.skipToEof is execute c "UPDATE test SET \ \__decimal = ? ,\ \__date = ? ,\ \__timestamp = ? WHERE __id=0" [MySQLNull, MySQLNull, MySQLNull] (_, is) <- query_ c "SELECT * FROM test" Just v <- Stream.read is assertEqual "roundtrip text protocol with null" v [ MySQLInt32 0 , MySQLBit bitV , MySQLInt8 (-128) , MySQLInt8U 255 , MySQLInt16 (-32768) , MySQLInt16U 65535 , MySQLNull , MySQLInt32U 16777215 , MySQLInt32 (-2147483648) , MySQLInt32U 4294967295 , MySQLInt64 (-9223372036854775808) , MySQLInt64U 18446744073709551615 , MySQLNull , MySQLFloat 3.14159 , MySQLNull , MySQLNull , MySQLDateTime (LocalTime (fromGregorian 2016 08 08) (TimeOfDay 17 25 59)) , MySQLNull , MySQLTime 1 (TimeOfDay 199 59 59) , MySQLYear 1999 , MySQLText "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLBytes "12345678" , MySQLText "韩冬真赞" , MySQLBytes "12345678" , MySQLNull , MySQLText "foo" , MySQLText "foo,bar" ] Stream.skipToEof is execute_ c "UPDATE test SET \ \__time = '199:59:59' ,\ \__year = 0 WHERE __id=0" (_, is) <- query_ c "SELECT __time, __year FROM test" Just v <- Stream.read is assertEqual "decode text protocol 2" v [ MySQLTime 0 (TimeOfDay 199 59 59) , MySQLYear 0 ] Stream.skipToEof is execute_ c "UPDATE test SET \ \__text = '' ,\ \__blob = '' WHERE __id=0" (_, is) <- query_ c "SELECT __text, __blob FROM test" Just v <- Stream.read is assertEqual "decode text protocol 3" v [ MySQLText "" , MySQLBytes "" ] Stream.skipToEof is execute c "UPDATE test SET \ \__time = ? ,\ \__year = ? WHERE __id=0" [ MySQLTime 0 (TimeOfDay 199 59 59), MySQLYear 0] (_, is) <- query_ c "SELECT __time, __year FROM test" Just v <- Stream.read is assertEqual "roundtrip text protocol 2" v [ MySQLTime 0 (TimeOfDay 199 59 59) , MySQLYear 0 ] Stream.skipToEof is
winterland1989/mysql-haskell
test/TextRow.hs
bsd-3-clause
13,111
0
13
5,759
2,256
1,151
1,105
274
1
module Codegen.Utils where import Data.Word import LLVM.General.AST import qualified LLVM.General.AST.Constant as C import qualified LLVM.General.AST.CallingConvention as CC import LLVM.General.AST.Type import LLVM.General.AST.IntegerPredicate type Instructions = [Named Instruction] defBits :: Word32 defBits = 64 int :: Type int = IntegerType defBits intv :: Integer -> C.Constant intv = C.Int defBits intv8 :: Integer -> C.Constant intv8 = C.Int 8 istr' :: Integer -> C.Constant istr' = C.Int 32 istr :: Integer -> Operand istr = constant . istr' getElementPtr :: Instruction getElementPtr = GetElementPtr { inBounds = True , address = error "No address specified" , indices = [] , metadata = [] } getElementPtr' :: Operand -> [Operand] -> Instruction getElementPtr' from inds = getElementPtr { address = from, indices = istr 0 : inds } getElementPtrUnsafe' :: Operand -> [Operand] -> Instruction getElementPtrUnsafe' from inds = (getElementPtr' from inds) { inBounds = False } load :: Instruction load = Load { volatile = False , address = error "No address specified" , maybeAtomicity = Nothing , alignment = 0 , metadata = [] } load' :: Operand -> Instruction load' a = load { address = a } store :: Instruction store = Store { volatile = False , address = error "No address specified" , value = error "No value specified" , maybeAtomicity = Nothing , alignment = 0 , metadata = [] } store' :: Operand -> Operand -> Instruction store' to from = store { address = to, value = from } call :: Instruction call = Call { isTailCall = False , callingConvention = CC.C , returnAttributes = [] , function = error "No function specified" , arguments = [] , functionAttributes = [] , metadata = [] } call' :: Operand -> [Operand] -> Instruction call' fun args = call { function = Right fun , arguments = map (, []) args } add :: Instruction add = Add { nsw = False , nuw = False , operand0 = error "No first operand supplied" , operand1 = error "No second operand supplied" , metadata = [] } add' :: Operand -> Operand -> Instruction add' a b = add { operand0 = a, operand1 = b } sub :: Instruction sub = Sub { nsw = False , nuw = False , operand0 = error "No first operand supplied" , operand1 = error "No second operand supplied" , metadata = [] } sub' :: Operand -> Operand -> Instruction sub' a b = add { operand0 = a, operand1 = b } mul :: Instruction mul = Mul { nsw = False , nuw = False , operand0 = error "No first operand supplied" , operand1 = error "No second operand supplied" , metadata = [] } mul' :: Operand -> Operand -> Instruction mul' a b = mul { operand0 = a, operand1 = b } icmp :: Instruction icmp = ICmp { iPredicate = error "No predicate specified" , operand0 = error "No first operand supplied" , operand1 = error "No second operand supplied" , metadata = [] } icmp' :: IntegerPredicate -> Operand -> Operand -> Instruction icmp' pr a b = icmp { iPredicate = pr , operand0 = a , operand1 = b } bitcast :: Instruction bitcast = BitCast { operand0 = error "No operand specified" , type' = error "No type specified" , metadata = [] } bitcast' :: Operand -> Type -> Instruction bitcast' op typ = bitcast { operand0 = op , type' = typ } select :: Instruction select = Select { condition' = error "No condition specified" , trueValue = error "No first operand supplied" , falseValue = error "No second operand supplied" , metadata = [] } select' :: Operand -> Operand -> Operand -> Instruction select' cond a b = select { condition' = cond , trueValue = a , falseValue = b } assign :: Type -> Name -> Instruction assign typ from = bitcast' (local typ from) typ local :: Type -> Name -> Operand local = LocalReference constant :: C.Constant -> Operand constant = ConstantOperand retBlock :: Name -> Instructions -> BasicBlock retBlock name cmds = BasicBlock name cmds (Do $ Ret Nothing []) brBlock :: Name -> Instructions -> Name -> BasicBlock brBlock name cmds to = BasicBlock name cmds (Do $ Br to []) sizeof :: Type -> [C.Constant] -> C.Constant sizeof typ inds = C.PtrToInt szp int where szp = C.GetElementPtr { C.inBounds = False , C.address = C.Null $ ptr typ , C.indices = istr' 0 : inds } sizeof' :: Type -> Integer -> C.Constant sizeof' typ n = C.PtrToInt szp int where szp = C.GetElementPtr { C.inBounds = False , C.address = C.Null $ ptr typ , C.indices = [istr' n] } globalRef :: Type -> Name -> Operand globalRef typ nam = ConstantOperand $ C.GlobalReference typ nam voidptr :: Type voidptr = ptr i8
abbradar/dnohs
src/Codegen/Utils.hs
bsd-3-clause
5,548
0
10
1,933
1,494
849
645
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Layout ( prop_layout ) where import Prelude hiding (map) import Data.List (intersperse) import Data.MonadicStream hiding (concatMap) import Control.Applicative import Test.QuickCheck import Text.Position import Text.Lexeme import qualified Data.Set as S import Language.Forvie.Layout -- This module defines QuickCheck2 property that states that, for a -- given s-expression, a mixed layout/non-layout regime gives the same -- answer as strictly inserted non-layout delimiters. -- This test is not a complete specification of layout... -- FIXME: also remember to generate some examples with {;} already in -------------------------------------------------------------------------------- data Structure = Block Bool [Structure] -- | Atom deriving Show instance Arbitrary Structure where arbitrary = sized structure where structure 0 = pure Atom structure n = oneof [ pure Atom , Block <$> arbitrary <*> structures n ] structures 0 = pure [] structures n = oneof [ pure [] , (:) <$> structure (n `div` 2) <*> structures (n `div` 2) ] data SToken = TokBlock | TokAtom | TokLBrace | TokRBrace | TokSemicolon deriving (Eq, Show, Ord) instance Layout SToken where semicolon = TokSemicolon lbrace = TokLBrace rbrace = TokRBrace blockOpener = S.fromList [TokBlock] -------------------------------------------------------------------------------- -- makes a dummy lexeme with the given indentation and token -- FIXME: do the indentation and line counts correctly mkLexeme :: Int -> a -> Lexeme a mkLexeme indent a = Lexeme a (Span (Position "<test input>" 0 0 indent) (Position "<test input>" 0 0 indent)) "" -------------------------------------------------------------------------------- -- Takes a structure and renders it as a stream of tokens, with the -- indentation levels and newlines inserted to simulate a user using -- layout to denote block structure. renderWithLayout :: Int -- indentation level -> Structure -> [Lexeme (NewlineOr SToken)] renderWithLayout indent (Block True elements) = [ mkLexeme indent (Token TokBlock) , mkLexeme indent Newline ] ++ renderListWithLayout (indent+1) elements renderWithLayout indent (Block False elements) = [ mkLexeme indent (Token TokBlock) , mkLexeme indent (Token TokLBrace) ] ++ Prelude.concat (intersperse [mkLexeme indent (Token TokSemicolon)] $ fmap (renderWithLayout indent) elements) ++ [ mkLexeme indent (Token TokRBrace) , mkLexeme indent Newline ] renderWithLayout indent Atom = [ mkLexeme indent (Token TokAtom) , mkLexeme indent Newline ] renderListWithLayout :: Int -> [Structure] -> [Lexeme (NewlineOr SToken)] renderListWithLayout indent = concatMap (renderWithLayout indent) -------------------------------------------------------------------------------- -- FIXME: get render without layout to return Maybe, and return -- Nothing when the layout usage annotations are invalid (not allowed -- to have empty layout blocks inside delimited blocks) renderWithoutLayout :: Structure -> [SToken] renderWithoutLayout (Block _ elements) = TokBlock : renderListWithoutLayout elements renderWithoutLayout Atom = [TokAtom] renderListWithoutLayout :: [Structure] -> [SToken] renderListWithoutLayout elements = TokLBrace : Prelude.concat (intersperse [TokSemicolon] $ fmap renderWithoutLayout elements) ++ [TokRBrace] -------------------------------------------------------------------------------- -- should this parse? -- block { block } -- block { block -- atom; atom } -- What does this mean? -- block { block -- ; atom -- } -- GHC seems to treat the "; atom" as part of the inner block. And the -- final '}' closes all blocks. This is what the current -- implementation in forvie does. I think that renderWithLayout needs -- to generate the right thing in this case. -- block -- block -- atom -- what is the actual specification of layout? -- - exactly what are the rules for empty blocks? -- - what are the rules for mixing user-delimited blocks and layout blocks? -- - exactly what information does the insertion of layout information rely on? -- block -- block -- atom -- block { atom; block { atom; atom }; block } -------------------------------------------------------------------------------- -- checkStructure ensures that empty layout blocks inside -- user-delimited blocks never have anything after them. This is not -- representable using mixed layout/non-layout checkStructure :: Structure -> Bool checkStructure (Block False l) = checkList l where checkList [] = True checkList (Block True []:_:l) = False checkList (x:l) = checkStructure x && checkList l checkStructure (Block True l) = all checkStructure l checkStructure (Atom) = True -------------------------------------------------------------------------------- structureLayout :: [Structure] -> Maybe [SToken] structureLayout s = ofList l |>> layout (OnLayoutError $ const Nothing) |>> map lexemeTok |>| toList where l = renderListWithLayout 0 s -------------------------------------------------------------------------------- prop_layout :: [Structure] -> Property prop_layout s = all checkStructure s ==> case structureLayout s of Nothing -> False Just l' -> renderListWithoutLayout s == l'
bobatkey/Forvie
tests/Layout.hs
bsd-3-clause
5,694
0
14
1,242
1,034
561
473
91
3
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies #-} module Examples.KeyMove where import Graphics.UI.Toy.Prelude data State = State { pos, vel :: R2 } type instance V State = R2 instance Interactive Gtk State where tick input state = return (State pos' vel', True) where pos' = pos state + vel' vel' = vel state * 0.9 + acc handleKey key v = r2 $ if keyHeld key input then v else (0, 0) acc = handleKey "w" ( 0, -1) + handleKey "a" (-1, 0) + handleKey "s" ( 0, 1) + handleKey "d" ( 1, 0) instance Diagrammable Cairo R2 State where diagram state = translate (pos state) $ circle 20 # lc black # lw 2 instance GtkDisplay State where display = displayDiagram diagram main = runToy $ State (100 & 100) (0 & 0)
mgsloan/toy-gtk-diagrams
Examples/KeyMove.hs
bsd-3-clause
776
0
13
203
297
158
139
20
1
-- | -- Module : Game.Terrain.Rendering -- Description : Responsible for generating meshes from terrain -- Copyright : (c) 2016 Caitlin Wilks -- License : BSD3 -- Maintainer : Caitlin Wilks <mitasuki@gmail.com> -- -- module Game.Terrain.Rendering where import Game.Terrain.Data import LambdaCube.GL import LambdaCube.GL.Mesh import Data.Foldable import Debug.Trace import qualified Data.Map as Map import qualified Data.Vector as V import qualified Data.Vector.Unboxed as VU -- Tuple accessors t3_1 (a, _, _) = a -- ^ Access the first element of a 3-tuple t3_2 (_, b, _) = b -- ^ Access the second element of a 3-tuple t3_3 (_, _, c) = c -- ^ Access the third element of a 3-tuple -- | Generates a mesh from a terrain chunk genChunkMesh :: IChunk -> Mesh genChunkMesh chunk@(IChunk dimensions@(dx, dy, dz) blocks) = let -- Generate a big list of indices for each block in the chunk -- Not!! the 3d rendering kind of indices indices = [(x,y,z) | x <- [0..dx-1], y <- [0..dy-1], z <- [0..dz-1]] -- Fold over block indices and generate faces for each block blockMeshes = map (genBlockMesh chunk) indices -- Get vertices and concatenate them into a single vector vertices = V.concat . map t3_1 $ blockMeshes -- Get uvs and concatenate them into a single vector uvs = V.concat . map t3_2 $ blockMeshes -- Get normals and concatenate them into a single vector normals = V.concat . map t3_3 $ blockMeshes in Mesh { mAttributes = Map.fromList [ ( "position", A_V3F vertices ) , ( "uv", A_V2F uvs ) , ( "normal", A_V3F normals ) ] , mPrimitive = P_Triangles } -- | Generates faces for a single block in a chunk genBlockMesh :: IChunk -> (Int, Int, Int) -> ( V.Vector (V3 Float) , V.Vector (V2 Float) , V.Vector (V3 Float) ) genBlockMesh chunk@(IChunk dimensions blocks) idx = let vectorIndex = posToIdx dimensions idx block = VU.unsafeIndex blocks vectorIndex genFace = genBlockFace chunk idx faces = map genFace cardinalDirections in if block then (V.concat . map t3_1 $ faces, V.concat . map t3_2 $ faces, V.concat . map t3_3 $ faces) else (V.empty, V.empty, V.empty) -- | Generates a face for a block, if applicable genBlockFace :: IChunk -> (Int, Int, Int) -> (Int, Int, Int) -> ( V.Vector (V3 Float) , V.Vector (V2 Float) , V.Vector (V3 Float) ) genBlockFace (IChunk dimensions@(dx, dy, dz) blocks) pos@(x, y, z) dir@(dirx, diry, dirz) = let min = -0.5 max = 0.5 defaultFace = [ V2 min min, V2 max min, V2 min max , V2 min max, V2 max min, V2 max max ] posF = fromIntegral <$> V3 x y z -- A constant 0.5 offset is added or the centre of -- block (0,0,0) would be at the origin addOffset (V3 a b c) (V3 d e f) = V3 (a+d+0.5) (b+e+0.5) (c+f+0.5) -- The block adjacent to the current one (in dir) -- If it's air, then we should generate a face so there's no holes -- in the mesh adjBlockPos = (x+dirx, y+diry, z+dirz) adjBlockIdx = posToIdx dimensions adjBlockPos adjBlock = if inRange dimensions adjBlockPos then VU.unsafeIndex blocks adjBlockIdx else False transformVertex = addOffset posF . cubeVertex dir normal = fromIntegral <$> V3 dirx diry dirz in if not adjBlock then let vertices = V.fromList (map transformVertex defaultFace) uvs = V.fromList $ cubeFaceUvs dir normals = V.fromList $ replicate 6 normal in (vertices, uvs, normals) else (V.empty, V.empty, V.empty) -- | Converts a 2d vertex on the face of a cube to a 3d vertex -- based on the direciton of the face from the centre of the cube cubeVertex :: (Int, Int, Int) -> V2 Float -> V3 Float cubeVertex dir (V2 x y) = case dir of ( 1, 0, 0) -> V3 0.5 y (-x) (-1, 0, 0) -> V3 (-0.5) y x ( 0, 1, 0) -> V3 (-x) 0.5 y ( 0, -1, 0) -> V3 x (-0.5) y ( 0, 0, 1) -> V3 x y 0.5 ( 0, 0, -1) -> V3 (-x) y (-0.5) -- | Convert from a cube face (direction from centre) to uvs cubeFaceUvs :: (Int, Int, Int) -> [V2 Float] cubeFaceUvs (_, y, _) = let baseUvs = [ V2 0 1, V2 1 1, V2 0 0 , V2 0 0, V2 1 1, V2 1 0 ] offset = case y of 0 -> (\(V2 a b) -> V2 (a*0.5+0.5) (b*0.5)) _ -> (\(V2 a b) -> V2 (a*0.5) (b*0.5)) in map offset baseUvs -- | The 6 cardinal directions cardinalDirections = [ (1, 0, 0), (-1, 0, 0) , (0, 1, 0), (0, -1, 0) , (0, 0, 1), (0, 0, -1) ] -- | Whether a set of coordinates is in range inRange :: (Int, Int, Int) -> (Int, Int, Int) -> Bool inRange (dx, dy, dz) (x, y, z) = x >= 0 && x < dx && y >= 0 && y < dy && z >= 0 && z < dz -- | Converts a (x,y,z) index to a vector index posToIdx :: (Int, Int, Int) -> (Int, Int, Int) -> Int posToIdx (dx, dy, dz) (x,y,z) = x + dx * (y + dy * z)
Catchouli/tyke
src/Game/Terrain/Rendering.hs
bsd-3-clause
5,678
0
17
2,094
1,738
973
765
92
6
module Network.Waisp.Handler.Slingshot.Network where -- | XXX: Ripped off from 'streaming-commons', give proper credit. -- TODO: This should be in another package and, possible, everything but -- bindPortTCP should be exported through an internal module. import Data.Monoid ((<>)) import Data.Foldable (traverse_) import Data.String (IsString(fromString)) import Network.Socket ( Socket , SocketType(Stream, Datagram) , AddrInfoFlag(AI_PASSIVE, AI_NUMERICSERV, AI_NUMERICHOST) , Family(AF_INET6) , SocketOption(ReuseAddr, NoDelay) , socket , listen , addrProtocol , maxListenQueue , defaultHints , addrFlags , addrSocketType , getAddrInfo , addrFamily , close , setSocketOption , bindSocket , addrAddress ) import Control.Monad.Catch ( catchIOError , bracketOnError ) -- | Attempt to bind a listening @Socket@ on the given host/port. If no host is -- given, will use the first address available. -- 'maxListenQueue' is topically 128 which is too short for -- high performance servers. So, we specify 'max 2048 maxListenQueue' to -- the listen queue. bindPortTCP :: Int -> HostPreference -> IO Socket bindPortTCP p s = do sock <- bindPort Stream p s listen sock $ max 2048 maxListenQueue return sock bindPort :: SocketType -> Int -> HostPreference -> IO Socket bindPort sockettype p s = do let hints = defaultHints { addrFlags = [ AI_PASSIVE , AI_NUMERICSERV , AI_NUMERICHOST ] , addrSocketType = sockettype } host = case s of Host s' -> Just s' _ -> Nothing port = Just . show $ p addrs <- getAddrInfo (Just hints) host port -- Choose an IPv6 socket if exists. This ensures the socket can -- handle both IPv4 and IPv6 if v6only is false. let addrs4 = filter (\x -> addrFamily x /= AF_INET6) addrs addrs6 = filter (\x -> addrFamily x == AF_INET6) addrs addrs' = case s of HostIPv4 -> addrs4 <> addrs6 HostIPv4Only -> addrs4 HostIPv6 -> addrs6 <> addrs4 HostIPv6Only -> addrs6 _ -> addrs tryAddrs (addr1:rest@(_:_)) = catchIOError (theBody addr1) (const $ tryAddrs rest) tryAddrs (addr1:[]) = theBody addr1 tryAddrs _ = error "bindPort: addrs is empty" sockOpts = case sockettype of Datagram -> [(ReuseAddr,1)] _ -> [(NoDelay,1), (ReuseAddr,1)] theBody addr = bracketOnError (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)) close (\sock -> do traverse_ (uncurry $ setSocketOption sock) sockOpts bindSocket sock (addrAddress addr) return sock) tryAddrs addrs' -- | Which host to bind. -- -- Note: The @IsString@ instance recognizes the following special values: -- -- * @*@ means @HostAny@ -- -- * @*4@ means @HostIPv4@ -- -- * @!4@ means @HostIPv4Only@ -- -- * @*6@ means @HostIPv6@ -- -- * @!6@ means @HostIPv6Only@ data HostPreference = HostAny | HostIPv4 | HostIPv4Only | HostIPv6 | HostIPv6Only | Host String deriving (Eq, Ord, Show, Read) instance IsString HostPreference where -- The funny code coming up is to get around some irritating warnings from -- GHC. I should be able to just write: {- fromString "*" = HostAny fromString "*4" = HostIPv4 fromString "!4" = HostIPv4Only fromString "*6" = HostIPv6 fromString "!6" = HostIPv6Only -} fromString s'@('*':s) = case s of [] -> HostAny ['4'] -> HostIPv4 ['6'] -> HostIPv6 _ -> Host s' fromString s'@('!':s) = case s of ['4'] -> HostIPv4Only ['6'] -> HostIPv6Only _ -> Host s' fromString s = Host s
jdnavarro/slingshot
src/Network/Waisp/Handler/Slingshot/Network.hs
bsd-3-clause
4,111
0
18
1,356
844
469
375
89
9
module Pos.Core.Slotting.LocalSlotIndex ( LocalSlotIndex (..) , mkLocalSlotIndex , addLocalSlotIndex , localSlotIndexToEnum , localSlotIndexFromEnum , localSlotIndexSucc , localSlotIndexPred , localSlotIndexMinBound , localSlotIndexMaxBound , localSlotIndexMaxBoundExplicit , localSlotIndices , unsafeMkLocalSlotIndex ) where import Universum import Control.Monad.Except (MonadError (throwError)) import Data.Aeson.TH (defaultOptions, deriveJSON) import Data.Ix (Ix) import Data.SafeCopy (base, deriveSafeCopySimple) import System.Random (Random (..)) import Pos.Binary.Class (Bi (..)) import Pos.Util.Util (leftToPanic) import Pos.Core.Slotting.SlotCount (SlotCount) -- | Index of slot inside a concrete epoch. newtype LocalSlotIndex = UnsafeLocalSlotIndex { getSlotIndex :: Word16 } deriving (Show, Eq, Ord, Ix, Generic, Hashable, Buildable, Typeable, NFData) localSlotIndexToEnum :: SlotCount -> Int -> LocalSlotIndex localSlotIndexToEnum epochSlots i | i >= fromIntegral epochSlots = error "toEnum @LocalSlotIndex: greater than maxBound" | i < 0 = error "toEnum @LocalSlotIndex: less than minBound" | otherwise = UnsafeLocalSlotIndex (fromIntegral i) localSlotIndexFromEnum :: LocalSlotIndex -> Int localSlotIndexFromEnum = fromIntegral . getSlotIndex localSlotIndexSucc :: SlotCount -> LocalSlotIndex -> LocalSlotIndex localSlotIndexSucc epochSlots = localSlotIndexToEnum epochSlots . (+ 1) . localSlotIndexFromEnum localSlotIndexPred :: SlotCount -> LocalSlotIndex -> LocalSlotIndex localSlotIndexPred epochSlots = localSlotIndexToEnum epochSlots . subtract 1 . localSlotIndexFromEnum instance Random LocalSlotIndex where random = error "random @LocalSlotIndex: undefined" randomR (UnsafeLocalSlotIndex lo, UnsafeLocalSlotIndex hi) g = let (r, g') = randomR (lo, hi) g in (UnsafeLocalSlotIndex r, g') instance Bi LocalSlotIndex where encode = encode . getSlotIndex decode = UnsafeLocalSlotIndex <$> decode localSlotIndexMinBound :: LocalSlotIndex localSlotIndexMinBound = UnsafeLocalSlotIndex 0 localSlotIndexMaxBound :: SlotCount -> LocalSlotIndex localSlotIndexMaxBound epochSlots = UnsafeLocalSlotIndex (fromIntegral epochSlots - 1) localSlotIndexMaxBoundExplicit :: SlotCount -> LocalSlotIndex localSlotIndexMaxBoundExplicit es = UnsafeLocalSlotIndex (fromIntegral es - 1) -- | All local slot indices for the given number of slots in epoch, in ascending -- order. localSlotIndices :: SlotCount -> [LocalSlotIndex] localSlotIndices slotsInEpoch = fmap UnsafeLocalSlotIndex [0..upperBound] where upperBound = fromIntegral slotsInEpoch - 1 mkLocalSlotIndex_ :: SlotCount -> Word16 -> Maybe LocalSlotIndex mkLocalSlotIndex_ es idx | idx < fromIntegral es = Just (UnsafeLocalSlotIndex idx) | otherwise = Nothing mkLocalSlotIndex :: MonadError Text m => SlotCount -> Word16 -> m LocalSlotIndex mkLocalSlotIndex es idx = case mkLocalSlotIndex_ es idx of Just it -> pure it Nothing -> throwError $ "local slot is greater than or equal to the number of slots in epoch: " <> show idx -- | Shift slot index by given amount, and return 'Nothing' if it has -- overflowed past 'epochSlots'. addLocalSlotIndex :: SlotCount -> SlotCount -> LocalSlotIndex -> Maybe LocalSlotIndex addLocalSlotIndex epochSlots x (UnsafeLocalSlotIndex i) | s < fromIntegral epochSlots = Just (UnsafeLocalSlotIndex (fromIntegral s)) | otherwise = Nothing where s :: Word64 s = fromIntegral x + fromIntegral i -- | Unsafe constructor of 'LocalSlotIndex'. unsafeMkLocalSlotIndex :: SlotCount -> Word16 -> LocalSlotIndex unsafeMkLocalSlotIndex epochSlots = leftToPanic "unsafeMkLocalSlotIndex failed: " . mkLocalSlotIndex epochSlots -- ----------------------------------------------------------------------------- -- TH derived instances at the end of the file. deriveJSON defaultOptions ''LocalSlotIndex deriveSafeCopySimple 0 'base ''LocalSlotIndex
input-output-hk/pos-haskell-prototype
core/src/Pos/Core/Slotting/LocalSlotIndex.hs
mit
4,181
0
11
815
879
463
416
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Redshift.DescribeOrderableClusterOptions -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of orderable cluster options. Before you create a new -- cluster you can use this operation to find what options are available, -- such as the EC2 Availability Zones (AZ) in the specific AWS region that -- you can specify, and the node types you can request. The node types -- differ by available storage, memory, CPU and price. With the cost -- involved you might want to obtain a list of cluster options in the -- specific region and specify values when creating a cluster. For more -- information about managing clusters, go to -- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html Amazon Redshift Clusters> -- in the /Amazon Redshift Cluster Management Guide/ -- -- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeOrderableClusterOptions.html AWS API Reference> for DescribeOrderableClusterOptions. -- -- This operation returns paginated results. module Network.AWS.Redshift.DescribeOrderableClusterOptions ( -- * Creating a Request describeOrderableClusterOptions , DescribeOrderableClusterOptions -- * Request Lenses , docoMarker , docoMaxRecords , docoClusterVersion , docoNodeType -- * Destructuring the Response , describeOrderableClusterOptionsResponse , DescribeOrderableClusterOptionsResponse -- * Response Lenses , docorsMarker , docorsOrderableClusterOptions , docorsResponseStatus ) where import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Redshift.Types import Network.AWS.Redshift.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'describeOrderableClusterOptions' smart constructor. data DescribeOrderableClusterOptions = DescribeOrderableClusterOptions' { _docoMarker :: !(Maybe Text) , _docoMaxRecords :: !(Maybe Int) , _docoClusterVersion :: !(Maybe Text) , _docoNodeType :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeOrderableClusterOptions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'docoMarker' -- -- * 'docoMaxRecords' -- -- * 'docoClusterVersion' -- -- * 'docoNodeType' describeOrderableClusterOptions :: DescribeOrderableClusterOptions describeOrderableClusterOptions = DescribeOrderableClusterOptions' { _docoMarker = Nothing , _docoMaxRecords = Nothing , _docoClusterVersion = Nothing , _docoNodeType = Nothing } -- | An optional parameter that specifies the starting point to return a set -- of response records. When the results of a -- DescribeOrderableClusterOptions request exceed the value specified in -- 'MaxRecords', AWS returns a value in the 'Marker' field of the response. -- You can retrieve the next set of response records by providing the -- returned marker value in the 'Marker' parameter and retrying the -- request. docoMarker :: Lens' DescribeOrderableClusterOptions (Maybe Text) docoMarker = lens _docoMarker (\ s a -> s{_docoMarker = a}); -- | The maximum number of response records to return in each call. If the -- number of remaining response records exceeds the specified 'MaxRecords' -- value, a value is returned in a 'marker' field of the response. You can -- retrieve the next set of records by retrying the command with the -- returned marker value. -- -- Default: '100' -- -- Constraints: minimum 20, maximum 100. docoMaxRecords :: Lens' DescribeOrderableClusterOptions (Maybe Int) docoMaxRecords = lens _docoMaxRecords (\ s a -> s{_docoMaxRecords = a}); -- | The version filter value. Specify this parameter to show only the -- available offerings matching the specified version. -- -- Default: All versions. -- -- Constraints: Must be one of the version returned from -- DescribeClusterVersions. docoClusterVersion :: Lens' DescribeOrderableClusterOptions (Maybe Text) docoClusterVersion = lens _docoClusterVersion (\ s a -> s{_docoClusterVersion = a}); -- | The node type filter value. Specify this parameter to show only the -- available offerings matching the specified node type. docoNodeType :: Lens' DescribeOrderableClusterOptions (Maybe Text) docoNodeType = lens _docoNodeType (\ s a -> s{_docoNodeType = a}); instance AWSPager DescribeOrderableClusterOptions where page rq rs | stop (rs ^. docorsMarker) = Nothing | stop (rs ^. docorsOrderableClusterOptions) = Nothing | otherwise = Just $ rq & docoMarker .~ rs ^. docorsMarker instance AWSRequest DescribeOrderableClusterOptions where type Rs DescribeOrderableClusterOptions = DescribeOrderableClusterOptionsResponse request = postQuery redshift response = receiveXMLWrapper "DescribeOrderableClusterOptionsResult" (\ s h x -> DescribeOrderableClusterOptionsResponse' <$> (x .@? "Marker") <*> (x .@? "OrderableClusterOptions" .!@ mempty >>= may (parseXMLList "OrderableClusterOption")) <*> (pure (fromEnum s))) instance ToHeaders DescribeOrderableClusterOptions where toHeaders = const mempty instance ToPath DescribeOrderableClusterOptions where toPath = const "/" instance ToQuery DescribeOrderableClusterOptions where toQuery DescribeOrderableClusterOptions'{..} = mconcat ["Action" =: ("DescribeOrderableClusterOptions" :: ByteString), "Version" =: ("2012-12-01" :: ByteString), "Marker" =: _docoMarker, "MaxRecords" =: _docoMaxRecords, "ClusterVersion" =: _docoClusterVersion, "NodeType" =: _docoNodeType] -- | Contains the output from the DescribeOrderableClusterOptions action. -- -- /See:/ 'describeOrderableClusterOptionsResponse' smart constructor. data DescribeOrderableClusterOptionsResponse = DescribeOrderableClusterOptionsResponse' { _docorsMarker :: !(Maybe Text) , _docorsOrderableClusterOptions :: !(Maybe [OrderableClusterOption]) , _docorsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeOrderableClusterOptionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'docorsMarker' -- -- * 'docorsOrderableClusterOptions' -- -- * 'docorsResponseStatus' describeOrderableClusterOptionsResponse :: Int -- ^ 'docorsResponseStatus' -> DescribeOrderableClusterOptionsResponse describeOrderableClusterOptionsResponse pResponseStatus_ = DescribeOrderableClusterOptionsResponse' { _docorsMarker = Nothing , _docorsOrderableClusterOptions = Nothing , _docorsResponseStatus = pResponseStatus_ } -- | A value that indicates the starting point for the next set of response -- records in a subsequent request. If a value is returned in a response, -- you can retrieve the next set of records by providing this returned -- marker value in the 'Marker' parameter and retrying the command. If the -- 'Marker' field is empty, all response records have been retrieved for -- the request. docorsMarker :: Lens' DescribeOrderableClusterOptionsResponse (Maybe Text) docorsMarker = lens _docorsMarker (\ s a -> s{_docorsMarker = a}); -- | An OrderableClusterOption structure containing information about -- orderable options for the Cluster. docorsOrderableClusterOptions :: Lens' DescribeOrderableClusterOptionsResponse [OrderableClusterOption] docorsOrderableClusterOptions = lens _docorsOrderableClusterOptions (\ s a -> s{_docorsOrderableClusterOptions = a}) . _Default . _Coerce; -- | The response status code. docorsResponseStatus :: Lens' DescribeOrderableClusterOptionsResponse Int docorsResponseStatus = lens _docorsResponseStatus (\ s a -> s{_docorsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-redshift/gen/Network/AWS/Redshift/DescribeOrderableClusterOptions.hs
mpl-2.0
8,805
0
15
1,733
1,016
608
408
116
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Db -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This provides a 'ProgramDb' type which holds configured and not-yet -- configured programs. It is the parameter to lots of actions elsewhere in -- Cabal that need to look up and run programs. If we had a Cabal monad, -- the 'ProgramDb' would probably be a reader or state component of it. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program.Db ( -- * The collection of configured programs we can run ProgramDb, emptyProgramDb, defaultProgramDb, restoreProgramDb, -- ** Query and manipulate the program db addKnownProgram, addKnownPrograms, lookupKnownProgram, knownPrograms, userSpecifyPath, userSpecifyPaths, userMaybeSpecifyPath, userSpecifyArgs, userSpecifyArgss, userSpecifiedArgs, lookupProgram, updateProgram, -- ** Query and manipulate the program db configureProgram, configureAllKnownPrograms, reconfigurePrograms, requireProgram, requireProgramVersion, ) where import Distribution.Simple.Program.Types ( Program(..), ProgArg, ConfiguredProgram(..), ProgramLocation(..) ) import Distribution.Simple.Program.Builtin ( builtinPrograms ) import Distribution.Simple.Utils ( die, findProgramLocation ) import Distribution.Version ( Version, VersionRange, isAnyVersion, withinRange ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Data.List ( foldl' ) import Data.Maybe ( catMaybes ) import qualified Data.Map as Map import Control.Monad ( join, foldM ) import System.Directory ( doesFileExist ) -- ------------------------------------------------------------ -- * Programs database -- ------------------------------------------------------------ -- | The configuration is a collection of information about programs. It -- contains information both about configured programs and also about programs -- that we are yet to configure. -- -- The idea is that we start from a collection of unconfigured programs and one -- by one we try to configure them at which point we move them into the -- configured collection. For unconfigured programs we record not just the -- 'Program' but also any user-provided arguments and location for the program. data ProgramDb = ProgramDb { unconfiguredProgs :: UnconfiguredProgs, configuredProgs :: ConfiguredProgs } type UnconfiguredProgram = (Program, Maybe FilePath, [ProgArg]) type UnconfiguredProgs = Map.Map String UnconfiguredProgram type ConfiguredProgs = Map.Map String ConfiguredProgram emptyProgramDb :: ProgramDb emptyProgramDb = ProgramDb Map.empty Map.empty defaultProgramDb :: ProgramDb defaultProgramDb = restoreProgramDb builtinPrograms emptyProgramDb -- internal helpers: updateUnconfiguredProgs :: (UnconfiguredProgs -> UnconfiguredProgs) -> ProgramDb -> ProgramDb updateUnconfiguredProgs update conf = conf { unconfiguredProgs = update (unconfiguredProgs conf) } updateConfiguredProgs :: (ConfiguredProgs -> ConfiguredProgs) -> ProgramDb -> ProgramDb updateConfiguredProgs update conf = conf { configuredProgs = update (configuredProgs conf) } -- Read & Show instances are based on listToFM -- Note that we only serialise the configured part of the database, this is -- because we don't need the unconfigured part after the configure stage, and -- additionally because we cannot read/show 'Program' as it contains functions. instance Show ProgramDb where show = show . Map.toAscList . configuredProgs instance Read ProgramDb where readsPrec p s = [ (emptyProgramDb { configuredProgs = Map.fromList s' }, r) | (s', r) <- readsPrec p s ] -- | The Read\/Show instance does not preserve all the unconfigured 'Programs' -- because 'Program' is not in Read\/Show because it contains functions. So to -- fully restore a deserialised 'ProgramDb' use this function to add -- back all the known 'Program's. -- -- * It does not add the default programs, but you probably want them, use -- 'builtinPrograms' in addition to any extra you might need. -- restoreProgramDb :: [Program] -> ProgramDb -> ProgramDb restoreProgramDb = addKnownPrograms -- ------------------------------- -- Managing unconfigured programs -- | Add a known program that we may configure later -- addKnownProgram :: Program -> ProgramDb -> ProgramDb addKnownProgram prog = updateUnconfiguredProgs $ Map.insertWith combine (programName prog) (prog, Nothing, []) where combine _ (_, path, args) = (prog, path, args) addKnownPrograms :: [Program] -> ProgramDb -> ProgramDb addKnownPrograms progs conf = foldl' (flip addKnownProgram) conf progs lookupKnownProgram :: String -> ProgramDb -> Maybe Program lookupKnownProgram name = fmap (\(p,_,_)->p) . Map.lookup name . unconfiguredProgs knownPrograms :: ProgramDb -> [(Program, Maybe ConfiguredProgram)] knownPrograms conf = [ (p,p') | (p,_,_) <- Map.elems (unconfiguredProgs conf) , let p' = Map.lookup (programName p) (configuredProgs conf) ] -- |User-specify this path. Basically override any path information -- for this program in the configuration. If it's not a known -- program ignore it. -- userSpecifyPath :: String -- ^Program name -> FilePath -- ^user-specified path to the program -> ProgramDb -> ProgramDb userSpecifyPath name path = updateUnconfiguredProgs $ flip Map.update name $ \(prog, _, args) -> Just (prog, Just path, args) userMaybeSpecifyPath :: String -> Maybe FilePath -> ProgramDb -> ProgramDb userMaybeSpecifyPath _ Nothing conf = conf userMaybeSpecifyPath name (Just path) conf = userSpecifyPath name path conf -- |User-specify the arguments for this program. Basically override -- any args information for this program in the configuration. If it's -- not a known program, ignore it.. userSpecifyArgs :: String -- ^Program name -> [ProgArg] -- ^user-specified args -> ProgramDb -> ProgramDb userSpecifyArgs name args' = updateUnconfiguredProgs (flip Map.update name $ \(prog, path, args) -> Just (prog, path, args ++ args')) . updateConfiguredProgs (flip Map.update name $ \prog -> Just prog { programOverrideArgs = programOverrideArgs prog ++ args' }) -- | Like 'userSpecifyPath' but for a list of progs and their paths. -- userSpecifyPaths :: [(String, FilePath)] -> ProgramDb -> ProgramDb userSpecifyPaths paths conf = foldl' (\conf' (prog, path) -> userSpecifyPath prog path conf') conf paths -- | Like 'userSpecifyPath' but for a list of progs and their args. -- userSpecifyArgss :: [(String, [ProgArg])] -> ProgramDb -> ProgramDb userSpecifyArgss argss conf = foldl' (\conf' (prog, args) -> userSpecifyArgs prog args conf') conf argss -- | Get the path that has been previously specified for a program, if any. -- userSpecifiedPath :: Program -> ProgramDb -> Maybe FilePath userSpecifiedPath prog = join . fmap (\(_,p,_)->p) . Map.lookup (programName prog) . unconfiguredProgs -- | Get any extra args that have been previously specified for a program. -- userSpecifiedArgs :: Program -> ProgramDb -> [ProgArg] userSpecifiedArgs prog = maybe [] (\(_,_,as)->as) . Map.lookup (programName prog) . unconfiguredProgs -- ----------------------------- -- Managing configured programs -- | Try to find a configured program lookupProgram :: Program -> ProgramDb -> Maybe ConfiguredProgram lookupProgram prog = Map.lookup (programName prog) . configuredProgs -- | Update a configured program in the database. updateProgram :: ConfiguredProgram -> ProgramDb -> ProgramDb updateProgram prog = updateConfiguredProgs $ Map.insert (programId prog) prog -- --------------------------- -- Configuring known programs -- | Try to configure a specific program. If the program is already included in -- the colleciton of unconfigured programs then we use any user-supplied -- location and arguments. If the program gets configured sucessfully it gets -- added to the configured collection. -- -- Note that it is not a failure if the program cannot be configured. It's only -- a failure if the user supplied a location and the program could not be found -- at that location. -- -- The reason for it not being a failure at this stage is that we don't know up -- front all the programs we will need, so we try to configure them all. -- To verify that a program was actually sucessfully configured use -- 'requireProgram'. -- configureProgram :: Verbosity -> Program -> ProgramDb -> IO ProgramDb configureProgram verbosity prog conf = do let name = programName prog maybeLocation <- case userSpecifiedPath prog conf of Nothing -> programFindLocation prog verbosity >>= return . fmap FoundOnSystem Just path -> do absolute <- doesFileExist path if absolute then return (Just (UserSpecified path)) else findProgramLocation verbosity path >>= maybe (die notFound) (return . Just . UserSpecified) where notFound = "Cannot find the program '" ++ name ++ "' at '" ++ path ++ "' or on the path" case maybeLocation of Nothing -> return conf Just location -> do version <- programFindVersion prog verbosity (locationPath location) let configuredProg = ConfiguredProgram { programId = name, programVersion = version, programDefaultArgs = [], programOverrideArgs = userSpecifiedArgs prog conf, programLocation = location } extraArgs <- programPostConf prog verbosity configuredProg let configuredProg' = configuredProg { programDefaultArgs = extraArgs } return (updateConfiguredProgs (Map.insert name configuredProg') conf) -- | Configure a bunch of programs using 'configureProgram'. Just a 'foldM'. -- configurePrograms :: Verbosity -> [Program] -> ProgramDb -> IO ProgramDb configurePrograms verbosity progs conf = foldM (flip (configureProgram verbosity)) conf progs -- | Try to configure all the known programs that have not yet been configured. -- configureAllKnownPrograms :: Verbosity -> ProgramDb -> IO ProgramDb configureAllKnownPrograms verbosity conf = configurePrograms verbosity [ prog | (prog,_,_) <- Map.elems notYetConfigured ] conf where notYetConfigured = unconfiguredProgs conf `Map.difference` configuredProgs conf -- | reconfigure a bunch of programs given new user-specified args. It takes -- the same inputs as 'userSpecifyPath' and 'userSpecifyArgs' and for all progs -- with a new path it calls 'configureProgram'. -- reconfigurePrograms :: Verbosity -> [(String, FilePath)] -> [(String, [ProgArg])] -> ProgramDb -> IO ProgramDb reconfigurePrograms verbosity paths argss conf = do configurePrograms verbosity progs . userSpecifyPaths paths . userSpecifyArgss argss $ conf where progs = catMaybes [ lookupKnownProgram name conf | (name,_) <- paths ] -- | Check that a program is configured and available to be run. -- -- It raises an exception if the program could not be configured, otherwise -- it returns the configured program. -- requireProgram :: Verbosity -> Program -> ProgramDb -> IO (ConfiguredProgram, ProgramDb) requireProgram verbosity prog conf = do -- If it's not already been configured, try to configure it now conf' <- case lookupProgram prog conf of Nothing -> configureProgram verbosity prog conf Just _ -> return conf case lookupProgram prog conf' of Nothing -> die notFound Just configuredProg -> return (configuredProg, conf') where notFound = "The program " ++ programName prog ++ " is required but it could not be found." -- | Check that a program is configured and available to be run. -- -- Additionally check that the version of the program number is suitable and -- return it. For example you could require 'AnyVersion' or -- @'orLaterVersion' ('Version' [1,0] [])@ -- -- It raises an exception if the program could not be configured or the version -- is unsuitable, otherwise it returns the configured program and its version -- number. -- requireProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (ConfiguredProgram, Version, ProgramDb) requireProgramVersion verbosity prog range conf = do -- If it's not already been configured, try to configure it now conf' <- case lookupProgram prog conf of Nothing -> configureProgram verbosity prog conf Just _ -> return conf case lookupProgram prog conf' of Nothing -> die notFound Just configuredProg@ConfiguredProgram { programLocation = location } -> case programVersion configuredProg of Just version | withinRange version range -> return (configuredProg, version, conf') | otherwise -> die (badVersion version location) Nothing -> die (noVersion location) where notFound = "The program " ++ programName prog ++ versionRequirement ++ " is required but it could not be found." badVersion v l = "The program " ++ programName prog ++ versionRequirement ++ " is required but the version found at " ++ locationPath l ++ " is version " ++ display v noVersion l = "The program " ++ programName prog ++ versionRequirement ++ " is required but the version of " ++ locationPath l ++ " could not be determined." versionRequirement | isAnyVersion range = "" | otherwise = " version " ++ display range
IreneKnapp/Faction
libfaction/Distribution/Simple/Program/Db.hs
bsd-3-clause
15,042
0
18
3,645
2,545
1,392
1,153
221
4
{-# LANGUAGE OverloadedStrings #-} module Graphics.Storyboard.Bling where -- import Data.Text(Text) -- -- import Graphics.Blank -- import qualified Graphics.Blank.Style as Style -- -- import Graphics.Storyboard.Slide -- import Graphics.Storyboard.Tile
tonymorris/story-board
src/Graphics/Storyboard/Bling.hs
bsd-3-clause
255
0
3
30
15
13
2
2
0
{- (c) Galois, 2006 (c) University of Glasgow, 2007 -} {-# LANGUAGE NondecreasingIndentation #-} module Coverage (addTicksToBinds, hpcInitCode) where import Type import HsSyn import Module import Outputable import DynFlags import Control.Monad import SrcLoc import ErrUtils import NameSet hiding (FreeVars) import Name import Bag import CostCentre import CoreSyn import Id import VarSet import Data.List import FastString import HscTypes import TyCon import UniqSupply import BasicTypes import MonadUtils import Maybes import CLabel import Util import Data.Array import Data.Time import System.Directory import Trace.Hpc.Mix import Trace.Hpc.Util import BreakArray import Data.Map (Map) import qualified Data.Map as Map {- ************************************************************************ * * * The main function: addTicksToBinds * * ************************************************************************ -} addTicksToBinds :: DynFlags -> Module -> ModLocation -- ... off the current module -> NameSet -- Exported Ids. When we call addTicksToBinds, -- isExportedId doesn't work yet (the desugarer -- hasn't set it), so we have to work from this set. -> [TyCon] -- Type constructor in this module -> LHsBinds Id -> IO (LHsBinds Id, HpcInfo, ModBreaks) addTicksToBinds dflags mod mod_loc exports tyCons binds | let passes = coveragePasses dflags, not (null passes), Just orig_file <- ml_hs_file mod_loc = do if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, emptyModBreaks) else do us <- mkSplitUniqSupply 'C' -- for cost centres let orig_file2 = guessSourceFile binds orig_file tickPass tickish (binds,st) = let env = TTE { fileName = mkFastString orig_file2 , declPath = [] , tte_dflags = dflags , exports = exports , inlines = emptyVarSet , inScope = emptyVarSet , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),()) | tyCon <- tyCons ] , density = mkDensity tickish dflags , this_mod = mod , tickishType = tickish } (binds',_,st') = unTM (addTickLHsBinds binds) env st in (binds', st') initState = TT { tickBoxCount = 0 , mixEntries = [] , breakCount = 0 , breaks = [] , uniqSupply = us } (binds1,st) = foldr tickPass (binds, initState) passes let tickCount = tickBoxCount st hashNo <- writeMixEntries dflags mod tickCount (reverse $ mixEntries st) orig_file2 modBreaks <- mkModBreaks dflags (breakCount st) (reverse $ breaks st) when (dopt Opt_D_dump_ticked dflags) $ log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (pprLHsBinds binds1) return (binds1, HpcInfo tickCount hashNo, modBreaks) | otherwise = return (binds, emptyHpcInfo False, emptyModBreaks) guessSourceFile :: LHsBinds Id -> FilePath -> FilePath guessSourceFile binds orig_file = -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name _ -> orig_file mkModBreaks :: DynFlags -> Int -> [MixEntry_] -> IO ModBreaks mkModBreaks dflags count entries = do breakArray <- newBreakArray dflags $ length entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ] varsTicks = listArray (0,count-1) [ vars | (_,_,vars,_) <- entries ] declsTicks= listArray (0,count-1) [ decls | (_,decls,_,_) <- entries ] modBreaks = emptyModBreaks { modBreaks_flags = breakArray , modBreaks_locs = locsTicks , modBreaks_vars = varsTicks , modBreaks_decls = declsTicks } -- return modBreaks writeMixEntries :: DynFlags -> Module -> Int -> [MixEntry_] -> FilePath -> IO Int writeMixEntries dflags mod count entries filename | not (gopt Opt_Hpc dflags) = return 0 | otherwise = do let hpc_dir = hpcDir dflags mod_name = moduleNameString (moduleName mod) hpc_mod_dir | modulePackageKey mod == mainPackageKey = hpc_dir | otherwise = hpc_dir ++ "/" ++ packageKeyString (modulePackageKey mod) tabStop = 8 -- <tab> counts as a normal char in GHC's location ranges. createDirectoryIfMissing True hpc_mod_dir modTime <- getModificationUTCTime filename let entries' = [ (hpcPos, box) | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ] when (length entries' /= count) $ do panic "the number of .mix entries are inconsistent" let hashNo = mixHash filename modTime tabStop entries' mixCreate hpc_mod_dir mod_name $ Mix filename modTime (toHash hashNo) tabStop entries' return hashNo -- ----------------------------------------------------------------------------- -- TickDensity: where to insert ticks data TickDensity = TickForCoverage -- for Hpc | TickForBreakPoints -- for GHCi | TickAllFunctions -- for -prof-auto-all | TickTopFunctions -- for -prof-auto-top | TickExportedFunctions -- for -prof-auto-exported | TickCallSites -- for stack tracing deriving Eq mkDensity :: TickishType -> DynFlags -> TickDensity mkDensity tickish dflags = case tickish of HpcTicks -> TickForCoverage SourceNotes -> TickForCoverage Breakpoints -> TickForBreakPoints ProfNotes -> case profAuto dflags of ProfAutoAll -> TickAllFunctions ProfAutoTop -> TickTopFunctions ProfAutoExports -> TickExportedFunctions ProfAutoCalls -> TickCallSites _other -> panic "mkDensity" -- | Decide whether to add a tick to a binding or not. shouldTickBind :: TickDensity -> Bool -- top level? -> Bool -- exported? -> Bool -- simple pat bind? -> Bool -- INLINE pragma? -> Bool shouldTickBind density top_lev exported simple_pat inline = case density of TickForBreakPoints -> not simple_pat -- we never add breakpoints to simple pattern bindings -- (there's always a tick on the rhs anyway). TickAllFunctions -> not inline TickTopFunctions -> top_lev && not inline TickExportedFunctions -> exported && not inline TickForCoverage -> True TickCallSites -> False shouldTickPatBind :: TickDensity -> Bool -> Bool shouldTickPatBind density top_lev = case density of TickForBreakPoints -> False TickAllFunctions -> True TickTopFunctions -> top_lev TickExportedFunctions -> False TickForCoverage -> False TickCallSites -> False -- ----------------------------------------------------------------------------- -- Adding ticks to bindings addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id) addTickLHsBinds = mapBagM addTickLHsBind addTickLHsBind :: LHsBind Id -> TM (LHsBind Id) addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds, abs_exports = abs_exports })) = do withEnv add_exports $ do withEnv add_inlines $ do binds' <- addTickLHsBinds binds return $ L pos $ bind { abs_binds = binds' } where -- in AbsBinds, the Id on each binding is not the actual top-level -- Id that we are defining, they are related by the abs_exports -- field of AbsBinds. So if we're doing TickExportedFunctions we need -- to add the local Ids to the set of exported Names so that we know to -- tick the right bindings. add_exports env = env{ exports = exports env `extendNameSetList` [ idName mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , idName pid `elemNameSet` (exports env) ] } add_inlines env = env{ inlines = inlines env `extendVarSetList` [ mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , isAnyInlinePragma (idInlinePragma pid) ] } addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do let name = getOccString id decl_path <- getPathEntry density <- getDensity inline_ids <- liftM inlines getEnv let inline = isAnyInlinePragma (idInlinePragma id) || id `elemVarSet` inline_ids -- See Note [inline sccs] tickish <- tickishType `liftM` getEnv if inline && tickish == ProfNotes then return (L pos funBind) else do (fvs, mg@(MG { mg_alts = matches' })) <- getFreeVars $ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) blackListed <- isBlackListed pos exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions -- We don't want redundant ticks on simple pattern bindings -- We don't want to tick non-exported bindings in TickExportedFunctions let simple = isSimplePatBind funBind toplev = null decl_path exported = idName id `elemNameSet` exported_names tick <- if not blackListed && shouldTickBind density toplev exported simple inline then bindTick density name pos fvs else return Nothing let mbCons = maybe Prelude.id (:) return $ L pos $ funBind { fun_matches = mg { mg_alts = matches' } , fun_tick = tick `mbCons` fun_tick funBind } where -- a binding is a simple pattern binding if it is a funbind with zero patterns isSimplePatBind :: HsBind a -> Bool isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0 -- TODO: Revisit this addTickLHsBind (L pos (pat@(PatBind { pat_lhs = lhs, pat_rhs = rhs }))) = do let name = "(...)" (fvs, rhs') <- getFreeVars $ addPathEntry name $ addTickGRHSs False False rhs let pat' = pat { pat_rhs = rhs'} -- Should create ticks here? density <- getDensity decl_path <- getPathEntry let top_lev = null decl_path if not (shouldTickPatBind density top_lev) then return (L pos pat') else do -- Allocate the ticks rhs_tick <- bindTick density name pos fvs let patvars = map getOccString (collectPatBinders lhs) patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars -- Add to pattern let mbCons = maybe id (:) rhs_ticks = rhs_tick `mbCons` fst (pat_ticks pat') patvar_tickss = zipWith mbCons patvar_ticks (snd (pat_ticks pat') ++ repeat []) return $ L pos $ pat' { pat_ticks = (rhs_ticks, patvar_tickss) } -- Only internal stuff, not from source, uses VarBind, so we ignore it. addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) bindTick density name pos fvs = do decl_path <- getPathEntry let toplev = null decl_path count_entries = toplev || density == TickAllFunctions top_only = density /= TickAllFunctions box_label = if toplev then TopLevelBox [name] else LocalBox (decl_path ++ [name]) -- allocATickBox box_label count_entries top_only pos fvs -- Note [inline sccs] -- -- It should be reasonable to add ticks to INLINE functions; however -- currently this tickles a bug later on because the SCCfinal pass -- does not look inside unfoldings to find CostCentres. It would be -- difficult to fix that, because SCCfinal currently works on STG and -- not Core (and since it also generates CostCentres for CAFs, -- changing this would be difficult too). -- -- Another reason not to add ticks to INLINE functions is that this -- sometimes handy for avoiding adding a tick to a particular function -- (see #6131) -- -- So for now we do not add any ticks to INLINE functions at all. -- ----------------------------------------------------------------------------- -- Decorate an LHsExpr with ticks -- selectively add ticks to interesting expressions addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExpr e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | isGoodBreakExpr e0 -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding. -- We always consider these to be breakpoints, unless the expression is a 'let' -- (because the body will definitely have a tick somewhere). ToDo: perhaps -- we should treat 'case' and 'if' the same way? addTickLHsExprRHS :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprRHS e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context: -- let binds in [], ( [] ) -- we never tick these if we're doing HPC, but otherwise -- we treat it like an ordinary expression. addTickLHsExprEvalInner :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprEvalInner e = do d <- getDensity case d of TickForCoverage -> addTickLHsExprNever e _otherwise -> addTickLHsExpr e -- | A let body is treated differently from addTickLHsExprEvalInner -- above with TickForBreakPoints, because for breakpoints we always -- want to tick the body, even if it is not a redex. See test -- break012. This gives the user the opportunity to inspect the -- values of the let-bound variables. addTickLHsExprLetBody :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprLetBody e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick, -- because the scope of this tick is completely subsumed by -- another. addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprNever (L pos e0) = do e1 <- addTickHsExpr e0 return $ L pos e1 -- general heuristic: expressions which do not denote values are good break points isGoodBreakExpr :: HsExpr Id -> Bool isGoodBreakExpr (HsApp {}) = True isGoodBreakExpr (OpApp {}) = True isGoodBreakExpr (NegApp {}) = True isGoodBreakExpr (HsIf {}) = True isGoodBreakExpr (HsMultiIf {}) = True isGoodBreakExpr (HsCase {}) = True isGoodBreakExpr (RecordCon {}) = True isGoodBreakExpr (RecordUpd {}) = True isGoodBreakExpr (ArithSeq {}) = True isGoodBreakExpr (PArrSeq {}) = True isGoodBreakExpr _other = False isCallSite :: HsExpr Id -> Bool isCallSite HsApp{} = True isCallSite OpApp{} = True isCallSite _ = False addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage (allocBinTickBox boxLabel pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) -- ----------------------------------------------------------------------------- -- Decoarate an HsExpr with ticks addTickHsExpr :: HsExpr Id -> TM (HsExpr Id) addTickHsExpr e@(HsVar id) = do freeVar id; return e addTickHsExpr e@(HsIPVar _) = return e addTickHsExpr e@(HsOverLit _) = return e addTickHsExpr e@(HsLit _) = return e addTickHsExpr (HsLam matchgroup) = liftM HsLam (addTickMatchGroup True matchgroup) addTickHsExpr (HsLamCase ty mgs) = liftM (HsLamCase ty) (addTickMatchGroup True mgs) addTickHsExpr (HsApp e1 e2) = liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (OpApp e1 e2 fix e3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsExprNever e2) (return fix) (addTickLHsExpr e3) addTickHsExpr (NegApp e neg) = liftM2 NegApp (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan neg) addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprEvalInner e) addTickHsExpr (SectionL e1 e2) = liftM2 SectionL (addTickLHsExpr e1) (addTickLHsExprNever e2) addTickHsExpr (SectionR e1 e2) = liftM2 SectionR (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (ExplicitTuple es boxity) = liftM2 ExplicitTuple (mapM addTickTupArg es) (return boxity) addTickHsExpr (HsCase e mgs) = liftM2 HsCase (addTickLHsExpr e) -- not an EvalInner; e might not necessarily -- be evaluated. (addTickMatchGroup False mgs) addTickHsExpr (HsIf cnd e1 e2 e3) = liftM3 (HsIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsExprOptAlt True e2) (addTickLHsExprOptAlt True e3) addTickHsExpr (HsMultiIf ty alts) = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' } addTickHsExpr (HsLet binds e) = bindLocals (collectLocalBinders binds) $ liftM2 HsLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo cxt stmts srcloc) = do { (stmts', _) <- addTickLStmts' forQual stmts (return ()) ; return (HsDo cxt stmts' srcloc) } where forQual = case cxt of ListComp -> Just $ BinBox QualBinBox _ -> Nothing addTickHsExpr (ExplicitList ty wit es) = liftM3 ExplicitList (return ty) (addTickWit wit) (mapM (addTickLHsExpr) es) where addTickWit Nothing = return Nothing addTickWit (Just fln) = do fln' <- addTickHsExpr fln return (Just fln') addTickHsExpr (ExplicitPArr ty es) = liftM2 ExplicitPArr (return ty) (mapM (addTickLHsExpr) es) addTickHsExpr (HsStatic e) = HsStatic <$> addTickLHsExpr e addTickHsExpr (RecordCon id ty rec_binds) = liftM3 RecordCon (return id) (return ty) (addTickHsRecordBinds rec_binds) addTickHsExpr (RecordUpd e rec_binds cons tys1 tys2) = liftM5 RecordUpd (addTickLHsExpr e) (addTickHsRecordBinds rec_binds) (return cons) (return tys1) (return tys2) addTickHsExpr (ExprWithTySigOut e ty) = liftM2 ExprWithTySigOut (addTickLHsExprNever e) -- No need to tick the inner expression -- for expressions with signatures (return ty) addTickHsExpr (ArithSeq ty wit arith_seq) = liftM3 ArithSeq (return ty) (addTickWit wit) (addTickArithSeqInfo arith_seq) where addTickWit Nothing = return Nothing addTickWit (Just fl) = do fl' <- addTickHsExpr fl return (Just fl') -- We might encounter existing ticks (multiple Coverage passes) addTickHsExpr (HsTick t e) = liftM (HsTick t) (addTickLHsExprNever e) addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e) addTickHsExpr (HsTickPragma _ (L pos e0)) = do e2 <- allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 return $ unLoc e2 addTickHsExpr (PArrSeq ty arith_seq) = liftM2 PArrSeq (return ty) (addTickArithSeqInfo arith_seq) addTickHsExpr (HsSCC nm e) = liftM2 HsSCC (return nm) (addTickLHsExpr e) addTickHsExpr (HsCoreAnn nm e) = liftM2 HsCoreAnn (return nm) (addTickLHsExpr e) addTickHsExpr e@(HsBracket {}) = return e addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e addTickHsExpr (HsProc pat cmdtop) = liftM2 HsProc (addTickLPat pat) (liftL (addTickHsCmdTop) cmdtop) addTickHsExpr (HsWrap w e) = liftM2 HsWrap (return w) (addTickHsExpr e) -- explicitly no tick on inside addTickHsExpr e@(HsType _) = return e addTickHsExpr (HsUnboundVar {}) = panic "addTickHsExpr.HsUnboundVar" -- Others dhould never happen in expression content. addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e) addTickTupArg :: LHsTupArg Id -> TM (LHsTupArg Id) addTickTupArg (L l (Present e)) = do { e' <- addTickLHsExpr e ; return (L l (Present e')) } addTickTupArg (L l (Missing ty)) = return (L l (Missing ty)) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup Id (LHsExpr Id) -> TM (MatchGroup Id (LHsExpr Id)) addTickMatchGroup is_lam mg@(MG { mg_alts = matches }) = do let isOneOfMany = matchesOneOfMany matches matches' <- mapM (liftL (addTickMatch isOneOfMany is_lam)) matches return $ mg { mg_alts = matches' } addTickMatch :: Bool -> Bool -> Match Id (LHsExpr Id) -> TM (Match Id (LHsExpr Id)) addTickMatch isOneOfMany isLambda (Match pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs return $ Match pats opSig gRHSs' addTickGRHSs :: Bool -> Bool -> GRHSs Id (LHsExpr Id) -> TM (GRHSs Id (LHsExpr Id)) addTickGRHSs isOneOfMany isLambda (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickGRHS :: Bool -> Bool -> GRHS Id (LHsExpr Id) -> TM (GRHS Id (LHsExpr Id)) addTickGRHS isOneOfMany isLambda (GRHS stmts expr) = do (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickGRHSBody isOneOfMany isLambda expr) return $ GRHS stmts' expr' addTickGRHSBody :: Bool -> Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickGRHSBody isOneOfMany isLambda expr@(L pos e0) = do d <- getDensity case d of TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $ allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM [ExprLStmt Id] addTickLStmts isGuard stmts = do (stmts, _) <- addTickLStmts' isGuard stmts (return ()) return stmts addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM a -> TM ([ExprLStmt Id], a) addTickLStmts' isGuard lstmts res = bindLocals (collectLStmtsBinders lstmts) $ do { lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts ; a <- res ; return (lstmts', a) } addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id (LHsExpr Id) -> TM (Stmt Id (LHsExpr Id)) addTickStmt _isGuard (LastStmt e ret) = do liftM2 LastStmt (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan ret) addTickStmt _isGuard (BindStmt pat e bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsExprRHS e) (addTickSyntaxExpr hpcSrcSpan bind) (addTickSyntaxExpr hpcSrcSpan fail) addTickStmt isGuard (BodyStmt e bind' guard' ty) = do liftM4 BodyStmt (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickStmt _isGuard (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt pairs mzipExpr bindExpr) = do liftM3 ParStmt (mapM (addTickStmtAndBinders isGuard) pairs) (addTickSyntaxExpr hpcSrcSpan mzipExpr) (addTickSyntaxExpr hpcSrcSpan bindExpr) addTickStmt isGuard stmt@(TransStmt { trS_stmts = stmts , trS_by = by, trS_using = using , trS_ret = returnExpr, trS_bind = bindExpr , trS_fmap = liftMExpr }) = do t_s <- addTickLStmts isGuard stmts t_y <- fmapMaybeM addTickLHsExprRHS by t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr t_m <- addTickSyntaxExpr hpcSrcSpan liftMExpr return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {}) = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e | otherwise = addTickLHsExprRHS e addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ParStmtBlock Id Id -> TM (ParStmtBlock Id Id) addTickStmtAndBinders isGuard (ParStmtBlock stmts ids returnExpr) = liftM3 ParStmtBlock (addTickLStmts isGuard stmts) (return ids) (addTickSyntaxExpr hpcSrcSpan returnExpr) addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id) addTickHsLocalBinds (HsValBinds binds) = liftM HsValBinds (addTickHsValBinds binds) addTickHsLocalBinds (HsIPBinds binds) = liftM HsIPBinds (addTickHsIPBinds binds) addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b) addTickHsValBinds (ValBindsOut binds sigs) = liftM2 ValBindsOut (mapM (\ (rec,binds') -> liftM2 (,) (return rec) (addTickLHsBinds binds')) binds) (return sigs) addTickHsValBinds _ = panic "addTickHsValBinds" addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id) addTickHsIPBinds (IPBinds ipbinds dictbinds) = liftM2 IPBinds (mapM (liftL (addTickIPBind)) ipbinds) (return dictbinds) addTickIPBind :: IPBind Id -> TM (IPBind Id) addTickIPBind (IPBind nm e) = liftM2 IPBind (return nm) (addTickLHsExpr e) -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id) addTickSyntaxExpr pos x = do L _ x' <- addTickLHsExpr (L pos x) return $ x' -- we do not walk into patterns. addTickLPat :: LPat Id -> TM (LPat Id) addTickLPat pat = return pat addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id) addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) = liftM4 HsCmdTop (addTickLHsCmd cmd) (return tys) (return ty) (return syntaxtable) addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id) addTickLHsCmd (L pos c0) = do c1 <- addTickHsCmd c0 return $ L pos c1 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id) addTickHsCmd (HsCmdLam matchgroup) = liftM HsCmdLam (addTickCmdMatchGroup matchgroup) addTickHsCmd (HsCmdApp c e) = liftM2 HsCmdApp (addTickLHsCmd c) (addTickLHsExpr e) {- addTickHsCmd (OpApp e1 c2 fix c3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsCmd c2) (return fix) (addTickLHsCmd c3) -} addTickHsCmd (HsCmdPar e) = liftM HsCmdPar (addTickLHsCmd e) addTickHsCmd (HsCmdCase e mgs) = liftM2 HsCmdCase (addTickLHsExpr e) (addTickCmdMatchGroup mgs) addTickHsCmd (HsCmdIf cnd e1 c2 c3) = liftM3 (HsCmdIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3) addTickHsCmd (HsCmdLet binds c) = bindLocals (collectLocalBinders binds) $ liftM2 HsCmdLet (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo stmts srcloc) = do { (stmts', _) <- addTickLCmdStmts' stmts (return ()) ; return (HsCmdDo stmts' srcloc) } addTickHsCmd (HsCmdArrApp e1 e2 ty1 arr_ty lr) = liftM5 HsCmdArrApp (addTickLHsExpr e1) (addTickLHsExpr e2) (return ty1) (return arr_ty) (return lr) addTickHsCmd (HsCmdArrForm e fix cmdtop) = liftM3 HsCmdArrForm (addTickLHsExpr e) (return fix) (mapM (liftL (addTickHsCmdTop)) cmdtop) addTickHsCmd (HsCmdCast co cmd) = liftM2 HsCmdCast (return co) (addTickHsCmd cmd) -- Others should never happen in a command context. --addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e) addTickCmdMatchGroup :: MatchGroup Id (LHsCmd Id) -> TM (MatchGroup Id (LHsCmd Id)) addTickCmdMatchGroup mg@(MG { mg_alts = matches }) = do matches' <- mapM (liftL addTickCmdMatch) matches return $ mg { mg_alts = matches' } addTickCmdMatch :: Match Id (LHsCmd Id) -> TM (Match Id (LHsCmd Id)) addTickCmdMatch (Match pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickCmdGRHSs gRHSs return $ Match pats opSig gRHSs' addTickCmdGRHSs :: GRHSs Id (LHsCmd Id) -> TM (GRHSs Id (LHsCmd Id)) addTickCmdGRHSs (GRHSs guarded local_binds) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded return $ GRHSs guarded' local_binds' where binders = collectLocalBinders local_binds addTickCmdGRHS :: GRHS Id (LHsCmd Id) -> TM (GRHS Id (LHsCmd Id)) -- The *guards* are *not* Cmds, although the body is -- C.f. addTickGRHS for the BinBox stuff addTickCmdGRHS (GRHS stmts cmd) = do { (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickLHsCmd cmd) ; return $ GRHS stmts' expr' } addTickLCmdStmts :: [LStmt Id (LHsCmd Id)] -> TM [LStmt Id (LHsCmd Id)] addTickLCmdStmts stmts = do (stmts, _) <- addTickLCmdStmts' stmts (return ()) return stmts addTickLCmdStmts' :: [LStmt Id (LHsCmd Id)] -> TM a -> TM ([LStmt Id (LHsCmd Id)], a) addTickLCmdStmts' lstmts res = bindLocals binders $ do lstmts' <- mapM (liftL addTickCmdStmt) lstmts a <- res return (lstmts', a) where binders = collectLStmtsBinders lstmts addTickCmdStmt :: Stmt Id (LHsCmd Id) -> TM (Stmt Id (LHsCmd Id)) addTickCmdStmt (BindStmt pat c bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsCmd c) (return bind) (return fail) addTickCmdStmt (LastStmt c ret) = do liftM2 LastStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan ret) addTickCmdStmt (BodyStmt c bind' guard' ty) = do liftM4 BodyStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickCmdStmt (LetStmt binds) = do liftM LetStmt (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {}) = do { stmts' <- addTickLCmdStmts (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } -- Others should never happen in a command context. addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt) addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id) addTickHsRecordBinds (HsRecFields fields dd) = do { fields' <- mapM process fields ; return (HsRecFields fields' dd) } where process (L l (HsRecField ids expr doc)) = do { expr' <- addTickLHsExpr expr ; return (L l (HsRecField ids expr' doc)) } addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id) addTickArithSeqInfo (From e1) = liftM From (addTickLHsExpr e1) addTickArithSeqInfo (FromThen e1 e2) = liftM2 FromThen (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromTo e1 e2) = liftM2 FromTo (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromThenTo e1 e2 e3) = liftM3 FromThenTo (addTickLHsExpr e1) (addTickLHsExpr e2) (addTickLHsExpr e3) liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a) liftL f (L loc a) = do a' <- f a return $ L loc a' data TickTransState = TT { tickBoxCount:: Int , mixEntries :: [MixEntry_] , breakCount :: Int , breaks :: [MixEntry_] , uniqSupply :: UniqSupply } data TickTransEnv = TTE { fileName :: FastString , density :: TickDensity , tte_dflags :: DynFlags , exports :: NameSet , inlines :: VarSet , declPath :: [String] , inScope :: VarSet , blackList :: Map SrcSpan () , this_mod :: Module , tickishType :: TickishType } -- deriving Show data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (hscTarget dflags == HscInterpreted) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (gopt Opt_SccProfilingOn dflags && profAuto dflags /= NoProfAuto) ProfNotes $ ifa (gopt Opt_Debug dflags) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs -- | Tickishs that only make sense when their source code location -- refers to the current file. This might not always be true due to -- LINE pragmas in the code - which would confuse at least HPC. tickSameFileOnly :: TickishType -> Bool tickSameFileOnly HpcTicks = True tickSameFileOnly _other = False type FreeVars = OccEnv Id noFVs :: FreeVars noFVs = emptyOccEnv -- Note [freevars] -- For breakpoints we want to collect the free variables of an -- expression for pinning on the HsTick. We don't want to collect -- *all* free variables though: in particular there's no point pinning -- on free variables that are will otherwise be in scope at the GHCi -- prompt, which means all top-level bindings. Unfortunately detecting -- top-level bindings isn't easy (collectHsBindsBinders on the top-level -- bindings doesn't do it), so we keep track of a set of "in-scope" -- variables in addition to the free variables, and the former is used -- to filter additions to the latter. This gives us complete control -- over what free variables we track. data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) } -- a combination of a state monad (TickTransState) and a writer -- monad (FreeVars). instance Functor TM where fmap = liftM instance Applicative TM where pure = return (<*>) = ap instance Monad TM where return a = TM $ \ _env st -> (a,noFVs,st) (TM m) >>= k = TM $ \ env st -> case m env st of (r1,fv1,st1) -> case unTM (k r1) env st1 of (r2,fv2,st2) -> (r2, fv1 `plusOccEnv` fv2, st2) instance HasDynFlags TM where getDynFlags = TM $ \ env st -> (tte_dflags env, noFVs, st) instance MonadUnique TM where getUniqueSupplyM = TM $ \_ st -> (uniqSupply st, noFVs, st) getUniqueM = TM $ \_ st -> let (u, us') = takeUniqFromSupply (uniqSupply st) in (u, noFVs, st { uniqSupply = us' }) getState :: TM TickTransState getState = TM $ \ _ st -> (st, noFVs, st) setState :: (TickTransState -> TickTransState) -> TM () setState f = TM $ \ _ st -> ((), noFVs, f st) getEnv :: TM TickTransEnv getEnv = TM $ \ env st -> (env, noFVs, st) withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a withEnv f (TM m) = TM $ \ env st -> case m (f env) st of (a, fvs, st') -> (a, fvs, st') getDensity :: TM TickDensity getDensity = TM $ \env st -> (density env, noFVs, st) ifDensity :: TickDensity -> TM a -> TM a -> TM a ifDensity d th el = do d0 <- getDensity; if d == d0 then th else el getFreeVars :: TM a -> TM (FreeVars, a) getFreeVars (TM m) = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st') freeVar :: Id -> TM () freeVar id = TM $ \ env st -> if id `elemVarSet` inScope env then ((), unitOccEnv (nameOccName (idName id)) id, st) else ((), noFVs, st) addPathEntry :: String -> TM a -> TM a addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] }) getPathEntry :: TM [String] getPathEntry = declPath `liftM` getEnv getFileName :: TM FastString getFileName = fileName `liftM` getEnv isGoodSrcSpan' :: SrcSpan -> Bool isGoodSrcSpan' pos@(RealSrcSpan _) = srcSpanStart pos /= srcSpanEnd pos isGoodSrcSpan' (UnhelpfulSpan _) = False isGoodTickSrcSpan :: SrcSpan -> TM Bool isGoodTickSrcSpan pos = do file_name <- getFileName tickish <- tickishType `liftM` getEnv let need_same_file = tickSameFileOnly tickish same_file = Just file_name == srcSpanFileName_maybe pos return (isGoodSrcSpan' pos && (not need_same_file || same_file)) ifGoodTickSrcSpan :: SrcSpan -> TM a -> TM a -> TM a ifGoodTickSrcSpan pos then_code else_code = do good <- isGoodTickSrcSpan pos if good then then_code else else_code bindLocals :: [Id] -> TM a -> TM a bindLocals new_ids (TM m) = TM $ \ env st -> case m env{ inScope = inScope env `extendVarSetList` new_ids } st of (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st') where occs = [ nameOccName (idName id) | id <- new_ids ] isBlackListed :: SrcSpan -> TM Bool isBlackListed pos = TM $ \ env st -> case Map.lookup pos (blackList env) of Nothing -> (False,noFVs,st) Just () -> (True,noFVs,st) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocTickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocTickBox boxLabel countEntries topOnly pos m = ifGoodTickSrcSpan pos (do (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env) return (L pos (HsTick tickish (L pos e))) ) (do e <- m return (L pos e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let mydecl_path = case boxLabel of TopLevelBox x -> x LocalBox xs -> xs _ -> panic "allocATickBox" tickish <- mkTickish boxLabel countEntries topOnly pos fvs mydecl_path return (Just tickish) ) (return Nothing) mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String] -> TM (Tickish Id) mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnLiftedType . idType) $ occEnvElts fvs -- unlifted types cause two problems here: -- * we can't bind them at the GHCi prompt -- (bindLocalsAtBreakpoint already fliters them out), -- * the simplifier might try to substitute a literal for -- the Id, and we can't handle that. me = (pos, decl_path, map (nameOccName.idName) ids, boxLabel) cc_name | topOnly = head decl_path | otherwise = concat (intersperse "." decl_path) dflags <- getDynFlags env <- getEnv case tickishType env of HpcTicks -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me : mixEntries st } return $ HpcTick (this_mod env) c ProfNotes -> do ccUnique <- getUniqueM let cc = mkUserCC (mkFastString cc_name) (this_mod env) pos ccUnique count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} Breakpoints -> do c <- liftM breakCount getState setState $ \st -> st { breakCount = c + 1 , breaks = me:breaks st } return $ Breakpoint c ids SourceNotes | RealSrcSpan pos' <- pos -> return $ SourceNote pos' cc_name _otherwise -> panic "mkTickish: bad source span!" allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of HpcTicks -> do e <- liftM (L pos) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e) _other -> allocTickBox (ExpBox False) False False pos m mkBinTickBoxHpc :: (Bool -> BoxLabel) -> SrcSpan -> LHsExpr Id -> TM (LHsExpr Id) mkBinTickBoxHpc boxLabel pos e = TM $ \ env st -> let meT = (pos,declPath env, [],boxLabel True) meF = (pos,declPath env, [],boxLabel False) meE = (pos,declPath env, [],ExpBox False) c = tickBoxCount st mes = mixEntries st in ( L pos $ HsTick (HpcTick (this_mod env) c) $ L pos $ HsBinTick (c+1) (c+2) e -- notice that F and T are reversed, -- because we are building the list in -- reverse... , noFVs , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes} ) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s) | isGoodSrcSpan' pos = toHpcPos (srcSpanStartLine s, srcSpanStartCol s, srcSpanEndLine s, srcSpanEndCol s - 1) -- the end column of a SrcSpan is one -- greater than the last column of the -- span (see SrcLoc), whereas HPC -- expects to the column range to be -- inclusive, hence we subtract one above. mkHpcPos _ = panic "bad source span; expected such spans to be filtered out" hpcSrcSpan :: SrcSpan hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals") matchesOneOfMany :: [LMatch Id body] -> Bool matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1 where matchCount (L _ (Match _pats _ty (GRHSs grhss _binds))) = length grhss type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel) -- For the hash value, we hash everything: the file name, -- the timestamp of the original source file, the tab stop, -- and the mix entries. We cheat, and hash the show'd string. -- This hash only has to be hashed at Mix creation time, -- and is for sanity checking only. mixHash :: FilePath -> UTCTime -> Int -> [MixEntry] -> Int mixHash file tm tabstop entries = fromIntegral $ hashString (show $ Mix file tm 0 tabstop entries) {- ************************************************************************ * * * initialisation * * ************************************************************************ Each module compiled with -fhpc declares an initialisation function of the form `hpc_init_<module>()`, which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) {extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} hpcInitCode :: Module -> HpcInfo -> SDoc hpcInitCode _ (NoHpcInfo {}) = Outputable.empty hpcInitCode this_mod (HpcInfo tickCount hashNo) = vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)" , braces (vcat [ ptext (sLit "extern StgWord64 ") <> tickboxes <> ptext (sLit "[]") <> semi, ptext (sLit "hs_hpc_module") <> parens (hcat (punctuate comma [ doubleQuotes full_name_str, int tickCount, -- really StgWord32 int hashNo, -- really StgWord32 tickboxes ])) <> semi ]) ] where tickboxes = ppr (mkHpcTicksLabel $ this_mod) module_name = hcat (map (text.charToC) $ bytesFS (moduleNameFS (Module.moduleName this_mod))) package_name = hcat (map (text.charToC) $ bytesFS (packageKeyFS (modulePackageKey this_mod))) full_name_str | modulePackageKey this_mod == mainPackageKey = module_name | otherwise = package_name <> char '/' <> module_name
bitemyapp/ghc
compiler/deSugar/Coverage.hs
bsd-3-clause
48,601
0
25
14,664
12,943
6,562
6,381
929
8
-- | Extra functions for optparse-applicative. module Options.Applicative.Builder.Extra (boolFlags ,boolFlagsNoDefault ,maybeBoolFlags ,firstBoolFlags ,enableDisableFlags ,enableDisableFlagsNoDefault ,extraHelpOption ,execExtraHelp ,textOption ,textArgument ,optionalFirst ) where import Control.Monad (when) import Data.Monoid import Options.Applicative import Options.Applicative.Types (readerAsk) import System.Environment (withArgs) import System.FilePath (takeBaseName) import Data.Text (Text) import qualified Data.Text as T -- | Enable/disable flags for a 'Bool'. boolFlags :: Bool -- ^ Default value -> String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlags defaultValue = enableDisableFlags defaultValue True False -- | Enable/disable flags for a 'Bool', without a default case (to allow chaining with '<|>'). boolFlagsNoDefault :: String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields Bool -> Parser Bool boolFlagsNoDefault = enableDisableFlagsNoDefault True False -- | Enable/disable flags for a @('Maybe' 'Bool')@. maybeBoolFlags :: String -- ^ Flag name -> String -- ^ Help suffix -> Mod FlagFields (Maybe Bool) -> Parser (Maybe Bool) maybeBoolFlags = enableDisableFlags Nothing (Just True) (Just False) -- | Like 'maybeBoolFlags', but parsing a 'First'. firstBoolFlags :: String -> String -> Mod FlagFields (Maybe Bool) -> Parser (First Bool) firstBoolFlags long0 help0 mod0 = First <$> maybeBoolFlags long0 help0 mod0 -- | Enable/disable flags for any type. enableDisableFlags :: a -- ^ Default value -> a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlags defaultValue enabledValue disabledValue name helpSuffix mods = enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods <|> pure defaultValue -- | Enable/disable flags for any type, without a default (to allow chaining with '<|>') enableDisableFlagsNoDefault :: a -- ^ Enabled value -> a -- ^ Disabled value -> String -- ^ Name -> String -- ^ Help suffix -> Mod FlagFields a -> Parser a enableDisableFlagsNoDefault enabledValue disabledValue name helpSuffix mods = last <$> some ((flag' enabledValue (hidden <> internal <> long name <> help helpSuffix <> mods) <|> flag' disabledValue (hidden <> internal <> long ("no-" ++ name) <> help helpSuffix <> mods)) <|> flag' disabledValue (long (concat ["[no-]", name]) <> help (concat ["Enable/disable ", helpSuffix]) <> mods)) -- | Show an extra help option (e.g. @--docker-help@ shows help for all @--docker*@ args). -- -- To actually have that help appear, use 'execExtraHelp' before executing the main parser. extraHelpOption :: Bool -- ^ Hide from the brief description? -> String -- ^ Program name, e.g. @"stack"@ -> String -- ^ Option glob expression, e.g. @"docker*"@ -> String -- ^ Help option name, e.g. @"docker-help"@ -> Parser (a -> a) extraHelpOption hide progName fakeName helpName = infoOption (optDesc' ++ ".") (long helpName <> hidden <> internal) <*> infoOption (optDesc' ++ ".") (long fakeName <> help optDesc' <> (if hide then hidden <> internal else idm)) where optDesc' = concat ["Run '", takeBaseName progName, " --", helpName, "' for details"] -- | Display extra help if extra help option passed in arguments. -- -- Since optparse-applicative doesn't allow an arbitrary IO action for an 'abortOption', this -- was the best way I found that doesn't require manually formatting the help. execExtraHelp :: [String] -- ^ Command line arguments -> String -- ^ Extra help option name, e.g. @"docker-help"@ -> Parser a -- ^ Option parser for the relevant command -> String -- ^ Option description -> IO () execExtraHelp args helpOpt parser pd = when (args == ["--" ++ helpOpt]) $ withArgs ["--help"] $ do _ <- execParser (info (hiddenHelper <*> ((,) <$> parser <*> some (strArgument (metavar "OTHER ARGUMENTS")))) (fullDesc <> progDesc pd)) return () where hiddenHelper = abortOption ShowHelpText (long "help" <> hidden <> internal) -- | 'option', specialized to 'Text'. textOption :: Mod OptionFields Text -> Parser Text textOption = option (T.pack <$> readerAsk) -- | 'argument', specialized to 'Text'. textArgument :: Mod ArgumentFields Text -> Parser Text textArgument = argument (T.pack <$> readerAsk) -- | Like 'optional', but returning a 'First'. optionalFirst :: Alternative f => f a -> f (First a) optionalFirst = fmap First . optional
Heather/stack
src/Options/Applicative/Builder/Extra.hs
bsd-3-clause
5,724
0
20
1,950
1,039
553
486
107
2
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {- NOTE: Don't modify this file unless you know what you are doing. If you are new to snap, start with Site.hs and Application.hs. This file contains boilerplate needed for dynamic reloading and is not meant for general consumption. Occasionally if we modify the way the dynamic reloader works and you want to upgrade, you might have to swap out this file for a newer version. But in most cases you'll never need to modify this code. -} module Main where ------------------------------------------------------------------------------ import Control.Exception (SomeException, try) import qualified Data.Text as T import Site import Snap.Core import Snap.Http.Server import Snap.Snaplet import Snap.Snaplet.Config import System.IO #ifdef DEVELOPMENT import Snap.Loader.Dynamic #else import Snap.Loader.Static #endif ------------------------------------------------------------------------------ -- | This is the entry point for this web server application. It supports -- easily switching between interpreting source and running statically compiled -- code. -- -- In either mode, the generated program should be run from the root of the -- project tree. When it is run, it locates its templates, static content, and -- source files in development mode, relative to the current working directory. -- -- When compiled with the development flag, only changes to the libraries, your -- cabal file, or this file should require a recompile to be picked up. -- Everything else is interpreted at runtime. There are a few consequences of -- this. -- -- First, this is much slower. Running the interpreter takes a significant -- chunk of time (a couple tenths of a second on the author's machine, at this -- time), regardless of the simplicity of the loaded code. In order to -- recompile and re-load server state as infrequently as possible, the source -- directories are watched for updates, as are any extra directories specified -- below. -- -- Second, the generated server binary is MUCH larger, since it links in the -- GHC API (via the hint library). -- -- Third, and the reason you would ever want to actually compile with -- development mode, is that it enables a faster development cycle. You can -- simply edit a file, save your changes, and hit reload to see your changes -- reflected immediately. -- -- When this is compiled without the development flag, all the actions are -- statically compiled in. This results in faster execution, a smaller binary -- size, and having to recompile the server for any code change. -- main :: IO () main = do -- Depending on the version of loadSnapTH in scope, this either enables -- dynamic reloading, or compiles it without. The last argument to -- loadSnapTH is a list of additional directories to watch for changes to -- trigger reloads in development mode. It doesn't need to include source -- directories, those are picked up automatically by the splice. (conf, site, cleanup) <- $(loadSnapTH [| getConf |] 'getActions ["snaplets/heist/templates"]) _ <- try $ httpServe conf site :: IO (Either SomeException ()) cleanup ------------------------------------------------------------------------------ -- | This action loads the config used by this application. The loaded config -- is returned as the first element of the tuple produced by the loadSnapTH -- Splice. The type is not solidly fixed, though it must be an IO action that -- produces the same type as 'getActions' takes. It also must be an instance of -- Typeable. If the type of this is changed, a full recompile will be needed to -- pick up the change, even in development mode. -- -- This action is only run once, regardless of whether development or -- production mode is in use. getConf :: IO (Config Snap AppConfig) getConf = commandLineAppConfig defaultConfig ------------------------------------------------------------------------------ -- | This function generates the the site handler and cleanup action from the -- configuration. In production mode, this action is only run once. In -- development mode, this action is run whenever the application is reloaded. -- -- Development mode also makes sure that the cleanup actions are run -- appropriately before shutdown. The cleanup action returned from loadSnapTH -- should still be used after the server has stopped handling requests, as the -- cleanup actions are only automatically run when a reload is triggered. -- -- This sample doesn't actually use the config passed in, but more -- sophisticated code might. getActions :: Config Snap AppConfig -> IO (Snap (), IO ()) getActions conf = do (msgs, site, cleanup) <- runSnaplet (appEnvironment =<< getOther conf) app hPutStrLn stderr $ T.unpack msgs return (site, cleanup)
alexandrelucchesi/pfec
rest-client/src/Main.hs
apache-2.0
5,008
0
11
1,011
335
211
124
27
1
yes = if foo then stuff else return ()
mpickering/hlint-refactor
tests/examples/Default27.hs
bsd-3-clause
38
0
7
8
19
10
9
1
2
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_HADDOCK show-extensions #-} {- | Copyright : Copyright (C) 2006-2018 Bjorn Buckwalter License : BSD3 Maintainer : bjorn@buckwalter.se Stability : Stable Portability: GHC only Provides a 'Functor' instance for 'Dimensional'. Note that this instance is dubious, because it allows you to break the dimensional abstraction. See 'dmap' for more information. Note that, while this instance overlaps with that given for 'Dimensionless', it is confluent with that instance. Note that this is an orphan instance. -} module Numeric.Units.Dimensional.Functor where import Numeric.Units.Dimensional import Prelude -- | A 'Functor' instance for 'Dimensional'. -- -- Note that this instance is dubious, because it allows you to break the dimensional abstraction. See 'dmap' for more information. -- -- Note that, while this instance overlaps with that given for 'Dimensionless', it is confluent with that instance. -- -- Note that this is an orphan instance. instance {-# OVERLAPPING #-} (KnownVariant v) => Functor (Dimensional v d) where fmap = dmap
bjornbm/dimensional
src/Numeric/Units/Dimensional/Functor.hs
bsd-3-clause
1,118
0
7
189
58
39
19
7
0
{-# LANGUAGE RankNTypes, NamedFieldPuns, RecordWildCards #-} module Distribution.Server.Features.Distro ( DistroFeature(..), DistroResource(..), initDistroFeature ) where import Distribution.Server.Framework import Distribution.Server.Features.Core import Distribution.Server.Features.Users import Distribution.Server.Users.Group (UserGroup(..), GroupDescription(..), nullDescription) import Distribution.Server.Features.Distro.State import Distribution.Server.Features.Distro.Types import Distribution.Server.Features.Distro.Backup (dumpBackup, restoreBackup) import Distribution.Server.Util.Parse (unpackUTF8) import Distribution.Text (display, simpleParse) import Distribution.Package import Data.List (intercalate) import Text.CSV (parseCSV) import Data.Version (showVersion) -- TODO: -- 1. write an HTML view for this module, and delete the text -- 2. use GroupResource from the Users feature -- 3. use MServerPart to support multiple views data DistroFeature = DistroFeature { distroFeatureInterface :: HackageFeature, distroResource :: DistroResource, maintainersGroup :: DynamicPath -> IO (Maybe UserGroup), queryPackageStatus :: forall m. MonadIO m => PackageName -> m [(DistroName, DistroPackageInfo)] } instance IsHackageFeature DistroFeature where getFeatureInterface = distroFeatureInterface data DistroResource = DistroResource { distroIndexPage :: Resource, distroAllPage :: Resource, distroPackages :: Resource, distroPackage :: Resource } initDistroFeature :: ServerEnv -> IO (UserFeature -> CoreFeature -> IO DistroFeature) initDistroFeature ServerEnv{serverStateDir} = do distrosState <- distrosStateComponent serverStateDir return $ \user core -> do let feature = distroFeature user core distrosState return feature distrosStateComponent :: FilePath -> IO (StateComponent AcidState Distros) distrosStateComponent stateDir = do st <- openLocalStateFrom (stateDir </> "db" </> "Distros") initialDistros return StateComponent { stateDesc = "" , stateHandle = st , getState = query st GetDistributions , putState = \(Distros dists versions) -> update st (ReplaceDistributions dists versions) , backupState = \_ -> dumpBackup , restoreState = restoreBackup , resetState = distrosStateComponent } distroFeature :: UserFeature -> CoreFeature -> StateComponent AcidState Distros -> DistroFeature distroFeature UserFeature{..} CoreFeature{coreResource=CoreResource{packageInPath}} distrosState = DistroFeature{..} where distroFeatureInterface = (emptyHackageFeature "distro") { featureResources = map ($ distroResource) [ distroIndexPage , distroAllPage , distroPackages , distroPackage ] , featureState = [abstractAcidStateComponent distrosState] } queryPackageStatus :: MonadIO m => PackageName -> m [(DistroName, DistroPackageInfo)] queryPackageStatus pkgname = queryState distrosState (PackageStatus pkgname) distroResource = DistroResource { distroIndexPage = (resourceAt "/distros/.:format") { resourceGet = [("txt", textEnumDistros)], resourcePost = [("", distroPostNew)] } , distroAllPage = (resourceAt "/distro/:distro") { resourcePut = [("", distroPutNew)], resourceDelete = [("", distroDelete)] } , distroPackages = (resourceAt "/distro/:distro/packages.:format") { resourceGet = [("txt", textDistroPkgs), ("csv", csvDistroPackageList)], resourcePut = [("csv", distroPackageListPut)] } , distroPackage = (resourceAt "/distro/:distro/package/:package.:format") { resourceGet = [("txt", textDistroPkg)], resourcePut = [("", distroPackagePut)], resourceDelete = [("", distroPackageDelete)] } } maintainersGroup = \dpath -> case simpleParse =<< lookup "distro" dpath of Nothing -> return Nothing Just dname -> getMaintainersGroup adminGroup dname textEnumDistros _ = fmap (toResponse . intercalate ", " . map display) (queryState distrosState EnumerateDistros) textDistroPkgs dpath = withDistroPath dpath $ \dname pkgs -> do let pkglines = map (\(name, info) -> display name ++ " at " ++ display (distroVersion info) ++ ": " ++ distroUrl info) $ pkgs return $ toResponse (unlines $ ("Packages for " ++ display dname):pkglines) csvDistroPackageList dpath = withDistroPath dpath $ \_dname pkgs -> do return $ toResponse $ packageListToCSV $ pkgs textDistroPkg dpath = withDistroPackagePath dpath $ \_ _ info -> return . toResponse $ show info -- result: see-other uri, or an error: not authenticated or not found (todo) distroDelete dpath = withDistroNamePath dpath $ \distro -> do guardAuthorised_ [InGroup adminGroup] --TODO: use the per-distro maintainer groups -- should also check for existence here of distro here void $ updateState distrosState $ RemoveDistro distro seeOther ("/distros/") (toResponse ()) -- result: ok response or not-found error distroPackageDelete dpath = withDistroPackagePath dpath $ \dname pkgname info -> do guardAuthorised_ [AnyKnownUser] --TODO: use the per-distro maintainer groups case info of Nothing -> notFound . toResponse $ "Package not found for " ++ display pkgname Just {} -> do void $ updateState distrosState $ DropPackage dname pkgname ok $ toResponse "Ok!" -- result: see-other response, or an error: not authenticated or not found (todo) distroPackagePut dpath = withDistroPackagePath dpath $ \dname pkgname _ -> lookPackageInfo $ \newPkgInfo -> do guardAuthorised_ [AnyKnownUser] --TODO: use the per-distro maintainer groups void $ updateState distrosState $ AddPackage dname pkgname newPkgInfo seeOther ("/distro/" ++ display dname ++ "/" ++ display pkgname) $ toResponse "Ok!" -- result: see-other response, or an error: not authentcated or bad request distroPostNew _ = lookDistroName $ \dname -> do guardAuthorised_ [AnyKnownUser] --TODO: use the per-distro maintainer groups success <- updateState distrosState $ AddDistro dname if success then seeOther ("/distro/" ++ display dname) $ toResponse "Ok!" else badRequest $ toResponse "Selected distribution name is already in use" distroPutNew dpath = withDistroNamePath dpath $ \dname -> do guardAuthorised_ [AnyKnownUser] --TODO: use the per-distro maintainer groups _success <- updateState distrosState $ AddDistro dname -- it doesn't matter if it exists already or not ok $ toResponse "Ok!" -- result: ok repsonse or not-found error distroPackageListPut dpath = withDistroPath dpath $ \dname _pkgs -> do guardAuthorised_ [AnyKnownUser] --TODO: use the per-distro maintainer groups lookCSVFile $ \csv -> case csvToPackageList csv of Nothing -> fail $ "Could not parse CSV File to a distro package list" Just list -> do void $ updateState distrosState $ PutDistroPackageList dname list ok $ toResponse "Ok!" withDistroNamePath :: DynamicPath -> (DistroName -> ServerPartE Response) -> ServerPartE Response withDistroNamePath dpath = require (return $ simpleParse =<< lookup "distro" dpath) withDistroPath :: DynamicPath -> (DistroName -> [(PackageName, DistroPackageInfo)] -> ServerPartE Response) -> ServerPartE Response withDistroPath dpath func = withDistroNamePath dpath $ \dname -> do isDist <- queryState distrosState (IsDistribution dname) case isDist of False -> notFound $ toResponse "Distribution does not exist" True -> do pkgs <- queryState distrosState (DistroStatus dname) func dname pkgs -- guards on the distro existing, but not the package withDistroPackagePath :: DynamicPath -> (DistroName -> PackageName -> Maybe DistroPackageInfo -> ServerPartE Response) -> ServerPartE Response withDistroPackagePath dpath func = withDistroNamePath dpath $ \dname -> do pkgname <- packageInPath dpath isDist <- queryState distrosState (IsDistribution dname) case isDist of False -> notFound $ toResponse "Distribution does not exist" True -> do pkgInfo <- queryState distrosState (DistroPackageStatus dname pkgname) func dname pkgname pkgInfo lookPackageInfo :: (DistroPackageInfo -> ServerPartE Response) -> ServerPartE Response lookPackageInfo func = do mInfo <- getDataFn $ do pVerStr <- look "version" pUriStr <- look "uri" case simpleParse pVerStr of Nothing -> mzero Just pVer -> return $ DistroPackageInfo pVer pUriStr case mInfo of (Left errs) -> ok $ toResponse $ unlines $ "Sorry, something went wrong there." : errs (Right pInfo) -> func pInfo lookDistroName :: (DistroName -> ServerPartE Response) -> ServerPartE Response lookDistroName func = withDataFn (look "distro") $ \dname -> case simpleParse dname of Just distro -> func distro _ -> badRequest $ toResponse "Not a valid distro name" getMaintainersGroup :: UserGroup -> DistroName -> IO (Maybe UserGroup) getMaintainersGroup admins dname = do isDist <- queryState distrosState (IsDistribution dname) case isDist of False -> return Nothing True -> return . Just $ UserGroup { groupDesc = maintainerGroupDescription dname , queryUserGroup = queryState distrosState $ GetDistroMaintainers dname , addUserToGroup = updateState distrosState . AddDistroMaintainer dname , removeUserFromGroup = updateState distrosState . RemoveDistroMaintainer dname , groupsAllowedToAdd = [admins] , groupsAllowedToDelete = [admins] } maintainerGroupDescription :: DistroName -> GroupDescription maintainerGroupDescription dname = nullDescription { groupTitle = "Maintainers" , groupEntity = Just (str, Just $ "/distro/" ++ display dname) , groupPrologue = "Maintainers for a distribution can map packages to it." } where str = display dname -- TODO: This calls parseCSV rather that importCSV -- not sure if that -- matters (in particular, importCSV chops off the last, extranenous, -- null entry that parseCSV adds) lookCSVFile :: (CSVFile -> ServerPartE Response) -> ServerPartE Response lookCSVFile func = do fileContents <- expectCSV case parseCSV "PUT input" (unpackUTF8 fileContents) of Left err -> badRequest $ toResponse $ "Could not parse CSV File: " ++ show err Right csv -> func (CSVFile csv) packageListToCSV :: [(PackageName, DistroPackageInfo)] -> CSVFile packageListToCSV entries = CSVFile $ map (\(pn,DistroPackageInfo version url) -> [display pn, showVersion version, url]) entries csvToPackageList :: CSVFile -> Maybe [(PackageName, DistroPackageInfo)] csvToPackageList (CSVFile records) = mapM fromRecord records where fromRecord [packageStr, versionStr, uri] = do package <- simpleParse packageStr version <- simpleParse versionStr return (package, DistroPackageInfo version uri) fromRecord _ = fail $ "Invalid distribution record"
ocharles/hackage-server
Distribution/Server/Features/Distro.hs
bsd-3-clause
11,883
0
23
2,969
2,718
1,411
1,307
200
11
{-# LANGUAGE BangPatterns, Rank2Types, UnboxedTuples #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Data.Text.Private -- Copyright : (c) 2011 Bryan O'Sullivan -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : GHC module Data.Text.Private ( runText , span_ ) where import Control.Monad.ST (ST, runST) import Data.Text.Internal (Text(..), textP) import Data.Text.Unsafe (Iter(..), iter) import qualified Data.Text.Array as A --LIQUID --LIQUID FIXME: the original type used unboxed tuples, (# Text, Text #) {-@ span_ :: (Char -> Bool) -> t:Text -> ( TextLE t, TextLE t ) @-} span_ :: (Char -> Bool) -> Text -> ( Text, Text ) span_ p t@(Text arr off len) = ( hd,tl ) where hd = textP arr off k tl = textP arr (off+k) (len-k) !k = loop len 0 --LIQUID loop !i | i < len && p c = loop (i+d) --LIQUID | otherwise = i --LIQUID where Iter c d = iter t i {- LIQUID WITNESS -} loop (d :: Int) !i | i < len = let Iter c d' = iter t i in if p c then loop (d-d') (i+d') else i | otherwise = i {-# INLINE span_ #-} {-@ runText :: (forall s. (m:A.MArray s -> MAValidO m -> ST s Text) -> ST s Text) -> Text @-} runText :: (forall s. (A.MArray s -> Int -> ST s Text) -> ST s Text) -> Text runText act = runST (act $ \ !marr !len -> do arr <- A.unsafeFreeze marr return $! textP arr 0 len) {-# INLINE runText #-}
mightymoose/liquidhaskell
benchmarks/text-0.11.2.3/Data/Text/Private.hs
bsd-3-clause
1,617
0
13
522
390
217
173
24
2
module Poly0 () where import Language.Haskell.Liquid.Prelude myabs x = if x `gt` 0 then x else 0 `minus` x ---------------------------------------------------------- myid3 x y = y x = choose 0 prop_id6 = liquidAssertB (x' `geq` 0) where x' = myid3 [] $ myabs x
mightymoose/liquidhaskell
tests/pos/poly2.hs
bsd-3-clause
275
0
9
57
97
56
41
7
2
module UnitTests.Distribution.Client.Targets ( tests ) where import Distribution.Client.Targets (UserConstraint (..), readUserConstraint) import Distribution.Compat.ReadP (ReadP, readP_to_S) import Distribution.Package (PackageName (..)) import Distribution.ParseUtils (parseCommaList) import Distribution.Text (parse) import Test.Tasty import Test.Tasty.HUnit import Data.Char (isSpace) tests :: [TestTree] tests = [ testCase "readUserConstraint" readUserConstraintTest , testCase "parseUserConstraint" parseUserConstraintTest , testCase "readUserConstraints" readUserConstraintsTest ] readUserConstraintTest :: Assertion readUserConstraintTest = assertEqual ("Couldn't read constraint: '" ++ constr ++ "'") expected actual where pkgName = "template-haskell" constr = pkgName ++ " installed" expected = UserConstraintInstalled (PackageName pkgName) actual = let (Right r) = readUserConstraint constr in r parseUserConstraintTest :: Assertion parseUserConstraintTest = assertEqual ("Couldn't parse constraint: '" ++ constr ++ "'") expected actual where pkgName = "template-haskell" constr = pkgName ++ " installed" expected = [UserConstraintInstalled (PackageName pkgName)] actual = [ x | (x, ys) <- readP_to_S parseUserConstraint constr , all isSpace ys] parseUserConstraint :: ReadP r UserConstraint parseUserConstraint = parse readUserConstraintsTest :: Assertion readUserConstraintsTest = assertEqual ("Couldn't read constraints: '" ++ constr ++ "'") expected actual where pkgName = "template-haskell" constr = pkgName ++ " installed" expected = [[UserConstraintInstalled (PackageName pkgName)]] actual = [ x | (x, ys) <- readP_to_S parseUserConstraints constr , all isSpace ys] parseUserConstraints :: ReadP r [UserConstraint] parseUserConstraints = parseCommaList parse
randen/cabal
cabal-install/tests/UnitTests/Distribution/Client/Targets.hs
bsd-3-clause
2,010
0
12
434
454
252
202
41
1
{-# LANGUAGE QuasiQuotes #-} module C.Compiler (compileTree) where import qualified C.Expr as C import C.Expr (Op) import Data.Hashable (hash) import Data.Maybe import Asm.QQ import Asm.Expr (Register(..), Instruction(..), Condition(..), litNum, litLbl, reg) import qualified Asm.Parser as A import qualified Asm.Expr as A import qualified Data.Map.Strict as Map type Id = String data VarDef = VarDef Id Int Int deriving (Eq) data FuncDef = FuncDef Id [VarDef] [VarDef] [C.Expr] deriving (Eq) --TODO Transform C AST to a bunch of these things data Expr = FuncCall FuncDef [Expr] | Var VarDef | Num Int | String String | Binop Op Expr Expr | Asm String | Nop data Ctx = Ctx [FuncDef] [VarDef] sizeOf = C.sizeOf; regLsb :: Register -> Register regLsb r | r <= L = r | r == BC = C | r == DE = E | r == HL = L regMsb :: Register -> Register regMsb r | r == BC = B | r == DE = D | r == HL = H asmHeader :: String -> [A.Expr] asmHeader "ti84pcse" = [asm| .org UserMem - 2 .db tExtTok, tAsm84CCmp ld ix, saveSScreen + 300h call main ret |] asmHeader "ti83p" = [asm| .org UserMem - 2 .db t2ByteTok, tAsmCmp ld ix, saveSScreen + 300h call main ret |] strLabel :: String -> String strLabel str = "STRCONST_" ++ show (toInteger (hash str) + (2^64)) localVars :: [C.Expr] -> [VarDef] localVars xprs = reverse $ varTable xprs [] 0 where varTable [] vars _ = vars varTable (C.VarDef name vtype:xprs) vars offs = varTable xprs (VarDef ('_':name) (sizeOf vtype) offs:vars) (offs + sizeOf vtype) varTable (expr:xprs) vars offs = varTable xprs vars offs varDefLocal :: VarDef -> A.Expr varDefLocal (VarDef name _ offs) = A.Define name $ litNum offs storeRegLocal :: Register -> VarDef -> [A.Expr] storeRegLocal src (VarDef var size _) | size == 1 && src > L = [lsb $ regLsb src] | src == HL = [lsb L, msb H] | src == DE = [lsb E, msb D] | src == BC = [lsb C, msb B] | src <= L = lsb src:[zeroMsb | size == 2] | otherwise = [] where lsb r = A.Instr LD [A.RegIndex IX $ litLbl var, reg r] msb r = A.Instr LD [A.RegIndex IX $ A.Binop A.Add (litLbl var) (litNum 1), reg r] zeroMsb = A.Instr LD [A.RegIndex IX $ litNum 1, litNum 0] loadRegLocal :: Register -> VarDef -> [A.Expr] loadRegLocal src (VarDef var size _) | size == 1 && src > L = [lsb $ regLsb src, zero $ regMsb src] | src == HL = [lsb L, msb H] | src == DE = [lsb E, msb D] | src == BC = [lsb C, msb B] | src <= L = [lsb src] | otherwise = [] where lsb r = A.Instr LD [reg r, A.RegIndex IX $ litLbl var] msb r = A.Instr LD [reg r, A.RegIndex IX $ A.Binop A.Add (litLbl var) (litNum 1)] zero r = A.Instr LD [reg r, litNum 0] findVar' :: [VarDef] -> String -> VarDef findVar' vars x = head $ filter (\(VarDef nm _ _) -> x == nm) vars findFunc :: [FuncDef] -> String -> FuncDef findFunc fns x = head $ filter (\(FuncDef nm _ _ _) -> x == nm) fns convExpr :: Ctx -> C.Expr -> Expr convExpr ctx@(Ctx fns _) (C.FuncCall nm args) = FuncCall (findFunc fns nm) (map (convExpr ctx) args) convExpr (Ctx _ vars) (C.Var nm) = Var $ findVar' vars ('_':nm) convExpr _ (C.Num x) = Num x convExpr _ (C.String x) = String x convExpr ctx@(Ctx _ _) (C.Binop op x y) = Binop op (convExpr ctx x) (convExpr ctx y) convExpr _ (C.Asm str) = Asm str convExpr _ _ = Nop convFunc :: C.Expr -> FuncDef convFunc (C.FuncDef nm ret fnargs body) = FuncDef nm args vars body where vars = localVars (fnargs ++ body) args = take (length fnargs) vars convFuncBody :: Ctx -> [C.Expr] -> [Expr] convFuncBody ctx = map (convExpr ctx) funcAsm :: (FuncDef, [Expr]) -> [A.Expr] funcAsm (FuncDef name args vars _, body) = prologue ++ varDefs ++ argDefs ++ concatMap exprAsm body ++ epilogue where label = name negVarSize = sum [s | (VarDef _ s _) <- vars] * (-1) varDefs = map varDefLocal vars argDefs = concat $ zipWith storeRegLocal [HL,DE,BC] args prologue = A.LabelDef label : if null vars then [] else [asm|push ix \ ld de,@{negVarSize} \ add ix,de|] epilogue = if null vars then [asm|ret|] else [asm|pop ix \ ret|] exprAsm :: Expr -> [A.Expr] exprAsm (FuncCall (FuncDef name _ _ _) args) = ldArgs args ++ [asm|call @{name}|] where ldArgs [] = [] ldArgs (x:[]) = exprAsm x ldArgs (x:y:[]) = concat [ exprAsm y, [asm|push hl|], exprAsm x, [asm|pop de|] ] ldArgs (x:y:z:[]) = concat [ exprAsm z, [asm|push hl|], exprAsm y, [asm|push hl|], exprAsm x, [asm|pop de \ pop bc|] ] ldArgs _ = [] exprAsm (Binop C.Assign (Var var) xpr) = exprAsm xpr ++ storeRegLocal HL var exprAsm (Binop C.Add x y) = concat [ exprAsm y, [asm|push hl|], exprAsm x, [asm|pop de \ add hl,de|] ] exprAsm (Binop C.Sub x y) = concat [ exprAsm y, [asm|push hl|], exprAsm x, [asm|pop de \ or a \ sbc hl,de|] ] exprAsm (Asm str) = case A.parseText "" str of Left err -> error err Right ast -> ast exprAsm (Var var) = loadRegLocal HL var exprAsm (Num x) = [asm|ld hl,@{x}|] exprAsm (String str) = [asm|ld hl,@{str}|] exprAsm (Binop op x y) = [] exprAsm x = [] compileTree :: [C.Expr] -> [A.Expr] compileTree tree = asmHeader "ti84pcse" ++ concatMap funcAsm funcs where funcDefs = map convFunc [fn | fn@(C.FuncDef {}) <- tree] funcs = [(fn, convFuncBody (Ctx funcDefs vs) body) | fn@(FuncDef _ _ vs body) <- funcDefs]
unknownloner/calccomp
C/Compiler.hs
mit
5,914
0
14
1,806
2,530
1,334
1,196
138
6
{-# LANGUAGE ExplicitForAll #-} -- We export this stuff separately so we don't clutter up the -- API of the Graphics.Gloss module. -- | This game mode lets you manage your own input. Pressing ESC will still abort the program, -- but you don't get automatic pan and zoom controls like with `displayInWindow`. module Graphics.Gloss.Interface.Pure.Game ( module Graphics.Gloss.Data.Display , module Graphics.Gloss.Data.Picture , module Graphics.Gloss.Data.Color , play , Event(..), Key(..), SpecialKey(..), MouseButton(..), KeyState(..), Modifiers(..)) where import Graphics.Gloss.Data.Display import Graphics.Gloss.Data.Picture import Graphics.Gloss.Data.Color import Graphics.Gloss.Internals.Interface.Game import Graphics.Gloss.Internals.Interface.Backend -- | Play a game in a window. play :: forall world . Display -- ^ Display mode. -> Color -- ^ Background color. -> Int -- ^ Number of simulation steps to take for each second of real time. -> world -- ^ The initial world. -> (world -> Picture) -- ^ A function to convert the world a picture. -> (Event -> world -> world) -- ^ A function to handle input events. -> (Float -> world -> world) -- ^ A function to step the world one iteration. -- It is passed the period of time (in seconds) needing to be advanced. -> IO () play display backColor simResolution worldStart worldToPicture worldHandleEvent worldAdvance = playWithBackendIO defaultBackendState display backColor simResolution worldStart (return . worldToPicture) (\event world -> return $ worldHandleEvent event world) (\time world -> return $ worldAdvance time world) True
gscalzo/HaskellTheHardWay
gloss-try/gloss-master/gloss/Graphics/Gloss/Interface/Pure/Game.hs
mit
1,898
2
15
536
289
181
108
30
1
module Alpha ( runMain , other ) where import Beta import Gamma import Delta.Epsilon import Delta.Zeta runMain = do putStrLn (show other) other = [1, 2, 3, 4, 5] |> head . groupBy (\a b -> a `mod` 2 == b `mod` 2) |> sum
Chatanga/codingame-hs
data/Alpha.hs
mit
245
0
12
70
106
62
44
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------ module Graphics.DetailGen.Monad ( -- * Shape Shape (..) -- * Detail , Detail (..) -- * DetailGen , DetailGen , runDetailGen , detail , branch , pureBranch , done ) where ------------------------------------------------------------------------------ import Control.Applicative import Control.Monad.Free import Data.Tree ------------------------------------------------------------------------------ import Graphics.DetailGen.PointSelection import Graphics.DetailGen.Vec3 ------------------------------------------------------------------------------ data Shape = Cube | Cylinder | Sphere deriving (Show) ------------------------------------------------------------------------------ data Detail = Detail { detailShape :: Shape , detailSelection :: PointSelection , detailGScale :: Vec3 , detailPScale :: Vec3 , detailUp :: Vec3 } deriving (Show) ------------------------------------------------------------------------------ data DetailBranch g = Apply Detail [g] | Branch [g] deriving (Show) instance Functor DetailBranch where fmap f (Apply d gs) = Apply d $ map f gs fmap f (Branch gs) = Branch $ map f gs ------------------------------------------------------------------------------ newtype DetailGen a = DetailGen { runDetailGen' :: Free DetailBranch a } deriving (Functor, Applicative, Monad) mk :: DetailBranch (Free DetailBranch a) -> DetailGen a mk = DetailGen . Free ------------------------------------------------------------------------------ detail :: Shape -> PointSelection -> Vec3 -> Vec3 -> Vec3 -> DetailGen () detail s sp gs ps u = mk $ Apply (Detail s sp gs ps u) [pure ()] ------------------------------------------------------------------------------ branch :: [DetailGen a] -> DetailGen a branch = mk . Branch . map runDetailGen' ------------------------------------------------------------------------------ pureBranch :: [a] -> DetailGen a pureBranch = branch . map (DetailGen . Pure) ------------------------------------------------------------------------------ done :: DetailGen () done = mk $ Branch [] ------------------------------------------------------------------------------ runDetailGen :: DetailGen () -> Forest Detail runDetailGen = unFree . runDetailGen' where unFree (Pure _) = [] unFree (Free b) = unBranch b unBranch (Apply d fs) = [Node d (concatMap unFree fs)] unBranch (Branch fs) = concatMap unFree fs
zmthy/incidental-detail
src/Graphics/DetailGen/Monad.hs
mit
2,642
0
11
443
591
327
264
50
3
module Exercise where subset :: Ord a => [a] -> [a] -> Bool subset sub set = and $ map (\x -> x `elem` set) sub
tcoenraad/functioneel-programmeren
2014/opg2b.hs
mit
113
0
9
27
63
35
28
3
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Test.Tasty.KAT.FileLoader -- License : MIT -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : Good -- -- extra loaders helpers -- module Test.Tasty.KAT.FileLoader ( katLoader , katLoaderSimple -- * generic helpers on TestResource , mapTestUnitValues , mapTestUnits -- * common helpers on TestResource , mapTestUnitValuesBase64 , mapTestUnitValuesBase16 -- * common value decoding helpers , valueUnbase16 , valueUnbase64 , valueInteger , valueHexInteger -- * associated hierarchy of KAT types , TestResource , TestGroup , TestUnit ) where import Control.Arrow (second) import Data.Bits import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Unsafe as B import Data.ByteString (ByteString) import Data.ByteString.Char8 () -- for Bytestring OverloadedString instance on old ghc import Data.List import Data.Word import Foreign.Storable import Foreign.Ptr import Test.Tasty.KAT.Internal type TestResource a = [(String, TestGroup a)] type TestGroup a = [TestUnit a] type TestUnit a = [a] -- | From a simple KAT file, extract -- -- * lines starting by #, are assumed to be comment -- -- format should be the following: -- -- > skipped .. -- > skipped .. -- > [group1] -- > -- > f1= v1 -- > f2= v2 -- > ... -- > -- > f1= v3 -- > f2= v4 -- > ... -- > -- > [group2] -- > ... katLoaderSimple :: [String] -> TestResource (String, String) katLoaderSimple = katLoader '=' "#" katLoader :: Char -- ^ key value separator, e.g. '=' -> String -- ^ line comment, e.g. "--" "#" -> [String] -- ^ input lines -> TestResource (String, String) katLoader kvSep lineComment = map (second (map (map kv))) . removeEmpty . map (second (splitWhen null)) -- split a group of lines into a group of tests . groupify "" [] . map noTrailing . filter (not . isComment) where isComment = isPrefixOf lineComment removeEmpty = filter ((/= []) . snd) groupify :: String -> [String] -> [String] -> [(String, [String])] groupify gname acc [] = [(gname, reverse acc)] groupify gname acc (x:xs) = case getGroupHeader x of Just hdr -> (gname, reverse acc) : groupify hdr [] xs Nothing -> groupify gname (x:acc) xs kv :: String -> (String, String) kv s = case break (== kvSep) s of (k, c:v) | c == kvSep -> (stripSpaces k, stripSpaces v) | otherwise -> (stripSpaces k, stripSpaces v) (_, _) -> (s, "") -- no error handling .. getGroupHeader :: String -> Maybe String getGroupHeader s | isPrefixOf "[" s && isSuffixOf "]" s = Just . drop 1 . reverse . drop 1 . reverse $ s | otherwise = Nothing noTrailing = reverse . dropWhile (== ' ') . reverse splitWhen :: (a -> Bool) -> [a] -> [[a]] splitWhen p s = case dropWhile p s of [] -> [] s' -> w : splitWhen p s'' where (w, s'') = break p s' stripSpaces = dropWhile (== ' ') . reverse . dropWhile (== ' ') . reverse mapTestUnitValues :: (String -> a) -> TestResource (String, String) -> TestResource (String,a) mapTestUnitValues f = map (second (map (map (\(k,v) -> (k, f v))))) mapTestUnits :: (TestUnit (String,a) -> TestUnit b) -> TestResource (String,a) -> TestResource b mapTestUnits f = map (second (map f)) mapTestUnitValuesBase64 :: TestResource (String, String) -> TestResource (String, ByteString) mapTestUnitValuesBase64 = mapTestUnitValues valueUnbase64 mapTestUnitValuesBase16 :: TestResource (String, String) -> TestResource (String, ByteString) mapTestUnitValuesBase16 = mapTestUnitValues valueUnbase16 -- expect an ascii string. valueUnbase64 :: String -> ByteString valueUnbase64 s | (length s `mod` 4) /= 0 = error ("decodiong base64 not proper length: " ++ s) | otherwise = unsafeCreateUptoN maxSz $ \ptr -> do szRemove <- loop s ptr return (maxSz - szRemove) where maxSz = (length s `div` 4) * 3 loop [] _ = return 0 loop (w:x:'=':'=':[]) ptr = do let w' = rset w x' = rset x poke ptr ((w' `shiftL` 2) .|. (x' `shiftR` 4)) return 2 loop (w:x:y:'=':[]) ptr = do let w' = rset w x' = rset x y' = rset y poke ptr ((w' `shiftL` 2) .|. (x' `shiftR` 4)) poke (ptr `plusPtr` 1) ((x' `shiftL` 4) .|. (y' `shiftR` 2)) return 1 loop (w:x:y:z:r) ptr = do let w' = rset w x' = rset x y' = rset y z' = rset z poke ptr ((w' `shiftL` 2) .|. (x' `shiftR` 4)) poke (ptr `plusPtr` 1) ((x' `shiftL` 4) .|. (y' `shiftR` 2)) poke (ptr `plusPtr` 2) ((y' `shiftL` 6) .|. z') loop r (ptr `plusPtr` 3) loop _ _ = error ("internal error in base64 decoding") rset :: Char -> Word8 rset c | cval <= 0xff = B.unsafeIndex rsetTable cval | otherwise = 0xff where cval = fromEnum c -- dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" rsetTable = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x3e\xff\xff\xff\x3f\ \\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\xff\xff\xff\xff\xff\xff\ \\xff\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\ \\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\xff\xff\xff\xff\xff\ \\xff\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\ \\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\ \\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" -- expect an ascii string. valueUnbase16 :: String -> ByteString valueUnbase16 s | odd (length s) = error ("decoding base16 not proper length: " ++ s) | otherwise = B.unsafeCreate (length s `div` 2) (loop s) where loop [] _ = return () loop (x1:x2:xs) ptr = do poke ptr ((unhex x1 `shiftL` 4) .|. unhex x2) loop xs (ptr `plusPtr` 2) loop _ _ = error "internal error in base16 decoding" unhex :: Char -> Word8 unhex c | c >= '0' && c <= '9' = fromIntegral (fromEnum c - fromEnum '0') | c >= 'a' && c <= 'f' = 10 + fromIntegral (fromEnum c - fromEnum 'a') | c >= 'A' && c <= 'F' = 10 + fromIntegral (fromEnum c - fromEnum 'A') | otherwise = error ("invalid base16 character " ++ show c ++ " in " ++ show s) valueInteger :: String -> Integer valueInteger s = read s valueHexInteger :: String -> Integer valueHexInteger s = read ("0x" ++ s)
vincenthz/tasty-kat
Test/Tasty/KAT/FileLoader.hs
mit
8,040
0
16
2,517
2,102
1,125
977
132
5
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE RankNTypes #-} module TowerIntersect where import Data.Hashable (Hashable) import Data.Holmes import Data.JoinSemilattice.Intersect (toList) import Data.List (transpose) import Data.Maybe (mapMaybe) import Data.Propagator import Data.Typeable (Typeable) import GHC.Generics (Generic) import Tower hiding (showSolution) -- | Value type for 4x4 tower defence puzzle. -- -- We allow 0..4 so that we can compare with 0 -- as an attacker count. newtype Val4 = V4 Int deriving stock (Show, Eq, Ord, Generic) deriving anyclass (Hashable) instance Num Val4 where fromInteger = toEnum . fromInteger -- this is not a valid Num instance, we just want to use -- it for counting (V4 a) + (V4 b) = if a + b > 4 then V4 4 else V4 (a + b) instance Enum Val4 where toEnum n | n < 0 || n > 4 = error $ "toEnum Val4 out of bounds: " ++ show n | otherwise = V4 n fromEnum v@(V4 m) | m < 0 || m > 4 = error $ "fromEnum Val4 out of bounds: " ++ show v | otherwise = m instance Bounded Val4 where minBound = toEnum 0 maxBound = toEnum 4 {- Encoding the board for Holmes -} intersectConfig :: Board -> Config Holmes (Intersect (Cell Val4)) intersectConfig (Board n) = case n of 4 -> (n * n) `from` [Cell v t | v <- [1 .. 4], t <- [False, True]] -- 1..3 fits in Val4... 3 -> (n * n) `from` [Cell v t | v <- [1 .. 3], t <- [False, True]] 2 -> (n * n) `from` [Cell v t | v <- [1 .. 2], t <- [False, True]] 1 -> (n * n) `from` [Cell v t | v <- [1 .. 1], t <- [False, True]] _ -> error "board size not implemented" {- Interacting with the solver -} showSolution :: (Show v, Bounded v, Enum v, Eq v) => Board -> [Intersect (Cell v)] -> IO () showSolution board sol = case extractSol of Nothing -> putStrLn "invalid solution" Just s -> showSol s where extractSol = if length exacts == length sol then Just exacts else Nothing exacts = mapMaybe (fromDefined . toList) sol fromDefined [x] = Just x fromDefined _ = Nothing showSol ss = mapM_ showRow $ rows board ss showRow r = putStrLn $ concat $ map (show . value) $ r solve :: (Bounded v, Enum v, Ord v, Hashable v, Show v, Typeable v) => Board -> Config Holmes (Intersect (Cell v)) -> (forall m. MonadCell m => [Prop m (Intersect (Cell v))] -> Prop m (Intersect Bool)) -> IO () solve board config constraints = do s <- config `satisfying` constraints case s of Nothing -> putStrLn "no solution" Just sol -> showSolution board sol
robx/puzzles
towerdefence/src/TowerIntersect.hs
mit
2,605
0
18
615
1,005
528
477
63
5
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module DynamoDbEventStore.InMemoryDynamoTable (InMemoryDynamoTable , emptyDynamoTable , readDb , writeDb , updateDb , queryDb , scanNeedsPagingDb ) where import BasicPrelude import Control.Lens import qualified Data.HashMap.Strict as HM import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified DynamoDbEventStore.Constants as Constants import DynamoDbEventStore.EventStoreCommands import GHC.Natural data InMemoryDynamoTable = InMemoryDynamoTable { _inMemoryDynamoTableTable :: HM.HashMap Text (Map Int64 (Int, DynamoValues)) , _inMemoryDynamoTableNeedsPaging :: Set DynamoKey } deriving (Eq, Show) $(makeLenses ''InMemoryDynamoTable) emptyDynamoTable :: InMemoryDynamoTable emptyDynamoTable = InMemoryDynamoTable { _inMemoryDynamoTableTable = mempty , _inMemoryDynamoTableNeedsPaging = mempty} readDb :: DynamoKey -> InMemoryDynamoTable -> Maybe DynamoReadResult readDb key@DynamoKey{..} db = let entry = db ^. (inMemoryDynamoTableTable . at dynamoKeyKey . non mempty . at dynamoKeyEventNumber) buildReadResult (version, value) = DynamoReadResult { dynamoReadResultKey = key , dynamoReadResultVersion = version , dynamoReadResultValue = value } in buildReadResult <$> entry updateDb :: DynamoKey -> HashMap Text ValueUpdate -> InMemoryDynamoTable -> InMemoryDynamoTable updateDb key@DynamoKey{..} updates db = let entryLocation = inMemoryDynamoTableTable . at dynamoKeyKey . non mempty . at dynamoKeyEventNumber . _Just . _2 in over entryLocation setValues db & over inMemoryDynamoTableNeedsPaging updatePagingTable where updatePagingTable = case HM.lookup Constants.needsPagingKey updates of Nothing -> id (Just (ValueUpdateSet _)) -> Set.insert key (Just ValueUpdateDelete) -> Set.delete key setValues :: DynamoValues -> DynamoValues setValues initialValues = HM.foldrWithKey applyUpdate initialValues updates applyUpdate :: Text -> ValueUpdate -> DynamoValues -> DynamoValues applyUpdate k (ValueUpdateSet attribute) = HM.insert k attribute applyUpdate k ValueUpdateDelete = HM.delete k writeDb :: DynamoKey -> DynamoValues -> DynamoVersion -> InMemoryDynamoTable -> (DynamoWriteResult, InMemoryDynamoTable) writeDb key@DynamoKey{..} values version db = let entryLocation = inMemoryDynamoTableTable . at dynamoKeyKey . non mempty . at dynamoKeyEventNumber currentVersion = fst <$> db ^. entryLocation in writeVersion version currentVersion where entryNeedsPaging = HM.member Constants.needsPagingKey values writeVersion 0 Nothing = performWrite 0 writeVersion _newVersion Nothing = (DynamoWriteWrongVersion, db) writeVersion newVersion (Just currentVersion) | currentVersion == newVersion - 1 = performWrite newVersion | otherwise = (DynamoWriteWrongVersion, db) updatePagingTable = if entryNeedsPaging then Set.insert key else Set.delete key performWrite newVersion = let newEntry = (newVersion, values) entryLocation = inMemoryDynamoTableTable . at dynamoKeyKey . non mempty . at dynamoKeyEventNumber db' = set entryLocation (Just newEntry) db & over inMemoryDynamoTableNeedsPaging updatePagingTable in (DynamoWriteSuccess, db') queryDb :: QueryDirection -> Text -> Natural -> Maybe Int64 -> InMemoryDynamoTable -> [DynamoReadResult] queryDb direction streamId maxEvents startEvent db = let rangeItems = db ^. inMemoryDynamoTableTable . at streamId . non mempty items = case (direction, startEvent) of (QueryDirectionForward, Nothing) -> Map.toAscList rangeItems (QueryDirectionForward, Just startEventNumber) -> rangeItems & Map.split startEventNumber & snd & Map.toAscList (QueryDirectionBackward, Nothing) -> Map.toDescList rangeItems (QueryDirectionBackward, Just startEventNumber) -> rangeItems & Map.split startEventNumber & fst & Map.toDescList itemsCutOff = take (fromIntegral maxEvents) items toReadResult (eventNumber, (currentVersion, value)) = DynamoReadResult { dynamoReadResultKey = DynamoKey streamId eventNumber , dynamoReadResultVersion = currentVersion , dynamoReadResultValue = value } in toReadResult <$> itemsCutOff scanNeedsPagingDb :: InMemoryDynamoTable -> [DynamoKey] scanNeedsPagingDb = view $ inMemoryDynamoTableNeedsPaging . to Set.toAscList
adbrowne/dynamodb-eventstore
dynamodb-eventstore/tests/DynamoDbEventStore/InMemoryDynamoTable.hs
mit
4,778
0
16
1,081
1,121
588
533
-1
-1
{- HAAP: Haskell Automated Assessment Platform This module provides the @CodeWorld@ plugin to compile _CodeWorld_ animations (<https://github.com/google/codeworld>) to HTML webpages. -} {-# LANGUAGE UndecidableInstances, TypeOperators, FlexibleContexts, FlexibleInstances, TypeFamilies, MultiParamTypeClasses, EmptyDataDecls, OverloadedStrings #-} module HAAP.Web.Graphics.CodeWorld where import HAAP.Core import HAAP.IO import HAAP.Compiler.GHCJS import HAAP.Utils import HAAP.Web.Hakyll import HAAP.Pretty import HAAP.Plugin import HAAP.Shelly import Control.Monad import Control.Monad.Reader as Reader --import Control.Monad.Except import Control.Exception.Safe import Control.Monad.Morph import Data.Foldable import Data.Either import Data.String import Data.Traversable import Data.Default import Data.Proxy import qualified Data.Text as T import System.FilePath import System.Directory import System.Process import qualified Shelly as Sh import GHC.Stack --import Codec.Picture.Metadata --import Codec.Picture data CodeWorld instance HaapPlugin CodeWorld where type PluginI CodeWorld = CodeWorldArgs type PluginO CodeWorld = () type PluginT CodeWorld = ReaderT CodeWorldArgs type PluginK CodeWorld t m = (MonadIO m) usePlugin getArgs m = do args <- getArgs x <- mapHaapMonad (flip Reader.runReaderT args . getComposeT) m return (x,()) data CWTemplate = CWGame CWGameType | CWDraw CWDrawType T.Text data CWGameType = CWGameFullscreen | CWGameConsole data CWDrawType = CWDrawFixed | CWDrawButton | CWDrawFullscreen data CodeWorldArgs = CodeWorldArgs { cwExecutable :: Either FilePath FilePath -- graphical web applications to compile with ghcjs and codeworld libraries, or a link to an existing runmain.js file , cwTitle :: T.Text , cwTemplate :: CWTemplate , cwGHCJS :: GHCJSArgs , cwIO :: IOArgs , cwHtmlPath :: FilePath -- relative path to the project to store codeworld results , cwImages :: [(String,FilePath)] -- a list of html identifiers and respective local files for loading images , cwAudios :: [(String,FilePath)] , cwExtras :: [FilePath] -- extra files to copy to the js folder } useAndRunCodeWorld :: (MonadIO m,HasPlugin Hakyll t m) => CodeWorldArgs -> Haap t m FilePath useAndRunCodeWorld args = usePlugin_ (return args) $ runCodeWorld runCodeWorld :: (MonadIO m,HasPlugin Hakyll t m,HasPlugin CodeWorld t m) => Haap t m FilePath runCodeWorld = do hp <- getHakyllP cw <- liftHaap $ liftPluginProxy (Proxy::Proxy CodeWorld) $ Reader.ask let cwerrorpath = addExtension (cwHtmlPath cw) "html" orErrorHakyllPage cwerrorpath cwerrorpath $ do tmp <- getProjectTmpPath let (tpltfile,textmessage) = case cwTemplate cw of CWGame CWGameConsole -> ("templates/cw-game-console.html","") CWGame CWGameFullscreen -> ("templates/cw-game-fullscreen.html","") CWDraw CWDrawFixed msg -> ("templates/cw-draw-fixed.html",msg) CWDraw CWDrawButton msg -> ("templates/cw-draw-button.html",msg) CWDraw CWDrawFullscreen msg -> ("templates/cw-draw-fullscreen.html",msg) -- compile files with ghcjs let ghcjs = cwGHCJS cw let io = cwIO cw let stack = maybe callStack id (ioCallStack io) (destdir,destfolder) <- case cwExecutable cw of Left cwexec -> do let exec = takeFileName cwexec let destdir = dropExtension (cwHtmlPath cw </> exec) let destfolder = addExtension destdir "jsexe" return (destdir,destfolder) Right htmldir -> return (cwHtmlPath cw,cwHtmlPath cw) res <- case cwExecutable cw of Left cwexec -> orIOResult $ runBaseShWith' (io) $ do let (dir,exec) = splitFileName cwexec let ghcjs' = ghcjs { ghcjsMake = True, ghcjsArgs = ghcjsArgs ghcjs ++ ["-o",dirToRoot dir </> tmp </> destdir], ghcjsIO = io } Sh.mkdir_p (fromString $ tmp </> destfolder) forM (cwExtras cw) $ \extra -> do let extraname = takeFileName extra shCp extra (tmp </> destfolder </> extraname) shCd dir --Sh.setenv "GHC_PACKAGE_PATH" (T.pack $ concatPaths ghcpackagedbs) --Sh.setenv "GHCJS_PACKAGE_PATH" (T.pack $ concatPaths ghcjspackagedbs) shGhcjsWith ghcjs' [exec] otherwise -> do let precompiled = "Pre-compiled at " <> prettyText (cwExecutable cw) return $ IOResult 0 precompiled precompiled let images = (cwImages cw) let audios = (cwAudios cw) if resOk res then addMessageToError (prettyText res) $ do hakyllFocus ["templates",tmp </> destfolder] $ hakyllRules $ do let message = text "=== Compiling ===" $+$ pretty res $+$ text "=== Running ===" match (fromGlob $ tmp </> destfolder </> "*.html") $ do route $ relativeRoute tmp `composeRoutes` funRoute (hakyllRoute hp) compile $ getResourceString >>= hakyllCompile hp let auxFiles = fromGlob (tmp </> destfolder </> "*") when (isLeft $ cwExecutable cw) $ match auxFiles $ do route $ relativeRoute tmp `composeRoutes` funRoute (hakyllRoute hp) compile copyFileCompiler let runpath = case cwExecutable cw of Left _ -> "." Right html -> dirToRoot destfolder </> html create [fromFilePath $ destfolder </> "run.html"] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp) compile $ do let mkImg s = s let imgCtx = field "imgid" (return . fst . itemBody) `mappend` constField "projectpath" (dirToRoot destfolder) `mappend` field "imgfile" (return . mkImg . snd . itemBody) `mappend` constField "runpath" (runpath) let audioCtx = field "audioid" (return . fst . itemBody) `mappend` constField "projectpath" (dirToRoot destfolder) `mappend` field "audiofile" (return . mkImg . snd . itemBody) `mappend` field "audiotype" (return . filter (/='.') . takeExtension . snd . itemBody) `mappend` constField "runpath" (runpath) let cwCtx = constField "title" (T.unpack $ cwTitle cw) `mappend` constField "projectpath" (dirToRoot destfolder) `mappend` constField "runpath" runpath `mappend` constField "message" (renderDocString message) `mappend` constField "textmessage" (T.unpack textmessage) `mappend` listField "images" imgCtx (mapM makeItem images) `mappend` listField "audios" audioCtx (mapM makeItem audios) makeItem "" >>= loadAndApplyHTMLTemplate tpltfile cwCtx >>= hakyllCompile hp return (hakyllRoute hp $ destfolder </> "run.html") else throw $ HaapException stack $ prettyText res instance HaapMonad m => HasPlugin CodeWorld (ReaderT CodeWorldArgs) m where liftPlugin = id instance (HaapStack t2 m) => HasPlugin CodeWorld (ComposeT (ReaderT CodeWorldArgs) t2) m where liftPlugin m = ComposeT $ hoist' lift m --loadCodeWorldImages :: (MonadIO m,HaapStack t m) => [(String,FilePath)] -> Haap t m [(String,FilePath),(Int,Int)] --loadCodeWorldImages xs = forM xs $ \(n,fp) -> do -- e <- runBaseIO $ readImageWithMetadata fp -- case e of -- Left err -> throwError $ HaapException $ "failed loading codeworld image" ++ show fp ++ "\n" ++ pretty err -- Right (_,md) -> -- mbw <- Juicy.lookup Width md -- w <- case mbw of -- Nothing -> throwError $ HaapException $ "failed loading codeworld image width" ++ show fp ++ "\n" ++ pretty err -- Just w -> return w -- mbh <- Juicy.lookup Height md -- h <- case mbh of -- Nothing -> throwError $ HaapException $ "failed loading codeworld image height" ++ show fp ++ "\n" ++ pretty err -- Just h -> return h -- return (w,h) -- return ((n,fp),(w,h))
hpacheco/HAAP
src/HAAP/Web/Graphics/CodeWorld.hs
mit
9,049
0
36
2,996
1,926
990
936
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.Box.SelectionContainer.Tab ( -- * The Tab widget TabWidget, -- * Constructor mkTabWidget) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when, join) import Data.Aeson import Data.HashMap.Strict as HM import Data.IORef (newIORef) import qualified Data.Scientific as Sci import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'TabWidget' represents a Tab widget from IPython.html.widgets. type TabWidget = IPythonWidget TabType -- | Create a new box mkTabWidget :: IO TabWidget mkTabWidget = do -- Default properties, with a random uuid uuid <- U.random let widgetState = WidgetState $ defaultSelectionContainerWidget "TabView" stateIO <- newIORef widgetState let box = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen box $ toJSON widgetState -- Return the widget return box instance IHaskellDisplay TabWidget where display b = do widgetSendView b return $ Display [] instance IHaskellWidget TabWidget where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "selected_index" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (Number num) = HM.lookup key2 dict2 setField' widget SelectedIndex (Sci.coefficient num) triggerChange widget
beni55/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Box/SelectionContainer/Tab.hs
mit
1,876
0
13
446
383
211
172
42
1
{-# LANGUAGE Arrows #-} module Core.Log( -- | Logging in game monad logInfo , logWarn , logError -- | Logging within game wire , logInfoA , logWarnA , logErrorA -- | Logging discrete events , logInfoE , logWarnE , logErrorE -- | Tracing events (debug) , traceEvent , traceEventShow ) where import Core.Monad import Control.Wire.Unsafe.Event import Control.Monad.State.Strict import qualified Data.Sequence as S import Prelude hiding (id, (.)) import FRP.Netwire import Data.Text (Text) import TextShow -- | Putting message into console logInfo, logWarn, logError, rawLog :: Text -> GameMonadG e () logInfo = rawLog . ("Info: " <>) logWarn = rawLog . ("Warn: " <>) logError = rawLog . ("Error: " <>) rawLog s = do cntx <- get put $ cntx { gameLogMessages = s S.<| gameLogMessages cntx } -- | Putting message into console, arrow version logInfoA, logWarnA, logErrorA :: GameWireG e Text () logInfoA = liftGameMonad1 logInfo logWarnA = liftGameMonad1 logWarn logErrorA = liftGameMonad1 logError -- | Putting message int console when an event fires logInfoE, logWarnE, logErrorE :: GameWireG e (Event Text) () logInfoE = logRawE logInfoA logWarnE = logRawE logWarnA logErrorE = logRawE logErrorA -- | Transforms logger that spams every step to event logger logRawE :: GameWireG e Text () -> GameWireG e (Event Text) () logRawE logger = proc ev -> case ev of NoEvent -> forceNF -< () Event msg -> logger -< msg -- | Prints occurences of event to log traceEventShow :: TextShow a => GameWireG e (Event a) (Event a) traceEventShow = traceEvent showt -- | Prints occurences of event to log using specific function to form message traceEvent :: (a -> Text) -> GameWireG e (Event a) (Event a) traceEvent f = proc ev -> do logInfoE . arr (fmap f) -< ev returnA -< ev
NCrashed/sinister
src/shared/Core/Log.hs
mit
1,824
2
12
365
495
277
218
46
2
module PackageList ( update , show' ) where -- -- -- show' :: IO () show' = putStrLn "Displaying a list of available packages" -- -- -- update :: IO () update = putStrLn "Updating package list from all available repositories"
grsmv/sllar-client
src/PackageList.hs
mit
234
0
6
49
54
32
22
7
1
{-| Provides functionality to setup the Lua environment and run Lua themes. To understand how a Lua theme is run you need to know: * How resources are passed into the runner * How information is passed between Lua and Haskell * What a theme should consist of This module provides a single function 'runThemeScript' that sets up the Lua environment and executes the theme in the theme dir API functionality in this module refers to the functions that can be called in Lua that executes Haskell code. Some API functions needs to access the database and/or the output buffer therefor those resources are kept in a central data type called 'LuaExtra'. (See "Foreign.Lua.Types" for information about this data type contains). When a Lua theme is executed it can access the Lua module __alven__ to use all the API functions. All functions except for one are used to retrieve data from the system (such as list of pages, specific pages, URLs, etc.). The exception is the __output__ function that is used to append the given data to a buffer that becomes the HTTP body after the theme has finished executing. Currently this buffer is simply an "IORef" to a "Text" value that is appended each time __output__ is called. -} module Foreign.Lua where import Import import qualified Scripting.Lua as Lua import Scripting.Lua (LuaState) import Filesystem.Path.CurrentOS (encodeString) import qualified Foreign.Lua.API as API import Foreign.Lua.Types (LuaExtra(..), LuaAPIExport(..)) ------------------------------------------------------------------------------- {-| Runs a theme script and returns the resulting output buffer or an error message that consists of a Lua stack trace. Adds right lua path to the given theme directory and registers all API functions that are used to interact with alven from Lua. See "Foreign.Lua.API" for more information. Note: Expects that the given 'LuaExtra' contain valid resources. Does not check whether the output buffer or db runner actually is setup correct. -} runThemeScript :: LuaExtra -> IO (Either String String) runThemeScript lextra = do lstate <- Lua.newstate Lua.openlibs lstate addThemePaths lextra lstate registerAPIFunctions lstate lextra let mainScript = (runDir lextra) </> "main.lua" Lua.loadfile lstate (encodeString mainScript) >>= runScript lstate where runScript lstate loadResult | loadResult == 0 = do res <- Lua.pcall lstate 0 0 0 handleResult lstate res | otherwise = returnError lstate handleResult lstate runResult | runResult == 0 = do Lua.close lstate readIORef (outputBuffer lextra) >>= return . Right | otherwise = returnError lstate returnError lstate = do errorMessage <- Lua.tostring lstate 1 Lua.pop lstate 1 Lua.close lstate return $ Left errorMessage {-| Adds search path to the directory where the theme is situated so that when a Lua script uses require it will find the scripts in the same directory. This is needed since the actual directory where the theme files are situated is not the working directory of the application. -} addThemePaths :: LuaExtra -> LuaState -> IO () addThemePaths lextra lstate = do Lua.getglobal lstate "package" Lua.getfield lstate (-1) "path" currPath <- Lua.tostring lstate (-1) let tdir = encodeString (runDir lextra) newPath = currPath ++ ";" ++ "./" ++ tdir ++ "/?.lua;" ++ "./" ++ tdir ++ "/?/?.lua" Lua.pop lstate 1 Lua.pushstring lstate newPath Lua.setfield lstate (-2) "path" Lua.pop lstate 1 {-| Register all API functions in the current state as the module "alven". See "API.exportedLuaFunctions" for the list of functions exported and the names they are exported as. For example a Haskell function `collectPrint` exported as `print`, will be accessable in Lua using `alven:print("Hello, testing output")`. -} registerAPIFunctions :: LuaState -> LuaExtra -> IO () registerAPIFunctions lstate lextra = do let exports = API.getExports Lua.createtable lstate 0 (length exports) forM_ exports add Lua.setglobal lstate "alven" where add Exists{..} = do Lua.pushrawhsfunction lstate (existsFunction lextra) Lua.setfield lstate (-2) existsName add _ = return ()
rzetterberg/alven
src/lib/Foreign/Lua.hs
mit
4,507
0
16
1,064
656
314
342
-1
-1
-- Dragon's Curve -- http://www.codewars.com/kata/53ad7224454985e4e8000eaa/ module DragonCurve where dragon :: Int -> String dragon n | n < 0 = "" | otherwise = filter (not . flip elem "ab") . f "Fa" $ n where f [] _ = [] f xs 0 = xs f xs n = f (concatMap g xs) (n-1) g c | c == 'a' = "aRbFR" | c == 'b' = "LFaLb" | otherwise = [c]
gafiatulin/codewars
src/6 kyu/DragonCurve.hs
mit
435
0
11
176
167
82
85
10
3
main :: IO () main = do print $ get $ test 9 test :: Integer -> Maybe Integer test i = do x <- may i may $ x + 1 may :: Integer -> Maybe Integer may i = Just i get :: Maybe Integer -> Integer get Nothing = 0 get (Just i) = i
dcjohnson/learning-haskell
arrow_notation.hs
mit
234
0
8
67
128
61
67
12
1
module Data.TransientStoreSpec where import Test.Hspec import Data.TransientStore import Control.Concurrent import Data.UUID spec :: Spec spec = do describe "peek" $ do it "returns Nothing if db is empty" $ do db <- create 5 :: IO (TransientStore String) peek db nil `shouldReturn` Nothing it "returns Nothing if key not in db" $ do db <- create 5 :: IO (TransientStore String) insert db "hello" result <- peek db nil result `shouldBe` Nothing it "returns the value if key in db" $ do db <- create 5 :: IO (TransientStore String) key <- insert db "hello" result <- peek db key result `shouldBe` (Just "hello") it "returns the value multiple times" $ do db <- create 5 :: IO (TransientStore String) key <- insert db "hello" result <- peek db key result `shouldBe` (Just "hello") result2 <- peek db key result2 `shouldBe` (Just "hello") it "returns the value if key one of several in db" $ do db <- create 5 :: IO (TransientStore String) key1 <- insert db "hello" key2 <- insert db "different" key1 `shouldNotBe` key2 result1 <- peek db key1 result1 `shouldBe` (Just "hello") result2 <- peek db key2 result2 `shouldBe` (Just "different") describe "pop" $ do it "returns a value once only" $ do db <- create 5 :: IO (TransientStore String) key <- insert db "hello" result <- pop db key result `shouldBe` (Just "hello") result2 <- pop db key result2 `shouldBe` Nothing describe "cleanIfNeeded" $ do it "should not remove a value after a short time" $ do db <- create 1 :: IO (TransientStore String) key <- insert db "hello" threadDelay 500000 result <- pop db key result `shouldBe` (Just "hello") it "should remove a value after a long time, but leave shorter values" $ do db <- create 1 :: IO (TransientStore String) key <- insert db "hello" key3 <- insert db "xyzzy" threadDelay 500000 result <- peek db key result `shouldBe` (Just "hello") key2 <- insert db "different" threadDelay 900000 result3 <- peek db key3 result3 `shouldBe` Nothing result2' <- peek db key2 result2' `shouldBe` (Just "different") threadDelay 2000000 result' <- peek db key result' `shouldBe` Nothing result2' <- peek db key2 result2' `shouldBe` Nothing it "should keep peek'd values alive" $ do db <- create 1 :: IO (TransientStore String) key1 <- insert db "hello" key2 <- insert db "there" threadDelay 500000 result1 <- peek db key1 result1 `shouldBe` (Just "hello") result2 <- peek db key2 result2 `shouldBe` (Just "there") threadDelay 500000 result1 <- peek db key1 result1 `shouldBe` (Just "hello") threadDelay 500000 result1 <- peek db key1 result1 `shouldBe` (Just "hello") threadDelay 500000 result1 <- peek db key1 result1 `shouldBe` (Just "hello") threadDelay 500000 result1 <- peek db key1 result1 `shouldBe` (Just "hello") result2 <- peek db key2 result2 `shouldBe` Nothing
steven777400/TwilioIVR
test/Data/TransientStoreSpec.hs
mit
3,839
0
19
1,541
1,103
503
600
93
1
module Main where import qualified GLM.Dot as D main :: IO () main = D.main
sordina/GLM
src/DotMain.hs
mit
78
0
6
17
29
18
11
4
1
{-# LANGUAGE DeriveGeneric, GeneralizedNewtypeDeriving #-} module Backhand.Unique where import GHC.Generics import Data.Aeson import Data.Hashable import Data.UUID import Data.Vector import Control.Concurrent.Unique import System.Random newtype ChanUUID = ChanUUID UUID deriving (Eq, Hashable, Generic) instance FromJSON ChanUUID where parseJSON = withArray "ChanUUID" $ \a -> case a !? 0 of Just v -> withText "UUID" ( \t -> case fromText t of Just u -> pure $ ChanUUID u Nothing -> fail "Expected UUID encountered invalid UUID format" ) v Nothing -> fail "Expected ChanUUID encountered empty array" instance ToJSON ChanUUID where toEncoding (ChanUUID uuid) = foldable [toJSON $ toText uuid] newChanUUID :: IO ChanUUID newChanUUID = fmap ChanUUID randomIO -- | Unique identification for connections. newtype UniqueRequester = UniqueRequester Unique deriving (Eq, Hashable) newRequesterId :: IO UniqueRequester newRequesterId = fmap UniqueRequester newUnique
quietspace/Backhand
backhand/src/Backhand/Unique.hs
mit
1,064
0
18
235
255
134
121
32
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html module Stratosphere.Resources.WAFSqlInjectionMatchSet where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.WAFSqlInjectionMatchSetSqlInjectionMatchTuple -- | Full data type definition for WAFSqlInjectionMatchSet. See -- 'wafSqlInjectionMatchSet' for a more convenient constructor. data WAFSqlInjectionMatchSet = WAFSqlInjectionMatchSet { _wAFSqlInjectionMatchSetName :: Val Text , _wAFSqlInjectionMatchSetSqlInjectionMatchTuples :: Maybe [WAFSqlInjectionMatchSetSqlInjectionMatchTuple] } deriving (Show, Eq) instance ToResourceProperties WAFSqlInjectionMatchSet where toResourceProperties WAFSqlInjectionMatchSet{..} = ResourceProperties { resourcePropertiesType = "AWS::WAF::SqlInjectionMatchSet" , resourcePropertiesProperties = hashMapFromList $ catMaybes [ (Just . ("Name",) . toJSON) _wAFSqlInjectionMatchSetName , fmap (("SqlInjectionMatchTuples",) . toJSON) _wAFSqlInjectionMatchSetSqlInjectionMatchTuples ] } -- | Constructor for 'WAFSqlInjectionMatchSet' containing required fields as -- arguments. wafSqlInjectionMatchSet :: Val Text -- ^ 'wafsimsName' -> WAFSqlInjectionMatchSet wafSqlInjectionMatchSet namearg = WAFSqlInjectionMatchSet { _wAFSqlInjectionMatchSetName = namearg , _wAFSqlInjectionMatchSetSqlInjectionMatchTuples = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html#cfn-waf-sqlinjectionmatchset-name wafsimsName :: Lens' WAFSqlInjectionMatchSet (Val Text) wafsimsName = lens _wAFSqlInjectionMatchSetName (\s a -> s { _wAFSqlInjectionMatchSetName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html#cfn-waf-sqlinjectionmatchset-sqlinjectionmatchtuples wafsimsSqlInjectionMatchTuples :: Lens' WAFSqlInjectionMatchSet (Maybe [WAFSqlInjectionMatchSetSqlInjectionMatchTuple]) wafsimsSqlInjectionMatchTuples = lens _wAFSqlInjectionMatchSetSqlInjectionMatchTuples (\s a -> s { _wAFSqlInjectionMatchSetSqlInjectionMatchTuples = a })
frontrowed/stratosphere
library-gen/Stratosphere/Resources/WAFSqlInjectionMatchSet.hs
mit
2,328
0
15
248
279
162
117
31
1
import Mario main = marioMain
mdietz94/MAAX
app/src/Main.hs
gpl-2.0
31
0
4
6
9
5
4
2
1
-- -*- mode: haskell -*- {-# LANGUAGE TemplateHaskell #-} module Baum.Order where import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Order = Pre | In | Post | Level deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Order]) instance Show Order where show = render . toDoc
marcellussiegburg/autotool
collection/src/Baum/Order.hs
gpl-2.0
317
0
9
57
94
54
40
9
0
module Grin.Main(compileToGrin) where import Control.Monad import Data.List import Data.Monoid(mappend) import System.Directory import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.UTF8 as LBS import qualified Data.Map as Map import qualified Data.Set as Set import qualified System import qualified System.FilePath as FP import C.Prims import Grin.DeadCode import Grin.Devolve(twiddleGrin,devolveTransform) import Grin.EvalInline(createEvalApply) import Grin.FromE import Grin.Grin import Grin.Lint import Grin.NodeAnalyze import Grin.Optimize import Grin.SSimplify import Grin.Show import Grin.StorageAnalysis import Ho.ReadSource import Options import PackedString import RawFiles import Support.TempDir import Support.Transform import Util.Gen import qualified C.FromGrin2 as FG2 import qualified FlagDump as FD import qualified Stats {-# NOINLINE compileToGrin #-} compileToGrin prog = do stats <- Stats.new putProgressLn "Converting to Grin..." x <- Grin.FromE.compile prog when verbose $ Stats.print "Grin" Stats.theStats wdump FD.GrinInitial $ do dumpGrin "initial" x x <- transformGrin simplifyParms x wdump FD.GrinNormalized $ do dumpGrin "normalized" x x <- explicitRecurse x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x putProgressLn "-- Speculative Execution Optimization" x <- grinSpeculate x lintCheckGrin x x <- transformGrin deadCodeParms x x <- transformGrin simplifyParms x x <- transformGrin pushParms x x <- transformGrin simplifyParms x wdump FD.OptimizationStats $ Stats.print "Optimization" stats putProgressLn "-- Node Usage Analysis" wdump FD.GrinPreeval $ dumpGrin "preeval" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x wdump FD.GrinPreeval $ dumpGrin "preeval2" x x <- transformGrin nodeAnalyzeParms x x <- transformGrin simplifyParms x x <- createEvalApply x x <- transformGrin simplifyParms x putProgressLn "-- Grin Devolution" wdump FD.GrinFinal $ dumpGrin "predevolve" x x <- transformGrin devolveTransform x --x <- opt "After Devolve Optimization" x x <- transformGrin simplifyParms x x <- return $ twiddleGrin x -- x <- return $ normalizeGrin x -- x <- return $ twiddleGrin x x <- storeAnalyze x dumpFinalGrin x compileGrinToC x dumpFinalGrin grin = do wdump FD.GrinGraph $ do let dot = graphGrin grin writeFile (outputName ++ "_grin.dot") dot wdump FD.GrinFinal $ dumpGrin "final" grin compileGrinToC grin = do let (cg,Requires reqs) = FG2.compileGrin grin rls = filter ("-l" `isPrefixOf`) $ map (unpackPS . snd) (Set.toList reqs) fn = outputName ++ lup "executable_extension" lup k = maybe "" id $ Map.lookup k (optInis options) cf <- case (optOutName options,optStop options) of (Just fn,StopC) -> return fn _ | dump FD.C -> return (fn ++ "_code.c") | otherwise -> fileInTempDir ("main_code.c") (\_ -> return ()) (argstring,sversion) <- getArgString (cc,args) <- fetchCompilerFlags forM_ [("rts/constants.h",constants_h), ("rts/stableptr.c",stableptr_c), ("rts/slub.c",slub_c), ("rts/profile.c",profile_c), ("rts/profile.h",profile_h), ("rts/gc.h",gc_h), ("rts/rts_support.c",rts_support_c), ("rts/rts_support.h",rts_support_h), ("rts/jhc_rts.c",jhc_rts_c), ("rts/jhc_rts.h",jhc_rts_h), ("lib/lib_cbits.c",lib_cbits_c), ("lib/lib_cbits.h",lib_cbits_h), ("rts/cdefs.h",cdefs_h), ("sys/queue.h",queue_h), ("HsFFI.h",hsffi_h), ("jhc_rts_header.h",jhc_rts_header_h), ("sys/wsize.h",wsize_h), ("rts/gc_jgc.c",gc_jgc_c), ("rts/gc_jgc.h",gc_jgc_h), ("rts/gc_jgc_internal.h",gc_jgc_internal_h), ("rts/gc_none.c",gc_none_c), ("rts/gc_none.h",gc_none_h), ("sys/bitarray.h",bitarray_h)] $ \ (fn,bs) -> do fileInTempDir fn $ flip BS.writeFile bs let cFiles = ["rts/profile.c", "rts/rts_support.c", "rts/gc_none.c", "rts/jhc_rts.c", "lib/lib_cbits.c", "rts/gc_jgc.c", "rts/stableptr.c"] tdir <- getTempDir ds <- catch (getDirectoryContents (tdir FP.</> "cbits")) (\_ -> return []) let extraCFiles = map (tdir FP.</>) cFiles ++ ["-I" ++ tdir ++ "/cbits", "-I" ++ tdir ] ++ [ tdir FP.</> "cbits" FP.</> fn | fn@(reverse -> 'c':'.':_) <- ds ] let comm = shellQuote $ [cc] ++ extraCFiles ++ [cf, "-o", fn] ++ args ++ rls globalvar n c = LBS.fromString $ "char " ++ n ++ "[] = \"" ++ c ++ "\";" putProgressLn ("Writing " ++ show cf) LBS.writeFile cf $ LBS.intercalate (LBS.fromString "\n") [ globalvar "jhc_c_compile" comm, globalvar "jhc_command" argstring, globalvar "jhc_version" sversion,LBS.empty,cg] when (optStop options == StopC) $ exitSuccess putProgressLn ("Running: " ++ comm) r <- System.system comm when (r /= System.ExitSuccess) $ fail "C code did not compile." return () grinParms = transformParms { transformDumpProgress = verbose, transformPass = "Grin" } simplifyParms = grinParms { transformCategory = "Simplify", transformOperation = Grin.SSimplify.simplify, transformIterate = IterateDone } nodeAnalyzeParms = grinParms { transformCategory = "NodeAnalyze", transformOperation = nodealyze } where nodealyze grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin g <- nodeAnalyze g st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st } pushParms = grinParms { transformCategory = "Push", transformOperation = pushGrin } where pushGrin grin = do nf <- mapMsnd (grinPush undefined) (grinFuncs grin) return $ setGrinFunctions nf grin deadCodeParms = grinParms { transformCategory = "DeadCode", transformOperation = op } where op grin = do stats <- Stats.new g <- deadCode stats (grinEntryPointNames grin) grin st <- Stats.readStat stats return g { grinStats = grinStats grin `mappend` st }
dec9ue/jhc_copygc
src/Grin/Main.hs
gpl-2.0
6,549
0
18
1,580
1,908
985
923
-1
-1
main :: IO() main = do print(count_digits 0) {- Зад. 1. Да се дефинира процедура count_digits :: Int -> Int, която генерира линейно рекурсивен процес и намира броя на цифрите на дадено естествено число n. -} count_digits :: Int -> Int count_digits 0 = -1 count_digits n = if n < 10 then 1 else 1 + count_digits(n `div` 10) {- Зад. 2. Да се дефинира процедура sum_digits :: Int -> Int, която генерира линейно рекурсивен процес и намира сумата от цифрите на дадено естествено число n. -} sum_digits :: Int -> Int sum_digits n = if n < 10 then n else n `mod` 10 + sum_digits(n `div` 10) {- Зад. 3. Да се дефинира процедура pow :: Double -> Int -> Double, която генерира линейно рекурсивен процес и намира x на степен n, където x е реално, а n - естествено число. -} pow :: Double -> Int -> Double pow x n = if n == 0 then 1 else x * pow x (n - 1) {- Зад. 4. Да се дефинира процедура sum_digits_iter :: Int -> Int, която генерира линейно итеративен процес и намира сумата от цифрите на дадено естествено число n. -} sum_digits_iter :: Int -> Int sum_digits_iter n = helper n 0 where helper 0 sum = sum helper n sum = helper (n `div` 10) (sum + (n `mod` 10)) {- Зад. 5. Да се дефинира процедура rev :: Int -> Int, която генерира линейно итеративен процес и по дадено естествено число n намира числото, записано със същите цифри, но в обратен ред. -} rev :: Int -> Int rev n = iter n (count_digits n - 1) where iter 0 _ = 0 iter n p = ((n `mod` 10) * (10^p)) + iter (n `div` 10) (p - 1) {- Зад. 6. Да се дефинира предикат prime :: Int -> Bool, който проверява дали дадено естествено число n е просто. Забележка: Числото 1 не е нито просто, нито съставно. -} prime :: Int -> Bool prime n | n < 2 = False | otherwise = iter n (round (sqrt (fromIntegral n))) where yiter n k | k < 2 = True | n `mod` k == 0 = False | otherwise = iter n (k - 1)
minchopaskal/Functional-Programming
Haskell/Practicum/ex1.hs
gpl-3.0
2,669
0
12
553
488
258
230
28
2
{-# LANGUAGE Arrows #-} module FRP.Counters ( CounterCommand(..), applyCounterCommand, CounterControl, counterControl ) where import Common.Counters import Data.Monoid import FRP.Yampa data CounterCommand = CounterAdd Int | CounterSub Int | CounterSet Int | CounterReset Int deriving Show instance Monoid CounterCommand where mempty = CounterAdd 0 _ `mappend` (CounterSet y) = CounterSet y _ `mappend` (CounterReset y) = CounterReset y (CounterSet x) `mappend` (CounterAdd y) = CounterSet (x + y) (CounterReset x) `mappend` (CounterAdd y) = CounterSet (x + y) (CounterSet x) `mappend` (CounterSub y) = CounterSet (0 `max` (x - y)) (CounterReset x) `mappend` (CounterSub y) = CounterSet (0 `max` (x - y)) (CounterAdd x) `mappend` (CounterAdd y) = CounterAdd (x + y) (CounterAdd x) `mappend` (CounterSub y) = if x >= y then CounterAdd (x - y) else CounterSub (y - x) (CounterSub x) `mappend` (CounterAdd y) = if y >= x then CounterAdd (y - x) else CounterSub (x - y) (CounterSub x) `mappend` (CounterSub y) = CounterSub (x + y) applyCounterCommand :: CounterCommand -> Int -> Int applyCounterCommand (CounterAdd x) z = z + x applyCounterCommand (CounterSub x) z = z - x applyCounterCommand (CounterSet x) _ = x applyCounterCommand (CounterReset x) _ = x type CounterControl = SF (Event CounterCommand) CounterState counterControl :: CounterState -> CounterControl counterControl c0 = (arr$ \e -> (e, ())) >>> second deltaTime >>> counterControlInner c0 counterControlInner :: CounterState -> SF (Event CounterCommand, Time) CounterState counterControlInner = sscan$ \c0 (cmd, dt) -> let c1 = case cmd of Event (CounterAdd x) -> addCounter x c0 Event (CounterSub x) -> subCounter x c0 Event (CounterSet x) -> setCounter x c0 Event (CounterReset x) -> resetCounter x c0 NoEvent -> c0 in updateCounter (floor$ dt * 1000) c1 deltaTime :: SF () Time deltaTime = (arr$ \(t0, t1) -> t1 - t0) <<< ((iPre 0 <<< time) &&& time)
CLowcay/CC_Clones
src/FRP/Counters.hs
gpl-3.0
1,954
14
16
341
858
450
408
43
5
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-type-defaults #-} module Main where import Control.Applicative import Data.Monoid import Text.Radexp.Simple import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import Test.HUnit import Test.QuickCheck newtype StringAbc = StringAbc String deriving ( Show ) instance Arbitrary StringAbc where arbitrary = StringAbc <$> listOf (elements "abc") newtype StringRe = StringRe String deriving ( Show ) instance Arbitrary StringRe where arbitrary = StringRe <$> listOf (elements "abc*+?()|.") main :: IO () main = defaultMainWithOpts [ testCase "simple" testSimple , testCase "dot" testDot , testCase "alternation" testAlternation , testCase "star" testStar , testProperty "matchSelf" propMatchSelf ] opts where opts = mempty { ropt_test_options = Just (mempty { topt_maximum_generated_tests = Just 500 , topt_maximum_unsuitable_generated_tests = Just 5000 })} -------------------------------- -- Unit tests -------------------------------- testSimple :: Assertion testSimple = do match "" "" @?= Just True match "ab" "ab" @?= Just True testDot :: Assertion testDot = do match "." "." @?= Just True match "." "a" @?= Just True match "a.b" "axb" @?= Just True match "a.." "abc" @?= Just True testAlternation :: Assertion testAlternation = do match "a|b" "a" @?= Just True match "a|b" "b" @?= Just True match "a|b" "c" @?= Just False match "ac|bd" "ac" @?= Just True match "ac|bd" "a" @?= Just False match "ac|bd" "bd" @?= Just True match "ac|bd" "b" @?= Just False testStar :: Assertion testStar = do match ".*" "abc" @?= Just True match ".*" "" @?= Just True testAnchored :: Assertion testAnchored = do match "a" "a" @?= Just True match "a" "ab" @?= Just False match "a" "ba" @?= Just False -------------------------------- -- QuickCheck properties -------------------------------- propMatchSelf :: StringAbc -> Bool propMatchSelf (StringAbc text) = match text text == Just True
scvalex/radexp
Test/Props.hs
gpl-3.0
2,276
0
13
546
595
292
303
63
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Enqueue (Command(..), Options(..), RetryCommand(..), run) where -------------------------------------------------------------------------------- import Control.Monad ((>=>), forM_, when, void) import Control.Monad.Trans (lift) import Data.List (nub) -------------------------------------------------------------------------------- import qualified Data.Aeson as Aeson import qualified Data.Aeson.Types as Aeson import qualified Data.Traversable as DT import qualified Database.PostgreSQL.Simple as PG import qualified Network.AMQP as AMQP import qualified Network.Mail.Mime as Mail import Control.Monad.Trans.Reader (ReaderT(runReaderT), ask) import Data.Aeson ((.:?)) import Database.PostgreSQL.Simple.SqlQQ (sql) -------------------------------------------------------------------------------- import qualified MusicBrainz.Email as Email import qualified MusicBrainz.Messaging as Messaging -------------------------------------------------------------------------------- data Command = PasswordReset PG.ConnectInfo | Retry [RetryCommand] -------------------------------------------------------------------------------- data RetryCommand = Unroutable | Invalid deriving (Eq) -------------------------------------------------------------------------------- data Options = Options Command Messaging.RabbitMQConnection -------------------------------------------------------------------------------- evaluateCommand :: Command -> ReaderT AMQP.Connection IO [Email.Email] -------------------------------------------------------------------------------- evaluateCommand (PasswordReset connInfo) = lift $ do pg <- PG.connect connInfo PG.fold_ pg editorsWithEmailAddresses [] go where go emails (editorName, emailAddress) = let email = Email.Email { Email.emailTemplate = Email.PasswordReset editorName , Email.emailTo = Mail.Address { Mail.addressName = Just editorName , Mail.addressEmail = emailAddress } , Email.emailFrom = Mail.Address { Mail.addressName = Just "MusicBrainz" , Mail.addressEmail = "noreply@musicbrainz.org" } } in return (email : emails) editorsWithEmailAddresses = [sql| SELECT name, email FROM editor WHERE email IS DISTINCT FROM '' AND email_confirm_date IS NOT NULL AND last_login_date < '2013-03-29' |] -------------------------------------------------------------------------------- evaluateCommand (Retry commands) = do rabbitMqConn <- ask lift $ do recvChan <- AMQP.openChannel rabbitMqConn sendChan <- AMQP.openChannel rabbitMqConn Email.establishRabbitMqConfiguration recvChan forM_ (nub commands) $ \command -> consume recvChan (commandQueue command) $ \(msg, _) -> consumeMessage command sendChan msg return [] where consumeMessage Invalid sendChan msg = AMQP.publishMsg sendChan Email.outboxExchange "" msg consumeMessage Unroutable sendChan msg = void $ maybe (AMQP.publishMsg sendChan Email.failureExchange Email.invalidKey msg) (void . DT.traverse (Email.enqueueEmail sendChan)) (Aeson.decode (AMQP.msgBody msg) >>= parseEmail) where parseEmail (Aeson.Object o) = Aeson.parseMaybe (.:? "email") o parseEmail _ = Nothing commandQueue Invalid = Email.invalidQueue commandQueue Unroutable = Email.unroutableQueue consume chan queue callback = let go = maybe (return ()) (callback >=> const go) =<< AMQP.getMsg chan AMQP.NoAck queue in go -------------------------------------------------------------------------------- run :: Options -> IO () run (Options command r) = do rabbitMqConn <- Messaging.connect r emails <- runReaderT (evaluateCommand command) rabbitMqConn when (not . null $ emails) $ do rabbitMq <- AMQP.openChannel rabbitMqConn mapM_ (Email.enqueueEmail rabbitMq) emails
metabrainz/musicbrainz-email
enqueue/Enqueue.hs
gpl-3.0
4,064
0
15
741
896
490
406
70
4
{-# 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.CloudMonitoring.MetricDescriptors.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List metric descriptors that match the query. If the query is not set, -- then all of the metric descriptors will be returned. Large responses -- will be paginated, use the nextPageToken returned in the response to -- request subsequent pages of results by setting the pageToken query -- parameter to the value of the nextPageToken. -- -- /See:/ <https://cloud.google.com/monitoring/v2beta2/ Cloud Monitoring API Reference> for @cloudmonitoring.metricDescriptors.list@. module Network.Google.Resource.CloudMonitoring.MetricDescriptors.List ( -- * REST Resource MetricDescriptorsListResource -- * Creating a Request , metricDescriptorsList , MetricDescriptorsList -- * Request Lenses , mdlProject , mdlCount , mdlPayload , mdlQuery , mdlPageToken ) where import Network.Google.CloudMonitoring.Types import Network.Google.Prelude -- | A resource alias for @cloudmonitoring.metricDescriptors.list@ method which the -- 'MetricDescriptorsList' request conforms to. type MetricDescriptorsListResource = "cloudmonitoring" :> "v2beta2" :> "projects" :> Capture "project" Text :> "metricDescriptors" :> QueryParam "count" (Textual Int32) :> QueryParam "query" Text :> QueryParam "pageToken" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ListMetricDescriptorsRequest :> Get '[JSON] ListMetricDescriptorsResponse -- | List metric descriptors that match the query. If the query is not set, -- then all of the metric descriptors will be returned. Large responses -- will be paginated, use the nextPageToken returned in the response to -- request subsequent pages of results by setting the pageToken query -- parameter to the value of the nextPageToken. -- -- /See:/ 'metricDescriptorsList' smart constructor. data MetricDescriptorsList = MetricDescriptorsList' { _mdlProject :: !Text , _mdlCount :: !(Textual Int32) , _mdlPayload :: !ListMetricDescriptorsRequest , _mdlQuery :: !(Maybe Text) , _mdlPageToken :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MetricDescriptorsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdlProject' -- -- * 'mdlCount' -- -- * 'mdlPayload' -- -- * 'mdlQuery' -- -- * 'mdlPageToken' metricDescriptorsList :: Text -- ^ 'mdlProject' -> ListMetricDescriptorsRequest -- ^ 'mdlPayload' -> MetricDescriptorsList metricDescriptorsList pMdlProject_ pMdlPayload_ = MetricDescriptorsList' { _mdlProject = pMdlProject_ , _mdlCount = 100 , _mdlPayload = pMdlPayload_ , _mdlQuery = Nothing , _mdlPageToken = Nothing } -- | The project id. The value can be the numeric project ID or string-based -- project name. mdlProject :: Lens' MetricDescriptorsList Text mdlProject = lens _mdlProject (\ s a -> s{_mdlProject = a}) -- | Maximum number of metric descriptors per page. Used for pagination. If -- not specified, count = 100. mdlCount :: Lens' MetricDescriptorsList Int32 mdlCount = lens _mdlCount (\ s a -> s{_mdlCount = a}) . _Coerce -- | Multipart request metadata. mdlPayload :: Lens' MetricDescriptorsList ListMetricDescriptorsRequest mdlPayload = lens _mdlPayload (\ s a -> s{_mdlPayload = a}) -- | The query used to search against existing metrics. Separate keywords -- with a space; the service joins all keywords with AND, meaning that all -- keywords must match for a metric to be returned. If this field is -- omitted, all metrics are returned. If an empty string is passed with -- this field, no metrics are returned. mdlQuery :: Lens' MetricDescriptorsList (Maybe Text) mdlQuery = lens _mdlQuery (\ s a -> s{_mdlQuery = a}) -- | The pagination token, which is used to page through large result sets. -- Set this value to the value of the nextPageToken to retrieve the next -- page of results. mdlPageToken :: Lens' MetricDescriptorsList (Maybe Text) mdlPageToken = lens _mdlPageToken (\ s a -> s{_mdlPageToken = a}) instance GoogleRequest MetricDescriptorsList where type Rs MetricDescriptorsList = ListMetricDescriptorsResponse type Scopes MetricDescriptorsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/monitoring"] requestClient MetricDescriptorsList'{..} = go _mdlProject (Just _mdlCount) _mdlQuery _mdlPageToken (Just AltJSON) _mdlPayload cloudMonitoringService where go = buildClient (Proxy :: Proxy MetricDescriptorsListResource) mempty
rueshyna/gogol
gogol-cloudmonitoring/gen/Network/Google/Resource/CloudMonitoring/MetricDescriptors/List.hs
mpl-2.0
5,674
0
17
1,281
655
390
265
95
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} module Main where import Control.Applicative ((<$>), (<*>), Applicative) import Control.Monad (foldM, replicateM) import Control.Monad.Random --import Control.Monad.Random.Class (MonadRandom) import Control.Monad.Reader import Control.Monad.Reader.Class import Control.Monad.State.Lazy import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HashMap import Data.List (unfoldr) import Data.Monoid ((<>)) randrand :: (MonadRandom m) => m Int randrand = getRandomR (0, 4) findDistribution :: forall a g . (RandomGen g, Eq a, Hashable a) => Rand g a -> Rand g (HashMap a Int) findDistribution randFunc = foldM (\hash _ -> fmap (insertItem hash) randFunc) HashMap.empty ([1..100000] :: [Integer]) where insertItem :: HashMap a Int -> a -> HashMap a Int insertItem hashmap key = HashMap.insertWith (+) key 1 hashmap findDistribution' :: forall a g . (RandomGen g, Eq a, Hashable a) => Rand g a -> Rand g (HashMap a Int) findDistribution' randFunc = go 0 HashMap.empty where go :: Int -> HashMap a Int -> Rand g (HashMap a Int) go 100000 hashmap = return hashmap go n hashmap = do key <- randFunc go (n+1) $ HashMap.insertWith (+) key 1 hashmap randrandrand :: (RandomGen g) => State g Int randrandrand = do oldGen <- get let (randVal, newGen) = randomR (0, 4) oldGen put newGen return randVal findDistribution'' :: forall a g . (RandomGen g, Eq a, Hashable a) => State g a -> State g (HashMap a Int) findDistribution'' randFunc = go 0 HashMap.empty where go :: Int -> HashMap a Int -> State g (HashMap a Int) go 100000 hashmap = return hashmap go n hashmap = do randVal <- randFunc go (n+1) $ HashMap.insertWith (+) randVal 1 hashmap totalRolls :: Int totalRolls = 10000000 ones :: [Integer] ones = repeat 1 genRandom :: (RandomGen g) => g -> (Integer, g) genRandom = randomR (0,4) listOfRandomRolls :: (RandomGen g) => g -> [Integer] listOfRandomRolls randGen = let allRolls = unfoldr (Just . genRandom) randGen in take totalRolls allRolls createProbDistHashMap :: (RandomGen g) => g -> HashMap Integer Integer createProbDistHashMap randGen = -- let replicatedRandomFunc = replicateM totalRolls randrandrand -- listOfRandomRolls = evalState replicatedRandomFunc randGen let zippedRolls = zip (listOfRandomRolls randGen) ones hashmap = HashMap.fromListWith (+) zippedRolls in hashmap genRandom' :: (RandomGen g, MonadReader g m, Functor m) => m (Integer, g) genRandom' = do oldGen <- ask let (num :: Integer, newGen) = randomR (1, 25) oldGen case num of 1 -> return (1, newGen) 2 -> return (2, newGen) 3 -> return (3, newGen) 4 -> return (4, newGen) 5 -> return (5, newGen) 6 -> return (6, newGen) 7 -> return (7, newGen) 8 -> return (1, newGen) 9 -> return (2, newGen) 10 -> return (3, newGen) 11 -> return (4, newGen) 12 -> return (5, newGen) 13 -> return (6, newGen) 14 -> return (7, newGen) 15 -> return (1, newGen) 16 -> return (2, newGen) 17 -> return (3, newGen) 18 -> return (4, newGen) 19 -> return (5, newGen) 20 -> return (6, newGen) 21 -> return (7, newGen) _ -> return $ runReader genRandom' newGen listOfRandomRolls' :: (RandomGen g, MonadReader g m, Functor m) => m [Integer] listOfRandomRolls' = do allRolls <- unfoldr (Just . genRandom') <$> ask return $ take totalRolls allRolls createProbDistHashMap' :: (RandomGen g, MonadReader g m, Functor m, Applicative m) => m (HashMap Integer Integer) createProbDistHashMap' = do zippedRolls <- zip <$> (listOfRandomRolls' <$> ask) <*> return ones let hashmap = HashMap.fromListWith (+) zippedRolls return hashmap printDistribution :: HashMap Integer Integer -> IO () printDistribution hashmap = forM_ (HashMap.toList hashmap) $ \(key, value) -> do putStrLn $ show key <> ": " <> show ((fromInteger value * 100) / (fromInteger $ toInteger totalRolls)) <> "% (" <> show value <> ")" main :: IO () main = do -- print =<< (evalRandIO $ findDistribution' randrand) randGen <- getStdGen -- hashmap <- createProbDistHashMap randGen let hashmap = runReader createProbDistHashMap' randGen printDistribution hashmap
cdepillabout/haskell-random-dice-test
src/Main.hs
mpl-2.0
4,692
0
18
1,257
1,635
856
779
114
22
{-# 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.YouTubeReporting.Jobs.Reports.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the metadata of a specific report. -- -- /See:/ <https://developers.google.com/youtube/reporting/v1/reports/ YouTube Reporting API Reference> for @youtubereporting.jobs.reports.get@. module Network.Google.Resource.YouTubeReporting.Jobs.Reports.Get ( -- * REST Resource JobsReportsGetResource -- * Creating a Request , jobsReportsGet , JobsReportsGet -- * Request Lenses , jrgXgafv , jrgJobId , jrgUploadProtocol , jrgAccessToken , jrgReportId , jrgUploadType , jrgOnBehalfOfContentOwner , jrgCallback ) where import Network.Google.Prelude import Network.Google.YouTubeReporting.Types -- | A resource alias for @youtubereporting.jobs.reports.get@ method which the -- 'JobsReportsGet' request conforms to. type JobsReportsGetResource = "v1" :> "jobs" :> Capture "jobId" Text :> "reports" :> Capture "reportId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "onBehalfOfContentOwner" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Report -- | Gets the metadata of a specific report. -- -- /See:/ 'jobsReportsGet' smart constructor. data JobsReportsGet = JobsReportsGet' { _jrgXgafv :: !(Maybe Xgafv) , _jrgJobId :: !Text , _jrgUploadProtocol :: !(Maybe Text) , _jrgAccessToken :: !(Maybe Text) , _jrgReportId :: !Text , _jrgUploadType :: !(Maybe Text) , _jrgOnBehalfOfContentOwner :: !(Maybe Text) , _jrgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'JobsReportsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'jrgXgafv' -- -- * 'jrgJobId' -- -- * 'jrgUploadProtocol' -- -- * 'jrgAccessToken' -- -- * 'jrgReportId' -- -- * 'jrgUploadType' -- -- * 'jrgOnBehalfOfContentOwner' -- -- * 'jrgCallback' jobsReportsGet :: Text -- ^ 'jrgJobId' -> Text -- ^ 'jrgReportId' -> JobsReportsGet jobsReportsGet pJrgJobId_ pJrgReportId_ = JobsReportsGet' { _jrgXgafv = Nothing , _jrgJobId = pJrgJobId_ , _jrgUploadProtocol = Nothing , _jrgAccessToken = Nothing , _jrgReportId = pJrgReportId_ , _jrgUploadType = Nothing , _jrgOnBehalfOfContentOwner = Nothing , _jrgCallback = Nothing } -- | V1 error format. jrgXgafv :: Lens' JobsReportsGet (Maybe Xgafv) jrgXgafv = lens _jrgXgafv (\ s a -> s{_jrgXgafv = a}) -- | The ID of the job. jrgJobId :: Lens' JobsReportsGet Text jrgJobId = lens _jrgJobId (\ s a -> s{_jrgJobId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). jrgUploadProtocol :: Lens' JobsReportsGet (Maybe Text) jrgUploadProtocol = lens _jrgUploadProtocol (\ s a -> s{_jrgUploadProtocol = a}) -- | OAuth access token. jrgAccessToken :: Lens' JobsReportsGet (Maybe Text) jrgAccessToken = lens _jrgAccessToken (\ s a -> s{_jrgAccessToken = a}) -- | The ID of the report to retrieve. jrgReportId :: Lens' JobsReportsGet Text jrgReportId = lens _jrgReportId (\ s a -> s{_jrgReportId = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). jrgUploadType :: Lens' JobsReportsGet (Maybe Text) jrgUploadType = lens _jrgUploadType (\ s a -> s{_jrgUploadType = a}) -- | The content owner\'s external ID on which behalf the user is acting on. -- If not set, the user is acting for himself (his own channel). jrgOnBehalfOfContentOwner :: Lens' JobsReportsGet (Maybe Text) jrgOnBehalfOfContentOwner = lens _jrgOnBehalfOfContentOwner (\ s a -> s{_jrgOnBehalfOfContentOwner = a}) -- | JSONP jrgCallback :: Lens' JobsReportsGet (Maybe Text) jrgCallback = lens _jrgCallback (\ s a -> s{_jrgCallback = a}) instance GoogleRequest JobsReportsGet where type Rs JobsReportsGet = Report type Scopes JobsReportsGet = '["https://www.googleapis.com/auth/yt-analytics-monetary.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly"] requestClient JobsReportsGet'{..} = go _jrgJobId _jrgReportId _jrgXgafv _jrgUploadProtocol _jrgAccessToken _jrgUploadType _jrgOnBehalfOfContentOwner _jrgCallback (Just AltJSON) youTubeReportingService where go = buildClient (Proxy :: Proxy JobsReportsGetResource) mempty
brendanhay/gogol
gogol-youtube-reporting/gen/Network/Google/Resource/YouTubeReporting/Jobs/Reports/Get.hs
mpl-2.0
5,494
0
19
1,302
862
501
361
124
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.ResourceManager -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates, reads, and updates metadata for Google Cloud Platform resource -- containers. -- -- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> module Network.Google.ResourceManager ( -- * Service Configuration resourceManagerService -- * OAuth Scopes , cloudPlatformReadOnlyScope , cloudPlatformScope -- * API Declaration , ResourceManagerAPI -- * Resources -- ** cloudresourcemanager.folders.create , module Network.Google.Resource.CloudResourceManager.Folders.Create -- ** cloudresourcemanager.folders.delete , module Network.Google.Resource.CloudResourceManager.Folders.Delete -- ** cloudresourcemanager.folders.get , module Network.Google.Resource.CloudResourceManager.Folders.Get -- ** cloudresourcemanager.folders.getIamPolicy , module Network.Google.Resource.CloudResourceManager.Folders.GetIAMPolicy -- ** cloudresourcemanager.folders.list , module Network.Google.Resource.CloudResourceManager.Folders.List -- ** cloudresourcemanager.folders.move , module Network.Google.Resource.CloudResourceManager.Folders.Move -- ** cloudresourcemanager.folders.patch , module Network.Google.Resource.CloudResourceManager.Folders.Patch -- ** cloudresourcemanager.folders.search , module Network.Google.Resource.CloudResourceManager.Folders.Search -- ** cloudresourcemanager.folders.setIamPolicy , module Network.Google.Resource.CloudResourceManager.Folders.SetIAMPolicy -- ** cloudresourcemanager.folders.testIamPermissions , module Network.Google.Resource.CloudResourceManager.Folders.TestIAMPermissions -- ** cloudresourcemanager.folders.undelete , module Network.Google.Resource.CloudResourceManager.Folders.Undelete -- ** cloudresourcemanager.liens.create , module Network.Google.Resource.CloudResourceManager.Liens.Create -- ** cloudresourcemanager.liens.delete , module Network.Google.Resource.CloudResourceManager.Liens.Delete -- ** cloudresourcemanager.liens.get , module Network.Google.Resource.CloudResourceManager.Liens.Get -- ** cloudresourcemanager.liens.list , module Network.Google.Resource.CloudResourceManager.Liens.List -- ** cloudresourcemanager.operations.get , module Network.Google.Resource.CloudResourceManager.Operations.Get -- ** cloudresourcemanager.organizations.get , module Network.Google.Resource.CloudResourceManager.Organizations.Get -- ** cloudresourcemanager.organizations.getIamPolicy , module Network.Google.Resource.CloudResourceManager.Organizations.GetIAMPolicy -- ** cloudresourcemanager.organizations.search , module Network.Google.Resource.CloudResourceManager.Organizations.Search -- ** cloudresourcemanager.organizations.setIamPolicy , module Network.Google.Resource.CloudResourceManager.Organizations.SetIAMPolicy -- ** cloudresourcemanager.organizations.testIamPermissions , module Network.Google.Resource.CloudResourceManager.Organizations.TestIAMPermissions -- ** cloudresourcemanager.projects.create , module Network.Google.Resource.CloudResourceManager.Projects.Create -- ** cloudresourcemanager.projects.delete , module Network.Google.Resource.CloudResourceManager.Projects.Delete -- ** cloudresourcemanager.projects.get , module Network.Google.Resource.CloudResourceManager.Projects.Get -- ** cloudresourcemanager.projects.getIamPolicy , module Network.Google.Resource.CloudResourceManager.Projects.GetIAMPolicy -- ** cloudresourcemanager.projects.list , module Network.Google.Resource.CloudResourceManager.Projects.List -- ** cloudresourcemanager.projects.move , module Network.Google.Resource.CloudResourceManager.Projects.Move -- ** cloudresourcemanager.projects.patch , module Network.Google.Resource.CloudResourceManager.Projects.Patch -- ** cloudresourcemanager.projects.search , module Network.Google.Resource.CloudResourceManager.Projects.Search -- ** cloudresourcemanager.projects.setIamPolicy , module Network.Google.Resource.CloudResourceManager.Projects.SetIAMPolicy -- ** cloudresourcemanager.projects.testIamPermissions , module Network.Google.Resource.CloudResourceManager.Projects.TestIAMPermissions -- ** cloudresourcemanager.projects.undelete , module Network.Google.Resource.CloudResourceManager.Projects.Undelete -- ** cloudresourcemanager.tagBindings.create , module Network.Google.Resource.CloudResourceManager.TagBindings.Create -- ** cloudresourcemanager.tagBindings.delete , module Network.Google.Resource.CloudResourceManager.TagBindings.Delete -- ** cloudresourcemanager.tagBindings.list , module Network.Google.Resource.CloudResourceManager.TagBindings.List -- ** cloudresourcemanager.tagKeys.create , module Network.Google.Resource.CloudResourceManager.TagKeys.Create -- ** cloudresourcemanager.tagKeys.delete , module Network.Google.Resource.CloudResourceManager.TagKeys.Delete -- ** cloudresourcemanager.tagKeys.get , module Network.Google.Resource.CloudResourceManager.TagKeys.Get -- ** cloudresourcemanager.tagKeys.getIamPolicy , module Network.Google.Resource.CloudResourceManager.TagKeys.GetIAMPolicy -- ** cloudresourcemanager.tagKeys.list , module Network.Google.Resource.CloudResourceManager.TagKeys.List -- ** cloudresourcemanager.tagKeys.patch , module Network.Google.Resource.CloudResourceManager.TagKeys.Patch -- ** cloudresourcemanager.tagKeys.setIamPolicy , module Network.Google.Resource.CloudResourceManager.TagKeys.SetIAMPolicy -- ** cloudresourcemanager.tagKeys.testIamPermissions , module Network.Google.Resource.CloudResourceManager.TagKeys.TestIAMPermissions -- ** cloudresourcemanager.tagValues.create , module Network.Google.Resource.CloudResourceManager.TagValues.Create -- ** cloudresourcemanager.tagValues.delete , module Network.Google.Resource.CloudResourceManager.TagValues.Delete -- ** cloudresourcemanager.tagValues.get , module Network.Google.Resource.CloudResourceManager.TagValues.Get -- ** cloudresourcemanager.tagValues.getIamPolicy , module Network.Google.Resource.CloudResourceManager.TagValues.GetIAMPolicy -- ** cloudresourcemanager.tagValues.list , module Network.Google.Resource.CloudResourceManager.TagValues.List -- ** cloudresourcemanager.tagValues.patch , module Network.Google.Resource.CloudResourceManager.TagValues.Patch -- ** cloudresourcemanager.tagValues.setIamPolicy , module Network.Google.Resource.CloudResourceManager.TagValues.SetIAMPolicy -- ** cloudresourcemanager.tagValues.testIamPermissions , module Network.Google.Resource.CloudResourceManager.TagValues.TestIAMPermissions -- * Types -- ** UndeleteOrganizationMetadata , UndeleteOrganizationMetadata , undeleteOrganizationMetadata -- ** ListFoldersResponse , ListFoldersResponse , listFoldersResponse , lfrNextPageToken , lfrFolders -- ** CreateProjectMetadata , CreateProjectMetadata , createProjectMetadata , cpmGettable , cpmReady , cpmCreateTime -- ** Status , Status , status , sDetails , sCode , sMessage -- ** OrganizationState , OrganizationState (..) -- ** AuditConfig , AuditConfig , auditConfig , acService , acAuditLogConfigs -- ** Expr , Expr , expr , eLocation , eExpression , eTitle , eDescription -- ** ListProjectsResponse , ListProjectsResponse , listProjectsResponse , lprNextPageToken , lprProjects -- ** GetIAMPolicyRequest , GetIAMPolicyRequest , getIAMPolicyRequest , giprOptions -- ** UndeleteFolderRequest , UndeleteFolderRequest , undeleteFolderRequest -- ** DeleteTagValueMetadata , DeleteTagValueMetadata , deleteTagValueMetadata -- ** UpdateTagValueMetadata , UpdateTagValueMetadata , updateTagValueMetadata -- ** Project , Project , project , pParent , pEtag , pState , pUpdateTime , pDeleteTime , pName , pDisplayName , pLabels , pProjectId , pCreateTime -- ** Operation , Operation , operation , oDone , oError , oResponse , oName , oMetadata -- ** Empty , Empty , empty -- ** FolderOperationErrorErrorMessageId , FolderOperationErrorErrorMessageId (..) -- ** SearchFoldersResponse , SearchFoldersResponse , searchFoldersResponse , sfrNextPageToken , sfrFolders -- ** ProjectCreationStatus , ProjectCreationStatus , projectCreationStatus , pcsGettable , pcsReady , pcsCreateTime -- ** CreateTagValueMetadata , CreateTagValueMetadata , createTagValueMetadata -- ** ListTagValuesResponse , ListTagValuesResponse , listTagValuesResponse , ltvrNextPageToken , ltvrTagValues -- ** CloudResourceManagerGoogleCloudResourceManagerV2alpha1FolderOperation , CloudResourceManagerGoogleCloudResourceManagerV2alpha1FolderOperation , cloudResourceManagerGoogleCloudResourceManagerV2alpha1FolderOperation , crmgcrmvfoDestinationParent , crmgcrmvfoDisplayName , crmgcrmvfoOperationType , crmgcrmvfoSourceParent -- ** StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- ** SearchProjectsResponse , SearchProjectsResponse , searchProjectsResponse , sprNextPageToken , sprProjects -- ** FolderOperationError , FolderOperationError , folderOperationError , foeErrorMessageId -- ** Folder , Folder , folder , fParent , fEtag , fState , fUpdateTime , fDeleteTime , fName , fDisplayName , fCreateTime -- ** GetPolicyOptions , GetPolicyOptions , getPolicyOptions , gpoRequestedPolicyVersion -- ** FolderOperationOperationType , FolderOperationOperationType (..) -- ** SetIAMPolicyRequest , SetIAMPolicyRequest , setIAMPolicyRequest , siprUpdateMask , siprPolicy -- ** TagValue , TagValue , tagValue , tvParent , tvEtag , tvShortName , tvUpdateTime , tvName , tvNamespacedName , tvDescription , tvCreateTime -- ** UndeleteFolderMetadata , UndeleteFolderMetadata , undeleteFolderMetadata -- ** ListLiensResponse , ListLiensResponse , listLiensResponse , llrNextPageToken , llrLiens -- ** CreateTagKeyMetadata , CreateTagKeyMetadata , createTagKeyMetadata -- ** CreateFolderMetadata , CreateFolderMetadata , createFolderMetadata , cfmParent , cfmDisplayName -- ** DeleteOrganizationMetadata , DeleteOrganizationMetadata , deleteOrganizationMetadata -- ** DeleteTagBindingMetadata , DeleteTagBindingMetadata , deleteTagBindingMetadata -- ** ListTagKeysResponse , ListTagKeysResponse , listTagKeysResponse , ltkrNextPageToken , ltkrTagKeys -- ** AuditLogConfigLogType , AuditLogConfigLogType (..) -- ** MoveFolderMetadata , MoveFolderMetadata , moveFolderMetadata , mfmDestinationParent , mfmDisplayName , mfmSourceParent -- ** Xgafv , Xgafv (..) -- ** UndeleteProjectMetadata , UndeleteProjectMetadata , undeleteProjectMetadata -- ** CreateTagBindingMetadata , CreateTagBindingMetadata , createTagBindingMetadata -- ** ProjectState , ProjectState (..) -- ** TestIAMPermissionsRequest , TestIAMPermissionsRequest , testIAMPermissionsRequest , tiprPermissions -- ** DeleteFolderMetadata , DeleteFolderMetadata , deleteFolderMetadata -- ** UpdateFolderMetadata , UpdateFolderMetadata , updateFolderMetadata -- ** MoveProjectRequest , MoveProjectRequest , moveProjectRequest , mprDestinationParent -- ** TagKey , TagKey , tagKey , tkParent , tkEtag , tkShortName , tkUpdateTime , tkName , tkNamespacedName , tkDescription , tkCreateTime -- ** CloudResourceManagerGoogleCloudResourceManagerV2beta1FolderOperation , CloudResourceManagerGoogleCloudResourceManagerV2beta1FolderOperation , cloudResourceManagerGoogleCloudResourceManagerV2beta1FolderOperation , cDestinationParent , cDisplayName , cOperationType , cSourceParent -- ** SearchOrganizationsResponse , SearchOrganizationsResponse , searchOrganizationsResponse , sorNextPageToken , sorOrganizations -- ** TestIAMPermissionsResponse , TestIAMPermissionsResponse , testIAMPermissionsResponse , tiamprPermissions -- ** Policy , Policy , policy , polAuditConfigs , polEtag , polVersion , polBindings -- ** ProjectLabels , ProjectLabels , projectLabels , plAddtional -- ** CloudResourceManagerGoogleCloudResourceManagerV2beta1FolderOperationOperationType , CloudResourceManagerGoogleCloudResourceManagerV2beta1FolderOperationOperationType (..) -- ** OperationMetadata , OperationMetadata , operationMetadata , omAddtional -- ** FolderOperation , FolderOperation , folderOperation , foDestinationParent , foDisplayName , foOperationType , foSourceParent -- ** AuditLogConfig , AuditLogConfig , auditLogConfig , alcLogType , alcExemptedMembers -- ** TagBinding , TagBinding , tagBinding , tbParent , tbTagValue , tbName -- ** Organization , Organization , organization , orgEtag , orgState , orgUpdateTime , orgDeleteTime , orgName , orgDisplayName , orgDirectoryCustomerId , orgCreateTime -- ** CloudResourceManagerGoogleCloudResourceManagerV2alpha1FolderOperationOperationType , CloudResourceManagerGoogleCloudResourceManagerV2alpha1FolderOperationOperationType (..) -- ** OperationResponse , OperationResponse , operationResponse , orAddtional -- ** UndeleteProjectRequest , UndeleteProjectRequest , undeleteProjectRequest -- ** Lien , Lien , lien , lParent , lOrigin , lReason , lName , lRestrictions , lCreateTime -- ** MoveFolderRequest , MoveFolderRequest , moveFolderRequest , mfrDestinationParent -- ** DeleteProjectMetadata , DeleteProjectMetadata , deleteProjectMetadata -- ** UpdateProjectMetadata , UpdateProjectMetadata , updateProjectMetadata -- ** FolderState , FolderState (..) -- ** MoveProjectMetadata , MoveProjectMetadata , moveProjectMetadata -- ** UpdateTagKeyMetadata , UpdateTagKeyMetadata , updateTagKeyMetadata -- ** DeleteTagKeyMetadata , DeleteTagKeyMetadata , deleteTagKeyMetadata -- ** Binding , Binding , binding , bMembers , bRole , bCondition -- ** ListTagBindingsResponse , ListTagBindingsResponse , listTagBindingsResponse , ltbrNextPageToken , ltbrTagBindings ) where import Network.Google.Prelude import Network.Google.Resource.CloudResourceManager.Folders.Create import Network.Google.Resource.CloudResourceManager.Folders.Delete import Network.Google.Resource.CloudResourceManager.Folders.Get import Network.Google.Resource.CloudResourceManager.Folders.GetIAMPolicy import Network.Google.Resource.CloudResourceManager.Folders.List import Network.Google.Resource.CloudResourceManager.Folders.Move import Network.Google.Resource.CloudResourceManager.Folders.Patch import Network.Google.Resource.CloudResourceManager.Folders.Search import Network.Google.Resource.CloudResourceManager.Folders.SetIAMPolicy import Network.Google.Resource.CloudResourceManager.Folders.TestIAMPermissions import Network.Google.Resource.CloudResourceManager.Folders.Undelete import Network.Google.Resource.CloudResourceManager.Liens.Create import Network.Google.Resource.CloudResourceManager.Liens.Delete import Network.Google.Resource.CloudResourceManager.Liens.Get import Network.Google.Resource.CloudResourceManager.Liens.List import Network.Google.Resource.CloudResourceManager.Operations.Get import Network.Google.Resource.CloudResourceManager.Organizations.Get import Network.Google.Resource.CloudResourceManager.Organizations.GetIAMPolicy import Network.Google.Resource.CloudResourceManager.Organizations.Search import Network.Google.Resource.CloudResourceManager.Organizations.SetIAMPolicy import Network.Google.Resource.CloudResourceManager.Organizations.TestIAMPermissions import Network.Google.Resource.CloudResourceManager.Projects.Create import Network.Google.Resource.CloudResourceManager.Projects.Delete import Network.Google.Resource.CloudResourceManager.Projects.Get import Network.Google.Resource.CloudResourceManager.Projects.GetIAMPolicy import Network.Google.Resource.CloudResourceManager.Projects.List import Network.Google.Resource.CloudResourceManager.Projects.Move import Network.Google.Resource.CloudResourceManager.Projects.Patch import Network.Google.Resource.CloudResourceManager.Projects.Search import Network.Google.Resource.CloudResourceManager.Projects.SetIAMPolicy import Network.Google.Resource.CloudResourceManager.Projects.TestIAMPermissions import Network.Google.Resource.CloudResourceManager.Projects.Undelete import Network.Google.Resource.CloudResourceManager.TagBindings.Create import Network.Google.Resource.CloudResourceManager.TagBindings.Delete import Network.Google.Resource.CloudResourceManager.TagBindings.List import Network.Google.Resource.CloudResourceManager.TagKeys.Create import Network.Google.Resource.CloudResourceManager.TagKeys.Delete import Network.Google.Resource.CloudResourceManager.TagKeys.Get import Network.Google.Resource.CloudResourceManager.TagKeys.GetIAMPolicy import Network.Google.Resource.CloudResourceManager.TagKeys.List import Network.Google.Resource.CloudResourceManager.TagKeys.Patch import Network.Google.Resource.CloudResourceManager.TagKeys.SetIAMPolicy import Network.Google.Resource.CloudResourceManager.TagKeys.TestIAMPermissions import Network.Google.Resource.CloudResourceManager.TagValues.Create import Network.Google.Resource.CloudResourceManager.TagValues.Delete import Network.Google.Resource.CloudResourceManager.TagValues.Get import Network.Google.Resource.CloudResourceManager.TagValues.GetIAMPolicy import Network.Google.Resource.CloudResourceManager.TagValues.List import Network.Google.Resource.CloudResourceManager.TagValues.Patch import Network.Google.Resource.CloudResourceManager.TagValues.SetIAMPolicy import Network.Google.Resource.CloudResourceManager.TagValues.TestIAMPermissions import Network.Google.ResourceManager.Types {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Cloud Resource Manager API service. type ResourceManagerAPI = TagValuesListResource :<|> TagValuesGetIAMPolicyResource :<|> TagValuesPatchResource :<|> TagValuesGetResource :<|> TagValuesCreateResource :<|> TagValuesSetIAMPolicyResource :<|> TagValuesTestIAMPermissionsResource :<|> TagValuesDeleteResource :<|> FoldersListResource :<|> FoldersUndeleteResource :<|> FoldersGetIAMPolicyResource :<|> FoldersPatchResource :<|> FoldersGetResource :<|> FoldersCreateResource :<|> FoldersSetIAMPolicyResource :<|> FoldersTestIAMPermissionsResource :<|> FoldersSearchResource :<|> FoldersDeleteResource :<|> FoldersMoveResource :<|> TagKeysListResource :<|> TagKeysGetIAMPolicyResource :<|> TagKeysPatchResource :<|> TagKeysGetResource :<|> TagKeysCreateResource :<|> TagKeysSetIAMPolicyResource :<|> TagKeysTestIAMPermissionsResource :<|> TagKeysDeleteResource :<|> LiensListResource :<|> LiensGetResource :<|> LiensCreateResource :<|> LiensDeleteResource :<|> TagBindingsListResource :<|> TagBindingsCreateResource :<|> TagBindingsDeleteResource :<|> OrganizationsGetIAMPolicyResource :<|> OrganizationsGetResource :<|> OrganizationsSetIAMPolicyResource :<|> OrganizationsTestIAMPermissionsResource :<|> OrganizationsSearchResource :<|> OperationsGetResource :<|> ProjectsListResource :<|> ProjectsUndeleteResource :<|> ProjectsGetIAMPolicyResource :<|> ProjectsPatchResource :<|> ProjectsGetResource :<|> ProjectsCreateResource :<|> ProjectsSetIAMPolicyResource :<|> ProjectsTestIAMPermissionsResource :<|> ProjectsSearchResource :<|> ProjectsDeleteResource :<|> ProjectsMoveResource
brendanhay/gogol
gogol-resourcemanager/gen/Network/Google/ResourceManager.hs
mpl-2.0
21,377
0
54
3,689
2,174
1,587
587
428
0
-- | This module defines both conditions and scopes. Since there is a mutual -- dependency, they need to go in the same module module Condition (Scope(..),Condition(..),Value(..),Predicate(..),ScopeType(..) ,scope ,condition ,value ,scopedValue ,scopeType ) where import Maker import Scoped(Label) import ScopeType(ScopeType(..),scopeType) import Data.String(IsString(..)) import Data.List((\\)) import qualified Data.Set as S import Data.Monoid((<>)) import qualified Data.Text as T(Text) import Control.Applicative -- | Wrapper for the concrete conditions newtype Predicate = Predicate Label deriving (Eq,Ord,Show) instance Data.String.IsString Predicate where fromString = Predicate . fromString -- | A @Condition@ is a boolean predicate. data Condition = Condition Label (Value ()) | BooleanCondition Label Bool | NumericCondition Label Double | Scoped (Scope Condition) | ScopedOrBoolean Label (Either Bool ScopeType) | ScopedOrNumeric Label (Either Double ScopeType) | VariableCheck Label (Either Label Double) | Or [Condition] | And [Condition] | Not [Condition] | Nand [Condition] | Trait Label deriving (Eq,Ord,Show) -- | A @Value@ is used as the argument to a @Condition@ or @`Command`@ data Value a = BooleanValue Bool | NumValue Double | ScopedValue ScopeType | Id T.Text deriving (Eq,Ord,Show) -- | @value@ makes a value of any non-scope, non-clause type value = BooleanValue True <$ checkKeys ["yes","true"] <|> BooleanValue False <$ checkKeys ["false","no"] <|> NumValue <$> number <|> Id <$> except (firstChild $ checkKeys ["yes","no","true","false"]) (label key) -- | @scopedValue@ makes a value of scoped type scopedValue = ScopedValue <$> scopeType -- | @Scope@s are used to refer to particular elements in-game, such as -- characters or titles. Each one creates a new entry on the scope stack. data Scope a = Scope { scopeType_ :: ScopeType, limit :: S.Set Condition, content :: [a] } deriving (Eq,Ord,Show) -- | Make a scope scope :: Maker a → Maker (Scope a) scope maker = Scope <$> scopeType <*> limit <*> content where limit = S.fromList . concat <$> mapSubForest condition @@@ "limit" content = maker /@@ "limit" predicate = label $ checkKeys unclassifiedPredicates -- | Make a condition condition:: Maker Condition condition = trait <|> boolean <|> (BooleanCondition <$> label (checkKeys booleanPredicates) <*> fetchBool) <|> (NumericCondition <$> label (checkKeys numericPredicates) <*> firstChild number) <|> ((\cond scope value -> Scoped $ Scope scope mempty [NumericCondition cond value]) <$> label (checkKeys numericPredicates) <*> scopeType ~@ "character" <*> number ~@ "value") <|> (ScopedOrBoolean <$> label (checkKeys scopedOrBooleanPredicates) <*> oneOf fetchBool (firstChild scopeType)) <|> (ScopedOrNumeric <$> label (checkKeys scopedOrNumericPredicates) <*> firstChild (oneOf number scopeType)) <|> simple <|> variableCheck <|> (Scoped <$ excludeKeys predicates <*> scope condition) where simple = Condition <$> predicate <*> firstChild value <?> "Concrete predicate" variableCheck = VariableCheck <$> fetchString @@ "which" <*> (Right <$> number ~@ "value" <|> Left <$> fetchString @@ "which") <?> "variable check" boolean = And <$> (checkKey "AND" *> mapSubForest condition) <|> Or <$> (checkKey "OR" *> mapSubForest condition) <|> Not <$> (checkKeys ["NOT","NOR"] *> mapSubForest condition) <|> Nand <$> (checkKey "NAND" *> mapSubForest condition) trait = Trait <$ checkKey "trait" <*> fetchString predicates :: [Label] predicates = ["random","AND","OR","NOT","calc_if_true" ,"age","age_diff","ai","always","attribute_diff","at_location","at_sea" ,"base_health","borders_major_river" ,"can_be_given_away","can_change_religion","can_call_crusade" ,"can_copy_personality_trait_from","can_have_more_leadership_traits","can_marry" ,"character" --,"check_variable" ,"claimed_by","combat_rating","combat_rating_diff" ,"completely_controls","conquest_culture","continent","controlled_by" ,"controls_religion","count","culture","culture_group" ,"defending_against_claimant","demesne_efficiency","demesne_size" ,"defacto_liege","de_jure_liege","de_jure_liege_or_above","de_jure_vassal_or_below" ,"death_reason","decadence","dynasty","difficulty","diplomacy" ,"diplomatic_immunity","dislike_tribal_organization","distance" ,"dynasty_realm_power","excommunicated_for","faction_power","family" ,"father_of_unborn_known","fertility","flank_has_leader","from_ruler_dynasty" ,"gold","graphical_culture" ,"had_character_flag","had_dynasty_flag","had_global_flag","had_province_flag" ,"had_title_flag","has_ambition","has_any_opinion_modifier","has_autocephaly" ,"has_building","has_called_crusade","has_character_flag" ,"has_character_modifier","has_claim","has_concubinage" ,"has_crown_law_title","has_de_jure_pretension","has_disease" ,"has_dlc","has_dynasty_flag","has_earmarked_regiments" ,"has_earmarked_regiments_not_raiding","has_embargo","has_empty_holding" ,"has_epidemic","has_focus","has_global_flag","has_guardian","has_heresies" ,"has_higher_tech_than","has_holder","has_horde_culture","has_job_action" ,"has_job_title","has_landed_title","has_law","has_lover","has_minor_title" ,"has_newly_acquired_titles","has_nickname","has_objective","has_opinion_modifier" ,"has_overseas_holdings","has_owner","has_plot","has_polygamy","has_province_flag" ,"has_province_modifier","has_raised_levies","has_regent","has_regiments" ,"has_siege","has_strong_claim","has_title_flag","has_trade_post","has_truce" ,"has_weak_claim","health","health_traits","held_title_rating" ,"higher_real_tier_than","higher_tier_than","holding_type","holy_order" ,"imprisoned_days","independent","intrigue","in_battle","in_command","in_faction" ,"in_revolt","in_siege","is_abroad","is_adult","is_alive","is_allied_with" ,"is_at_sea","is_attacker","is_betrothed","is_capital","is_chancellor" ,"is_child_of","is_close_relative","is_conquered","is_consort","is_contested" ,"is_councillor","is_crown_law_title","is_dying","is_father","is_father_real_father" ,"is_female","is_feudal","is_foe","is_former_lover","is_friend","is_guardian" ,"is_heresy_of","is_heretic","is_holy_site","is_ill","is_ironman","is_landed" ,"is_lowborn","is_main_spouse","is_marriage_adult","is_married" ,"is_married_matrilineally","is_marshal","is_merchant_republic" ,"is_mother","is_occupied","is_older_than","it_parent_religion" ,"is_patrician","is_playable","is_plot_active","is_plot_target_of" ,"is_pregnant","is_pretender","is_priest","is_primary_heir" ,"is_primary_holder_title","is_primary_title_tier","is_primary_type_title" ,"is_primary_war_attacker","is_primary_war_defender","is_recent_grant" ,"is_reformed_religion","is_reincarnated","is_republic","is_rival" ,"is_ruler","is_spiritual","is_spymaster","is_theocracy","is_tital_active" ,"is_titular","is_treasurer","is_tribal","is_tribal_type_tital" ,"is_valid_attraction","is_valid_viking_invasion_target","is_variable_equal" ,"is_vassal_or_below","is_vice_royalty","is_winter","is_within_diplo_range" ,"leads_faction","learning","lifestyle_traits","likes_better_than" ,"loot","lower_real_tier_than","lower_tier_than","martial","mercenary" ,"month","monthly_income","multiplayer","num_culture_realm_provs" ,"num_fitting_characters_for_title","num_of_baron_titles","num_of_buildings" ,"num_of_children","num_of_claims","num_of_consorts","num_of_count_titles" ,"num_of_duke_titles","num_of_dynasty_members","num_of_emperor_titles" ,"num_of_empty_holdings","num_of_extra_landed_titles" ,"num_of_faction_backers","num_of_friends","num_of_holy_sites" ,"num_of_king_titles","num_of_lovers","num_of_max_settlements" ,"num_of_plot_backers","num_of_prisoners","num_of_realm_counties" ,"num_of_rivals","num_of_settlements","num_of_spouses","num_of_titles" ,"num_of_trade_posts","num_of_trade_post_diff","num_of_traits" ,"num_of_unique_dynasty_vassals","num_of_vassals","num_title_realm_provs" ,"num_traits","opinion","opinion_diff","opinion_levy_raised_days" ,"overlord_of","over_max_demesne_size","over_vassal_limit","owns","pacifist" ,"personal_opinion","personal_opinion_diff","personality_traits","piety" ,"plot_is_known_by","plot_power","plot_power_contribution","port" ,"preparing_invasion","prestige","prisoner","province","province_id" ,"real_tier","realm_diplomacy","realm_intrigue","realm_martial" ,"realm_size","realm_stewardship","rebel","relative_power" ,"relative_power_to_liege","religion","religion_authority" ,"religion_group","reverse_has_opinion_modifier","reverse_has_truce" ,"reverse_opinion","reverse_personal_opinion","reverse_personal_opinion_diff" ,"revolt_risk","rightful_religious_head","ruled_years","same_guardian" ,"same_liege","same_realm","same_sex","scaled_wealth","sibling","stewardship" ,"trait","temporary","terrain","their_opinion","tier","title","total_claims" ,"treasury","troops","using_cb","vassal_of","war","war_score" ,"war_title","war_with","was_conceived_a_bastard","wealth" ,"would_be_heir_under_law","year","yearly_income"] booleanPredicates = [ "ai", "always", "borders_major_river", "can_be_given_away" , "can_change_religion", "can_call_crusade", "can_have_more_leadership_traits" , "controls_religion", "diplomatic_immunity" , "dislikes_tribal_organization", "father_of_unborn_unknown" , "flank_has_leader", "from_ruler_dynasty", "has_autocephaly" , "has_called_crusade", "has_concubinage", "has_crown_law_title" , "has_disease", "has_empty_holding", "has_epidemic", "has_guardian" , "has_heresies", "has_holder", "has_horde_culture", "has_lover" , "has_newly_acquired_holdings", "has_overseas_holdings", "has_owner" , "has_polygamy", "has_regent", "has_regiments", "has_siege", "has_trade_post" , "holy_order", "independent", "in_battle", "in_command", "in_revolt" , "in_siege", "is_abroad", "is_adult", "is_alive", "is_at_sea", "is_attacker" , "is_betrothed", "is_chancellor", "is_conquered" , "is_contested", "is_councillor", "is_crown_law_title", "is_dying" , "is_father_real_father", "is_female", "is_feudal", "is_former_lover" , "is_heretic", "is_ill", "is_ironman", "is_land", "is_landed" , "is_landless_type_title", "is_looting", "is_lowborn", "is_main_spouse" , "is_marriage_adult", "is_married_matrilineally", "is_marshal" , "is_merchant_republic", "is_occupied", "is_patrician", "is_playable" , "is_plot_active", "is_pregnant", "is_pretender", "is_priest" , "is_primary_holder_title", "is_primary_holder_title_tier" , "is_primary_type_title", "is_primary_war_attacker", "is_primary_war_defender" , "is_recent_grant", "is_reincarnated", "is_republic", "is_ruler" , "is_spiritual", "is_spymaster", "is_theocracy", "is_titular", "is_treasurer" , "is_tribal", "is_vice_royalty", "is_winter", "mercenary", "multiplayer" , "pacifist", "preparing_invasion", "prisoner", "rebel", "temporary", "war" , "was_conceived_a_bastard" ] numericPredicates = [ -- Double predicates "base_health", "demesne_efficiency", "decadence", "dynasty_realm_power" , "fertility", "monthly_income", "plot_power", "relative_power_to_liege" , "revolt_risk", "scaled_wealth", "treasury", "war_score", "yearly_income" ] <> [ -- Integer predicates "age", "combat_rating", "count", "demesne_size", "diplomacy", "gold", "health" , "health_traits", "imprisoned_days", "intrigue", "learning" , "lifestyle_traits", "loot", "martial", "month" , "num_fitting_characters_for_title", "num_of_baron_titles", "num_of_buildings" , "num_of_children", "num_of_claims", "num_of_consorts", "num_of_count_titles" , "num_of_duke_titles", "num_of_dynasty_members", "num_of_emperor_titles" , "num_of_empty_holdings", "num_of_extra_landed_titles" , "num_of_faction_backers", "num_of_friends", "num_of_holy_sites" , "num_of_king_titles", "num_of_lovers", "num_of_max_settlements" , "num_of_plot_backers", "num_of_prisoners", "num_of_rivals" , "num_of_settlements", "num_of_spouses", "num_of_titles", "num_of_trade_posts" , "num_of_trade_post_diff", "num_of_traits", "num_of_unique_dynasty_vassals" , "num_of_vassals", "num_traits", "over_max_demesne_size", "over_vassal_limit" , "personality_traits", "piety", "prestige" , "real_month_of_year", "realm_diplomacy", "realm_intrigue", "realm_learning" , "realm_martial", "realm_size", "realm_stewardship", "ruled_years" , "stewardship", "wealth", "year" ] scopedOrBooleanPredicates = [ "conquest_culture", "is_capital" ] scopedOrNumericPredicates = [ "province_id", "religion_authority" ] unclassifiedPredicates = predicates \\ (booleanPredicates <> numericPredicates <> [ "is_variable_equal" ])
joelwilliamson/validator
Condition.hs
agpl-3.0
14,373
0
22
2,819
2,577
1,595
982
-1
-1
module Git.Command.Help (run) where run :: [String] -> IO () run args = return ()
wereHamster/yag
Git/Command/Help.hs
unlicense
82
0
7
15
42
23
19
3
1
{-# LANGUAGE DeriveGeneric #-} {-| Module : Models.Events Description : A module for communication events. Copyright : (c) 2017 Pascal Poizat License : Apache-2.0 (see the file LICENSE) Maintainer : pascal.poizat@lip6.fr Stability : experimental Portability : unknown -} module Models.Events ( -- * constructors IOEvent(..) , TIOEvent(..) , IOLTS , TIOLTS , CIOEvent(..) , CTIOEvent(..) , CIOLTS , CTIOLTS , liftToTIOEvent , liftToCTIOEvent) where import Data.Aeson import Data.Hashable (Hashable) import GHC.Generics (Generic) import Models.Communication (Communication (..)) import Models.TCommunication (TCommunication (..)) import Models.Complementary (Complementary (..)) import Models.Internal (Internal (..)) import Models.LabelledTransitionSystem (LTS) {-| Input-Output Events with internal events (TIOEvents). -} data TIOEvent a = TTau -- ^ internal action (non-observable) | TReceive a -- ^ reception of something | TSend a -- ^ sending of something deriving (Eq, Ord, Generic) {-| Input-Output Events (IOEvents). -} data IOEvent a = Receive a -- ^ reception of something | Send a -- ^ sending of something deriving (Eq, Ord, Generic) liftToTIOEvent :: IOEvent a -> TIOEvent a liftToTIOEvent (Receive a) = TReceive a liftToTIOEvent (Send a) = TSend a {-| Hash instance for input-output events. -} instance Hashable a => Hashable (TIOEvent a) {-| FromJSON instance for input-output events. -} instance (FromJSON a) => FromJSON (TIOEvent a ) {-| ToJSON instance for input-output events. -} instance (ToJSON a) => ToJSON (TIOEvent a) {-| Hash instance for input-output events. -} instance Hashable a => Hashable (IOEvent a) {-| FromJSON instance for input-output events. -} instance (FromJSON a) => FromJSON (IOEvent a ) {-| ToJSON instance for input-output events. -} instance (ToJSON a) => ToJSON (IOEvent a) {-| Communication input-output events with internal events (CTIOEvents). -} data CTIOEvent a = CTTau -- ^ internal action (non-observable) | CTReceive a -- ^ reception of a call | CTReply a -- ^ reply to a call | CTInvoke a -- ^ passing a call (= invocation) | CTResult a -- ^ getting the result of a call deriving (Eq, Ord, Generic) {-| Communication input-output events (CIOEvents). -} data CIOEvent a = CReceive a -- ^ reception of a call | CReply a -- ^ reply to a call | CInvoke a -- ^ passing a call (= invocation) | CResult a -- ^ getting the result of a call deriving (Eq, Ord, Generic) liftToCTIOEvent :: CIOEvent a -> CTIOEvent a liftToCTIOEvent (CReceive a) = CTReceive a liftToCTIOEvent (CReply a) = CTReply a liftToCTIOEvent (CInvoke a) = CTInvoke a liftToCTIOEvent (CResult a) = CTResult a {-| Hash instance for communication input-output events. -} instance Hashable a => Hashable (CTIOEvent a) {-| FromJSON instance for communication input-output events. -} instance (FromJSON a) => FromJSON (CTIOEvent a ) {-| ToJSON instance for communication input-output events. -} instance (ToJSON a) => ToJSON (CTIOEvent a) {-| Hash instance for communication input-output events. -} instance Hashable a => Hashable (CIOEvent a) {-| FromJSON instance for communication input-output events. -} instance (FromJSON a) => FromJSON (CIOEvent a ) {-| ToJSON instance for communication input-output events. -} instance (ToJSON a) => ToJSON (CIOEvent a) {-| Input-output LTS (TIOLTS). This is an LTS where labels are input-output events with internal events. -} type TIOLTS a = LTS (TIOEvent a) {-| Input-output LTS (IOLTS). This is an LTS where labels are input-output events. -} type IOLTS a = LTS (IOEvent a) {-| Communication input-output LTS (CTIOLTS). This is an LTS where labels are communication input-output events with internal events. -} type CTIOLTS a = LTS (CTIOEvent a) {-| Communication input-output LTS (CIOLTS). This is an LTS where labels are communication input-output events. -} type CIOLTS a = LTS (CIOEvent a) {-| Show instance for input-output events with internal events. -} instance Show a => Show (TIOEvent a) where show TTau = "tau" show (TReceive a) = "receive " ++ show a show (TSend a) = "send " ++ show a {-| Show instance for input-output events. -} instance Show a => Show (IOEvent a) where show (Receive a) = "receive " ++ show a show (Send a) = "send " ++ show a {-| Complementary instance for input-output events with internal events. -} instance Complementary (TIOEvent a) where complementary TTau = TTau complementary (TReceive a) = TSend a complementary (TSend a) = TReceive a {-| Complementary instance for input-output events. -} instance Complementary (IOEvent a) where complementary (Receive a) = Send a complementary (Send a) = Receive a {-| Internal instance for input-output events with internal events. -} instance Internal (TIOEvent a) where isInternal TTau = True isInternal _ = False {-| Communication instance for input-output events with internal events. -} instance TCommunication (TIOEvent a) where isInput (TReceive _) = True isInput _ = False {-| Communication instance for input-output events. -} instance Communication (IOEvent a) where isInput (Receive _) = True isInput _ = False {-| Show instance for communication input-output events with internal events. -} instance Show a => Show (CTIOEvent a) where show CTTau = "tau" show (CTReceive a) = "receive " ++ show a show (CTReply a) = "reply " ++ show a show (CTInvoke a) = "invoke " ++ show a show (CTResult a) = "result " ++ show a {-| Show instance for communication input-output events. -} instance Show a => Show (CIOEvent a) where show (CReceive a) = "receive " ++ show a show (CReply a) = "reply " ++ show a show (CInvoke a) = "invoke " ++ show a show (CResult a) = "result " ++ show a {-| Complementary instance for communication input-output events with internal events. -} instance Complementary (CTIOEvent a) where complementary CTTau = CTTau complementary (CTReceive a) = CTInvoke a complementary (CTReply a) = CTResult a complementary (CTInvoke a) = CTReceive a complementary (CTResult a) = CTReply a {-| Complementary instance for communication input-output events. -} instance Complementary (CIOEvent a) where complementary (CReceive a) = CInvoke a complementary (CReply a) = CResult a complementary (CInvoke a) = CReceive a complementary (CResult a) = CReply a {-| Internal instance for communication input-output events with internal events. -} instance Internal (CTIOEvent a) where isInternal CTTau = True isInternal _ = False {-| TCommunication instance for communication input-output events with internal events. -} instance TCommunication (CTIOEvent a) where isInput (CTReceive _) = True isInput (CTResult _) = True isInput _ = False {-| Communication instance for communication input-output events. -} instance Communication (CIOEvent a) where isInput (CReceive _) = True isInput (CResult _) = True isInput _ = False
pascalpoizat/vecahaskell
src/Models/Events.hs
apache-2.0
7,240
0
8
1,538
1,654
867
787
122
1
module Braxton.A282169Spec (main, spec) where import Test.Hspec import Braxton.A282169 (a282169) main :: IO () main = hspec spec spec :: Spec spec = describe "A282169" $ it "correctly computes the first 5 elements" $ take 5 (map a282169 [1..]) `shouldBe` expectedValue where expectedValue = [1,2,2,6,6]
peterokagey/haskellOEIS
test/Braxton/A282169Spec.hs
apache-2.0
317
0
10
59
115
65
50
10
1
{-# LANGUAGE BangPatterns #-} module Kernel.CPU.GCF (kernel) where import Foreign.C import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Array import Data.Complex import Kernel.CPU.FFT import Data import Vector foreign import ccall mkGCFLayer :: FftPlan -> Ptr (Complex Double) -- destination buffer -> Ptr (Ptr (Complex Double)) -- table -> Ptr (Complex Double) -- work buffer -> CInt -- support size to extract -> CInt -- maximum support size -> CInt -- lead dim padding -> Double -- Theta/2 -> Double -- w -> IO FftPlan foreign import ccall calcAccums :: Ptr Double -- uvws -> Ptr Double -- sums (out) -> Ptr CInt -- npts (out) -> Double -- wstep -> CInt -- # of points baselines * channels * timesteps -> CInt -- # of planes -> IO () kernel :: GridPar -> GCFPar -> Vis -> IO GCFSet kernel gp gcfp vis = allocaArray numOfPlanes $ \wsump -> allocaArray numOfPlanes $ \np -> allocaArray arenaSize $ \arenap -> do fftInitThreading gcfDataPtr <- mallocArray gcfDataSize gcfTablePtr <- mallocArray gcfTableSize calcAccums uvwp wsump np wstep (f $ visTimesteps vis * (length $ visBaselines vis)) (f numOfPlanes) -- I'm using an explicit recursion explicitly. -- Usually this generates much better code. -- OTOH, higher-order functions could potentially be fused. let mkLayers !p0 !destPtr !dTabPtr (s:ss) wsumpc npc wmid = do wsumc <- peek wsumpc nc <- peek npc let avg = if nc > 0 then wsumc/fromIntegral nc else wmid -- Use scaled w's for GCF computation !p <- mkGCFLayer p0 destPtr dTabPtr arenap (f s) (f gcfMaxSize) (f pad) t2 (avg * scale) mkLayers p (advancePtr destPtr $ over2 * s * s) (advancePtr dTabPtr over2) ss (advancePtr wsumpc 1) (advancePtr npc 1) (wmid + wstep) mkLayers _ _ _ [] _ _ _ = return () -- mkLayers nullPtr gcfDataPtr gcfTablePtr layerSupps wsump np (- wstep * fromIntegral maxWPlane) -- FIXME!!!: Change all data types in such a way -- that they would bring their own finalizers with them !!! -- ATM we hack freeGCFSet slightly (see Data.hs) return $ GCFSet gcfp [] (CVector gcfTableSize $ castPtr gcfTablePtr) where uvwp = case visPositions vis of CVector _ p -> castPtr p _ -> error "Wrong uvw location for CPU GCF." f = fromIntegral t2 = gridTheta gp / 2 wstep = gcfpStepW gcfp over = gcfpOver gcfp over2 = over * over gcfMaxSize = gcfpMaxSize gcfp supp i = min gcfMaxSize (gcfpMinSize gcfp + gcfpGrowth gcfp * abs i) maxWPlane = max (round (visMaxW vis / wstep)) (round (-visMinW vis / wstep)) numOfPlanes = 2*maxWPlane+1 layerSupps = map supp [-maxWPlane .. maxWPlane] gcfDataSize = over2 * sum (map (\s -> s * s) layerSupps) gcfTableSize = over2 * (1 + 2 * maxWPlane) l = over * gcfMaxSize pad = 4 pitch = l + pad arenaSize = l * pitch scale = gridTheta gp
SKA-ScienceDataProcessor/RC
MS4/dna-programs/Kernel/CPU/GCF.hs
apache-2.0
3,094
1
23
863
914
465
449
73
4
{-# LANGUAGE TemplateHaskell #-} {-| Lenses for Ganeti config objects -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Objects.Lens where import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as UTF8 import Control.Lens (Simple) import Control.Lens.Iso (Iso, iso) import qualified Data.Set as Set import System.Time (ClockTime(..)) import Ganeti.Lens (makeCustomLenses, Lens') import Ganeti.Objects -- | Isomorphism between Strings and bytestrings stringL :: Simple Iso BS.ByteString String stringL = iso UTF8.toString UTF8.fromString -- | Class of objects that have timestamps. class TimeStampObject a => TimeStampObjectL a where mTimeL :: Lens' a ClockTime -- | Class of objects that have an UUID. class UuidObject a => UuidObjectL a where uuidL :: Lens' a String -- | Class of object that have a serial number. class SerialNoObject a => SerialNoObjectL a where serialL :: Lens' a Int -- | Class of objects that have tags. class TagsObject a => TagsObjectL a where tagsL :: Lens' a (Set.Set String) $(makeCustomLenses ''AddressPool) $(makeCustomLenses ''Network) instance SerialNoObjectL Network where serialL = networkSerialL instance TagsObjectL Network where tagsL = networkTagsL instance UuidObjectL Network where uuidL = networkUuidL . stringL instance TimeStampObjectL Network where mTimeL = networkMtimeL $(makeCustomLenses ''PartialNic) $(makeCustomLenses ''Disk) instance TimeStampObjectL Disk where mTimeL = diskMtimeL instance UuidObjectL Disk where uuidL = diskUuidL . stringL instance SerialNoObjectL Disk where serialL = diskSerialL $(makeCustomLenses ''Instance) instance TimeStampObjectL Instance where mTimeL = instMtimeL instance UuidObjectL Instance where uuidL = instUuidL . stringL instance SerialNoObjectL Instance where serialL = instSerialL instance TagsObjectL Instance where tagsL = instTagsL $(makeCustomLenses ''MinMaxISpecs) $(makeCustomLenses ''PartialIPolicy) $(makeCustomLenses ''FilledIPolicy) $(makeCustomLenses ''Node) instance TimeStampObjectL Node where mTimeL = nodeMtimeL instance UuidObjectL Node where uuidL = nodeUuidL . stringL instance SerialNoObjectL Node where serialL = nodeSerialL instance TagsObjectL Node where tagsL = nodeTagsL $(makeCustomLenses ''NodeGroup) instance TimeStampObjectL NodeGroup where mTimeL = groupMtimeL instance UuidObjectL NodeGroup where uuidL = groupUuidL . stringL instance SerialNoObjectL NodeGroup where serialL = groupSerialL instance TagsObjectL NodeGroup where tagsL = groupTagsL $(makeCustomLenses ''Cluster) instance TimeStampObjectL Cluster where mTimeL = clusterMtimeL instance UuidObjectL Cluster where uuidL = clusterUuidL . stringL instance SerialNoObjectL Cluster where serialL = clusterSerialL instance TagsObjectL Cluster where tagsL = clusterTagsL $(makeCustomLenses ''MaintenanceData) instance TimeStampObjectL MaintenanceData where mTimeL = maintMtimeL instance SerialNoObjectL MaintenanceData where serialL = maintSerialL $(makeCustomLenses ''ConfigData) instance SerialNoObjectL ConfigData where serialL = configSerialL instance TimeStampObjectL ConfigData where mTimeL = configMtimeL $(makeCustomLenses ''Incident)
leshchevds/ganeti
src/Ganeti/Objects/Lens.hs
bsd-2-clause
4,515
0
10
691
779
404
375
88
1
module Model.Par.Observer ( Observer(..) , filtered ) where import Data.Functor.Contravariant import Data.Functor.Contravariant.Divisible import Data.Void import Model.Par newtype Observer a = Observer { (!) :: a -> Par () } instance Contravariant Observer where contramap f (Observer g) = Observer (g . f) instance Divisible Observer where conquer = Observer $ \ _ -> return () divide f m n = Observer $ \ a -> case f a of (b, c) -> do m!b; n!c instance Decidable Observer where lose f = Observer $ absurd . f choose f m n = Observer $ \ a -> case f a of Left b -> m!b Right c -> n!c -- | Primarily used for filtering inputs to observers filtered :: Decidable f => (a -> Bool) -> f a -> f a filtered p = choose (\a -> if p a then Right a else Left ()) conquer
ekmett/models
src/Model/Par/Observer.hs
bsd-2-clause
797
21
10
184
281
162
119
21
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UnicodeSyntax #-} {-| The 'Worker' module contains the workhorse code of the parallelization infrastructure in the form of the 'forkWorkerThread' function, which explores a tree step by step while continuously polling for requests; for more details see 'forkWorkerThread'. -} module LogicGrowsOnTrees.Parallel.Common.Worker ( -- * Types -- ** Worker interaction ProgressUpdate(..) , ProgressUpdateFor , StolenWorkload(..) , StolenWorkloadFor , WorkerRequestQueue , WorkerRequestQueueFor , WorkerEnvironment(..) , WorkerEnvironmentFor , WorkerTerminationReason(..) , WorkerTerminationReasonFor , WorkerPushActionFor -- * Functions , forkWorkerThread , sendAbortRequest , sendProgressUpdateRequest , sendWorkloadStealRequest , exploreTreeGeneric ) where import Control.Arrow ((&&&),(>>>)) import Control.Concurrent (forkIO,ThreadId,yield) import Control.Concurrent.MVar (MVar,newEmptyMVar,putMVar,takeMVar) import Control.DeepSeq (NFData) import Control.Exception (AsyncException(ThreadKilled,UserInterrupt),catch,fromException) import Control.Monad (liftM) import Control.Monad.IO.Class import Data.Functor ((<$>)) import Data.IORef (atomicModifyIORef,IORef,newIORef,readIORef) import Data.Maybe (fromMaybe) import Data.Monoid ((<>),Monoid(..)) import Data.Sequence ((|>),(><)) import Data.Serialize import qualified Data.Sequence as Seq import Data.Void (Void,absurd) import GHC.Generics (Generic) import qualified System.Log.Logger as Logger import System.Log.Logger (Priority(DEBUG)) import System.Log.Logger.TH import LogicGrowsOnTrees hiding (exploreTree,exploreTreeT,exploreTreeUntilFirst,exploreTreeTUntilFirst) import LogicGrowsOnTrees.Checkpoint import LogicGrowsOnTrees.Parallel.ExplorationMode import LogicGrowsOnTrees.Parallel.Purity import LogicGrowsOnTrees.Path import LogicGrowsOnTrees.Workload -------------------------------------------------------------------------------- ------------------------------------ Types ------------------------------------- -------------------------------------------------------------------------------- ------------------------------ Worker responses -------------------------------- {-| A progress update sent to the supervisor; it has a component which contains information about how much of the tree has been explored and what results have been found so far, as well as the remaining 'Workload' to be completed by this worker. -} data ProgressUpdate progress = ProgressUpdate { progressUpdateProgress :: progress , progressUpdateRemainingWorkload :: Workload } deriving (Eq,Generic,Show) instance Serialize α ⇒ Serialize (ProgressUpdate α) where {-| A convenient type alias for the type of 'ProgressUpdate' associated with the given exploration mode. -} type ProgressUpdateFor exploration_mode = ProgressUpdate (ProgressFor exploration_mode) {-| A stolen workload sent to the supervisor; in addition to a component with the stolen 'Workload' itself, it also has a 'ProgressUpdate' component, which is required in order to maintain the invariant that all of the 'Workload's that the supervisor has on file (both assigned to workers and unassigned) plus the current progress equals the full tree. -} data StolenWorkload progress = StolenWorkload { stolenWorkloadProgressUpdate :: ProgressUpdate progress , stolenWorkload :: Workload } deriving (Eq,Generic,Show) instance Serialize α ⇒ Serialize (StolenWorkload α) where {-| A convenient type alias for the type of 'StolenWorkload' associated with the the given exploration mode. -} type StolenWorkloadFor exploration_mode = StolenWorkload (ProgressFor exploration_mode) ------------------------------- Worker requests -------------------------------- {-| A worker request. -} data WorkerRequest progress = {-| Request that the worker abort. -} AbortRequested {-| Request that the worker respond with a progress update. -} | ProgressUpdateRequested (ProgressUpdate progress → IO ()) {-| Request that the worker respond with a stolen workload (if possible). -} | WorkloadStealRequested (Maybe (StolenWorkload progress) → IO ()) {-| A queue of worker requests. NOTE: Although the type is a list, and requests are added by prepending them to the list, it still acts as a queue because the worker will reverse the list before processing the requests. -} type WorkerRequestQueue progress = IORef [WorkerRequest progress] {-| A convenient type alias for the type of 'WorkerRequestQueue' associated with the given exploration mode. -} type WorkerRequestQueueFor exploration_mode = WorkerRequestQueue (ProgressFor exploration_mode) --------------------------------- Worker types --------------------------------- {-| The environment of a running worker. -} data WorkerEnvironment progress = WorkerEnvironment { workerInitialPath :: Path {-^ the initial path of the worker's workload -} , workerThreadId :: ThreadId {-^ the thread id of the worker thread -} , workerPendingRequests :: WorkerRequestQueue progress {-^ the request queue for the worker -} , workerTerminationFlag :: MVar () {-^ an MVar that is filled when the worker terminates -} } {-| A convenient type alias for the type of 'WorkerEnvironment' associated with the given exploration mode. -} type WorkerEnvironmentFor exploration_mode = WorkerEnvironment (ProgressFor exploration_mode) {-| The reason why a worker terminated. -} data WorkerTerminationReason worker_final_progress = {-| worker completed normally without error; included is the final result -} WorkerFinished worker_final_progress {-| worker failed; included is the message of the failure (this would have been a value of type 'SomeException' if it were not for the fact that this value will often have to be sent over communication channels and exceptions cannot be serialized (as they have unknown type), meaning that it usually has to be turned into a 'String' via 'show' anyway) -} | WorkerFailed String {-| worker was aborted by either an external request or the 'ThreadKilled' or 'UserInterrupt' exceptions -} | WorkerAborted deriving (Eq,Generic,Show) {-| The 'Functor' instance lets you manipulate the final progress value when the termination reason is 'WorkerFinished'. -} instance Functor WorkerTerminationReason where fmap f (WorkerFinished x) = WorkerFinished (f x) fmap _ (WorkerFailed x) = WorkerFailed x fmap _ WorkerAborted = WorkerAborted instance NFData progress ⇒ NFData (WorkerTerminationReason progress) where {-| A convenient type alias for the type of 'WorkerTerminationReason' associated with the given exploration mode. -} type WorkerTerminationReasonFor exploration_mode = WorkerTerminationReason (WorkerFinishedProgressFor exploration_mode) {-| The action that a worker can take to push a result to the supervisor; this type is effectively null (with the exact value 'absurd') for all modes except 'FoundModeUsingPush'. -} type family WorkerPushActionFor exploration_mode :: * -- NOTE: Setting the below instances equal to Void → () is a hack around the -- fact that using types with constructors result in a weird compiler bug. type instance WorkerPushActionFor (AllMode result) = Void → () type instance WorkerPushActionFor (FirstMode result) = Void → () type instance WorkerPushActionFor (FoundModeUsingPull result) = Void → () type instance WorkerPushActionFor (FoundModeUsingPush result) = ProgressUpdate (Progress result) → IO () ------------------------------- Tree properties -------------------------------- {-| Functions for working with a tree of a particular purity. -} data TreeFunctionsForPurity (m :: * → *) (n :: * → *) (α :: *) = MonadIO n ⇒ TreeFunctionsForPurity { walk :: Path → TreeT m α → n (TreeT m α) , step :: ExplorationTState m α → n (Maybe α,Maybe (ExplorationTState m α)) , run :: (∀ β. n β → IO β) } -------------------------------------------------------------------------------- ----------------------------------- Loggers ------------------------------------ -------------------------------------------------------------------------------- deriveLoggers "Logger" [DEBUG] -------------------------------------------------------------------------------- ----------------------------- Main worker function ----------------------------- -------------------------------------------------------------------------------- {-| The 'forkWorkerThread' function is the workhorse of the parallization infrastructure; it explores a tree in a separate thread while polling for requests. Specifically, the worker alternates between stepping through the tree and checking to see if there are any new requests in the queue. The worker is optimized around the observation that the vast majority of its time is spent exploring the tree rather than responding to requests, and so the amount of overhead needed to check if any requests are present needs to be minimized at the cost of possibly delaying a response to an incoming request. For this reason, it uses an 'IORef' for the queue to minimize the cost of peeking at it rather than an 'MVar' or some other thread synchronization variable; the trade-off is that if a request is added to the queue by a different processor then it might not be noticed immediately the caches get synchronized. Likewise, the request queue uses the List type rather than something like "Data.Sequence" for simplicity; the vast majority of the time the worker will encounter an empty list, and on the rare occasion when the list is non-empty it will be short enough that 'reverse'ing it will not pose a significant cost. At any given point in the exploration, there is an initial path which locates the subtree that was given as the original workload, a cursor which indicates the subtree /within/ this subtree that makes up the /current/ workload, and the context which indicates the current location in the subtree that is being explored. All workers start with an empty cursor; when a workload is stolen, decisions made early on in the the context are frozen and moved into the cursor because if they were not then when the worker backtracked it would explore a workload that it just gave away, resulting in some results being observed twice. The worker terminates either if it finishes exploring all the nodes in its (current) workload, if an error occurs, or if it is aborted either via. the 'ThreadKilled' and 'UserInterrupt' exceptions or by an abort request placed in the request queue. -} forkWorkerThread :: ExplorationMode exploration_mode {-^ the mode in to explore the tree -} → Purity m n {-^ the purity of the tree -} → (WorkerTerminationReasonFor exploration_mode → IO ()) {-^ the action to run when the worker has terminated -} → TreeT m (ResultFor exploration_mode) {-^ the tree -} → Workload {-^ the workload for the worker -} → WorkerPushActionFor exploration_mode {-^ the action to push a result to the supervisor; this should be equal to 'absurd' except when the exploration mode is 'FoundModeUsingPush'. -} → IO (WorkerEnvironmentFor exploration_mode) {-^ the environment for the worker -} forkWorkerThread exploration_mode purity finishedCallback tree (Workload initial_path initial_checkpoint) push = do -- Note: the following line of code needs to be this way --- that is, using -- do notation to extract the value of TreeFunctionsForPurity --- or else -- GHC's head will explode! TreeFunctionsForPurity{..} ← case getTreeFunctionsForPurity purity of x → return x pending_requests_ref ← newIORef [] ------------------------------- LOOP PHASES -------------------------------- let -- LOOP PHASE 1: Check if there are any pending requests; if so, proceed -- to phase 2; otherwise (the most common case), skip to -- phase 3. loop1 (!result) cursor exploration_state = liftIO (readIORef pending_requests_ref) >>= \case [] → loop3 result cursor exploration_state _ → do debugM "Worker thread's request queue is non-empty." (liftM reverse . liftIO $ atomicModifyIORef pending_requests_ref (const [] &&& id)) >>= loop2 result cursor exploration_state -- LOOP PHASE 2: Process all pending requests. loop2 result cursor exploration_state@(ExplorationTState context checkpoint tree) requests = case requests of [] → liftIO yield >> loop3 result cursor exploration_state AbortRequested:_ → do debugM "Worker thread received abort request." return WorkerAborted ProgressUpdateRequested submitProgress:rest_requests → do debugM "Worker thread received progress update request." liftIO . submitProgress $ computeProgressUpdate exploration_mode result initial_path cursor context checkpoint loop2 initial_intermediate_value cursor exploration_state rest_requests WorkloadStealRequested submitMaybeWorkload:rest_requests → do debugM "Worker thread received workload steal." case tryStealWorkload initial_path cursor context of Nothing → do debugM "No workload is available to steal." liftIO $ submitMaybeWorkload Nothing loop2 result cursor exploration_state rest_requests Just (new_cursor,new_context,workload) → do debugM "Returning workload to supervisor." liftIO . submitMaybeWorkload . Just $ StolenWorkload (computeProgressUpdate exploration_mode result initial_path new_cursor new_context checkpoint) workload loop2 initial_intermediate_value new_cursor (ExplorationTState new_context checkpoint tree) rest_requests -- LOOP PHASE 3: Take a step through the tree, and then (if not finished) -- return to phase 1. loop3 result cursor exploration_state = do (maybe_solution,maybe_new_exploration_state) ← step exploration_state case maybe_new_exploration_state of Nothing → -- We have completed exploring the tree. let explored_checkpoint = checkpointFromInitialPath initial_path . checkpointFromCursor cursor $ Explored in return . WorkerFinished $ -- NOTE: Do *not* refactor the code below; if you do so -- then it will confuse the type-checker. case exploration_mode of AllMode → Progress explored_checkpoint (maybe result (result <>) maybe_solution) FirstMode → Progress explored_checkpoint maybe_solution FoundModeUsingPull _ → Progress explored_checkpoint (maybe result (result <>) maybe_solution) FoundModeUsingPush _ → Progress explored_checkpoint (fromMaybe mempty maybe_solution) Just new_exploration_state@(ExplorationTState context checkpoint _) → let new_checkpoint = checkpointFromSetting initial_path cursor context checkpoint in case maybe_solution of Nothing → loop1 result cursor new_exploration_state Just (!solution) → case exploration_mode of AllMode → loop1 (result <> solution) cursor new_exploration_state FirstMode → return . WorkerFinished $ Progress new_checkpoint (Just solution) FoundModeUsingPull f → let new_result = result <> solution in if f new_result then return . WorkerFinished $ Progress new_checkpoint new_result else loop1 new_result cursor new_exploration_state FoundModeUsingPush _ → do liftIO . push $ ProgressUpdate (Progress new_checkpoint solution) (workloadFromSetting initial_path cursor context checkpoint) loop1 () cursor new_exploration_state ----------------------------- LAUNCH THE WORKER ---------------------------- finished_flag ← newEmptyMVar thread_id ← forkIO $ do termination_reason ← debugM "Worker thread has been forked." >> (run $ walk initial_path tree >>= loop1 initial_intermediate_value Seq.empty . initialExplorationState initial_checkpoint ) `catch` (fromException >>> \case Just ThreadKilled → WorkerAborted Just UserInterrupt → WorkerAborted e → WorkerFailed (show e) >>> pure ) debugM $ "Worker thread has terminated with reason " ++ case termination_reason of WorkerFinished _ → "finished." WorkerFailed message → "failed: " ++ show message WorkerAborted → "aborted." putMVar finished_flag () finishedCallback termination_reason return $ WorkerEnvironment initial_path thread_id pending_requests_ref finished_flag where initial_intermediate_value = initialWorkerIntermediateValue exploration_mode {-# INLINE forkWorkerThread #-} -------------------------------------------------------------------------------- ------------------------------ Request functions ------------------------------ -------------------------------------------------------------------------------- {-| Sends a request to abort. -} sendAbortRequest :: WorkerRequestQueue progress → IO () sendAbortRequest = flip sendRequest AbortRequested {-| Sends a request for a progress update along with a response action to perform when the progress update is available. -} sendProgressUpdateRequest :: WorkerRequestQueue progress {-^ the request queue -} → (ProgressUpdate progress → IO ()) {-^ the action to perform when the update is available -} → IO () sendProgressUpdateRequest queue = sendRequest queue . ProgressUpdateRequested {-| Sends a request to steal a workload along with a response action to perform when the progress update is available. -} sendWorkloadStealRequest :: WorkerRequestQueue progress {-^ the request queue -} → (Maybe (StolenWorkload progress) → IO ()) {-^ the action to perform when the update is available -} → IO () sendWorkloadStealRequest queue = sendRequest queue . WorkloadStealRequested {-| Sends a request to a worker. -} sendRequest :: WorkerRequestQueue progress → WorkerRequest progress → IO () sendRequest queue request = atomicModifyIORef queue ((request:) &&& const ()) -------------------------------------------------------------------------------- ------------------------------ Utility functions ------------------------------- -------------------------------------------------------------------------------- {-| Explores a tree with the specified purity using the given mode by forking a worker thread and waiting for it to finish; it exists to facilitate testing and benchmarking and is not a function that you are likely to ever have a need for yourself. -} exploreTreeGeneric :: ( WorkerPushActionFor exploration_mode ~ (Void → ()) , ResultFor exploration_mode ~ α ) ⇒ ExplorationMode exploration_mode → Purity m n → TreeT m α → IO (WorkerTerminationReason (FinalResultFor exploration_mode)) exploreTreeGeneric exploration_mode purity tree = do final_progress_mvar ← newEmptyMVar _ ← forkWorkerThread exploration_mode purity (putMVar final_progress_mvar) tree entire_workload absurd final_progress ← takeMVar final_progress_mvar return . flip fmap final_progress $ \progress → case exploration_mode of AllMode → progressResult progress FirstMode → Progress (progressCheckpoint progress) <$> progressResult progress FoundModeUsingPull f → if f (progressResult progress) then Right progress else Left (progressResult progress) {-# INLINE exploreTreeGeneric #-} -------------------------------------------------------------------------------- ------------------------------ Internal functions ------------------------------ -------------------------------------------------------------------------------- checkpointFromSetting :: Path → CheckpointCursor → Context m α → Checkpoint → Checkpoint checkpointFromSetting initial_path cursor context = checkpointFromInitialPath initial_path . checkpointFromCursor cursor . checkpointFromContext context computeProgressUpdate :: ResultFor exploration_mode ~ α ⇒ ExplorationMode exploration_mode → WorkerIntermediateValueFor exploration_mode → Path → CheckpointCursor → Context m α → Checkpoint → ProgressUpdate (ProgressFor exploration_mode) computeProgressUpdate exploration_mode result initial_path cursor context checkpoint = ProgressUpdate (case exploration_mode of AllMode → Progress full_checkpoint result FirstMode → full_checkpoint FoundModeUsingPull _ → Progress full_checkpoint result FoundModeUsingPush _ → Progress full_checkpoint mempty ) (workloadFromSetting initial_path cursor context checkpoint) where full_checkpoint = checkpointFromSetting initial_path cursor context checkpoint getTreeFunctionsForPurity :: Purity m n → TreeFunctionsForPurity m n α getTreeFunctionsForPurity Pure = TreeFunctionsForPurity{..} where walk path tree = pure $ sendTreeDownPath path tree step = return . stepThroughTreeStartingFromCheckpoint run = id getTreeFunctionsForPurity (ImpureAtopIO run) = TreeFunctionsForPurity{..} where walk = sendTreeTDownPath step = stepThroughTreeTStartingFromCheckpoint {-# INLINE getTreeFunctionsForPurity #-} tryStealWorkload :: Path → CheckpointCursor → Context m α → Maybe (CheckpointCursor,Context m α,Workload) tryStealWorkload initial_path cursor context = go cursor (reverse context) where go _ [] = Nothing go cursor (CacheContextStep cache:rest_context) = go (cursor |> CachePointD cache) rest_context go cursor (RightBranchContextStep:rest_context) = go (cursor |> ChoicePointD RightBranch Explored) rest_context go cursor (LeftBranchContextStep other_checkpoint _:rest_context) = Just (cursor |> ChoicePointD LeftBranch Unexplored ,reverse rest_context ,Workload ((initial_path >< pathFromCursor cursor) |> ChoiceStep RightBranch) other_checkpoint ) workloadFromSetting :: Path → CheckpointCursor → Context m α → Checkpoint → Workload workloadFromSetting initial_path cursor context = Workload (initial_path >< pathFromCursor cursor) . checkpointFromContext context
gcross/LogicGrowsOnTrees
LogicGrowsOnTrees/sources/LogicGrowsOnTrees/Parallel/Common/Worker.hs
bsd-2-clause
25,356
10
26
6,472
3,110
1,665
1,445
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QMessageBox_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:21 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QMessageBox_h where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QMessageBox ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QMessageBox_unSetUserMethod" qtc_QMessageBox_unSetUserMethod :: Ptr (TQMessageBox a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QMessageBoxSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QMessageBox ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QMessageBoxSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QMessageBox ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QMessageBoxSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QMessageBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QMessageBox ()) (QMessageBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setUserMethod" qtc_QMessageBox_setUserMethod :: Ptr (TQMessageBox a) -> CInt -> Ptr (Ptr (TQMessageBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QMessageBox :: (Ptr (TQMessageBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QMessageBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QMessageBoxSc a) (QMessageBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QMessageBox ()) (QMessageBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setUserMethodVariant" qtc_QMessageBox_setUserMethodVariant :: Ptr (TQMessageBox a) -> CInt -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QMessageBox :: (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QMessageBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QMessageBoxSc a) (QMessageBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QMessageBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QMessageBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QMessageBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QMessageBox ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QMessageBox_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QMessageBox_unSetHandler" qtc_QMessageBox_unSetHandler :: Ptr (TQMessageBox a) -> CWString -> IO (CBool) instance QunSetHandler (QMessageBoxSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QMessageBox_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler1" qtc_QMessageBox_setHandler1 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox1 :: (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QchangeEvent_h (QMessageBox ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_changeEvent" qtc_QMessageBox_changeEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QMessageBoxSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_changeEvent cobj_x0 cobj_x1 instance QcloseEvent_h (QMessageBox ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_closeEvent" qtc_QMessageBox_closeEvent :: Ptr (TQMessageBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QMessageBoxSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_closeEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler2" qtc_QMessageBox_setHandler2 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox2 :: (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QMessageBox ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_event cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_event" qtc_QMessageBox_event :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QMessageBoxSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_event cobj_x0 cobj_x1 instance QkeyPressEvent_h (QMessageBox ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_keyPressEvent" qtc_QMessageBox_keyPressEvent :: Ptr (TQMessageBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QMessageBoxSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyPressEvent cobj_x0 cobj_x1 instance QresizeEvent_h (QMessageBox ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_resizeEvent" qtc_QMessageBox_resizeEvent :: Ptr (TQMessageBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QMessageBoxSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_resizeEvent cobj_x0 cobj_x1 instance QshowEvent_h (QMessageBox ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_showEvent" qtc_QMessageBox_showEvent :: Ptr (TQMessageBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QMessageBoxSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_showEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler3" qtc_QMessageBox_setHandler3 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox3 :: (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqsizeHint_h (QMessageBox ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint cobj_x0 foreign import ccall "qtc_QMessageBox_sizeHint" qtc_QMessageBox_sizeHint :: Ptr (TQMessageBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QMessageBoxSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint cobj_x0 instance QsizeHint_h (QMessageBox ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QMessageBox_sizeHint_qth" qtc_QMessageBox_sizeHint_qth :: Ptr (TQMessageBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QMessageBoxSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler4" qtc_QMessageBox_setHandler4 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox4 :: (Ptr (TQMessageBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qaccept_h (QMessageBox ()) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_accept cobj_x0 foreign import ccall "qtc_QMessageBox_accept" qtc_QMessageBox_accept :: Ptr (TQMessageBox a) -> IO () instance Qaccept_h (QMessageBoxSc a) (()) where accept_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_accept cobj_x0 instance QcontextMenuEvent_h (QMessageBox ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_contextMenuEvent" qtc_QMessageBox_contextMenuEvent :: Ptr (TQMessageBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QMessageBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler5" qtc_QMessageBox_setHandler5 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox5 :: (Ptr (TQMessageBox x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qdone_h (QMessageBox ()) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_done cobj_x0 (toCInt x1) foreign import ccall "qtc_QMessageBox_done" qtc_QMessageBox_done :: Ptr (TQMessageBox a) -> CInt -> IO () instance Qdone_h (QMessageBoxSc a) ((Int)) where done_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_done cobj_x0 (toCInt x1) instance QqminimumSizeHint_h (QMessageBox ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint cobj_x0 foreign import ccall "qtc_QMessageBox_minimumSizeHint" qtc_QMessageBox_minimumSizeHint :: Ptr (TQMessageBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QMessageBoxSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QMessageBox ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QMessageBox_minimumSizeHint_qth" qtc_QMessageBox_minimumSizeHint_qth :: Ptr (TQMessageBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QMessageBoxSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance Qreject_h (QMessageBox ()) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_reject cobj_x0 foreign import ccall "qtc_QMessageBox_reject" qtc_QMessageBox_reject :: Ptr (TQMessageBox a) -> IO () instance Qreject_h (QMessageBoxSc a) (()) where reject_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_reject cobj_x0 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler6" qtc_QMessageBox_setHandler6 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox6 :: (Ptr (TQMessageBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QMessageBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetVisible_h (QMessageBox ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QMessageBox_setVisible" qtc_QMessageBox_setVisible :: Ptr (TQMessageBox a) -> CBool -> IO () instance QsetVisible_h (QMessageBoxSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_setVisible cobj_x0 (toCBool x1) instance QactionEvent_h (QMessageBox ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_actionEvent" qtc_QMessageBox_actionEvent :: Ptr (TQMessageBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QMessageBoxSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_actionEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler7" qtc_QMessageBox_setHandler7 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox7 :: (Ptr (TQMessageBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QdevType_h (QMessageBox ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_devType cobj_x0 foreign import ccall "qtc_QMessageBox_devType" qtc_QMessageBox_devType :: Ptr (TQMessageBox a) -> IO CInt instance QdevType_h (QMessageBoxSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_devType cobj_x0 instance QdragEnterEvent_h (QMessageBox ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragEnterEvent" qtc_QMessageBox_dragEnterEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QMessageBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QMessageBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragLeaveEvent" qtc_QMessageBox_dragLeaveEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QMessageBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QMessageBox ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dragMoveEvent" qtc_QMessageBox_dragMoveEvent :: Ptr (TQMessageBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QMessageBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QMessageBox ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_dropEvent" qtc_QMessageBox_dropEvent :: Ptr (TQMessageBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QMessageBoxSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QMessageBox ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_enterEvent" qtc_QMessageBox_enterEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QMessageBoxSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QMessageBox ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_focusInEvent" qtc_QMessageBox_focusInEvent :: Ptr (TQMessageBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QMessageBoxSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QMessageBox ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_focusOutEvent" qtc_QMessageBox_focusOutEvent :: Ptr (TQMessageBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QMessageBoxSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler8" qtc_QMessageBox_setHandler8 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox8 :: (Ptr (TQMessageBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QMessageBox ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QMessageBox_heightForWidth" qtc_QMessageBox_heightForWidth :: Ptr (TQMessageBox a) -> CInt -> IO CInt instance QheightForWidth_h (QMessageBoxSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QMessageBox ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_hideEvent" qtc_QMessageBox_hideEvent :: Ptr (TQMessageBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QMessageBoxSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler9" qtc_QMessageBox_setHandler9 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox9 :: (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qMessageBoxFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinputMethodQuery_h (QMessageBox ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QMessageBox_inputMethodQuery" qtc_QMessageBox_inputMethodQuery :: Ptr (TQMessageBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QMessageBoxSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QMessageBox ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_keyReleaseEvent" qtc_QMessageBox_keyReleaseEvent :: Ptr (TQMessageBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QMessageBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QMessageBox ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_leaveEvent" qtc_QMessageBox_leaveEvent :: Ptr (TQMessageBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QMessageBoxSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseDoubleClickEvent" qtc_QMessageBox_mouseDoubleClickEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseMoveEvent" qtc_QMessageBox_mouseMoveEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mousePressEvent" qtc_QMessageBox_mousePressEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QMessageBox ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_mouseReleaseEvent" qtc_QMessageBox_mouseReleaseEvent :: Ptr (TQMessageBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QMessageBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QMessageBox ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_moveEvent" qtc_QMessageBox_moveEvent :: Ptr (TQMessageBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QMessageBoxSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QMessageBox ()) (QMessageBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QMessageBox_setHandler10" qtc_QMessageBox_setHandler10 :: Ptr (TQMessageBox a) -> CWString -> Ptr (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QMessageBox10 :: (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QMessageBox10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QMessageBoxSc a) (QMessageBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QMessageBox10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QMessageBox10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QMessageBox_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQMessageBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qMessageBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QpaintEngine_h (QMessageBox ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_paintEngine cobj_x0 foreign import ccall "qtc_QMessageBox_paintEngine" qtc_QMessageBox_paintEngine :: Ptr (TQMessageBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QMessageBoxSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QMessageBox_paintEngine cobj_x0 instance QpaintEvent_h (QMessageBox ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_paintEvent" qtc_QMessageBox_paintEvent :: Ptr (TQMessageBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QMessageBoxSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_paintEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QMessageBox ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_tabletEvent" qtc_QMessageBox_tabletEvent :: Ptr (TQMessageBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QMessageBoxSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QMessageBox ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QMessageBox_wheelEvent" qtc_QMessageBox_wheelEvent :: Ptr (TQMessageBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QMessageBoxSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QMessageBox_wheelEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QMessageBox_h.hs
bsd-2-clause
60,217
0
18
12,816
19,731
9,515
10,216
-1
-1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} module Fragment.Bool.Ast ( module X ) where import Fragment.Bool.Ast.Type as X import Fragment.Bool.Ast.Pattern as X import Fragment.Bool.Ast.Term as X
dalaing/type-systems
src/Fragment/Bool/Ast.hs
bsd-3-clause
312
0
4
55
41
31
10
5
0
import qualified Sharc.Types as Sh import Csound.Base import Sharc.Data import Sharc.Types note2sig :: Sh.Note -> Sig note2sig n = oscBy (harmonics2tab $ Sh.noteHarmonics n) (sig $ double $ Sh.pitchFund $ Sh.notePitch n) note2tab :: Sh.Note -> Tab note2tab n = (harmonics2tab $ Sh.noteHarmonics n) deg x = 180 * x / pi harmonics2tab harmonics = sines3 $ fmap (\h -> (fromIntegral $ Sh.harmonicId h, Sh.harmonicAmplitude h, deg $ Sh.harmonicPhase h)) harmonics
FranklinChen/csound-expression
ideas/Sharc.hs
bsd-3-clause
467
0
12
78
186
97
89
10
1
module MABS ( mabs ) where import qualified ANTs (applyTransforms, computeWarp) import Control.Monad (unless) import Data.List (intercalate) import Data.List.Split (splitOn) import qualified Development.Shake as Shake (need) import qualified FSL (average, threshold) import qualified System.Directory as IO (copyFile) import System.IO.Temp (withSystemTempFile) import Util (convertImage) import Development.Shake import Development.Shake.FilePath ((</>), (<.>), takeBaseName) mabs :: FilePath -> [[FilePath]] -> FilePath -> FilePath -> Action () mabs antsPath trainingPairs t1 out = withTempDir $ \tmpdir -> do registeredmasks <- liftIO $ traverse (\(trainingVol:trainingMask:_) -> register antsPath tmpdir (trainingVol, trainingMask) t1) trainingPairs let tmpnii = tmpdir </> "tmp.nii.gz" FSL.average tmpnii registeredmasks FSL.threshold 0.5 tmpnii tmpnii liftIO $ Util.convertImage tmpnii out register :: FilePath -> FilePath -> (FilePath, FilePath) -> FilePath -> IO FilePath register antsPath outdir (moving, movingMask) fixed = let outMask = outdir </> (intercalate "-" ["Mask" ,takeBaseName movingMask ,"in" ,takeBaseName moving]) <.> "nii.gz" in withSystemTempFile "warp.nii.gz" $ \tmpwarp _ -> do liftIO $ ANTs.computeWarp antsPath moving fixed tmpwarp liftIO $ ANTs.applyTransforms antsPath "NearestNeighbor" [tmpwarp] movingMask fixed outMask return outMask
pnlbwh/test-tensormasking
pipeline-lib/MABS.hs
bsd-3-clause
1,773
0
16
571
447
244
203
34
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Models.Media ( Media(..) , PostMedia(..) , postMediaQueryByPostId , createMediaTable , createPostMediaTable ) where import Control.Applicative ((<$>), (<*>)) import Data.Aeson import qualified Data.ByteString.Char8 as B import Data.Data import qualified Data.Text as T import Database.PostgreSQL.Simple.FromRow (FromRow, field, fromRow) import Database.PostgreSQL.Simple.SqlQQ import Database.PostgreSQL.Simple.ToField (toField) import Database.PostgreSQL.Simple.ToRow (ToRow, toRow) import Database.PostgreSQL.Simple.Types (Query (..)) import GHC.Generics import Prelude (Bool, Eq, Int, Show, ($)) import Servant.Elm postMediaQueryByPostId :: Query postMediaQueryByPostId = Query $ B.unwords [ "select m.id, m.name, m.url, m.location, m.description, pm.is_featured " , "from media m where " , " inner join post_media pm on pm.media_id = m.id " , "where pm.post_id = ?" ] data Media = Media { mediaid :: !Int , name :: !T.Text , url :: !T.Text , location :: !T.Text , description :: !T.Text } deriving (Eq, Show, Generic, Data) instance ElmType Media instance ToJSON Media instance FromJSON Media instance FromRow Media where fromRow = Media <$> field <*> field <*> field <*> field <*> field instance ToRow Media where toRow m = [toField $ mediaid (m :: Media) , toField $ name m , toField $ url m , toField $ location m , toField $ description m ] data PostMedia = PostMedia { postid :: !Int , mediaid :: !Int , isFeatured :: !Bool } deriving (Eq, Show, Generic) instance ElmType PostMedia instance ToJSON PostMedia instance FromRow PostMedia where fromRow = PostMedia <$> field <*> field <*> field instance ToRow PostMedia where toRow pm = [toField $ postid (pm :: PostMedia) , toField $ mediaid (pm :: PostMedia) , toField $ isFeatured pm ] createMediaTable :: Query createMediaTable = [sql| CREATE TABLE media ( id serial primary key, name text NOT NULL, url text NOT NULL, location text NOT NULL, description text NOT NULL ); |] createPostMediaTable :: Query createPostMediaTable = [sql| CREATE TABLE post_media ( post_id integer NOT NULL, media_id integer NOT NULL, is_featured bool, PRIMARY KEY(post_id, media_id), CONSTRAINT post_fkey FOREIGN KEY (post_id) REFERENCES public.post (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE, CONSTRAINT media_fkey FOREIGN KEY (media_id) REFERENCES public.media (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE ); |]
pellagic-puffbomb/simpleservantblog
src/Models/Media.hs
bsd-3-clause
3,342
0
10
1,126
579
340
239
84
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} import ClassyPrelude main :: IO () main = putStrLn "Test suite not yet implemented"
JoeMShanahan/blizzard-haskell-api
test/Spec.hs
bsd-3-clause
156
0
6
24
24
13
11
5
1
module HasOffers.API.Affiliate.OfferFile where import Data.Text import GHC.Generics import Data.Aeson import Control.Applicative import Network.HTTP.Client import qualified Data.ByteString.Char8 as BS import HasOffers.API.Common --------------------------------------------------------------------------------
kelecorix/api-hasoffers
src/HasOffers/API/Affiliate/OfferFile.hs
bsd-3-clause
320
0
4
31
50
34
16
8
0
{-# LANGUAGE DeriveGeneric #-} {- Andy Gill and Colin Runciman, June 2006 -} -- | Datatypes and file-access routines for the tick data file -- (@.tix@) used by Hpc. module Trace.Haptics.Tix ( Tix (..) , TixModule (..) , tixModuleName , tixModuleHash , tixModuleTixs , readTix , writeTix , getTixFileName ) where import Control.DeepSeq import GHC.Generics import System.FilePath (replaceExtension) import Trace.Haptics.Utils (Hash, catchIO, readFileUtf8, writeFileUtf8) -- | 'Tix' is the storage format for our dynamic information about -- what boxes are ticked. data Tix = Tix [TixModule] deriving (Read, Show, Eq, Generic) data TixModule = TixModule String -- module name Hash -- hash number Int -- length of Tix list (allows pre-allocation at parse time). [Integer] -- actual ticks deriving ( Read , Show , Eq , Generic ) instance NFData Tix instance NFData TixModule -- TODO: Turn extractors below into proper 'TixModule' field-labels tixModuleName :: TixModule -> String tixModuleName (TixModule nm _ _ _) = nm tixModuleHash :: TixModule -> Hash tixModuleHash (TixModule _ h _ _) = h tixModuleTixs :: TixModule -> [Integer] tixModuleTixs (TixModule _ _ _ tixs) = tixs -- We /always/ read and write Tix from the current working directory. -- | Read a @.tix@ File. readTix :: String -> IO (Maybe Tix) readTix tixFilename = catchIO (fmap (Just . read) $ readFileUtf8 tixFilename) (const $ return Nothing) -- | Write a @.tix@ File. writeTix :: String -> Tix -> IO () writeTix name tix = writeFileUtf8 name (show tix) -- | 'getTixFullName' takes a binary or @.tix@-file name, -- and normalizes it into a @.tix@-file name. getTixFileName :: String -> String getTixFileName str = replaceExtension str "tix"
Javran/haptics
src/Trace/Haptics/Tix.hs
bsd-3-clause
1,814
0
10
382
391
219
172
49
1
{-# LANGUAGE OverloadedStrings #-} module Hasmin.Types.GradientSpec where import Data.Text (Text) import Hasmin.Parser.Value import Hasmin.TestUtils gradientTests :: Spec gradientTests = describe "<gradient> minification tests" $ mapM_ (matchSpecWithDesc (minifyWithTestConfig <$> value)) gradientTestsInfo gradientTestsInfo :: [(String, Text, Text)] gradientTestsInfo = [("Converts \"to top\" to 0 (unitless 0 <angle>)" ,"linear-gradient(to top, red, blue)" ,"linear-gradient(0,red,blue)") ,("Converts \"to right\" to 90deg" ,"linear-gradient(to right, green, violet)" ,"linear-gradient(90deg,green,violet)") ,("Converts \"to left\" to 270deg" ,"linear-gradient(to left, pink, peru)" ,"linear-gradient(270deg,pink,peru)") ,("Removes \"to bottom\", since that's the default <side-or-corner> value" ,"linear-gradient(to bottom, green, violet)" ,"linear-gradient(green,violet)") ,("Removes \"180deg\", since that equals \"to bottom\", which is the default value" ,"linear-gradient(180deg, green, violet)" ,"linear-gradient(green,violet)") ,("Should not convert \"to top right\"" ,"linear-gradient(to top right, pink, peru)" ,"linear-gradient(to top right,pink,peru)") ,("Should not convert \"to bottom left\"" ,"linear-gradient(to bottom left, pink, peru)" ,"linear-gradient(to bottom left,pink,peru)") ,("Reduces a <percentage> value to 0 when it is the same as the previous" ,"linear-gradient(72deg, pink 25%, peru 25%)" ,"linear-gradient(72deg,pink 25%,peru 0)") ,("Reduces a <percentage> value to 0 when it is less than the greatest previous one" ,"linear-gradient(72deg, pink 50%, peru 40%)" ,"linear-gradient(72deg,pink 50%,peru 0)") ,("Reduces a <length> value to 0 when it is the same as the previous" ,"linear-gradient(72deg, pink 3em, peru 3em)" ,"linear-gradient(72deg,pink 3em,peru 0)") ,("Reduces a <length> value to 0 when it is less than the greatest previous one" ,"linear-gradient(72deg, pink 6pc, peru 90px)" -- 6pc == 96px ,"linear-gradient(72deg,pink 6pc,peru 0)") ,("Removes default start and end <percentage> values" ,"linear-gradient(pink 0%, peru 100%)" ,"linear-gradient(pink,peru)") ,("Should not remove trailing zero when it is the last stop" ,"linear-gradient(pink,peru 0)" ,"linear-gradient(pink,peru 0)") ,("Reduce complex combination of linear and non linear color hints" ,"linear-gradient(pink 1%, peru 10%, green 20%, red 30%, violet 50%, purple 55%, cyan 60%, #ccc 80%, #000 100%)" ,"linear-gradient(pink 1%,peru 10%,green,red 30%,violet 50%,purple,cyan 60%,#ccc,#000)") ,("Removes circle in radial-gradient() when using a single <length>" ,"radial-gradient(circle 1px, pink, peru)" ,"radial-gradient(1px,pink,peru)") ,("Removes ellipse in radial-gradient() when using two <length-percentage>" ,"radial-gradient(ellipse 1px 1px, pink, peru)" ,"radial-gradient(1px 1px,pink,peru)") ,("Removes ellipse in radial-gradient() when using an <extent-keyword> in second place" ,"radial-gradient(ellipse closest-side, pink, peru)" ,"radial-gradient(closest-side,pink,peru)") ,("Removes ellipse in radial-gradient() when using an <extent-keyword> first" ,"radial-gradient(farthest-side ellipse, pink, peru)" ,"radial-gradient(farthest-side,pink,peru)") ,("Removes 'ellipse farthest-corner' in radial-gradient()" ,"radial-gradient(ellipse farthest-corner, pink, peru)" ,"radial-gradient(pink,peru)") ] spec :: Spec spec = gradientTests main :: IO () main = hspec spec
contivero/hasmin
tests/Hasmin/Types/GradientSpec.hs
bsd-3-clause
3,643
0
10
621
343
219
124
72
1
-- | Testing task assignment annotations. module Main where import Control.Monad import Data.Maybe import NewARSim import System.Random import Test.QuickCheck type IntPort p = DataElem Unqueued Int p type P a = (a, a) type C = P (IntPort Required) -- | @comp1@ runs every time "task1" is activated, and is mapped as the first -- runnable in that task. comp1 :: AUTOSAR (IntPort Provided) comp1 = atomic $ do a <- providedPort s <- interRunnableVariable 0 runnableT ["task1" :-> 0] (MinInterval 0) [TimingEvent 0.2] $ do Ok x <- rteIrvRead s rteWrite a x printlog "comp1" $ "write " ++ show x rteIrvWrite s (x + 1) return $ seal a -- | A task assignment in which we allow @comp2@ to run every second activation -- of "task1". comp2 :: AUTOSAR (IntPort Provided) comp2 = atomic $ do a <- providedPort s <- interRunnableVariable 0 runnableT ["task1" :>> (1, 2)] (MinInterval 0) [TimingEvent 0.4] $ do Ok x <- rteIrvRead s rteWrite a x printlog "comp2" $ "write " ++ show x rteIrvWrite s ((x + 1) `mod` 3) return $ seal a -- | Since @comp3@ depends on @comp2@ we would have to schedule it to run every -- second activation (and last) in "task1" if we were to map it to that task. comp3 :: AUTOSAR C comp3 = atomic $ do c1 <- requiredPort c2 <- requiredPort runnableT ["task2" :-> 0] (MinInterval 0) [DataReceivedEvent c2] $ do Ok a <- rteRead c1 Ok b <- rteRead c2 printlog "comp3" (a, b) return $ seal (c1, c2) -- Triggering task2 on c2 works, but triggering on c1 fails since it has data -- prior to c2, and comp3 is not pending. softw :: AUTOSAR () softw = composition $ do a <- comp1 b <- comp2 (c1, c2) <- comp3 connect a c1 connect b c2 declareTask "task1" (TimingEvent 0.1) declareTask "task2" (DataReceivedEvent c2) exampleQC :: Property exampleQC = traceProp softw $ \trs -> counterexample (traceTable trs) $ all (isNothing . transError) . snd $ trs main :: IO () main = do g <- newStdGen simulateStandalone True 2.0 printAll (RandomSched g) softw return () main2 :: IO () main2 = forever main
josefs/autosar
ARSim/arsim/Test.hs
bsd-3-clause
2,120
0
15
487
696
339
357
57
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module CCGServer.Tagging where import Control.Applicative import Control.Monad import Data.Maybe import Data.IORef import Data.List import qualified Data.Map as Map import Data.Map (Map) import qualified Graphics.UI.Threepenny as UI import Graphics.UI.Threepenny.Core setup :: Window -> UI () setup window = do -- GUI elements return window # set UI.title "Hello World!" elPlus <- UI.button # set UI.text "+" elMinu <- UI.button # set UI.text "-" elSave <- UI.button # set UI.text "Save Changes" elDrop <- UI.button # set UI.text "Discard Changes" elMode <- UI.button # set UI.text "View" elBlank <- UI.input # set UI.text "" result <- UI.span inputs <- liftIO $ newIORef [] mode <- liftIO $ newIORef View edited <- liftIO $ newIORef False dats <- liftIO $ newIORef example -- GUI Layout let key = fst example -- Layout and display let displayAll = void $ do xs <- mapM (get value) =<< liftIO (readIORef inputs) element result # set text (":\t"++((intercalate ", ").reverse $ xs)) redoLayout :: UI () redoLayout = void $ do emode <- liftIO (readIORef mode) edits <- liftIO (readIORef edited) let canedit = canEdit emode layout <- mkLayout canedit =<< liftIO (readIORef inputs) getBody window # set children [layout] displayAll mkLayout :: Bool -> [Element] -> UI Element mkLayout e xs = column $ ([row [element elMode], UI.hr]++ mkLine e xs key ++ [UI.hr, row [element elSave, element elDrop]]) mkLine :: Bool -> [Element] -> String -> [UI Element] mkLine e xs s = [row [UI.span # set text s]] ++ rebutrows where rebutrows = if e then concatMap (\x -> [row x]) (reverse xs') else [row [element result]] xs' = (ebut (head xs)):(map (\x -> [element x]) (tail xs)) ebut y = (element y):(if e then [element elPlus, element elMinu] else []) -- Mode switching let toggleMode :: UI () toggleMode = do liftIO $ modifyIORef mode (toggle) toggler = void $ do emode <- liftIO (readIORef mode) element elMode # set text (show.toggle$emode) -- Save/Discard modifications saveChanges :: UI () saveChanges = do tags <- mapM (get value) =<< liftIO (readIORef inputs) liftIO $ modifyIORef dats (\(y,x) -> (y, tags)) discardChanges :: UI () discardChanges = do liftIO $ modifyIORef inputs (const []) vdat <- liftIO (readIORef dats) mapM_ addInputVal (snd vdat) when (null (snd vdat)) (addInput) -- Add/Remove Fields addInputVal :: String -> UI () addInputVal s = do elInput <- UI.input # set value s on (domEvent "livechange") elInput $ \_ -> (liftIO $ modifyIORef edited (const True)) >> displayAll liftIO $ modifyIORef inputs (elInput:) addInput :: UI () addInput = addInputVal "" dropInput :: UI () dropInput = do elInput <- UI.input # set value "" on (domEvent "livechange") elInput $ \_ -> (liftIO $ modifyIORef edited (const True)) >> displayAll liftIO $ modifyIORef inputs ((cond null (elInput:) id).(drop 1)) -- Click behaviors on UI.click elPlus $ const $ do liftIO $ modifyIORef edited (const True) addInput redoLayout on UI.click elMinu $ const $ do liftIO $ modifyIORef edited (const True) dropInput redoLayout on UI.click elMode $ const $ do toggleMode toggler redoLayout on UI.click elSave $ const $ do saveChanges liftIO $ modifyIORef edited (const False) redoLayout on UI.click elDrop $ const $ do discardChanges liftIO $ modifyIORef edited (const False) redoLayout toggleMode >> toggler >> discardChanges >> redoLayout -- Mode toggle data Mode = View | Edit deriving (Read, Show, Eq) toggle :: Mode -> Mode toggle View = Edit toggle Edit = View canEdit :: Mode -> Bool canEdit View = False canEdit Edit = True -- conditional operator: performs function on value depending on test of value cond :: (a -> Bool) -> (a -> b) -> (a -> b) -> (a -> b) cond p f g = \x -> if p x then f x else g x example = ("Cat",[])
archaephyrryx/CCG-Project
CCGServer/Tagging.hs
bsd-3-clause
4,029
51
21
895
1,706
842
864
111
3
{-# language CPP #-} -- No documentation found for Chapter "SharingMode" module Vulkan.Core10.Enums.SharingMode (SharingMode( SHARING_MODE_EXCLUSIVE , SHARING_MODE_CONCURRENT , .. )) where import Vulkan.Internal.Utils (enumReadPrec) import Vulkan.Internal.Utils (enumShowsPrec) import GHC.Show (showsPrec) import Vulkan.Zero (Zero) import Foreign.Storable (Storable) import Data.Int (Int32) import GHC.Read (Read(readPrec)) import GHC.Show (Show(showsPrec)) -- | VkSharingMode - Buffer and image sharing modes -- -- = Description -- -- Note -- -- 'SHARING_MODE_CONCURRENT' /may/ result in lower performance access to -- the buffer or image than 'SHARING_MODE_EXCLUSIVE'. -- -- Ranges of buffers and image subresources of image objects created using -- 'SHARING_MODE_EXCLUSIVE' /must/ only be accessed by queues in the queue -- family that has /ownership/ of the resource. Upon creation, such -- resources are not owned by any queue family; ownership is implicitly -- acquired upon first use within a queue. Once a resource using -- 'SHARING_MODE_EXCLUSIVE' is owned by some queue family, the application -- /must/ perform a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-queue-transfers queue family ownership transfer> -- to make the memory contents of a range or image subresource accessible -- to a different queue family. -- -- Note -- -- Images still require a -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#resources-image-layouts layout transition> -- from 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_UNDEFINED' or -- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_PREINITIALIZED' before -- being used on the first queue. -- -- A queue family /can/ take ownership of an image subresource or buffer -- range of a resource created with 'SHARING_MODE_EXCLUSIVE', without an -- ownership transfer, in the same way as for a resource that was just -- created; however, taking ownership in this way has the effect that the -- contents of the image subresource or buffer range are undefined. -- -- Ranges of buffers and image subresources of image objects created using -- 'SHARING_MODE_CONCURRENT' /must/ only be accessed by queues from the -- queue families specified through the @queueFamilyIndexCount@ and -- @pQueueFamilyIndices@ members of the corresponding create info -- structures. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>, -- 'Vulkan.Core10.Buffer.BufferCreateInfo', -- 'Vulkan.Core10.Image.ImageCreateInfo', -- 'Vulkan.Extensions.VK_EXT_image_drm_format_modifier.PhysicalDeviceImageDrmFormatModifierInfoEXT', -- 'Vulkan.Extensions.VK_KHR_swapchain.SwapchainCreateInfoKHR' newtype SharingMode = SharingMode Int32 deriving newtype (Eq, Ord, Storable, Zero) -- | 'SHARING_MODE_EXCLUSIVE' specifies that access to any range or image -- subresource of the object will be exclusive to a single queue family at -- a time. pattern SHARING_MODE_EXCLUSIVE = SharingMode 0 -- | 'SHARING_MODE_CONCURRENT' specifies that concurrent access to any range -- or image subresource of the object from multiple queue families is -- supported. pattern SHARING_MODE_CONCURRENT = SharingMode 1 {-# complete SHARING_MODE_EXCLUSIVE, SHARING_MODE_CONCURRENT :: SharingMode #-} conNameSharingMode :: String conNameSharingMode = "SharingMode" enumPrefixSharingMode :: String enumPrefixSharingMode = "SHARING_MODE_" showTableSharingMode :: [(SharingMode, String)] showTableSharingMode = [(SHARING_MODE_EXCLUSIVE, "EXCLUSIVE"), (SHARING_MODE_CONCURRENT, "CONCURRENT")] instance Show SharingMode where showsPrec = enumShowsPrec enumPrefixSharingMode showTableSharingMode conNameSharingMode (\(SharingMode x) -> x) (showsPrec 11) instance Read SharingMode where readPrec = enumReadPrec enumPrefixSharingMode showTableSharingMode conNameSharingMode SharingMode
expipiplus1/vulkan
src/Vulkan/Core10/Enums/SharingMode.hs
bsd-3-clause
4,107
1
10
642
342
224
118
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Network.WebSockets.Socket.Tests ( tests ) where import Control.Applicative ((<$>)) import Control.Concurrent (forkIO, killThread, threadDelay) import Control.Exception (SomeException, catch) import Control.Monad (forever, forM_, replicateM) import Prelude hiding (catch) import Data.ByteString (ByteString) import Data.Enumerator (Iteratee, ($$)) import System.Random (newStdGen) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, (@=?)) import Test.QuickCheck (Arbitrary, arbitrary) import Test.QuickCheck.Gen (Gen (..)) import qualified Data.ByteString.Lazy as BL import qualified Data.Enumerator as E import qualified Network.Socket as S import qualified Network.Socket.Enumerator as SE import Network.WebSockets import Network.WebSockets.Monad import Network.WebSockets.Socket import Network.WebSockets.Protocol.Hybi00.Internal import Network.WebSockets.Protocol.Hybi10.Internal import Network.WebSockets.Tests.Util import Network.WebSockets.Tests.Util.Http tests :: Test tests = testGroup "Network.WebSockets.Socket.Tests" [ testCase "sendReceive-hybi10" (sendReceive Hybi10_) , testCase "sendReceive-hybi00" (sendReceive Hybi00_) ] client :: Int -> (Iteratee ByteString IO () -> Iteratee ByteString IO a) -> IO a client port app = do sock <- S.socket S.AF_INET S.Stream S.defaultProtocol hostAddr <- S.inet_addr "127.0.0.1" let addr = S.SockAddrInet (fromIntegral port) hostAddr S.connect sock addr res <- E.run_ $ SE.enumSocket 4096 sock $$ app $ iterSocket sock S.sClose sock return res webSocketsClient :: Protocol p => Int -> p -> WebSockets p a -> IO a webSocketsClient port proto ws = client port $ runWebSocketsWith' defaultWebSocketsOptions proto ws sample :: Arbitrary a => IO [a] sample = do gen <- newStdGen return $ (unGen arbitrary) gen 512 sendReceive :: forall p. (ExampleRequest p, TextProtocol p) => p -> Assertion sendReceive proto = do serverThread <- forkIO $ retry $ runServer "0.0.0.0" 42940 server waitSome texts <- map unArbitraryUtf8 <$> sample texts' <- retry $ webSocketsClient 42940 proto $ client' texts waitSome killThread serverThread texts @=? texts' where waitSome = threadDelay $ 200 * 1000 server :: Request -> WebSockets p () server _ = flip catchWsError (\_ -> return ()) $ forever $ do text <- receiveData sendTextData (text :: BL.ByteString) client' :: [BL.ByteString] -> WebSockets p [BL.ByteString] client' texts = do sendBuilder $ encodeRequestBody $ exampleRequest proto forM_ texts sendTextData replicateM (length texts) $ do receiveData -- HOLY SHIT WHAT SORT OF ATROCITY IS THIS?!?!?! -- -- The problem is that sometimes, the server hasn't been brought down yet -- before the next test, which will cause it not to be able to bind to the -- same port again. In this case, we just retry. -- -- The same is true for our client: possibly, the server is not up yet -- before we run the client. We also want to retry in that case. retry :: IO a -> IO a retry action = action `catch` \(_ :: SomeException) -> action
0xfaded/websockets
tests/haskell/Network/WebSockets/Socket/Tests.hs
bsd-3-clause
3,287
0
13
636
897
482
415
69
1
{-{ http://en2.wikipedia.org/wiki/Zenix_(game) }-} ----------- -- Zenix -- ----------- module Zenix (Zenix, zenix) where import Game import Data.Array import Graphics.UI.WX hiding (border, point) import Graphics.UI.WXCore hiding (point) import Tools data Zenix = Zenix (Array (Int, Int) (Maybe Player)) deriving (Eq, Show) type ZenixMove = (Int, Int) zenix :: Zenix zenix = undefined instance Game Zenix where name _ = "zenix" standard _ = Properties { players = 2, boardsize = 8, human = [True, False, False] } possible _ = PropertyRange { playersrange = [2, 3], boardsizerange = [4 .. 12] } new pr = let bsz = boardsize pr in Zenix $ array ((0, 0), (bsz - 1, bsz - 1)) [((x, y), Nothing) | x <- [0 .. bsz - 1], y <- [0 .. bsz - 1]] moves pr p (Zenix st) = map (move pr) (allMoves pr p st) showmove pr p (Zenix s) i = case allMoves pr p s !! i of (x, y) -> ['a' ..] !! x : show (1 + y) value pr p (Zenix st) | null $ allMoves pr p st = let winners = map fst $ filter (\(_i, c) -> c == maximum chains) $ zip [0 ..] chains in foldr ($) (replicate (players pr) (-1)) $ map (|> 1) winners | otherwise = map myvalue [0 .. players pr - 1] where bsz = boardsize pr chains :: [Int] chains = map (\p' -> scan p' bsz []) [0 .. players pr - 1] myvalue :: Player -> Float myvalue p' = let t = fromInteger . toInteger $ (players pr) * (chains !! p') - sum chains n = fromInteger . toInteger $ 2 * bsz in t / n scan :: Player -> Int -> [Int] -> Int scan p' y _ | y >= bsz = scan p' (bsz - 1) [0 .. bsz] scan _p y [] = bsz - y scan p' y xs = scan p' (y - 1) $ filter good [0 .. y] where good :: Int -> Bool good x = st ! (x, y) == Just p' && (x `elem` xs || (x + 1) `elem` xs) board p pr vart _ia move' = do marble <- bitmapCreateLoad "images\\marble.bmp" wxBITMAP_TYPE_ANY varg <- varCreate $ grate rectZero 0 (0, 0) sizeZero let onpaint :: DC () -> Rect -> IO () onpaint dc r = do t <- varGet vart let Zenix st = state t bsz = boardsize pr b <- border dc (bsz, bsz) let g = grate r b (2 * bsz, bsz) (Size 4 7) radius = rectWidth (field g (0, 0)) {- lin' :: Rect -> Rect -> Color -> IO () lin' (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) c = do line dc (pt (x1 + w1 `div` 2) (y1 + h1)) (pt (x2 + w2 `div` 2) (y2 + h2)) [penWidth := 4, penColor := c] lin :: (Int, Int) -> (Int, Int) -> Color -> IO () lin p q = lin' (field g $ tograte bsz p) (field g $ tograte bsz q) -} varSet varg g tileBitmap dc r marble --{ drawGrate dc g [penColor := yellow] for 0 (bsz - 1) (\i -> do drawTextRect dc [['A' ..] !! i] $ edge g (2 * i, bsz) drawTextRect dc (show (i + 1)) $ field g (i - 1, bsz - i - 1) ) for 0 (bsz - 1) (\i -> for 0 (bsz - 1) (\j -> when (j - i >= 0) $ drawPiece dc (field g $ tograte bsz (i, j)) radius (st ! (i, j)) )) onclick :: Point -> IO () onclick point = do t <- varGet vart g <- varGet varg let Zenix st = state t bsz = boardsize pr n = fromgrate bsz $ locate g point case lookup n $ zip (allMoves pr (player t) st) [0..] of Nothing -> return () Just i -> move' i set p [ on click := onclick , on paint := onpaint , on resize ::= repaint ] return () drawPiece :: DC () -> Rect -> Int -> Maybe Player -> IO () drawPiece dc (Rect x y _w h) r mp = do case mp of Just 0 -> circle dc (pt x (y + h `div` 2)) r [brushKind := BrushSolid, brushColor := blue ] Just 1 -> circle dc (pt x (y + h `div` 2)) r [brushKind := BrushSolid, brushColor := red ] Just 2 -> circle dc (pt x (y + h `div` 2)) r [brushKind := BrushSolid, brushColor := green] Nothing -> circle dc (pt x (y + h `div` 2)) r [brushKind := BrushTransparent] _ -> error "drawPiece: Unexpected value" {- (+-) :: Num a => (a, a) -> (a, a) -> (a, a) (a, b) +- (c, d) = (a + c, b + d) -} allMoves :: Properties -> Player -> Array (Int, Int) (Maybe Player) -> [ZenixMove] allMoves pr _p st | otherwise = filter free $ indices st where bsz = boardsize pr free :: ZenixMove -> Bool free (x, y) = y - x >= 0 && st ! (x, y) == Nothing && (y == bsz - 1 || (st ! (x, y + 1) /= Nothing && st ! (x + 1, y + 1) /= Nothing)) move :: Properties -> ZenixMove -> (Player, Zenix) -> (Player, Zenix) move pr place (p, Zenix s) = ( (p + 1) `mod` players pr , Zenix $ s // [(place, Just p)] ) {-{ win :: Array (Int, Int) (Maybe Player) -> Int -> Player -> Bool win st bsz 0 = any ((== bsz - 1) . snd) $ floodfill st 0 (zip [0 .. bsz - 1] [-1, -1 ..]) win st bsz 1 = any ((== bsz - 1) . fst) $ floodfill st 1 (zip [-1, -1 ..] [0 .. bsz - 1]) floodfill :: Array (Int, Int) (Maybe Player) -> Player -> [(Int, Int)] -> [(Int, Int)] floodfill st p togo = floodfill_ p togo [] where floodfill_ :: Player -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] floodfill_ p [] known = known floodfill_ p (f : togo) known = let new = filter (not . flip elem known) $ map (f +-) steps good = filter (\f -> st ! f == Just p) $ filter (inRange (bounds st)) new in floodfill_ p (togo ++ good) (known ++ good) steps :: [(Int, Int)] steps = [(1, 1), (1, 0), (0, -1), (-1, -1), (-1, 0), (0, 1)] jumps :: [((Int, Int), [(Int, Int)])] jumps = [ (( 2, 1), [( 1, 0), ( 1, 1)]) , (( 1, 2), [( 0, 1), ( 1, 1)]) , ((-1, 1), [( 0, 1), (-1, 0)]) , ((-2, -1), [(-1, 0), (-1, -1)]) , ((-1, -2), [( 0, -1), (-1, -1)]) , (( 1, -1), [( 1, 0), ( 0, -1)]) ] }-} tograte :: Int -> (Int, Int) -> (Int, Int) tograte bsz (i, j) = (bsz + 2 * i - j, j) fromgrate :: Int -> (Int, Int) -> (Int, Int) fromgrate bsz (i, j) = ((i + j - bsz + 1) `div` 2, j) {- i = s - 1 + x - y j = 2s - 2 - x - y i + j = 3s - 3 - 2y 2y = 3s - 3 - i - j y = (...) / 2 i - j = -s + 1 + 2x 2x = s - 1 + i - j -} {- the zenixboard internally look like this: 0 * 1 * * 2 * * * 3 * * * * 4 * * * * * 5 * * * * * * 0 1 2 3 4 5 -}
HJvT/GeBoP
Zenix.hs
bsd-3-clause
6,548
0
24
2,278
2,220
1,166
1,054
92
5
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE Safe #-} #endif #if __GLASGOW_HASKELL__ >= 708 {-# LANGUAGE RoleAnnotations #-} #endif #if __GLASGOW_HASKELL__ >= 710 {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Data.NF.Internal -- Copyright : (c) Stanford University 2015 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ezyang@cs.stanford.edu -- Stability : experimental -- Portability : portable -- -- This module is intended for internal use. Unlike "Data.NF.Unsafe", -- this module exports the true constructor for 'NF', globally revealing -- coercibility between @a@ and @'NF' a@, etc., in the importing module. -- This is usually overkill, and makes it harder to avoid accidentally -- performing invalid coercions. module Data.NF.Internal( #if __GLASGOW_HASKELL__ >= 800 NF(..,NF) #else NF(..) #if __GLASGOW_HASKELL__ >= 710 , pattern NF #endif #endif ) where import Control.DeepSeq import Data.Typeable -- | 'NF' is an abstract data type representing data which has been -- evaluated to normal form. Specifically, if a value of type @'NF' a@ -- is in weak head normal form, then it is in reduced normal form; -- alternatively, it is only necessary to 'seq' an @'NF' a@ to assure that -- it is fully evaluated. newtype NF a -- | For @'UnsafeNF' x@ to preserve the 'NF' invariant, you must -- show that @'UnsafeNF' x == 'deepseq' x ('UnsafeNF' x)@. = UnsafeNF a deriving (Eq, Ord, Typeable) #if __GLASGOW_HASKELL__ >= 708 -- Suppose we have -- -- data T = ... -- newtype U = U T -- instance NFData T where ... -- instance NFData U where ... something different ... -- -- If we let GHC infer a representational role for NF's parameter, -- then someone could coerce from NF T (which is presumed to be in -- T-normal form) to NF U (which is expected to be in U-normal form). type role NF nominal #endif -- UGH! GHC swapped the constraint order between -- 7.10 and 8.0. If anyone's using some beta compiler in between, -- it might throw up. -- -- Very unfortunately, GHC (as of 8.0) does not allow the pattern -- synonym to be *matched* without an NFData context. Hopefully -- this will be fixed eventually. #if __GLASGOW_HASKELL__ >= 710 -- | Pattern synonym for the 'NF' type. Applying this synonym -- is equivalent to calling 'Data.NF.makeNF'; matching on it -- is equivalent to calling 'Data.NF.getNF'. #endif #if __GLASGOW_HASKELL__ == 710 pattern NF :: () => NFData a => a -> NF a #elif __GLASGOW_HASKELL__ >= 800 pattern NF :: NFData a => a -> NF a #endif #if __GLASGOW_HASKELL__ >= 710 pattern NF a <- UnsafeNF a where NF a = a `deepseq` UnsafeNF a #endif instance NFData (NF a) where rnf x = x `seq` ()
ezyang/nf
Data/NF/Internal.hs
bsd-3-clause
2,859
2
9
523
212
148
64
11
0
{-# LANGUAGE TemplateHaskell #-} module Game.Monsters.MMutantGlobals where import Control.Lens (makeLenses) import Types makeLenses ''MMutantGlobals initialMMutantGlobals :: MMutantGlobals initialMMutantGlobals = MMutantGlobals { _mMutantSoundSwing = 0 , _mMutantSoundHit = 0 , _mMutantSoundHit2 = 0 , _mMutantSoundDeath = 0 , _mMutantSoundIdle = 0 , _mMutantSoundPain1 = 0 , _mMutantSoundPain2 = 0 , _mMutantSoundSight = 0 , _mMutantSoundSearch = 0 , _mMutantSoundStep1 = 0 , _mMutantSoundStep2 = 0 , _mMutantSoundStep3 = 0 , _mMutantSoundThud = 0 }
ksaveljev/hake-2
src/Game/Monsters/MMutantGlobals.hs
bsd-3-clause
795
0
6
317
119
76
43
20
1
module Code29_Loopless where import Data.List hiding (insert) import Code28 {- bumpDn = unfoldr stepDn . prologDn prologDn (k,n) = (k,k,n-1,1) stepDn (j,k,m,n) = if m < n then Nothing else Just (m+j,(k-j,k,m-1,n)) prologUp (k,n) = (if even n then k else 0,k,1,n-1) stepUp (j,k,m,n) = if m > n then Nothing else Just (m+j,(k-j,k,m+1,n)) -} jcode :: Int -> [Int] jcode = unfoldr step . wrapQueue . fst . foldr op' (empty,empty) . pairs where pairs n = addpair (0,n) [] addpair :: (Int,Int) -> [(Int,Int)] -> [(Int,Int)] addpair (_,1) ps = ps addpair (k,n) ps = addpair (k',n-1) ((k,n):ps) where k' = if odd n then k+1 else 1 mix :: [a] -> (Queue (Rose a), Queue (Rose a)) -> Queue (Rose a) mix [] (ys,_) = ys mix (x:xs) (ys,sy) = insert ys (Node x (mix xs (sy,ys))) step :: [Forest a] -> Maybe (a, [Forest a]) step [] = Nothing step (zs:zss) = Just (x,consQueue xs (consQueue ys zss)) where (Node x xs, ys) = remove zs consQueue :: Queue a -> [Queue a] -> [Queue a] consQueue xs xss = if isempty xs then xss else xs:xss wrapQueue :: Queue a -> [Queue a] wrapQueue xs = consQueue xs [] bump :: (Int,Int,Int,Int,Int) -> Maybe (Int,(Int,Int,Int,Int,Int)) bump (i,j,k,m,n) = if i*(n-m) < 0 then Nothing else Just (m+j,(i,k-j,k,m+i,n)) prologDn :: (Int,Int) -> (Int,Int,Int,Int,Int) prologDn (k,n) = (-1,k,k,n-1,1) prologUp :: (Int,Int) -> (Int,Int,Int,Int,Int) prologUp (k,n) = (1,if even n then k else 0,k,1,n-1) op' :: (Int, Int) -> (Forest Int,Forest Int) -> (Forest Int,Forest Int) op' (k,n) (ys,sy) = if odd n then ( mix (unfoldr bump (-1,k,k,n-1,1)) (ys,sy), mix (unfoldr bump (1,0,k,1,n-1)) (sy,ys)) else ( mix (unfoldr bump (-1,k,k,n-1,1)) (ys,sy), mix (unfoldr bump (1,k,k,1,n-1)) (ys,sy))
sampou-org/pfad
Code/Code29_Loopless.hs
bsd-3-clause
2,025
0
11
621
1,023
578
445
35
2
{-# LANGUAGE MultiParamTypeClasses, GeneralizedNewtypeDeriving, FlexibleInstances, UndecidableInstances, GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ViewPatterns #-} module Language.JQuery.Internal.Types where import Control.Monad.State import Text.Blaze.Html import Text.Blaze.Html.Renderer.String import Language.JavaScript.AST data JQueryStmt where JQS_jQuery :: (JQueryVariable t, JQuerySelector sel) => sel -> JQueryStmts t -> JQueryStmt JQS_bind :: (JQueryVariable t, JQuerySelector sel) => JQueryVar t -> sel -> JQueryStmts t -> JQueryStmt data JQueryStmts t where JQSs_chain :: JQueryStmts a -> JQueryStmts b -> JQueryStmts b JQSs_call :: String -> [Expr] -> JQueryStmts a newtype JQuery a = JQuery { unJQ :: State JQueryS a } data JQueryS = JQueryS { jqueryLastStmt :: Maybe JQueryStmt , jqueryLastVarId :: Int , jqueryChain :: JQueryChain } data JQueryChain where JQC_empty :: JQueryChain JQC_single :: JQueryStmt -> JQueryChain JQC_chain :: JQueryChain -> JQueryStmt -> JQueryChain -------------------------------------------------------------------------------- -- newtypes newtype JQueryObject = JQueryObject Name -------------------------------------------------------------------------------- -- Variables newtype JQueryVar a = JQueryVar Name class JQueryVariable a where type Var a bindable :: JQueryStmts a -> Bool toVar :: JQueryStmts a -> Name -> Var a instance JQueryVariable () where type Var () = () bindable _ = False toVar _ _ = () instance JQueryVariable String where type Var String = JQueryVar String bindable _ = True toVar _ n = JQueryVar n -------------------------------------------------------------------------------- -- Values class JavaScriptValue t a | a -> t where valToExpr :: a -> Expr instance JavaScriptValue String String where valToExpr (jsString -> Right jss) = ExprLit (LitString jss) valToExpr s = error $ "`JavaScriptValue valToExpr' conversion error of String \"" ++ s ++ "\"" instance JavaScriptValue Html Html where valToExpr h = valToExpr (renderHtml h) instance JavaScriptValue Double Double where valToExpr d = ExprLit (LitNumber (Number d)) instance JavaScriptValue Bool Bool where valToExpr b = ExprLit (LitBool b) instance JavaScriptValue t a => JavaScriptValue t (JQueryVar a) where valToExpr (JQueryVar n) = ExprName n -- | Class \"alias\" for @JavaScriptValue String a@ class JavaScriptValue String a => StringValue a where instance JavaScriptValue String a => StringValue a where -- | Class \"alias\" for @JavaScriptValue Html a@ class JavaScriptValue Html a => HtmlValue a where instance JavaScriptValue Html a => HtmlValue a where -------------------------------------------------------------------------------- -- Selectors -- type Selector = JQuerySelector a => a class JQuerySelector a where selToExpr :: a -> Expr instance JQuerySelector String where selToExpr (jsString -> Right jss) = ExprLit (LitString jss) selToExpr s = error $ "`JQuerySelector selToExpr' conversion error of String \"" ++ s ++ "\"" instance JQuerySelector JQueryObject where selToExpr (JQueryObject n) = ExprName n
mcmaniac/hs-jquery
src/Language/JQuery/Internal/Types.hs
bsd-3-clause
3,468
0
10
691
776
411
365
-1
-1
{-# LANGUAGE TupleSections, GADTs, StandaloneDeriving #-} module V1SizeFlow ( sizeFlow, Suspended, SizeFlowResult ) where import V1IState import V1Flow newtype Size = Size Int deriving (Read, Show) newtype Height = Height Int deriving (Read, Show) newtype Weight = Weight Int deriving (Read, Show) newtype Colour = Colour String deriving (Read, Show) askKnownSize :: StateMachine as (Bool, as) Bool askKnownSize = askYN "Do you know your size?" (,) -- askSize takes an environment of type as and adds a Size element askSize :: StateMachine as (Size, as) Size askSize = askNumber "What is your size?" Size (,) -- askHeight takes an environment of type as and adds a Height element askHeight :: StateMachine as (Height, as) Height askHeight = askNumber "What is your height?" Height (,) -- etc askWeight :: StateMachine as (Weight, as) Weight askWeight = askNumber "What is your weight?" Weight (,) askColour :: StateMachine as (Colour, as) () askColour = ilift (putStrLn "What is your favourite colour?") >>> ilift readLn >>>= \answer -> imodify (Colour answer,) calculateSize :: Height -> Weight -> Size calculateSize (Height h) (Weight w) = Size (h - w) -- or whatever the calculation is data Stage as where AskKnownSize :: Stage () AskSize :: Stage (Bool, ()) AskWeight :: Stage (Bool, ()) AskHeight :: Stage (Weight, (Bool, ())) AskColour :: Stage (Size, (Bool, ())) deriving instance Show (Stage as) data Suspended where Suspended :: (Show as) => Stage as -> as -> Suspended instance Show Suspended where show (Suspended stage as) = show stage ++ ", " ++ show as instance Read Suspended where readsPrec = const $ uncurry ($) . mapFst parse . fmap (drop 2) . break (==',') where parse :: String -> String -> [(Suspended, String)] parse stage = case stage of "AskKnownSize" -> parse' AskKnownSize "AskSize" -> parse' AskSize "AskWeight" -> parse' AskWeight "AskHeight" -> parse' AskHeight "AskColour" -> parse' AskColour _ -> const [] parse' :: (Show as, Read as) => Stage as -> String -> [(Suspended, String)] parse' stg st = [(Suspended stg (read st), mempty)] mapFst :: (a -> c) -> (a, b) -> (c, b) mapFst f ~(a, b) = (f a, b) type SizeFlowResult = (Colour, (Size, (Bool, ()))) resume :: Suspended -> StateMachine as SizeFlowResult () resume (Suspended AskKnownSize e) = iput e >>> suspend AskKnownSize >>> askKnownSize >>>= \ b -> resume' (if b then AskSize else AskWeight) (b, e) resume (Suspended AskSize e) = iput e >>> askSize >>> iget >>>= resume' AskColour resume (Suspended AskWeight e) = iput e >>> askWeight >>> iget >>>= resume' AskHeight resume (Suspended AskHeight e) = iput e >>> askHeight >>> imodify (\(h, (w, xs)) -> (calculateSize h w, xs)) >>> iget >>>= resume' AskColour resume (Suspended AskColour e) = iput e >>> askColour -- >>> iget >>>= ireturn resume' :: Show as => Stage as -> as -> StateMachine as SizeFlowResult () resume' stage as = suspend stage >>> resume (Suspended stage as) -- given persist :: Suspended -> IO () suspend :: (Show as) => Stage as -> StateMachine as as () suspend = suspend' Suspended -- iget >>>= \env -> -- ilift (persist (Suspended stage env)) suspend' :: Show sp => (stage -> as -> sp) -> stage -> StateMachine as as () suspend' mks stage = iget >>>= \env -> ilift (persist (mks stage env)) sizeFlow :: Flow Suspended as SizeFlowResult () sizeFlow = Flow resume -- resumeFlow () "AskWeight, (False,())" sizeFlow
homam/fsm-conversational-ui
src/V1SizeFlow.hs
bsd-3-clause
3,589
0
12
788
1,253
666
587
83
2
module Insomnia.ToF.Query where import qualified Unbound.Generics.LocallyNameless as U import Insomnia.Query import Insomnia.ToF.Env import Insomnia.ToF.Module (modulePath) import qualified FOmega.Syntax as F queryExpr :: ToF m => QueryExpr -> m F.Command queryExpr qe_ = case qe_ of GenSamplesQE p params -> do (_absSig, m) <- modulePath p let vl = U.s2n "l" l = F.V vl queryCmd = F.EffectC (F.SamplePC params) m printCmd = F.EffectC F.PrintPC l c = F.BindC $ U.bind (vl, U.embed queryCmd) printCmd return c
lambdageek/insomnia
src/Insomnia/ToF/Query.hs
bsd-3-clause
569
0
17
136
199
106
93
18
1
import Parser (parseString) import CodeGenerator (compile) import BfIR (toString) import Control.Applicative((<$>)) import qualified Data.ByteString.Lazy.Char8 as BLC import ShortBytes(getCachedShortByteParams) main :: IO () main = do shortByteParams <- getCachedShortByteParams (toString . compile shortByteParams . parseString) <$> getContents >>= BLC.putStrLn --main = print $ length $ optimizeOutput (replicate 100000000 $ BfDot) -- main :: IO () -- main = (show . parseString) <$> getContents >>= putStrLn
benma/bfc
src/Main.hs
bsd-3-clause
521
0
12
74
107
63
44
10
1
module SpaceAge (Planet(..), ageOn) where data Planet = Mercury | Venus | Earth | Mars | Jupiter | Saturn | Uranus | Neptune yearRelativeToEarth :: Planet -> Double yearRelativeToEarth Earth = 1.0 yearRelativeToEarth Mercury = 0.2408467 yearRelativeToEarth Venus = 0.61519726 yearRelativeToEarth Mars = 1.8808158 yearRelativeToEarth Jupiter = 11.862615 yearRelativeToEarth Saturn = 29.447498 yearRelativeToEarth Uranus = 84.016846 yearRelativeToEarth Neptune = 164.79132 ageOn :: Planet -> Double -> Double ageOn planet seconds = seconds / (secondsInYear * yearRelativeToEarth planet) where secondsInYear = 60 * 60 * 24 * 365.25
Bugfry/exercises
exercism/haskell/space-age/src/SpaceAge.hs
mit
727
0
9
185
173
95
78
21
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ECS.DeregisterTaskDefinition -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deregisters the specified task definition by family and revision. Upon -- deregistration, the task definition is marked as 'INACTIVE'. Existing -- tasks and services that reference an 'INACTIVE' task definition continue -- to run without disruption. Existing services that reference an -- 'INACTIVE' task definition can still scale up or down by modifying the -- service\'s desired count. -- -- You cannot use an 'INACTIVE' task definition to run new tasks or create -- new services, and you cannot update an existing service to reference an -- 'INACTIVE' task definition (although there may be up to a 10 minute -- window following deregistration where these restrictions have not yet -- taken effect). -- -- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterTaskDefinition.html AWS API Reference> for DeregisterTaskDefinition. module Network.AWS.ECS.DeregisterTaskDefinition ( -- * Creating a Request deregisterTaskDefinition , DeregisterTaskDefinition -- * Request Lenses , derTaskDefinition -- * Destructuring the Response , deregisterTaskDefinitionResponse , DeregisterTaskDefinitionResponse -- * Response Lenses , dtdrsTaskDefinition , dtdrsResponseStatus ) where import Network.AWS.ECS.Types import Network.AWS.ECS.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'deregisterTaskDefinition' smart constructor. newtype DeregisterTaskDefinition = DeregisterTaskDefinition' { _derTaskDefinition :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeregisterTaskDefinition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'derTaskDefinition' deregisterTaskDefinition :: Text -- ^ 'derTaskDefinition' -> DeregisterTaskDefinition deregisterTaskDefinition pTaskDefinition_ = DeregisterTaskDefinition' { _derTaskDefinition = pTaskDefinition_ } -- | The 'family' and 'revision' ('family:revision') or full Amazon Resource -- Name (ARN) of the task definition that you want to deregister. You must -- specify a 'revision'. derTaskDefinition :: Lens' DeregisterTaskDefinition Text derTaskDefinition = lens _derTaskDefinition (\ s a -> s{_derTaskDefinition = a}); instance AWSRequest DeregisterTaskDefinition where type Rs DeregisterTaskDefinition = DeregisterTaskDefinitionResponse request = postJSON eCS response = receiveJSON (\ s h x -> DeregisterTaskDefinitionResponse' <$> (x .?> "taskDefinition") <*> (pure (fromEnum s))) instance ToHeaders DeregisterTaskDefinition where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonEC2ContainerServiceV20141113.DeregisterTaskDefinition" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DeregisterTaskDefinition where toJSON DeregisterTaskDefinition'{..} = object (catMaybes [Just ("taskDefinition" .= _derTaskDefinition)]) instance ToPath DeregisterTaskDefinition where toPath = const "/" instance ToQuery DeregisterTaskDefinition where toQuery = const mempty -- | /See:/ 'deregisterTaskDefinitionResponse' smart constructor. data DeregisterTaskDefinitionResponse = DeregisterTaskDefinitionResponse' { _dtdrsTaskDefinition :: !(Maybe TaskDefinition) , _dtdrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeregisterTaskDefinitionResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtdrsTaskDefinition' -- -- * 'dtdrsResponseStatus' deregisterTaskDefinitionResponse :: Int -- ^ 'dtdrsResponseStatus' -> DeregisterTaskDefinitionResponse deregisterTaskDefinitionResponse pResponseStatus_ = DeregisterTaskDefinitionResponse' { _dtdrsTaskDefinition = Nothing , _dtdrsResponseStatus = pResponseStatus_ } -- | The full description of the deregistered task. dtdrsTaskDefinition :: Lens' DeregisterTaskDefinitionResponse (Maybe TaskDefinition) dtdrsTaskDefinition = lens _dtdrsTaskDefinition (\ s a -> s{_dtdrsTaskDefinition = a}); -- | The response status code. dtdrsResponseStatus :: Lens' DeregisterTaskDefinitionResponse Int dtdrsResponseStatus = lens _dtdrsResponseStatus (\ s a -> s{_dtdrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ecs/gen/Network/AWS/ECS/DeregisterTaskDefinition.hs
mpl-2.0
5,401
0
13
1,075
591
357
234
79
1
module Ignore where
carymrobbins/intellij-haskforce
tests/gold/resolve/Module00003/Ignore.hs
apache-2.0
20
0
2
3
4
3
1
1
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Servant.Swagger.Internal.TypeLevel.TMap where import Data.Proxy import GHC.Exts (Constraint) -- $setup -- >>> :set -XDataKinds -- >>> :set -XFlexibleContexts -- >>> :set -XGADTs -- >>> :set -XRankNTypes -- >>> :set -XScopedTypeVariables -- >>> import GHC.TypeLits -- >>> import Data.List -- | Map a list of constrained types to a list of values. -- -- >>> tmap (Proxy :: Proxy KnownSymbol) symbolVal (Proxy :: Proxy ["hello", "world"]) -- ["hello","world"] class TMap (q :: k -> Constraint) (xs :: [k]) where tmap :: p q -> (forall x p'. q x => p' x -> a) -> p'' xs -> [a] instance TMap q '[] where tmap _ _ _ = [] instance (q x, TMap q xs) => TMap q (x ': xs) where tmap q f _ = f (Proxy :: Proxy x) : tmap q f (Proxy :: Proxy xs)
haskell-servant/servant-swagger
src/Servant/Swagger/Internal/TypeLevel/TMap.hs
bsd-3-clause
1,163
0
13
277
233
135
98
19
0
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Control.Exception (SomeException, try) import qualified Data.Text as T import Snap.Http.Server import Snap.Snaplet import Snap.Core import Snap.Snaplet.Config import System.IO import Site #ifdef DEVELOPMENT import Snap.Loader.Dynamic #else import Snap.Loader.Static #endif main :: IO () main = do (conf, site, cleanup) <- $(loadSnapTH [| getConf |] 'getActions ["resources/templates"]) _ <- try $ httpServe conf site :: IO (Either SomeException ()) cleanup getConf :: IO (Config Snap AppConfig) getConf = commandLineConfig defaultConfig -- | This function generates the the site handler and cleanup action -- from the configuration. In production mode, this action is only -- run once. In development mode, this action is run whenever the -- application is reloaded. -- -- Development mode also makes sure that the cleanup actions are run -- appropriately before shutdown. The cleanup action returned from -- loadSnapTH should still be used after the server has stopped -- handling requests, as the cleanup actions are only automatically -- run when a reload is triggered. -- -- This sample doesn't actually use the config passed in, but more -- sophisticated code might. getActions :: Config Snap AppConfig -> IO (Snap (), IO ()) getActions conf = do (msgs, site, cleanup) <- runSnaplet (appEnvironment =<< getOther conf) app hPutStrLn stderr $ T.unpack msgs return (site, cleanup)
Palmik/snaplet-mongodb-minimalistic
examples/example1/src/Main.hs
bsd-3-clause
1,674
0
11
431
286
162
124
26
1
{-# LANGUAGE RebindableSyntax #-} {-# OPTIONS_GHC -fplugin Control.Supermonad.Plugin #-} {- ****************************************************************************** * H M T C * * * * Module: ScopeLevel * * Purpose: Definition of and operation on scope level. * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2013 * * * ****************************************************************************** -} -- | ScopeLevel: Definition of and operation on scope level module ScopeLevel ( ScopeLvl, -- Scope level topMajScopeLvl, -- :: Int topScopeLvl, -- :: ScopeLvl majScopeLvl, -- :: ScopeLvl -> Int minScopeLvl, -- :: ScopeLvl -> Int incMajScopeLvl, -- :: ScopeLvl -> ScopeLvl incMinScopeLvl -- :: ScopeLvl -> ScopeLvl ) where import Control.Supermonad.Prelude ------------------------------------------------------------------------------ -- Scope level ------------------------------------------------------------------------------ -- | Scope level. -- Pair of major (depth of procedure/function) nesting -- and minor (depth of let-command nesting) levels. type ScopeLvl = (Int, Int) topMajScopeLvl :: Int topMajScopeLvl = 0 topScopeLvl :: ScopeLvl topScopeLvl = (topMajScopeLvl, 0) majScopeLvl :: ScopeLvl -> Int majScopeLvl = fst minScopeLvl :: ScopeLvl -> Int minScopeLvl = fst incMajScopeLvl :: ScopeLvl -> ScopeLvl incMajScopeLvl (majl, _) = (majl + 1, 0) incMinScopeLvl :: ScopeLvl -> ScopeLvl incMinScopeLvl (majl, minl) = (majl, minl + 1)
jbracker/supermonad-plugin
examples/monad/hmtc/supermonad/ScopeLevel.hs
bsd-3-clause
2,021
0
6
742
182
117
65
24
1
{-# LANGUAGE ExistentialQuantification, GADTs, ScopedTypeVariables, TypeFamilies, FlexibleInstances, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, BangPatterns, UndecidableInstances, EmptyDataDecls, RecursiveDo, RoleAnnotations, FunctionalDependencies, FlexibleContexts #-} module Reflex.Host.Class where import Reflex.Class import Control.Applicative import Control.Monad.Fix import Control.Monad.Trans import Control.Monad.Trans.Reader (ReaderT()) import Control.Monad.Trans.Writer (WriterT()) import Control.Monad.Trans.Cont (ContT()) import Control.Monad.Trans.Except (ExceptT()) import Control.Monad.Trans.RWS (RWST()) import Control.Monad.Trans.State (StateT()) import qualified Control.Monad.Trans.State.Strict as Strict import Data.Dependent.Sum (DSum) import Data.Monoid import Data.GADT.Compare import Control.Monad.Ref -- Note: this import must come last to silence warnings from AMP import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl) -- | Framework implementation support class for the reflex implementation represented by @t@. class (Reflex t, MonadReflexCreateTrigger t (HostFrame t), MonadSample t (HostFrame t), MonadHold t (HostFrame t), MonadFix (HostFrame t), MonadSubscribeEvent t (HostFrame t)) => ReflexHost t where type EventTrigger t :: * -> * type EventHandle t :: * -> * type HostFrame t :: * -> * -- | Monad in which Events can be 'subscribed'. This forces all underlying event sources to be initialized, so that the event will fire whenever it ought to. Events must be subscribed before they are read using readEvent class (Reflex t, Monad m) => MonadSubscribeEvent t m | m -> t where -- | Subscribe to an event and set it up if needed. -- -- This function will create a new 'EventHandle' from an 'Event'. This handle may then be used via -- 'readEvent' in the read callback of 'fireEventsAndRead'. -- -- If the event wasn't subscribed to before (either manually or through a dependent event or behavior) -- then this function will cause the event and all dependencies of this event to be set up. -- For example, if the event was created by 'newEventWithTrigger', then it's callback will be executed. -- -- It's safe to call this function multiple times. subscribeEvent :: Event t a -> m (EventHandle t a) -- | Monad that allows to read events' values. class (ReflexHost t, Applicative m, Monad m) => MonadReadEvent t m | m -> t where -- | Read the value of an 'Event' from an 'EventHandle' (created by calling 'subscribeEvent'). -- -- After event propagation is done, all events can be in two states: either they are firing with some value or they are not firing. -- In the former case, this function returns @Just act@, where @act@ in an action to read the current value of -- the event. In the latter case, the function returns @Nothing@. -- -- This function is normally used in the calllback for 'fireEventsAndRead'. readEvent :: EventHandle t a -> m (Maybe (m a)) -- | A monad where new events feed from external sources can be created. class (Applicative m, Monad m) => MonadReflexCreateTrigger t m | m -> t where -- | Creates a root 'Event' (one that is not based on any other event). -- -- When a subscriber first subscribes to an event (building another event -- that depends on the subscription) the given callback function is run and -- passed a trigger. The callback function can then set up the event source in IO. -- After this is done, the callback function must return an accompanying teardown action. -- -- Any time between setup and teardown the trigger can be used to fire -- the event, by passing it to 'fireEventsAndRead'. -- -- Note: An event may be set up multiple times. So after the teardown action is executed, the event may still be set up again in the future. newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a) newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k) class (ReflexHost t, MonadReflexCreateTrigger t m, MonadSubscribeEvent t m, MonadReadEvent t (ReadPhase m), MonadSample t (ReadPhase m), MonadHold t (ReadPhase m)) => MonadReflexHost t m | m -> t where type ReadPhase m :: * -> * -- | Propagate some events firings and read the values of events afterwards. -- -- This function will create a new frame to fire the given events. It will then update all -- dependent events and behaviors. After that is done, the given callback is executed which -- allows to read the final values of events and check whether they have fired in this frame or -- not. -- -- All events that are given are fired at the same time. -- -- This function is typically used in the main loop of a reflex framework implementation. -- The main loop waits for external events to happen (such as keyboard input or a mouse click) -- and then fires the corresponding events using this function. The read callback can be used -- to read output events and perform a corresponding response action to the external event. fireEventsAndRead :: [DSum (EventTrigger t)] -> (ReadPhase m a) -> m a -- | Run a frame without any events firing. -- -- This function should be used when you want to use 'sample' and 'hold' when no events are currently firing. -- Using this function in that case can improve performance, since the implementation can assume that no events -- are firing when 'sample' or 'hold' are called. -- -- This function is commonly used to set up the basic event network when the application starts up. runHostFrame :: HostFrame t a -> m a -- | Like 'fireEventsAndRead', but without reading any events. fireEvents :: MonadReflexHost t m => [DSum (EventTrigger t)] -> m () fireEvents dm = fireEventsAndRead dm $ return () {-# INLINE fireEvents #-} -- | Create a new event and store its trigger in an 'IORef' while it's active. -- -- An event is only active between the set up (when it's first subscribed to) and the teardown phases (when noboby is subscribing the event anymore). -- This function returns an Event and an 'IORef'. As long as the event is active, the 'IORef' will contain 'Just' the event trigger to -- trigger this event. When the event is not active, the 'IORef' will contain 'Nothing'. This allows event sources to be more efficient, -- since they don't need to produce events when nobody is listening. newEventWithTriggerRef :: (MonadReflexCreateTrigger t m, MonadRef m, Ref m ~ Ref IO) => m (Event t a, Ref m (Maybe (EventTrigger t a))) newEventWithTriggerRef = do rt <- newRef Nothing e <- newEventWithTrigger $ \t -> do writeRef rt $ Just t return $ writeRef rt Nothing return (e, rt) {-# INLINE newEventWithTriggerRef #-} -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ReaderT r m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ReaderT r m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (ReaderT r m) where type ReadPhase (ReaderT r m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (WriterT w m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (WriterT w m) where subscribeEvent = lift . subscribeEvent instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (WriterT w m) where type ReadPhase (WriterT w m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (StateT s m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance MonadSubscribeEvent t m => MonadSubscribeEvent t (StateT r m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (StateT s m) where type ReadPhase (StateT s m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance MonadSubscribeEvent t m => MonadSubscribeEvent t (Strict.StateT r m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (Strict.StateT s m) where type ReadPhase (Strict.StateT s m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ContT r m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (ContT r m) where type ReadPhase (ContT r m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ExceptT e m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance MonadSubscribeEvent t m => MonadSubscribeEvent t (ExceptT r m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (ExceptT e m) where type ReadPhase (ExceptT e m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame instance (MonadReflexCreateTrigger t m, Monoid w) => MonadReflexCreateTrigger t (RWST r w s m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer instance (MonadSubscribeEvent t m, Monoid w) => MonadSubscribeEvent t (RWST r w s m) where subscribeEvent = lift . subscribeEvent instance (MonadReflexHost t m, Monoid w) => MonadReflexHost t (RWST r w s m) where type ReadPhase (RWST r w s m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame
k0001/reflex
src/Reflex/Host/Class.hs
bsd-3-clause
10,881
0
16
1,876
2,171
1,150
1,021
107
1