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 Main where
data Suit = Spades | Hearts deriving (Show)
data Rank = Ten | Jack | Queen | King | Ace deriving (Show)
type Card = (Rank, Suit)
type Hand = [Card]
value :: Rank -> Integer
value Ten = 1
value Jack = 2
value Queen = 3
value King = 4
value Ace = 5
cardValue :: Card -> Integer
cardValue (rank, suit) = value rank
| mtraina/seven-languages-seven-weeks | week-7-haskell/day3/cards_with_show.hs | mit | 357 | 0 | 6 | 97 | 143 | 82 | 61 | 13 | 1 |
module PPL2.VM.ALU.Types where
import PPL2.Prelude
import PPL2.VM.Types
import PPL2.VM.Control.Types (MicroInstr)
import Data.IntMap (IntMap)
import qualified Data.IntMap as I
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.List as L
-- ----------------------------------------
type CInstr v = (Mnemonic, MicroInstr v)
type CInstrList v = [CInstr v]
type CInstrSet v = MapMnemonics (MicroInstr v)
newtype MapMnemonics a =
CIS {unCIS :: Map Mnemonic a}
newtype ALU v =
ALU {unALU :: IntMap (MicroInstr v)}
-- ----------------------------------------
newCInstrSet :: [(Mnemonic, a)] -> MapMnemonics a
newCInstrSet =
L.foldl' unionCInstrSet (CIS M.empty)
.
map (\ (mn, mi) -> CIS $ M.singleton mn mi)
unionCInstrSet :: MapMnemonics a -> MapMnemonics a -> MapMnemonics a
unionCInstrSet (CIS s1) (CIS s2) =
CIS $ M.unionWithKey doubleMnemonics s1 s2
doubleMnemonics :: Mnemonic -> a -> a -> a
doubleMnemonics dmn _m1 _m2 =
error $
"PPL2.VI.ALU.Types': doublicated mnemonics in instruction set: "
++ show dmn
-- derive the ALU from the instruction set
toALU :: CInstrSet v -> ALU v
toALU =
ALU . I.fromList . zip [0..] . map snd . M.toAscList . unCIS
-- decoding opcodes back to mnemonics
toMnemonic :: CInstrSet v -> (OpCode -> Maybe Mnemonic)
toMnemonic inset
= flip I.lookup ocm
where
ocm = I.fromList . zip [0..] . map fst . M.toAscList . unCIS $ inset
-- test whether a name is a mnemonic
hasOpCode :: MapMnemonics a -> (Mnemonic -> Bool)
hasOpCode inset = isJust . toOpCode inset
-- for encoding assembler mnemonics into opcodes
toOpCode :: MapMnemonics a -> (Mnemonic -> Maybe OpCode)
toOpCode inset mn = M.lookup mn im
where
ms = map fst . M.toAscList . unCIS $ inset
im = M.fromList (zip ms [0..])
-- the opcode decoding
getMicroInstr :: OpCode -> ALU v -> Maybe (MicroInstr v)
getMicroInstr oc (ALU a) = I.lookup oc a
-- ----------------------------------------
| UweSchmidt/ppl2 | src/PPL2/VM/ALU/Types.hs | mit | 1,989 | 0 | 13 | 397 | 636 | 344 | 292 | 44 | 1 |
import System.IO
import System.Random
import Control.Monad
main = do
gen <- getStdGen
askForNumber gen
askForNumber :: StdGen -> IO ()
askForNumber gen = do
let (randNumber, newGen) = randomR (1, 10) gen :: (Int, StdGen)
putStr "What is the secret number (1-10)? "
hFlush stdout
numberString <- getLine
when (not $ null numberString) $ do
let [number] = reads numberString
if randNumber == number
then putStrLn "You are right!"
else putStrLn $ "Sorry, it was " ++ show randNumber
askForNumber newGen
| feliposz/learning-stuff | haskell/guess2.hs | mit | 587 | 0 | 13 | 168 | 182 | 87 | 95 | 18 | 2 |
{-|
Module : Control.Monad.Bayes.Traced.Common
Description : Numeric code for Trace MCMC
Copyright : (c) Adam Scibior, 2015-2020
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : GHC
-}
module Control.Monad.Bayes.Traced.Common (
Trace,
singleton,
output,
scored,
bind,
mhTrans,
mhTrans'
) where
import Control.Monad.Trans.Writer
import qualified Data.Vector as V
import Data.Functor.Identity
import Numeric.Log (Log, ln)
import Control.Monad.Bayes.Class
import Control.Monad.Bayes.Weighted as Weighted
import Control.Monad.Bayes.Free as FreeSampler
data Trace a =
Trace {
variables :: [Double],
output :: a,
density :: Log Double
}
instance Functor Trace where
fmap f t = t {output = f (output t)}
instance Applicative Trace where
pure x = Trace {variables = [], output = x, density = 1}
tf <*> tx = Trace {variables = variables tf ++ variables tx, output = output tf (output tx), density = density tf * density tx}
instance Monad Trace where
t >>= f =
let t' = f (output t) in
t' {variables = variables t ++ variables t', density = density t * density t'}
singleton :: Double -> Trace Double
singleton u = Trace {variables = [u], output = u, density = 1}
scored :: Log Double -> Trace ()
scored w = Trace {variables = [], output = (), density = w}
bind :: Monad m => m (Trace a) -> (a -> m (Trace b)) -> m (Trace b)
bind dx f = do
t1 <- dx
t2 <- f (output t1)
return $ t2 {variables = variables t1 ++ variables t2, density = density t1 * density t2}
-- | A single Metropolis-corrected transition of single-site Trace MCMC.
mhTrans :: MonadSample m => Weighted (FreeSampler m) a -> Trace a -> m (Trace a)
mhTrans m t = do
let us = variables t
p = density t
us' <- do
let n = length us
i <- categorical $ V.replicate n (1 / fromIntegral n)
u' <- random
let (xs, _:ys) = splitAt i us
return $ xs ++ (u':ys)
((b, q), vs) <- runWriterT $ runWeighted $ Weighted.hoist (WriterT . withPartialRandomness us') m
let ratio = (exp . ln) $ min 1 (q * fromIntegral (length us) / (p * fromIntegral (length vs)))
accept <- bernoulli ratio
return $ if accept then Trace vs b q else t
-- | A variant of 'mhTrans' with an external sampling monad.
mhTrans' :: MonadSample m => Weighted (FreeSampler Identity) a -> Trace a -> m (Trace a)
mhTrans' m = mhTrans (Weighted.hoist (FreeSampler.hoist (return . runIdentity)) m)
| adscib/monad-bayes | src/Control/Monad/Bayes/Traced/Common.hs | mit | 2,461 | 0 | 18 | 532 | 942 | 492 | 450 | 54 | 2 |
-- | Controls and helpers for changing slides in a deck.
module Haste.Deck.Control (
forward, back, goto, skip,
present, present_, enableDeck, disableDeck
) where
import Control.Monad
import Control.Monad.IO.Class
import Data.IORef
import Haste
import Haste.Concurrent
import Haste.DOM
import Haste.Events
import Haste.Deck.Config
import Haste.Deck.Internal
import Haste.Deck.Types
-- | Advance a deck to the next slide.
forward :: MonadIO m => Deck -> m ()
forward = liftIO . concurrent . flip putMVar Next . deckProceedMVar
-- | Go back one slide.
back :: MonadIO m => Deck -> m ()
back = liftIO . concurrent . flip putMVar Prev . deckProceedMVar
-- | Go to the given slide. Clamped to @[1, num_slides]@.
goto :: MonadIO m => Deck -> Int -> m ()
goto d = liftIO . concurrent . putMVar (deckProceedMVar d) . Goto
-- | Skip a number of slides. Negative numbers skip backward.
skip :: MonadIO m => Deck -> Int -> m ()
skip d = liftIO . concurrent . putMVar (deckProceedMVar d) . Skip
-- | Hook keydown events for left and right, pgup and pgdn and use them to flip
-- between the slides of the given deck.
-- Also hooks home and end to skip to the first and last slide respectively.
--
-- Note that it is not necessary to call @enableDeck@ in order to animate
-- a deck; it is a mere convenience function. For more fine-grained control,
-- 'forward', 'back', etc. can be used to change slides on custom triggers.
enableDeck :: MonadIO m => Deck -> m ()
enableDeck d = liftIO $ do
-- IORefs are fine here since there's no concurrency to worry about
oldhandler <- readIORef (deckUnregHandler d)
case oldhandler of
Just _ -> return ()
Nothing -> do
h <- documentBody `onEvent` KeyDown $ \key ->
case key of
37 -> back d -- left
39 -> forward d -- right
33 -> back d -- pgup
34 -> forward d -- pgdn
36 -> goto d 0 -- home
35 -> goto d maxBound -- end
_ -> return ()
unswipe <- onSwipe $ \dir ->
case dir of
L -> forward d
R -> back d
writeIORef (deckUnregHandler d) (Just $ unregisterHandler h >> unswipe)
-- | Stop catching keydown events for the given deck.
disableDeck :: MonadIO m => Deck -> m ()
disableDeck d = liftIO $ do
-- IORefs are fine here since there's no concurrency to worry about
munreg <- readIORef (deckUnregHandler d)
case munreg of
Just unreg -> unreg >> writeIORef (deckUnregHandler d) Nothing
Nothing -> return ()
-- | Run a deck in "presenter mode" - display slides in full screen, hook the
-- keys and touch events used by 'enableDeck' for navigation, and inspect
-- the hash part of the URL for which slide to start at.
present :: Config -> [Slide] -> IO Deck
present cfg s = do
hash <- getHash
let setSlideNo = case fromJSString hash of
Just ix | ix > 0 -> const ix
_ -> id
r <- newIORef True
d <- flip createDeck s $ cfg {startAtSlide = setSlideNo $ startAtSlide cfg,
onSlideChange = \_ n -> safeSetHash r n}
onHashChange $ \_ h -> do
enable <- readIORef r
when enable $ case fromJSString h of
Just n -> goto d n
_ -> goto d 0
setChildren documentBody [d]
enableDeck d
return d
where
-- Hack to work around the fact that setting the hash triggers the
-- hashchange event.
safeSetHash r slide = do
writeIORef r False
setHash (toJSString slide)
void $ setTimer (Once 100) $ writeIORef r True
-- | Run presenter mode without returning the deck.
present_ :: Config -> [Slide] -> IO ()
present_ cfg slides = void $ present cfg slides
data Direction = L | R
-- | Runs an action when a single touch left or right swipe happens.
onSwipe :: (Direction -> IO ()) -> IO (IO ())
onSwipe m = do
r <- newIORef Nothing
-- When a touch happens, save the coordinates for later.
h1 <- documentBody `onEvent` TouchStart $ \td ->
case changedTouches td of
[t] -> writeIORef r (Just t)
_ -> return ()
-- If the previously registered touch moves, register a swipe if it moves
-- horizontally by >=30 pixels and vertically by <30 pixels.
h2 <- documentBody `onEvent` TouchMove $ \td -> do
mt <- readIORef r
case (mt, changedTouches td) of
(Just t, [t']) | identifier t == identifier t' ->
case (screenCoords t, screenCoords t') of
((x, y), (x', y'))
| abs y - abs y' >= 30 -> return () -- diagonal swipe; ignore
| x' - x <= -30 -> writeIORef r Nothing >> m L
| x' - x >= 30 -> writeIORef r Nothing >> m R
| otherwise -> return ()
_ ->
return ()
-- When the registered touch leaves the screen, unregister it.
h3 <- documentBody `onEvent` TouchEnd $ \td -> do
mtouch <- readIORef r
case fmap identifier mtouch of
Just ident | any (\t' -> ident == identifier t') (changedTouches td) ->
writeIORef r Nothing
_ ->
return ()
return $ mapM_ unregisterHandler [h1, h2, h3]
| valderman/haste-deck | Haste/Deck/Control.hs | mit | 5,211 | 0 | 24 | 1,510 | 1,440 | 714 | 726 | 98 | 9 |
{-# LANGUAGE DataKinds #-}
{-# OPTIONS_GHC -fdefer-type-errors -Wwarn #-}
module Servant.Server.Internal.ContextSpec (spec) where
import Data.Proxy
(Proxy (..))
import Test.Hspec
(Spec, context, describe, it, shouldBe)
import Test.ShouldNotTypecheck
(shouldNotTypecheck)
import Servant.API
import Servant.Server.Internal.Context
spec :: Spec
spec = do
describe "getContextEntry" $ do
it "gets the context if a matching one exists" $ do
let cxt = 'a' :. EmptyContext
getContextEntry cxt `shouldBe` 'a'
it "gets the first matching context" $ do
let cxt = 'a' :. 'b' :. EmptyContext
getContextEntry cxt `shouldBe` 'a'
it "does not typecheck if type does not exist" $ do
let cxt = 'a' :. EmptyContext
x = getContextEntry cxt :: Bool
shouldNotTypecheck x
context "Show instance" $ do
it "has a Show instance" $ do
let cxt = 'a' :. True :. EmptyContext
show cxt `shouldBe` "'a' :. True :. EmptyContext"
context "bracketing" $ do
it "works" $ do
let cxt = 'a' :. True :. EmptyContext
show (Just cxt) `shouldBe` "Just ('a' :. True :. EmptyContext)"
it "works with operators" $ do
let cxt = (1 :: Integer) :. 'a' :. EmptyContext :<|> 'b' :. True :. EmptyContext
show cxt `shouldBe` "1 :. 'a' :. EmptyContext :<|> 'b' :. True :. EmptyContext"
describe "descendIntoNamedContext" $ do
let cxt :: Context [Char, NamedContext "sub" '[Char]]
cxt =
'a' :.
(NamedContext subContext :: NamedContext "sub" '[Char])
:. EmptyContext
subContext = 'b' :. EmptyContext
it "allows extracting subcontexts" $ do
descendIntoNamedContext (Proxy :: Proxy "sub") cxt `shouldBe` subContext
it "allows extracting entries from subcontexts" $ do
getContextEntry (descendIntoNamedContext (Proxy :: Proxy "sub") cxt :: Context '[Char])
`shouldBe` 'b'
it "does not typecheck if subContext has the wrong type" $ do
let x = descendIntoNamedContext (Proxy :: Proxy "sub") cxt :: Context '[Int]
shouldNotTypecheck (show x)
it "does not typecheck if subContext with that name doesn't exist" $ do
let x = descendIntoNamedContext (Proxy :: Proxy "foo") cxt :: Context '[Char]
shouldNotTypecheck (show x)
| zoomhub/zoomhub | vendor/servant/servant-server/test/Servant/Server/Internal/ContextSpec.hs | mit | 2,432 | 0 | 27 | 688 | 642 | 318 | 324 | 53 | 1 |
module Mockups.Elements.Txt where
import qualified Data.ByteString.Char8 as BS
import Mockups.Elements.Common
data TxtAttr
= TxtContent BS.ByteString
| TxtColor Color
deriving (Eq, Show)
| ostapneko/tiny-mockups | src/main/Mockups/Elements/Txt.hs | mit | 211 | 0 | 7 | 45 | 49 | 31 | 18 | 7 | 0 |
-- Модуль для тестирования библиотеки
import Text.Parsec
import qualified Address.Number as N
import qualified Address.String as S
import Address.Main
import Address.Types
main = do
-- TODO: Тут хорошо было бы сделать модульное тестирование
print $ parseAddr "строение 1-A/2"
print $ parseAddr "стр 1-A/2"
print $ parseAddr "стр. 1-A/2"
print $ parseAddr "стр.1-A/2"
print $ parseAddr "1-A/2 строение"
print $ parseAddr "1-A/2 стр"
print $ parseAddr "1-A/2 с"
print $ parseAddr "ул. 1-я Дубровская"
print $ parseAddr "д.1 к.2"
print $ parseAddr "ул. Дубровская д.4 к.2"
print $ parseAddr "ул. 1-я Дубровская, д.4"
print $ parseAddr "г. Москва ул. 1-я Дубровская д.4 к.2"
print $ parseAddr "Раменское г. Высоковольтная ул"
print $ parseAddr "город москва улица дубровская"
print $ parseAddr "Егорьевск г. Профсоюзная ул. д. 30" -- Без запятых
print $ parseAddr "Москва г."
print $ parseAddr "г Москва"
print $ parseAddr "Всеволода Вишневского ул., д.4-А"
print $ parseAddr "ул. Всеволода Вишневского, д.4-А"
print $ parseAddr "Ореховый б-р, д.49, к.1"
print $ parseAddr "Семеновская наб., д.3, к.1"
print $ parseAddr "Алябьева ул.,д.1-33,к.1"
print $ parseAddr "Алябьева УЛ.,Д.1-33,к.1"
print $ parseAddr "Зеленоград г., КОРПУС №225-А"
print $ parseAddr "пр. Ленинский, д.10, к.5"
print $ parseAddr "д.1, к.2, Ленинский пр."
print $ parseAddr "Ленинский б-р, д.10, к.5"
print $ parseAddr "ул. 1-я Дубровская, д.4"
print $ parseAddr "Алябьева ул., д.7/33, к.1"
print $ parseAddr "МО, ул. 1-я Дубровская"
-- Без ключей
print $ parseAddr "Таганская, 1"
print $ parseAddr "1 Дубровская, 1"
--print $ parseAddr "1, 1, Дубровская"
print $ parseAddr "Одинцово г.,Любы Новоселовой б-р,д.17"
print $ parseAddr "МО, 1-я Дубровская шоссе ул, д1, лит А"
print $ parseAddr "Волхонское шоссе ул,д.31"
print $ parseAddr "Мытнинская ул.,д.25 Лит. А"
print $ parseAddr "Обводного канала набережная ул.,д.123 Лит А"
print $ parseAddr "Серебристый бульвар ул.,д.14 к.2"
--print $ parseAddr "Мира пр-т ,д.54"
print $ parseAddr "Владик, 10-лет Октября ул.,д.2"
--putStrLn $ format $ fromRight $ parseAddr "МО, ул. 1-я Дубровская, д.99"
--where fromRight (Right x) = x
| kahless/russian-address-parser | src/Address/_Test.hs | mit | 2,988 | 1 | 8 | 475 | 438 | 188 | 250 | 45 | 1 |
module Plumbing (
hashObject
, writeTree
, setRef
) where
import qualified App
import qualified Data.ByteString as B
import Control.Monad.Trans.State (evalStateT)
import System.Directory ( doesDirectoryExist, getDirectoryContents )
import System.FilePath ( (</>) )
import System.Log.Logger
import Control.Exception
import Data.Maybe (catMaybes)
import System.IO.Error
import Control.Monad (guard)
import Store.Blob as BlobStore
import Store.Ref as RefStore
import qualified Blob
import qualified Tree
import qualified Ref
logTag :: String
logTag = App.logTag ++ ".Plumbing"
hashObject :: B.ByteString -> Blob.Id
hashObject bytes = Blob.createId (Blob.Bytes bytes)
writeTree :: (BlobStore a) => FilePath -> a -> IO Blob.Id
writeTree path store = do
tree <- createTree path store
treeBlob <- saveTree tree store
let (Blob.Blob blobId _) = treeBlob
return blobId
setRef :: (RefStore a) => String -> Blob.Id -> a -> IO ()
setRef name value store = do
let ref = Ref.create (Ref.createId name) value
evalStateT (RefStore.set ref) store
return ()
createTree :: (BlobStore a) => FilePath -> a -> IO Tree.Tree
createTree path store = do
names <- listDirectory path
entries <- mapM toEntry names
return $ Tree.create (catMaybes entries)
where
toEntry name = createTreeEntry path name store
listDirectory :: FilePath -> IO [FilePath]
listDirectory path = do
names <- getDirectoryContents path
return $ filter (`notElem` [".", ".."]) names
createTreeEntry :: (BlobStore a) => FilePath -> FilePath -> a -> IO (Maybe Tree.Entry)
createTreeEntry parentPath name store = do
isDir <- doesDirectoryExist fullpath
case isDir of
True -> createDirEntry
False -> createFileEntry
where
fullpath = parentPath </> name
createDirEntry = do
blobId <- writeTree fullpath store
return . Just $ Tree.createEntry name 0 blobId
createFileEntry = do
result <- tryJust (guard . isDoesNotExistError) (blobFromPath fullpath)
case result of
Left e -> do
noticeM logTag ("Problem reading file: " ++ fullpath ++", exception: " ++ (show e))
return Nothing
Right blob -> do
evalStateT (BlobStore.put blob) store
let (Blob.Blob blobId _) = blob
return . Just $ Tree.createEntry name 0 blobId
blobFromPath :: FilePath -> IO Blob.Blob
blobFromPath path = do
contents <- B.readFile path
return $ Blob.create contents
saveTree :: (BlobStore a) => Tree.Tree -> a -> IO Blob.Blob
saveTree tree store = do
let treeBlob = Tree.toBlob tree
evalStateT (BlobStore.put treeBlob) store
return treeBlob
| danstiner/clod | src/Plumbing.hs | mit | 2,747 | 0 | 19 | 661 | 901 | 453 | 448 | 73 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : DSP.Basic
-- Copyright : (c) Matthew Donadio 1998
-- License : GPL
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Basic functions for manipulating signals
--
-----------------------------------------------------------------------------
module DSP.Basic where
import DSP.Source.Basic (zeros)
import Data.Array (Array, Ix, listArray, elems)
-- * Functions
-- | 'linspace' generates a list of values linearly spaced between specified
-- start and end values (array will include both start and end values).
--
-- @linspace 0.0 1.0 5 == [ 0.0, 0.25, 0.5, 0.75 1.0 ]@
linspace :: Double -> Double -> Int -> [Double]
linspace a b n =
map (\ i -> a + (fromIntegral i) * inc) [(0::Int) .. (n - 1)]
where
inc = (b - a) / (fromIntegral (n - 1))
-- | 'logspace' generates a list of values logarithmically spaced between the
-- values 10 ** start and 10 ** end (array will include both start and end values).
--
-- @logspace 0.0 1.0 4 == [ 1.0, 2.1544, 4.6416, 10.0 ]@
logspace :: Double -> Double -> Int -> [Double]
logspace a b n =
map (\ x -> 10.0 ** x) $ linspace a b n
-- | 'delay' is the unit delay function, eg,
--
-- @delay1 [ 1, 2, 3 ] == [ 0, 1, 2, 3 ]@
delay1 :: (Num a) => [a] -> [a]
delay1 a = 0 : a
-- | 'delay' is the n sample delay function, eg,
--
-- @delay 3 [ 1, 2, 3 ] == [ 0, 0, 0, 1, 2, 3 ]@
delay :: (Num a) => Int -> [a] -> [a]
delay n a = replicate n 0 ++ a
-- | @downsample@ throws away every n'th sample, eg,
--
-- @downsample 2 [ 1, 2, 3, 4, 5, 6 ] == [ 1, 3, 5 ]@
downsample :: Int -> [a] -> [a]
downsample n =
map head . takeWhile (not . null) . iterate (drop n)
downsampleRec :: Int -> [a] -> [a]
downsampleRec _ [] = []
downsampleRec n (x:xs) = x : downsample n (drop (n - 1) xs)
-- | @upsample@ inserts n-1 zeros between each sample, eg,
--
-- @upsample 2 [ 1, 2, 3 ] == [ 1, 0, 2, 0, 3, 0 ]@
upsample :: (Num a) => Int -> [a] -> [a]
upsample n = concatMap (: replicate (n-1) 0)
upsampleRec :: (Num a) => Int -> [a] -> [a]
upsampleRec _ [] = []
upsampleRec n (x:xs) = x : zero n xs
where zero 1 ys = upsample n ys
zero i ys = 0 : zero (i-1) ys
-- | @upsampleAndHold@ replicates each sample n times, eg,
--
-- @upsampleAndHold 3 [ 1, 2, 3 ] == [ 1, 1, 1, 2, 2, 2, 3, 3, 3 ]@
upsampleAndHold :: Int -> [a] -> [a]
upsampleAndHold n = concatMap (replicate n)
-- | merges elements from two lists into one list in an alternating way
--
-- @interleave [0,1,2,3] [10,11,12,13] == [0,10,1,11,2,12,3,13]@
interleave :: [a] -> [a] -> [a]
interleave (e:es) (o:os) = e : o : interleave es os
interleave _ _ = []
-- | split a list into two lists in an alternating way
--
-- @uninterleave [1,2,3,4,5,6] == ([1,3,5],[2,4,6])@
--
-- It's a special case of 'Numeric.Random.Spectrum.Pink.split'.
uninterleave :: [a] -> ([a],[a])
uninterleave = foldr (\x ~(xs,ys) -> (x:ys,xs)) ([],[])
-- | pad a sequence with zeros to length n
--
-- @pad [ 1, 2, 3 ] 6 == [ 1, 2, 3, 0, 0, 0 ]@
pad :: (Ix a, Integral a, Num b) => Array a b -> a -> Array a b
pad x n = listArray (0,n-1) $ elems x ++ zeros
-- | generates a 'Just' if the given condition holds
toMaybe :: Bool -> a -> Maybe a
toMaybe False _ = Nothing
toMaybe True x = Just x
-- | Computes the square of the Euclidean norm of a 2D point
norm2sqr :: Num a => (a,a) -> a
norm2sqr (x,y) = x^!2 + y^!2
-- | Power with fixed exponent type.
-- This eliminates warnings about using default types.
infixr 8 ^!
(^!) :: Num a => a -> Int -> a
(^!) x n = x^n
| tolysz/dsp | DSP/Basic.hs | gpl-2.0 | 3,650 | 0 | 11 | 824 | 1,021 | 572 | 449 | 44 | 2 |
-- #hide
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Domain
-- Copyright : (c) Sven Panne 2002-2009
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- This is a purely internal module for handling evaluator domains.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Domain (
Domain(..)
) where
import Foreign.Ptr
import Foreign.Storable
import Graphics.Rendering.OpenGL.GL.QueryUtils
import Graphics.Rendering.OpenGL.Raw.Core31
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility (
glEvalCoord1d, glEvalCoord1dv, glEvalCoord1f, glEvalCoord1fv, glEvalCoord2d,
glEvalCoord2dv, glEvalCoord2f, glEvalCoord2fv, glGetMapdv, glGetMapfv,
glMap1d, glMap1f, glMap2d, glMap2f, glMapGrid1d, glMapGrid1f, glMapGrid2d,
glMapGrid2f )
--------------------------------------------------------------------------------
class Storable d => Domain d where
glMap1 :: GLenum -> d -> d -> GLint -> GLint -> Ptr d -> IO ()
glMap2 :: GLenum -> d -> d -> GLint -> GLint -> d -> d -> GLint -> GLint -> Ptr d -> IO ()
glGetMapv :: GLenum -> GLenum -> Ptr d -> IO ()
evalCoord1 :: d -> IO ()
evalCoord1v :: Ptr d -> IO ()
evalCoord2 :: (d, d) -> IO ()
evalCoord2v :: Ptr d -> IO ()
glMapGrid1 :: GLint -> d -> d -> IO ()
glMapGrid2 :: GLint -> d -> d -> GLint -> d -> d -> IO ()
get2 :: (d -> d -> a) -> GetPName -> IO a
get4 :: (d -> d -> d -> d -> a) -> GetPName -> IO a
--------------------------------------------------------------------------------
instance Domain GLfloat where
glMap1 = glMap1f
glMap2 = glMap2f
glGetMapv = glGetMapfv
evalCoord1 = glEvalCoord1f
evalCoord1v = glEvalCoord1fv
evalCoord2 = uncurry glEvalCoord2f
evalCoord2v = glEvalCoord2fv
glMapGrid1 = glMapGrid1f
glMapGrid2 = glMapGrid2f
get2 = getFloat2
get4 = getFloat4
instance Domain GLdouble where
glMap1 = glMap1d
glMap2 = glMap2d
glGetMapv = glGetMapdv
evalCoord1 = glEvalCoord1d
evalCoord1v = glEvalCoord1dv
evalCoord2 = uncurry glEvalCoord2d
evalCoord2v = glEvalCoord2dv
glMapGrid1 = glMapGrid1d
glMapGrid2 = glMapGrid2d
get2 = getDouble2
get4 = getDouble4
| ducis/haAni | hs/common/Graphics/Rendering/OpenGL/GL/Domain.hs | gpl-2.0 | 2,503 | 0 | 18 | 538 | 574 | 324 | 250 | 47 | 0 |
-- | Highlights Haskell code with ANSI terminal codes.
module Language.Haskell.HsColour.TTY (hscolour,hscolourG) where
{-@ LIQUID "--totality" @-}
import Language.Haskell.HsColour.ANSI as ANSI
import Language.Haskell.HsColour.Classify
import Language.Haskell.HsColour.Colourise
import Language.Haskell.HsColour.Output(TerminalType(Ansi16Colour))
-- | = 'hscolourG' 'Ansi16Colour'
hscolour :: ColourPrefs -- ^ Colour preferences.
-> String -- ^ Haskell source code.
-> String -- ^ Coloured Haskell source code.
hscolour = hscolourG Ansi16Colour
-- | Highlights Haskell code with ANSI terminal codes.
hscolourG terminalType pref = concatMap (renderTokenG terminalType pref) . tokenise
renderToken :: ColourPrefs -> (TokenType,String) -> String
renderToken = renderTokenG Ansi16Colour
renderTokenG terminalType pref (t,s) = ANSI.highlightG terminalType (colourise pref t) s
| nikivazou/hscolour | Language/Haskell/HsColour/TTY.hs | gpl-2.0 | 906 | 0 | 8 | 134 | 170 | 102 | 68 | 13 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Run.RunData.Plain.ShadeSceneKonami
(
ShadeSceneKonami (..),
loadShadeSceneKonami,
unloadShadeSceneKonami,
beginShadeSceneKonami,
endShadeSceneKonami,
) where
import MyPrelude
import File
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
data ShadeSceneKonami =
ShadeSceneKonami
{
shadeSceneKonamiPrg :: !GLuint,
shadeSceneKonamiUniProjModvMatrix :: !GLint,
shadeSceneKonamiUniAlpha :: !GLint,
shadeSceneKonamiUniTweak :: !GLint,
shadeSceneKonamiVAO :: !GLuint,
shadeSceneKonamiVBO :: !GLuint,
shadeSceneKonamiTex :: !GLuint
}
loadShadeSceneKonami :: IO ShadeSceneKonami
loadShadeSceneKonami = do
vsh <- fileStaticData "shaders/SceneKonami.vsh"
fsh <- fileStaticData "shaders/SceneKonami.fsh"
prg <- createPrg vsh fsh [ (attPos, "a_pos"),
(attTexCoord, "a_texcoord") ] [
(tex0, "u_tex_scene"),
(tex1, "u_tex_image")]
uProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
uAlpha <- getUniformLocation prg "u_alpha"
uTweak <- getUniformLocation prg "u_tweak"
-- vao
vao <- bindNewVAO
glEnableVertexAttribArray attPos
glEnableVertexAttribArray attTexCoord
-- vbo. content created by beginShadeScenePause
vbo <- bindNewBuf gl_ARRAY_BUFFER
-- tex. content created by endShadeScenePause
tex <- bindNewTex gl_TEXTURE_2D
return ShadeSceneKonami
{
shadeSceneKonamiPrg = prg,
shadeSceneKonamiUniProjModvMatrix = uProjModvMatrix,
shadeSceneKonamiUniAlpha = uAlpha,
shadeSceneKonamiUniTweak = uTweak,
shadeSceneKonamiVAO = vao,
shadeSceneKonamiVBO = vbo,
shadeSceneKonamiTex = tex
}
unloadShadeSceneKonami :: ShadeSceneKonami -> IO ()
unloadShadeSceneKonami sh = do
return ()
--------------------------------------------------------------------------------
-- using ShadeSceneKonami
-- question: ShadeSceneKonami -> IO ShadeSceneKonami?
-- if so, then we need to modify GameData in real time.
beginShadeSceneKonami :: ShadeSceneKonami -> IO ()
beginShadeSceneKonami sh = do
-- vbo
glBindVertexArrayOES $ shadeSceneKonamiVAO sh
glBindBuffer gl_ARRAY_BUFFER $ shadeSceneKonamiVBO sh
allocaBytes 32 $ \ptr -> do
pokeByteOff ptr (0 + 0) (-1 :: GLbyte)
pokeByteOff ptr (0 + 1) (1 :: GLbyte)
pokeByteOff ptr (0 + 2) (0 :: GLbyte)
pokeByteOff ptr (0 + 4) (0 :: GLushort)
pokeByteOff ptr (0 + 6) (1 :: GLushort)
pokeByteOff ptr (8 + 0) (-1 :: GLbyte)
pokeByteOff ptr (8 + 1) (-1 :: GLbyte)
pokeByteOff ptr (8 + 2) (0 :: GLbyte)
pokeByteOff ptr (8 + 4) (0 :: GLushort)
pokeByteOff ptr (8 + 6) (0 :: GLushort)
pokeByteOff ptr (16 + 0) (1 :: GLbyte)
pokeByteOff ptr (16 + 1) (1 :: GLbyte)
pokeByteOff ptr (16 + 2) (0 :: GLbyte)
pokeByteOff ptr (16 + 4) (1 :: GLushort)
pokeByteOff ptr (16 + 6) (1 :: GLushort)
pokeByteOff ptr (24 + 0) (1 :: GLbyte)
pokeByteOff ptr (24 + 1) (-1 :: GLbyte)
pokeByteOff ptr (24 + 2) (0 :: GLbyte)
pokeByteOff ptr (24 + 4) (1 :: GLushort)
pokeByteOff ptr (24 + 6) (0 :: GLushort)
glBufferData gl_ARRAY_BUFFER 32 ptr gl_STATIC_DRAW
glVertexAttribPointer attPos 3 gl_BYTE gl_FALSE 8 (mkPtrGLvoid 0)
glVertexAttribPointer attTexCoord 2 gl_UNSIGNED_SHORT gl_FALSE 8 $ mkPtrGLvoid 4
-- tex
glBindTexture gl_TEXTURE_2D $ shadeSceneKonamiTex sh
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_S $ fI gl_CLAMP_TO_EDGE
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_WRAP_T $ fI gl_CLAMP_TO_EDGE
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MAG_FILTER $ fI gl_LINEAR
glTexParameteri gl_TEXTURE_2D gl_TEXTURE_MIN_FILTER $ fI gl_LINEAR
path <- fileStaticData "Run/Scene/konami.png"
loadTexPreMult gl_TEXTURE_2D gl_RGBA path
return ()
-- | question: will this save memory?
endShadeSceneKonami :: ShadeSceneKonami -> IO ()
endShadeSceneKonami sh = do
glBindBuffer gl_ARRAY_BUFFER $ shadeSceneKonamiVBO sh
glBufferData gl_ARRAY_BUFFER 0 nullPtr gl_STATIC_DRAW
glBindTexture gl_TEXTURE_2D $ shadeSceneKonamiTex sh
glTexImage2D gl_TEXTURE_2D 0 (fI gl_RGBA) 0 0 0 gl_RGBA gl_UNSIGNED_BYTE nullPtr
| karamellpelle/grid | source/Game/Run/RunData/Plain/ShadeSceneKonami.hs | gpl-3.0 | 5,267 | 0 | 13 | 1,330 | 1,148 | 590 | 558 | 104 | 1 |
{-# LANGUAGE OverloadedLists #-}
module Nirum.Constructs.DeclarationSetSpec (SampleDecl (..), spec) where
import Control.Exception.Base (evaluate)
import Data.String (IsString (..))
import Test.Hspec.Meta
import Nirum.Constructs (Construct (..))
import qualified Nirum.Constructs.Annotation as A
import Nirum.Constructs.Annotation (AnnotationSet)
import Nirum.Constructs.Declaration (Declaration (..), Documented)
import Nirum.Constructs.DeclarationSet ( DeclarationSet
, NameDuplication (..)
, delete
, empty
, fromList
, lookup'
, null'
, size
, toList
, union
, (!)
)
import Nirum.Constructs.Name (Name (Name))
data SampleDecl = SampleDecl Name AnnotationSet deriving (Eq, Ord, Show)
instance Construct SampleDecl where
toCode _ = "(do not impl)"
instance Documented SampleDecl
instance Declaration SampleDecl where
name (SampleDecl name' _) = name'
annotations (SampleDecl _ anno') = anno'
instance IsString SampleDecl where
fromString s = SampleDecl (fromString s) A.empty
type SampleDeclSet = DeclarationSet SampleDecl
spec :: Spec
spec =
describe "DeclarationSet" $ do
let sd fname bname = SampleDecl (Name fname bname) A.empty
context "fromList" $ do
let fl = fromList :: [SampleDecl]
-> Either NameDuplication SampleDeclSet
it ("returns Left FacialNameDuplication "
++ "if duplicated facial name exists") $ do
fl ["foo", "bar", "foo"] `shouldBe`
Left (FacialNameDuplication "foo")
fl ["foo", "bar", "bar"] `shouldBe`
Left (FacialNameDuplication "bar")
fl ["foo", "bar", sd "foo" "baz"] `shouldBe`
Left (FacialNameDuplication $ Name "foo" "baz")
it ("returns Left BehindNameDuplication "
++ "if duplicated behind name exists") $ do
fl ["foo", "bar", sd "baz" "foo"] `shouldBe`
Left (BehindNameDuplication $ Name "baz" "foo")
fl [sd "foo" "bar", "bar", "baz"] `shouldBe`
Left (BehindNameDuplication "bar")
it "returns Right DeclarationSet if there are no duplications" $ do
let Right dset = fl ["foo", "bar", "baz"]
toList dset `shouldBe` ["foo", "bar", "baz"]
let dset = ["foo", "bar", sd "baz" "asdf"] :: SampleDeclSet
context "toList" $
it "returns [Declaration]" $ do
toList dset `shouldBe` ["foo", "bar", sd "baz" "asdf"]
toList (empty :: SampleDeclSet) `shouldBe` []
context "size" $
it "returns its cardinality" $ do
size dset `shouldBe` 3
size (empty :: SampleDeclSet) `shouldBe` 0
context "null" $ do
it "returns True if the set is empty" $ do
([] :: SampleDeclSet) `shouldSatisfy` null'
(empty :: SampleDeclSet) `shouldSatisfy` null'
it "returns False if the set is not empty" $
dset `shouldNotSatisfy` null'
context "lookup" $ do
it "returns Nothing if there is no such facial name" $
lookup' "not-exists" dset `shouldBe` Nothing
it "returns Just Declaration if the name exists" $ do
lookup' "foo" dset `shouldBe` Just "foo"
lookup' "bar" dset `shouldBe` Just "bar"
lookup' "baz" dset `shouldBe` Just (sd "baz" "asdf")
context "DeclarationSet ! Identifier" $ do
it "returns Declaration if the name exists" $ do
dset ! "foo" `shouldBe` "foo"
dset ! "bar" `shouldBe` "bar"
dset ! "baz" `shouldBe` sd "baz" "asdf"
it "fails if there is no such facial name" $
evaluate (dset ! "not-exists") `shouldThrow` anyException
context "union" $ do
it "returns Right DeclarationSet if there aren't no duplications" $
union dset ["apple", "banana"] `shouldBe`
Right ["foo" , "bar" , sd "baz" "asdf", "apple", "banana"]
it "returns Left FacialNameDuplication if facial names are dup" $
union dset [sd "foo" "xyz"] `shouldBe`
Left (FacialNameDuplication $ Name "foo" "xyz")
it "returns Left BehindNameDuplication if behind names are dup" $
union dset [sd "xyz" "foo"] `shouldBe`
Left (BehindNameDuplication $ Name "xyz" "foo")
specify "delete" $
delete "bar" dset `shouldBe` ["foo", sd "baz" "asdf"]
| dahlia/nirum | test/Nirum/Constructs/DeclarationSetSpec.hs | gpl-3.0 | 5,054 | 0 | 18 | 1,880 | 1,213 | 632 | 581 | 96 | 1 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback is distributed in the hope that it will be useful, but WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for |
| more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.View.Abilities
(AbilitiesState(..), AbilitiesAction(..), newAbilitiesView)
where
import Control.Applicative ((<$>))
import Control.Arrow ((***))
import Control.Monad (zipWithM)
import Data.Maybe (isNothing, listToMaybe)
import Fallback.Data.Color
import Fallback.Data.Point
import qualified Fallback.Data.TotalMap as TM (get)
import Fallback.Draw
import Fallback.Scenario.Abilities
(getAbility, abilityFullDescription, abilityIconCoords)
import Fallback.Scenario.Feats
(featCastingCost, featDescription, featIconCoords)
import Fallback.State.Action
import Fallback.State.Item (itemIconCoords, itemName, wdFeats)
import Fallback.State.Party
import Fallback.State.Resources
(FontTag(..), Resources, rsrcAbilityIcon, rsrcFont, rsrcItemIcon)
import Fallback.State.Simple
import Fallback.State.Tags
(AbilityTag, FeatTag, ItemTag(WeaponItemTag), WeaponItemTag, classAbility,
featName)
import Fallback.View.Base
import Fallback.View.Dialog (newDialogBackgroundView)
import Fallback.View.Hover
import Fallback.View.Widget
-------------------------------------------------------------------------------
data AbilitiesState = AbilitiesState
{ abilsActiveCharacter :: CharacterNumber,
abilsInCombat :: Bool,
abilsMetaAbilityTag :: Maybe FeatTag,
abilsParty :: Party }
data AbilitiesAction = UseAbility AbilityNumber
| UseCombatFeat FeatTag
| UseNormalAttack
abilsGetCharacter :: AbilitiesState -> Character
abilsGetCharacter as =
partyGetCharacter (abilsParty as) (abilsActiveCharacter as)
data TooltipKey = NoTooltip
| AbilityTooltip AbilityTag AbilityRank
| AttackTooltip (Maybe WeaponItemTag)
| FeatTooltip (Maybe WeaponItemTag) FeatTag
-------------------------------------------------------------------------------
buttonSize, buttonSpacing :: Int
buttonSize = 40
buttonSpacing = 8
-------------------------------------------------------------------------------
newAbilitiesView :: (MonadDraw m) => Resources -> HoverSink Cursor
-> m (View AbilitiesState AbilitiesAction)
newAbilitiesView resources cursorSink = do
let margin = 20
headingHeight = 20
sectionSpacing = 10
let headingFont = rsrcFont resources FontGeorgiaBold11
tooltipRef <- newHoverRef NoTooltip
let tooltipSink = hoverSink tooltipRef
let makeAbilityWidget abilNum index =
subView_ (Rect (margin + (index `mod` 5) *
(buttonSize + buttonSpacing))
(margin + headingHeight +
(index `div` 5) * (buttonSize + buttonSpacing))
buttonSize buttonSize) <$>
newAbilityWidget resources tooltipSink abilNum
let rectFn _ (w, h) =
let w' = 2 * margin + 5 * buttonSize + 4 * buttonSpacing
h' = 2 * margin + 2 * headingHeight +
3 * buttonSize + buttonSpacing + sectionSpacing
in Rect ((w - w') `div` 2) ((h - h') `div` 2) w' h'
hoverJunction tooltipRef <$> compoundViewM [
(return $ hoverView tooltipSink NoTooltip nullView),
(subView rectFn <$> compoundViewM [
(hoverView cursorSink DefaultCursor <$> newDialogBackgroundView),
(return $ vmap (const "Abilities") $ makeLabel headingFont blackColor $
\(w, _) -> LocMidtop $ Point (w `div` 2) margin),
(compoundView <$> zipWithM makeAbilityWidget [minBound .. maxBound]
[0 ..]),
(subView_ (Rect margin (margin + headingHeight + 2 * buttonSize +
buttonSpacing + sectionSpacing)
(buttonSize * 2 + buttonSpacing)
(buttonSize + headingHeight)) <$>
newAttackSection resources tooltipSink),
(subView_ (Rect (margin + 2 * buttonSize + 2 * buttonSpacing)
(margin + headingHeight + 2 * buttonSize +
buttonSpacing + sectionSpacing)
(buttonSize * 3 + buttonSpacing * 2)
(buttonSize + headingHeight)) <$>
newFeatsSection resources tooltipSink)]),
(newAbilityInfoView resources tooltipRef),
(newFeatInfoView resources tooltipRef)]
-------------------------------------------------------------------------------
newAbilityWidget :: (MonadDraw m) => Resources -> HoverSink TooltipKey
-> AbilityNumber -> m (View AbilitiesState AbilitiesAction)
newAbilityWidget resources tooltipSink abilNum = do
let maybeFn as = do
let char = abilsGetCharacter as
abilRank <- TM.get abilNum $ chrAbilities char
let abilTag = classAbility (chrClass char) abilNum
Just ((as, char), (abilTag, abilRank))
let eitherFn ((as, char), (abilTag, abilRank)) =
case getAbility (chrClass char) abilNum abilRank of
ActiveAbility _ cost eff ->
-- TODO: take AP needed into account when deciding if can use
Left (abilTag, canUseActiveAbility as cost eff)
PassiveAbility -> Right abilTag
active <- newActiveAbilityWidget resources abilNum
passive <- newPassiveAbilityWidget resources
newMaybeView maybeFn =<<
(hoverView' tooltipSink (Just . uncurry AbilityTooltip . snd) <$>
newEitherView eitherFn active passive)
newActiveAbilityWidget :: (MonadDraw m) => Resources -> AbilityNumber
-> m (View (AbilityTag, Bool) AbilitiesAction)
newActiveAbilityWidget resources abilNum =
vmap (rsrcAbilityIcon resources . abilityIconCoords *** enabledIf) <$>
newIconButton [] (UseAbility abilNum)
newPassiveAbilityWidget :: (MonadDraw m) => Resources -> m (View AbilityTag b)
newPassiveAbilityWidget resources = do
let paint abilTag = do
rect <- canvasRect
drawBevelRect (Tint 0 0 0 128) 5 rect
let icon = rsrcAbilityIcon resources $ abilityIconCoords abilTag
blitLocTinted (Tint 255 255 255 192) icon $
LocCenter (rectCenter rect :: IPoint)
return $ inertView paint
-------------------------------------------------------------------------------
newAttackSection :: (MonadDraw m) => Resources -> HoverSink TooltipKey
-> m (View AbilitiesState AbilitiesAction)
newAttackSection resources tooltipSink = do
let headingFont = rsrcFont resources FontGeorgiaBold11
let inputFn as = (mbTag, abilsInCombat as) where
mbTag = eqpWeapon $ chrEquipment $
partyGetCharacter (abilsParty as) (abilsActiveCharacter as)
let hoverFn (mbTag, _) = Just (AttackTooltip mbTag)
let buttonFn (mbTag, enabled) =
(rsrcItemIcon resources $
maybe (1, 7) (itemIconCoords . WeaponItemTag) mbTag,
enabledIf enabled)
let rectFn _ (w, h) =
Rect ((w - buttonSize) `div` 2) (h - buttonSize) buttonSize buttonSize
compoundViewM [
(return $ vmap (const "Attack") $ makeLabel headingFont blackColor $
\(w, _) -> LocMidtop $ Point (w `div` 2) 0),
(subView rectFn . vmap inputFn . hoverView' tooltipSink hoverFn .
vmap buttonFn <$> newIconButton [] UseNormalAttack)]
-------------------------------------------------------------------------------
newFeatsSection :: (MonadDraw m) => Resources -> HoverSink TooltipKey
-> m (View AbilitiesState AbilitiesAction)
newFeatsSection resources tooltipSink = do
let headingFont = rsrcFont resources FontGeorgiaBold11
let inputFn as =
let char = partyGetCharacter (abilsParty as) (abilsActiveCharacter as)
in (as, eqpWeapon (chrEquipment char),
wdFeats (chrEquippedWeaponData char))
let rectFn idx (_, _, featTags) (w, h) =
Rect ((w - length featTags * (buttonSize + buttonSpacing) +
buttonSpacing) `div` 2 + idx * (buttonSize + buttonSpacing))
(h - buttonSize) buttonSize buttonSize
let makeFeatButton idx =
subView (rectFn idx) <$> newFeatButton resources tooltipSink idx
compoundViewM [
(return $ vmap (const "Combat Feats") $ makeLabel headingFont blackColor $
\(w, _) -> LocMidtop $ Point (w `div` 2) 0),
(vmap inputFn . compoundView <$> mapM makeFeatButton [0 .. 2])]
newFeatButton :: (MonadDraw m) => Resources -> HoverSink TooltipKey -> Int
-> m (View (AbilitiesState, Maybe WeaponItemTag,
[FeatTag]) AbilitiesAction)
newFeatButton resources tooltipSink idx = do
let tryGetInput (as, mbWTag, featTags) = do
featTag <- listToMaybe $ drop idx featTags
Just ((mbWTag, featTag),
(rsrcAbilityIcon resources (featIconCoords featTag),
if abilsMetaAbilityTag as == Just featTag then DepressedButton
else enabledIf (abilsInCombat as &&
partyCanAffordCastingCost (abilsActiveCharacter as)
(featCastingCost featTag) (abilsParty as))))
newMaybeView tryGetInput =<<
hoverView' tooltipSink (Just . uncurry FeatTooltip . fst) .
f2map (const . UseCombatFeat . snd . fst) . vmap snd <$>
newIconButton [] ()
-------------------------------------------------------------------------------
newAbilityInfoView :: (MonadDraw m) => Resources -> HoverRef TooltipKey
-> m (View a b)
newAbilityInfoView resources tooltipRef = do
cache <- newDrawRef Nothing
let inputFn _ = do
tooltipKey <- readHoverRef tooltipRef
case tooltipKey of
AbilityTooltip tag rank -> do
let key = (tag, rank)
mbCached <- readDrawRef cache
desc <- do
case mbCached of
Just (key', string) | key' == key -> return string
_ -> do
let string = uncurry abilityFullDescription key
writeDrawRef cache $ Just (key, string)
return string
return (Just desc)
_ -> do
writeDrawRef cache Nothing
return Nothing
vmapM inputFn . subView (\_ (w, h) -> Rect (half (w - 400)) (half h)
400 (half h)) <$>
(newMaybeView id =<< newTooltipView resources)
newFeatInfoView :: (MonadDraw m) => Resources -> HoverRef TooltipKey
-> m (View a b)
newFeatInfoView resources tooltipRef = do
let inputFn _ = do
tooltipKey <- readHoverRef tooltipRef
case tooltipKey of
AttackTooltip mbTag -> return $ Just $ attackDescription mbTag
FeatTooltip mbWTag featTag ->
return $ Just $ featFullDescription mbWTag featTag
_ -> return Nothing
let rectFn _ (w, h) = Rect (half (w - 400)) 0 400 (half h)
tooltip <- newTooltipView resources
vmapM inputFn <$> newMaybeView id (subView rectFn tooltip)
-------------------------------------------------------------------------------
canUseActiveAbility :: AbilitiesState -> CastingCost -> AbilityEffect -> Bool
canUseActiveAbility abils cost eff =
partyCanAffordCastingCost (abilsActiveCharacter abils) cost
(abilsParty abils) &&
case eff of { GeneralAbility _ _ -> True; _ -> abilsInCombat abils }
attackDescription :: Maybe WeaponItemTag -> String
attackDescription mbTag =
"{b}Attack{_} -- " ++ weaponName mbTag ++ " -- " ++
costDescription NoCost ++ "\nAttack with " ++
(if isNothing mbTag then "your bare hands." else "your equipped weapon.")
featFullDescription :: Maybe WeaponItemTag -> FeatTag -> String
featFullDescription mbWTag featTag =
"{b}" ++ featName featTag ++ "{_} -- " ++ weaponName mbWTag ++ " -- " ++
costDescription (featCastingCost featTag) ++ "\n" ++ featDescription featTag
weaponName :: Maybe WeaponItemTag -> String
weaponName = maybe "Fists" (itemName . WeaponItemTag)
-------------------------------------------------------------------------------
| mdsteele/fallback | src/Fallback/View/Abilities.hs | gpl-3.0 | 13,251 | 0 | 28 | 3,572 | 3,328 | 1,705 | 1,623 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Blogger.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Blogger.Types.Sum where
import Network.Google.Prelude
-- | Sort search results
data PostsListOrderBy
= Published
-- ^ @published@
-- Order by the date the post was published
| Updated
-- ^ @updated@
-- Order by the date the post was last updated
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsListOrderBy
instance FromHttpApiData PostsListOrderBy where
parseQueryParam = \case
"published" -> Right Published
"updated" -> Right Updated
x -> Left ("Unable to parse PostsListOrderBy from: " <> x)
instance ToHttpApiData PostsListOrderBy where
toQueryParam = \case
Published -> "published"
Updated -> "updated"
instance FromJSON PostsListOrderBy where
parseJSON = parseJSONText "PostsListOrderBy"
instance ToJSON PostsListOrderBy where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require escalated access.
data PostsListView
= Admin
-- ^ @ADMIN@
-- Admin level detail
| Author
-- ^ @AUTHOR@
-- Author level detail
| Reader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsListView
instance FromHttpApiData PostsListView where
parseQueryParam = \case
"ADMIN" -> Right Admin
"AUTHOR" -> Right Author
"READER" -> Right Reader
x -> Left ("Unable to parse PostsListView from: " <> x)
instance ToHttpApiData PostsListView where
toQueryParam = \case
Admin -> "ADMIN"
Author -> "AUTHOR"
Reader -> "READER"
instance FromJSON PostsListView where
parseJSON = parseJSONText "PostsListView"
instance ToJSON PostsListView where
toJSON = toJSONText
data PageViewsGetRange
= PVGR30DAYS
-- ^ @30DAYS@
-- Page view counts from the last thirty days.
| PVGR7DAYS
-- ^ @7DAYS@
-- Page view counts from the last seven days.
| PVGRAll
-- ^ @all@
-- Total page view counts from all time.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PageViewsGetRange
instance FromHttpApiData PageViewsGetRange where
parseQueryParam = \case
"30DAYS" -> Right PVGR30DAYS
"7DAYS" -> Right PVGR7DAYS
"all" -> Right PVGRAll
x -> Left ("Unable to parse PageViewsGetRange from: " <> x)
instance ToHttpApiData PageViewsGetRange where
toQueryParam = \case
PVGR30DAYS -> "30DAYS"
PVGR7DAYS -> "7DAYS"
PVGRAll -> "all"
instance FromJSON PageViewsGetRange where
parseJSON = parseJSONText "PageViewsGetRange"
instance ToJSON PageViewsGetRange where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require elevated access.
data CommentsListView
= CLVAdmin
-- ^ @ADMIN@
-- Admin level detail
| CLVAuthor
-- ^ @AUTHOR@
-- Author level detail
| CLVReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommentsListView
instance FromHttpApiData CommentsListView where
parseQueryParam = \case
"ADMIN" -> Right CLVAdmin
"AUTHOR" -> Right CLVAuthor
"READER" -> Right CLVReader
x -> Left ("Unable to parse CommentsListView from: " <> x)
instance ToHttpApiData CommentsListView where
toQueryParam = \case
CLVAdmin -> "ADMIN"
CLVAuthor -> "AUTHOR"
CLVReader -> "READER"
instance FromJSON CommentsListView where
parseJSON = parseJSONText "CommentsListView"
instance ToJSON CommentsListView where
toJSON = toJSONText
data PostUserInfosListStatus
= Draft
-- ^ @draft@
-- Draft posts
| Live
-- ^ @live@
-- Published posts
| Scheduled
-- ^ @scheduled@
-- Posts that are scheduled to publish in future.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostUserInfosListStatus
instance FromHttpApiData PostUserInfosListStatus where
parseQueryParam = \case
"draft" -> Right Draft
"live" -> Right Live
"scheduled" -> Right Scheduled
x -> Left ("Unable to parse PostUserInfosListStatus from: " <> x)
instance ToHttpApiData PostUserInfosListStatus where
toQueryParam = \case
Draft -> "draft"
Live -> "live"
Scheduled -> "scheduled"
instance FromJSON PostUserInfosListStatus where
parseJSON = parseJSONText "PostUserInfosListStatus"
instance ToJSON PostUserInfosListStatus where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require elevated access.
data PostsGetView
= PGVAdmin
-- ^ @ADMIN@
-- Admin level detail
| PGVAuthor
-- ^ @AUTHOR@
-- Author level detail
| PGVReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsGetView
instance FromHttpApiData PostsGetView where
parseQueryParam = \case
"ADMIN" -> Right PGVAdmin
"AUTHOR" -> Right PGVAuthor
"READER" -> Right PGVReader
x -> Left ("Unable to parse PostsGetView from: " <> x)
instance ToHttpApiData PostsGetView where
toQueryParam = \case
PGVAdmin -> "ADMIN"
PGVAuthor -> "AUTHOR"
PGVReader -> "READER"
instance FromJSON PostsGetView where
parseJSON = parseJSONText "PostsGetView"
instance ToJSON PostsGetView where
toJSON = toJSONText
-- | Sort search results
data PostsSearchOrderBy
= PSOBPublished
-- ^ @published@
-- Order by the date the post was published
| PSOBUpdated
-- ^ @updated@
-- Order by the date the post was last updated
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsSearchOrderBy
instance FromHttpApiData PostsSearchOrderBy where
parseQueryParam = \case
"published" -> Right PSOBPublished
"updated" -> Right PSOBUpdated
x -> Left ("Unable to parse PostsSearchOrderBy from: " <> x)
instance ToHttpApiData PostsSearchOrderBy where
toQueryParam = \case
PSOBPublished -> "published"
PSOBUpdated -> "updated"
instance FromJSON PostsSearchOrderBy where
parseJSON = parseJSONText "PostsSearchOrderBy"
instance ToJSON PostsSearchOrderBy where
toJSON = toJSONText
data CommentsListByBlogStatus
= CLBBSEmptied
-- ^ @emptied@
-- Comments that have had their content removed
| CLBBSLive
-- ^ @live@
-- Comments that are publicly visible
| CLBBSPending
-- ^ @pending@
-- Comments that are awaiting administrator approval
| CLBBSSpam
-- ^ @spam@
-- Comments marked as spam by the administrator
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommentsListByBlogStatus
instance FromHttpApiData CommentsListByBlogStatus where
parseQueryParam = \case
"emptied" -> Right CLBBSEmptied
"live" -> Right CLBBSLive
"pending" -> Right CLBBSPending
"spam" -> Right CLBBSSpam
x -> Left ("Unable to parse CommentsListByBlogStatus from: " <> x)
instance ToHttpApiData CommentsListByBlogStatus where
toQueryParam = \case
CLBBSEmptied -> "emptied"
CLBBSLive -> "live"
CLBBSPending -> "pending"
CLBBSSpam -> "spam"
instance FromJSON CommentsListByBlogStatus where
parseJSON = parseJSONText "CommentsListByBlogStatus"
instance ToJSON CommentsListByBlogStatus where
toJSON = toJSONText
data PagesGetView
= PAdmin
-- ^ @ADMIN@
-- Admin level detail
| PAuthor
-- ^ @AUTHOR@
-- Author level detail
| PReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PagesGetView
instance FromHttpApiData PagesGetView where
parseQueryParam = \case
"ADMIN" -> Right PAdmin
"AUTHOR" -> Right PAuthor
"READER" -> Right PReader
x -> Left ("Unable to parse PagesGetView from: " <> x)
instance ToHttpApiData PagesGetView where
toQueryParam = \case
PAdmin -> "ADMIN"
PAuthor -> "AUTHOR"
PReader -> "READER"
instance FromJSON PagesGetView where
parseJSON = parseJSONText "PagesGetView"
instance ToJSON PagesGetView where
toJSON = toJSONText
-- | Sort order applied to search results. Default is published.
data PostUserInfosListOrderBy
= PUILOBPublished
-- ^ @published@
-- Order by the date the post was published
| PUILOBUpdated
-- ^ @updated@
-- Order by the date the post was last updated
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostUserInfosListOrderBy
instance FromHttpApiData PostUserInfosListOrderBy where
parseQueryParam = \case
"published" -> Right PUILOBPublished
"updated" -> Right PUILOBUpdated
x -> Left ("Unable to parse PostUserInfosListOrderBy from: " <> x)
instance ToHttpApiData PostUserInfosListOrderBy where
toQueryParam = \case
PUILOBPublished -> "published"
PUILOBUpdated -> "updated"
instance FromJSON PostUserInfosListOrderBy where
parseJSON = parseJSONText "PostUserInfosListOrderBy"
instance ToJSON PostUserInfosListOrderBy where
toJSON = toJSONText
-- | Access level with which to view the blog. Note that some fields require
-- elevated access.
data BlogsGetView
= BGVAdmin
-- ^ @ADMIN@
-- Admin level detail.
| BGVAuthor
-- ^ @AUTHOR@
-- Author level detail.
| BGVReader
-- ^ @READER@
-- Reader level detail.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BlogsGetView
instance FromHttpApiData BlogsGetView where
parseQueryParam = \case
"ADMIN" -> Right BGVAdmin
"AUTHOR" -> Right BGVAuthor
"READER" -> Right BGVReader
x -> Left ("Unable to parse BlogsGetView from: " <> x)
instance ToHttpApiData BlogsGetView where
toQueryParam = \case
BGVAdmin -> "ADMIN"
BGVAuthor -> "AUTHOR"
BGVReader -> "READER"
instance FromJSON BlogsGetView where
parseJSON = parseJSONText "BlogsGetView"
instance ToJSON BlogsGetView where
toJSON = toJSONText
-- | Access level with which to view the blog. Note that some fields require
-- elevated access.
data BlogsGetByURLView
= BGBUVAdmin
-- ^ @ADMIN@
-- Admin level detail.
| BGBUVAuthor
-- ^ @AUTHOR@
-- Author level detail.
| BGBUVReader
-- ^ @READER@
-- Reader level detail.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BlogsGetByURLView
instance FromHttpApiData BlogsGetByURLView where
parseQueryParam = \case
"ADMIN" -> Right BGBUVAdmin
"AUTHOR" -> Right BGBUVAuthor
"READER" -> Right BGBUVReader
x -> Left ("Unable to parse BlogsGetByURLView from: " <> x)
instance ToHttpApiData BlogsGetByURLView where
toQueryParam = \case
BGBUVAdmin -> "ADMIN"
BGBUVAuthor -> "AUTHOR"
BGBUVReader -> "READER"
instance FromJSON BlogsGetByURLView where
parseJSON = parseJSONText "BlogsGetByURLView"
instance ToJSON BlogsGetByURLView where
toJSON = toJSONText
data CommentsListStatus
= CLSEmptied
-- ^ @emptied@
-- Comments that have had their content removed
| CLSLive
-- ^ @live@
-- Comments that are publicly visible
| CLSPending
-- ^ @pending@
-- Comments that are awaiting administrator approval
| CLSSpam
-- ^ @spam@
-- Comments marked as spam by the administrator
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommentsListStatus
instance FromHttpApiData CommentsListStatus where
parseQueryParam = \case
"emptied" -> Right CLSEmptied
"live" -> Right CLSLive
"pending" -> Right CLSPending
"spam" -> Right CLSSpam
x -> Left ("Unable to parse CommentsListStatus from: " <> x)
instance ToHttpApiData CommentsListStatus where
toQueryParam = \case
CLSEmptied -> "emptied"
CLSLive -> "live"
CLSPending -> "pending"
CLSSpam -> "spam"
instance FromJSON CommentsListStatus where
parseJSON = parseJSONText "CommentsListStatus"
instance ToJSON CommentsListStatus where
toJSON = toJSONText
-- | Blog statuses to include in the result (default: Live blogs only). Note
-- that ADMIN access is required to view deleted blogs.
data BlogsListByUserStatus
= BLBUSDeleted
-- ^ @DELETED@
-- Blog has been deleted by an administrator.
| BLBUSLive
-- ^ @LIVE@
-- Blog is currently live.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BlogsListByUserStatus
instance FromHttpApiData BlogsListByUserStatus where
parseQueryParam = \case
"DELETED" -> Right BLBUSDeleted
"LIVE" -> Right BLBUSLive
x -> Left ("Unable to parse BlogsListByUserStatus from: " <> x)
instance ToHttpApiData BlogsListByUserStatus where
toQueryParam = \case
BLBUSDeleted -> "DELETED"
BLBUSLive -> "LIVE"
instance FromJSON BlogsListByUserStatus where
parseJSON = parseJSONText "BlogsListByUserStatus"
instance ToJSON BlogsListByUserStatus where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require elevated access.
data PagesListView
= PLVAdmin
-- ^ @ADMIN@
-- Admin level detail
| PLVAuthor
-- ^ @AUTHOR@
-- Author level detail
| PLVReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PagesListView
instance FromHttpApiData PagesListView where
parseQueryParam = \case
"ADMIN" -> Right PLVAdmin
"AUTHOR" -> Right PLVAuthor
"READER" -> Right PLVReader
x -> Left ("Unable to parse PagesListView from: " <> x)
instance ToHttpApiData PagesListView where
toQueryParam = \case
PLVAdmin -> "ADMIN"
PLVAuthor -> "AUTHOR"
PLVReader -> "READER"
instance FromJSON PagesListView where
parseJSON = parseJSONText "PagesListView"
instance ToJSON PagesListView where
toJSON = toJSONText
-- | Statuses to include in the results.
data PostsListStatus
= PLSDraft
-- ^ @draft@
-- Draft (non-published) posts.
| PLSLive
-- ^ @live@
-- Published posts
| PLSScheduled
-- ^ @scheduled@
-- Posts that are scheduled to publish in the future.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsListStatus
instance FromHttpApiData PostsListStatus where
parseQueryParam = \case
"draft" -> Right PLSDraft
"live" -> Right PLSLive
"scheduled" -> Right PLSScheduled
x -> Left ("Unable to parse PostsListStatus from: " <> x)
instance ToHttpApiData PostsListStatus where
toQueryParam = \case
PLSDraft -> "draft"
PLSLive -> "live"
PLSScheduled -> "scheduled"
instance FromJSON PostsListStatus where
parseJSON = parseJSONText "PostsListStatus"
instance ToJSON PostsListStatus where
toJSON = toJSONText
-- | Access level with which to view the blogs. Note that some fields require
-- elevated access.
data BlogsListByUserView
= BLBUVAdmin
-- ^ @ADMIN@
-- Admin level detail.
| BLBUVAuthor
-- ^ @AUTHOR@
-- Author level detail.
| BLBUVReader
-- ^ @READER@
-- Reader level detail.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BlogsListByUserView
instance FromHttpApiData BlogsListByUserView where
parseQueryParam = \case
"ADMIN" -> Right BLBUVAdmin
"AUTHOR" -> Right BLBUVAuthor
"READER" -> Right BLBUVReader
x -> Left ("Unable to parse BlogsListByUserView from: " <> x)
instance ToHttpApiData BlogsListByUserView where
toQueryParam = \case
BLBUVAdmin -> "ADMIN"
BLBUVAuthor -> "AUTHOR"
BLBUVReader -> "READER"
instance FromJSON BlogsListByUserView where
parseJSON = parseJSONText "BlogsListByUserView"
instance ToJSON BlogsListByUserView where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require elevated access.
data PostUserInfosListView
= PUILVAdmin
-- ^ @ADMIN@
-- Admin level detail
| PUILVAuthor
-- ^ @AUTHOR@
-- Author level detail
| PUILVReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostUserInfosListView
instance FromHttpApiData PostUserInfosListView where
parseQueryParam = \case
"ADMIN" -> Right PUILVAdmin
"AUTHOR" -> Right PUILVAuthor
"READER" -> Right PUILVReader
x -> Left ("Unable to parse PostUserInfosListView from: " <> x)
instance ToHttpApiData PostUserInfosListView where
toQueryParam = \case
PUILVAdmin -> "ADMIN"
PUILVAuthor -> "AUTHOR"
PUILVReader -> "READER"
instance FromJSON PostUserInfosListView where
parseJSON = parseJSONText "PostUserInfosListView"
instance ToJSON PostUserInfosListView where
toJSON = toJSONText
-- | Access level for the requested comment (default: READER). Note that some
-- comments will require elevated permissions, for example comments where
-- the parent posts which is in a draft state, or comments that are pending
-- moderation.
data CommentsGetView
= CGVAdmin
-- ^ @ADMIN@
-- Admin level detail
| CGVAuthor
-- ^ @AUTHOR@
-- Author level detail
| CGVReader
-- ^ @READER@
-- Admin level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable CommentsGetView
instance FromHttpApiData CommentsGetView where
parseQueryParam = \case
"ADMIN" -> Right CGVAdmin
"AUTHOR" -> Right CGVAuthor
"READER" -> Right CGVReader
x -> Left ("Unable to parse CommentsGetView from: " <> x)
instance ToHttpApiData CommentsGetView where
toQueryParam = \case
CGVAdmin -> "ADMIN"
CGVAuthor -> "AUTHOR"
CGVReader -> "READER"
instance FromJSON CommentsGetView where
parseJSON = parseJSONText "CommentsGetView"
instance ToJSON CommentsGetView where
toJSON = toJSONText
-- | Access level with which to view the returned result. Note that some
-- fields require elevated access.
data PostsGetByPathView
= PGBPVAdmin
-- ^ @ADMIN@
-- Admin level detail
| PGBPVAuthor
-- ^ @AUTHOR@
-- Author level detail
| PGBPVReader
-- ^ @READER@
-- Reader level detail
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PostsGetByPathView
instance FromHttpApiData PostsGetByPathView where
parseQueryParam = \case
"ADMIN" -> Right PGBPVAdmin
"AUTHOR" -> Right PGBPVAuthor
"READER" -> Right PGBPVReader
x -> Left ("Unable to parse PostsGetByPathView from: " <> x)
instance ToHttpApiData PostsGetByPathView where
toQueryParam = \case
PGBPVAdmin -> "ADMIN"
PGBPVAuthor -> "AUTHOR"
PGBPVReader -> "READER"
instance FromJSON PostsGetByPathView where
parseJSON = parseJSONText "PostsGetByPathView"
instance ToJSON PostsGetByPathView where
toJSON = toJSONText
data PagesListStatus
= PDraft
-- ^ @draft@
-- Draft (unpublished) Pages
| PLive
-- ^ @live@
-- Pages that are publicly visible
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable PagesListStatus
instance FromHttpApiData PagesListStatus where
parseQueryParam = \case
"draft" -> Right PDraft
"live" -> Right PLive
x -> Left ("Unable to parse PagesListStatus from: " <> x)
instance ToHttpApiData PagesListStatus where
toQueryParam = \case
PDraft -> "draft"
PLive -> "live"
instance FromJSON PagesListStatus where
parseJSON = parseJSONText "PagesListStatus"
instance ToJSON PagesListStatus where
toJSON = toJSONText
-- | User access types for blogs to include in the results, e.g. AUTHOR will
-- return blogs where the user has author level access. If no roles are
-- specified, defaults to ADMIN and AUTHOR roles.
data BlogsListByUserRole
= BLBURAdmin
-- ^ @ADMIN@
-- Admin role - Blogs where the user has Admin level access.
| BLBURAuthor
-- ^ @AUTHOR@
-- Author role - Blogs where the user has Author level access.
| BLBURReader
-- ^ @READER@
-- Reader role - Blogs where the user has Reader level access (to a private
-- blog).
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable BlogsListByUserRole
instance FromHttpApiData BlogsListByUserRole where
parseQueryParam = \case
"ADMIN" -> Right BLBURAdmin
"AUTHOR" -> Right BLBURAuthor
"READER" -> Right BLBURReader
x -> Left ("Unable to parse BlogsListByUserRole from: " <> x)
instance ToHttpApiData BlogsListByUserRole where
toQueryParam = \case
BLBURAdmin -> "ADMIN"
BLBURAuthor -> "AUTHOR"
BLBURReader -> "READER"
instance FromJSON BlogsListByUserRole where
parseJSON = parseJSONText "BlogsListByUserRole"
instance ToJSON BlogsListByUserRole where
toJSON = toJSONText
| rueshyna/gogol | gogol-blogger/gen/Network/Google/Blogger/Types/Sum.hs | mpl-2.0 | 22,302 | 0 | 11 | 5,534 | 3,983 | 2,114 | 1,869 | 461 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.FirebaseRules.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.FirebaseRules.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
-- | The requested runtime executable version. Defaults to
-- FIREBASE_RULES_EXECUTABLE_V1.
data ProjectsReleasesGetExecutableExecutableVersion
= ReleaseExecutableVersionUnspecified
-- ^ @RELEASE_EXECUTABLE_VERSION_UNSPECIFIED@
-- Executable format unspecified. Defaults to FIREBASE_RULES_EXECUTABLE_V1
| FirebaseRulesExecutableV1
-- ^ @FIREBASE_RULES_EXECUTABLE_V1@
-- Firebase Rules syntax \'rules2\' executable versions: Custom AST for use
-- with Java clients.
| FirebaseRulesExecutableV2
-- ^ @FIREBASE_RULES_EXECUTABLE_V2@
-- CEL-based executable for use with C++ clients.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable ProjectsReleasesGetExecutableExecutableVersion
instance FromHttpApiData ProjectsReleasesGetExecutableExecutableVersion where
parseQueryParam = \case
"RELEASE_EXECUTABLE_VERSION_UNSPECIFIED" -> Right ReleaseExecutableVersionUnspecified
"FIREBASE_RULES_EXECUTABLE_V1" -> Right FirebaseRulesExecutableV1
"FIREBASE_RULES_EXECUTABLE_V2" -> Right FirebaseRulesExecutableV2
x -> Left ("Unable to parse ProjectsReleasesGetExecutableExecutableVersion from: " <> x)
instance ToHttpApiData ProjectsReleasesGetExecutableExecutableVersion where
toQueryParam = \case
ReleaseExecutableVersionUnspecified -> "RELEASE_EXECUTABLE_VERSION_UNSPECIFIED"
FirebaseRulesExecutableV1 -> "FIREBASE_RULES_EXECUTABLE_V1"
FirebaseRulesExecutableV2 -> "FIREBASE_RULES_EXECUTABLE_V2"
instance FromJSON ProjectsReleasesGetExecutableExecutableVersion where
parseJSON = parseJSONText "ProjectsReleasesGetExecutableExecutableVersion"
instance ToJSON ProjectsReleasesGetExecutableExecutableVersion where
toJSON = toJSONText
-- | Specifies what should be included in the response.
data TestCaseExpressionReportLevel
= LevelUnspecified
-- ^ @LEVEL_UNSPECIFIED@
-- No level has been specified. Defaults to \"NONE\" behavior.
| None
-- ^ @NONE@
-- Do not include any additional information.
| Full
-- ^ @FULL@
-- Include detailed reporting on expressions evaluated.
| Visited
-- ^ @VISITED@
-- Only include the expressions that were visited during evaluation.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TestCaseExpressionReportLevel
instance FromHttpApiData TestCaseExpressionReportLevel where
parseQueryParam = \case
"LEVEL_UNSPECIFIED" -> Right LevelUnspecified
"NONE" -> Right None
"FULL" -> Right Full
"VISITED" -> Right Visited
x -> Left ("Unable to parse TestCaseExpressionReportLevel from: " <> x)
instance ToHttpApiData TestCaseExpressionReportLevel where
toQueryParam = \case
LevelUnspecified -> "LEVEL_UNSPECIFIED"
None -> "NONE"
Full -> "FULL"
Visited -> "VISITED"
instance FromJSON TestCaseExpressionReportLevel where
parseJSON = parseJSONText "TestCaseExpressionReportLevel"
instance ToJSON TestCaseExpressionReportLevel where
toJSON = toJSONText
-- | State of the test.
data TestResultState
= StateUnspecified
-- ^ @STATE_UNSPECIFIED@
-- Test state is not set.
| Success
-- ^ @SUCCESS@
-- Test is a success.
| Failure
-- ^ @FAILURE@
-- Test is a failure.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TestResultState
instance FromHttpApiData TestResultState where
parseQueryParam = \case
"STATE_UNSPECIFIED" -> Right StateUnspecified
"SUCCESS" -> Right Success
"FAILURE" -> Right Failure
x -> Left ("Unable to parse TestResultState from: " <> x)
instance ToHttpApiData TestResultState where
toQueryParam = \case
StateUnspecified -> "STATE_UNSPECIFIED"
Success -> "SUCCESS"
Failure -> "FAILURE"
instance FromJSON TestResultState where
parseJSON = parseJSONText "TestResultState"
instance ToJSON TestResultState where
toJSON = toJSONText
-- | Specifies whether paths (such as request.path) are encoded and how.
data TestCasePathEncoding
= EncodingUnspecified
-- ^ @ENCODING_UNSPECIFIED@
-- No encoding has been specified. Defaults to \"URL_ENCODED\" behavior.
| URLEncoded
-- ^ @URL_ENCODED@
-- Treats path segments as URL encoded but with non-encoded separators
-- (\"\/\"). This is the default behavior.
| Plain
-- ^ @PLAIN@
-- Treats total path as non-URL encoded e.g. raw.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TestCasePathEncoding
instance FromHttpApiData TestCasePathEncoding where
parseQueryParam = \case
"ENCODING_UNSPECIFIED" -> Right EncodingUnspecified
"URL_ENCODED" -> Right URLEncoded
"PLAIN" -> Right Plain
x -> Left ("Unable to parse TestCasePathEncoding from: " <> x)
instance ToHttpApiData TestCasePathEncoding where
toQueryParam = \case
EncodingUnspecified -> "ENCODING_UNSPECIFIED"
URLEncoded -> "URL_ENCODED"
Plain -> "PLAIN"
instance FromJSON TestCasePathEncoding where
parseJSON = parseJSONText "TestCasePathEncoding"
instance ToJSON TestCasePathEncoding where
toJSON = toJSONText
-- | V1 error format.
data Xgafv
= X1
-- ^ @1@
-- v1 error format
| X2
-- ^ @2@
-- v2 error format
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable Xgafv
instance FromHttpApiData Xgafv where
parseQueryParam = \case
"1" -> Right X1
"2" -> Right X2
x -> Left ("Unable to parse Xgafv from: " <> x)
instance ToHttpApiData Xgafv where
toQueryParam = \case
X1 -> "1"
X2 -> "2"
instance FromJSON Xgafv where
parseJSON = parseJSONText "Xgafv"
instance ToJSON Xgafv where
toJSON = toJSONText
-- | The severity of the issue.
data IssueSeverity
= SeverityUnspecified
-- ^ @SEVERITY_UNSPECIFIED@
-- An unspecified severity.
| Deprecation
-- ^ @DEPRECATION@
-- Deprecation issue for statements and method that may no longer be
-- supported or maintained.
| Warning
-- ^ @WARNING@
-- Warnings such as: unused variables.
| Error'
-- ^ @ERROR@
-- Errors such as: unmatched curly braces or variable redefinition.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable IssueSeverity
instance FromHttpApiData IssueSeverity where
parseQueryParam = \case
"SEVERITY_UNSPECIFIED" -> Right SeverityUnspecified
"DEPRECATION" -> Right Deprecation
"WARNING" -> Right Warning
"ERROR" -> Right Error'
x -> Left ("Unable to parse IssueSeverity from: " <> x)
instance ToHttpApiData IssueSeverity where
toQueryParam = \case
SeverityUnspecified -> "SEVERITY_UNSPECIFIED"
Deprecation -> "DEPRECATION"
Warning -> "WARNING"
Error' -> "ERROR"
instance FromJSON IssueSeverity where
parseJSON = parseJSONText "IssueSeverity"
instance ToJSON IssueSeverity where
toJSON = toJSONText
-- | Test expectation.
data TestCaseExpectation
= ExpectationUnspecified
-- ^ @EXPECTATION_UNSPECIFIED@
-- Unspecified expectation.
| Allow
-- ^ @ALLOW@
-- Expect an allowed result.
| Deny
-- ^ @DENY@
-- Expect a denied result.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable TestCaseExpectation
instance FromHttpApiData TestCaseExpectation where
parseQueryParam = \case
"EXPECTATION_UNSPECIFIED" -> Right ExpectationUnspecified
"ALLOW" -> Right Allow
"DENY" -> Right Deny
x -> Left ("Unable to parse TestCaseExpectation from: " <> x)
instance ToHttpApiData TestCaseExpectation where
toQueryParam = \case
ExpectationUnspecified -> "EXPECTATION_UNSPECIFIED"
Allow -> "ALLOW"
Deny -> "DENY"
instance FromJSON TestCaseExpectation where
parseJSON = parseJSONText "TestCaseExpectation"
instance ToJSON TestCaseExpectation where
toJSON = toJSONText
-- | The Rules runtime version of the executable.
data GetReleaseExecutableResponseExecutableVersion
= GREREVReleaseExecutableVersionUnspecified
-- ^ @RELEASE_EXECUTABLE_VERSION_UNSPECIFIED@
-- Executable format unspecified. Defaults to FIREBASE_RULES_EXECUTABLE_V1
| GREREVFirebaseRulesExecutableV1
-- ^ @FIREBASE_RULES_EXECUTABLE_V1@
-- Firebase Rules syntax \'rules2\' executable versions: Custom AST for use
-- with Java clients.
| GREREVFirebaseRulesExecutableV2
-- ^ @FIREBASE_RULES_EXECUTABLE_V2@
-- CEL-based executable for use with C++ clients.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable GetReleaseExecutableResponseExecutableVersion
instance FromHttpApiData GetReleaseExecutableResponseExecutableVersion where
parseQueryParam = \case
"RELEASE_EXECUTABLE_VERSION_UNSPECIFIED" -> Right GREREVReleaseExecutableVersionUnspecified
"FIREBASE_RULES_EXECUTABLE_V1" -> Right GREREVFirebaseRulesExecutableV1
"FIREBASE_RULES_EXECUTABLE_V2" -> Right GREREVFirebaseRulesExecutableV2
x -> Left ("Unable to parse GetReleaseExecutableResponseExecutableVersion from: " <> x)
instance ToHttpApiData GetReleaseExecutableResponseExecutableVersion where
toQueryParam = \case
GREREVReleaseExecutableVersionUnspecified -> "RELEASE_EXECUTABLE_VERSION_UNSPECIFIED"
GREREVFirebaseRulesExecutableV1 -> "FIREBASE_RULES_EXECUTABLE_V1"
GREREVFirebaseRulesExecutableV2 -> "FIREBASE_RULES_EXECUTABLE_V2"
instance FromJSON GetReleaseExecutableResponseExecutableVersion where
parseJSON = parseJSONText "GetReleaseExecutableResponseExecutableVersion"
instance ToJSON GetReleaseExecutableResponseExecutableVersion where
toJSON = toJSONText
-- | \`Language\` used to generate the executable bytes.
data GetReleaseExecutableResponseLanguage
= LanguageUnspecified
-- ^ @LANGUAGE_UNSPECIFIED@
-- Language unspecified. Defaults to FIREBASE_RULES.
| FirebaseRules
-- ^ @FIREBASE_RULES@
-- Firebase Rules language.
| EventFlowTriggers
-- ^ @EVENT_FLOW_TRIGGERS@
-- Event Flow triggers.
deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic)
instance Hashable GetReleaseExecutableResponseLanguage
instance FromHttpApiData GetReleaseExecutableResponseLanguage where
parseQueryParam = \case
"LANGUAGE_UNSPECIFIED" -> Right LanguageUnspecified
"FIREBASE_RULES" -> Right FirebaseRules
"EVENT_FLOW_TRIGGERS" -> Right EventFlowTriggers
x -> Left ("Unable to parse GetReleaseExecutableResponseLanguage from: " <> x)
instance ToHttpApiData GetReleaseExecutableResponseLanguage where
toQueryParam = \case
LanguageUnspecified -> "LANGUAGE_UNSPECIFIED"
FirebaseRules -> "FIREBASE_RULES"
EventFlowTriggers -> "EVENT_FLOW_TRIGGERS"
instance FromJSON GetReleaseExecutableResponseLanguage where
parseJSON = parseJSONText "GetReleaseExecutableResponseLanguage"
instance ToJSON GetReleaseExecutableResponseLanguage where
toJSON = toJSONText
| brendanhay/gogol | gogol-firebase-rules/gen/Network/Google/FirebaseRules/Types/Sum.hs | mpl-2.0 | 11,913 | 0 | 11 | 2,458 | 1,698 | 909 | 789 | 200 | 0 |
{-# 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.TPU.Projects.Locations.Operations.Cancel
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ <https://cloud.google.com/tpu/ Cloud TPU API Reference> for @tpu.projects.locations.operations.cancel@.
module Network.Google.Resource.TPU.Projects.Locations.Operations.Cancel
(
-- * REST Resource
ProjectsLocationsOperationsCancelResource
-- * Creating a Request
, projectsLocationsOperationsCancel
, ProjectsLocationsOperationsCancel
-- * Request Lenses
, plocXgafv
, plocUploadProtocol
, plocAccessToken
, plocUploadType
, plocName
, plocCallback
) where
import Network.Google.Prelude
import Network.Google.TPU.Types
-- | A resource alias for @tpu.projects.locations.operations.cancel@ method which the
-- 'ProjectsLocationsOperationsCancel' request conforms to.
type ProjectsLocationsOperationsCancelResource =
"v1" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Post '[JSON] Empty
-- | Starts asynchronous cancellation on a long-running operation. The server
-- makes a best effort to cancel the operation, but success is not
-- guaranteed. If the server doesn\'t support this method, it returns
-- \`google.rpc.Code.UNIMPLEMENTED\`. Clients can use
-- Operations.GetOperation or other methods to check whether the
-- cancellation succeeded or whether the operation completed despite
-- cancellation. On successful cancellation, the operation is not deleted;
-- instead, it becomes an operation with an Operation.error value with a
-- google.rpc.Status.code of 1, corresponding to \`Code.CANCELLED\`.
--
-- /See:/ 'projectsLocationsOperationsCancel' smart constructor.
data ProjectsLocationsOperationsCancel =
ProjectsLocationsOperationsCancel'
{ _plocXgafv :: !(Maybe Xgafv)
, _plocUploadProtocol :: !(Maybe Text)
, _plocAccessToken :: !(Maybe Text)
, _plocUploadType :: !(Maybe Text)
, _plocName :: !Text
, _plocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsOperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plocXgafv'
--
-- * 'plocUploadProtocol'
--
-- * 'plocAccessToken'
--
-- * 'plocUploadType'
--
-- * 'plocName'
--
-- * 'plocCallback'
projectsLocationsOperationsCancel
:: Text -- ^ 'plocName'
-> ProjectsLocationsOperationsCancel
projectsLocationsOperationsCancel pPlocName_ =
ProjectsLocationsOperationsCancel'
{ _plocXgafv = Nothing
, _plocUploadProtocol = Nothing
, _plocAccessToken = Nothing
, _plocUploadType = Nothing
, _plocName = pPlocName_
, _plocCallback = Nothing
}
-- | V1 error format.
plocXgafv :: Lens' ProjectsLocationsOperationsCancel (Maybe Xgafv)
plocXgafv
= lens _plocXgafv (\ s a -> s{_plocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plocUploadProtocol :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadProtocol
= lens _plocUploadProtocol
(\ s a -> s{_plocUploadProtocol = a})
-- | OAuth access token.
plocAccessToken :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocAccessToken
= lens _plocAccessToken
(\ s a -> s{_plocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plocUploadType :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocUploadType
= lens _plocUploadType
(\ s a -> s{_plocUploadType = a})
-- | The name of the operation resource to be cancelled.
plocName :: Lens' ProjectsLocationsOperationsCancel Text
plocName = lens _plocName (\ s a -> s{_plocName = a})
-- | JSONP
plocCallback :: Lens' ProjectsLocationsOperationsCancel (Maybe Text)
plocCallback
= lens _plocCallback (\ s a -> s{_plocCallback = a})
instance GoogleRequest
ProjectsLocationsOperationsCancel
where
type Rs ProjectsLocationsOperationsCancel = Empty
type Scopes ProjectsLocationsOperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsOperationsCancel'{..}
= go _plocName _plocXgafv _plocUploadProtocol
_plocAccessToken
_plocUploadType
_plocCallback
(Just AltJSON)
tPUService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsOperationsCancelResource)
mempty
| brendanhay/gogol | gogol-tpu/gen/Network/Google/Resource/TPU/Projects/Locations/Operations/Cancel.hs | mpl-2.0 | 6,102 | 0 | 15 | 1,233 | 714 | 424 | 290 | 103 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.URLShortener.URL.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of URLs shortened by a user.
--
-- /See:/ <https://developers.google.com/url-shortener/v1/getting_started URL Shortener API Reference> for @urlshortener.url.list@.
module Network.Google.Resource.URLShortener.URL.List
(
-- * REST Resource
URLListResource
-- * Creating a Request
, urlList
, URLList
-- * Request Lenses
, ulStartToken
, ulProjection
) where
import Network.Google.Prelude
import Network.Google.URLShortener.Types
-- | A resource alias for @urlshortener.url.list@ method which the
-- 'URLList' request conforms to.
type URLListResource =
"urlshortener" :>
"v1" :>
"url" :>
"history" :>
QueryParam "start-token" Text :>
QueryParam "projection" URLListProjection :>
QueryParam "alt" AltJSON :> Get '[JSON] URLHistory
-- | Retrieves a list of URLs shortened by a user.
--
-- /See:/ 'urlList' smart constructor.
data URLList =
URLList'
{ _ulStartToken :: !(Maybe Text)
, _ulProjection :: !(Maybe URLListProjection)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'URLList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ulStartToken'
--
-- * 'ulProjection'
urlList
:: URLList
urlList = URLList' {_ulStartToken = Nothing, _ulProjection = Nothing}
-- | Token for requesting successive pages of results.
ulStartToken :: Lens' URLList (Maybe Text)
ulStartToken
= lens _ulStartToken (\ s a -> s{_ulStartToken = a})
-- | Additional information to return.
ulProjection :: Lens' URLList (Maybe URLListProjection)
ulProjection
= lens _ulProjection (\ s a -> s{_ulProjection = a})
instance GoogleRequest URLList where
type Rs URLList = URLHistory
type Scopes URLList =
'["https://www.googleapis.com/auth/urlshortener"]
requestClient URLList'{..}
= go _ulStartToken _ulProjection (Just AltJSON)
uRLShortenerService
where go
= buildClient (Proxy :: Proxy URLListResource) mempty
| brendanhay/gogol | gogol-urlshortener/gen/Network/Google/Resource/URLShortener/URL/List.hs | mpl-2.0 | 2,916 | 0 | 14 | 645 | 390 | 233 | 157 | 56 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidEnterprise.ManagedConfigurationsforUser.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all the per-user managed configurations for the specified user.
-- Only the ID is set.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.managedconfigurationsforuser.list@.
module Network.Google.Resource.AndroidEnterprise.ManagedConfigurationsforUser.List
(
-- * REST Resource
ManagedConfigurationsforUserListResource
-- * Creating a Request
, managedConfigurationsforUserList
, ManagedConfigurationsforUserList
-- * Request Lenses
, mculXgafv
, mculUploadProtocol
, mculEnterpriseId
, mculAccessToken
, mculUploadType
, mculUserId
, mculCallback
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.managedconfigurationsforuser.list@ method which the
-- 'ManagedConfigurationsforUserList' request conforms to.
type ManagedConfigurationsforUserListResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
Capture "enterpriseId" Text :>
"users" :>
Capture "userId" Text :>
"managedConfigurationsForUser" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
ManagedConfigurationsForUserListResponse
-- | Lists all the per-user managed configurations for the specified user.
-- Only the ID is set.
--
-- /See:/ 'managedConfigurationsforUserList' smart constructor.
data ManagedConfigurationsforUserList =
ManagedConfigurationsforUserList'
{ _mculXgafv :: !(Maybe Xgafv)
, _mculUploadProtocol :: !(Maybe Text)
, _mculEnterpriseId :: !Text
, _mculAccessToken :: !(Maybe Text)
, _mculUploadType :: !(Maybe Text)
, _mculUserId :: !Text
, _mculCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ManagedConfigurationsforUserList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mculXgafv'
--
-- * 'mculUploadProtocol'
--
-- * 'mculEnterpriseId'
--
-- * 'mculAccessToken'
--
-- * 'mculUploadType'
--
-- * 'mculUserId'
--
-- * 'mculCallback'
managedConfigurationsforUserList
:: Text -- ^ 'mculEnterpriseId'
-> Text -- ^ 'mculUserId'
-> ManagedConfigurationsforUserList
managedConfigurationsforUserList pMculEnterpriseId_ pMculUserId_ =
ManagedConfigurationsforUserList'
{ _mculXgafv = Nothing
, _mculUploadProtocol = Nothing
, _mculEnterpriseId = pMculEnterpriseId_
, _mculAccessToken = Nothing
, _mculUploadType = Nothing
, _mculUserId = pMculUserId_
, _mculCallback = Nothing
}
-- | V1 error format.
mculXgafv :: Lens' ManagedConfigurationsforUserList (Maybe Xgafv)
mculXgafv
= lens _mculXgafv (\ s a -> s{_mculXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
mculUploadProtocol :: Lens' ManagedConfigurationsforUserList (Maybe Text)
mculUploadProtocol
= lens _mculUploadProtocol
(\ s a -> s{_mculUploadProtocol = a})
-- | The ID of the enterprise.
mculEnterpriseId :: Lens' ManagedConfigurationsforUserList Text
mculEnterpriseId
= lens _mculEnterpriseId
(\ s a -> s{_mculEnterpriseId = a})
-- | OAuth access token.
mculAccessToken :: Lens' ManagedConfigurationsforUserList (Maybe Text)
mculAccessToken
= lens _mculAccessToken
(\ s a -> s{_mculAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
mculUploadType :: Lens' ManagedConfigurationsforUserList (Maybe Text)
mculUploadType
= lens _mculUploadType
(\ s a -> s{_mculUploadType = a})
-- | The ID of the user.
mculUserId :: Lens' ManagedConfigurationsforUserList Text
mculUserId
= lens _mculUserId (\ s a -> s{_mculUserId = a})
-- | JSONP
mculCallback :: Lens' ManagedConfigurationsforUserList (Maybe Text)
mculCallback
= lens _mculCallback (\ s a -> s{_mculCallback = a})
instance GoogleRequest
ManagedConfigurationsforUserList
where
type Rs ManagedConfigurationsforUserList =
ManagedConfigurationsForUserListResponse
type Scopes ManagedConfigurationsforUserList =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient ManagedConfigurationsforUserList'{..}
= go _mculEnterpriseId _mculUserId _mculXgafv
_mculUploadProtocol
_mculAccessToken
_mculUploadType
_mculCallback
(Just AltJSON)
androidEnterpriseService
where go
= buildClient
(Proxy ::
Proxy ManagedConfigurationsforUserListResource)
mempty
| brendanhay/gogol | gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/ManagedConfigurationsforUser/List.hs | mpl-2.0 | 5,908 | 0 | 20 | 1,390 | 787 | 458 | 329 | 123 | 1 |
module Data.Multimap.Tests
( runTests
) where
import qualified Data.Multimap as Multimap
import qualified Data.Set as Set
import Test.Dwergaz
testKey1 :: String
testKey1 = "one"
testKey2 :: String
testKey2 = "two"
empty :: Multimap.Multimap String Int
empty = Multimap.empty
inserter :: (Ord k, Ord v) => (k, v) -> Multimap.Multimap k v -> Multimap.Multimap k v
inserter (k, v) = Multimap.insert k v
emptyIsNull :: Test
emptyIsNull =
Predicate "null returns true on empty map"
Multimap.null
empty
nonEmptyIsNotNull :: Test
nonEmptyIsNotNull =
Predicate "null returns false on non-empty map"
(not . Multimap.null)
(Multimap.insert testKey1 1 empty)
nonEmptyHasItem :: Test
nonEmptyHasItem =
Expect "non-empty map has inserted item"
(==)
(Multimap.lookup testKey1 testMap)
(Set.fromList [1])
where
testMap = foldr inserter empty [(testKey1, 1)]
twoValuesUnderKey :: Test
twoValuesUnderKey =
Expect "two values can be stored under the same key"
(==)
(Multimap.lookup testKey1 testMap)
(Set.fromList [1, 2])
where
testMap = foldr inserter empty [(testKey1, 1), (testKey1, 2)]
deleteAllWorks :: Test
deleteAllWorks =
Expect "deleteAll removes all values under a key"
(==)
(Multimap.lookup testKey1 (Multimap.deleteAll testKey1 testMap))
Set.empty
where
testMap = foldr inserter empty [(testKey1, 1), (testKey1, 2)]
deleteWorks :: Test
deleteWorks =
Expect "delete removes a specific value under a key"
(==)
(Multimap.lookup testKey1 (Multimap.delete testKey1 1 testMap))
(Set.fromList [2])
where
testMap = foldr inserter empty [(testKey1, 1), (testKey1, 2)]
fromListWorks :: Test
fromListWorks =
Expect "fromList constructs a map from a list of pairs"
(==)
(Multimap.fromList [(testKey1, 1), (testKey1, 2)])
(foldr inserter empty [(testKey1, 1), (testKey1, 2)])
elemsWorks :: Test
elemsWorks =
Expect "elems returns all values in the map"
(==)
(Multimap.elems testMap)
[1, 2, 3]
where
testMap = foldr inserter empty [(testKey1, 1), (testKey1, 2), (testKey2, 3)]
tests :: [Test]
tests =
[ emptyIsNull
, nonEmptyIsNotNull
, nonEmptyHasItem
, twoValuesUnderKey
, deleteAllWorks
, deleteWorks
, fromListWorks
, elemsWorks
]
runTests :: [Result]
runTests = runTest <$> tests
| henrytill/hecate | tests/Data/Multimap/Tests.hs | apache-2.0 | 2,477 | 0 | 10 | 616 | 709 | 407 | 302 | 76 | 1 |
module Graham.A328045 (a328045, a328045_list) where
import Data.List (genericIndex, subsequences)
import Graham.A006255 (a006255_list)
import Graham.A300518 (a300518)
import Math.NumberTheory.Powers.Squares (isSquare')
import Math.NumberTheory.Powers.Fourth (isFourthPower')
a328045 :: Integer -> Integer
a328045 n
| isSquare' n = n
| agreesWithGraham n = a300518 n + n
| otherwise = last $ head $ filter anyProductIsFourthPower candidateSequences where
candidateSequences = map (n:) $ subsequences $ possibleBases n
a328045_list :: [Integer]
a328045_list = map a328045 [0..]
raiseUp :: [Integer] -> [[Integer]]
raiseUp = foldr (\a -> concatMap (\ts -> [a^1 : ts, a^2 : ts, a^3 : ts])) [[]]
anyProductIsFourthPower :: [Integer] -> Bool
anyProductIsFourthPower as = any (isFourthPower' . product) $ raiseUp as
agreesWithGraham :: Integer -> Bool
agreesWithGraham n = lowerBound == upperBound n where
lowerBound = a300518 n + n
upperBound :: Integer -> Integer
upperBound = genericIndex (0 : a006255_list)
possibleBases n = [i | i <- [n+1..ub], n <= (i - a300518 i) || i + a300518 i <= ub] where
ub = upperBound n
| peterokagey/haskellOEIS | src/Graham/A328045.hs | apache-2.0 | 1,146 | 0 | 13 | 197 | 439 | 235 | 204 | 25 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGroupBox_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:26
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGroupBox_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 (QGroupBox ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGroupBox_unSetUserMethod" qtc_QGroupBox_unSetUserMethod :: Ptr (TQGroupBox a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGroupBoxSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGroupBox ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGroupBoxSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGroupBox ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGroupBoxSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGroupBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGroupBox ()) (QGroupBox x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGroupBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGroupBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGroupBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGroupBox 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_QGroupBox_setUserMethod" qtc_QGroupBox_setUserMethod :: Ptr (TQGroupBox a) -> CInt -> Ptr (Ptr (TQGroupBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGroupBox :: (Ptr (TQGroupBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQGroupBox x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGroupBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGroupBoxSc a) (QGroupBox x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGroupBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGroupBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGroupBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGroupBox 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 (QGroupBox ()) (QGroupBox x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGroupBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGroupBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGroupBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGroupBox 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_QGroupBox_setUserMethodVariant" qtc_QGroupBox_setUserMethodVariant :: Ptr (TQGroupBox a) -> CInt -> Ptr (Ptr (TQGroupBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGroupBox :: (Ptr (TQGroupBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGroupBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGroupBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGroupBoxSc a) (QGroupBox x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGroupBox setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGroupBox_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGroupBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGroupBox 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 (QGroupBox ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGroupBox_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGroupBox_unSetHandler" qtc_QGroupBox_unSetHandler :: Ptr (TQGroupBox a) -> CWString -> IO (CBool)
instance QunSetHandler (QGroupBoxSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGroupBox_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler1" qtc_QGroupBox_setHandler1 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox1 :: (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_changeEvent" qtc_QGroupBox_changeEvent :: Ptr (TQGroupBox a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QGroupBoxSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_changeEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler2" qtc_QGroupBox_setHandler2 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox2 :: (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_event cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_event" qtc_QGroupBox_event :: Ptr (TQGroupBox a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QGroupBoxSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_event cobj_x0 cobj_x1
instance QfocusInEvent_h (QGroupBox ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_focusInEvent" qtc_QGroupBox_focusInEvent :: Ptr (TQGroupBox a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGroupBoxSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_focusInEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler3" qtc_QGroupBox_setHandler3 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox3 :: (Ptr (TQGroupBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQGroupBox x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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 QqminimumSizeHint_h (QGroupBox ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_minimumSizeHint cobj_x0
foreign import ccall "qtc_QGroupBox_minimumSizeHint" qtc_QGroupBox_minimumSizeHint :: Ptr (TQGroupBox a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QGroupBoxSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QGroupBox ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGroupBox_minimumSizeHint_qth" qtc_QGroupBox_minimumSizeHint_qth :: Ptr (TQGroupBox a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QGroupBoxSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QmouseMoveEvent_h (QGroupBox ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_mouseMoveEvent" qtc_QGroupBox_mouseMoveEvent :: Ptr (TQGroupBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGroupBoxSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGroupBox ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_mousePressEvent" qtc_QGroupBox_mousePressEvent :: Ptr (TQGroupBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGroupBoxSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGroupBox ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_mouseReleaseEvent" qtc_QGroupBox_mouseReleaseEvent :: Ptr (TQGroupBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGroupBoxSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseReleaseEvent cobj_x0 cobj_x1
instance QpaintEvent_h (QGroupBox ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_paintEvent" qtc_QGroupBox_paintEvent :: Ptr (TQGroupBox a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QGroupBoxSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_paintEvent cobj_x0 cobj_x1
instance QresizeEvent_h (QGroupBox ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_resizeEvent" qtc_QGroupBox_resizeEvent :: Ptr (TQGroupBox a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QGroupBoxSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_resizeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QGroupBox ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_actionEvent" qtc_QGroupBox_actionEvent :: Ptr (TQGroupBox a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QGroupBoxSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QGroupBox ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_closeEvent" qtc_QGroupBox_closeEvent :: Ptr (TQGroupBox a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QGroupBoxSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QGroupBox ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_contextMenuEvent" qtc_QGroupBox_contextMenuEvent :: Ptr (TQGroupBox a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGroupBoxSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler4" qtc_QGroupBox_setHandler4 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox4 :: (Ptr (TQGroupBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGroupBox x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_devType cobj_x0
foreign import ccall "qtc_QGroupBox_devType" qtc_QGroupBox_devType :: Ptr (TQGroupBox a) -> IO CInt
instance QdevType_h (QGroupBoxSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_devType cobj_x0
instance QdragEnterEvent_h (QGroupBox ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_dragEnterEvent" qtc_QGroupBox_dragEnterEvent :: Ptr (TQGroupBox a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QGroupBoxSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGroupBox ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_dragLeaveEvent" qtc_QGroupBox_dragLeaveEvent :: Ptr (TQGroupBox a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGroupBoxSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGroupBox ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_dragMoveEvent" qtc_QGroupBox_dragMoveEvent :: Ptr (TQGroupBox a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QGroupBoxSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGroupBox ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_dropEvent" qtc_QGroupBox_dropEvent :: Ptr (TQGroupBox a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QGroupBoxSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QGroupBox ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_enterEvent" qtc_QGroupBox_enterEvent :: Ptr (TQGroupBox a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QGroupBoxSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_enterEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGroupBox ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_focusOutEvent" qtc_QGroupBox_focusOutEvent :: Ptr (TQGroupBox a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGroupBoxSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler5" qtc_QGroupBox_setHandler5 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox5 :: (Ptr (TQGroupBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQGroupBox x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGroupBox_heightForWidth" qtc_QGroupBox_heightForWidth :: Ptr (TQGroupBox a) -> CInt -> IO CInt
instance QheightForWidth_h (QGroupBoxSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QGroupBox ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_hideEvent" qtc_QGroupBox_hideEvent :: Ptr (TQGroupBox a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QGroupBoxSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler6" qtc_QGroupBox_setHandler6 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox6 :: (Ptr (TQGroupBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGroupBox x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGroupBox_inputMethodQuery" qtc_QGroupBox_inputMethodQuery :: Ptr (TQGroupBox a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGroupBoxSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent_h (QGroupBox ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_keyPressEvent" qtc_QGroupBox_keyPressEvent :: Ptr (TQGroupBox a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGroupBoxSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGroupBox ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_keyReleaseEvent" qtc_QGroupBox_keyReleaseEvent :: Ptr (TQGroupBox a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGroupBoxSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QGroupBox ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_leaveEvent" qtc_QGroupBox_leaveEvent :: Ptr (TQGroupBox a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QGroupBoxSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_leaveEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGroupBox ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_mouseDoubleClickEvent" qtc_QGroupBox_mouseDoubleClickEvent :: Ptr (TQGroupBox a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGroupBoxSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QGroupBox ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_moveEvent" qtc_QGroupBox_moveEvent :: Ptr (TQGroupBox a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QGroupBoxSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler7" qtc_QGroupBox_setHandler7 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox7 :: (Ptr (TQGroupBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQGroupBox x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_paintEngine cobj_x0
foreign import ccall "qtc_QGroupBox_paintEngine" qtc_QGroupBox_paintEngine :: Ptr (TQGroupBox a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QGroupBoxSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_paintEngine cobj_x0
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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_QGroupBox_setHandler8" qtc_QGroupBox_setHandler8 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox8 :: (Ptr (TQGroupBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQGroupBox x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qGroupBoxFromPtr 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 (QGroupBox ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGroupBox_setVisible" qtc_QGroupBox_setVisible :: Ptr (TQGroupBox a) -> CBool -> IO ()
instance QsetVisible_h (QGroupBoxSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QGroupBox ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_showEvent" qtc_QGroupBox_showEvent :: Ptr (TQGroupBox a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QGroupBoxSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QGroupBox ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_sizeHint cobj_x0
foreign import ccall "qtc_QGroupBox_sizeHint" qtc_QGroupBox_sizeHint :: Ptr (TQGroupBox a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QGroupBoxSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_sizeHint cobj_x0
instance QsizeHint_h (QGroupBox ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QGroupBox_sizeHint_qth" qtc_QGroupBox_sizeHint_qth :: Ptr (TQGroupBox a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QGroupBoxSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGroupBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent_h (QGroupBox ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_tabletEvent" qtc_QGroupBox_tabletEvent :: Ptr (TQGroupBox a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QGroupBoxSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QGroupBox ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGroupBox_wheelEvent" qtc_QGroupBox_wheelEvent :: Ptr (TQGroupBox a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGroupBoxSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGroupBox_wheelEvent cobj_x0 cobj_x1
instance QsetHandler (QGroupBox ()) (QGroupBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qGroupBoxFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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_QGroupBox_setHandler9" qtc_QGroupBox_setHandler9 :: Ptr (TQGroupBox a) -> CWString -> Ptr (Ptr (TQGroupBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGroupBox9 :: (Ptr (TQGroupBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGroupBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGroupBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGroupBoxSc a) (QGroupBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGroupBox9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGroupBox9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGroupBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGroupBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qGroupBoxFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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 QeventFilter_h (QGroupBox ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGroupBox_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGroupBox_eventFilter" qtc_QGroupBox_eventFilter :: Ptr (TQGroupBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QGroupBoxSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGroupBox_eventFilter cobj_x0 cobj_x1 cobj_x2
| keera-studios/hsQt | Qtc/Gui/QGroupBox_h.hs | bsd-2-clause | 56,487 | 0 | 18 | 12,271 | 18,825 | 9,082 | 9,743 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.Eval
-- Copyright : (c) 2009 Daniel Schoepe
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Daniel Schoepe <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Evaluate haskell expressions at runtime in the running xmonad instance.
--
-----------------------------------------------------------------------------
module XMonad.Actions.MyEval (
-- * Usage
-- $usage
-- * Documentation
-- $documentation
evalExpression
, evalExpressionWithReturn
, EvalConfig(..)
, defaultEvalConfig
) where
import XMonad.Core
import XMonad.Util.Run
import Language.Haskell.Interpreter
import Data.List
-- $usage
-- This module provides functions to evaluate haskell expressions at runtime
-- To use it, bind a key to evalExpression, for example in combination with a prompt:
--
-- > import XMonad
-- > import XMonad.Actions.Eval
-- > import XMonad.Prompt.Input
-- > ..
-- > , ((modMask,xK_t), inputPrompt defaultXPConfig "Eval" >>= flip whenJust (evalExpression defaultEvalConfig))
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- $documentation
-- In here due to the apparent lack of a replace function in the standard library.
-- (Used for correctly displaying newlines in error messages)
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace lst@(x:xs) sub repl | sub `isPrefixOf` lst = repl ++ replace (drop (length sub) lst) sub repl
| otherwise = x:(replace xs sub repl)
replace _ _ _ = []
-- | Configuration structure
data EvalConfig = EvalConfig { handleError :: InterpreterError -> X String
-- ^ Function to handle errors
, imports :: [(ModuleName,Maybe String)]
-- ^ Modules to import for interpreting the expression.
-- The pair consists of the module name and an optional
-- qualification of the imported module.
, modules :: [String]
-- ^ Other source files that should be loaded
-- The definitions of these modules will be visible
-- regardless of whether they are exported.
}
-- | Defaults for evaluating expressions.
defaultEvalConfig :: EvalConfig
defaultEvalConfig = EvalConfig { handleError = handleErrorDefault
, imports = [("Prelude",Nothing),("XMonad",Nothing),
("XMonad.StackSet",Just "W"),("XMonad.Core",Nothing)]
, modules = []
}
-- | Default way to handle(in this case: display) an error during interpretation of an expression.
handleErrorDefault :: InterpreterError -> X String
handleErrorDefault err = io (safeSpawn "/usr/bin/xmessage" [replace (show err) "\\n" "\n"]) >>
return "Error"
-- | Returns an Interpreter action that loads the desired modules and interprets the expression.
interpret' :: EvalConfig -> String -> Interpreter (X String)
interpret' conf s = do
loadModules $ modules conf
setTopLevelModules =<< getLoadedModules
setImportsQ $ imports conf
interpret ("show `fmap` ("++s++")") (return "")
-- | Evaluates a given expression whose result type has to be an instance of Show
evalExpressionWithReturn :: EvalConfig -> String -> X String
evalExpressionWithReturn conf s = io (runInterpreter $ interpret' conf s) >>=
either (handleError conf) id
-- | Evaluates a given expression, but discard the returned value. Provided for
-- more convenient use in keybindings
evalExpression :: EvalConfig -> String -> X ()
evalExpression cnf = (>> return ()) . evalExpressionWithReturn cnf
| eb-gh-cr/XMonadContrib1 | XMonad/Actions/MyEval.hs | bsd-3-clause | 4,233 | 0 | 12 | 1,299 | 581 | 332 | 249 | 35 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Web.Bugzilla.Search
(
-- * Search operators
(.==.)
, (./=.)
, (.<.)
, (.<=.)
, (.>.)
, (.>=.)
, (.=~.)
, (./=~.)
, equalsAny
, contains
, containsCase
, containsAny
, containsAll
, changedBefore
, changedAfter
, changedFrom
, changedTo
, changedBy
, contentMatches
, isEmpty
, (.&&.)
, (.||.)
, not'
-- * Search expressions
, Field (..)
, SearchExpression
) where
import qualified Data.Text as T
import Data.Time.Clock (UTCTime(..))
import Web.Bugzilla.Internal.Search
import Web.Bugzilla.Internal.Types
(.==.) :: FieldType a => Field a -> a -> SearchExpression
(.==.) = (Term .) . BinaryOp "equals"
infix 4 .==.
(./=.) :: FieldType a => Field a -> a -> SearchExpression
(./=.) = (Term .) . BinaryOp "notequals"
infix 4 ./=.
(.<.) :: FieldType a => Field a -> a -> SearchExpression
(.<.) = (Term .) . BinaryOp "lessthan"
infix 4 .<.
(.<=.) :: FieldType a => Field a -> a -> SearchExpression
(.<=.) = (Term .) . BinaryOp "lessthaneq"
infix 4 .<=.
(.>.) :: FieldType a => Field a -> a -> SearchExpression
(.>.) = (Term .) . BinaryOp "greaterthan"
infix 4 .>.
(.>=.) :: FieldType a => Field a -> a -> SearchExpression
(.>=.) = (Term .) . BinaryOp "greaterthaneq"
infix 4 .>=.
(.=~.) :: FieldType a => Field a -> a -> SearchExpression
(.=~.) = (Term .) . BinaryOp "regexp"
(./=~.) :: FieldType a => Field a -> a -> SearchExpression
(./=~.) = (Term .) . BinaryOp "notregexp"
equalsAny :: FieldType a => Field a -> [a] -> SearchExpression
equalsAny = (Term .) . BinaryOp "anyexact"
contains :: Field T.Text -> T.Text -> SearchExpression
contains = (Term .) . BinaryOp "substring"
containsCase :: Field T.Text -> T.Text -> SearchExpression
containsCase = (Term .) . BinaryOp "casesubstring"
containsAny :: Field T.Text -> [T.Text] -> SearchExpression
containsAny = (Term .) . BinaryOp "anywordssubstr"
containsAll :: Field T.Text -> [T.Text] -> SearchExpression
containsAll = (Term .) . BinaryOp "allwordssubstr"
changedBefore :: FieldType a => Field a -> UTCTime -> SearchExpression
changedBefore = (Term .) . BinaryOp "changedbefore"
changedAfter :: FieldType a => Field a -> UTCTime -> SearchExpression
changedAfter = (Term .) . BinaryOp "changedafter"
changedFrom :: FieldType a => Field a -> a -> SearchExpression
changedFrom = (Term .) . BinaryOp "changedfrom"
changedTo :: FieldType a => Field a -> a -> SearchExpression
changedTo = (Term .) . BinaryOp "changedto"
changedBy :: FieldType a => Field a -> UserEmail -> SearchExpression
changedBy = (Term .) . BinaryOp "changedby"
contentMatches :: T.Text -> SearchExpression
contentMatches = Term . BinaryOp "matches" ContentField
isEmpty :: FieldType a => Field a -> SearchExpression
isEmpty = Term . UnaryOp "isempty"
(.&&.) :: SearchExpression -> SearchExpression -> SearchExpression
(.&&.) a (And as) = And (a:as)
(.&&.) a b = And [a, b]
infixr 3 .&&.
(.||.) :: SearchExpression -> SearchExpression -> SearchExpression
(.||.) a (Or as) = Or (a:as)
(.||.) a b = Or [a, b]
infixr 2 .||.
not' :: SearchExpression -> SearchExpression
not' (Not a) = a
not' a = Not a
| sethfowler/hsbugzilla | src/Web/Bugzilla/Search.hs | bsd-3-clause | 3,132 | 0 | 8 | 556 | 1,138 | 644 | 494 | 90 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveGeneric, RankNTypes #-}
module MinIR.OrderedIndex ( OrderedIndex
, fromTerms
, termsScore
) where
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Vector as V
import Data.Hashable
import Control.Lens
import Data.List (tails)
import Data.Foldable.Strict
import Data.Monoid
import Data.Binary
import GHC.Generics (Generic)
import MinIR.Types
import MinIR.TermIndex (Score)
import MinIR.FreqMap (fFreqs, fTotal, FreqMap)
import MinIR.CorpusStats
import qualified MinIR.FreqMap as FM
ngrams :: Int -> [a] -> [[a]]
ngrams n = filter (\a->length a == 2) . map (take n) . tails
instance Hashable a => Hashable (V.Vector a) where
hashWithSalt salt = hashWithSalt salt . V.toList
instance (Hashable k, Eq k, Binary k, Binary v) => Binary (HashMap k v) where
get = HM.fromList `fmap` get
put = put . HM.toList
instance (Binary v) => Binary (V.Vector v) where
get = V.fromList `fmap` get
put = put . V.toList
newtype OrderedIndex doc term
= OIdx { _oFreq :: HashMap (V.Vector term) (FreqMap doc) }
deriving (Show, Generic)
makeLenses ''OrderedIndex
instance (Hashable term, Eq term, Binary doc, Binary term)
=> Binary (OrderedIndex doc term)
instance (Hashable term, Eq term, Hashable doc, Eq doc, Ord doc)
=> Monoid (OrderedIndex doc term) where
mempty = OIdx HM.empty
OIdx a `mappend` OIdx b = OIdx (HM.unionWith mappend a b)
{-# INLINE fromTerms #-}
fromTerms :: (Hashable doc, Hashable term, Eq term, Ord doc)
=> Int -> doc -> [term] -> OrderedIndex doc term
fromTerms n doc terms = foldMap' (fromNGram doc . V.fromList) $ ngrams n terms
{-# INLINE fromNGram #-}
fromNGram :: (Hashable doc, Hashable term, Ord doc)
=> doc -> V.Vector term -> OrderedIndex doc term
fromNGram doc ngram = OIdx (HM.singleton ngram $ FM.singleton doc 1)
firsts :: V.Vector a -> [V.Vector a]
firsts xs | V.length xs < 2 = [xs]
| otherwise = map (\n->V.take n xs) [2..V.length xs]
termsScore :: (Ord doc, Hashable term, Eq term)
=> Int -> Double -> CorpusStats doc term -> OrderedIndex doc term
-> [term] -> M.Map doc Score
termsScore n alphaD stats oidx terms =
let ngrams' = map V.fromList $ ngrams n terms
in foldl' (M.unionWith (+)) mempty $ do
ngram <- ngrams'
doc <- oidx ^. oFreq . at ngram . def mempty . fFreqs . to M.keys
let score = nGramDocScore alphaD stats oidx ngram doc
return $ M.singleton doc score
def :: a -> Iso' (Maybe a) a
def a = iso (maybe a id) Just
nGramDocScore :: (Ord doc, Hashable term, Eq term)
=> Double -> CorpusStats doc term -> OrderedIndex doc term
-> V.Vector term -> doc -> Score
nGramDocScore alphaD stats oidx ngram doc =
(1 - ad) * realToFrac tf / d + ad * cf / c
where cf = oidx ^. oFreq . at ngram . def mempty . fTotal . to realToFrac
tf = oidx ^. oFreq . at ngram . def mempty . fFreqs . at doc . non 0 . to realToFrac
d = stats ^. cDocs . at doc . non 0 . to realToFrac
c = stats ^. cTotalTerms . to realToFrac
ad = realToFrac alphaD
| bgamari/minir | MinIR/OrderedIndex.hs | bsd-3-clause | 3,422 | 0 | 15 | 915 | 1,316 | 679 | 637 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Web.Tumblr.Types where
import Control.Applicative (empty)
import Data.Aeson
import Data.Time (UTCTime)
import Data.Time.Format (parseTimeM, defaultTimeLocale)
import Data.Time.LocalTime (zonedTimeToUTC)
import Data.Aeson.Casing ( aesonPrefix, snakeCase )
import GHC.Generics ( Generic )
-- for reference, visit http://www.tumblr.com/docs/en/api/v2
data BlogInfo = BlogInfo
{ blogInfoTitle :: String,
blogInfoPosts :: Int,
blogInfoName :: String,
blogInfoURL :: Maybe String,
blogInfoUpdated :: Int, -- seconds since epoch
blogInfoDescription :: String,
blogInfoAsk :: Bool,
blogInfoAskAnon :: Bool,
blogInfoLikes :: Int
}
deriving (Show, Eq)
instance FromJSON BlogInfo where
parseJSON (Object w) =
(w .: "blog") >>= \v ->
BlogInfo
<$> v .: "title"
<*> v .: "posts"
<*> v .: "name"
<*> v .: "url"
<*> v .: "updated"
<*> v .: "description"
<*> v .: "ask"
<*> v .: "ask_anon"
<*> v .: "likes"
parseJSON _ = empty
newtype Avatar = Avatar {avatarURL :: String}
deriving (Show, Eq)
instance FromJSON Avatar where
parseJSON (Object v) = Avatar <$> v .: "avatar_url"
parseJSON _ = empty
data Likes = Likes
{ likedPosts :: [Post],
likedCount :: Int
}
deriving (Show, Generic, Eq)
instance FromJSON Likes where
parseJSON = genericParseJSON $ aesonPrefix snakeCase
newtype Followers = Followers {followers :: [User]}
deriving (Show, Eq)
instance FromJSON Followers where
parseJSON (Object v) = Followers <$> v .: "users"
parseJSON _ = empty
data User = User
{ userName :: String,
userURL :: String,
userUpdated :: Int
}
deriving (Show, Eq)
instance FromJSON User where
parseJSON (Object v) =
User
<$> v .: "name"
<*> v .: "url"
<*> v .: "updated"
parseJSON _ = empty
data Posts = Posts {postsBlog :: BlogInfo, posts :: [Post]} deriving (Show, Eq)
instance FromJSON Posts where
parseJSON o@(Object v) =
Posts
<$> parseJSON o
<*> v .: "posts"
parseJSON _ = empty
newtype JustPosts = JustPosts {justPosts :: [Post]}
deriving (Show, Eq)
instance FromJSON JustPosts where
parseJSON (Object v) =
JustPosts
<$> v .: "posts"
parseJSON _ = empty
data PostState = Published | Queued | Draft | Private | Unapproved deriving (Show, Eq)
instance FromJSON PostState where
parseJSON (String "published") = pure Published
parseJSON (String "queued") = pure Queued
parseJSON (String "draft") = pure Draft
parseJSON (String "private") = pure Private
parseJSON (String "unapproved") = pure Unapproved
parseJSON _ = empty
data PostFormat = Html | Markdown deriving (Show, Eq)
instance FromJSON PostFormat where
parseJSON (String "html") = pure Html
parseJSON (String "markdown") = pure Markdown
parseJSON _ = empty
data PhotoInfo = PhotoInfo {sizeWidth :: Int, sizeHeight :: Int, photoURL :: String} deriving (Show, Eq)
newtype Photo = Photo {originalSize :: PhotoInfo}
deriving (Show, Eq)
data Dialogue = Dialogue {dialogueSpeaker :: String, dialogueSpeakerLabel :: String, dialoguePhrase :: String} deriving (Show, Eq)
data VideoPlayer = VideoPlayer {videoPlayerWidth :: Int, videoPlayerEmbedCode :: String} deriving (Show, Eq)
data PostData
= TextPost {textTitle :: String, textBody :: String}
| PhotoPost {photoPostPhotos :: [Photo], photoPostCaption :: String}
| QuotePost {quoteText :: String, quoteSource :: String}
| LinkPost {linkTitle :: String, linkURL :: String, linkDescription :: String}
| ChatPost {chatTitle :: Maybe String, chatBody :: String, chatDialogue :: [Dialogue]}
| AudioPost
{ audioCaption :: String,
audioPlayer :: String,
audioPlays :: Int,
audioAlbumArt :: Maybe String,
audioArtist :: Maybe String,
audioAlbum :: Maybe String,
audioTrackName :: Maybe String,
audioTrackNumber :: Maybe Int,
audioYear :: Maybe Int
}
| VideoPost {videoCaption :: String, videoPlayer :: [VideoPlayer]}
| AnswerPost {askingName :: String, askingURL :: String, answerQuestion :: String, answerAnswer :: String}
deriving (Show, Eq)
instance FromJSON PhotoInfo where
parseJSON (Object v) =
PhotoInfo
<$> v .: "width"
<*> v .: "height"
<*> v .: "url"
parseJSON _ = empty
instance FromJSON Photo where
parseJSON (Object v) =
Photo
<$> v .: "original_size" -- <*>
-- v .: "alt_sizes" -- TODO
parseJSON _ = empty
instance FromJSON Dialogue where
parseJSON (Object v) =
Dialogue
<$> v .: "name"
<*> v .: "label"
<*> v .: "phrase"
parseJSON _ = empty
instance FromJSON VideoPlayer where
parseJSON (Object v) =
VideoPlayer
<$> v .: "width"
<*> v .: "embed_code"
parseJSON _ = empty
data Post = Post
{ postBlogName :: String,
postId :: Int,
postURL :: String,
postDate :: UTCTime,
postTime :: Int,
postState :: PostState,
postFormat :: PostFormat,
postReblogKey :: String,
postTags :: [String],
noteCount :: Int,
postBookmarklet :: Bool,
postMobile :: Bool,
postSourceURL :: Maybe String,
postSourceTitle :: Maybe String,
postLiked :: Bool,
postTypeSpecificData :: PostData
}
deriving (Show, Eq)
instance FromJSON Post where
parseJSON (Object v) =
Post
<$> v .: "blog_name"
<*> v .: "id"
<*> v .: "post_url"
<*> ((v .: "date") >>= parseTumblrTime)
<*> v .: "timestamp"
<*> v .: "state"
<*> v .: "format"
<*> v .: "reblog_key"
<*> v .: "tags"
<*> v .:? "note_count" .!= 0
<*> v .:? "bookmarklet" .!= False
<*> v .:? "mobile" .!= False
<*> v .:? "source_title"
<*> v .:? "source_url"
<*> v .:? "liked" .!= False
<*> ((v .: "type") >>= parseJSONTypeSpecific)
where
parseJSONTypeSpecific ("text" :: String) =
TextPost
<$> v .: "title"
<*> v .: "body"
parseJSONTypeSpecific "photo" =
PhotoPost
<$> v .: "photos"
<*> v .: "caption"
parseJSONTypeSpecific "quote" =
QuotePost
<$> v .: "text"
<*> v .: "source"
parseJSONTypeSpecific "link" =
LinkPost
<$> v .: "title"
<*> v .: "url"
<*> v .: "description"
parseJSONTypeSpecific "chat" =
ChatPost
<$> v .: "title"
<*> v .: "body"
<*> v .: "dialogue"
parseJSONTypeSpecific "audio" =
AudioPost
<$> v .: "caption"
<*> v .: "player"
<*> v .: "plays"
<*> v .:? "album_art"
<*> v .:? "artist"
<*> v .:? "album"
<*> v .:? "track_name"
<*> v .:? "track_number"
<*> v .:? "year"
parseJSONTypeSpecific "video" =
VideoPost
<$> v .: "caption"
<*> v .: "player"
parseJSONTypeSpecific "answer" =
AnswerPost
<$> v .: "asking_name"
<*> v .: "asking_url"
<*> v .: "question"
<*> v .: "answer"
parseJSONTypeSpecific _ = fail "Invalid post type."
parseTumblrTime t = case parseTimeM True defaultTimeLocale "%F %X %Z" t of
Just t' -> pure (zonedTimeToUTC t')
Nothing -> fail "Could not parse date"
parseJSON _ = empty
| Taneb/humblr | src/Web/Tumblr/Types.hs | bsd-3-clause | 7,462 | 0 | 39 | 2,039 | 2,149 | 1,181 | 968 | 225 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Commands (
Command(..)
, commands
) where
import Data.Aeson
import qualified Data.Text as T
import qualified Data.Map as M
import HQStatus (getHQStatusString)
data Command = Command
{ help :: T.Text
, reply :: [T.Text] -> IO T.Text
, inGroupChat :: Bool
, showInInfo :: Bool
}
info :: [T.Text] -> IO T.Text
info _ = do
let about = "I am λ-Bot - written in exceptionally bad haskell"
return $
T.unlines $ about : [infoMsg cname h i s | (cname, Command h _ i s) <- M.toList commands, s ]
where
infoMsg n h i s = T.concat [n, ": ", h, if not i then " -- in private chat only" else ""]
commands :: M.Map T.Text Command
commands = M.fromList
[ ("ping", Command "Answers with pong" (\_ -> return "pong") True True)
, ("calc", Command "Simple calculator -- not implented (yet)" (\_ -> return "Not implemented") False True)
, ("status", Command "Shows GCHQ status" (const getHQStatusString) True True)
, ("info", Command "" info True False)
]
| astro/l-bot | src/Commands.hs | bsd-3-clause | 1,042 | 0 | 12 | 238 | 360 | 200 | 160 | 25 | 2 |
-- Advent of Code
---- Day 25: Let It Snow
module AOC2015.Day25 where
import Math.NumberTheory.Powers
{-
Right-to-left binary method
https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
-}
coord :: Int -> Int -> Int
coord n m = div (k*(k+1)) 2 + m
where
k = n + m
answers :: IO ()
answers = do
putStrLn "-- Advent of Code 2015, Day 25 --"
-- n and m are the input here
let part1 = f 3010 3019
where
f n m =
mod (powerMod 252533 c 33554393 * 20151125) 33554393
where
c = coord (n-1) (m-1)
putStrLn $ "Part One: " ++ show part1
| bitrauser/aoc | src/AOC2015/Day25.hs | bsd-3-clause | 629 | 0 | 16 | 175 | 179 | 93 | 86 | 13 | 1 |
module Web.Dash.Fetch (
fetch
, fetch'
) where
import Data.Maybe
import Network.URL
import Network.Curl
import Text.JSON
type PeriodOptions = [(String, String)]
-- | @fetch'@ fetches the data for the given API Token, @token@,
-- and metric name, @metric@, in the time window, @opts@
fetch' :: String -> String -> PeriodOptions -> IO JSValue
fetch' token metric opts = do
contents <- readContentsURL $ urlString token metric opts
return $ deserialize contents
-- | @fetch@ fetches the data for the given API Token, @token@,
-- and metric name, @metric@, in the default time window
fetch :: String -> String -> IO JSValue
fetch token metric = fetch' token metric []
-- | @baseURL@ is the base URL for the given API Token, @token@
baseURL :: String -> Maybe URL
baseURL token = importURL $ "https://dash.fiveruns.com/apps/" ++ token ++ "/data-v1.js"
-- | @urlString@ builds the full API URL from the @token@, @metric@,
-- and given time window, @opts@
urlString :: String -> String -> PeriodOptions -> String
urlString token metric opts = case baseURL token of
Just url -> exportURL $ foldl (add_param) url (("metric_name", metric):opts)
Nothing -> error "Could not generate URL"
-- | @deserialize@ parses the JSON input, @input@, into a JSValue
deserialize :: String -> JSValue
deserialize input = case decodeStrict input of
Ok value -> value
Error e -> error $ "Could not parse result: " ++ e
-- | @readContentsURL@ reads the content from the given URL, @u@.
-- Via a standard @GET@.
readContentsURL :: URLString -> IO String
readContentsURL u = do
let opts = [ CurlFollowLocation True ]
(_,xs) <- curlGetString u opts
return xs | bruce/dash-haskell | Web/Dash/Fetch.hs | bsd-3-clause | 1,748 | 0 | 12 | 390 | 377 | 196 | 181 | 29 | 2 |
module TestDirScanner (tests) where
import Definitions
import DirScanner
import Fixtures
import System.FilePath
import Test.Hspec.HUnit()
import Test.Hspec.Monadic
import Test.HUnit
tests = describe "dir scanner:" $ do
it "finds html files recursively" $ withTmpDir $ \tmpDir -> do
createEmptyFile $ tmpDir </> "a.html"
createEmptyFile $ tmpDir </> "a.css"
createEmptyFile $ tmpDir </> "sub" </> "b.html"
createEmptyFile $ tmpDir </> "sub" </> "b.css"
folded <- findHtmlFiles tmpDir
folded @?= [ tmpDir </> "a.html"
, tmpDir </> "sub" </> "b.html"
]
it "scans html files in directory" $ do
defTree <- scanHtmlDocs "sample-docs/android" (constScanner (Definition "" ""))
defTree @?= [Definition "" "", Definition "" ""]
constScanner :: DefTree -> FileScanner
constScanner d _ _ = [d]
| rickardlindberg/alldoc | tests/TestDirScanner.hs | bsd-3-clause | 898 | 0 | 16 | 227 | 244 | 124 | 120 | 22 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
-- |
-- Module : Simulation.Aivika.Experiment.Chart.DeviationChartView
-- Copyright : Copyright (c) 2012-2017, David Sorokin <[email protected]>
-- License : BSD3
-- Maintainer : David Sorokin <[email protected]>
-- Stability : experimental
-- Tested with: GHC 8.0.1
--
-- The module defines 'DeviationChartView' that plots the deviation chart using rule of 3-sigma.
--
module Simulation.Aivika.Experiment.Chart.DeviationChartView
(DeviationChartView(..),
defaultDeviationChartView) where
import Control.Monad
import Control.Monad.Trans
import Control.Concurrent.MVar
import Control.Lens
import qualified Data.Map as M
import Data.IORef
import Data.Maybe
import Data.Either
import Data.Monoid
import Data.Array
import Data.Array.IO.Safe
import Data.Default.Class
import System.IO
import System.FilePath
import Graphics.Rendering.Chart
import Simulation.Aivika
import Simulation.Aivika.Experiment
import Simulation.Aivika.Experiment.Base
import Simulation.Aivika.Experiment.Concurrent.MVar
import Simulation.Aivika.Experiment.Chart.Types
import Simulation.Aivika.Experiment.Chart.Utils (colourisePlotLines, colourisePlotFillBetween)
-- | Defines the 'View' that plots the deviation chart in time points by the specified grid.
data DeviationChartView =
DeviationChartView { deviationChartTitle :: String,
-- ^ This is a title used in HTML.
deviationChartDescription :: String,
-- ^ This is a description used in HTML.
deviationChartWidth :: Int,
-- ^ The width of the chart.
deviationChartHeight :: Int,
-- ^ The height of the chart.
deviationChartGridSize :: Int,
-- ^ The size of the grid, where the series data are collected.
deviationChartFileName :: ExperimentFilePath,
-- ^ It defines the file name with optional extension for each image to be saved.
-- It may include special variable @$TITLE@.
--
-- An example is
--
-- @
-- deviationChartFileName = UniqueFilePath \"$TITLE\"
-- @
deviationChartTransform :: ResultTransform,
-- ^ The transform applied to the results before receiving series.
deviationChartLeftYSeries :: ResultTransform,
-- ^ It defines the series to be plotted basing on the left Y axis.
deviationChartRightYSeries :: ResultTransform,
-- ^ It defines the series to be plotted basing on the right Y axis.
deviationChartPlotTitle :: String,
-- ^ This is a title used in the chart.
-- It may include special variable @$TITLE@.
--
-- An example is
--
-- @
-- deviationChartPlotTitle = \"$TITLE\"
-- @
deviationChartPlotLines :: [PlotLines Double Double ->
PlotLines Double Double],
-- ^ Probably, an infinite sequence of plot
-- transformations based on which the plot
-- is constructed for each series. Generally,
-- it may not coincide with a sequence of
-- labels as one label may denote a whole list
-- or an array of data providers.
--
-- Here you can define a colour or style of
-- the plot lines.
deviationChartPlotFillBetween :: [PlotFillBetween Double Double ->
PlotFillBetween Double Double],
-- ^ Corresponds exactly to 'deviationChartPlotLines'
-- but used for plotting the deviation areas
-- by the rule of 3-sigma, while the former
-- is used for plotting the trends of the
-- random processes.
deviationChartBottomAxis :: LayoutAxis Double ->
LayoutAxis Double,
-- ^ A transformation of the bottom axis,
-- after title @time@ is added.
deviationChartLayout :: LayoutLR Double Double Double ->
LayoutLR Double Double Double
-- ^ A transformation of the plot layout,
-- where you can redefine the axes, for example.
}
-- | The default deviation chart view.
defaultDeviationChartView :: DeviationChartView
defaultDeviationChartView =
DeviationChartView { deviationChartTitle = "Deviation Chart",
deviationChartDescription = "It shows the Deviation chart by rule 3-sigma.",
deviationChartWidth = 640,
deviationChartHeight = 480,
deviationChartGridSize = 2 * 640,
deviationChartFileName = UniqueFilePath "DeviationChart",
deviationChartTransform = id,
deviationChartLeftYSeries = mempty,
deviationChartRightYSeries = mempty,
deviationChartPlotTitle = "$TITLE",
deviationChartPlotLines = colourisePlotLines,
deviationChartPlotFillBetween = colourisePlotFillBetween,
deviationChartBottomAxis = id,
deviationChartLayout = id }
instance ChartRendering r => ExperimentView DeviationChartView (WebPageRenderer r) where
outputView v =
let reporter exp (WebPageRenderer renderer _) dir =
do st <- newDeviationChart v exp renderer dir
let context =
WebPageContext $
WebPageWriter { reporterWriteTOCHtml = deviationChartTOCHtml st,
reporterWriteHtml = deviationChartHtml st }
return ExperimentReporter { reporterInitialise = return (),
reporterFinalise = finaliseDeviationChart st,
reporterSimulate = simulateDeviationChart st,
reporterContext = context }
in ExperimentGenerator { generateReporter = reporter }
instance ChartRendering r => ExperimentView DeviationChartView (FileRenderer r) where
outputView v =
let reporter exp (FileRenderer renderer _) dir =
do st <- newDeviationChart v exp renderer dir
return ExperimentReporter { reporterInitialise = return (),
reporterFinalise = finaliseDeviationChart st,
reporterSimulate = simulateDeviationChart st,
reporterContext = FileContext }
in ExperimentGenerator { generateReporter = reporter }
-- | The state of the view.
data DeviationChartViewState r =
DeviationChartViewState { deviationChartView :: DeviationChartView,
deviationChartExperiment :: Experiment,
deviationChartRenderer :: r,
deviationChartDir :: FilePath,
deviationChartFile :: IORef (Maybe FilePath),
deviationChartResults :: MVar (Maybe DeviationChartResults) }
-- | The deviation chart item.
data DeviationChartResults =
DeviationChartResults { deviationChartTimes :: IOArray Int Double,
deviationChartNames :: [Either String String],
deviationChartStats :: [MVar (IOArray Int (SamplingStats Double))] }
-- | Create a new state of the view.
newDeviationChart :: DeviationChartView -> Experiment -> r -> FilePath -> ExperimentWriter (DeviationChartViewState r)
newDeviationChart view exp renderer dir =
liftIO $
do f <- newIORef Nothing
r <- newMVar Nothing
return DeviationChartViewState { deviationChartView = view,
deviationChartExperiment = exp,
deviationChartRenderer = renderer,
deviationChartDir = dir,
deviationChartFile = f,
deviationChartResults = r }
-- | Create new chart results.
newDeviationChartResults :: DeviationChartViewState r -> [Either String String] -> IO DeviationChartResults
newDeviationChartResults st names =
do let exp = deviationChartExperiment st
view = deviationChartView st
size = deviationChartGridSize view
specs = experimentSpecs exp
grid = timeGrid specs size
bnds = (0, 1 + length grid)
times <- liftIO $ newListArray bnds $ map snd grid
stats <- forM names $ \_ ->
liftIO $ newArray bnds emptySamplingStats >>= newMVar
return DeviationChartResults { deviationChartTimes = times,
deviationChartNames = names,
deviationChartStats = stats }
-- | Require to return unique chart results associated with the specified state.
requireDeviationChartResults :: DeviationChartViewState r -> [Either String String] -> IO DeviationChartResults
requireDeviationChartResults st names =
maybePutMVar (deviationChartResults st)
(newDeviationChartResults st names) $ \results ->
if (names /= deviationChartNames results)
then error "Series with different names are returned for different runs: requireDeviationChartResults"
else return results
-- | Simulate the specified series.
simulateDeviationChart :: DeviationChartViewState r -> ExperimentData -> Composite ()
simulateDeviationChart st expdata =
do let view = deviationChartView st
loc = localisePathResultTitle $
experimentLocalisation $
deviationChartExperiment st
rs1 = deviationChartLeftYSeries view $
deviationChartTransform view $
experimentResults expdata
rs2 = deviationChartRightYSeries view $
deviationChartTransform view $
experimentResults expdata
exts1 = resultsToDoubleStatsEitherValues rs1
exts2 = resultsToDoubleStatsEitherValues rs2
exts = exts1 ++ exts2
names1 = map (loc . resultValueIdPath) exts1
names2 = map (loc . resultValueIdPath) exts2
names = map Left names1 ++ map Right names2
signal <- liftEvent $
newSignalInTimeGrid $
deviationChartGridSize view
hs <- forM exts $ \ext ->
newSignalHistory $
flip mapSignalM signal $ \i ->
resultValueData ext
disposableComposite $
DisposableEvent $
do results <- liftIO $ requireDeviationChartResults st names
let stats = deviationChartStats results
forM_ (zip hs stats) $ \(h, stats') ->
do (ts, xs) <- readSignalHistory h
let (lo, hi) = bounds ts
liftIO $
withMVar stats' $ \stats'' ->
forM_ [lo..hi] $ \i ->
do let x = xs ! i
y <- readArray stats'' i
let y' = combineSamplingStatsEither x y
y' `seq` writeArray stats'' i y'
-- | Plot the deviation chart after the simulation is complete.
finaliseDeviationChart :: ChartRendering r => DeviationChartViewState r -> ExperimentWriter ()
finaliseDeviationChart st =
do let view = deviationChartView st
title = deviationChartTitle view
plotTitle = deviationChartPlotTitle view
plotTitle' =
replace "$TITLE" title
plotTitle
width = deviationChartWidth view
height = deviationChartHeight view
plotLines = deviationChartPlotLines view
plotFillBetween = deviationChartPlotFillBetween view
plotBottomAxis = deviationChartBottomAxis view
plotLayout = deviationChartLayout view
renderer = deviationChartRenderer st
file <- resolveFilePath (deviationChartDir st) $
mapFilePath (flip replaceExtension $ renderableChartExtension renderer) $
expandFilePath (deviationChartFileName view) $
M.fromList [("$TITLE", title)]
results <- liftIO $ readMVar $ deviationChartResults st
case results of
Nothing -> return ()
Just results ->
liftIO $
do let times = deviationChartTimes results
names = deviationChartNames results
stats = deviationChartStats results
ps1 <- forM (zip3 names stats plotLines) $ \(name, stats', plotLines) ->
do stats'' <- readMVar stats'
xs <- getAssocs stats''
zs <- forM xs $ \(i, stats) ->
do t <- readArray times i
return (t, samplingStatsMean stats)
let p = toPlot $
plotLines $
plot_lines_values .~ filterPlotLinesValues zs $
plot_lines_title .~ either id id name $
def
case name of
Left _ -> return $ Left p
Right _ -> return $ Right p
ps2 <- forM (zip3 names stats plotFillBetween) $ \(name, stats', plotFillBetween) ->
do stats'' <- readMVar stats'
xs <- getAssocs stats''
zs <- forM xs $ \(i, stats) ->
do t <- readArray times i
let mu = samplingStatsMean stats
sigma = samplingStatsDeviation stats
return (t, (mu - 3 * sigma, mu + 3 * sigma))
let p = toPlot $
plotFillBetween $
plot_fillbetween_values .~ filterPlotFillBetweenValues zs $
plot_fillbetween_title .~ either id id name $
def
case name of
Left _ -> return $ Left p
Right _ -> return $ Right p
let ps = join $ flip map (zip ps1 ps2) $ \(p1, p2) -> [p2, p1]
axis = plotBottomAxis $
laxis_title .~ "time" $
def
updateLeftAxis =
if null $ lefts ps
then layoutlr_left_axis_visibility .~ AxisVisibility False False False
else id
updateRightAxis =
if null $ rights ps
then layoutlr_right_axis_visibility .~ AxisVisibility False False False
else id
chart = plotLayout .
renderingLayoutLR renderer .
updateLeftAxis . updateRightAxis $
layoutlr_x_axis .~ axis $
layoutlr_title .~ plotTitle' $
layoutlr_plots .~ ps $
def
renderChart renderer (width, height) file (toRenderable chart)
when (experimentVerbose $ deviationChartExperiment st) $
putStr "Generated file " >> putStrLn file
writeIORef (deviationChartFile st) $ Just file
-- | Remove the NaN and inifity values.
filterPlotLinesValues :: [(Double, Double)] -> [[(Double, Double)]]
filterPlotLinesValues =
filter (not . null) .
divideBy (\(t, x) -> isNaN x || isInfinite x)
-- | Remove the NaN and inifity values.
filterPlotFillBetweenValues :: [(Double, (Double, Double))] -> [(Double, (Double, Double))]
filterPlotFillBetweenValues =
filter $ \(t, (x1, x2)) -> not $ isNaN x1 || isInfinite x1 || isNaN x2 || isInfinite x2
-- | Get the HTML code.
deviationChartHtml :: DeviationChartViewState r -> Int -> HtmlWriter ()
deviationChartHtml st index =
do header st index
file <- liftIO $ readIORef (deviationChartFile st)
case file of
Nothing -> return ()
Just f ->
writeHtmlParagraph $
writeHtmlImage (makeRelative (deviationChartDir st) f)
header :: DeviationChartViewState r -> Int -> HtmlWriter ()
header st index =
do writeHtmlHeader3WithId ("id" ++ show index) $
writeHtmlText (deviationChartTitle $ deviationChartView st)
let description = deviationChartDescription $ deviationChartView st
unless (null description) $
writeHtmlParagraph $
writeHtmlText description
-- | Get the TOC item.
deviationChartTOCHtml :: DeviationChartViewState r -> Int -> HtmlWriter ()
deviationChartTOCHtml st index =
writeHtmlListItem $
writeHtmlLink ("#id" ++ show index) $
writeHtmlText (deviationChartTitle $ deviationChartView st)
| dsorokin/aivika-experiment-chart | Simulation/Aivika/Experiment/Chart/DeviationChartView.hs | bsd-3-clause | 17,560 | 0 | 27 | 6,554 | 3,086 | 1,612 | 1,474 | 273 | 6 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
#endif
module Text.RE.TDFA.Text.Lazy
(
-- * Tutorial
-- $tutorial
-- * The Match Operators
(*=~)
, (?=~)
, (=~)
, (=~~)
-- * The Toolkit
-- $toolkit
, module Text.RE
-- * The 'RE' Type
-- $re
, module Text.RE.TDFA.RE
) where
import Prelude.Compat
import qualified Data.Text.Lazy as TL
import Data.Typeable
import Text.Regex.Base
import Text.RE
import Text.RE.Internal.AddCaptureNames
import Text.RE.TDFA.RE
import qualified Text.Regex.TDFA as TDFA
-- | find all matches in text
(*=~) :: TL.Text
-> RE
-> Matches TL.Text
(*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs
-- | find first match in text
(?=~) :: TL.Text
-> RE
-> Match TL.Text
(?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base polymorphic match operator
(=~) :: ( Typeable a
, RegexContext TDFA.Regex TL.Text a
, RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String
)
=> TL.Text
-> RE
-> a
(=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs
-- | the regex-base monadic, polymorphic match operator
(=~~) :: ( Monad m
, Functor m
, Typeable a
, RegexContext TDFA.Regex TL.Text a
, RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String
)
=> TL.Text
-> RE
-> m a
(=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs
instance IsRegex RE TL.Text where
matchOnce = flip (?=~)
matchMany = flip (*=~)
regexSource = reSource
-- $tutorial
-- We have a regex tutorial at <http://tutorial.regex.uk>. These API
-- docs are mainly for reference.
-- $toolkit
--
-- Beyond the above match operators and the regular expression type
-- below, "Text.RE" contains the toolkit for replacing captures,
-- specifying options, etc.
-- $re
--
-- "Text.RE.TDFA.RE" contains the toolkit specific to the 'RE' type,
-- the type generated by the gegex compiler.
| cdornan/idiot | Text/RE/TDFA/Text/Lazy.hs | bsd-3-clause | 2,471 | 0 | 8 | 659 | 486 | 289 | 197 | 50 | 1 |
module Arhelk.Russian.Lemma.Data.Substantive where
import Arhelk.Russian.Lemma.Data.Common
import Lens.Simple
import Data.Monoid
import TextShow
-- | Склонение. Describes declension of substantives
data Declension =
FirstDeclension
| SecondDeclension
| ThirdDeclension
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow Declension where
showb v = case v of
FirstDeclension -> "I скл."
SecondDeclension -> "II скл."
ThirdDeclension -> "III скл."
-- | Падеж. Grammatical case.
data GrammarCase =
Nominativus -- ^ Иминительный
| Genitivus -- ^ Родительный
| Dativus -- ^ Дательный
| Accusativus -- ^ Винительный
| Ablativus -- ^ Творительный
| Praepositionalis -- ^ Предложный
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow GrammarCase where
showb v = case v of
Nominativus -> "им. падеж"
Genitivus -> "род. падеж"
Dativus -> "дат. падеж"
Accusativus -> "вин. падеж"
Ablativus -> "твор. падеж"
Praepositionalis -> "предл. падеж"
-- | Имя нарицательное или собственное
data Appellativity =
AppellativeNoun -- ^ Нарицательное
| ProperNoun -- ^ Собственное
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow Appellativity where
showb v = case v of
AppellativeNoun -> "нариц."
ProperNoun -> "собств."
-- | Одушевленность
data Animacy =
AnimateNoun -- ^ Одушевленное
| InanimateNoun -- ^ Неодушевленное
deriving (Eq, Ord, Enum, Show, Bounded)
instance TextShow Animacy where
showb v = case v of
AnimateNoun -> "одушвл."
InanimateNoun -> "неодушвл."
-- | Substantive morphological properties
data SubstantiveProperties = SubstantiveProperties {
_substAppellativity :: Maybe Appellativity
, _substAnimacy :: Maybe Animacy
, _substDeclension :: Maybe Declension
, _substGender :: Maybe GrammarGender
, _substQuantity :: Maybe GrammarQuantity
, _substCase :: Maybe GrammarCase
} deriving (Eq, Show)
$(makeLenses ''SubstantiveProperties)
instance Monoid SubstantiveProperties where
mempty = SubstantiveProperties {
_substAppellativity = Nothing
, _substAnimacy = Nothing
, _substDeclension = Nothing
, _substGender = Nothing
, _substQuantity = Nothing
, _substCase = Nothing
}
mappend a b = SubstantiveProperties {
_substAppellativity = getFirst $ First (_substAppellativity a) <> First (_substAppellativity b)
, _substAnimacy = getFirst $ First (_substAnimacy a) <> First (_substAnimacy b)
, _substDeclension = getFirst $ First (_substDeclension a) <> First (_substDeclension b)
, _substGender = getFirst $ First (_substGender a) <> First (_substGender b)
, _substQuantity = getFirst $ First (_substQuantity a) <> First (_substQuantity b)
, _substCase = getFirst $ First (_substCase a) <> First (_substCase b)
}
instance TextShow SubstantiveProperties where
showb SubstantiveProperties{..} = unwordsB [
maybe "" showb _substAppellativity
, maybe "" showb _substAnimacy
, maybe "" showb _substDeclension
, maybe "" showb _substGender
, maybe "" showb _substQuantity
, maybe "" showb _substCase
] | Teaspot-Studio/arhelk-russian | src/Arhelk/Russian/Lemma/Data/Substantive.hs | bsd-3-clause | 3,365 | 0 | 12 | 602 | 776 | 419 | 357 | -1 | -1 |
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <[email protected]>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
-- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Lambdalift(lambdalift) where
import Monad
import Common
import Kindle
import PP
lambdalift ds m = localStore (llModule ds m)
data Env = Env { decls :: Decls, -- global type declarations
thisSubst :: Map Name AType, --
thisVars :: [Name], -- variables reachable through "this"
locals :: ATEnv, -- non-global value names in scope
expansions :: Map Name ([Name],[Name]) -- non-global functions and their added type/term parameters
}
nullEnv = Env { decls = primDecls,
thisSubst = [],
thisVars = [],
locals = [],
expansions = []
}
addDecls ds env = env { decls = ds ++ decls env }
setThis vs xs env = env { thisSubst = vs `zip` map TThis [1..], thisVars = xs }
addLocals te env = env { locals = te ++ prune (locals env) (dom te) } -- prune so that shadowed variables don't
-- get lifted multiple times
addExpansions exps env = env { expansions = exps ++ expansions env }
findStructInstance env (Prim CLOS _) ts = (closBind ts, [])
findStructInstance env n ts = (subst s te, [ t | (v,t) <- s, v `elem` vs' ])
where Struct vs te l = if isTuple n then tupleDecl n else lookup' (decls env) n
s = vs `zip` ts
vs' = equants l
-- Convert a module
llModule dsi (Module m ns es ds bs) = do bs <- mapM (llBind env0) bs
s <- currentStore
return (Module m ns es (ds ++ declsOfStore s) (bs ++ bindsOfStore s))
where env0 = addDecls (ds ++ dsi) nullEnv
declsOfStore s = [ d | Left d <- s ]
bindsOfStore s = [ b | Right b <- s ]
-- Convert a binding
llBind env (x, Fun vs t te c) = do c <- llCmd (addLocals te env) c
return (x, Fun vs t te c)
llBind env (x, Val t e) = do e <- llExp env e
return (x, Val (mkT env t) e)
{- Lambda-lifting a set of recursive bindings:
\v -> letrec f r v x = ... r ... v ...
letrec f x = ... r ... v ... g r v y = ... f r v e ...
r = { a = ... g e ... } ==> in \v ->
g y = ... f e ... letrec r = { a = ... g r v e ... }
in f e in f r v e
-}
{- Closing a struct with function fields:
\v -> \v ->
{ f x = ... v ... { f x = ... this.v ...
w = ... v ... } ==> w = ... v ...
v = v }
-}
-- Convert a command
llCmd env (CBind r bs c) = do vals' <- mapM (llBind env') vals
funs' <- mapM (llBind (setThis [] [] env')) funs
store <- currentStore
let fs = dom funs' `intersect` [ f | Right (f,_) <- store ]
fs' <- mapM (newName . str) fs
let s = fs `zip` fs'
mapM_ liftFun (subst s funs')
c' <- llCmd env2 c
return (cBindR r (subst s vals') (subst s c'))
where (vals,funs) = partition isVal bs
free0 = evars funs
free1 = free0 ++ concat [ xs | (f,(_,xs)) <- expansions env, f `elem` free0 ]
fte = locals (if r then env1 else env) `restrict` free1
vs1 = concat [ vs | (f,(vs,_)) <- expansions env, f `elem` free0 ]
fvs = nub (typevars funs ++ typevars fte ++ vs1)
env1 = addLocals (mapSnd typeOf' vals) env
env2 = addExpansions (dom funs `zip` repeat (fvs, dom fte)) env1
env' = if r then env2 else env
liftFun (x, Fun vs t te c) = addToStore (Right (x, Fun (fvs++vs) t (fte++te) c))
llCmd env (CRet e) = liftM CRet (llExp env e)
llCmd env (CRun e c) = liftM2 CRun (llExp env e) (llCmd env c)
llCmd env (CUpd x e c) = liftM2 (CUpd x) (llExp env e) (llCmd env c)
llCmd env (CUpdS e x e' c) = do e <- llExp env e
liftM2 (CUpdS e x) (llExp env e') (llCmd env c)
llCmd env (CUpdA e i e' c) = liftM4 CUpdA (llExp env e) (llExp env i) (llExp env e') (llCmd env c)
llCmd env (CSwitch e alts) = liftM2 CSwitch (llExp env e) (mapM (llAlt env) alts)
llCmd env (CSeq c c') = liftM2 CSeq (llCmd env c) (llCmd env c')
llCmd env (CBreak) = return CBreak
llCmd env (CRaise e) = liftM CRaise (llExp env e)
llCmd env (CWhile e c c') = liftM3 CWhile (llExp env e) (llCmd env c) (llCmd env c')
llCmd env (CCont) = return CCont
-- Convert a switch alternative
llAlt env (ACon x vs te c) = liftM (ACon x vs (mkT env te)) (llCmd (addLocals te env) c)
llAlt env (ALit l c) = liftM (ALit l) (llCmd env c)
llAlt env (AWild c) = liftM AWild (llCmd env c)
-- Convert an expression
llExp env (ECall x ts es) = do es <- mapM (llExp env) es
case lookup x (expansions env) of
Just (vs,xs) -> return (ECall x (mkT env (map tVar vs ++ ts)) (map (mkEVar env) xs ++ es))
Nothing -> return (ECall x (mkT env ts) es)
llExp env ee@(ENew n ts0 bs)
| null fte && null fvs = liftM (ENew n ts) (mapM (llBind env) bs)
| otherwise = do n' <- getStructName (Struct tvs (te ++ mapSnd ValT fte) (Extends n ts tvs))
vals' <- mapM (llBind env) vals
funs' <- mapM (llBind (setThis tvs (dom fte) env)) funs
-- tr ("lift ENew: " ++ render (pr (TCon n ts)) ++ " fvs: " ++ show fvs ++ " new: " ++ show n')
return (ECast (TCon n ts) (ENew n' (ts'++map close' fvs) (vals' ++ funs' ++ map close fte)))
where ts = mkT env ts0
(vals,funs) = partition isVal bs
free0 = evars funs
free1 = free0 ++ concat [ xs | (f,(_,xs)) <- expansions env, f `elem` free0 ]
fte = locals env `restrict` free1
vs1 = concat [ vs | (f,(vs,_)) <- expansions env, f `elem` free0 ]
fvs = nub (typevars funs ++ typevars fte ++ vs1)
tvs = take (length ts') abcSupply ++ fvs
(te,ts') = findStructInstance env n ts
close (x,t) = (x, Val (mkT env t) (mkEVar env x))
close' v = mkT env (tVar v)
llExp env (EVar x) = return (mkEVar env x)
llExp env (EThis) = return (EThis)
llExp env (ELit l) = return (ELit l)
llExp env (ESel e l) = liftM (flip ESel l) (llExp env e)
llExp env (EEnter e f ts es) = do e <- llExp env e
liftM (EEnter e f (mkT env ts)) (mapM (llExp env) es)
llExp env (ECast t e) = liftM (ECast (mkT env t)) (llExp env e)
mkEVar env x = if x `elem` thisVars env then ESel EThis x else EVar x
mkT env t = subst (thisSubst env) t
getStructName str = do s <- currentStore
case findStruct str (declsOfStore s) of
Just n -> return n
Nothing -> do n <- newName typeSym
addToStore (Left (n, str))
return n
| mattias-lundell/timber-llvm | src/Lambdalift.hs | bsd-3-clause | 11,061 | 0 | 17 | 5,250 | 2,843 | 1,457 | 1,386 | 105 | 3 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE ConstraintKinds #-}
module Fragment.Annotation.Rules.Type.Infer.SyntaxDirected (
AnnotationInferTypeContext
, annotationInferTypeRules
) where
import Rules.Type.Infer.SyntaxDirected
import Fragment.Annotation.Ast.Term
import Fragment.Annotation.Rules.Type.Infer.Common
type AnnotationInferTypeContext e w s r m ki ty pt tm a = AsTmAnnotation ki ty pt tm
annotationInferTypeRules :: AnnotationInferTypeContext e w s r m ki ty pt tm a
=> InferTypeInput e w s r m m ki ty pt tm a
annotationInferTypeRules =
let
ah = AnnotationHelper expectType
in
inferTypeInput ah
| dalaing/type-systems | src/Fragment/Annotation/Rules/Type/Infer/SyntaxDirected.hs | bsd-3-clause | 777 | 0 | 9 | 150 | 143 | 86 | 57 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Find paths given the root directory of deployment.
module Paths
( RootDir
, incoming
, angelConf
, nginxConf
, postgresConf
) where
import Prelude ()
import Filesystem.Path.CurrentOS (FilePath, (</>))
type RootDir = FilePath
incoming :: RootDir -> FilePath
incoming = (</> "incoming")
angelConf :: RootDir -> FilePath
angelConf r = r </> "etc" </> "angel.conf"
nginxConf :: FilePath
nginxConf = "/etc/nginx/sites-enabled/yesod-deploy.conf"
postgresConf :: RootDir -> FilePath
postgresConf r = r </> "etc" </> "postgres.yaml"
| yesodweb/deploy | src/Paths.hs | bsd-3-clause | 595 | 0 | 6 | 110 | 129 | 78 | 51 | 18 | 1 |
{-# language TemplateHaskell, GADTs #-}
import Data.Function.Memoize
import Control.Monad (forM_, when)
import Test3Helper
-- NonstandardParams is defined by:
--
-- data NonstandardParams a b
-- = NonstandardParams (a -> Bool) b
--
-- This won’t compile because it needs addition typeclass constraints in
-- the instance context:
--
-- $(deriveMemoizable ''NonstandardParams)
instance (Eq a, Enum a, Bounded a, Memoizable b) => Memoizable (NonstandardParams a b) where
memoize = $(deriveMemoize ''NonstandardParams)
applyToLength :: NonstandardParams Bool Int -> Bool
applyToLength (NonstandardParams f z) = f (odd z)
cases = [ (NonstandardParams id 5, True)
, (NonstandardParams id 6, False)
, (NonstandardParams not 5, False)
, (NonstandardParams not 6, True)
]
main :: IO ()
main = do
let memoized = memoize applyToLength
forM_ cases $ \(input, expected) -> do
let actual = applyToLength input
when (actual /= expected) $
fail $ "Test failed: got " ++ show actual ++
" when " ++ show expected ++ " expected."
| tov/memoize | test/test3.hs | bsd-3-clause | 1,093 | 0 | 19 | 235 | 293 | 156 | 137 | 20 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
module HW06.HW06 where
-- Exercise 1 -----------------------------------------
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
fibs1 :: [Integer]
fibs1 = fib `map` [0..]
-- Exercise 2 -----------------------------------------
fibs2 :: [Integer]
fibs2 = 0 : 1 : zipWith (+) fibs2 (tail fibs2)
-- Exercise 3 -----------------------------------------
data Stream a = a `Cons` (Stream a)
streamToList :: Stream a -> [a]
streamToList (a `Cons` as) = a : streamToList as
instance Show a => Show (Stream a) where
show as = let asList = take 20 . streamToList $ as
in "Stream " ++ show asList
-- Exercise 4 -----------------------------------------
streamRepeat :: a -> Stream a
streamRepeat a = Cons a $ streamRepeat a
streamMap :: (a -> b) -> Stream a -> Stream b
streamMap f (a `Cons` as) = f a `Cons` streamMap f as
streamFromSeed :: (a -> a) -> a -> Stream a
streamFromSeed g a = a `Cons` streamFromSeed g (g a)
-- Exercise 5 -----------------------------------------
nats :: Stream Integer
nats = streamFromSeed (+1) 0
interleaveStreams :: Stream a -> Stream a -> Stream a
interleaveStreams (a `Cons` as) bs = a `Cons` interleaveStreams bs as
ruler :: Stream Integer
ruler = interleaveStreams zeros $ streamMap (+1) ruler
where
zeros = streamRepeat 0
-- Exercise 6 -----------------------------------------
x :: Stream Integer
x = Cons 0 $ Cons 1 $ streamRepeat 0
instance Num (Stream Integer) where
fromInteger n = Cons n $ streamRepeat 0
negate (a `Cons` as) = negate a `Cons` negate as
(a `Cons` as) + (b `Cons` bs) = (a + b) `Cons` (as + bs)
(a `Cons` as) * allB@(b `Cons` bs) = (a * b) `Cons` (streamMap (a*) bs + as * allB)
instance Fractional (Stream Integer) where
(a `Cons` as) / (b `Cons` bs) = q
where
q = (a `div` b) `Cons` streamMap (`div` b) (as - q * bs)
fibs3 :: Stream Integer
fibs3 = x / (1 - x - x * x)
-- Exercise 7 -----------------------------------------
newtype Matrix = Matrix (Integer, Integer, Integer, Integer)
instance Num Matrix where
(Matrix (x1, x2, x3, x4)) * (Matrix (y1, y2, y3, y4)) =
Matrix ( x1*y1 + x2*y3
, x1*y2 + x2*y4
, x3*y1 + x4*y3
, x3*y2 + x4*y4
)
fib4 :: Integer -> Integer
fib4 0 = 0
fib4 n = let m = Matrix (1, 1, 1, 0)
(Matrix (_, ans, _, _)) = m ^ n
in ans
| kemskems/cis194-spring13 | src/HW06/HW06.hs | bsd-3-clause | 2,524 | 0 | 12 | 610 | 1,041 | 567 | 474 | 55 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
--------------------------------------------------------------------------------
{-|
Module : Media
Copyright : (c) Daan Leijen 2003
(c) shelarcy 2007
License : wxWindows
Maintainer : [email protected]
Stability : provisional
Portability : portable
Images, Media, Sounds, and action!
-}
--------------------------------------------------------------------------------
module Graphics.UI.WX.Media
( -- * Media
Media(..)
-- * Sound
, sound, playLoop, playWait
-- * Images
, image, imageCreateFromFile, imageCreateFromPixels, imageGetPixels
, imageCreateFromPixelArray, imageGetPixelArray
-- * Bitmaps
, bitmap, bitmapCreateFromFile, bitmapFromImage
) where
import System.IO.Unsafe( unsafePerformIO )
import Graphics.UI.WXCore
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Classes
{--------------------------------------------------------------------
Bitmaps
--------------------------------------------------------------------}
-- | Return a managed bitmap object. Bitmaps are abstract images used
-- for drawing to a device context. The file path should point to
-- a valid bitmap file, normally a @.ico@, @.bmp@, @.xpm@, or @.png@,
-- but any file format supported by 'Image' is correctly loaded.
--
-- Instances: 'Sized'.
bitmap :: FilePath -> Bitmap ()
bitmap fname
= unsafePerformIO $ bitmapCreateFromFile fname
instance Sized (Bitmap a) where
size = newAttr "size" bitmapGetSize bitmapSetSize
-- | Create a bitmap from an image with the same color depth.
bitmapFromImage :: Image a -> IO (Bitmap ())
bitmapFromImage image'
= bitmapCreateFromImage image' (-1)
{--------------------------------------------------------------------
Images
--------------------------------------------------------------------}
-- | Return a managed image. Images are platform independent representations
-- of pictures, using an array of rgb pixels. See "Graphics.UI.WXCore.Image" for
-- low-level pixel manipulation. The file path should point to
-- a valid image file, like @.jpg@, @.bmp@, @.xpm@, or @.png@, for example.
--
-- Instances: 'Sized'.
image :: FilePath -> Image ()
image fname
= unsafePerformIO $ imageCreateFromFile fname
instance Sized (Image a) where
size = newAttr "size" imageGetSize imageRescale
{--------------------------------------------------------------------
Media
--------------------------------------------------------------------}
-- | Abstract layer between 'MediaCtrl' and 'Sound'. This class intends to
-- avoid breaking backward-compatibility.
class Media w where
-- | If use this method with 'Sound', play a sound fragment asynchronously.
-- If use this method with 'MediaCtrl', play media that is loaded by
-- 'mediaCtrlLoad'.
play :: w -> IO ()
stop :: w -> IO ()
{--------------------------------------------------------------------
Sounds
--------------------------------------------------------------------}
-- | Return a managed sound object. The file path points to
-- a valid sound file, normally a @.wav@.
sound :: FilePath -> Sound ()
sound fname
= unsafePerformIO $ soundCreate fname False
instance Media (Sound a) where
play sound' = unitIO (soundPlay sound' wxSOUND_ASYNC)
stop = soundStop
-- | Play a sound fragment repeatedly (and asynchronously).
playLoop :: Sound a -> IO ()
playLoop sound'
= unitIO (soundPlay sound' $ wxSOUND_ASYNC .+. wxSOUND_LOOP)
-- | Play a sound fragment synchronously (i.e. wait till completion).
playWait :: Sound a -> IO ()
playWait sound'
= unitIO (soundPlay sound' wxSOUND_SYNC)
| jacekszymanski/wxHaskell | wx/src/Graphics/UI/WX/Media.hs | lgpl-2.1 | 3,779 | 0 | 9 | 679 | 453 | 254 | 199 | 40 | 1 |
{-# language DataKinds #-}
{-# language FlexibleInstances #-}
import Control.Monad ( unless )
import qualified OpenCV as CV
import OpenCV.TypeLevel
import OpenCV.VideoIO.Types
main :: IO ()
main = do
cap <- CV.newVideoCapture
-- Open the first available video capture device. Usually the
-- webcam if run on a laptop.
CV.exceptErrorIO $ CV.videoCaptureOpen cap $ CV.VideoDeviceSource 0 Nothing
isOpened <- CV.videoCaptureIsOpened cap
case isOpened of
False -> putStrLn "Couldn't open video capture device"
True -> do
w <- CV.videoCaptureGetI cap VideoCapPropFrameWidth
h <- CV.videoCaptureGetI cap VideoCapPropFrameHeight
putStrLn $ "Video size: " ++ show w ++ " x " ++ show h
CV.withWindow "video" $ \window -> do
loop cap window
where
loop cap window = do
_ok <- CV.videoCaptureGrab cap
mbImg <- CV.videoCaptureRetrieve cap
case mbImg of
Just img -> do
-- Assert that the retrieved frame is 2-dimensional.
let img' :: CV.Mat ('S ['D, 'D]) 'D 'D
img' = CV.exceptError $ CV.coerceMat img
CV.imshow window img'
key <- CV.waitKey 20
-- Loop unless the escape key is pressed.
unless (key == 27) $ loop cap window
-- Out of frames, stop looping.
Nothing -> pure ()
| lukexi/haskell-opencv | examples/src/videoio.hs | bsd-3-clause | 1,376 | 0 | 19 | 401 | 360 | 172 | 188 | 30 | 3 |
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2011
--
-- Generate code to initialise cost centres
--
-- -----------------------------------------------------------------------------
module Eta.Profiling.ProfInit (profilingInitCode) where
import Eta.Profiling.CostCentre
-- import Eta.Main.DynFlags
import Eta.Utils.Outputable
-- import Eta.Utils.FastString
import Eta.BasicTypes.Module
-- -----------------------------------------------------------------------------
-- Initialising cost centres
-- We must produce declarations for the cost-centres defined in this
-- module;
profilingInitCode :: Module -> CollectedCCs -> SDoc
profilingInitCode _ (_, ___extern_CCs, _)
= sdocWithDynFlags $ const empty
-- if not (gopt Opt_SccProfilingOn dflags)
-- then empty
-- else vcat
-- [ text "static void prof_init_" <> ppr this_mod
-- <> text "(void) __attribute__((constructor));"
-- , text "static void prof_init_" <> ppr this_mod <> text "(void)"
-- , braces (vcat (
-- map emitRegisterCC local_CCs ++
-- map emitRegisterCCS singleton_CCSs
-- ))
-- ]
-- where
-- emitRegisterCC cc =
-- ptext (sLit "extern CostCentre ") <> cc_lbl <> ptext (sLit "[];") $$
-- ptext (sLit "REGISTER_CC(") <> cc_lbl <> char ')' <> semi
-- where cc_lbl = ppr (mkCCLabel cc)
-- emitRegisterCCS ccs =
-- ptext (sLit "extern CostCentreStack ") <> ccs_lbl <> ptext (sLit "[];") $$
-- ptext (sLit "REGISTER_CCS(") <> ccs_lbl <> char ')' <> semi
-- where ccs_lbl = ppr (mkCCSLabel ccs)
| rahulmutt/ghcvm | compiler/Eta/Profiling/ProfInit.hs | bsd-3-clause | 1,654 | 0 | 6 | 329 | 102 | 74 | 28 | 7 | 1 |
module Tests.TestSuiteTasty where
import System.Exit (exitFailure)
import System.Environment (lookupEnv)
import qualified Tests.Parser as P
import qualified Tests.TypeCheck as TC
import qualified Tests.Simplify as S
import qualified Tests.Disintegrate as D
import qualified Tests.Sample as E
import qualified Tests.RoundTrip as RT
import Test.HUnit
-- Tasty
import Test.Tasty
import Test.Tasty.HUnit.Adapter ( hUnitTestToTestTree )
import Test.Tasty.Runners.Html ( htmlRunner )
import Test.Tasty.Ingredients.Rerun ( rerunningTests )
import Test.Tasty.Ingredients.Basic ( consoleTestReporter, listingTests )
-- master test suite
ignored :: Assertion
ignored = putStrLn "Warning: maple tests will be ignored"
simplifyTests :: Test -> Maybe String -> Test
simplifyTests t env =
case env of
Just _ -> t
Nothing -> test ignored
allTests :: Maybe String -> TestTree
allTests env =
testGroup "hakaru" $
hUnitTestToTestTree $
test
[ TestLabel "Parser" P.allTests
, TestLabel "TypeCheck" TC.allTests
, TestLabel "Simplify" (simplifyTests S.allTests env)
, TestLabel "Disintegrate" D.allTests
, TestLabel "Evaluate" E.allTests
, TestLabel "RoundTrip" (simplifyTests RT.allTests env)
]
hakaruRecipe =
[ rerunningTests [ htmlRunner, consoleTestReporter ], listingTests ]
main = (allTests <$> lookupEnv "LOCAL_MAPLE") >>= defaultMainWithIngredients hakaruRecipe
| zachsully/hakaru | haskell/Tests/TestSuiteTasty.hs | bsd-3-clause | 1,465 | 0 | 11 | 284 | 350 | 201 | 149 | 36 | 2 |
{-| Instance status data collector.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.DataCollectors.InstStatus
( main
, options
, arguments
, dcName
, dcVersion
, dcFormatVersion
, dcCategory
, dcKind
, dcReport
) where
import Control.Exception.Base
import Data.List
import Data.Maybe
import qualified Data.Map as Map
import Network.BSD (getHostName)
import qualified Text.JSON as J
import Ganeti.BasicTypes as BT
import Ganeti.Confd.ClientFunctions
import Ganeti.Common
import qualified Ganeti.Constants as C
import Ganeti.DataCollectors.CLI
import Ganeti.DataCollectors.InstStatusTypes
import Ganeti.DataCollectors.Types
import Ganeti.Hypervisor.Xen
import Ganeti.Hypervisor.Xen.Types
import Ganeti.Logging
import Ganeti.Objects
import Ganeti.Path
import Ganeti.Types
import Ganeti.Utils
-- | The name of this data collector.
dcName :: String
dcName = C.dataCollectorInstStatus
-- | The version of this data collector.
dcVersion :: DCVersion
dcVersion = DCVerBuiltin
-- | The version number for the data format of this data collector.
dcFormatVersion :: Int
dcFormatVersion = 1
-- | The category of this data collector.
dcCategory :: Maybe DCCategory
dcCategory = Just DCInstance
-- | The kind of this data collector.
dcKind :: DCKind
dcKind = DCKStatus
-- | The report of this data collector.
dcReport :: IO DCReport
dcReport = buildInstStatusReport Nothing Nothing
-- * Command line options
options :: IO [OptType]
options = return
[ oConfdAddr
, oConfdPort
]
-- | The list of arguments supported by the program.
arguments :: [ArgCompletion]
arguments = []
-- | Try to get the reason trail for an instance. In case it is not possible,
-- log the failure and return an empty list instead.
getReasonTrail :: String -> IO ReasonTrail
getReasonTrail instanceName = do
fileName <- getInstReasonFilename instanceName
content <- try $ readFile fileName
case content of
Left e -> do
logWarning $
"Unable to open the reason trail for instance " ++ instanceName ++
" expected at " ++ fileName ++ ": " ++ show (e :: IOException)
return []
Right trailString ->
case J.decode trailString of
J.Ok t -> return t
J.Error msg -> do
logWarning $ "Unable to parse the reason trail: " ++ msg
return []
-- | Determine the value of the status field for the report of one instance
computeStatusField :: AdminState -> ActualState -> DCStatus
computeStatusField AdminDown actualState =
if actualState `notElem` [ActualShutdown, ActualDying]
then DCStatus DCSCBad "The instance is not stopped as it should be"
else DCStatus DCSCOk ""
computeStatusField AdminUp ActualHung =
DCStatus DCSCUnknown "Instance marked as running, but it appears to be hung"
computeStatusField AdminUp actualState =
if actualState `notElem` [ActualRunning, ActualBlocked]
then DCStatus DCSCBad "The instance is not running as it should be"
else DCStatus DCSCOk ""
computeStatusField AdminOffline _ =
-- FIXME: The "offline" status seems not to be used anywhere in the source
-- code, but it is defined, so we have to consider it anyway here.
DCStatus DCSCUnknown "The instance is marked as offline"
-- Builds the status of an instance using runtime information about the Xen
-- Domains, their uptime information and the static information provided by
-- the ConfD server.
buildStatus :: Map.Map String Domain -> Map.Map Int UptimeInfo
-> RealInstanceData
-> IO InstStatus
buildStatus domains uptimes inst = do
let name = realInstName inst
currDomain = Map.lookup name domains
idNum = fmap domId currDomain
currUInfo = idNum >>= (`Map.lookup` uptimes)
uptime = fmap uInfoUptime currUInfo
adminState = realInstAdminState inst
actualState =
if adminState == AdminDown && isNothing currDomain
then ActualShutdown
else case currDomain of
(Just dom@(Domain _ _ _ _ (Just isHung))) ->
if isHung
then ActualHung
else domState dom
_ -> ActualUnknown
status = computeStatusField adminState actualState
trail <- getReasonTrail name
return $
InstStatus
name
(realInstUuid inst)
adminState
actualState
uptime
(realInstMtime inst)
trail
status
-- | Compute the status code and message, given the current DRBD data
-- The final state will have the code corresponding to the worst code of
-- all the devices, and the error message given from the concatenation of the
-- non-empty error messages.
computeGlobalStatus :: [InstStatus] -> DCStatus
computeGlobalStatus instStatusList =
let dcstatuses = map iStatStatus instStatusList
statuses = map (\s -> (dcStatusCode s, dcStatusMessage s)) dcstatuses
(code, strList) = foldr mergeStatuses (DCSCOk, [""]) statuses
in DCStatus code $ intercalate "\n" strList
-- | Build the report of this data collector, containing all the information
-- about the status of the instances.
buildInstStatusReport :: Maybe String -> Maybe Int -> IO DCReport
buildInstStatusReport srvAddr srvPort = do
node <- getHostName
answer <- runResultT $ getInstances node srvAddr srvPort
inst <- exitIfBad "Can't get instance info from ConfD" answer
d <- getInferredDomInfo
let toReal (RealInstance i) = Just i
toReal _ = Nothing
reportData <-
case d of
BT.Ok domains -> do
uptimes <- getUptimeInfo
let primaryInst = mapMaybe toReal $ fst inst
iStatus <- mapM (buildStatus domains uptimes) primaryInst
let globalStatus = computeGlobalStatus iStatus
return $ ReportData iStatus globalStatus
BT.Bad m ->
return . ReportData [] . DCStatus DCSCBad $
"Unable to receive the list of instances: " ++ m
let jsonReport = J.showJSON reportData
buildReport dcName dcVersion dcFormatVersion dcCategory dcKind jsonReport
-- | Main function.
main :: Options -> [String] -> IO ()
main opts _ = do
report <- buildInstStatusReport (optConfdAddr opts) (optConfdPort opts)
putStrLn $ J.encode report
| apyrgio/ganeti | src/Ganeti/DataCollectors/InstStatus.hs | bsd-2-clause | 7,407 | 0 | 20 | 1,540 | 1,276 | 665 | 611 | 139 | 4 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Active Scan Rules - Alpha | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/ascanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 986 | 83 | 53 | 162 | 403 | 212 | 191 | -1 | -1 |
-- This example demonstrates the peril of trying to benchmark a
-- function that performs lazy I/O.
import Criterion.Main
main :: IO ()
main = defaultMain [
-- By using whnfIO, when the benchmark loop goes through an
-- iteration, we inspect only the first constructor returned after
-- the file is opened. Since the entire file must be read in
-- order for it to be closed, this causes file handles to leak,
-- and our benchmark will probably crash while running with an
-- error like this:
--
-- openFile: resource exhausted (Too many open files)
bench "whnfIO readFile" $ whnfIO (readFile "BadReadFile.hs")
]
| paulolieuthier/criterion | examples/BadReadFile.hs | bsd-2-clause | 653 | 0 | 10 | 147 | 53 | 31 | 22 | 4 | 1 |
module SchemeParse
( parseAtom
{-, parseString-}
, parseNumber
, parseExpr
, readExpr) where
import Control.Monad
import Text.ParserCombinators.Parsec hiding (spaces)
import SchemeDef
{-spaces :: Parser ()
spaces = skipMany1 space-}
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~"
parseAtom :: Parser LispVal
parseAtom = do first <- letter <|> symbol <|> char '#'
rest <- many (letter <|> digit <|> symbol)
let atom = first : rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
_ -> Atom atom
{-parseString :: Parser LispVal
parseString = do char '"'
x <- many chars
char '"'
return $ String x
where chars = escapedChar <|> noneOf "\""
escapedChar = char "\\" >> choice -}
parseNumber :: Parser LispVal
parseNumber = liftM (Number . read) $ many1 digit
parseExpr :: Parser LispVal
parseExpr = parseAtom
{-<|> parseString-}
<|> parseNumber
readExpr :: String -> LispVal
readExpr input = case parse parseExpr "lisp" input of
Left err -> String $ "Parse error: " ++ show err
Right val -> val
| phlip9/scheme-interpreter | SchemeParse.hs | mit | 1,242 | 0 | 11 | 400 | 265 | 136 | 129 | 27 | 3 |
{-
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
-}
-- Some custom data types to help define the problem
type Year = Int
type Day = Int
data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Enum, Eq, Ord, Show)
data Date = Date Year Month Day deriving (Eq, Ord, Show)
data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Enum, Eq, Show)
-- Quick check if a year is a leap year
isLeapYear :: Year -> Bool
isLeapYear y = y `mod` 400 == 0 || (y `mod` 4 == 0 && y `mod` 100 /= 0)
-- Determine the next day of a given date
next :: Date -> Date
next (Date y m d)
| m == December && d == 31 = Date (y+1) January 1
| d == 31 = Date y (succ m) 1
| m == February && d == 28 = if isLeapYear y then Date y February 29 else Date y March 1
| m == February && d == 29 = Date y March 1
| m `elem` [April, June, September, November] && d == 30 = Date y (succ m) 1
| otherwise = Date y m (d+1)
-- The first known Monday given in the problem description
initialMonday :: Date
initialMonday = Date 1900 January 1
-- An infinite sequence of dates starting from initialMonday
calendar :: [Date]
calendar = iterate next initialMonday
-- An infinite cycle of the days of the week
weekdays :: [WeekDay]
weekdays = cycle [Monday .. Sunday]
-- Pairing the day of the week with an actual date beginning on a known Monday (see above)
days :: [(WeekDay, Date)]
days = zip weekdays calendar
-- Filter the given period
period :: [(WeekDay, Date)]
period = dropWhile (\(w,d) -> d < (Date 1901 January 1)) (takeWhile (\(w,d) -> d <= (Date 2000 December 31)) days)
-- Filter only the sundays that happened in the first of the month
sundayFirsts :: [(WeekDay, Date)]
sundayFirsts = filter (\(w,Date y m d) -> w == Sunday && d == 1) period
-- Count them
euler19 :: Int
euler19 = length sundayFirsts
| feliposz/project-euler-solutions | haskell/euler19.hs | mit | 2,405 | 2 | 12 | 504 | 682 | 378 | 304 | 29 | 2 |
module Main where
{-
pwr :: Integral a => a -> a -> a
pwr b e = pwr' b b e
pwr' :: Integral a => a -> a -> a -> a
pwr' acc b 1 = acc
pwr' acc b e = pwr' (acc*b) b (e-1)
x % y
| x < y = x
| x == y = 0
| otherwise = (x - y) % y
-}
result :: (Enum a, RealFloat a) => a
result = head [ a * b * sqrt (a * a + b * b) | a <- [1..998], b <- [1..998], a < b, a + b + sqrt (a * a + b * b) == 1000]
main :: IO ()
main = print $ floor result | ron-wolf/haskeuler | src/09.hs | mit | 450 | 0 | 14 | 151 | 152 | 80 | 72 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.List.NonEmpty
import Language.SAL
main :: IO ()
main = putStrLn (renderSAL ctx)
ctx :: Context
ctx = Context "salctx" Nothing body
where
body = ContextBody (ModuleDecl salmod :| [])
salmod :: ModuleDeclaration
salmod =
let
ins = InputDecl $ VarDecls (VarDecl "x" (TyBasic INTEGER) :| [])
outs = OutputDecl $ VarDecls (VarDecl "y" (TyBasic INTEGER) :| [])
expr = InfixApp (NameExpr "x") "+" (NumLit 1)
d1 = DefSimple (SimpleDefinition (LhsCurrent "y" [])
(RhsExpr expr))
defs = DefDecl $ Definitions (d1 :| [])
in
ModuleDeclaration "salmod" Nothing $
BaseModule
[ ins
, outs
, defs
]
| GaloisInc/language-sal | examples/salmod.hs | mit | 769 | 0 | 15 | 224 | 257 | 133 | 124 | 23 | 1 |
module KMC.Syntax.ParserCombinators
( repetitions
, delims
, parens
, brackets
, braces
, suppressDelims
, parseTable
, nonGroupParens
, genParseTable
) where
import Control.Applicative hiding (many)
import Text.ParserCombinators.Parsec (choice, count, many, many1,
optionMaybe, string, try)
import KMC.Syntax.ParserTypes
import Prelude
--------------------------------------------------------------------------------
-- Various useful parser combinators.
--------------------------------------------------------------------------------
-- | Automatically build a parse table from a data type that implements the Show
-- type class. Takes a function that specifies how the parsers
-- should behave as a function of their "Show value", a function to transform
-- the parsed constructors, and a list of the constructors that should be
-- made parsable by what "show" returns.
genParseTable :: (Show a)
=> (String -> Parser String) -> (a -> b) -> [a] -> Parser b
genParseTable p f = parseTable p f . map (\v -> (show v, v))
-- | Build a parser for a given table. The result of each parser
-- is the value created by "valMod" applied to the right value in the tuple.
parseTable :: (s -> Parser s) -> (a -> b) -> [(s, a)] -> Parser b
parseTable parserMod valMod = choice . map
(\(s,v) -> parserMod s >> return (valMod v))
-- | Given an ordering relation and an integer n, repeat the given parser either
-- (== n) times, (<= n) times, or (>= n) times. Negative n are clamped to 0.
repetitions :: Ordering -> Int -> Parser a -> Parser [a]
repetitions o n = let n' = if n < 0 then 0 else n in case o of
EQ -> count n'
LT -> maximumRepetitions n'
GT -> minimumRepetitions n'
-- | Repeat parser minimum n times and collect the results.
minimumRepetitions :: Int -> Parser a -> Parser [a]
minimumRepetitions 0 p = many p
minimumRepetitions 1 p = many1 p
minimumRepetitions n p = do
xs <- count n p
xs' <- many p
return (xs ++ xs')
-- | Repeat parser maximum n times and collect the results.
maximumRepetitions :: Int -> Parser a -> Parser [a]
maximumRepetitions 0 _ = return []
maximumRepetitions 1 p = p >>= return . (:[])
maximumRepetitions n p = do
x <- p
mxs <- optionMaybe (maximumRepetitions (n - 1) p)
case mxs of
Nothing -> return [x]
Just xs -> return (x:xs)
-- | Build a parser that parses the given left- and right-delimiters around
-- the provided parser p.
delims :: String -> String -> Parser a -> Parser a
delims left right p = try (string left) *> p <* (string right)
-- | Put parentheses around parser
parens :: Parser a -> Parser a
parens = delims "(" ")"
nonGroupParens :: Parser a -> Parser a
nonGroupParens = delims "(?:" ")"
-- | Put brackets around parser
brackets :: Parser a -> Parser a
brackets = delims "[" "]"
-- | Put braces around parser
braces :: Parser a -> Parser a
braces = delims "{" "}"
-- | Put "suppression delimiters" around parser
suppressDelims :: Parser a -> Parser a
suppressDelims = delims "$(" ")$"
| diku-kmc/regexps-syntax | KMC/Syntax/ParserCombinators.hs | mit | 3,169 | 0 | 12 | 747 | 793 | 415 | 378 | 54 | 4 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Y2018.M04.D09.Exercise where
import Data.Aeson
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
{--
Okay, fam. We're going to wrap up our preparation for the data load by
parsing tags into a tags lookup table.
--}
-- below imports available via 1HaskellADay git repository
import Data.LookupTable
import Store.SQL.Connection
import Store.SQL.Util.Indexed
import Store.SQL.Util.LookupTable
tags :: FilePath
tags = "Y2018/M04/D09/tags.json"
data Tag = SomeStructureYouDeclare
readTags :: FilePath -> IO [Tag]
readTags json = undefined
-- and then, into the database we go:
tagStmt :: Query
tagStmt = [sql|INSERT INTO tag VALUES (?,?)|]
insertTags :: Connection -> LookupTable -> IO ()
insertTags conn = undefined
| geophf/1HaskellADay | exercises/HAD/Y2018/M04/D09/Exercise.hs | mit | 804 | 0 | 8 | 116 | 135 | 84 | 51 | 18 | 1 |
{-# LANGUAGE FlexibleContexts
, UndecidableSuperClasses #-}
module MiniSequel.Mapper
where
import MiniSequel
import MiniSequel.Expression ((=.), SequelExpression)
import Database.HDBC
import Data.Data
import Data.Char (toUpper, toLower, isUpper)
import Data.Maybe (fromJust)
import qualified GHC.Generics as G
import qualified Generics.SOP as SOP
sequelValues :: (SOP.Generic a, SOP.All2 SequelValue (SOP.Code a)) => a -> [SequelExpression]
sequelValues a = SOP.hcollapse (SOP.hcmap
(Proxy :: Proxy SequelValue)
(\ (SOP.I x) -> SOP.K (v x))
(SOP.from a))
class SequelMapper a where
fromSqlRow :: [SqlValue] -> a
create :: a -> SequelQuery
createMulti :: [a] -> SequelQuery
createMulti a = query
where
fields = fromJust . _colums . create . head $ a
vals = map (head . fromJust . _values . create) a
query = makeQuery tableName $ do
insert fields
values vals
tableName = _from . create . head $ a
snakeCase :: String -> String
snakeCase = map toLower . concat . underscores . splitR isUpper
where
underscores :: [String] -> [String]
underscores [] = []
underscores (h:t) = h : map ('_':) t
splitR :: (Char -> Bool) -> String -> [String]
splitR _ [] = []
splitR p s =
let
go :: Char -> String -> [String]
go m s' = case break p s' of
(b', []) -> [ m:b' ]
(b', x:xs) -> ( m:b' ) : go x xs
in case break p s of
(b, []) -> [ b ]
([], h:t) -> go h t
(b, h:t) -> b : go h t
class (G.Generic a, Data a, SOP.Generic a, SOP.All2 SequelValue (SOP.Code a)) => SequelMapperUpdateable a where
store :: a -> SequelQuery
store a = query
where
key:fields = map (s.snakeCase) $ constrFields . toConstr $ a
id : vals = sequelValues a
query = undefined
-- update set_fields $
-- where' (key =. id) $
-- from table_name
table_name = ts $ snakeCase $ show $ toConstr a
set_fields = zipWith (=.) fields vals
| TachoMex/MiniSequel | src/MiniSequel/Mapper.hs | mit | 2,283 | 0 | 16 | 814 | 786 | 420 | 366 | 52 | 6 |
{-|
Module: Y2015.D06
Description: Advent of Code Day 06 Solutions.
License: MIT
Maintainer: @tylerjl
Solutions to the day 06 set of problems for <adventofcode.com>.
-}
module Y2015.D06
( testA
, testB
, Instruction(..)
, Range(..)
, parseInstructions
, configureGridA
, configureGridB
, lightSimulation
) where
import Control.Applicative ((<|>))
import Data.List (foldl')
import qualified Data.Array.Repa as R
import Data.Array.Repa (Z(..), (:.)(..))
import qualified Text.Parsec as P
import Text.Parsec.Char (char, endOfLine)
import Text.Parsec.String (Parser)
import Data.Vector.Unboxed.Base (Unbox)
import Y2015.Util (regularParse, intParser)
type Point = (Int, Int)
-- |Represents a two-dimensional range of lights.
data Range =
Range Point
Point
deriving (Eq, Show)
-- |Type of light grid instruction.
data Instruction
= On Range
| Off Range
| Toggle Range
deriving (Show)
size :: Int
size = 1000
initialGrid :: R.Array R.U R.DIM2 Int
initialGrid =
R.fromListUnboxed (Z :. size :. size :: R.DIM2) (replicate (size * size) 0)
instructionsParser :: Parser [Instruction]
instructionsParser = P.many (instruction <* P.optional endOfLine)
instruction :: Parser Instruction
instruction = On <$> directive "turn on"
<|> Off <$> directive "turn off"
<|> Toggle <$> directive "toggle"
directive :: String -> Parser Range
directive s = P.skipMany1 (P.try (P.string s *> P.skipMany1 P.space)) *> range
range :: Parser Range
range = Range <$> point <* P.string " through " <*> point
point :: Parser Point
point = (,) <$> intParser <* char ',' <*> intParser
-- |Folding function to aggregate computation for 'Instruction's per part
-- |A spec.
configureGridA
:: R.Array R.U R.DIM2 Int -- ^ Light grid.
-> Instruction -- ^ Operation 'Instruction'.
-> R.Array R.U R.DIM2 Int -- ^ Resultant light grid.
configureGridA a (On r) = switch a (const 1) r
configureGridA a (Off r) = switch a (const 0) r
configureGridA a (Toggle r) = switch a toggle r
-- |Folding function to aggregate computation for 'Instruction's per part
-- |B spec.
configureGridB
:: R.Array R.U R.DIM2 Int -- ^ Light grid.
-> Instruction -- ^ Operation 'Instruction'.
-> R.Array R.U R.DIM2 Int -- ^ Resultant light grid.
configureGridB a (On r) = switch a (+ 1) r
configureGridB a (Off r) = switch a dim r
configureGridB a (Toggle r) = switch a (+ 2) r
toggle :: Int -> Int
toggle 1 = 0
toggle _ = 1
dim :: Int -> Int
dim = max 0 . subtract 1
switch
:: (R.Source r a, Unbox a)
=> R.Array r R.DIM2 a -> (a -> a) -> Range -> R.Array R.U R.DIM2 a
switch a f r = R.computeS $ R.traverse a id (set f r)
-- This is pretty confusing:
-- Custom mapping function (set the lights)
-- -> Range to apply the function upon
-- -> Function to retrieve original elements from
-- -> Original array constructor
-- -> New (or unchanged) value
set :: (a -> a) -> Range -> (R.DIM2 -> a) -> R.DIM2 -> a
set f (Range (x', y') (x'', y'')) g (Z :. x :. y)
| withinX && withinY = f orig
| otherwise = orig
where
withinX = x >= x' && x <= x''
withinY = y >= y' && y <= y''
orig = g (Z :. x :. y)
-- |Execute 'Instruction' and return number of lit lights per part A spec.
testA
:: Instruction -- ^ Given 'Instruction'.
-> Int -- ^ Number of lit lights.
testA = R.foldAllS (+) 0 . configureGridA initialGrid
-- |Execute 'Instruction' and return number of lit lights per part B spec.
testB
:: Instruction -- ^ Given 'Instruction'
-> Int -- ^ Number of lit lights.
testB = R.foldAllS (+) 0 . configureGridB initialGrid
-- |Parses a string into a list of 'Instruction's.
parseInstructions
:: String -- ^ Input string to parse.
-> Either P.ParseError [Instruction] -- ^ Either an error or parsed structure.
parseInstructions = regularParse instructionsParser
-- |Run a light simulation
lightSimulation
:: (Monad m, Foldable t)
=> (R.Array R.U R.DIM2 Int -> a -> R.Array R.U R.DIM2 Int) -- ^ REPA Light grid
-> t a -- ^ 'Instruction's
-> m Int -- ^ Lit lights
lightSimulation f = R.sumAllP . foldl' f initialGrid
| tylerjl/adventofcode | src/Y2015/D06.hs | mit | 4,087 | 0 | 12 | 835 | 1,233 | 669 | 564 | 93 | 1 |
-- | In this module, we model an /elementary topos/ with Haskell types
-- (see <https://en.wikipedia.org/wiki/Topos>).
-- To be more precise, we model the "smallest elementary topos with a
-- natural number object". Without such a natural number object,
-- the resulting topos would be boring, consisting merely of the finite
-- sets. By adding one infinite object, namely the natural numbers, we
-- get access to all sorts of interesting objects - rational numbers,
-- (constructible) real numbers, differentiable functions, a big chunk of
-- all those objects that are studied in mathematics.
module Protop.Core
( module Protop.Core.Compositions
, module Protop.Core.Equalizers
, module Protop.Core.Exponentials
, module Protop.Core.Identities
, module Protop.Core.Monos
, module Protop.Core.Morphisms
, module Protop.Core.Natural
, module Protop.Core.Objects
, module Protop.Core.Omega
, module Protop.Core.Products
, module Protop.Core.Proofs
, module Protop.Core.Reflexivities
, module Protop.Core.Setoids
, module Protop.Core.Symmetries
, module Protop.Core.Transitivities
, module Protop.Core.Terminal
) where
import Protop.Core.Compositions
import Protop.Core.Equalizers
import Protop.Core.Exponentials
import Protop.Core.Identities
import Protop.Core.Monos
import Protop.Core.Morphisms
import Protop.Core.Natural
import Protop.Core.Objects
import Protop.Core.Omega
import Protop.Core.Products
import Protop.Core.Proofs
import Protop.Core.Reflexivities
import Protop.Core.Setoids
import Protop.Core.Symmetries
import Protop.Core.Transitivities
import Protop.Core.Terminal
| brunjlar/protop | src/Protop/Core.hs | mit | 1,649 | 0 | 5 | 247 | 225 | 158 | 67 | 33 | 0 |
module Solidran.Hamm.DetailSpec (spec) where
import Test.Hspec
import Solidran.Hamm.Detail
spec :: Spec
spec = do
describe "Solidran.Hamm.Detail" $ do
describe "hammingDist" $ do
it "should work in the given sample" $ do
hammingDist "GAGCCTACTAACGGGAT" "CATCGTAATGACGGCCT"
`shouldBe` 7
it "should work on empty strings" $ do
hammingDist "" ""
`shouldBe` 0
it "should work with any character" $ do
hammingDist "333yg!.u=)8GYGU3¥~" "/^ayg?.u=)8gYGU3¥~"
`shouldBe` 5
hammingDist "%&\"lqyYYUIhCDX%°" "%&'lqyYYUIhCDX%°"
`shouldBe` 1
| Jefffrey/Solidran | test/Solidran/Hamm/DetailSpec.hs | mit | 726 | 0 | 17 | 261 | 139 | 69 | 70 | 18 | 1 |
{-|
Module : Optimization.TAC.UnneededLabels
Description : Remove labels which are never jumped to.
Copyright : 2014, Jonas Cleve
License : GPL-3
-}
module Optimization.TAC.UnneededLabels (
removeUnneededLabels
) where
import Interface.TAC (
TAC, Command (..), Label,
isGoto, getLabelFromGoto
)
import Prelude (
notElem, filter,
($)
)
import Data.List (
nub
)
import Data.Functor (
(<$>)
)
-- * Exported functions
-- | Removes all labels from the TAC that are never jumped to by some goto
-- instruction.
removeUnneededLabels :: TAC -> TAC
removeUnneededLabels tac = removeUnneededLabels' tac
where
removeUnneededLabels' :: TAC -> TAC
removeUnneededLabels' [] = []
removeUnneededLabels' (Label l : tac_)
| l `notElem` jumpTargets = removeUnneededLabels' tac_
removeUnneededLabels' (t:tac_) = t : removeUnneededLabels' tac_
-- Get all labels that are jumped to by some goto instruction
jumpTargets :: [Label]
jumpTargets = nub $ getLabelFromGoto <$> filter isGoto tac
| Potregon/while | src/Optimization/TAC/UnneededLabels.hs | gpl-3.0 | 1,062 | 0 | 10 | 235 | 205 | 118 | 87 | 21 | 3 |
fact1 0 = 1
fact1 n = fact1 (n-1) * n
fact2 n | n == 0 = 1
| otherwise = fact2 (n-1) * n
fact3 n = case n == 0 of
True -> 1
False -> fact3 (n-1) * n
fact4 n = case n of
0 -> 1
_ -> fact4 (n-1) * n
fact5 n = product [1..n]
fact6 n = if n == 0
then 1
else n * fact5 (n-1) | graninas/Haskell-Algorithms | Tests/Fact.hs | gpl-3.0 | 341 | 4 | 9 | 148 | 206 | 100 | 106 | 14 | 2 |
module Level.Task where
import Control.Lens.Operators
import Level
import qualified Level.Command as Command
import StaticElement(StaticElement)
import Task
import Counter
import Actor (TaskType(Mine))
import Unfold
import Level.Transformation
mine :: StaticElement -> Level -> Identifier Task -> Task
mine s lvl i = Task
{ _id = i
, _target = lvl ^. coordOf s
, _taskType = Mine
, _command = \dwarf lvl' -> Command.mine s dwarf lvl' `catch` handler
, _precondition = \lvl' -> isReachable (lvl' ^. coordOf s) lvl'
}
where
catch :: Unfold LevelTrans -> (LevelError -> TaskStatus) -> Unfold (Level -> TaskStatus)
catch cmd h = fmap (\cmd' lvl' -> either h InProgress (cmd' lvl')) cmd
handler _ = Reschedule
| svenkeidel/gnome-citadel | src/Level/Task.hs | gpl-3.0 | 801 | 0 | 12 | 208 | 251 | 141 | 110 | 20 | 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.Route53.UpdateHealthCheck
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This action updates an existing health check.
--
-- To update a health check, send a 'POST' request to the
-- '2013-04-01\/healthcheck\/health check ID' resource. The request body
-- must include an XML document with an 'UpdateHealthCheckRequest' element.
-- The response returns an 'UpdateHealthCheckResponse' element, which
-- contains metadata about the health check.
--
-- /See:/ <http://docs.aws.amazon.com/Route53/latest/APIReference/API_UpdateHealthCheck.html AWS API Reference> for UpdateHealthCheck.
module Network.AWS.Route53.UpdateHealthCheck
(
-- * Creating a Request
updateHealthCheck
, UpdateHealthCheck
-- * Request Lenses
, uhcFailureThreshold
, uhcIPAddress
, uhcSearchString
, uhcHealthThreshold
, uhcResourcePath
, uhcHealthCheckVersion
, uhcInverted
, uhcFullyQualifiedDomainName
, uhcChildHealthChecks
, uhcPort
, uhcHealthCheckId
-- * Destructuring the Response
, updateHealthCheckResponse
, UpdateHealthCheckResponse
-- * Response Lenses
, uhcrsResponseStatus
, uhcrsHealthCheck
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.Route53.Types
import Network.AWS.Route53.Types.Product
-- | >A complex type that contains information about the request to update a
-- health check.
--
-- /See:/ 'updateHealthCheck' smart constructor.
data UpdateHealthCheck = UpdateHealthCheck'
{ _uhcFailureThreshold :: !(Maybe Nat)
, _uhcIPAddress :: !(Maybe Text)
, _uhcSearchString :: !(Maybe Text)
, _uhcHealthThreshold :: !(Maybe Nat)
, _uhcResourcePath :: !(Maybe Text)
, _uhcHealthCheckVersion :: !(Maybe Nat)
, _uhcInverted :: !(Maybe Bool)
, _uhcFullyQualifiedDomainName :: !(Maybe Text)
, _uhcChildHealthChecks :: !(Maybe [Text])
, _uhcPort :: !(Maybe Nat)
, _uhcHealthCheckId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateHealthCheck' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uhcFailureThreshold'
--
-- * 'uhcIPAddress'
--
-- * 'uhcSearchString'
--
-- * 'uhcHealthThreshold'
--
-- * 'uhcResourcePath'
--
-- * 'uhcHealthCheckVersion'
--
-- * 'uhcInverted'
--
-- * 'uhcFullyQualifiedDomainName'
--
-- * 'uhcChildHealthChecks'
--
-- * 'uhcPort'
--
-- * 'uhcHealthCheckId'
updateHealthCheck
:: Text -- ^ 'uhcHealthCheckId'
-> UpdateHealthCheck
updateHealthCheck pHealthCheckId_ =
UpdateHealthCheck'
{ _uhcFailureThreshold = Nothing
, _uhcIPAddress = Nothing
, _uhcSearchString = Nothing
, _uhcHealthThreshold = Nothing
, _uhcResourcePath = Nothing
, _uhcHealthCheckVersion = Nothing
, _uhcInverted = Nothing
, _uhcFullyQualifiedDomainName = Nothing
, _uhcChildHealthChecks = Nothing
, _uhcPort = Nothing
, _uhcHealthCheckId = pHealthCheckId_
}
-- | The number of consecutive health checks that an endpoint must pass or
-- fail for Route 53 to change the current status of the endpoint from
-- unhealthy to healthy or vice versa.
--
-- Valid values are integers between 1 and 10. For more information, see
-- \"How Amazon Route 53 Determines Whether an Endpoint Is Healthy\" in the
-- Amazon Route 53 Developer Guide.
--
-- Specify this value only if you want to change it.
uhcFailureThreshold :: Lens' UpdateHealthCheck (Maybe Natural)
uhcFailureThreshold = lens _uhcFailureThreshold (\ s a -> s{_uhcFailureThreshold = a}) . mapping _Nat;
-- | The IP address of the resource that you want to check.
--
-- Specify this value only if you want to change it.
uhcIPAddress :: Lens' UpdateHealthCheck (Maybe Text)
uhcIPAddress = lens _uhcIPAddress (\ s a -> s{_uhcIPAddress = a});
-- | If the value of 'Type' is 'HTTP_STR_MATCH' or 'HTTP_STR_MATCH', the
-- string that you want Route 53 to search for in the response body from
-- the specified resource. If the string appears in the response body,
-- Route 53 considers the resource healthy.
--
-- Specify this value only if you want to change it.
uhcSearchString :: Lens' UpdateHealthCheck (Maybe Text)
uhcSearchString = lens _uhcSearchString (\ s a -> s{_uhcSearchString = a});
-- | The minimum number of child health checks that must be healthy for Route
-- 53 to consider the parent health check to be healthy. Valid values are
-- integers between 0 and 256, inclusive.
--
-- Specify this value only if you want to change it.
uhcHealthThreshold :: Lens' UpdateHealthCheck (Maybe Natural)
uhcHealthThreshold = lens _uhcHealthThreshold (\ s a -> s{_uhcHealthThreshold = a}) . mapping _Nat;
-- | The path that you want Amazon Route 53 to request when performing health
-- checks. The path can be any value for which your endpoint will return an
-- HTTP status code of 2xx or 3xx when the endpoint is healthy, for example
-- the file \/docs\/route53-health-check.html.
--
-- Specify this value only if you want to change it.
uhcResourcePath :: Lens' UpdateHealthCheck (Maybe Text)
uhcResourcePath = lens _uhcResourcePath (\ s a -> s{_uhcResourcePath = a});
-- | Optional. When you specify a health check version, Route 53 compares
-- this value with the current value in the health check, which prevents
-- you from updating the health check when the versions don\'t match. Using
-- 'HealthCheckVersion' lets you prevent overwriting another change to the
-- health check.
uhcHealthCheckVersion :: Lens' UpdateHealthCheck (Maybe Natural)
uhcHealthCheckVersion = lens _uhcHealthCheckVersion (\ s a -> s{_uhcHealthCheckVersion = a}) . mapping _Nat;
-- | A boolean value that indicates whether the status of health check should
-- be inverted. For example, if a health check is healthy but 'Inverted' is
-- 'True', then Route 53 considers the health check to be unhealthy.
--
-- Specify this value only if you want to change it.
uhcInverted :: Lens' UpdateHealthCheck (Maybe Bool)
uhcInverted = lens _uhcInverted (\ s a -> s{_uhcInverted = a});
-- | Fully qualified domain name of the instance to be health checked.
--
-- Specify this value only if you want to change it.
uhcFullyQualifiedDomainName :: Lens' UpdateHealthCheck (Maybe Text)
uhcFullyQualifiedDomainName = lens _uhcFullyQualifiedDomainName (\ s a -> s{_uhcFullyQualifiedDomainName = a});
-- | For a specified parent health check, a list of 'HealthCheckId' values
-- for the associated child health checks.
--
-- Specify this value only if you want to change it.
uhcChildHealthChecks :: Lens' UpdateHealthCheck [Text]
uhcChildHealthChecks = lens _uhcChildHealthChecks (\ s a -> s{_uhcChildHealthChecks = a}) . _Default . _Coerce;
-- | The port on which you want Route 53 to open a connection to perform
-- health checks.
--
-- Specify this value only if you want to change it.
uhcPort :: Lens' UpdateHealthCheck (Maybe Natural)
uhcPort = lens _uhcPort (\ s a -> s{_uhcPort = a}) . mapping _Nat;
-- | The ID of the health check to update.
uhcHealthCheckId :: Lens' UpdateHealthCheck Text
uhcHealthCheckId = lens _uhcHealthCheckId (\ s a -> s{_uhcHealthCheckId = a});
instance AWSRequest UpdateHealthCheck where
type Rs UpdateHealthCheck = UpdateHealthCheckResponse
request = postXML route53
response
= receiveXML
(\ s h x ->
UpdateHealthCheckResponse' <$>
(pure (fromEnum s)) <*> (x .@ "HealthCheck"))
instance ToElement UpdateHealthCheck where
toElement
= mkElement
"{https://route53.amazonaws.com/doc/2013-04-01/}UpdateHealthCheckRequest"
instance ToHeaders UpdateHealthCheck where
toHeaders = const mempty
instance ToPath UpdateHealthCheck where
toPath UpdateHealthCheck'{..}
= mconcat
["/2013-04-01/healthcheck/", toBS _uhcHealthCheckId]
instance ToQuery UpdateHealthCheck where
toQuery = const mempty
instance ToXML UpdateHealthCheck where
toXML UpdateHealthCheck'{..}
= mconcat
["FailureThreshold" @= _uhcFailureThreshold,
"IPAddress" @= _uhcIPAddress,
"SearchString" @= _uhcSearchString,
"HealthThreshold" @= _uhcHealthThreshold,
"ResourcePath" @= _uhcResourcePath,
"HealthCheckVersion" @= _uhcHealthCheckVersion,
"Inverted" @= _uhcInverted,
"FullyQualifiedDomainName" @=
_uhcFullyQualifiedDomainName,
"ChildHealthChecks" @=
toXML
(toXMLList "ChildHealthCheck" <$>
_uhcChildHealthChecks),
"Port" @= _uhcPort]
-- | /See:/ 'updateHealthCheckResponse' smart constructor.
data UpdateHealthCheckResponse = UpdateHealthCheckResponse'
{ _uhcrsResponseStatus :: !Int
, _uhcrsHealthCheck :: !HealthCheck
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateHealthCheckResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uhcrsResponseStatus'
--
-- * 'uhcrsHealthCheck'
updateHealthCheckResponse
:: Int -- ^ 'uhcrsResponseStatus'
-> HealthCheck -- ^ 'uhcrsHealthCheck'
-> UpdateHealthCheckResponse
updateHealthCheckResponse pResponseStatus_ pHealthCheck_ =
UpdateHealthCheckResponse'
{ _uhcrsResponseStatus = pResponseStatus_
, _uhcrsHealthCheck = pHealthCheck_
}
-- | The response status code.
uhcrsResponseStatus :: Lens' UpdateHealthCheckResponse Int
uhcrsResponseStatus = lens _uhcrsResponseStatus (\ s a -> s{_uhcrsResponseStatus = a});
-- | Undocumented member.
uhcrsHealthCheck :: Lens' UpdateHealthCheckResponse HealthCheck
uhcrsHealthCheck = lens _uhcrsHealthCheck (\ s a -> s{_uhcrsHealthCheck = a});
| olorin/amazonka | amazonka-route53/gen/Network/AWS/Route53/UpdateHealthCheck.hs | mpl-2.0 | 10,652 | 0 | 14 | 2,210 | 1,427 | 852 | 575 | 162 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Games.Players.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the Player resource with the given ID. To retrieve the player
-- for the currently authenticated user, set playerId to me.
--
-- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.players.get@.
module Network.Google.Resource.Games.Players.Get
(
-- * REST Resource
PlayersGetResource
-- * Creating a Request
, playersGet
, PlayersGet
-- * Request Lenses
, pgConsistencyToken
, pgLanguage
, pgPlayerId
) where
import Network.Google.Games.Types
import Network.Google.Prelude
-- | A resource alias for @games.players.get@ method which the
-- 'PlayersGet' request conforms to.
type PlayersGetResource =
"games" :>
"v1" :>
"players" :>
Capture "playerId" Text :>
QueryParam "consistencyToken" (Textual Int64) :>
QueryParam "language" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Player
-- | Retrieves the Player resource with the given ID. To retrieve the player
-- for the currently authenticated user, set playerId to me.
--
-- /See:/ 'playersGet' smart constructor.
data PlayersGet = PlayersGet'
{ _pgConsistencyToken :: !(Maybe (Textual Int64))
, _pgLanguage :: !(Maybe Text)
, _pgPlayerId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'PlayersGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pgConsistencyToken'
--
-- * 'pgLanguage'
--
-- * 'pgPlayerId'
playersGet
:: Text -- ^ 'pgPlayerId'
-> PlayersGet
playersGet pPgPlayerId_ =
PlayersGet'
{ _pgConsistencyToken = Nothing
, _pgLanguage = Nothing
, _pgPlayerId = pPgPlayerId_
}
-- | The last-seen mutation timestamp.
pgConsistencyToken :: Lens' PlayersGet (Maybe Int64)
pgConsistencyToken
= lens _pgConsistencyToken
(\ s a -> s{_pgConsistencyToken = a})
. mapping _Coerce
-- | The preferred language to use for strings returned by this method.
pgLanguage :: Lens' PlayersGet (Maybe Text)
pgLanguage
= lens _pgLanguage (\ s a -> s{_pgLanguage = a})
-- | A player ID. A value of me may be used in place of the authenticated
-- player\'s ID.
pgPlayerId :: Lens' PlayersGet Text
pgPlayerId
= lens _pgPlayerId (\ s a -> s{_pgPlayerId = a})
instance GoogleRequest PlayersGet where
type Rs PlayersGet = Player
type Scopes PlayersGet =
'["https://www.googleapis.com/auth/games",
"https://www.googleapis.com/auth/plus.login"]
requestClient PlayersGet'{..}
= go _pgPlayerId _pgConsistencyToken _pgLanguage
(Just AltJSON)
gamesService
where go
= buildClient (Proxy :: Proxy PlayersGetResource)
mempty
| rueshyna/gogol | gogol-games/gen/Network/Google/Resource/Games/Players/Get.hs | mpl-2.0 | 3,666 | 0 | 14 | 869 | 487 | 288 | 199 | 72 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Storage.Objects.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an object\'s metadata. This method supports patch semantics.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.objects.patch@.
module Network.Google.Resource.Storage.Objects.Patch
(
-- * REST Resource
ObjectsPatchResource
-- * Creating a Request
, objectsPatch
, ObjectsPatch
-- * Request Lenses
, opIfMetagenerationMatch
, opIfGenerationNotMatch
, opIfGenerationMatch
, opPredefinedACL
, opBucket
, opPayload
, opIfMetagenerationNotMatch
, opObject
, opProjection
, opGeneration
) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.objects.patch@ method which the
-- 'ObjectsPatch' request conforms to.
type ObjectsPatchResource =
"storage" :>
"v1" :>
"b" :>
Capture "bucket" Text :>
"o" :>
Capture "object" Text :>
QueryParam "ifMetagenerationMatch" (Textual Int64) :>
QueryParam "ifGenerationNotMatch" (Textual Int64) :>
QueryParam "ifGenerationMatch" (Textual Int64) :>
QueryParam "predefinedAcl" ObjectsPatchPredefinedACL
:>
QueryParam "ifMetagenerationNotMatch" (Textual Int64)
:>
QueryParam "projection" ObjectsPatchProjection :>
QueryParam "generation" (Textual Int64) :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Object :> Patch '[JSON] Object
-- | Updates an object\'s metadata. This method supports patch semantics.
--
-- /See:/ 'objectsPatch' smart constructor.
data ObjectsPatch = ObjectsPatch'
{ _opIfMetagenerationMatch :: !(Maybe (Textual Int64))
, _opIfGenerationNotMatch :: !(Maybe (Textual Int64))
, _opIfGenerationMatch :: !(Maybe (Textual Int64))
, _opPredefinedACL :: !(Maybe ObjectsPatchPredefinedACL)
, _opBucket :: !Text
, _opPayload :: !Object
, _opIfMetagenerationNotMatch :: !(Maybe (Textual Int64))
, _opObject :: !Text
, _opProjection :: !(Maybe ObjectsPatchProjection)
, _opGeneration :: !(Maybe (Textual Int64))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ObjectsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'opIfMetagenerationMatch'
--
-- * 'opIfGenerationNotMatch'
--
-- * 'opIfGenerationMatch'
--
-- * 'opPredefinedACL'
--
-- * 'opBucket'
--
-- * 'opPayload'
--
-- * 'opIfMetagenerationNotMatch'
--
-- * 'opObject'
--
-- * 'opProjection'
--
-- * 'opGeneration'
objectsPatch
:: Text -- ^ 'opBucket'
-> Object -- ^ 'opPayload'
-> Text -- ^ 'opObject'
-> ObjectsPatch
objectsPatch pOpBucket_ pOpPayload_ pOpObject_ =
ObjectsPatch'
{ _opIfMetagenerationMatch = Nothing
, _opIfGenerationNotMatch = Nothing
, _opIfGenerationMatch = Nothing
, _opPredefinedACL = Nothing
, _opBucket = pOpBucket_
, _opPayload = pOpPayload_
, _opIfMetagenerationNotMatch = Nothing
, _opObject = pOpObject_
, _opProjection = Nothing
, _opGeneration = Nothing
}
-- | Makes the operation conditional on whether the object\'s current
-- metageneration matches the given value.
opIfMetagenerationMatch :: Lens' ObjectsPatch (Maybe Int64)
opIfMetagenerationMatch
= lens _opIfMetagenerationMatch
(\ s a -> s{_opIfMetagenerationMatch = a})
. mapping _Coerce
-- | Makes the operation conditional on whether the object\'s current
-- generation does not match the given value.
opIfGenerationNotMatch :: Lens' ObjectsPatch (Maybe Int64)
opIfGenerationNotMatch
= lens _opIfGenerationNotMatch
(\ s a -> s{_opIfGenerationNotMatch = a})
. mapping _Coerce
-- | Makes the operation conditional on whether the object\'s current
-- generation matches the given value.
opIfGenerationMatch :: Lens' ObjectsPatch (Maybe Int64)
opIfGenerationMatch
= lens _opIfGenerationMatch
(\ s a -> s{_opIfGenerationMatch = a})
. mapping _Coerce
-- | Apply a predefined set of access controls to this object.
opPredefinedACL :: Lens' ObjectsPatch (Maybe ObjectsPatchPredefinedACL)
opPredefinedACL
= lens _opPredefinedACL
(\ s a -> s{_opPredefinedACL = a})
-- | Name of the bucket in which the object resides.
opBucket :: Lens' ObjectsPatch Text
opBucket = lens _opBucket (\ s a -> s{_opBucket = a})
-- | Multipart request metadata.
opPayload :: Lens' ObjectsPatch Object
opPayload
= lens _opPayload (\ s a -> s{_opPayload = a})
-- | Makes the operation conditional on whether the object\'s current
-- metageneration does not match the given value.
opIfMetagenerationNotMatch :: Lens' ObjectsPatch (Maybe Int64)
opIfMetagenerationNotMatch
= lens _opIfMetagenerationNotMatch
(\ s a -> s{_opIfMetagenerationNotMatch = a})
. mapping _Coerce
-- | Name of the object. For information about how to URL encode object names
-- to be path safe, see Encoding URI Path Parts.
opObject :: Lens' ObjectsPatch Text
opObject = lens _opObject (\ s a -> s{_opObject = a})
-- | Set of properties to return. Defaults to full.
opProjection :: Lens' ObjectsPatch (Maybe ObjectsPatchProjection)
opProjection
= lens _opProjection (\ s a -> s{_opProjection = a})
-- | If present, selects a specific revision of this object (as opposed to
-- the latest version, the default).
opGeneration :: Lens' ObjectsPatch (Maybe Int64)
opGeneration
= lens _opGeneration (\ s a -> s{_opGeneration = a})
. mapping _Coerce
instance GoogleRequest ObjectsPatch where
type Rs ObjectsPatch = Object
type Scopes ObjectsPatch =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/devstorage.full_control"]
requestClient ObjectsPatch'{..}
= go _opBucket _opObject _opIfMetagenerationMatch
_opIfGenerationNotMatch
_opIfGenerationMatch
_opPredefinedACL
_opIfMetagenerationNotMatch
_opProjection
_opGeneration
(Just AltJSON)
_opPayload
storageService
where go
= buildClient (Proxy :: Proxy ObjectsPatchResource)
mempty
| rueshyna/gogol | gogol-storage/gen/Network/Google/Resource/Storage/Objects/Patch.hs | mpl-2.0 | 7,369 | 0 | 22 | 1,852 | 1,125 | 643 | 482 | 153 | 1 |
{-# LANGUAGE CPP #-}
import qualified Control.Exception as E
import Control.Monad (filterM, join, liftM2, mapM_, unless, when)
import qualified Data.ByteString.Lazy as B
import Data.Char ( ord )
import Data.Functor ( (<$>) )
import Data.List (foldl', foldr, intersperse, intercalate, nub, lookup, isPrefixOf, isInfixOf)
import Data.List.Split (splitOn)
import Data.Maybe (fromJust, isNothing, isJust, listToMaybe)
import Distribution.Compat.Exception (catchIO)
import Distribution.PackageDescription
import Distribution.Pretty(prettyShow)
import Distribution.Simple
import Distribution.Simple.InstallDirs (InstallDirs(..))
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo, localPkgDescr, installedPkgs, withPrograms, buildDir, absoluteInstallDirs)
import Distribution.Simple.PackageIndex(SearchResult (..), searchByName )
import Distribution.Simple.Program (ConfiguredProgram (..), lookupProgram, runProgram, simpleProgram, locationPath)
import Distribution.Simple.Setup ( BuildFlags, ConfigFlags
, CopyDest(..), CopyFlags, copyVerbosity
, InstallFlags, installVerbosity
, fromFlag, fromFlagOrDefault, copyDest
)
import Distribution.Simple.Utils ( installOrdinaryFile
, IOData(..)
, IODataMode(..)
, rawSystemExitWithEnv
, rawSystemStdInOut
)
import Distribution.System (OS (..), Arch (..), buildOS, buildArch)
import Distribution.Verbosity (Verbosity, normal, verbose)
import Distribution.Version(Version(..))
import System.Directory ( createDirectoryIfMissing, doesFileExist
, findExecutable, getCurrentDirectory
, getDirectoryContents, getModificationTime
)
import System.Environment (lookupEnv, getEnvironment)
import System.Exit (ExitCode (..), die, exitFailure)
import System.FilePath ((</>), (<.>), replaceExtension, takeFileName, dropFileName, addExtension, takeDirectory)
import System.IO (hPutStrLn, readFile, stderr)
import System.IO.Error (isDoesNotExistError)
import System.IO.Unsafe (unsafePerformIO)
import qualified System.Process as Process
import System.Process (system, readProcess)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Some utility functions
whenM :: Monad m => m Bool -> m () -> m ()
whenM mp e = mp >>= \p -> when p e
-- Find the first element in a list that matches a condition
findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
findM _ [] = return Nothing
findM mp (x : xs) =
do
r <- mp x
if r
then return $ Just x
else findM mp xs
main :: IO ()
main = defaultMainWithHooks simpleUserHooks
{ confHook = myConfHook
, buildHook = myBuildHook
, copyHook = myCopyHook
, instHook = myInstHook
}
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
sourceDirectory :: FilePath
includeDirectory :: FilePath
sourceDirectory = "cpp"
includeDirectory = "include"
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
rawShellSystemStdInOut :: Verbosity -- Verbosity level
-> FilePath -- Path to command
-> [String] -- Command arguments
-> IO (String, String, ExitCode) -- (Command result, Errors, Command exit status)
rawShellSystemStdInOut v f as =
rawSystemStdInOut v "sh" (f:as) Nothing Nothing Nothing IODataModeText >>=
\(IODataText result, errors, exitStatus) -> return (result, errors, exitStatus)
isWindowsMsys :: IO Bool
isWindowsMsys = (buildOS == Windows&&) . isJust <$> lookupEnv "MSYSTEM"
-- Comment out type signature because of a Cabal API change from 1.6 to 1.7
myConfHook (pkg0, pbi) flags = do
let whenExecutableNotFound = whenM (isNothing <$> findExecutable "wx-config")
mswMsys <- isWindowsMsys
if mswMsys then do
(r, e, c) <- rawShellSystemStdInOut normal "wx-config" ["--release"]
unless (c == ExitSuccess) $
-- In case you use Stack on Windows which internally use MSYS.
-- From Windows Console rawShellSystemStdInOut doesn't work
whenExecutableNotFound $ do
putStrLn ("Error: MSYS environment wx-config script not found, please install wx-config before installing wxc" ++ "\n"
++ e ++ "\n"
++ show c)
exitFailure
else
whenExecutableNotFound $
do
putStrLn "Error: wx-config not found, please install wx-config before installing wxc"
exitFailure
whenM bitnessMismatch
exitFailure
wxVersion <- checkWxVersion
generateHeaders wxVersion
lbi <- confHook simpleUserHooks (pkg0, pbi) flags
let lpd = localPkgDescr lbi
let lib = fromJust (library lpd)
let libbi = libBuildInfo lib
let custom_bi = customFieldsBI libbi
wx <- fmap parseWxConfig (readWxConfig wxVersion) >>= deMsysPaths
let libbi' = libbi
{ extraLibDirs = extraLibDirs libbi ++ extraLibDirs wx
-- Remove wx libraries from here on windows because archive names differ from dlls
-- causing GHCI to fail to load them
, extraLibs = if buildOS == Windows then
extraLibs libbi
else
extraLibs libbi ++ reverse (extraLibs wx)
, ldOptions = ldOptions libbi ++ ldOptions wx
, frameworks = frameworks libbi ++ frameworks wx
, includeDirs = includeDirs libbi ++ includeDirs wx
, ccOptions = ccOptions libbi ++ ccOptions wx ++ ["-DwxcREFUSE_MEDIACTRL"]
}
let lib' = lib { libBuildInfo = libbi' }
let lpd' = lpd { library = Just lib' }
return $ lbi { localPkgDescr = lpd' }
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
generateHeaders :: String -> IO ()
generateHeaders wxVersion =
do
writeFile ("src" </> "include" </> "wxc_def.h")
$ cppDefinition "wxVERSION_NUMBER" (wxVERSION_NUMBER wxVersion)
cppDefinition :: Show a => String -> a -> String
cppDefinition name value =
"#define " ++ name ++ " " ++ show value ++ "\n"
wxVERSION_NUMBER :: String -> Int
wxVERSION_NUMBER wxVersion =
let (major : minor : remaining) = splitOn "." wxVersion in
read major * 1000 + read minor * 100 +
case remaining of
[] -> 0
[revision] -> read revision
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
{-
Bitness check
-}
data Bitness
= Bits32
| Bits64
| Universal
| Unknown
deriving Eq
instance Show Bitness where
show Bits32 = "32"
show Bits64 = "64"
show Universal = "Universal"
show Unknown = "Unknown"
data CheckResult
= OK
| NotOK Bitness Bitness
| NotChecked
deriving Eq
{-
Extract bitness info from a dynamic library and compare to the
bitness of this program. Works for architectures I386 and X86_64.
-}
checkBitness :: FilePath -> IO CheckResult
checkBitness file =
if thisBitness == Unknown
then return NotChecked
else
if buildOS == Windows
then compareBitness <$> getWindowsBitness file
else compareBitness . readBitness <$> readProcess "file" [file] ""
where
getWindowsBitness :: FilePath -> IO Bitness
getWindowsBitness fp =
do
contents <- B.unpack <$> B.readFile file
if take 2 contents /= [0x4D, 0x5A] -- "MZ"
then return Unknown -- The file is not an executable
else
do
-- The offset of the PE header is at 0x3C.
-- In the PE header, after "PE\0\0", one finds the type of
-- machine the executable is compiled for.
-- According to
-- http://www.opensource.apple.com/source/cctools/cctools-795/include/coff/ms_dos_stub.h?txt
-- the index is four byte long. It is in little endian order.
--
-- N.B. Might need an update when Windows runs on ARM
let machineOffsetList = reverse $ take 4 $ drop 0x3C $ contents
let machineOffset = listToInt machineOffsetList + 4
return $
case contents !! machineOffset of
0x4C -> Bits32 -- "The file is 32 bit"
0x64 -> Bits64 -- "The file is 64 bit"
_ -> Unknown -- "The bitness is not recognized"
where
listToInt :: Integral a => [a] -> Int
listToInt xs = foldl1 (\x y -> 256 * x + y) (map fromIntegral xs)
compareBitness :: Bitness -> CheckResult
compareBitness thatBitness =
if thatBitness == Unknown
then NotChecked
else
if thisBitness == thatBitness ||
thatBitness == Universal
then OK
else NotOK thisBitness thatBitness
thisBitness =
case buildArch of
I386 -> Bits32
X86_64 -> Bits64
_ -> Unknown
readBitness :: String -> Bitness
readBitness string
| anyInString [ " i386", " 80386"
, " 32-bit", "AMD386" ] = Bits32
| anyInString [ " x86_64", " 64-bit" ] = Bits64
| anyInString [ "universal binary" ] = Universal
| otherwise = Unknown
where
anyInString :: [String] -> Bool
anyInString strings = any (`isInfixOf` string) strings
{-
Return True if this program is 32 bit and the wxWidgets dynamic
libraries are 64 bits or vice versa. Also, print a result message.
If there is insufficient data, or the OS is not handled, return
False, to prevent unnecessary abortion of the install procedure
N.B. If the installation procedure is simplified, we cannot
use the file-command on Windows anymore, as it is part of MSYS
N.B. This does not work if we are cross-compiling
-}
bitnessMismatch :: IO Bool
bitnessMismatch =
if buildOS `elem` [Windows, Linux, OSX]
then check
else return False -- Other OSes are not checked
where
check =
do
maybeWxwin <- lookupEnv "WXWIN"
maybeWxcfg <- lookupEnv "WXCFG"
if isNothing maybeWxwin || isNothing maybeWxcfg
then return False -- Insufficient data, just continue installing
else check2 (fromJust maybeWxwin) (fromJust maybeWxcfg)
check2 wxwin wxcfg =
do
let path = normalisePath $ wxwin </> "lib" </> wxcfg </> ".."
maybeDynamicLibraryName <- getDynamicLibraryName path
case maybeDynamicLibraryName of
Nothing ->
putStrLn "Could not find a dynamic library to check bitness, continuing installation" >>
return False
Just dynamicLibraryName ->
check3 path dynamicLibraryName
check3 path dynamicLibraryName =
do
bitnessCheckResult <- checkBitness $ path </> dynamicLibraryName
case bitnessCheckResult of
NotOK thisBitness thatBitness ->
do
putStrLn $ "Error: The bitness does not match,"
++ " wxHaskell is being compiled as "
++ show thisBitness ++ " bit, the file "
++ dynamicLibraryName ++ " is "
++ show thatBitness ++ " bit."
return True
OK ->
do
putStrLn $ "The bitness is correct"
return False
NotChecked ->
do
putStrLn $ "The bitness is not checked"
return False
getDynamicLibraryName :: FilePath -> IO (Maybe String)
getDynamicLibraryName path =
listToMaybe . filter isLibrary <$> getDirectoryContents path
`E.onException` return Nothing
where
isLibrary x = any (`isPrefixOf` x) ["libwx_base", "wxbase"] &&
any (`isInfixOf` x) [".dll", ".dylib", ".so."]
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- A list of wxWidgets versions that can be handled by this version of wxHaskell
wxCompatibleVersions = ["3.0", "2.9"] -- Preferred version first
checkWxVersion :: IO String
checkWxVersion =
do
maybeWxVersion <- findWxVersion
case maybeWxVersion of
Nothing ->
error ("This version of wxc requires one of the following wxWidgets versions to be available: "
++ show wxCompatibleVersions
)
Just wxVersion ->
return wxVersion
-- Get the preprocessor/compiler/linker options used for the most recent
-- compatible wxWidgets installed.
-- Abort the setup procedure when no proper version of wxWidgets is found
readWxConfig :: String -> IO String
readWxConfig wxVersion =
do
putStrLn ("Configuring wxc to build against wxWidgets " ++ wxVersion)
#if defined(freebsd_HOST_OS) || defined (netbsd_HOST_OS)
putStrLn "defined(freebsd_HOST_OS) || defined (netbsd_HOST_OS)"
-- find GL/glx.h on non-Linux systems
let glIncludeDirs = readProcess "pkg-config" ["--cflags", "gl"] "" `E.onException` return ""
#else
let glIncludeDirs = return ""
#endif
-- Additional libraries that are needed for wxc
-- Note: "all" option doesn't bring them on the popular wx-config-win
-- (https://github.com/wxHaskell/wxHaskell/tree/master/wx-config-win,
-- other versions can be found at https://github.com/kowey/wx-config-win
-- and branches of it)
let neededLibs = [intercalate "," ["richtext", "xrc", "qa", "html", "adv", "core", "xml", "net", "base", "aui", "propgrid", "ribbon", "gl", "stc"]]
-- The Windows port of wx-config doesn't let you specify a version (yet)
isMsys <- isWindowsMsys
case (buildOS, isMsys) of
-- wx-config-win does not list all libraries if --cppflags comes after --libs :-(
(Windows, False) -> liftM2 (++) glIncludeDirs (wx_config $ ["--cppflags", "--libs"] ++ neededLibs)
(Windows, True) -> wx_config (["--gl-libs", "--cppflags", "--libs"] ++ neededLibs)
_ -> liftM2 (++) glIncludeDirs (wx_config ["--version=" ++ wxVersion, "--libs", "all", "--cppflags"])
wx_config :: [String] -> IO String
wx_config parms = do
let runExecutable failureAction =
readProcess "wx-config" parms "" `E.onException` failureAction
b <- isWindowsMsys
if b
then do
(r, e, c) <- rawShellSystemStdInOut normal "wx-config" parms
if c == ExitSuccess then
return r
else runExecutable $ do
putStrLn $ "Error: Failed to execute wx-config\n" ++ e
exitFailure
else
runExecutable $ return ""
-- Try to find a compatible version of wxWidgets
-- (a version that can be handled by this version of wxHaskell)
findWxVersion :: IO (Maybe String)
findWxVersion =
if buildOS == Windows
-- The Windows port of wx-config doesn't let you specify a version, nor query the full version,
-- accordingly we just check what version is installed (which is returned with --release)
then checkCompatibility <$> readVersionWindows
else findM (fmap isCompatible . readVersion) wxCompatibleVersions
where
readVersionWindows :: IO String
readVersionWindows =
wx_config ["--version"] -- Sample output: 3.0.1
readVersion :: String -> IO String
readVersion x =
wx_config ["--version=" ++ x, "--version-full"] -- Sample output: 3.0.1.0
isCompatible :: String -> Bool
isCompatible xs =
any (`isPrefixOf` xs) wxCompatibleVersions
checkCompatibility :: String -> Maybe String
checkCompatibility version =
if isCompatible version
then Just version
else Nothing
parseWxConfig :: String -> BuildInfo
parseWxConfig s =
helper emptyBuildInfo (words s)
where
helper b ("-framework":w:ws) = helper (b { frameworks = w : frameworks b }) ws
helper b (w:ws) = helper (f b w) ws
helper b [] = b
f b w =
case w of
('-':'L':v) -> b { extraLibDirs = v : extraLibDirs b }
('-':'l':v) -> b { extraLibs = v : extraLibs b }
('-':'I':v) -> b { includeDirs = v : includeDirs b }
('-':'D':_) -> b { ccOptions = w : ccOptions b }
_ -> b
deMsysPaths :: BuildInfo -> IO BuildInfo
deMsysPaths bi = do
b <- isWindowsMsys
if b
then do
let cor ph = do
(IODataText r, e, c ) <- rawSystemStdInOut normal "sh" ["-c", "cd " ++ ph ++ "; pwd -W"] Nothing Nothing Nothing IODataModeText
unless (c == ExitSuccess) (putStrLn ("Error: failed to convert MSYS path to native path \n" ++ e) >> exitFailure)
return . head . lines $ r
elds <- mapM cor (extraLibDirs bi)
incds <- mapM cor (includeDirs bi)
return $ bi {extraLibDirs = elds, includeDirs = incds}
else
return bi
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- | Extend the standard build hook to build a shared library for wxc - this will statically link
-- any libraries which are unavailable as shared variants. This is mainly a work-around for the
-- fact that GHCi needs to load shared libraries at run-time, and that the Windows MinGW environment
-- is shipped with only a static version of libstdc++.
-- TODO: Does not currently create the build output directory.
myBuildHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()
myBuildHook pkg_descr local_bld_info user_hooks bld_flags =
do
-- Extract the custom fields customFieldsPD where field name is x-dll-sources
let lib = fromJust (library pkg_descr)
lib_bi = libBuildInfo lib
custom_bi = customFieldsBI lib_bi
dll_name = fromJust (lookup "x-dll-name" custom_bi)
dll_srcs = (lines . fromJust) (lookup "x-dll-sources" custom_bi)
dll_libs = (lines . fromJust) (lookup "x-dll-extra-libraries" custom_bi)
cc_opts = ccOptions lib_bi
ld_opts = ldOptions lib_bi
inc_dirs = includeDirs lib_bi
lib_dirs = extraLibDirs lib_bi
libs = extraLibs lib_bi
bld_dir = buildDir local_bld_info
progs = withPrograms local_bld_info
gcc = fromJust (lookupProgram (simpleProgram "gcc") progs)
ver = (pkgVersion . package) pkg_descr
inst_lib_dir = libdir $ absoluteInstallDirs pkg_descr local_bld_info NoCopyDest
-- Compile C/C++ sources - output directory is dist/build/src/cpp
putStrLn "Building wxc"
objs <- mapM (compileCxx gcc cc_opts inc_dirs bld_dir) dll_srcs
-- Link C/C++ sources as a DLL - output directory is dist/build
if buildOS == Windows then do
-- Since we removed wx libraries in myConfHook we need to add them here when linking wxc.dll
wx <- fmap parseWxConfig (checkWxVersion >>= readWxConfig) >>= deMsysPaths
linkSharedLib gcc ld_opts lib_dirs (libs ++ reverse (extraLibs wx) ++ dll_libs) objs ver bld_dir dll_name inst_lib_dir
else
linkSharedLib gcc ld_opts lib_dirs (libs ++ dll_libs) objs ver bld_dir dll_name inst_lib_dir
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- | Return any compiler options required to support shared library creation
osCompileOpts :: [String] -- ^ Platform-specific compile options
osCompileOpts =
case buildOS of
Windows -> ["-DBUILD_DLL"]
OSX -> ["-fPIC"]
_ -> ["-fPIC"]
sharedLibName :: Version -- ^ Version information to be used for Unix shared libraries
-> String -- ^ Name of the shared library
-> String
sharedLibName ver basename =
case buildOS of
Windows -> addExtension basename ".dll"
OSX -> "lib" ++ addExtension basename ".dylib"
_ -> "lib" ++ basename ++ ".so." ++ full_ver
where
full_ver = prettyShow ver
-- | Return any linker options required to support shared library creation
linkCxxOpts :: Version -- ^ Version information to be used for Unix shared libraries
-> FilePath -- ^ Directory in which library will be built
-> String -- ^ Name of the shared library
-> String -- ^ Absolute path of the shared library
-> [String] -- ^ List of options which can be applied to 'runProgram'
linkCxxOpts ver out_dir basename basepath =
case buildOS of
Windows -> ["-Wl,--dll", "-shared",
"-o", out_dir </> sharedLibName ver basename,
"-Wl,--out-implib," ++ "lib" ++ addExtension basename ".a",
"-Wl,--export-all-symbols", "-Wl,--enable-auto-import",
"-Wl,-no-undefined,--enable-runtime-pseudo-reloc"]
OSX -> ["-dynamiclib",
"-o", out_dir </> sharedLibName ver basename,
"-install_name", basepath </> sharedLibName ver basename,
"-Wl,-undefined,dynamic_lookup"]
_ -> ["-shared",
"-Wl,-soname,lib" ++ basename ++ ".so",
"-o", out_dir </> sharedLibName ver basename]
-- | Compile a single source file using the configured gcc, if the object file does not yet
-- exist, or is older than the source file.
-- TODO: Does not do dependency resolution properly
compileCxx :: ConfiguredProgram -- ^ Program used to perform C/C++ compilation (gcc)
-> [String] -- ^ Compile options provided by Cabal and wx-config
-> [String] -- ^ Include paths provided by Cabal and wx-config
-> FilePath -- ^ Base output directory
-> FilePath -- ^ Path to source file
-> IO FilePath -- ^ Path to generated object code
compileCxx gcc opts incls out_path cxx_src =
do
let includes = map ("-I" ++) incls
out_path' = normalisePath out_path
cxx_src' = normalisePath cxx_src
out_file = out_path' </> dropFileName cxx_src </> replaceExtension (takeFileName cxx_src) ".o"
out = ["-c", cxx_src', "-o", out_file]
opts' = opts ++ osCompileOpts
do_it <- needsCompiling cxx_src out_file
when do_it $ createDirectoryIfMissing True (dropFileName out_file) >>
runProgram verbose gcc (includes ++ opts' ++ out)
return out_file
-- | Return True if obj does not exist or is older than src.
-- Real dependency checking would be nice here...
needsCompiling :: FilePath -- ^ Path to source file
-> FilePath -- ^ Path to object file
-> IO Bool -- ^ True if compilation required
needsCompiling src obj =
do
has_obj <- doesFileExist obj
if has_obj
then do
mtime_src <- getModificationTime src
mtime_obj <- getModificationTime obj
if mtime_obj < mtime_src then return True else return False
else
return True
-- | Create a dynamically linked library using the configured ld.
linkSharedLib :: ConfiguredProgram -- ^ Program used to perform linking
-> [String] -- ^ Linker options supplied by Cabal
-> [FilePath] -- ^ Library directories
-> [String] -- ^ Libraries
-> [String] -- ^ Objects
-> Version -- ^ wxCore version (wxC has same version number)
-> FilePath -- ^ Directory in which library will be generated
-> String -- ^ Name of the shared library
-> String -- ^ Absolute path of the shared library
-> IO ()
linkSharedLib gcc opts lib_dirs libs objs ver out_dir dll_name dll_path =
do
let lib_dirs' = map (\d -> "-L" ++ normalisePath d) lib_dirs
out_dir' = normalisePath out_dir
opts' = opts ++ linkCxxOpts ver out_dir' dll_name dll_path
objs' = map normalisePath objs
libs' = ["-lstdc++"] ++ map ("-l" ++) libs
target = out_dir' </> sharedLibName ver dll_name
link <- linkingNeeded target objs'
when link $
do
putStrLn "Linking wxc"
runProgram verbose gcc (opts' ++ objs' ++ lib_dirs' ++ libs')
-- | Check if one of the input files is more recent then the output file
linkingNeeded :: FilePath -> [FilePath] -> IO Bool
linkingNeeded output input =
do
fileExists <- doesFileExist output
if not fileExists
then return True
else
do
mostRecentModificationTime <- maximum <$> mapM getModificationTime input
outputModificationTime <- getModificationTime output
return $ mostRecentModificationTime > outputModificationTime
-- | The 'normalise' implementation in System.FilePath does not meet the requirements of
-- calling and/or running external programs on Windows particularly well as it does not
-- normalise the '/' character to '\\'. The problem is that some MinGW programs do not
-- like to see paths with a mixture of '/' and '\\'. Since we are calling out to these,
-- we require a stricter normalisation.
normalisePath :: FilePath -> FilePath
normalisePath = case buildOS of
Windows -> dosifyFilePath
_ -> unixifyFilePath
-- | Replace a character in a String with some other character
replace :: Char -- ^ Character to replace
-> Char -- ^ Character with which to replace
-> String -- ^ String in which to replace
-> String -- ^ Transformed string
replace old new = map replace'
where
replace' elem = if elem == old then new else elem
unixifyFilePath = replace '\\' '/'
dosifyFilePath = replace '/' '\\'
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- | Run ldconfig in `path`, creating an appropriate `.so` file
ldconfig :: FilePath -> IO ()
ldconfig path = case buildOS of
Windows -> return ()
OSX -> return ()
_ ->
do
ld_exit_code <- system ("/sbin/ldconfig -n " ++ path)
case ld_exit_code of
ExitSuccess -> return ()
otherwise -> error "Couldn't execute ldconfig, ensure it is on your path"
-- | Create an additional symlink for Stack GHCi to work properly. See Github PR #33.
mkSymlink :: FilePath -> IO ()
mkSymlink path = case buildOS of
Windows -> return ()
OSX -> return ()
_ ->
do
ln_exit_code <- system ("ln -sf " ++ target ++ " " ++ link_name)
case ln_exit_code of
ExitSuccess -> return ()
otherwise -> error "Couldn't execute ln, ensure that it is on your path."
where
target = path </> "libwxc.so"
link_name = takeDirectory path </> "libwxc.so"
myCopyHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO ()
myCopyHook = hookHelper (fromFlag . copyVerbosity) (fromFlagOrDefault NoCopyDest . copyDest) (copyHook simpleUserHooks)
myInstHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO ()
myInstHook = hookHelper (fromFlag . installVerbosity) (const NoCopyDest) (instHook simpleUserHooks)
hookHelper ::
(a -> Verbosity) ->
(a -> CopyDest) ->
(PackageDescription -> LocalBuildInfo -> UserHooks -> a -> IO ()) ->
PackageDescription -> LocalBuildInfo -> UserHooks -> a -> IO ()
hookHelper verbosity copydest origHook pkg_descr local_bld_info user_hooks flags =
do
-- Perform simpleUserHooks (copyHook/instHook => to copy installIncludes)
origHook pkg_descr local_bld_info user_hooks flags
-- Copy shared library
let bld_dir = buildDir local_bld_info
ver = (pkgVersion . package) pkg_descr
lib = fromJust (library pkg_descr)
lib_bi = libBuildInfo lib
custom_bi = customFieldsBI lib_bi
dll_name = fromJust (lookup "x-dll-name" custom_bi)
lib_name = sharedLibName ver dll_name
inst_lib_dir = libdir $ absoluteInstallDirs pkg_descr local_bld_info (copydest flags)
installOrdinaryFile (verbosity flags) (bld_dir </> lib_name) (inst_lib_dir </> lib_name)
ldconfig inst_lib_dir
mkSymlink inst_lib_dir
| jacekszymanski/wxHaskell | wxc/Setup.hs | lgpl-2.1 | 29,164 | 13 | 20 | 9,044 | 5,731 | 3,006 | 2,725 | -1 | -1 |
module System.Monitoring.Nrpe (
checkNRPE
, liftNRPE
, IONRPE
, NRPE
-- re-exports lower-level modules
, module System.Monitoring.Nrpe.Protocol
, module System.Monitoring.Nrpe.Nagios
) where
import Data.ByteString (ByteString)
import Control.Applicative ((<$>))
import System.Monitoring.Nrpe.Protocol (Service (..), Result, check)
import System.Monitoring.Nrpe.Nagios (PluginOutput, parseOutput)
type NRPE a = Result (Either String a)
type IONRPE a = IO (NRPE a)
-- Lifts a pure function into an IONRPE.
liftNRPE :: (a -> b) -> IONRPE a -> IONRPE b
liftNRPE = fmap . fmap . fmap
-- Executes and parse an NRPE check result.
checkNRPE :: Service -> ByteString -> IONRPE PluginOutput
checkNRPE s x = fmap parseOutput <$> check s x
| lucasdicioccio/nrpe | src/System/Monitoring/Nrpe.hs | apache-2.0 | 752 | 0 | 7 | 129 | 210 | 125 | 85 | 17 | 1 |
{-# LANGUAGE ViewPatterns #-}
module Language.K3.Codegen.CPP.Materialization.Common where
import Control.Arrow
import Data.Hashable
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Expression
import Language.K3.Core.Type
rollLambdaChain :: K3 Expression -> ([(Identifier, K3 Expression)], K3 Expression)
rollLambdaChain e@(tag &&& children -> (ELambda i, [f])) = let (ies, b) = rollLambdaChain f in ((i, e):ies, b)
rollLambdaChain e = ([], e)
rollAppChain :: K3 Expression -> (K3 Expression, [K3 Expression])
rollAppChain e@(tag &&& children -> (EOperate OApp, [f, x])) = let (f', xs) = rollAppChain f in (f', xs ++ [e])
rollAppChain e = (e, [])
anon :: Int
anon = hashJunctureName "!"
anonS :: Identifier
anonS = "!"
hashJunctureName :: Identifier -> Int
hashJunctureName = hash
isNonScalarType :: K3 Type -> Bool
isNonScalarType t = case t of
(tag -> TString) -> True
(tag &&& children -> (TTuple, cs)) -> any isNonScalarType cs
(tag &&& children -> (TRecord _, cs)) -> any isNonScalarType cs
(tag -> TCollection) -> True
_ -> False
| DaMSL/K3 | src/Language/K3/Codegen/CPP/Materialization/Common.hs | apache-2.0 | 1,095 | 0 | 11 | 174 | 435 | 244 | 191 | 27 | 5 |
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : [email protected]
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
module Compiler.Back.TypeNames where
import Compiler.Types2.TypeInfo (typeModeNames)
import Compiler.Back.Graph
import Compiler.Back.GenDecls
import Data.Maybe (fromMaybe)
import Data.List (stripPrefix)
nameTy :: String -> LfTy
nameTy n = (LfTy n [])
namedTy :: String -> [Ty] -> LfTy
namedTy n l = (LfTy n l)
eqTys :: LfTy -> LfTy
eqTys tin@(LfTy name l) = case (name, map (mapTree eqTys) l) of
-- vectors
("LVec", [et]) -> namedTy "Vec" [et]
-- maps
("VecMap", [Tup [kt, vt],_,_,_]) -> namedTy "Map" [kt, vt]
("LMap", [_,kt,vt,_]) -> namedTy "Map" [kt,vt]
("DMap", [_,kt,vt,_,_,_,_]) -> namedTy "Map" [kt, vt]
-- Get rid of pointers
("Ptr", [(Lf t)]) -> t
("SPtr", [(Lf t)]) -> t
-- everything else the same
other -> tin
-- |Returns true for all types that should be copied by
-- |value rather than by pointer.
copyByVal :: Ty -> Bool
copyByVal ty = case ty of
(Lf (LfTy "SPtr" [Lf (LfTy "VecMap" _)])) -> True
(Lf (LfTy "DMap" l)) -> True
_ -> False
-- |Returns the value to use when creating a fresh instance of this
-- |type.
defaultInitializer :: Monad m => Ty -> Id -> GenM1 m Id
defaultInitializer (Lf lfTy) tyId = case lfTy of
(LfTy "SPtr" [Lf (LfTy "VecMap" _)]) -> return $ "new " ++ (init $ fromMaybe tyId $ stripPrefix "boost::shared_ptr<" tyId)
(LfTy "DMap" l) -> return $ "new " ++ (init $ fromMaybe tyId $ stripPrefix "boost::shared_ptr<" tyId)
other -> return ""
defaultInitializer other tyId = return ""
-- |getTypeName ty. Returns the C++ type
-- |to use for ty, or Nothing if this type should not
-- |be stored as a data structure.
getTypeName :: Monad m => LfTy -> [Maybe Id] -> GenM1 m (Maybe Id)
getTypeName lfTy children = case (lfTy, children) of
-- mirrored type are themselves
--(LfTy "Mirr" [ty], [tid]) -> return $ Just $ fromMaybe (error msg) tid
-- distributed vector
(LfTy "LVec" [et], [tid]) -> return $ Just $ "flocc::vec<" ++ (fromMaybe (error msg) tid) ++ " >"
-- distributed maps
{-(LfTy "DistMap" [kt, vt, kf, pf, nl], [ktid, vtid, _, _, _]) -> return $ Just $ "std::map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++ (fromMaybe (error msg) vtid) ++ " >"
(LfTy "DistHashMap" [kt, v2, kf, pf, nl], [ktid, vtid, _, _, _]) ->
return $ Just $ "dense_hash_map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++
(fromMaybe (error msg) vtid) ++ ", " ++
"hash<" ++ (fromMaybe (error msg) ktid) ++ " >, " ++
"eq" ++ (fromMaybe (error msg) ktid) ++ " >"-}
(LfTy "VecMap" [kvt, pkt, Lf (LfTy "Null" []), projt], [kvtid, pktid, sktid, projtid]) -> -- vec map with null secondary key
return $ Just $ "flocc::vecmap<" ++ (fromMaybe (error $ msg ++ "/elT/"++ (show kvt)) kvtid) ++ ", " ++
(fromMaybe (error $ msg ++ "/priKeyT/"++ (show pkt)) pktid) ++ ", " ++
"char, " ++
(fromMaybe (error $ msg ++ "/projFun/"++ (show projt)) projtid) ++ " >"
(LfTy "VecMap" [kvt, pkt, skt, projt], [kvtid, pktid, sktid, projtid]) -> -- any other vecmap
return $ Just $ "flocc::vecmap<" ++ (fromMaybe (error $ msg ++ "/elT/"++ (show kvt)) kvtid) ++ ", " ++
(fromMaybe (error $ msg ++ "/priKeyT/"++ (show pkt)) pktid) ++ ", " ++
(fromMaybe (error $ msg ++ "/secKeyT/"++ (show skt)) sktid) ++ ", " ++
(fromMaybe (error $ msg ++ "/projFun/"++ (show projt)) projtid) ++ " >"
(LfTy "LMap" [(Lf (LfTy mode [])), kt, v2, sf], [_, ktid, vtid, _]) -> case mode of
-- hash map
"Hsh" -> return $ Just $ "google::dense_hash_map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++
(fromMaybe "char" vtid) ++ ", " ++
"flocc::hasher<" ++ (fromMaybe (error msg) ktid) ++ " >, " ++
"flocc::eq<" ++ (fromMaybe (error msg) ktid) ++ " > >"
(LfTy "MultiMap" [mmKt, kvt], [mmKtid, kvtid]) -> -- a std::multimap
return $ Just $ "std::multimap<" ++ (fromMaybe (error msg) mmKtid) ++ ", " ++
(fromMaybe (error msg) kvtid) ++ " >"
-- redistributer
(LfTy "Reparter" [elT, outT], [elTid, outTid]) ->
return $ Just $ "flocc::reparter<" ++ (fromMaybe (error msg) elTid) ++ ", " ++ (fromMaybe (error msg) outTid) ++ " >"
-- iterators
(LfTy "Iter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::iterator"
(LfTy "ConstIter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::iterator" --"::const_iterator"
(LfTy "IdxIter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::idx_iterator"
-- pointers
(LfTy "Ptr" [vTy], [vTId]) -> return $ Just $ (fromMaybe (error msg) vTId) ++ "*"
(LfTy "SPtr" [vTy], [vTId]) -> return $ Just $ "boost::shared_ptr<" ++ (fromMaybe (error msg) vTId) ++ " >"
-- distributed array
{-(LfTy "DistArr" [idxTy, valty, layoutF, invLayoutF, partF, dims, mirrDims], [idxTid, valTid, _, _, _, _, _]) -> do
-- get number of int's in flattened idxTy
let flatIdxTy = flattenTree idxTy
-- return template class
return $ Just $ "SubArray<" ++ (fromMaybe (error msg) valTid) ++ ", " ++ (show $ length flatIdxTy) ++ ">"
-- distributed array
(LfTy "DistArrRoot" [idxTy, valty, layoutF, invLayoutF, partF, dims, mirrDims], [idxTid, valTid, _, _, _, _, _]) -> do
-- get number of int's in flattened idxTy
let flatIdxTy = flattenTree idxTy
-- return template class
return $ Just $ "RootArray<" ++ (fromMaybe (error msg) valTid) ++ ", " ++ (show $ length flatIdxTy) ++ ">"
(LfTy "DistArr1D" [valTy, kf, vf, nl], [tid, _, _, _]) -> return $ Just $ "std::vector<" ++ (fromMaybe (error msg) tid) ++ " >"-}
-- mpi datatype
(LfTy "MPIType" [], _) -> return $ Just "MPI::Datatype"
-- used for distribution meta-data, not actual data types
{-(LfTy "NullFun" [], _) -> return Nothing
(LfTy "NullDim" [], _) -> return Nothing
(LfTy "MirrDims" [], _) -> return Nothing
(LfTy "DimDists" _, _) -> return Nothing
(LfTy "Fringe" [], _) -> return Nothing
(LfTy "Mirr" [], _) -> return Nothing
(LfTy ('P':'a':'r':'t':_) [], _) -> return Nothing
-- from DistHistDemo
(LfTy "AllNodes" [], _) -> return Nothing
(LfTy "snd" [], _) -> return Nothing
(LfTy "fst" [], _) -> return Nothing
(LfTy "modN" l, _) -> return Nothing
(LfTy "Snd" [], _) -> return Nothing
(LfTy "Fst" [], _) -> return Nothing
(LfTy "ModN" l, _) -> return Nothing-}
-- functions (TODO create fun_class?)
(FunTy graph, _) -> return Nothing
-- type modes
(LfTy name [], _) -> case elem name typeModeNames of
True -> return Nothing
False -> error $ "TypeNames:getTypeName: can't return type name for " ++ (show lfTy)
_ -> error $ "TypeNames:getTypeName: can't return type name for " ++ (show lfTy)
where msg = "getTypeName:couldn't generate type name for " ++ (show lfTy)
-- TODO ADD CONSTRUCTORS TO SUBARRAY, SO WE CAN ALWAYS CREATE SUBARRAYS, AND THEY CAN
-- CREATE NEW UNDERLYING ROOT ARRAYS, IF NONE IS GIVEN
getMPITypeName :: Monad m => Ty -> Maybe Id -> GenM1 m (Maybe (Id, Code))
getMPITypeName ty idv = case ty of
-- scalars
Lf lty -> case lty of
-- scalar types
_ | ty == intTy -> return $ Just ("MPI::INT", "")
_ | ty == uintTy -> return $ Just ("MPI::UNSIGNED", "")
_ | ty == floatTy -> return $ Just ("MPI::DOUBLE", "")
_ | ty == boolTy -> return $ Just ("MPI::C_BOOL", "")
_ | ty == nullTy -> return $ Nothing
-- structs (not needed as packed)
-- TODO just use packed and size of struct
-- arrays
-- TODO generate data type for this collection
-- other collections
-- TODO just use n copies of struct mpi data type
other -> error $ "cant generate mpi type for " ++ (show ty)
| flocc-net/flocc | v0.1/Compiler/Back/TypeNames.hs | apache-2.0 | 8,904 | 0 | 24 | 2,350 | 2,062 | 1,105 | 957 | 74 | 16 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsItemGroup_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:25
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsItemGroup_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
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 (QGraphicsItemGroup ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsItemGroup_unSetUserMethod" qtc_QGraphicsItemGroup_unSetUserMethod :: Ptr (TQGraphicsItemGroup a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsItemGroupSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsItemGroup ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsItemGroupSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsItemGroup ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsItemGroupSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsItemGroup setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsItemGroup_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsItemGroup_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup 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_QGraphicsItemGroup_setUserMethod" qtc_QGraphicsItemGroup_setUserMethod :: Ptr (TQGraphicsItemGroup a) -> CInt -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsItemGroup :: (Ptr (TQGraphicsItemGroup x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsItemGroup_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsItemGroup setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsItemGroup_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsItemGroup_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup 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 (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsItemGroup setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsItemGroup_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsItemGroup_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup 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_QGraphicsItemGroup_setUserMethodVariant" qtc_QGraphicsItemGroup_setUserMethodVariant :: Ptr (TQGraphicsItemGroup a) -> CInt -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsItemGroup :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsItemGroup_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsItemGroup setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsItemGroup_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsItemGroup_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup 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 (QGraphicsItemGroup ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsItemGroup_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsItemGroup_unSetHandler" qtc_QGraphicsItemGroup_unSetHandler :: Ptr (TQGraphicsItemGroup a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsItemGroupSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsItemGroup_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler1" qtc_QGraphicsItemGroup_setHandler1 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup1 :: (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 QqqboundingRect_h (QGraphicsItemGroup ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsItemGroup_boundingRect" qtc_QGraphicsItemGroup_boundingRect :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsItemGroupSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsItemGroup ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsItemGroup_boundingRect_qth" qtc_QGraphicsItemGroup_boundingRect_qth :: Ptr (TQGraphicsItemGroup a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsItemGroupSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler2" qtc_QGraphicsItemGroup_setHandler2 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup2 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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_QGraphicsItemGroup_setHandler3" qtc_QGraphicsItemGroup_setHandler3 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup3 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr 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 QisObscuredBy_h (QGraphicsItemGroup ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_isObscuredBy" qtc_QGraphicsItemGroup_isObscuredBy :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem" qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler4" qtc_QGraphicsItemGroup_setHandler4 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup4 :: (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 QopaqueArea_h (QGraphicsItemGroup ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsItemGroup_opaqueArea" qtc_QGraphicsItemGroup_opaqueArea :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsItemGroupSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_opaqueArea cobj_x0
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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_QGraphicsItemGroup_setHandler5" qtc_QGraphicsItemGroup_setHandler5 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup5 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
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 Qpaint_h (QGraphicsItemGroup ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItemGroup_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsItemGroup_paint1" qtc_QGraphicsItemGroup_paint1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsItemGroupSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsItemGroup_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler6" qtc_QGraphicsItemGroup_setHandler6 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup6 :: (Ptr (TQGraphicsItemGroup x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf 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 Qqtype_h (QGraphicsItemGroup ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_type cobj_x0
foreign import ccall "qtc_QGraphicsItemGroup_type" qtc_QGraphicsItemGroup_type :: Ptr (TQGraphicsItemGroup a) -> IO CInt
instance Qqtype_h (QGraphicsItemGroupSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_type cobj_x0
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler7" qtc_QGraphicsItemGroup_setHandler7 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup7 :: (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 Qadvance_h (QGraphicsItemGroup ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsItemGroup_advance" qtc_QGraphicsItemGroup_advance :: Ptr (TQGraphicsItemGroup a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsItemGroupSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsItemGroup_setHandler8" qtc_QGraphicsItemGroup_setHandler8 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup8 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsItemGroup_setHandler9" qtc_QGraphicsItemGroup_setHandler9 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup9 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem" qtc_QGraphicsItemGroup_collidesWithItem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem1" qtc_QGraphicsItemGroup_collidesWithItem1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem" qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem" qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler10" qtc_QGraphicsItemGroup_setHandler10 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup10 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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_QGraphicsItemGroup_setHandler11" qtc_QGraphicsItemGroup_setHandler11 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup11 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
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 QcollidesWithPath_h (QGraphicsItemGroup ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithPath" qtc_QGraphicsItemGroup_collidesWithPath :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsItemGroupSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsItemGroup ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsItemGroup_collidesWithPath1" qtc_QGraphicsItemGroup_collidesWithPath1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsItemGroupSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler12" qtc_QGraphicsItemGroup_setHandler12 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup12 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 Qqcontains_h (QGraphicsItemGroup ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItemGroup_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsItemGroup_contains_qth" qtc_QGraphicsItemGroup_contains_qth :: Ptr (TQGraphicsItemGroup a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsItemGroupSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsItemGroup_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsItemGroup ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_contains" qtc_QGraphicsItemGroup_contains :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsItemGroupSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler13" qtc_QGraphicsItemGroup_setHandler13 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup13 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QcontextMenuEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_contextMenuEvent" qtc_QGraphicsItemGroup_contextMenuEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_dragEnterEvent" qtc_QGraphicsItemGroup_dragEnterEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_dragLeaveEvent" qtc_QGraphicsItemGroup_dragLeaveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_dragMoveEvent" qtc_QGraphicsItemGroup_dragMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_dropEvent" qtc_QGraphicsItemGroup_dropEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsItemGroup ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_focusInEvent" qtc_QGraphicsItemGroup_focusInEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsItemGroupSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsItemGroup ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_focusOutEvent" qtc_QGraphicsItemGroup_focusOutEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsItemGroupSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_hoverEnterEvent" qtc_QGraphicsItemGroup_hoverEnterEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_hoverLeaveEvent" qtc_QGraphicsItemGroup_hoverLeaveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_hoverMoveEvent" qtc_QGraphicsItemGroup_hoverMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsItemGroup ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_inputMethodEvent" qtc_QGraphicsItemGroup_inputMethodEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsItemGroupSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler14" qtc_QGraphicsItemGroup_setHandler14 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup14 :: (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 (QGraphicsItemGroup ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsItemGroup_inputMethodQuery" qtc_QGraphicsItemGroup_inputMethodQuery :: Ptr (TQGraphicsItemGroup a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsItemGroupSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
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_QGraphicsItemGroup_setHandler15" qtc_QGraphicsItemGroup_setHandler15 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup15 :: (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
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 QitemChange_h (QGraphicsItemGroup ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsItemGroup_itemChange" qtc_QGraphicsItemGroup_itemChange :: Ptr (TQGraphicsItemGroup a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsItemGroupSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsItemGroup ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_keyPressEvent" qtc_QGraphicsItemGroup_keyPressEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsItemGroupSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsItemGroup ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_keyReleaseEvent" qtc_QGraphicsItemGroup_keyReleaseEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsItemGroupSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_mouseDoubleClickEvent" qtc_QGraphicsItemGroup_mouseDoubleClickEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_mouseMoveEvent" qtc_QGraphicsItemGroup_mouseMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_mousePressEvent" qtc_QGraphicsItemGroup_mousePressEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_mouseReleaseEvent" qtc_QGraphicsItemGroup_mouseReleaseEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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_QGraphicsItemGroup_setHandler16" qtc_QGraphicsItemGroup_setHandler16 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup16 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf 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 QsceneEvent_h (QGraphicsItemGroup ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_sceneEvent" qtc_QGraphicsItemGroup_sceneEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsItemGroupSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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_QGraphicsItemGroup_setHandler17" qtc_QGraphicsItemGroup_setHandler17 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup17 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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 QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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_QGraphicsItemGroup_setHandler18" qtc_QGraphicsItemGroup_setHandler18 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup18 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsItemGroup18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsItemGroup18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsItemGroup_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
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 QsceneEventFilter_h (QGraphicsItemGroup ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItemGroup_sceneEventFilter" qtc_QGraphicsItemGroup_sceneEventFilter :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem" qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance Qshape_h (QGraphicsItemGroup ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_shape cobj_x0
foreign import ccall "qtc_QGraphicsItemGroup_shape" qtc_QGraphicsItemGroup_shape :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsItemGroupSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsItemGroup_shape cobj_x0
instance QwheelEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsItemGroup_wheelEvent" qtc_QGraphicsItemGroup_wheelEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsItemGroup_wheelEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QGraphicsItemGroup_h.hs | bsd-2-clause | 98,747 | 0 | 18 | 20,812 | 30,664 | 14,671 | 15,993 | -1 | -1 |
module Handler.View where
import Import
import Handler.Markdown (renderMarkdown)
getViewR :: NoteId -> Handler RepHtml
getViewR noteId = do
note <- runDB $ get404 noteId
defaultLayout $ do
setTitle (toHtml $ noteTitle note)
let markdown = renderMarkdown (unTextarea $ noteText note)
$(widgetFile "view")
| MasseR/introitu | Handler/View.hs | bsd-2-clause | 322 | 0 | 16 | 60 | 108 | 52 | 56 | -1 | -1 |
module Permutations where
import Data.List (delete, nub)
-- | List all permutations of a list (4 kyu)
-- | Link: https://biturl.io/Permutations
-- | My original solution
permutations :: Eq a => [a] -> [[a]]
permutations [] = [[]]
permutations xs = nub [x : ys | x <- xs, ys <- permutations (delete x xs)]
| Eugleo/Code-Wars | src/combinatorics-kata/Permutations.hs | bsd-3-clause | 308 | 0 | 11 | 58 | 105 | 58 | 47 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main ( main ) where
import Control.Applicative ((<$>))
import Control.Monad (forever, mzero)
import Control.Monad.Trans (liftIO)
import Control.Monad.IO.Class (MonadIO)
import Control.Concurrent (forkIO, ThreadId)
import Data.Aeson (FromJSON (..), ToJSON (..), (.:), (.=))
import qualified Data.Aeson as A
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Data.Text.IO as T
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Text (Text)
import Data.List (isPrefixOf)
import qualified Data.Vector as V
import Data.Monoid ((<>))
import Control.Monad (when)
import qualified Network.HTTP.Conduit as Http
import qualified Network.URI as Uri
import qualified Network.WebSockets as WS
import System.Process (system)
import System.Exit (ExitCode)
import CmdArgs
import Options.Applicative
import Watch (monitor)
import Chrome
import Commands
opts :: ParserInfo CmdArgs
opts = info (helper <*> cmdArgs)
(fullDesc
<> progDesc "For WAI complaint haskell web applications"
<> header "Reloader: Reload chrome tabs when files change locally." )
main :: IO ()
main = do
CmdArgs shouldRestart website files <- execParser opts
when shouldRestart (startChrome >> return ())
pages <- getChromiumPageInfo 9160
putStrLn "" >> putStrLn "pages:"
print pages
let (ci : _) = filter (\page -> isPrefixOf website (pageURL page)) pages
putStrLn "" >> putStrLn "ci:"
print ci
-- putStrLn "" >> putStrLn "request"
-- LBS.putStrLn $ A.encode $ searchName "remi"
--
let (host, port, path) = parseUri (chromiumDebuggerUrl ci)
WS.runClient host port path $ \conn -> do
forkIO (monitor (const (WS.sendTextData conn $ A.encode reload)) >> return ())
WS.sendTextData conn $ A.encode reload
forever $ do
msg <- WS.receiveData conn
liftIO $ do
putStrLn "------------------\nresult:"
T.putStrLn msg
putStrLn "------------------"
txt <- getLine
let cmd = A.encode reload
print cmd
WS.sendTextData conn cmd
| rvion/chrome-reloader | src/Main.hs | bsd-3-clause | 2,454 | 0 | 20 | 742 | 651 | 354 | 297 | 58 | 1 |
{-
Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka,
Patrik Jansson and Josef Svenningsson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Chalmers University of Technology nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL 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 Main where
import ARSim
-- | Just send 123 to the queue
r1 :: PQ Int c -> RunM (StdRet ())
r1 pqe = do rte_send pqe (123::Int)
-- | Provides a port (create it) and run r1 every 1.0 time units
c1 :: AR c (PQ Int ())
c1 = do pqe <- providedQueueElement
runnable Concurrent [Timed 1.0] (r1 pqe)
return (seal pqe)
-- | Just receive a value and do nothing with it
r2 :: Valuable a => RQ a c -> RunM ()
r2 rqe = do Ok x <- rte_receive rqe; return ()
-- | Requires a port (parametrised over the port) and "runs" r2
c2 :: AR c (RQ Int ())
c2 = do rqe <- requiredQueueElement 10 -- Queue of size 10
runnable Concurrent [ReceiveQ rqe] (r2 rqe)
return (seal rqe)
-- | Connect c1 and c2 to create a program that sends and receives.
test :: AR c ()
test = do pqe <- component c1
rqe <- component c2
connect pqe rqe
-- | Run the simulation of this test program, showing a trace of the execution
main = putTraceLabels $ fst $ (simulationHead test)
| josefs/autosar | oldARSim/Main.hs | bsd-3-clause | 2,812 | 0 | 9 | 724 | 317 | 154 | 163 | 19 | 1 |
module HaskellCI.Config.Jobs where
import HaskellCI.Prelude
import qualified Distribution.Compat.CharParsing as C
import qualified Distribution.Parsec as C
import qualified Distribution.Pretty as C
import qualified Text.PrettyPrint as PP
-- | Jobs
--
-- * @N:M@ - @N@ ghcs (cabal -j), @M@ threads (ghc -j)
--
-- >>> let parseJobs = C.simpleParsec :: String -> Maybe Jobs
-- >>> parseJobs "2:2"
-- Just (BothJobs 2 2)
--
-- >>> parseJobs ":2"
-- Just (GhcJobs 2)
--
-- >>> parseJobs "2"
-- Just (CabalJobs 2)
--
-- >>> parseJobs "garbage"
-- Nothing
--
data Jobs
= CabalJobs Int
| GhcJobs Int
| BothJobs Int Int
deriving (Show)
cabalJobs :: Jobs -> Maybe Int
cabalJobs (CabalJobs n) = Just n
cabalJobs (GhcJobs _) = Nothing
cabalJobs (BothJobs n _) = Just n
ghcJobs :: Jobs -> Maybe Int
ghcJobs (CabalJobs _) = Nothing
ghcJobs (GhcJobs m) = Just m
ghcJobs (BothJobs _ m) = Just m
instance C.Parsec Jobs where
parsec = ghc <|> rest where
ghc = C.char ':' *> (GhcJobs <$> C.integral)
rest = do
n <- C.integral
m' <- C.optional (C.char ':' *> C.integral)
return $ case m' of
Nothing -> CabalJobs n
Just m -> BothJobs n m
instance C.Pretty Jobs where
pretty (BothJobs n m) = PP.int n PP.<> PP.colon PP.<> PP.int m
pretty (CabalJobs n) = PP.int n
pretty (GhcJobs m) = PP.colon PP.<> PP.int m
| hvr/multi-ghc-travis | src/HaskellCI/Config/Jobs.hs | bsd-3-clause | 1,460 | 0 | 15 | 400 | 428 | 229 | 199 | 32 | 1 |
-- {-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE ExplicitForAll #-}
--{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
-- {-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE RankNTypes #-}
--{-# LANGUAGE RebindableSyntax #-}
--{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedLists #-}
--{-# LANGUAGE NamedFieldPuns #-}
module FV.Fit (
fit, kAddF, kAdd, ksm'
, kChi2
) where
import Prelude.Extended
--import qualified Data.Vector.Unboxed as A ( foldl, unzip, length )
import Data.Maybe ( Maybe (..), mapMaybe )
import Data.Cov
import FV.Jacob as J
import FV.Types ( VHMeas (..), HMeas (..), QMeas (..), XMeas (..)
, XFit (..)
, Prong (..), Chi2 (..)
)
fit :: VHMeas -> Prong
fit vhm = kSmooth vhm <<< kFilter $ vhm
kFilter :: VHMeas -> XMeas
kFilter VHMeas {vertex=v, helices=hl} = foldl kAdd v hl
kAdd :: XMeas -> HMeas -> XMeas
kAdd (XMeas v vv) (HMeas h hh w0) = kAdd' x_km1 p_k x_e q_e (Chi2 1e6) 0 where
x_km1 = XMeas v (inv vv)
p_k = HMeas h (inv hh) w0
x_e = v
q_e = J.hv2q h v
goodEnough :: Chi2 -> Chi2 -> Int -> Bool
--goodEnough (Chi2 c0) (Chi2 c) i | i < 99 && trace ("." <> show i <> "|" <> to1fix (abs (c-c0)) <> " " <> to1fix c) false = undefined
goodEnough (Chi2 c0) (Chi2 c) i = abs (c - c0) < chi2cut || i > iterMax where
chi2cut = 0.5
iterMax = 99 :: Int
-- | add a helix measurement to kalman filter, return updated vertex position
-- | if we can't invert, don't update vertex
kAdd' :: XMeas -> HMeas -> Vec3 -> Vec3 -> Chi2 -> Int -> XMeas
--kAdd' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e _ i |
-- i == 0 && trace ("kadd'-->" <> show i <> "|" <> show v0 <> show h) false = undefined
kAdd' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e 𝜒2_0 iter = x_k where
jj = J.expand x_e q_e
Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj
aaT = tr aa
bbT = tr bb
x_k = case invMaybe (bb .*. gg) of
Nothing -> XMeas v0 (inv uu0) `debug` "... can't invert in kAdd'"
Just ww -> let
gb = gg - gg .*. (bbT .*. ww)
uu = uu0 + aa .*. gb
cc = inv uu
m = h - h0
v = cc *. (uu0 *. v0 + aaT *. gb *. m)
dm = m - aa *. v
q = ww *. (bbT *. gg *. dm)
𝜒2 = Chi2 $ (dm - bb *. q) .*. gg + (v - v0) .*. uu0
x_k' = if goodEnough 𝜒2_0 𝜒2 iter -- `debug` ("--> kAdd' chi2 is " <> show 𝜒2)
then XMeas v cc
else kAdd' (XMeas v0 uu0) (HMeas h gg w0) v q 𝜒2 (iter+1)
in x_k'
kAddF :: XFit -> HMeas -> XFit
kAddF (XFit v vv _) (HMeas h hh _) = kAddF' v (inv vv) h (inv hh) v (J.hv2q h v) (Chi2 1e6) 0
kAddF' :: Vec3 -> Cov3 -> Vec5 -> Cov5 -> Vec3 -> Vec3 -> Chi2 -> Int -> XFit
kAddF' v0 uu0 h gg x_e q_e 𝜒2_0 iter = x_k where
jj = J.expand x_e q_e
Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj
aaT = tr aa
bbT = tr bb
x_k = case invMaybe (bb .*. gg) of
Nothing -> XFit v0 (inv uu0) (Chi2 1e6) `debug` "... can't invert in kAddF'"
Just ww -> let
gb = gg - gg .*. (bbT .*. ww)
uu = uu0 + aa .*. gb
cc = inv uu
m = h - h0
v = cc *. (uu0 *. v0 + aaT *. gb *. m)
dm = m - aa *. v
q = ww *. (bbT *. gg *. dm)
𝜒2 = Chi2 $ (dm - bb *. q) .*. gg + (v - v0) .*. uu0
x_k' = if goodEnough 𝜒2_0 𝜒2 iter -- `debug` (printf "--> kAddF' chi2 is %9.1f, %9.1f" 𝜒2 (scalar $ sw (v-v0) uu0))
then XFit v cc 𝜒2
else kAddF' v0 uu0 h gg v q 𝜒2 (iter+1)
in x_k'
kSmooth :: VHMeas -> XMeas -> Prong
--kSmooth vm v | trace ("kSmooth " <> (show <<< length <<< helices $ vm) <> ", vertex at " <> (show v) ) false = undefined
kSmooth (VHMeas {vertex= v0, helices= hl}) v = pr' where
(ql, chi2l) = unzip $ mapMaybe (ksm v) hl
hl' = hl
n = length hl
n' = length ql
n'' = if n == n' then n else n' `debug` "kSmooth killed helices"
pr' = Prong { fitVertex= v, fitMomenta= ql, fitChi2s= chi2l, nProng= n'', measurements= VHMeas {vertex= v0, helices= hl'} }
-- kalman smoother step: calculate 3-mom q and chi2 at kalman filter'ed vertex
-- if we can't invert, return Nothing and this track will not be included
ksm :: XMeas -> HMeas -> Maybe (QMeas, Chi2)
ksm (XMeas x cc) (HMeas h hh w0) = do
let
jj = J.expand x (J.hv2q h x)
Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj
gg = inv hh
ww <- invMaybe (bb .*. gg)
let p = h - h0
uu = inv cc
aaT = tr aa
bbT = tr bb
dp = p - aa *. x
q = ww *. (bbT *. gg *. dp)
mee = (cc *. aaT) *. gg *. bb *. ww
dd = ww + mee .*. uu
r = p - aa *. x - bb *. q
ch = r .*. gg
gb = gg - gg .*. (bbT .*. ww)
uu' = uu - aa .*. gb
cx = if det uu' < 0.0 then 1000.0
`debug` ("--> ksm bad " <> show (det uu')
<> show uu')
else cx'' where
cc' = inv uu' -- `debug` ("--> ksm " ++ show uu')
x' = cc' *. (uu *. x - aaT *. gb *. p)
dx = x - x'
cx' = dx .*. uu'
cx'' = if cx' < 0.0 then 2000.0 `debug` ("--> ksm chi2 is " <> show cx' <> ", " <> show ch <> ", " <> show (max cx' 0.0 + ch))
else cx'
𝜒2 = cx + ch
pure (QMeas q dd w0, Chi2 𝜒2)
ksm' :: XMeas -> Maybe HMeas -> Maybe (QMeas, Chi2)
ksm' _ Nothing = Nothing
ksm' xm (Just hm) = ksm xm hm
-- calculate Chi2 of a new helix measurement using kalman filter
-- if we can't invert, return 0.0
kChi2 :: XMeas -> HMeas -> Chi2
kChi2 (XMeas v vv) (HMeas h hh w0) = kChi2' x_km1 p_k x_e q_e (Chi2 1e6) 0 where
x_km1 = XMeas v (inv vv)
p_k = HMeas h (inv hh) w0
x_e = v
q_e = J.hv2q h v
kChi2' :: XMeas -> HMeas -> Vec3 -> Vec3 -> Chi2 -> Int -> Chi2
kChi2' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e 𝜒2_0 iter = x_k where
jj = J.expand x_e q_e
Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj
aaT = tr aa
bbT = tr bb
x_k = case invMaybe (bb .*. gg) of
Nothing -> Chi2 0.0
Just ww -> let
gb = gg - gg .*. (bbT .*. ww)
uu = uu0 + aa .*. gb
cc = inv uu
m = h - h0
v = cc *. (uu0 *. v0 + aaT *. gb *. m)
dm = m - aa *. v
q = ww *. bbT *. gg *. dm
𝜒2 = Chi2 $ (v - v0) .*. uu0 -- or shoud it use uu?? + sw (dm - bb * q) gg
x_k' = if goodEnough 𝜒2_0 𝜒2 iter
then 𝜒2
else kChi2' (XMeas v0 uu0) (HMeas h gg w0) v q 𝜒2 (iter+1)
in x_k'
| LATBauerdick/fv.hs | src/FV/Fit.hs | bsd-3-clause | 7,151 | 38 | 20 | 2,667 | 2,488 | 1,330 | 1,158 | 142 | 3 |
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module RegAlloc.Linear.FreeRegs (
FR(..),
maxSpillSlots
)
#include "HsVersions.h"
where
import Reg
import RegClass
import Panic
import Platform
-- -----------------------------------------------------------------------------
-- The free register set
-- This needs to be *efficient*
-- Here's an inefficient 'executable specification' of the FreeRegs data type:
--
-- type FreeRegs = [RegNo]
-- noFreeRegs = 0
-- releaseReg n f = if n `elem` f then f else (n : f)
-- initFreeRegs = allocatableRegs
-- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f
-- allocateReg f r = filter (/= r) f
import qualified RegAlloc.Linear.PPC.FreeRegs as PPC
import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC
import qualified RegAlloc.Linear.X86.FreeRegs as X86
import qualified PPC.Instr
import qualified SPARC.Instr
import qualified X86.Instr
class Show freeRegs => FR freeRegs where
frAllocateReg :: RealReg -> freeRegs -> freeRegs
frGetFreeRegs :: Platform -> RegClass -> freeRegs -> [RealReg]
frInitFreeRegs :: Platform -> freeRegs
frReleaseReg :: RealReg -> freeRegs -> freeRegs
instance FR X86.FreeRegs where
frAllocateReg = X86.allocateReg
frGetFreeRegs = X86.getFreeRegs
frInitFreeRegs = X86.initFreeRegs
frReleaseReg = X86.releaseReg
instance FR PPC.FreeRegs where
frAllocateReg = PPC.allocateReg
frGetFreeRegs = \_ -> PPC.getFreeRegs
frInitFreeRegs = \_ -> PPC.initFreeRegs
frReleaseReg = PPC.releaseReg
instance FR SPARC.FreeRegs where
frAllocateReg = SPARC.allocateReg
frGetFreeRegs = \_ -> SPARC.getFreeRegs
frInitFreeRegs = \_ -> SPARC.initFreeRegs
frReleaseReg = SPARC.releaseReg
maxSpillSlots :: Platform -> Int
maxSpillSlots platform
= case platformArch platform of
ArchX86 -> X86.Instr.maxSpillSlots True -- 32bit
ArchX86_64 -> X86.Instr.maxSpillSlots False -- not 32bit
ArchPPC -> PPC.Instr.maxSpillSlots
ArchSPARC -> SPARC.Instr.maxSpillSlots
ArchARM _ _ _ -> panic "maxSpillSlots ArchARM"
ArchPPC_64 -> panic "maxSpillSlots ArchPPC_64"
ArchUnknown -> panic "maxSpillSlots ArchUnknown"
| nomeata/ghc | compiler/nativeGen/RegAlloc/Linear/FreeRegs.hs | bsd-3-clause | 2,590 | 0 | 10 | 560 | 404 | 238 | 166 | 44 | 7 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-@ LIQUID "--no-termination "@-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
import Prelude hiding (sum, length, (!!), Functor(..))
import qualified Prelude as P
[lq| qualif Size(v:int, xs:a): v = (size xs) |]
[lq| data List a = Nil | Cons (hd::a) (tl::(List a)) |]
data List a = Nil | Cons a (List a)
[lq| length :: xs:List a -> {v:Nat | v = (size xs)} |]
length :: List a -> Int
length Nil = 0
length (Cons x xs) = 1 + length xs
[lq| (!!) :: xs:List a -> {v:Nat | v < (size xs)} -> a |]
(!!) :: List a -> Int -> a
Nil !! i = liquidError "impossible"
(Cons x _) !! 0 = x
(Cons x xs) !! i = xs !! (i - 1)
[lq| class measure size :: forall a. a -> Int |]
[lq| class Sized s where
size :: forall a. x:s a -> {v:Nat | v = (size x)}
|]
class Sized s where
size :: s a -> Int
instance Sized List where
[lq| instance measure size :: List a -> Int
size (Nil) = 0
size (Cons x xs) = 1 + (size xs)
|]
size = length
instance Sized [] where
[lq| instance measure size :: [a] -> Int
size ([]) = 0
size (x:xs) = 1 + (size xs)
|]
size [] = 0
size (x:xs) = 1 + size xs
[lq| class (Sized s) => Indexable s where
index :: forall a. x:s a -> {v:Nat | v < (size x)} -> a
|]
class (Sized s) => Indexable s where
index :: s a -> Int -> a
instance Indexable List where
index = (!!)
[lq| sum :: Indexable s => s Int -> Int |]
sum :: Indexable s => s Int -> Int
sum xs = go max 0
where
max = size xs
go (d::Int) i
| i < max = index xs i + go (d-1) (i+1)
| otherwise = 0
[lq| sumList :: List Int -> Int |]
sumList :: List Int -> Int
sumList xs = go max 0
where
max = size xs
go (d::Int) i
| i < max = index xs i + go (d-1) (i+1)
| otherwise = 0
[lq| x :: {v:List Int | (size v) = 3} |]
x :: List Int
x = 1 `Cons` (2 `Cons` (3 `Cons` Nil))
foo = liquidAssert $ size (Cons 1 Nil) == size [1]
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/Class.hs | bsd-3-clause | 2,007 | 4 | 9 | 577 | 679 | 366 | 313 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Provides operations for BitFields that are used in the protocol.
module Network.BitTorrent.BitField (
BitField(..)
, newBitField
, get
, set
, completed
, toPWP
) where
import Control.DeepSeq
import Data.Bits
import Data.ByteString (ByteString)
import Data.Foldable as Foldable
import qualified Data.ByteString as B
import Data.Monoid
import Data.Word
import GHC.Generics (Generic)
import Network.BitTorrent.PWP
import Network.BitTorrent.Utility
-- | Holds the completion status of pieces.
-- Works by using tightly packed bits to store this information efficiently.
-- Can describe 8 piece statuses per byte.
data BitField = BitField
{ raw :: !ByteString -- ^ Raw byte array.
, length :: Word32 -- ^ Length of the bitfield.
} deriving(Show, Eq, Generic, NFData)
-- | /O(n)/ Creates a new bitfield with the specified length.
-- Starts out with all pieces marked as unfinished.
newBitField :: Word32 -> BitField
newBitField len = BitField (B.replicate (fromIntegral byteLength) 0) len
where byteLength = divideSize len 8
{-# INLINABLE newBitField #-}
-- | /O(1)/ Get the status of a single piece.
get :: BitField -> Word32 -> Bool
get (BitField field _) ix = testBit word (7 - fromIntegral ix `rem` 8)
where byteIx = fromIntegral $ ix `quot` 8
word = B.index field byteIx
{-# INLINABLE get #-}
-- | /O(n)/ Sets the status of a single piece by returning a new
-- bitfield with the change applied.
set :: BitField
-> Word32 -- ^ Piece ID
-> Bool -- ^ New status
-> BitField
set (BitField field len) ix val = (BitField $! updatedField) $! len
where byteIx = fromIntegral ix `quot` 8
word = B.index field byteIx
modifier True = setBit
modifier False = clearBit
updatedByte = modifier val word (7 - fromIntegral ix `rem` 8)
updatedField = B.take byteIx field <> B.singleton updatedByte <> B.drop (byteIx + 1) field
{-# INLINABLE set #-}
-- | /O(n)/ Get the ratio of completed pieces.
completed :: BitField
-> Float -- ^ Result in range /[0;1]/
completed (BitField b len) = fromIntegral (Foldable.sum (popCount <$> B.unpack b)) / fromIntegral len
{-# INLINABLE completed #-}
-- | /O(1)/ Cast the BitField to a PWP message.
toPWP :: BitField -> PWP
toPWP (BitField raw _) = Bitfield raw
{-# INLINABLE toPWP #-}
| farnoy/torrent | src/Network/BitTorrent/BitField.hs | bsd-3-clause | 2,400 | 0 | 12 | 471 | 536 | 302 | 234 | 49 | 2 |
-- | contains a prettyprinter for the
-- Template Haskell datatypes
module Language.Haskell.TH.Ppr where
-- All of the exports from this module should
-- be "public" functions. The main module TH
-- re-exports them all.
import Text.PrettyPrint (render)
import Language.Haskell.TH.PprLib
import Language.Haskell.TH.Syntax
import Data.Word ( Word8 )
import Data.Char ( toLower, chr, ord, isSymbol )
import GHC.Show ( showMultiLineString )
import Data.Ratio ( numerator, denominator )
nestDepth :: Int
nestDepth = 4
type Precedence = Int
appPrec, unopPrec, opPrec, noPrec :: Precedence
appPrec = 3 -- Argument of a function application
opPrec = 2 -- Argument of an infix operator
unopPrec = 1 -- Argument of an unresolved infix operator
noPrec = 0 -- Others
parensIf :: Bool -> Doc -> Doc
parensIf True d = parens d
parensIf False d = d
------------------------------
pprint :: Ppr a => a -> String
pprint x = render $ to_HPJ_Doc $ ppr x
class Ppr a where
ppr :: a -> Doc
ppr_list :: [a] -> Doc
ppr_list = vcat . map ppr
instance Ppr a => Ppr [a] where
ppr x = ppr_list x
------------------------------
instance Ppr Name where
ppr v = pprName v
------------------------------
instance Ppr Info where
ppr (TyConI d) = ppr d
ppr (ClassI d is) = ppr d $$ vcat (map ppr is)
ppr (FamilyI d is) = ppr d $$ vcat (map ppr is)
ppr (PrimTyConI name arity is_unlifted)
= text "Primitive"
<+> (if is_unlifted then text "unlifted" else empty)
<+> text "type constructor" <+> quotes (ppr name)
<+> parens (text "arity" <+> int arity)
ppr (ClassOpI v ty cls)
= text "Class op from" <+> ppr cls <> colon <+> ppr_sig v ty
ppr (DataConI v ty tc)
= text "Constructor from" <+> ppr tc <> colon <+> ppr_sig v ty
ppr (TyVarI v ty)
= text "Type variable" <+> ppr v <+> equals <+> ppr ty
ppr (VarI v ty mb_d)
= vcat [ppr_sig v ty,
case mb_d of { Nothing -> empty; Just d -> ppr d }]
ppr_sig :: Name -> Type -> Doc
ppr_sig v ty = pprName' Applied v <+> dcolon <+> ppr ty
pprFixity :: Name -> Fixity -> Doc
pprFixity _ f | f == defaultFixity = empty
pprFixity v (Fixity i d) = ppr_fix d <+> int i <+> ppr v
where ppr_fix InfixR = text "infixr"
ppr_fix InfixL = text "infixl"
ppr_fix InfixN = text "infix"
------------------------------
instance Ppr Module where
ppr (Module pkg m) = text (pkgString pkg) <+> text (modString m)
instance Ppr ModuleInfo where
ppr (ModuleInfo imps) = text "Module" <+> vcat (map ppr imps)
------------------------------
instance Ppr Exp where
ppr = pprExp noPrec
pprPrefixOcc :: Name -> Doc
-- Print operators with parens around them
pprPrefixOcc n = parensIf (isSymOcc n) (ppr n)
isSymOcc :: Name -> Bool
isSymOcc n
= case nameBase n of
[] -> True -- Empty name; weird
(c:_) -> isSymbolASCII c || (ord c > 0x7f && isSymbol c)
-- c.f. OccName.startsVarSym in GHC itself
isSymbolASCII :: Char -> Bool
isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
pprInfixExp :: Exp -> Doc
pprInfixExp (VarE v) = pprName' Infix v
pprInfixExp (ConE v) = pprName' Infix v
pprInfixExp _ = text "<<Non-variable/constructor in infix context>>"
pprExp :: Precedence -> Exp -> Doc
pprExp _ (VarE v) = pprName' Applied v
pprExp _ (ConE c) = pprName' Applied c
pprExp i (LitE l) = pprLit i l
pprExp i (AppE e1 e2) = parensIf (i >= appPrec) $ pprExp opPrec e1
<+> pprExp appPrec e2
pprExp _ (ParensE e) = parens (pprExp noPrec e)
pprExp i (UInfixE e1 op e2)
= parensIf (i > unopPrec) $ pprExp unopPrec e1
<+> pprInfixExp op
<+> pprExp unopPrec e2
pprExp i (InfixE (Just e1) op (Just e2))
= parensIf (i >= opPrec) $ pprExp opPrec e1
<+> pprInfixExp op
<+> pprExp opPrec e2
pprExp _ (InfixE me1 op me2) = parens $ pprMaybeExp noPrec me1
<+> pprInfixExp op
<+> pprMaybeExp noPrec me2
pprExp i (LamE ps e) = parensIf (i > noPrec) $ char '\\' <> hsep (map (pprPat appPrec) ps)
<+> text "->" <+> ppr e
pprExp i (LamCaseE ms) = parensIf (i > noPrec)
$ text "\\case" $$ nest nestDepth (ppr ms)
pprExp _ (TupE es) = parens (commaSep es)
pprExp _ (UnboxedTupE es) = hashParens (commaSep es)
-- Nesting in Cond is to avoid potential problems in do statments
pprExp i (CondE guard true false)
= parensIf (i > noPrec) $ sep [text "if" <+> ppr guard,
nest 1 $ text "then" <+> ppr true,
nest 1 $ text "else" <+> ppr false]
pprExp i (MultiIfE alts)
= parensIf (i > noPrec) $ vcat $
case alts of
[] -> [text "if {}"]
(alt : alts') -> text "if" <+> pprGuarded arrow alt
: map (nest 3 . pprGuarded arrow) alts'
pprExp i (LetE ds_ e) = parensIf (i > noPrec) $ text "let" <+> pprDecs ds_
$$ text " in" <+> ppr e
where
pprDecs [] = empty
pprDecs [d] = ppr d
pprDecs ds = braces (semiSep ds)
pprExp i (CaseE e ms)
= parensIf (i > noPrec) $ text "case" <+> ppr e <+> text "of"
$$ nest nestDepth (ppr ms)
pprExp i (DoE ss_) = parensIf (i > noPrec) $ text "do" <+> pprStms ss_
where
pprStms [] = empty
pprStms [s] = ppr s
pprStms ss = braces (semiSep ss)
pprExp _ (CompE []) = text "<<Empty CompExp>>"
-- This will probably break with fixity declarations - would need a ';'
pprExp _ (CompE ss) =
if null ss'
-- If there are no statements in a list comprehension besides the last
-- one, we simply treat it like a normal list.
then text "[" <> ppr s <> text "]"
else text "[" <> ppr s
<+> text "|"
<+> commaSep ss'
<> text "]"
where s = last ss
ss' = init ss
pprExp _ (ArithSeqE d) = ppr d
pprExp _ (ListE es) = brackets (commaSep es)
pprExp i (SigE e t) = parensIf (i > noPrec) $ ppr e <+> dcolon <+> ppr t
pprExp _ (RecConE nm fs) = ppr nm <> braces (pprFields fs)
pprExp _ (RecUpdE e fs) = pprExp appPrec e <> braces (pprFields fs)
pprExp i (StaticE e) = parensIf (i >= appPrec) $
text "static"<+> pprExp appPrec e
pprExp _ (UnboundVarE v) = pprName' Applied v
pprFields :: [(Name,Exp)] -> Doc
pprFields = sep . punctuate comma . map (\(s,e) -> ppr s <+> equals <+> ppr e)
pprMaybeExp :: Precedence -> Maybe Exp -> Doc
pprMaybeExp _ Nothing = empty
pprMaybeExp i (Just e) = pprExp i e
------------------------------
instance Ppr Stmt where
ppr (BindS p e) = ppr p <+> text "<-" <+> ppr e
ppr (LetS ds) = text "let" <+> (braces (semiSep ds))
ppr (NoBindS e) = ppr e
ppr (ParS sss) = sep $ punctuate (text "|")
$ map commaSep sss
------------------------------
instance Ppr Match where
ppr (Match p rhs ds) = ppr p <+> pprBody False rhs
$$ where_clause ds
------------------------------
pprGuarded :: Doc -> (Guard, Exp) -> Doc
pprGuarded eqDoc (guard, expr) = case guard of
NormalG guardExpr -> char '|' <+> ppr guardExpr <+> eqDoc <+> ppr expr
PatG stmts -> char '|' <+> vcat (punctuate comma $ map ppr stmts) $$
nest nestDepth (eqDoc <+> ppr expr)
------------------------------
pprBody :: Bool -> Body -> Doc
pprBody eq body = case body of
GuardedB xs -> nest nestDepth $ vcat $ map (pprGuarded eqDoc) xs
NormalB e -> eqDoc <+> ppr e
where eqDoc | eq = equals
| otherwise = arrow
------------------------------
instance Ppr Lit where
ppr = pprLit noPrec
pprLit :: Precedence -> Lit -> Doc
pprLit i (IntPrimL x) = parensIf (i > noPrec && x < 0)
(integer x <> char '#')
pprLit _ (WordPrimL x) = integer x <> text "##"
pprLit i (FloatPrimL x) = parensIf (i > noPrec && x < 0)
(float (fromRational x) <> char '#')
pprLit i (DoublePrimL x) = parensIf (i > noPrec && x < 0)
(double (fromRational x) <> text "##")
pprLit i (IntegerL x) = parensIf (i > noPrec && x < 0) (integer x)
pprLit _ (CharL c) = text (show c)
pprLit _ (CharPrimL c) = text (show c) <> char '#'
pprLit _ (StringL s) = pprString s
pprLit _ (StringPrimL s) = pprString (bytesToString s) <> char '#'
pprLit i (RationalL rat) = parensIf (i > noPrec) $
integer (numerator rat) <+> char '/'
<+> integer (denominator rat)
bytesToString :: [Word8] -> String
bytesToString = map (chr . fromIntegral)
pprString :: String -> Doc
-- Print newlines as newlines with Haskell string escape notation,
-- not as '\n'. For other non-printables use regular escape notation.
pprString s = vcat (map text (showMultiLineString s))
------------------------------
instance Ppr Pat where
ppr = pprPat noPrec
pprPat :: Precedence -> Pat -> Doc
pprPat i (LitP l) = pprLit i l
pprPat _ (VarP v) = pprName' Applied v
pprPat _ (TupP ps) = parens (commaSep ps)
pprPat _ (UnboxedTupP ps) = hashParens (commaSep ps)
pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s
<+> sep (map (pprPat appPrec) ps)
pprPat _ (ParensP p) = parens $ pprPat noPrec p
pprPat i (UInfixP p1 n p2)
= parensIf (i > unopPrec) (pprPat unopPrec p1 <+>
pprName' Infix n <+>
pprPat unopPrec p2)
pprPat i (InfixP p1 n p2)
= parensIf (i >= opPrec) (pprPat opPrec p1 <+>
pprName' Infix n <+>
pprPat opPrec p2)
pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p
pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p
pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@"
<> pprPat appPrec p
pprPat _ WildP = text "_"
pprPat _ (RecP nm fs)
= parens $ ppr nm
<+> braces (sep $ punctuate comma $
map (\(s,p) -> ppr s <+> equals <+> ppr p) fs)
pprPat _ (ListP ps) = brackets (commaSep ps)
pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> dcolon <+> ppr t
pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p
------------------------------
instance Ppr Dec where
ppr = ppr_dec True
ppr_dec :: Bool -- declaration on the toplevel?
-> Dec
-> Doc
ppr_dec _ (FunD f cs) = vcat $ map (\c -> pprPrefixOcc f <+> ppr c) cs
ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r
$$ where_clause ds
ppr_dec _ (TySynD t xs rhs)
= ppr_tySyn empty t (hsep (map ppr xs)) rhs
ppr_dec _ (DataD ctxt t xs ksig cs decs)
= ppr_data empty ctxt t (hsep (map ppr xs)) ksig cs decs
ppr_dec _ (NewtypeD ctxt t xs ksig c decs)
= ppr_newtype empty ctxt t (sep (map ppr xs)) ksig c decs
ppr_dec _ (ClassD ctxt c xs fds ds)
= text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds
$$ where_clause ds
ppr_dec _ (InstanceD o ctxt i ds) =
text "instance" <+> maybe empty ppr_overlap o <+> pprCxt ctxt <+> ppr i
$$ where_clause ds
ppr_dec _ (SigD f t) = pprPrefixOcc f <+> dcolon <+> ppr t
ppr_dec _ (ForeignD f) = ppr f
ppr_dec _ (InfixD fx n) = pprFixity n fx
ppr_dec _ (PragmaD p) = ppr p
ppr_dec isTop (DataFamilyD tc tvs kind)
= text "data" <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind
where
maybeFamily | isTop = text "family"
| otherwise = empty
maybeKind | (Just k') <- kind = dcolon <+> ppr k'
| otherwise = empty
ppr_dec isTop (DataInstD ctxt tc tys ksig cs decs)
= ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) ksig cs decs
where
maybeInst | isTop = text "instance"
| otherwise = empty
ppr_dec isTop (NewtypeInstD ctxt tc tys ksig c decs)
= ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) ksig c decs
where
maybeInst | isTop = text "instance"
| otherwise = empty
ppr_dec isTop (TySynInstD tc (TySynEqn tys rhs))
= ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs
where
maybeInst | isTop = text "instance"
| otherwise = empty
ppr_dec isTop (OpenTypeFamilyD tfhead)
= text "type" <+> maybeFamily <+> ppr_tf_head tfhead
where
maybeFamily | isTop = text "family"
| otherwise = empty
ppr_dec _ (ClosedTypeFamilyD tfhead@(TypeFamilyHead tc _ _ _) eqns)
= hang (text "type family" <+> ppr_tf_head tfhead <+> text "where")
nestDepth (vcat (map ppr_eqn eqns))
where
ppr_eqn (TySynEqn lhs rhs)
= ppr tc <+> sep (map pprParendType lhs) <+> text "=" <+> ppr rhs
ppr_dec _ (RoleAnnotD name roles)
= hsep [ text "type role", ppr name ] <+> hsep (map ppr roles)
ppr_dec _ (StandaloneDerivD cxt ty)
= hsep [ text "deriving instance", pprCxt cxt, ppr ty ]
ppr_dec _ (DefaultSigD n ty)
= hsep [ text "default", pprPrefixOcc n, dcolon, ppr ty ]
ppr_overlap :: Overlap -> Doc
ppr_overlap o = text $
case o of
Overlaps -> "{-# OVERLAPS #-}"
Overlappable -> "{-# OVERLAPPABLE #-}"
Overlapping -> "{-# OVERLAPPING #-}"
Incoherent -> "{-# INCOHERENT #-}"
ppr_data :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> [Con] -> Cxt -> Doc
ppr_data maybeInst ctxt t argsDoc ksig cs decs
= sep [text "data" <+> maybeInst
<+> pprCxt ctxt
<+> ppr t <+> argsDoc <+> ksigDoc <+> maybeWhere,
nest nestDepth (sep (pref $ map ppr cs)),
if null decs
then empty
else nest nestDepth
$ text "deriving" <+> ppr_cxt_preds decs]
where
pref :: [Doc] -> [Doc]
pref xs | isGadtDecl = xs
pref [] = [] -- No constructors; can't happen in H98
pref (d:ds) = (char '=' <+> d):map (char '|' <+>) ds
maybeWhere :: Doc
maybeWhere | isGadtDecl = text "where"
| otherwise = empty
isGadtDecl :: Bool
isGadtDecl = not (null cs) && all isGadtCon cs
where isGadtCon (GadtC _ _ _ ) = True
isGadtCon (RecGadtC _ _ _) = True
isGadtCon (ForallC _ _ x ) = isGadtCon x
isGadtCon _ = False
ksigDoc = case ksig of
Nothing -> empty
Just k -> dcolon <+> ppr k
ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> Con -> Cxt -> Doc
ppr_newtype maybeInst ctxt t argsDoc ksig c decs
= sep [text "newtype" <+> maybeInst
<+> pprCxt ctxt
<+> ppr t <+> argsDoc <+> ksigDoc,
nest 2 (char '=' <+> ppr c),
if null decs
then empty
else nest nestDepth
$ text "deriving" <+> ppr_cxt_preds decs]
where
ksigDoc = case ksig of
Nothing -> empty
Just k -> dcolon <+> ppr k
ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc
ppr_tySyn maybeInst t argsDoc rhs
= text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs
ppr_tf_head :: TypeFamilyHead -> Doc
ppr_tf_head (TypeFamilyHead tc tvs res inj)
= ppr tc <+> hsep (map ppr tvs) <+> ppr res <+> maybeInj
where
maybeInj | (Just inj') <- inj = ppr inj'
| otherwise = empty
------------------------------
instance Ppr FunDep where
ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys)
ppr_list [] = empty
ppr_list xs = char '|' <+> commaSep xs
------------------------------
instance Ppr FamFlavour where
ppr DataFam = text "data"
ppr TypeFam = text "type"
------------------------------
instance Ppr FamilyResultSig where
ppr NoSig = empty
ppr (KindSig k) = dcolon <+> ppr k
ppr (TyVarSig bndr) = text "=" <+> ppr bndr
------------------------------
instance Ppr InjectivityAnn where
ppr (InjectivityAnn lhs rhs) =
char '|' <+> ppr lhs <+> text "->" <+> hsep (map ppr rhs)
------------------------------
instance Ppr Foreign where
ppr (ImportF callconv safety impent as typ)
= text "foreign import"
<+> showtextl callconv
<+> showtextl safety
<+> text (show impent)
<+> ppr as
<+> dcolon <+> ppr typ
ppr (ExportF callconv expent as typ)
= text "foreign export"
<+> showtextl callconv
<+> text (show expent)
<+> ppr as
<+> dcolon <+> ppr typ
------------------------------
instance Ppr Pragma where
ppr (InlineP n inline rm phases)
= text "{-#"
<+> ppr inline
<+> ppr rm
<+> ppr phases
<+> ppr n
<+> text "#-}"
ppr (SpecialiseP n ty inline phases)
= text "{-# SPECIALISE"
<+> maybe empty ppr inline
<+> ppr phases
<+> sep [ ppr n <+> dcolon
, nest 2 $ ppr ty ]
<+> text "#-}"
ppr (SpecialiseInstP inst)
= text "{-# SPECIALISE instance" <+> ppr inst <+> text "#-}"
ppr (RuleP n bndrs lhs rhs phases)
= sep [ text "{-# RULES" <+> pprString n <+> ppr phases
, nest 4 $ ppr_forall <+> ppr lhs
, nest 4 $ char '=' <+> ppr rhs <+> text "#-}" ]
where ppr_forall | null bndrs = empty
| otherwise = text "forall"
<+> fsep (map ppr bndrs)
<+> char '.'
ppr (AnnP tgt expr)
= text "{-# ANN" <+> target1 tgt <+> ppr expr <+> text "#-}"
where target1 ModuleAnnotation = text "module"
target1 (TypeAnnotation t) = text "type" <+> ppr t
target1 (ValueAnnotation v) = ppr v
ppr (LineP line file)
= text "{-# LINE" <+> int line <+> text (show file) <+> text "#-}"
------------------------------
instance Ppr Inline where
ppr NoInline = text "NOINLINE"
ppr Inline = text "INLINE"
ppr Inlinable = text "INLINABLE"
------------------------------
instance Ppr RuleMatch where
ppr ConLike = text "CONLIKE"
ppr FunLike = empty
------------------------------
instance Ppr Phases where
ppr AllPhases = empty
ppr (FromPhase i) = brackets $ int i
ppr (BeforePhase i) = brackets $ char '~' <> int i
------------------------------
instance Ppr RuleBndr where
ppr (RuleVar n) = ppr n
ppr (TypedRuleVar n ty) = parens $ ppr n <+> dcolon <+> ppr ty
------------------------------
instance Ppr Clause where
ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs
$$ where_clause ds
------------------------------
instance Ppr Con where
ppr (NormalC c sts) = ppr c <+> sep (map pprBangType sts)
ppr (RecC c vsts)
= ppr c <+> braces (sep (punctuate comma $ map pprVarBangType vsts))
ppr (InfixC st1 c st2) = pprBangType st1
<+> pprName' Infix c
<+> pprBangType st2
ppr (ForallC ns ctxt (GadtC c sts ty))
= commaSepApplied c <+> dcolon <+> pprForall ns ctxt
<+> pprGadtRHS sts ty
ppr (ForallC ns ctxt (RecGadtC c vsts ty))
= commaSepApplied c <+> dcolon <+> pprForall ns ctxt
<+> pprRecFields vsts ty
ppr (ForallC ns ctxt con)
= pprForall ns ctxt <+> ppr con
ppr (GadtC c sts ty)
= commaSepApplied c <+> dcolon <+> pprGadtRHS sts ty
ppr (RecGadtC c vsts ty)
= commaSepApplied c <+> dcolon <+> pprRecFields vsts ty
commaSepApplied :: [Name] -> Doc
commaSepApplied = commaSepWith (pprName' Applied)
pprForall :: [TyVarBndr] -> Cxt -> Doc
pprForall ns ctxt
= text "forall" <+> hsep (map ppr ns)
<+> char '.' <+> pprCxt ctxt
pprRecFields :: [(Name, Strict, Type)] -> Type -> Doc
pprRecFields vsts ty
= braces (sep (punctuate comma $ map pprVarBangType vsts))
<+> arrow <+> ppr ty
pprGadtRHS :: [(Strict, Type)] -> Type -> Doc
pprGadtRHS [] ty
= ppr ty
pprGadtRHS sts ty
= sep (punctuate (space <> arrow) (map pprBangType sts))
<+> arrow <+> ppr ty
------------------------------
pprVarBangType :: VarBangType -> Doc
-- Slight infelicity: with print non-atomic type with parens
pprVarBangType (v, bang, t) = ppr v <+> dcolon <+> pprBangType (bang, t)
------------------------------
pprBangType :: BangType -> Doc
-- Make sure we print
--
-- Con {-# UNPACK #-} a
--
-- rather than
--
-- Con {-# UNPACK #-}a
--
-- when there's no strictness annotation. If there is a strictness annotation,
-- it's okay to not put a space between it and the type.
pprBangType (bt@(Bang _ NoSourceStrictness), t) = ppr bt <+> pprParendType t
pprBangType (bt, t) = ppr bt <> pprParendType t
------------------------------
instance Ppr Bang where
ppr (Bang su ss) = ppr su <+> ppr ss
------------------------------
instance Ppr SourceUnpackedness where
ppr NoSourceUnpackedness = empty
ppr SourceNoUnpack = text "{-# NOUNPACK #-}"
ppr SourceUnpack = text "{-# UNPACK #-}"
------------------------------
instance Ppr SourceStrictness where
ppr NoSourceStrictness = empty
ppr SourceLazy = char '~'
ppr SourceStrict = char '!'
------------------------------
instance Ppr DecidedStrictness where
ppr DecidedLazy = empty
ppr DecidedStrict = char '!'
ppr DecidedUnpack = text "{-# UNPACK #-} !"
------------------------------
{-# DEPRECATED pprVarStrictType
"As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'pprVarBangType' instead." #-}
pprVarStrictType :: (Name, Strict, Type) -> Doc
pprVarStrictType = pprVarBangType
------------------------------
{-# DEPRECATED pprStrictType
"As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'pprBangType' instead." #-}
pprStrictType :: (Strict, Type) -> Doc
pprStrictType = pprBangType
------------------------------
pprParendType :: Type -> Doc
pprParendType (VarT v) = ppr v
pprParendType (ConT c) = ppr c
pprParendType (TupleT 0) = text "()"
pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma))
pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma
pprParendType ArrowT = parens (text "->")
pprParendType ListT = text "[]"
pprParendType (LitT l) = pprTyLit l
pprParendType (PromotedT c) = text "'" <> ppr c
pprParendType (PromotedTupleT 0) = text "'()"
pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma))
pprParendType PromotedNilT = text "'[]"
pprParendType PromotedConsT = text "(':)"
pprParendType StarT = char '*'
pprParendType ConstraintT = text "Constraint"
pprParendType (SigT ty k) = parens (ppr ty <+> text "::" <+> ppr k)
pprParendType WildCardT = char '_'
pprParendType (InfixT x n y) = parens (ppr x <+> pprName' Infix n <+> ppr y)
pprParendType t@(UInfixT {}) = parens (pprUInfixT t)
pprParendType (ParensT t) = ppr t
pprParendType tuple | (TupleT n, args) <- split tuple
, length args == n
= parens (commaSep args)
pprParendType other = parens (ppr other)
pprUInfixT :: Type -> Doc
pprUInfixT (UInfixT x n y) = pprUInfixT x <+> pprName' Infix n <+> pprUInfixT y
pprUInfixT t = ppr t
instance Ppr Type where
ppr (ForallT tvars ctxt ty)
= text "forall" <+> hsep (map ppr tvars) <+> text "."
<+> sep [pprCxt ctxt, ppr ty]
ppr ty = pprTyApp (split ty)
-- Works, in a degnerate way, for SigT, and puts parens round (ty :: kind)
-- See Note [Pretty-printing kind signatures]
{- Note [Pretty-printing kind signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC's parser only recognises a kind signature in a type when there are
parens around it. E.g. the parens are required here:
f :: (Int :: *)
type instance F Int = (Bool :: *)
So we always print a SigT with parens (see Trac #10050). -}
pprTyApp :: (Type, [Type]) -> Doc
pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2]
pprTyApp (EqualityT, [arg1, arg2]) =
sep [pprFunArgType arg1 <+> text "~", ppr arg2]
pprTyApp (ListT, [arg]) = brackets (ppr arg)
pprTyApp (TupleT n, args)
| length args == n = parens (commaSep args)
pprTyApp (PromotedTupleT n, args)
| length args == n = quoteParens (commaSep args)
pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args)
pprFunArgType :: Type -> Doc -- Should really use a precedence argument
-- Everything except forall and (->) binds more tightly than (->)
pprFunArgType ty@(ForallT {}) = parens (ppr ty)
pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty)
pprFunArgType ty@(SigT _ _) = parens (ppr ty)
pprFunArgType ty = ppr ty
split :: Type -> (Type, [Type]) -- Split into function and args
split t = go t []
where go (AppT t1 t2) args = go t1 (t2:args)
go ty args = (ty, args)
pprTyLit :: TyLit -> Doc
pprTyLit (NumTyLit n) = integer n
pprTyLit (StrTyLit s) = text (show s)
instance Ppr TyLit where
ppr = pprTyLit
------------------------------
instance Ppr TyVarBndr where
ppr (PlainTV nm) = ppr nm
ppr (KindedTV nm k) = parens (ppr nm <+> dcolon <+> ppr k)
instance Ppr Role where
ppr NominalR = text "nominal"
ppr RepresentationalR = text "representational"
ppr PhantomR = text "phantom"
ppr InferR = text "_"
------------------------------
pprCxt :: Cxt -> Doc
pprCxt [] = empty
pprCxt ts = ppr_cxt_preds ts <+> text "=>"
ppr_cxt_preds :: Cxt -> Doc
ppr_cxt_preds [] = empty
ppr_cxt_preds [t] = ppr t
ppr_cxt_preds ts = parens (commaSep ts)
------------------------------
instance Ppr Range where
ppr = brackets . pprRange
where pprRange :: Range -> Doc
pprRange (FromR e) = ppr e <> text ".."
pprRange (FromThenR e1 e2) = ppr e1 <> text ","
<> ppr e2 <> text ".."
pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2
pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text ","
<> ppr e2 <> text ".."
<> ppr e3
------------------------------
where_clause :: [Dec] -> Doc
where_clause [] = empty
where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds)
showtextl :: Show a => a -> Doc
showtextl = text . map toLower . show
hashParens :: Doc -> Doc
hashParens d = text "(# " <> d <> text " #)"
quoteParens :: Doc -> Doc
quoteParens d = text "'(" <> d <> text ")"
-----------------------------
instance Ppr Loc where
ppr (Loc { loc_module = md
, loc_package = pkg
, loc_start = (start_ln, start_col)
, loc_end = (end_ln, end_col) })
= hcat [ text pkg, colon, text md, colon
, parens $ int start_ln <> comma <> int start_col
, text "-"
, parens $ int end_ln <> comma <> int end_col ]
-- Takes a list of printable things and prints them separated by commas followed
-- by space.
commaSep :: Ppr a => [a] -> Doc
commaSep = commaSepWith ppr
-- Takes a list of things and prints them with the given pretty-printing
-- function, separated by commas followed by space.
commaSepWith :: (a -> Doc) -> [a] -> Doc
commaSepWith pprFun = sep . punctuate comma . map pprFun
-- Takes a list of printable things and prints them separated by semicolons
-- followed by space.
semiSep :: Ppr a => [a] -> Doc
semiSep = sep . punctuate semi . map ppr
| GaloisInc/halvm-ghc | libraries/template-haskell/Language/Haskell/TH/Ppr.hs | bsd-3-clause | 28,065 | 0 | 14 | 8,235 | 9,832 | 4,812 | 5,020 | 569 | 8 |
{-# LANGUAGE CPP, BangPatterns #-}
{-# OPTIONS -Wall #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.CFamily.Data.InputStream
-- Copyright : (c) 2008,2011 Benedikt Huber
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- Compile time input abstraction for the parser, relying on ByteString.
-- The String interface only supports Latin-1 since alex-3, as alex now requires
-- byte based access to the input stream.
-------------------------------------------------------------------------------
module Language.CFamily.Data.InputStream (
InputStream, readInputStream,inputStreamToString,inputStreamFromString,
takeByte, takeChar, inputStreamEmpty, takeChars,
countLines,
)
where
import Data.Word
#ifndef NO_BYTESTRING
import Data.ByteString (ByteString)
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BSC
#else
import qualified Data.Char as Char
#endif
-- Generic InputStream stuff
-- | read a file into an 'InputStream'
readInputStream :: FilePath -> IO InputStream
-- | convert 'InputStream' to 'String'
inputStreamToString :: InputStream -> String
{-# INLINE inputStreamToString #-}
-- | convert a 'String' to an 'InputStream'
inputStreamFromString :: String -> InputStream
-- | @(b,is') = takeByte is@ reads and removes
-- the first byte @b@ from the 'InputStream' @is@
takeByte :: InputStream -> (Word8, InputStream)
{-# INLINE takeByte #-}
-- | @(c,is') = takeChar is@ reads and removes
-- the first character @c@ from the 'InputStream' @is@
takeChar :: InputStream -> (Char, InputStream)
{-# INLINE takeChar #-}
-- | return @True@ if the given input stream is empty
inputStreamEmpty :: InputStream -> Bool
{-# INLINE inputStreamEmpty #-}
-- | @str = takeChars n is@ returns the first @n@ characters
-- of the given input stream, without removing them
takeChars :: Int -> InputStream -> [Char]
{-# INLINE takeChars #-}
-- | @countLines@ returns the number of text lines in the
-- given 'InputStream'
countLines :: InputStream -> Int
#ifndef NO_BYTESTRING
type InputStream = ByteString
takeByte bs = BSW.head bs `seq` (BSW.head bs, BSW.tail bs)
takeChar bs = BSC.head bs `seq` (BSC.head bs, BSC.tail bs)
inputStreamEmpty = BSW.null
#ifndef __HADDOCK__
takeChars !n bstr = BSC.unpack $ BSC.take n bstr --leaks
#endif
readInputStream = BSW.readFile
inputStreamToString = BSC.unpack
inputStreamFromString = BSC.pack
countLines = length . BSC.lines
#else
type InputStream = String
takeByte bs
| Char.isLatin1 c = let b = fromIntegral (Char.ord c) in b `seq` (b, tail bs)
| otherwise = error "takeByte: not a latin-1 character"
where c = head bs
takeChar bs = (head bs, tail bs)
inputStreamEmpty = null
takeChars n str = take n str
readInputStream = readFile
inputStreamToString = id
inputStreamFromString = id
countLines = length . lines
#endif
| micknelso/language-c | src/Language/CFamily/Data/InputStream.hs | bsd-3-clause | 2,994 | 0 | 8 | 493 | 345 | 216 | 129 | 32 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances, ViewPatterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.HyperDex.Client
-- Copyright : (c) Aaron Friel 2013
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : maybe
-- Portability : portable
--
-- UTF8 String and Text support for HyperDex.
--
-- A helper function to create attributes is exported.
--
-----------------------------------------------------------------------------
module Database.HyperDex.Utf8
( mkAttributeUtf8
, mkAttributeCheckUtf8
, mkMapAttributeUtf8
, mkMapAttributesFromMapUtf8
)
where
import Database.HyperDex.Internal.Data.Attribute
import Database.HyperDex.Internal.Data.AttributeCheck
import Database.HyperDex.Internal.Data.MapAttribute
import Database.HyperDex.Internal.Serialize
import Database.HyperDex.Internal.Data.Hyperdex
import Data.Serialize
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding
import Data.Map (Map)
instance HyperSerialize [Char] where
getH = remaining >>= getByteString >>= return . Text.unpack . decodeUtf8
putH = putByteString . encodeUtf8 . Text.pack
datatype = const HyperdatatypeString
instance HyperSerialize Text where
getH = remaining >>= getByteString >>= return . decodeUtf8
putH = putByteString . encodeUtf8
datatype = const HyperdatatypeString
-- | Create an attribute using a name serialized as a UTF8 bytestring.
mkAttributeUtf8 :: HyperSerialize a => Text -> a -> Attribute
mkAttributeUtf8 (encodeUtf8 -> name) value = mkAttribute name value
-- | Create an attribute using a name serialized as a UTF8 bytestring.
mkAttributeCheckUtf8 :: HyperSerialize a => Text -> a -> Hyperpredicate -> AttributeCheck
mkAttributeCheckUtf8 (encodeUtf8 -> name) = mkAttributeCheck name
-- | Create an attribute using a name serialized as a UTF8 bytestring.
mkMapAttributeUtf8 :: (HyperSerialize k, HyperSerialize v) => Text -> k -> v -> MapAttribute
mkMapAttributeUtf8 (encodeUtf8 -> name) = mkMapAttribute name
-- | Create an attribute using a name serialized as a UTF8 bytestring.
mkMapAttributesFromMapUtf8 :: (HyperSerialize k, HyperSerialize v) => Text -> Map k v -> [MapAttribute]
mkMapAttributesFromMapUtf8 = mkMapAttributesFromMap . encodeUtf8
| AaronFriel/hyhac | src/Database/HyperDex/Utf8.hs | bsd-3-clause | 2,349 | 0 | 9 | 330 | 397 | 232 | 165 | 33 | 1 |
module Automata where
import Sets
-- Estrutura de um automato finito nao deterministico
data Nfa a = NFA (Set a)
(Set (Move a))
a
(Set a)
deriving (Eq, Show)
--
data Move a = Move a Char a
|Emove a a
deriving (Eq, Ord, Show)
startstate :: Nfa a -> a
startstate (NFA s mov start final) = start
states :: Nfa a -> Set a
states (NFA s mov start final) = s
moves :: Nfa a -> Set (Move a)
moves (NFA s mov start final) = mov
finishstates :: Nfa a -> Set a
finishstates (NFA s mov start final) = final
trans :: Ord a => Nfa a -> String -> Set a
trans mach = foldl step startset
where
step set ch = onetrans mach ch set
startset = closure mach (sing (startstate mach))
trans2 :: Ord a => Nfa a -> String -> [(String,Set a)]
trans2 mach = transAux mach ""
where
transAux mach str [] = [(str,trans mach str)]
transAux mach str (y:ys) = (str,trans mach str) : transAux mach (str ++ [y]) ys
lastMatch :: Ord a => Nfa a -> String -> (String,Set a)
lastMatch mach str = lastM
where
fim = finishstates mach
matches = trans2 mach str
notEmpty = filter (not . isEmpty . inter fim . snd) matches
lastM = if null notEmpty
then ("", empty)
else last notEmpty
onetrans :: Ord a => Nfa a -> Char -> Set a -> Set a
onetrans mach c x = closure mach (onemove mach c x)
onetrans2 :: Ord a => Nfa a -> Char -> Set a -> (Set a,Set a)
onetrans2 mach@(NFA states moves start term) c x
= (r,f)
where
r = closure mach (onemove mach c x)
f = inter r term
onemove :: Ord a => Nfa a -> Char -> Set a -> Set a
onemove (NFA states moves start term) c x
= makeSet [s | t <- flatten x, Move z d s <- flatten moves, z == t, c == d]
closure :: Ord a => Nfa a -> Set a -> Set a
closure (NFA states moves start term) = setlimit add
where
add stateset = stateset `union` makeSet accessible
where
accessible
= [s | x <- flatten stateset, Emove y s <- flatten moves, y == x]
printNfa :: (Show a) => Nfa a -> String
printNfa (NFA states moves start finish)
= "States:\t" ++ showStates (flatten states) ++ "\n" ++
"Moves:\n" ++ concatMap printMove (flatten moves) ++ "\n" ++
"Start:\t" ++ show start ++ "\n" ++
"Finish:\t" ++ showStates (flatten finish) ++ "\n"
showStates :: (Show a) => [a] -> String
showStates = concatMap ((++ " ") . show)
printMove :: (Show a) => Move a -> String
printMove (Move s1 c s2) = "\t" ++ show s1 ++ "----(" ++ [c] ++ ")---->" ++ show s2 ++ "\n"
printMove (Emove s1 s2) = "\t" ++ show s1 ++ "----(@)---->" ++ show s2 ++ "\n"
| arthurmgo/regex-ftc | src/Automata.hs | bsd-3-clause | 2,764 | 0 | 18 | 853 | 1,221 | 611 | 610 | 60 | 2 |
module DropNth where
--(Problem 16) Drop every N'th element from a list.
dropNth :: [a] -> Int -> [a]
dropNth [] _ = []
dropNth y@(x:xs) n = (take (n - 1) y) ++ dropNth (drop 2 xs) n
| michael-j-clark/hjs99 | src/11to20/DropNth.hs | bsd-3-clause | 188 | 0 | 9 | 44 | 90 | 49 | 41 | 4 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | See "Control.Monad.Ether.Reader".
module Control.Monad.Ether.Implicit.Reader
(
-- * MonadReader class
MonadReader
, local
, ask
, reader
, asks
-- * The Reader monad
, Reader
, runReader
-- * The ReaderT monad transformer
, ReaderT
, readerT
, runReaderT
) where
import Data.Proxy
import qualified Control.Monad.Ether.Reader as Explicit
-- | See 'Control.Monad.Ether.Reader.ReaderT'.
type ReaderT r = Explicit.ReaderT r r
-- | See 'Control.Monad.Ether.Reader.Reader'.
type Reader r = Explicit.Reader r r
-- | See 'Control.Monad.Ether.Reader.readerT'.
readerT :: (r -> m a) -> ReaderT r m a
readerT = Explicit.readerT Proxy
-- | See 'Control.Monad.Ether.Reader.runReaderT'.
runReaderT :: ReaderT r m a -> r -> m a
runReaderT = Explicit.runReaderT Proxy
-- | See 'Control.Monad.Ether.Reader.runReader'.
runReader :: Reader r a -> r -> a
runReader = Explicit.runReader Proxy
-- | See 'Control.Monad.Ether.Reader.MonadReader'.
type MonadReader r = Explicit.MonadReader r r
-- | See 'Control.Monad.Ether.Reader.local'.
local :: forall m r a . MonadReader r m => (r -> r) -> m a -> m a
local = Explicit.local (Proxy :: Proxy r)
-- | See 'Control.Monad.Ether.Reader.ask'.
ask :: forall m r . MonadReader r m => m r
ask = Explicit.ask (Proxy :: Proxy r)
-- | See 'Control.Monad.Ether.Reader.reader'.
reader :: forall m r a . MonadReader r m => (r -> a) -> m a
reader = Explicit.reader (Proxy :: Proxy r)
-- | See 'Control.Monad.Ether.Reader.asks'.
asks :: forall m r a . MonadReader r m => (r -> a) -> m a
asks = Explicit.asks (Proxy :: Proxy r)
| bitemyapp/ether | src/Control/Monad/Ether/Implicit/Reader.hs | bsd-3-clause | 1,690 | 0 | 9 | 333 | 422 | 239 | 183 | 33 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.MessagePack.Types.Instances () where
import Data.Void (Void)
import Data.MessagePack.Types.Class (MessagePack)
import Data.MessagePack.Types.Generic ()
instance MessagePack a => MessagePack (Maybe a)
instance (MessagePack a, MessagePack b) => MessagePack (Either a b)
instance MessagePack Void
| SX91/hs-msgpack-types | src/Data/MessagePack/Types/Instances.hs | bsd-3-clause | 403 | 0 | 7 | 96 | 101 | 57 | 44 | 8 | 0 |
{-# LANGUAGE DoRec #-}
module LazyRec where
import Control.Monad.Trans.Writer
import Data.Maybe
type Symbol = String
type Line = Int
type SymData = (Symbol, Line)
type Stmt = (SymData, [String])
type Prog = [Stmt]
prog :: Prog
prog =
[ (("alma", 1), ["korte", "alma"])
, (("korte", 2), ["szilva"])
, (("szilva", 3), ["alma"])
]
type Ref = (Symbol, SymData)
refek :: Prog -> [Ref]
refek stmts =
let (allSyms, refs) = unzip $ map (stmtRefek allSyms) stmts
in concat refs
stmtRefek :: [SymData] -> Stmt -> (SymData, [Ref])
stmtRefek allSymData (symData, usedSyms) =
let thisSym = fst symData
addThisSym = map ((,) thisSym)
refs = addThisSym $ catMaybes $ map resolveSym usedSyms
in (symData, refs)
where
resolveSym s = listToMaybe $ filter (\sd -> fst sd == s) allSymData
stmtRefekM :: [SymData] -> Stmt -> Writer [Ref] SymData
stmtRefekM allSymData stmt =
writer $ stmtRefek allSymData stmt
refekM :: Prog -> [Ref]
refekM stmts =
let (allSyms, refs) = runWriter $ mapM (stmtRefekM allSyms) stmts
in refs
refekM2 :: Prog -> [Ref]
refekM2 stmts = snd . runWriter $ do
rec allSyms <- mapM (stmtRefekM allSyms) stmts
return allSyms
main = do
--mapM_ print $ refek prog
mapM_ print $ refekM2 prog
| robinp/haskell-toys | src/Toys/LazyRec.hs | bsd-3-clause | 1,248 | 0 | 13 | 258 | 500 | 277 | 223 | 39 | 1 |
module Win32Font
{-
( CharSet
, PitchAndFamily
, OutPrecision
, ClipPrecision
, FontQuality
, FontWeight
, createFont, deleteFont
, StockFont, getStockFont
, oEM_FIXED_FONT, aNSI_FIXED_FONT, aNSI_VAR_FONT, sYSTEM_FONT
, dEVICE_DEFAULT_FONT, sYSTEM_FIXED_FONT
) where
-}
where
import StdDIS
import Win32Types
import GDITypes
----------------------------------------------------------------
-- Types
----------------------------------------------------------------
type CharSet = UINT
type PitchAndFamily = UINT
type OutPrecision = UINT
type ClipPrecision = UINT
type FontQuality = UINT
type FontWeight = Word32
type FaceName = String
-- # A FaceName is a string no more that LF_FACESIZE in length
-- # (including null terminator).
-- %const Int LF_FACESIZE # == 32
-- %sentinel_array : FaceName : CHAR : char : $0 = '\0' : ('\0' == $0) : LF_FACESIZE
----------------------------------------------------------------
-- Constants
----------------------------------------------------------------
aNSI_CHARSET :: CharSet
aNSI_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_aNSI_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_aNSI_CHARSET :: IO (Word32)
dEFAULT_CHARSET :: CharSet
dEFAULT_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_dEFAULT_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_dEFAULT_CHARSET :: IO (Word32)
sYMBOL_CHARSET :: CharSet
sYMBOL_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_sYMBOL_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_sYMBOL_CHARSET :: IO (Word32)
sHIFTJIS_CHARSET :: CharSet
sHIFTJIS_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_sHIFTJIS_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_sHIFTJIS_CHARSET :: IO (Word32)
hANGEUL_CHARSET :: CharSet
hANGEUL_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_hANGEUL_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_hANGEUL_CHARSET :: IO (Word32)
cHINESEBIG5_CHARSET :: CharSet
cHINESEBIG5_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_cHINESEBIG5_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cHINESEBIG5_CHARSET :: IO (Word32)
oEM_CHARSET :: CharSet
oEM_CHARSET =
unsafePerformIO(
prim_Win32Font_cpp_oEM_CHARSET >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oEM_CHARSET :: IO (Word32)
dEFAULT_PITCH :: PitchAndFamily
dEFAULT_PITCH =
unsafePerformIO(
prim_Win32Font_cpp_dEFAULT_PITCH >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_dEFAULT_PITCH :: IO (Word32)
fIXED_PITCH :: PitchAndFamily
fIXED_PITCH =
unsafePerformIO(
prim_Win32Font_cpp_fIXED_PITCH >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fIXED_PITCH :: IO (Word32)
vARIABLE_PITCH :: PitchAndFamily
vARIABLE_PITCH =
unsafePerformIO(
prim_Win32Font_cpp_vARIABLE_PITCH >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_vARIABLE_PITCH :: IO (Word32)
fF_DONTCARE :: PitchAndFamily
fF_DONTCARE =
unsafePerformIO(
prim_Win32Font_cpp_fF_DONTCARE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_DONTCARE :: IO (Word32)
fF_ROMAN :: PitchAndFamily
fF_ROMAN =
unsafePerformIO(
prim_Win32Font_cpp_fF_ROMAN >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_ROMAN :: IO (Word32)
fF_SWISS :: PitchAndFamily
fF_SWISS =
unsafePerformIO(
prim_Win32Font_cpp_fF_SWISS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_SWISS :: IO (Word32)
fF_MODERN :: PitchAndFamily
fF_MODERN =
unsafePerformIO(
prim_Win32Font_cpp_fF_MODERN >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_MODERN :: IO (Word32)
fF_SCRIPT :: PitchAndFamily
fF_SCRIPT =
unsafePerformIO(
prim_Win32Font_cpp_fF_SCRIPT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_SCRIPT :: IO (Word32)
fF_DECORATIVE :: PitchAndFamily
fF_DECORATIVE =
unsafePerformIO(
prim_Win32Font_cpp_fF_DECORATIVE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fF_DECORATIVE :: IO (Word32)
familyMask :: PitchAndFamily
familyMask =
unsafePerformIO(
prim_Win32Font_cpp_familyMask >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_familyMask :: IO (Word32)
pitchMask :: PitchAndFamily
pitchMask =
unsafePerformIO(
prim_Win32Font_cpp_pitchMask >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_pitchMask :: IO (Word32)
oUT_DEFAULT_PRECIS :: OutPrecision
oUT_DEFAULT_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_DEFAULT_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_DEFAULT_PRECIS :: IO (Word32)
oUT_STRING_PRECIS :: OutPrecision
oUT_STRING_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_STRING_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_STRING_PRECIS :: IO (Word32)
oUT_CHARACTER_PRECIS :: OutPrecision
oUT_CHARACTER_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_CHARACTER_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_CHARACTER_PRECIS :: IO (Word32)
oUT_STROKE_PRECIS :: OutPrecision
oUT_STROKE_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_STROKE_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_STROKE_PRECIS :: IO (Word32)
oUT_TT_PRECIS :: OutPrecision
oUT_TT_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_TT_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_TT_PRECIS :: IO (Word32)
oUT_DEVICE_PRECIS :: OutPrecision
oUT_DEVICE_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_DEVICE_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_DEVICE_PRECIS :: IO (Word32)
oUT_RASTER_PRECIS :: OutPrecision
oUT_RASTER_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_RASTER_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_RASTER_PRECIS :: IO (Word32)
oUT_TT_ONLY_PRECIS :: OutPrecision
oUT_TT_ONLY_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_oUT_TT_ONLY_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_oUT_TT_ONLY_PRECIS :: IO (Word32)
cLIP_DEFAULT_PRECIS :: ClipPrecision
cLIP_DEFAULT_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_DEFAULT_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_DEFAULT_PRECIS :: IO (Word32)
cLIP_CHARACTER_PRECIS :: ClipPrecision
cLIP_CHARACTER_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_CHARACTER_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_CHARACTER_PRECIS :: IO (Word32)
cLIP_STROKE_PRECIS :: ClipPrecision
cLIP_STROKE_PRECIS =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_STROKE_PRECIS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_STROKE_PRECIS :: IO (Word32)
cLIP_MASK :: ClipPrecision
cLIP_MASK =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_MASK >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_MASK :: IO (Word32)
cLIP_LH_ANGLES :: ClipPrecision
cLIP_LH_ANGLES =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_LH_ANGLES >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_LH_ANGLES :: IO (Word32)
cLIP_TT_ALWAYS :: ClipPrecision
cLIP_TT_ALWAYS =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_TT_ALWAYS >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_TT_ALWAYS :: IO (Word32)
cLIP_EMBEDDED :: ClipPrecision
cLIP_EMBEDDED =
unsafePerformIO(
prim_Win32Font_cpp_cLIP_EMBEDDED >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_cLIP_EMBEDDED :: IO (Word32)
dEFAULT_QUALITY :: FontQuality
dEFAULT_QUALITY =
unsafePerformIO(
prim_Win32Font_cpp_dEFAULT_QUALITY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_dEFAULT_QUALITY :: IO (Word32)
dRAFT_QUALITY :: FontQuality
dRAFT_QUALITY =
unsafePerformIO(
prim_Win32Font_cpp_dRAFT_QUALITY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_dRAFT_QUALITY :: IO (Word32)
pROOF_QUALITY :: FontQuality
pROOF_QUALITY =
unsafePerformIO(
prim_Win32Font_cpp_pROOF_QUALITY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_pROOF_QUALITY :: IO (Word32)
fW_DONTCARE :: FontWeight
fW_DONTCARE =
unsafePerformIO(
prim_Win32Font_cpp_fW_DONTCARE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_DONTCARE :: IO (Word32)
fW_THIN :: FontWeight
fW_THIN =
unsafePerformIO(
prim_Win32Font_cpp_fW_THIN >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_THIN :: IO (Word32)
fW_EXTRALIGHT :: FontWeight
fW_EXTRALIGHT =
unsafePerformIO(
prim_Win32Font_cpp_fW_EXTRALIGHT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_EXTRALIGHT :: IO (Word32)
fW_LIGHT :: FontWeight
fW_LIGHT =
unsafePerformIO(
prim_Win32Font_cpp_fW_LIGHT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_LIGHT :: IO (Word32)
fW_NORMAL :: FontWeight
fW_NORMAL =
unsafePerformIO(
prim_Win32Font_cpp_fW_NORMAL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_NORMAL :: IO (Word32)
fW_MEDIUM :: FontWeight
fW_MEDIUM =
unsafePerformIO(
prim_Win32Font_cpp_fW_MEDIUM >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_MEDIUM :: IO (Word32)
fW_SEMIBOLD :: FontWeight
fW_SEMIBOLD =
unsafePerformIO(
prim_Win32Font_cpp_fW_SEMIBOLD >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_SEMIBOLD :: IO (Word32)
fW_BOLD :: FontWeight
fW_BOLD =
unsafePerformIO(
prim_Win32Font_cpp_fW_BOLD >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_BOLD :: IO (Word32)
fW_EXTRABOLD :: FontWeight
fW_EXTRABOLD =
unsafePerformIO(
prim_Win32Font_cpp_fW_EXTRABOLD >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_EXTRABOLD :: IO (Word32)
fW_HEAVY :: FontWeight
fW_HEAVY =
unsafePerformIO(
prim_Win32Font_cpp_fW_HEAVY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_HEAVY :: IO (Word32)
fW_REGULAR :: FontWeight
fW_REGULAR =
unsafePerformIO(
prim_Win32Font_cpp_fW_REGULAR >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Font_cpp_fW_REGULAR :: IO (Word32)
----------------------------------------------------------------
-- Functions
----------------------------------------------------------------
createFont :: INT -> INT -> INT -> INT -> FontWeight -> Bool -> Bool -> Bool -> CharSet -> OutPrecision -> ClipPrecision -> FontQuality -> PitchAndFamily -> FaceName -> IO HFONT
createFont gc_arg1 gc_arg2 gc_arg3 gc_arg4 arg5 gc_arg5 gc_arg6 gc_arg7 arg9 arg10 arg11 arg12 arg13 gc_arg8 =
case ( fromIntegral gc_arg1) of { arg1 ->
case ( fromIntegral gc_arg2) of { arg2 ->
case ( fromIntegral gc_arg3) of { arg3 ->
case ( fromIntegral gc_arg4) of { arg4 ->
(marshall_bool_ gc_arg5) >>= \ (arg6) ->
(marshall_bool_ gc_arg6) >>= \ (arg7) ->
(marshall_bool_ gc_arg7) >>= \ (arg8) ->
(marshall_string_ gc_arg8) >>= \ (arg14) ->
prim_Win32Font_cpp_createFont arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12 arg13 arg14 >>= \ (res1,gc_failed,gc_failstring) ->
if ( gc_failed /= (0::Int))
then unmarshall_string_ gc_failstring >>= ioError . userError
else (return (res1))}}}}
primitive prim_Win32Font_cpp_createFont :: Int -> Int -> Int -> Int -> Word32 -> Int -> Int -> Int -> Word32 -> Word32 -> Word32 -> Word32 -> Word32 -> Addr -> IO (Addr,Int,Addr)
-- test :: IO ()
-- test = do
-- f <- createFont_adr (100,100) 0 False False "Arial"
-- putStrLn "Created first font"
-- f <- createFont_adr (100,100) (-90) False False "Bogus"
-- putStrLn "Created second font"
--
-- createFont_adr (width, height) escapement bold italic family =
-- createFont height width
-- (round (escapement * 1800/pi))
-- 0 -- orientation
-- weight
-- italic False False -- italic, underline, strikeout
-- aNSI_CHARSET
-- oUT_DEFAULT_PRECIS
-- cLIP_DEFAULT_PRECIS
-- dEFAULT_QUALITY
-- dEFAULT_PITCH
-- family
-- where
-- weight | bold = fW_BOLD
-- | otherwise = fW_NORMAL
-- missing CreateFontIndirect from WinFonts.ss; GSL ???
deleteFont :: HFONT -> IO ()
deleteFont arg1 =
prim_Win32Font_cpp_deleteFont arg1
primitive prim_Win32Font_cpp_deleteFont :: Addr -> IO ()
----------------------------------------------------------------
type StockFont = WORD
oEM_FIXED_FONT :: StockFont
oEM_FIXED_FONT =
unsafePerformIO(
prim_Win32Font_cpp_oEM_FIXED_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_oEM_FIXED_FONT :: IO (Word32)
aNSI_FIXED_FONT :: StockFont
aNSI_FIXED_FONT =
unsafePerformIO(
prim_Win32Font_cpp_aNSI_FIXED_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_aNSI_FIXED_FONT :: IO (Word32)
aNSI_VAR_FONT :: StockFont
aNSI_VAR_FONT =
unsafePerformIO(
prim_Win32Font_cpp_aNSI_VAR_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_aNSI_VAR_FONT :: IO (Word32)
sYSTEM_FONT :: StockFont
sYSTEM_FONT =
unsafePerformIO(
prim_Win32Font_cpp_sYSTEM_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_sYSTEM_FONT :: IO (Word32)
dEVICE_DEFAULT_FONT :: StockFont
dEVICE_DEFAULT_FONT =
unsafePerformIO(
prim_Win32Font_cpp_dEVICE_DEFAULT_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_dEVICE_DEFAULT_FONT :: IO (Word32)
sYSTEM_FIXED_FONT :: StockFont
sYSTEM_FIXED_FONT =
unsafePerformIO(
prim_Win32Font_cpp_sYSTEM_FIXED_FONT >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Font_cpp_sYSTEM_FIXED_FONT :: IO (Word32)
getStockFont :: StockFont -> IO HFONT
getStockFont gc_arg1 =
case ( fromIntegral gc_arg1) of { arg1 ->
prim_Win32Font_cpp_getStockFont arg1 >>= \ (res1) ->
(return (res1))}
primitive prim_Win32Font_cpp_getStockFont :: Word32 -> IO (Addr)
----------------------------------------------------------------
-- End
----------------------------------------------------------------
needPrims_hugs 2
| OS2World/DEV-UTIL-HUGS | libraries/win32/Win32Font.hs | bsd-3-clause | 14,409 | 143 | 31 | 2,242 | 3,506 | 1,906 | 1,600 | -1 | -1 |
module Simplify where
import Prelude hiding (pi, abs)
import Lang.LF
import Terms
import qualified Debug.Trace as Debug
data BindData (γ :: Ctx *) where
BindEmpty :: BindData E
BindLetcont :: BindData γ
-> LF γ TERM {- :: v ==> term -}
-> BindData (γ ::> b)
BindOpaque :: BindData γ
-> BindData (γ ::> b)
BindLetval :: BindData γ
-> Bool -- Has at most one occurance?
-> Bool -- Is cheap?
-> LF γ TERM {- :: val -}
-> BindData (γ ::> b)
BindLetproj :: BindData γ
-> Bool {- False = fst, True = snd -}
-> LF γ TERM {- :: v -}
-> BindData (γ ::> b)
lookupContData :: BindData γ
-> Var γ
-> Maybe (LF γ TERM)
lookupContData = go WeakRefl
where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (LF γ' TERM)
go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v
go w (BindOpaque bd) (F v) = go (WeakRight w) bd v
go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v
go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v
go w (BindLetcont _ v) B = Just (weaken (WeakRight w) v)
go _ _ _ = Nothing
lookupValData :: BindData γ
-> Var γ
-> Maybe (Bool, Bool, LF γ TERM)
lookupValData = go WeakRefl
where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (Bool, Bool, LF γ' TERM)
go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v
go w (BindOpaque bd) (F v) = go (WeakRight w) bd v
go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v
go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v
go w (BindLetval _ lin cheap val) B = Just (lin, cheap, weaken (WeakRight w) val)
go _ _ _ = Nothing
lookupProjData :: BindData γ
-> Var γ
-> Maybe (Bool, LF γ TERM)
lookupProjData = go WeakRefl
where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (Bool, LF γ' TERM)
go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v
go w (BindOpaque bd) (F v) = go (WeakRight w) bd v
go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v
go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v
go w (BindLetproj _ b v) B = Just (b, weaken (WeakRight w) v)
go _ _ _ = Nothing
dropData :: Var γ
-> Int
-> BindData γ
-> BindData γ
dropData v n bd
| n <= 1 = bd
| otherwise = go bd v
where go :: BindData γ -> Var γ -> BindData γ
go (BindLetcont bd k) (F v) = BindLetcont (go bd v) k
go (BindOpaque bd) (F v) = BindOpaque (go bd v)
go (BindLetval bd lin cheap val) (F v) = BindLetval (go bd v) lin cheap val
go (BindLetproj bd x y) (F v) = BindLetproj (go bd v) x y
go (BindLetcont bd _) B = BindOpaque bd
go (BindLetval bd _ cheap val) B = BindLetval bd False cheap val
go (BindLetproj bd _ _) B = BindOpaque bd
go bd _ = bd
newtype InlineHeuristic
= InlineHeuristic
{ applyHeuristic :: forall γ. LF γ TERM -> Bool }
simplifier :: forall γ
. (LiftClosed γ
, ?hyps :: H γ
, ?soln :: LFSoln LF
, ?ischeap :: InlineHeuristic
)
=> BindData γ
-> LF γ TERM
-> M (LF γ TERM)
simplifier bd (termView -> VConst "letcont" [k,m]) = do
-- first, simplify inside the bound continuation body
k' <- case termView k of
VLam nm x t km -> do
q <- simplifier (BindOpaque bd) km
mkLam nm x t q
_ -> fail "simplifier: expected function in 'letcont'"
case tryEtaCont k' of
Just j ->
Debug.trace "η-CONT" $ do
j' <- j
m' <- return m @@ return j'
let bd' = case termView j' of
VVar vj [] -> dropData vj (varCensus vj m') bd
_ -> bd
simplifier bd' m'
_ -> do
-- next, simplify inside the body of the 'letcont'
case termView m of
VLam nm x t m' -> do
q <- if (varCensus x m' == 1) then do
simplifier (BindLetcont bd k') m'
else
Debug.trace ("CONT multiple occur: " ++ show (varCensus x m')) $
simplifier (BindOpaque bd) m'
-- DEAD-cont. remove dead code if the 'letcont' variable is now unused
if freeVar x q then
"letcont" @@ (return k') @@ (mkLam nm x t q)
else
Debug.trace "DEAD-CONT" $
strengthen q
_ -> fail "simplifier: expected function in 'letcont' body"
-- η-CONT rule. If the bound contnuation is just an η-expanded
-- version of 'j', replace the bound variable in the body with 'j'
-- and drop the 'letcont'
where tryEtaCont :: LF γ TERM -> Maybe (M (LF γ TERM))
tryEtaCont (termView -> VLam _ x _
(termView -> VConst "enter" [ j, termView -> VVar x' []]))
| x == x' =
case termView j of
VVar (F j') [] -> Just $ mkVar j'
VConst c [] -> Just $ tmConst c
_ -> Nothing
tryEtaCont _ = Nothing
simplifier bd (termView -> VConst "letval" [v0,m]) = do
-- first simplify the value
v <- simplifyVal bd v0
let hyps = ?hyps
case termView v of
-- η-FUN rule. If the bound value is just an η-expanded 'g', then replace
-- the body of the let with 'g' and drop the let.
VConst "lam" [termView -> VLam _ k _ (termView -> VLam _ x _ (termView ->
VConst "app" [ termView -> VVar (F (F g)) []
, termView -> VVar (F k') []
, termView -> VVar x' []
]))]
| k == k', x == x' ->
let ?hyps = hyps in
Debug.trace "η-FUN" $
simplifier bd =<< (return m) @@ (var g)
-- η-PAIR rule. If a pair is bound in a context where the components of the
-- pair were previously projected from a pair variable, replace the reconstructed
-- pair with the original variable. (NB: this rule is only valid for strict pairs)
VConst "pair" [ termView -> VVar x []
, termView -> VVar y []
]
| Just (True, vx) <- lookupProjData bd x
, Just (False,vy) <- lookupProjData bd y
, alphaEq vx vy ->
Debug.trace "η-PAIR" $ do
m' <- return m @@ return vx
let bd' = case termView vx of
VVar vx' [] -> dropData vx' (varCensus vx' m') bd
_ -> bd
simplifier bd' m'
-- η-UNIT rule. Replace every let-binding of tt with a distinguished
-- variable standing for the constant unit value
VConst "tt" [] ->
Debug.trace "η-UNIT" $ do
simplifier bd =<< (return m) @@ "tt_CAF"
-- otherwise, recurse
_ -> case termView m of
VLam nm x t m' -> do
q <- let bd' = BindLetval bd (varCensus x m' <= 1)
(applyHeuristic ?ischeap v)
v in
simplifier bd' m'
-- DEAD-val remove dead code if the 'letval' variable is now unused
if freeVar x q then
"letval" @@ return v @@ mkLam nm x t q
else
Debug.trace "DEAD-VAL" $
strengthen q
_ -> fail "simplifier: expected function in 'letval'"
simplifier bd (termView -> VConst "let_prj1" [v, m]) = do
let bd' = BindLetproj bd False v
case termView v of
-- β-PAIR1 rule
VVar v' []
| Just (_, _, termView -> VConst "pair" [x,_]) <- lookupValData bd v' ->
Debug.trace "β-PAIR1" $ do
m' <- return m @@ return x
let bd' = case termView x of
VVar x' [] -> dropData x' (varCensus x' m') bd
_ -> bd
simplifier bd' m'
_ ->
case termView m of
VLam nm x t m' -> do
q <- simplifier bd' m'
-- DEAD-proj. remove dead code if the 'let_prj' variable is now unused
if freeVar x q then
"let_prj1" @@ return v @@ mkLam nm x t q
else
Debug.trace "DEAD-PROJ1" $
strengthen q
_ -> fail "simplifier: expected function in 'let_prj1'"
simplifier bd (termView -> VConst "let_prj2" [ v, m]) = do
let bd' = BindLetproj bd True v
case termView v of
-- β-PAIR2 rule
VVar v' []
| Just (_, _, termView -> VConst "pair" [_,y]) <- lookupValData bd v' ->
Debug.trace "β-PAIR2" $ do
m' <- return m @@ return y
let bd' = case termView y of
VVar y' [] -> dropData y' (varCensus y' m') bd
_ -> bd
simplifier bd' m'
_ ->
case termView m of
VLam nm x t m' -> do
q <- simplifier bd' m'
-- DEAD-proj. remove dead code if the 'let_prj' variable is now unused
if freeVar x q then
"let_prj2" @@ return v @@ mkLam nm x t q
else
Debug.trace "DEAD-PROJ2" $
strengthen q
_ -> fail "simplifier: expected function in 'let_prj2'"
simplifier bd (termView -> VConst "enter" [termView -> VVar kv [], x])
| Just cont <- lookupContData bd kv =
Debug.trace "β-CONT" $ do
cont' <- return cont @@ return x
let bd' =
case termView x of
VVar x' [] -> dropData x' (varCensus x' cont') bd
_ -> bd
simplifier bd' cont'
simplifier bd (termView -> VConst "app" [ termView -> VVar f [], j, y])
| Just (lin, cheap, termView -> VConst "lam" [m]) <- lookupValData bd f
, lin || cheap =
Debug.trace "β-FUN" $ do
m' <- return m @@ return j @@ return y
let bd' =
(case termView j of
VVar j' [] -> dropData j' (varCensus j' m')
_ -> id) $
(case termView y of
VVar y' [] -> dropData y' (varCensus y' m')
_ -> id) $
bd
simplifier bd' m'
simplifier bd m@(termView -> VConst "case" [e,l,r]) = do
case termView e of
VVar e' []
-- β-CASE rules. If we case on an 'inl' or 'inr' value, simply
-- enter the correct continuation.
| Just (_, _, termView -> VConst "inl" [x]) <- lookupValData bd e' ->
Debug.trace "β-CASE-L" $
simplifier bd =<< "enter" @@ return l @@ return x
| Just (_, _, termView -> VConst "inr" [x]) <- lookupValData bd e' ->
Debug.trace "β-CASE-R" $
simplifier bd =<< "enter" @@ return r @@ return x
_ -> case (termView l, termView r) of
-- η-case rule. If the branches of a case simply reconstitute
-- an either value and then enter the same continuation, we can skip
-- the case and just enter the continuation. (NB: this rule is only valid
-- for strict languages).
(VVar l' [], VVar r' [])
| Just lk <- lookupContData bd l'
, Just rk <- lookupContData bd r'
, Just k1 <- tryEtaCase "inl" lk
, Just k2 <- tryEtaCase "inr" rk
, k1 == k2 ->
Debug.trace "η-CASE"
simplifier bd =<< "enter" @@ var k1 @@ return e
_ -> return m
where
tryEtaCase :: String -> LF γ TERM -> Maybe (Var γ)
tryEtaCase con m =
case termView m of
VLam _ x _ (termView ->
VConst "letval" [ termView -> VConst (CNm con') [termView -> VVar x' []]
, termView -> VLam _ y _ (termView ->
VConst "enter" [ termView -> VVar (F (F k)) []
, termView -> VVar y' []
])
])
| con == con', x == x', y == y' -> Just k
_ -> Nothing
-- No other rule applies, just return the term
simplifier _ m = return m
simplifyVal :: forall γ
. (LiftClosed γ, ?hyps :: H γ
, ?soln :: LFSoln LF
, ?ischeap :: InlineHeuristic
)
=> BindData γ
-> LF γ TERM
-> M (LF γ TERM)
-- Simplify inside the body of lambdas
simplifyVal bd (termView -> VConst "lam"
[termView -> VLam jnm j jt
(termView -> VLam xnm x xt m)
]) = do
let bd' = BindOpaque (BindOpaque bd)
m' <- simplifier bd' m
"lam" @@ (mkLam jnm j jt =<< mkLam xnm x xt m')
-- otherwise return the term unchanged
simplifyVal _ m = return m
| robdockins/canonical-lf | toyml/Simplify.hs | bsd-3-clause | 13,373 | 0 | 26 | 5,522 | 4,399 | 2,123 | 2,276 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Test.AWS.Gen.SWF
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Test.AWS.Gen.SWF where
import Data.Proxy
import Test.AWS.Fixture
import Test.AWS.Prelude
import Test.Tasty
import Network.AWS.SWF
import Test.AWS.SWF.Internal
-- Auto-generated: the actual test selection needs to be manually placed into
-- the top-level so that real test data can be incrementally added.
--
-- This commented snippet is what the entire set should look like:
-- fixtures :: TestTree
-- fixtures =
-- [ testGroup "request"
-- [ testListOpenWorkflowExecutions $
-- listOpenWorkflowExecutions
--
-- , testRegisterActivityType $
-- registerActivityType
--
-- , testListActivityTypes $
-- listActivityTypes
--
-- , testCountPendingActivityTasks $
-- countPendingActivityTasks
--
-- , testRegisterWorkflowType $
-- registerWorkflowType
--
-- , testListWorkflowTypes $
-- listWorkflowTypes
--
-- , testRespondActivityTaskFailed $
-- respondActivityTaskFailed
--
-- , testCountOpenWorkflowExecutions $
-- countOpenWorkflowExecutions
--
-- , testDescribeWorkflowType $
-- describeWorkflowType
--
-- , testDeprecateWorkflowType $
-- deprecateWorkflowType
--
-- , testRequestCancelWorkflowExecution $
-- requestCancelWorkflowExecution
--
-- , testRegisterDomain $
-- registerDomain
--
-- , testRespondDecisionTaskCompleted $
-- respondDecisionTaskCompleted
--
-- , testPollForActivityTask $
-- pollForActivityTask
--
-- , testRespondActivityTaskCompleted $
-- respondActivityTaskCompleted
--
-- , testDescribeWorkflowExecution $
-- describeWorkflowExecution
--
-- , testSignalWorkflowExecution $
-- signalWorkflowExecution
--
-- , testCountPendingDecisionTasks $
-- countPendingDecisionTasks
--
-- , testListClosedWorkflowExecutions $
-- listClosedWorkflowExecutions
--
-- , testRecordActivityTaskHeartbeat $
-- recordActivityTaskHeartbeat
--
-- , testDescribeDomain $
-- describeDomain
--
-- , testGetWorkflowExecutionHistory $
-- getWorkflowExecutionHistory
--
-- , testDeprecateDomain $
-- deprecateDomain
--
-- , testTerminateWorkflowExecution $
-- terminateWorkflowExecution
--
-- , testDescribeActivityType $
-- describeActivityType
--
-- , testDeprecateActivityType $
-- deprecateActivityType
--
-- , testCountClosedWorkflowExecutions $
-- countClosedWorkflowExecutions
--
-- , testRespondActivityTaskCanceled $
-- respondActivityTaskCanceled
--
-- , testStartWorkflowExecution $
-- startWorkflowExecution
--
-- , testPollForDecisionTask $
-- pollForDecisionTask
--
-- , testListDomains $
-- listDomains
--
-- ]
-- , testGroup "response"
-- [ testListOpenWorkflowExecutionsResponse $
-- workflowExecutionInfos
--
-- , testRegisterActivityTypeResponse $
-- registerActivityTypeResponse
--
-- , testListActivityTypesResponse $
-- listActivityTypesResponse
--
-- , testCountPendingActivityTasksResponse $
-- pendingTaskCount
--
-- , testRegisterWorkflowTypeResponse $
-- registerWorkflowTypeResponse
--
-- , testListWorkflowTypesResponse $
-- listWorkflowTypesResponse
--
-- , testRespondActivityTaskFailedResponse $
-- respondActivityTaskFailedResponse
--
-- , testCountOpenWorkflowExecutionsResponse $
-- workflowExecutionCount
--
-- , testDescribeWorkflowTypeResponse $
-- describeWorkflowTypeResponse
--
-- , testDeprecateWorkflowTypeResponse $
-- deprecateWorkflowTypeResponse
--
-- , testRequestCancelWorkflowExecutionResponse $
-- requestCancelWorkflowExecutionResponse
--
-- , testRegisterDomainResponse $
-- registerDomainResponse
--
-- , testRespondDecisionTaskCompletedResponse $
-- respondDecisionTaskCompletedResponse
--
-- , testPollForActivityTaskResponse $
-- pollForActivityTaskResponse
--
-- , testRespondActivityTaskCompletedResponse $
-- respondActivityTaskCompletedResponse
--
-- , testDescribeWorkflowExecutionResponse $
-- describeWorkflowExecutionResponse
--
-- , testSignalWorkflowExecutionResponse $
-- signalWorkflowExecutionResponse
--
-- , testCountPendingDecisionTasksResponse $
-- pendingTaskCount
--
-- , testListClosedWorkflowExecutionsResponse $
-- workflowExecutionInfos
--
-- , testRecordActivityTaskHeartbeatResponse $
-- recordActivityTaskHeartbeatResponse
--
-- , testDescribeDomainResponse $
-- describeDomainResponse
--
-- , testGetWorkflowExecutionHistoryResponse $
-- getWorkflowExecutionHistoryResponse
--
-- , testDeprecateDomainResponse $
-- deprecateDomainResponse
--
-- , testTerminateWorkflowExecutionResponse $
-- terminateWorkflowExecutionResponse
--
-- , testDescribeActivityTypeResponse $
-- describeActivityTypeResponse
--
-- , testDeprecateActivityTypeResponse $
-- deprecateActivityTypeResponse
--
-- , testCountClosedWorkflowExecutionsResponse $
-- workflowExecutionCount
--
-- , testRespondActivityTaskCanceledResponse $
-- respondActivityTaskCanceledResponse
--
-- , testStartWorkflowExecutionResponse $
-- startWorkflowExecutionResponse
--
-- , testPollForDecisionTaskResponse $
-- pollForDecisionTaskResponse
--
-- , testListDomainsResponse $
-- listDomainsResponse
--
-- ]
-- ]
-- Requests
testListOpenWorkflowExecutions :: ListOpenWorkflowExecutions -> TestTree
testListOpenWorkflowExecutions = req
"ListOpenWorkflowExecutions"
"fixture/ListOpenWorkflowExecutions.yaml"
testRegisterActivityType :: RegisterActivityType -> TestTree
testRegisterActivityType = req
"RegisterActivityType"
"fixture/RegisterActivityType.yaml"
testListActivityTypes :: ListActivityTypes -> TestTree
testListActivityTypes = req
"ListActivityTypes"
"fixture/ListActivityTypes.yaml"
testCountPendingActivityTasks :: CountPendingActivityTasks -> TestTree
testCountPendingActivityTasks = req
"CountPendingActivityTasks"
"fixture/CountPendingActivityTasks.yaml"
testRegisterWorkflowType :: RegisterWorkflowType -> TestTree
testRegisterWorkflowType = req
"RegisterWorkflowType"
"fixture/RegisterWorkflowType.yaml"
testListWorkflowTypes :: ListWorkflowTypes -> TestTree
testListWorkflowTypes = req
"ListWorkflowTypes"
"fixture/ListWorkflowTypes.yaml"
testRespondActivityTaskFailed :: RespondActivityTaskFailed -> TestTree
testRespondActivityTaskFailed = req
"RespondActivityTaskFailed"
"fixture/RespondActivityTaskFailed.yaml"
testCountOpenWorkflowExecutions :: CountOpenWorkflowExecutions -> TestTree
testCountOpenWorkflowExecutions = req
"CountOpenWorkflowExecutions"
"fixture/CountOpenWorkflowExecutions.yaml"
testDescribeWorkflowType :: DescribeWorkflowType -> TestTree
testDescribeWorkflowType = req
"DescribeWorkflowType"
"fixture/DescribeWorkflowType.yaml"
testDeprecateWorkflowType :: DeprecateWorkflowType -> TestTree
testDeprecateWorkflowType = req
"DeprecateWorkflowType"
"fixture/DeprecateWorkflowType.yaml"
testRequestCancelWorkflowExecution :: RequestCancelWorkflowExecution -> TestTree
testRequestCancelWorkflowExecution = req
"RequestCancelWorkflowExecution"
"fixture/RequestCancelWorkflowExecution.yaml"
testRegisterDomain :: RegisterDomain -> TestTree
testRegisterDomain = req
"RegisterDomain"
"fixture/RegisterDomain.yaml"
testRespondDecisionTaskCompleted :: RespondDecisionTaskCompleted -> TestTree
testRespondDecisionTaskCompleted = req
"RespondDecisionTaskCompleted"
"fixture/RespondDecisionTaskCompleted.yaml"
testPollForActivityTask :: PollForActivityTask -> TestTree
testPollForActivityTask = req
"PollForActivityTask"
"fixture/PollForActivityTask.yaml"
testRespondActivityTaskCompleted :: RespondActivityTaskCompleted -> TestTree
testRespondActivityTaskCompleted = req
"RespondActivityTaskCompleted"
"fixture/RespondActivityTaskCompleted.yaml"
testDescribeWorkflowExecution :: DescribeWorkflowExecution -> TestTree
testDescribeWorkflowExecution = req
"DescribeWorkflowExecution"
"fixture/DescribeWorkflowExecution.yaml"
testSignalWorkflowExecution :: SignalWorkflowExecution -> TestTree
testSignalWorkflowExecution = req
"SignalWorkflowExecution"
"fixture/SignalWorkflowExecution.yaml"
testCountPendingDecisionTasks :: CountPendingDecisionTasks -> TestTree
testCountPendingDecisionTasks = req
"CountPendingDecisionTasks"
"fixture/CountPendingDecisionTasks.yaml"
testListClosedWorkflowExecutions :: ListClosedWorkflowExecutions -> TestTree
testListClosedWorkflowExecutions = req
"ListClosedWorkflowExecutions"
"fixture/ListClosedWorkflowExecutions.yaml"
testRecordActivityTaskHeartbeat :: RecordActivityTaskHeartbeat -> TestTree
testRecordActivityTaskHeartbeat = req
"RecordActivityTaskHeartbeat"
"fixture/RecordActivityTaskHeartbeat.yaml"
testDescribeDomain :: DescribeDomain -> TestTree
testDescribeDomain = req
"DescribeDomain"
"fixture/DescribeDomain.yaml"
testGetWorkflowExecutionHistory :: GetWorkflowExecutionHistory -> TestTree
testGetWorkflowExecutionHistory = req
"GetWorkflowExecutionHistory"
"fixture/GetWorkflowExecutionHistory.yaml"
testDeprecateDomain :: DeprecateDomain -> TestTree
testDeprecateDomain = req
"DeprecateDomain"
"fixture/DeprecateDomain.yaml"
testTerminateWorkflowExecution :: TerminateWorkflowExecution -> TestTree
testTerminateWorkflowExecution = req
"TerminateWorkflowExecution"
"fixture/TerminateWorkflowExecution.yaml"
testDescribeActivityType :: DescribeActivityType -> TestTree
testDescribeActivityType = req
"DescribeActivityType"
"fixture/DescribeActivityType.yaml"
testDeprecateActivityType :: DeprecateActivityType -> TestTree
testDeprecateActivityType = req
"DeprecateActivityType"
"fixture/DeprecateActivityType.yaml"
testCountClosedWorkflowExecutions :: CountClosedWorkflowExecutions -> TestTree
testCountClosedWorkflowExecutions = req
"CountClosedWorkflowExecutions"
"fixture/CountClosedWorkflowExecutions.yaml"
testRespondActivityTaskCanceled :: RespondActivityTaskCanceled -> TestTree
testRespondActivityTaskCanceled = req
"RespondActivityTaskCanceled"
"fixture/RespondActivityTaskCanceled.yaml"
testStartWorkflowExecution :: StartWorkflowExecution -> TestTree
testStartWorkflowExecution = req
"StartWorkflowExecution"
"fixture/StartWorkflowExecution.yaml"
testPollForDecisionTask :: PollForDecisionTask -> TestTree
testPollForDecisionTask = req
"PollForDecisionTask"
"fixture/PollForDecisionTask.yaml"
testListDomains :: ListDomains -> TestTree
testListDomains = req
"ListDomains"
"fixture/ListDomains.yaml"
-- Responses
testListOpenWorkflowExecutionsResponse :: WorkflowExecutionInfos -> TestTree
testListOpenWorkflowExecutionsResponse = res
"ListOpenWorkflowExecutionsResponse"
"fixture/ListOpenWorkflowExecutionsResponse.proto"
sWF
(Proxy :: Proxy ListOpenWorkflowExecutions)
testRegisterActivityTypeResponse :: RegisterActivityTypeResponse -> TestTree
testRegisterActivityTypeResponse = res
"RegisterActivityTypeResponse"
"fixture/RegisterActivityTypeResponse.proto"
sWF
(Proxy :: Proxy RegisterActivityType)
testListActivityTypesResponse :: ListActivityTypesResponse -> TestTree
testListActivityTypesResponse = res
"ListActivityTypesResponse"
"fixture/ListActivityTypesResponse.proto"
sWF
(Proxy :: Proxy ListActivityTypes)
testCountPendingActivityTasksResponse :: PendingTaskCount -> TestTree
testCountPendingActivityTasksResponse = res
"CountPendingActivityTasksResponse"
"fixture/CountPendingActivityTasksResponse.proto"
sWF
(Proxy :: Proxy CountPendingActivityTasks)
testRegisterWorkflowTypeResponse :: RegisterWorkflowTypeResponse -> TestTree
testRegisterWorkflowTypeResponse = res
"RegisterWorkflowTypeResponse"
"fixture/RegisterWorkflowTypeResponse.proto"
sWF
(Proxy :: Proxy RegisterWorkflowType)
testListWorkflowTypesResponse :: ListWorkflowTypesResponse -> TestTree
testListWorkflowTypesResponse = res
"ListWorkflowTypesResponse"
"fixture/ListWorkflowTypesResponse.proto"
sWF
(Proxy :: Proxy ListWorkflowTypes)
testRespondActivityTaskFailedResponse :: RespondActivityTaskFailedResponse -> TestTree
testRespondActivityTaskFailedResponse = res
"RespondActivityTaskFailedResponse"
"fixture/RespondActivityTaskFailedResponse.proto"
sWF
(Proxy :: Proxy RespondActivityTaskFailed)
testCountOpenWorkflowExecutionsResponse :: WorkflowExecutionCount -> TestTree
testCountOpenWorkflowExecutionsResponse = res
"CountOpenWorkflowExecutionsResponse"
"fixture/CountOpenWorkflowExecutionsResponse.proto"
sWF
(Proxy :: Proxy CountOpenWorkflowExecutions)
testDescribeWorkflowTypeResponse :: DescribeWorkflowTypeResponse -> TestTree
testDescribeWorkflowTypeResponse = res
"DescribeWorkflowTypeResponse"
"fixture/DescribeWorkflowTypeResponse.proto"
sWF
(Proxy :: Proxy DescribeWorkflowType)
testDeprecateWorkflowTypeResponse :: DeprecateWorkflowTypeResponse -> TestTree
testDeprecateWorkflowTypeResponse = res
"DeprecateWorkflowTypeResponse"
"fixture/DeprecateWorkflowTypeResponse.proto"
sWF
(Proxy :: Proxy DeprecateWorkflowType)
testRequestCancelWorkflowExecutionResponse :: RequestCancelWorkflowExecutionResponse -> TestTree
testRequestCancelWorkflowExecutionResponse = res
"RequestCancelWorkflowExecutionResponse"
"fixture/RequestCancelWorkflowExecutionResponse.proto"
sWF
(Proxy :: Proxy RequestCancelWorkflowExecution)
testRegisterDomainResponse :: RegisterDomainResponse -> TestTree
testRegisterDomainResponse = res
"RegisterDomainResponse"
"fixture/RegisterDomainResponse.proto"
sWF
(Proxy :: Proxy RegisterDomain)
testRespondDecisionTaskCompletedResponse :: RespondDecisionTaskCompletedResponse -> TestTree
testRespondDecisionTaskCompletedResponse = res
"RespondDecisionTaskCompletedResponse"
"fixture/RespondDecisionTaskCompletedResponse.proto"
sWF
(Proxy :: Proxy RespondDecisionTaskCompleted)
testPollForActivityTaskResponse :: PollForActivityTaskResponse -> TestTree
testPollForActivityTaskResponse = res
"PollForActivityTaskResponse"
"fixture/PollForActivityTaskResponse.proto"
sWF
(Proxy :: Proxy PollForActivityTask)
testRespondActivityTaskCompletedResponse :: RespondActivityTaskCompletedResponse -> TestTree
testRespondActivityTaskCompletedResponse = res
"RespondActivityTaskCompletedResponse"
"fixture/RespondActivityTaskCompletedResponse.proto"
sWF
(Proxy :: Proxy RespondActivityTaskCompleted)
testDescribeWorkflowExecutionResponse :: DescribeWorkflowExecutionResponse -> TestTree
testDescribeWorkflowExecutionResponse = res
"DescribeWorkflowExecutionResponse"
"fixture/DescribeWorkflowExecutionResponse.proto"
sWF
(Proxy :: Proxy DescribeWorkflowExecution)
testSignalWorkflowExecutionResponse :: SignalWorkflowExecutionResponse -> TestTree
testSignalWorkflowExecutionResponse = res
"SignalWorkflowExecutionResponse"
"fixture/SignalWorkflowExecutionResponse.proto"
sWF
(Proxy :: Proxy SignalWorkflowExecution)
testCountPendingDecisionTasksResponse :: PendingTaskCount -> TestTree
testCountPendingDecisionTasksResponse = res
"CountPendingDecisionTasksResponse"
"fixture/CountPendingDecisionTasksResponse.proto"
sWF
(Proxy :: Proxy CountPendingDecisionTasks)
testListClosedWorkflowExecutionsResponse :: WorkflowExecutionInfos -> TestTree
testListClosedWorkflowExecutionsResponse = res
"ListClosedWorkflowExecutionsResponse"
"fixture/ListClosedWorkflowExecutionsResponse.proto"
sWF
(Proxy :: Proxy ListClosedWorkflowExecutions)
testRecordActivityTaskHeartbeatResponse :: RecordActivityTaskHeartbeatResponse -> TestTree
testRecordActivityTaskHeartbeatResponse = res
"RecordActivityTaskHeartbeatResponse"
"fixture/RecordActivityTaskHeartbeatResponse.proto"
sWF
(Proxy :: Proxy RecordActivityTaskHeartbeat)
testDescribeDomainResponse :: DescribeDomainResponse -> TestTree
testDescribeDomainResponse = res
"DescribeDomainResponse"
"fixture/DescribeDomainResponse.proto"
sWF
(Proxy :: Proxy DescribeDomain)
testGetWorkflowExecutionHistoryResponse :: GetWorkflowExecutionHistoryResponse -> TestTree
testGetWorkflowExecutionHistoryResponse = res
"GetWorkflowExecutionHistoryResponse"
"fixture/GetWorkflowExecutionHistoryResponse.proto"
sWF
(Proxy :: Proxy GetWorkflowExecutionHistory)
testDeprecateDomainResponse :: DeprecateDomainResponse -> TestTree
testDeprecateDomainResponse = res
"DeprecateDomainResponse"
"fixture/DeprecateDomainResponse.proto"
sWF
(Proxy :: Proxy DeprecateDomain)
testTerminateWorkflowExecutionResponse :: TerminateWorkflowExecutionResponse -> TestTree
testTerminateWorkflowExecutionResponse = res
"TerminateWorkflowExecutionResponse"
"fixture/TerminateWorkflowExecutionResponse.proto"
sWF
(Proxy :: Proxy TerminateWorkflowExecution)
testDescribeActivityTypeResponse :: DescribeActivityTypeResponse -> TestTree
testDescribeActivityTypeResponse = res
"DescribeActivityTypeResponse"
"fixture/DescribeActivityTypeResponse.proto"
sWF
(Proxy :: Proxy DescribeActivityType)
testDeprecateActivityTypeResponse :: DeprecateActivityTypeResponse -> TestTree
testDeprecateActivityTypeResponse = res
"DeprecateActivityTypeResponse"
"fixture/DeprecateActivityTypeResponse.proto"
sWF
(Proxy :: Proxy DeprecateActivityType)
testCountClosedWorkflowExecutionsResponse :: WorkflowExecutionCount -> TestTree
testCountClosedWorkflowExecutionsResponse = res
"CountClosedWorkflowExecutionsResponse"
"fixture/CountClosedWorkflowExecutionsResponse.proto"
sWF
(Proxy :: Proxy CountClosedWorkflowExecutions)
testRespondActivityTaskCanceledResponse :: RespondActivityTaskCanceledResponse -> TestTree
testRespondActivityTaskCanceledResponse = res
"RespondActivityTaskCanceledResponse"
"fixture/RespondActivityTaskCanceledResponse.proto"
sWF
(Proxy :: Proxy RespondActivityTaskCanceled)
testStartWorkflowExecutionResponse :: StartWorkflowExecutionResponse -> TestTree
testStartWorkflowExecutionResponse = res
"StartWorkflowExecutionResponse"
"fixture/StartWorkflowExecutionResponse.proto"
sWF
(Proxy :: Proxy StartWorkflowExecution)
testPollForDecisionTaskResponse :: PollForDecisionTaskResponse -> TestTree
testPollForDecisionTaskResponse = res
"PollForDecisionTaskResponse"
"fixture/PollForDecisionTaskResponse.proto"
sWF
(Proxy :: Proxy PollForDecisionTask)
testListDomainsResponse :: ListDomainsResponse -> TestTree
testListDomainsResponse = res
"ListDomainsResponse"
"fixture/ListDomainsResponse.proto"
sWF
(Proxy :: Proxy ListDomains)
| fmapfmapfmap/amazonka | amazonka-swf/test/Test/AWS/Gen/SWF.hs | mpl-2.0 | 20,077 | 0 | 7 | 3,449 | 1,834 | 1,076 | 758 | 319 | 1 |
module B1.Program.Chart.TaskManager
( TaskManager
, newTaskManager
) where
data TaskManager = TaskManager (IORef [IO ()])
newTaskManager :: IO TaskManager
newTaskManager = do
workQueue <- newIORef []
return $ TaskManager workQueue
| madjestic/b1 | src/B1/Program/Chart/ThreadManager.hs | bsd-3-clause | 244 | 0 | 11 | 43 | 74 | 39 | 35 | 8 | 1 |
{-# LANGUAGE FlexibleInstances,FlexibleContexts,MultiWayIf,CPP #-}
module Herbie.MathInfo
where
import Class
import DsBinds
import DsMonad
import ErrUtils
import GhcPlugins hiding (trace)
import Unique
import MkId
import PrelNames
import UniqSupply
import TcRnMonad
import TcSimplify
import Type
import Control.Monad
import Control.Monad.Except
import Control.Monad.Trans
import Data.Char
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Ratio
import Herbie.CoreManip
import Herbie.MathExpr
import Prelude
import Show
-- import Debug.Trace hiding (traceM)
trace a b = b
traceM a = return ()
--------------------------------------------------------------------------------
-- | The fields of this type correspond to the sections of a function type.
--
-- Must satisfy the invariant that every class in "getCxt" has an associated dictionary in "getDicts".
data ParamType = ParamType
{ getQuantifier :: [Var]
, getCxt :: [Type]
, getDicts :: [CoreExpr]
, getParam :: Type
}
-- | This type is a simplified version of the CoreExpr type.
-- It only supports math expressions.
-- We first convert a CoreExpr into a MathInfo,
-- perform all the manipulation on the MathExpr within the MathInfo,
-- then use the information in MathInfo to convert the MathExpr back into a CoreExpr.
data MathInfo = MathInfo
{ getMathExpr :: MathExpr
, getParamType :: ParamType
, getExprs :: [(String,Expr Var)]
-- ^ the fst value is the unique name assigned to non-mathematical expressions
-- the snd value is the expression
}
-- | Pretty print a math expression
pprMathInfo :: MathInfo -> String
pprMathInfo mathInfo = go 1 False $ getMathExpr mathInfo
where
isLitOrLeaf :: MathExpr -> Bool
isLitOrLeaf (ELit _ ) = True
isLitOrLeaf (ELeaf _) = True
isLitOrLeaf _ = False
go :: Int -> Bool -> MathExpr -> String
go i b e = if b && not (isLitOrLeaf e)
then "("++str++")"
else str
where
str = case e of
-- EMonOp "negate" l@(ELit _) -> "-"++go i False l
EMonOp "negate" e1 -> "-"++go i False e1
EMonOp op e1 -> op++" "++go i True e1
EBinOp op e1 e2 -> if op `elem` fancyOps
then op++" "++go i True e1++" "++go i True e2
else go i parens1 e1++" "++op++" "++go i parens2 e2
where
parens1 = case e1 of
-- (EBinOp op' _ _) -> op/=op'
(EMonOp _ _) -> False
_ -> True
parens2 = case e2 of
-- (EBinOp op' _ _) -> op/=op' || not (op `elem` commutativeOpList)
(EMonOp _ _) -> False
_ -> True
ELit l -> if toRational (floor l) == l
then if length (show (floor l :: Integer)) < 10
then show (floor l :: Integer)
else show (fromRational l :: Double)
else show (fromRational l :: Double)
ELeaf l -> case lookup l $ getExprs mathInfo of
Just (Var _) -> pprVariable l mathInfo
Just _ -> pprExpr l mathInfo
-- Just _ -> "???"
EIf cond e1 e2 -> "if "++go i False cond++"\n"
++white++"then "++go (i+1) False e1++"\n"
++white++"else "++go (i+1) False e2
where
white = replicate (4*i) ' '
-- | If there is no ambiguity, the variable is displayed without the unique.
-- Otherwise, it is returned with the unique
pprVariable :: String -> MathInfo -> String
pprVariable var mathInfo = if length (filter (==pprvar) pprvars)
> length (filter (==var) $ map fst $ getExprs mathInfo)
then var
else pprvar
where
pprvar = ppr var
pprvars = map ppr $ map fst $ getExprs mathInfo
ppr = concat . intersperse "_" . init . splitOn "_"
-- | The names of expressions are long and awkward.
-- This gives us a display-friendly version.
pprExpr :: String -> MathInfo -> String
pprExpr var mathInfo = "?"++show index
where
index = case findIndex (==var) notvars of
Just x -> x
notvars
= map fst
$ filter (\(v,e) -> case e of (Var _) -> False; otherwise -> True)
$ getExprs mathInfo
-- | If the given expression is a math expression,
-- returns the type of the variable that the math expression operates on.
varTypeIfValidExpr :: CoreExpr -> Maybe Type
varTypeIfValidExpr e = case e of
-- might be a binary math operation
(App (App (App (App (Var v) (Type t)) _) _) _) -> if var2str v `elem` binOpList
then if isValidType t
then Just t
else Nothing
else Nothing
-- might be a unary math operation
(App (App (App (Var v) (Type t)) _) _) -> if var2str v `elem` monOpList
then if isValidType t
then Just t
else Nothing
else Nothing
-- first function is anything else means that we're not a math expression
_ -> Nothing
where
isValidType :: Type -> Bool
isValidType t = isTyVarTy t || case splitTyConApp_maybe t of
Nothing -> True
Just (tyCon,_) -> tyCon == floatTyCon || tyCon == doubleTyCon
-- | Converts a CoreExpr into a MathInfo
mkMathInfo :: DynFlags -> [Var] -> Type -> Expr Var -> Maybe MathInfo
mkMathInfo dflags dicts bndType e = case varTypeIfValidExpr e of
Nothing -> Nothing
Just t -> if mathExprDepth getMathExpr>1 || lispHasRepeatVars (mathExpr2lisp getMathExpr)
then Just $ MathInfo
getMathExpr
ParamType
{ getQuantifier = quantifier
, getCxt = cxt
, getDicts = map Var dicts
, getParam = t
}
exprs
else Nothing
where
(getMathExpr,exprs) = go e []
-- this should never return Nothing if validExpr is not Nothing
(quantifier,unquantified) = extractQuantifiers bndType
(cxt,uncxt) = extractContext unquantified
-- recursively converts the `Expr Var` into a MathExpr and a dictionary
go :: Expr Var
-> [(String,Expr Var)]
-> (MathExpr
,[(String,Expr Var)]
)
-- we need to special case the $ operator for when MathExpr is run before any rewrite rules
go e@(App (App (App (App (Var v) (Type _)) (Type _)) a1) a2) exprs
= if var2str v == "$"
then go (App a1 a2) exprs
else (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)])
-- polymorphic literals created via fromInteger
go e@(App (App (App (Var v) (Type _)) dict) (Lit l)) exprs
= (ELit $ lit2rational l, exprs)
-- polymorphic literals created via fromRational
go e@(App (App (App (Var v) (Type _)) dict)
(App (App (App (Var _) (Type _)) (Lit l1)) (Lit l2))) exprs
= (ELit $ lit2rational l1 / lit2rational l2, exprs)
-- non-polymorphic literals
go e@(App (Var _) (Lit l)) exprs
= (ELit $ lit2rational l, exprs)
-- binary operators
go e@(App (App (App (App (Var v) (Type _)) dict) a1) a2) exprs
= if var2str v `elem` binOpList
then let (a1',exprs1) = go a1 []
(a2',exprs2) = go a2 []
in ( EBinOp (var2str v) a1' a2'
, exprs++exprs1++exprs2
)
else (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)])
-- unary operators
go e@(App (App (App (Var v) (Type _)) dict) a) exprs
= if var2str v `elem` monOpList
then let (a',exprs') = go a []
in ( EMonOp (var2str v) a'
, exprs++exprs'
)
else (ELeaf $ expr2str dflags e,(expr2str dflags e,e):exprs)
-- everything else
go e exprs = (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)])
-- | Converts a MathInfo back into a CoreExpr
mathInfo2expr :: ModGuts -> MathInfo -> ExceptT ExceptionType CoreM CoreExpr
mathInfo2expr guts herbie = go (getMathExpr herbie)
where
pt = getParamType herbie
-- binary operators
go (EBinOp opstr a1 a2) = do
a1' <- go a1
a2' <- go a2
f <- getDecoratedFunction guts opstr (getParam pt) (getDicts pt)
return $ App (App f a1') a2'
-- unary operators
go (EMonOp opstr a) = do
a' <- go a
f <- getDecoratedFunction guts opstr (getParam pt) (getDicts pt)
castToType
(getDicts pt)
(getParam pt)
$ App f a'
-- if statements
go (EIf cond a1 a2) = do
cond' <- go cond >>= castToType (getDicts pt) boolTy
a1' <- go a1
a2' <- go a2
wildUniq <- getUniqueM
let wildName = mkSystemName wildUniq (mkVarOcc "wild")
wildVar = mkLocalVar VanillaId wildName boolTy vanillaIdInfo
return $ Case
cond'
wildVar
(getParam pt)
[ (DataAlt falseDataCon, [], a2')
, (DataAlt trueDataCon, [], a1')
]
-- leaf is a numeric literal
go (ELit r) = do
fromRationalExpr <- getDecoratedFunction guts "fromRational" (getParam pt) (getDicts pt)
integerTyCon <- lookupTyCon integerTyConName
let integerTy = mkTyConTy integerTyCon
ratioTyCon <- lookupTyCon ratioTyConName
tmpUniq <- getUniqueM
let tmpName = mkSystemName tmpUniq (mkVarOcc "a")
tmpVar = mkTyVar tmpName liftedTypeKind
tmpVarT = mkTyVarTy tmpVar
ratioConTy = mkForAllTy tmpVar $ mkFunTys [tmpVarT,tmpVarT] $ mkAppTy (mkTyConTy ratioTyCon) tmpVarT
ratioConVar = mkGlobalVar VanillaId ratioDataConName ratioConTy vanillaIdInfo
return $ App
fromRationalExpr
(App
(App
(App
(Var ratioConVar )
(Type integerTy)
)
(Lit $ LitInteger (numerator r) integerTy)
)
(Lit $ LitInteger (denominator r) integerTy)
)
-- leaf is any other expression
go (ELeaf str) = do
dflags <- getDynFlags
return $ case lookup str (getExprs herbie) of
Just x -> x
Nothing -> error $ "mathInfo2expr: var " ++ str ++ " not in scope"
++"; in scope vars="++show (nub $ map fst $ getExprs herbie)
| mikeizbicki/HerbiePlugin | src/Herbie/MathInfo.hs | bsd-3-clause | 11,357 | 0 | 21 | 4,332 | 3,018 | 1,557 | 1,461 | 203 | 15 |
module Term.CLS where
-- $Id$
-- untersuche, ob CL(S) rückwärts change-bounded ist
-- falls ja, dann wäre das ein argument für REG-erhaltung
import Term.Type
import Term.Dot
import Term.Match
import Term.Change
import ToDoc
import Data.FiniteMap
import Control.Monad ( when )
type STerm = Term Char
instance ToDoc (Int, Char) where
toDoc (i, c) = text (show i ++ [c])
instance Show (Int, Char) where
show = render . toDoc
build :: [ STerm ] -> STerm
build ( x : xs ) = foldl bin x xs
spine :: STerm -> [ STerm ]
-- invers zu build
spine t = sp t []
where sp t xs = case children t of
[l, r] -> sp l (r : xs)
[] -> t : xs
instance ToDoc STerm where
toDoc t =
let x : xs = spine t
par = if null xs then id else parens
in par $ text [ symbol x ] <+> fsep (map toDoc xs)
instance Show STerm where show = render . toDoc
buildV :: [ VTerm Char ] -> VTerm Char
buildV ( x : xs ) = foldl binV x xs
var :: String -> VTerm Char
var x = Term { symbol = Left x , children = [] }
con :: a -> VTerm a
con x = Term { symbol = Right x , children = [] }
binV :: VTerm Char -> VTerm Char -> VTerm Char
binV l r = Term { symbol = Right '@'
, children = [ l, r ]
}
cls :: TRS Char
cls = [ ( buildV [ con 'S', var "x", var "y", var "z" ]
, buildV [ var "x", var "z" , buildV [ var "y", var "z" ] ]
)
]
clsg :: TRS Char
clsg = do
let sub = listToFM [ ("z", s ) ]
(l,r) <- cls
return (applyV sub l, applyV sub r)
rev :: TRS a -> TRS a
rev trs = do (l,r) <- trs ; return (r,l)
icls, iclsg :: TRS Char
icls = rev cls
iclsg = rev clsg
bin :: STerm -> STerm -> STerm
bin l r = Term { symbol = '@'
, children = [ l, r ]
}
s :: STerm
s = Term { symbol = 'S' , children = [] }
t = build [s,s]
a = build [s,s,s]
stt = build [s, t, t]
om = bin stt stt
sterms :: Int -> [ STerm ]
-- zähle anzahl der S
sterms n | n == 1 = return s
sterms n = do
a <- [ 1 .. n-1 ]
let b = n - a
l <- sterms a
r <- sterms b
return $ bin l r
check trs = mapM_ handle $ do
n <- [1 .. ]
t <- sterms n
s <- successors trs $ young t
let m = maximum $ map (age . symbol) $ subterms s
return ( m, t, s )
handle (m,t,s) =
if m < 3 then putStr (show m)
else do print (m,t,s)
when ( m > 3 ) $ display s
| Erdwolf/autotool-bonn | src/Term/CLS.hs | gpl-2.0 | 2,342 | 8 | 15 | 721 | 1,144 | 598 | 546 | 75 | 2 |
-- ==========================================================--
-- === Raw lexical analysis (tokenisation) of source ===--
-- === Lexer.hs ===--
-- ==========================================================--
module Main where
-- import Char -- 1.3
----------------------------------------------------------
-- Lexemes --
----------------------------------------------------------
type Token = (Int, Int, Lex, String) -- (line, column, lexeme type, value)
data Lex = Lcon -- constructor used as prefix:
-- normal prefix constructor,
-- or bracketed infix constructor
| Lconop -- constructor used as infix:
-- normal prefix constructor in backquotes,
-- or infix constructor (starting with ":")
| Lvar -- variable used as prefix:
-- normal prefix variable,
-- or bracketed infix var (operator)
| Lvarop -- variable used as infix:
-- normal prefix variable in backquotes,
-- or infix variable (operator)
-- | Ltycon -- constructor starting with A-Z
-- subcase of Lcon
-- | Ltyvar -- variable starting with a-z
-- subcase of Lvar
| Lintlit -- integer literal
| Lcharlit -- character literal
| Lstringlit -- string literal
| Llbrace -- {
| Lrbrace -- }
| Lsemi -- ;
| Lequals -- =
| Lbar -- |
| Larrow -- ->
| Llparen -- (
| Lrparen -- )
| Lcomma -- ,
| Llbrack -- [
| Lrbrack -- ]
| Lunder -- _
| Lminus -- -
| Lslash -- \
| Lmodule
| Linfixl
| Linfixr
| Linfix
| Lext
| Ldata
| Lif
| Lthen
| Lelse
| Llet
| Lin
| Lcase
| Lof
| Lwhere
| Leof -- deriving (Eq, Show{-was:Text-})
eqLex :: Lex -> Lex -> Bool
eqLex Lcon Lcon = True
eqLex Lconop Lconop = True
eqLex Lvar Lvar = True
eqLex Lvarop Lvarop = True
eqLex Lintlit Lintlit = True -- integer literal
eqLex Lcharlit Lcharlit = True -- character literal
eqLex Lstringlit Lstringlit = True -- string literal
eqLex Llbrace Llbrace = True -- {
eqLex Lrbrace Lrbrace = True -- }
eqLex Lsemi Lsemi = True -- ;
eqLex Lequals Lequals = True -- =
eqLex Lbar Lbar = True -- |
eqLex Larrow Larrow = True -- ->
eqLex Llparen Llparen = True -- (
eqLex Lrparen Lrparen = True -- )
eqLex Lcomma Lcomma = True -- ,
eqLex Llbrack Llbrack = True -- [
eqLex Lrbrack Lrbrack = True -- ]
eqLex Lunder Lunder = True -- _
eqLex Lminus Lminus = True -- -
eqLex Lslash Lslash = True -- \
eqLex Lmodule Lmodule = True
eqLex Linfixl Linfixl = True
eqLex Linfixr Linfixr = True
eqLex Linfix Linfix = True
eqLex Lext Lext = True
eqLex Ldata Ldata = True
eqLex Lif Lif = True
eqLex Lthen Lthen = True
eqLex Lelse Lelse = True
eqLex Llet Llet = True
eqLex Lin Lin = True
eqLex Lcase Lcase = True
eqLex Lof Lof = True
eqLex Lwhere Lwhere = True
eqLex Leof Leof = True -- deriving (Eq, Show{-was:Text-})
eqLex _ _ = False
{-
Lexing rules:
case (
if next is \, -> Llparen
if next is symbol, take symbols and expect closing ) -> Lvar
if next is :, take tail-ident-chars, expect closing ) -> Lcon
otherwise -> Llparen
case `
if next A-Z, take tail-ident-chars, expect ` -> Lconop
if next a-z, take tail-ident-chars, expect ` -> Lvarop
otherwise -> error
case A-Z
take tail-ident-chars -> Lcon
case a-z
take tail-ident-chars -> Lvar
case 0-9
take 0-9s -> Lintlit
case '
expect a lit-char, then ' -> charlit
case "
expect lit-chars, then " -> stringlit
case {
case - -> run_comment
otherwise -> Llbrace
case } -> Lrbrace
case ) -> Lrparen
case [ -> Llbrack
case ] -> Lrbrack
case ; -> Lsemi
case , -> Lcomma
case _ -> Lunder
case -
case - -> line_comment
case > -> Larrow
otherwise -> Lminus
case # in column 1: this is a preprocessor line
case :!#$%&*+./<=>?@\^|~
take symbols, then case resulting
"=" -> Lequals
"|" -> Lbar
"\" -> Lslash
otherwise
if starts with : -> Lconop
else -> lvarop
-}
-- ==========================================================--
--
leLex :: Int -> Int -> String -> [Token]
leLex l n []
= repeat (99997, 99997, Leof, "")
leLex l n ('(':[])
= [(l, n, Llparen, ")")]
leLex l n ('(':c:cs)
| c `eqChar` ':'
= case leChunk (n+1) leIsTailChar cs of
(restSym, nn, restInput) -> case restInput of
[] -> leFail l nn " ) expected"
(')':as) -> (l, n, Lvar, c:restSym) : leLex l (nn+1) as
(_:_) -> leFail l nn " ) expected"
| c `eqChar` '\\'
= (l, n, Llparen, "(") : leLex l (n+1) (c:cs)
| leIsSymbol c
= case leChunk (n+1) leIsSymbol cs of
(restSym, nn, restInput) -> case restInput of
[] -> leFail l nn " ) expected"
(')':as) -> (l, n, Lvar, c:restSym) : leLex l (nn+1) as
(_:_) -> leFail l nn " ) expected"
| otherwise
= (l, n, Llparen, "(") : leLex l (n+1) (c:cs)
leLex l n ('`':c:cs)
| isAlpha c
= case leChunk (n+1) isAlpha cs of
(restSym, nn, restInput) -> case restInput of
[] -> leFail l nn " ` expected"
('`':as) -> (l, n, if isUpper c then Lconop else Lvarop, c:restSym)
: leLex l (nn+1) as
(_:_) -> leFail l nn " ` expected"
| otherwise
= leFail l n "Bad infix operator"
leLex l n ('"':cs)
= case leTakeLitChars True l (n+1) cs of
(restSym, nn, restInput) -> case restInput of
[] -> leFail l nn " \" expected"
('"':as) -> (l, n, Lstringlit, restSym) : leLex l (nn+1) as
(_:_) -> leFail l nn " \" expected"
leLex l n ('\'':cs)
= case leTakeLitChars False l (n+1) cs of
(restSym, nn, restInput) -> case restInput of
[] -> leFail l nn " ' expected"
('\'':as) -> case restSym of
[_] -> (l, n, Lcharlit, restSym) : leLex l (nn+1) as
_ -> leFail l (n+1) "Bad character literal"
(_:_) -> leFail l nn " ' expected"
leLex l n ('}':cs)
= (l, n, Lrbrace, "}") : leLex l (n+1) cs
leLex l n (')':cs)
= (l, n, Lrparen, ")") : leLex l (n+1) cs
leLex l n ('[':cs)
= (l, n, Llbrack, "[") : leLex l (n+1) cs
leLex l n (']':cs)
= (l, n, Lrbrack, "]") : leLex l (n+1) cs
leLex l n (';':cs)
= (l, n, Lsemi, ";") : leLex l (n+1) cs
leLex l n (',':cs)
= (l, n, Lcomma, ",") : leLex l (n+1) cs
leLex l n ('_':cs)
= (l, n, Lunder, "_") : leLex l (n+1) cs
leLex l n ('{':cs)
= case cs of
[] -> [(l, n, Llbrace, "}")]
('-':cs2) -> leLexRComment l (n+2) cs2
(_:_) -> (l, n, Llbrace, "}") : leLex l (n+1) cs
leLex l n ('-':cs)
= case cs of
[] -> [(l, n, Lminus, "-")]
('-':cs2) -> leLexLComment l (n+2) cs2
('>':cs3) -> (l, n, Larrow, "->") : leLex l (n+2) cs3
('}':cs3) -> leFail l n "Misplaced -}"
(_:_) -> (l, n, Lminus, "-") : leLex l (n+1) cs
leLex l n (' ':cs)
= leLex l (n+1) cs
leLex l n ('\n':cs)
= leLex (l+1) 1 cs
leLex l n ('\t':cs)
= leLex l (n - (n `mod` 8) + 9) cs
leLex l n (c:cs)
= if c `eqChar` '#'
then if n == 1
then
{- This is a CPP line number thingy -}
let lineNoText = takeWhile isDigit (tail cs)
lineNo = leStringToInt lineNoText
nextLine = drop 1 (dropWhile (\x -> not (eqChar '\n' x)) cs)
in
leLex lineNo 1 nextLine
else
{- it's a symbol starting with # -}
case leChunk (n+1) leIsSymbol cs of
(restSym, nn, restText) -> (l, n, Lvarop, c:restSym) :
leLex l nn restText
else
if isAlpha c
then case leChunk (n+1) leIsTailChar cs of
(restSym, nn, restText) -> (l, n, if isUpper c
then Lcon
else Lvar, c:restSym) :
leLex l nn restText
else
if isDigit c
then case leChunk (n+1) isDigit cs of
(restSym, nn, restText) -> (l, n, Lintlit, c:restSym) :
leLex l nn restText
else
if leIsSymbol c
then case leChunk (n+1) leIsSymbol cs of
(restSym, nn, restText) -> (l, n, if c `eqChar` ':'
then Lconop
else Lvarop, c:restSym) :
leLex l nn restText
else
leFail l n ("Illegal character " ++ [c])
-- ==========================================================--
--
leChunk :: Int -> (Char -> Bool) -> String -> (String, Int, String)
leChunk n proper []
= ([], n, [])
leChunk n proper (c:cs)
| proper c
= case leChunk (n+1) proper cs of
(restId, col, restInput) -> (c:restId, col, restInput)
| otherwise
= ([], n, c:cs)
-- ==========================================================--
--
leTakeLitChars :: Bool -> Int -> Int -> String -> (String, Int, String)
leTakeLitChars d l n []
= leFail l n "End of file inside literal"
leTakeLitChars d l n ('\\':'\\':cs)
= case leTakeLitChars d l (n+2) cs of
(rest, col, left) -> ('\\':rest, col, left)
leTakeLitChars d l n ('\\':'n':cs)
= case leTakeLitChars d l (n+2) cs of
(rest, col, left) -> ('\n':rest, col, left)
leTakeLitChars d l n ('\\':'t':cs)
= case leTakeLitChars d l (n+2) cs of
(rest, col, left) -> ('\t':rest, col, left)
leTakeLitChars d l n ('\\':'"':cs)
= case leTakeLitChars d l (n+2) cs of
(rest, col, left) -> ('"':rest, col, left)
leTakeLitChars d l n ('\\':'\'':cs)
= case leTakeLitChars d l (n+2) cs of
(rest, col, left) -> ('\'':rest, col, left)
leTakeLitChars d l n ('"':cs)
| d = ([], n, ('"':cs))
| not d = case leTakeLitChars d l (n+1) cs of
(rest, col, left) -> ('"':rest, col, left)
leTakeLitChars d l n ('\'':cs)
| not d = ([], n, ('\'':cs))
| d = case leTakeLitChars d l (n+1) cs of
(rest, col, left) -> ('\'':rest, col, left)
leTakeLitChars d l n ('\n':cs)
= leFail l n "Literal exceeds line"
leTakeLitChars d l n ('\t':cs)
= leFail l n "Literal contains tab"
leTakeLitChars d l n (c:cs)
= case leTakeLitChars d l (n+1) cs of
(rest, col, left) -> (c:rest, col, left)
-- ==========================================================--
--
leLexLComment :: Int -> Int -> String -> [Token]
leLexLComment l n cs
= leLex (l+1) 1 (drop 1 (dropWhile (\x -> not (eqChar '\n' x)) cs))
-- ==========================================================--
--
leLexRComment :: Int -> Int -> String -> [Token]
leLexRComment l n []
= leFail l n "End of file inside {- ... -} comment"
leLexRComment l n ('-':'}':cs)
= leLex l (n+2) cs
leLexRComment l n ('\n':cs)
= leLexRComment (l+1) 1 cs
leLexRComment l n ('\t':cs)
= leLexRComment l (n - (n `mod` 8) + 9) cs
leLexRComment l n (c:cs)
= leLexRComment l (n+1) cs
-- ==========================================================--
--
leIsSymbol :: Char -> Bool
leIsSymbol c = elemBy eqChar c leSymbols
leSymbols = ":!#$%&*+./<=>?\\@^|~"
-- ==========================================================--
--
leIsTailChar :: Char -> Bool
leIsTailChar c
= isLower c ||
isUpper c ||
isDigit c ||
c `eqChar` '\'' ||
c `eqChar` '_' ||
c `eqChar` '\''
-- ==========================================================--
--
leIsLitChar :: Char -> Bool
leIsLitChar c
= c `neqChar` '\n' &&
c `neqChar` '\t' &&
c `neqChar` '\'' &&
c `neqChar` '"'
neqChar c1 c2 = not (eqChar c1 c2)
-- ==========================================================--
--
leStringToInt :: String -> Int
leStringToInt
= let s2i [] = 0
s2i (d:ds) = (ord d - ord '0') + 10 *s2i ds
in s2i . reverse
-- ==========================================================--
--
leFail l n m
= faiL ("Lexical error, line " ++ showInt l ++ ", col " ++ showInt n ++
":\n " ++ m )
faiL m = error ( "\n\n" ++ m ++ "\n" )
-- ==========================================================--
-- === end Lexer.hs ===--
-- ==========================================================--
-- ==========================================================--
-- === Keyword spotting, and offside rule implementation ===--
-- === Layout.hs ===--
-- ==========================================================--
--module Layout
-- ==========================================================--
--
laKeyword :: Token -> Token
laKeyword (l, n, what, text)
= let
f Lvarop "=" = Lequals
f Lvarop "|" = Lbar
f Lvarop "\\" = Lslash
f Lvar "module" = Lmodule
f Lvar "infix" = Linfix
f Lvar "infixl" = Linfixl
f Lvar "infixr" = Linfixr
f Lvar "ext" = Lext
f Lvar "data" = Ldata
f Lvar "if" = Lif
f Lvar "then" = Lthen
f Lvar "else" = Lelse
f Lvar "let" = Llet
f Lvar "in" = Lin
f Lvar "case" = Lcase
f Lvar "of" = Lof
f Lvar "where" = Lwhere
f item words = item
in
(l, n, f what text, text)
-- ==========================================================--
--
laLayout :: Int -> [Int] -> [Token] -> [Token]
laLayout l s []
= laRbrace (length s - 1) 99999 99999
laLayout l s (t1:[])
= t1 : laRbrace (length s - 1) 99998 99998
laLayout l (s:ss) (t1@(l1, n1, w1, c1) :
t2@(l2, n2, w2, c2) : ts)
| elemBy eqLex w1 [Lof, Llet, Lwhere] && not (w2 `eqLex` Llbrace)
= t1 :
(l1, n1, Llbrace, "{") :
t2 :
laLayout l2 (n2:s:ss) ts
| l1 == l
= t1 :
laLayout l (s:ss) (t2:ts)
| n1 > s
= t1 :
laLayout l1 (s:ss) (t2:ts)
| n1 == s
= (l1, n1, Lsemi, ";") :
t1 :
laLayout l1 (s:ss) (t2:ts)
| n1 < s
= (l1, n1, Lrbrace, "}") :
laLayout l ss (t1:t2:ts)
-- ==========================================================--
--
laRbrace c l n
= take c (repeat (l, n, Lrbrace, "}"))
-- ==========================================================--
--
laMain :: String -> [Token]
laMain
= laLayout 1 [0] . map laKeyword . leLex 1 1
-- ==========================================================--
-- === end Layout.hs ===--
-- ==========================================================--
-- ==========================================================--
-- === Abstract syntax for modules ===--
-- === AbsSyntax.hs ===--
-- ==========================================================--
--module AbsSyntax where
--1.3:data Maybe a = Nothing
-- | Just a
type AList a b = [(a, b)]
type Id = String
data Module
= MkModule Id [TopDecl]
-- deriving (Show{-was:Text-})
data FixityDecl
= MkFixDecl Id (Fixity, Int)
-- deriving (Show{-was:Text-})
data DataDecl
= MkDataDecl Id ([Id], [ConstrAltDecl])
-- deriving (Show{-was:Text-})
data TopDecl
= MkTopF FixityDecl
| MkTopD DataDecl
| MkTopV ValBind
-- deriving (Show{-was:Text-})
data Fixity
= InfixL
| InfixR
| InfixN
-- deriving (Eq,Show{-was:Text-})
eqFixity :: Fixity -> Fixity -> Bool
eqFixity InfixL InfixL = True
eqFixity InfixR InfixR = True
eqFixity InfixN InfixN = True
eqFixity _ _ = False
type ConstrAltDecl
= (Id, [TypeExpr])
data TypeExpr = TypeVar Id
| TypeArr TypeExpr TypeExpr
| TypeCon Id [TypeExpr]
| TypeList TypeExpr
| TypeTuple [TypeExpr]
-- deriving (Show{-was:Text-})
data ValBind
= MkValBind Int Lhs Expr
-- deriving (Show{-was:Text-})
data Lhs
= LhsPat Pat
| LhsVar Id [Pat]
-- deriving (Show{-was:Text-})
data Pat
= PatVar Id
| PatCon Id [Pat]
| PatWild
| PatList [Pat]
| PatTuple [Pat]
-- deriving (Show{-was:Text-})
data Expr
= ExprVar Id
| ExprCon Id
| ExprApp Expr Expr
| ExprLam [Pat] Expr
| ExprCase Expr [ExprCaseAlt]
| ExprLetrec [ValBind] Expr
| ExprWhere Expr [ValBind]
| ExprGuards [(Expr, Expr)]
| ExprLiteral Literal
| ExprList [Expr]
| ExprTuple [Expr]
| ExprIf Expr Expr Expr
| ExprBar
| ExprFail
-- deriving (Show{-was:Text-})
data ExprCaseAlt
= MkExprCaseAlt Pat Expr
-- deriving (Show{-was:Text-})
data Literal
= LiteralInt Int
| LiteralChar Char
| LiteralString String
-- deriving (Show{-was:Text-})
-- ==========================================================--
-- === end AbsSyntax.hs ===--
-- ==========================================================--
-- ==========================================================--
-- === Parser generics ===--
-- === ParserGeneric.hs ===--
-- ==========================================================--
--module ParserGeneric
type PEnv = AList String (Fixity, Int)
data PResult a = POk PEnv [Token] a
| PFail Token
type Parser a = PEnv -> [Token] -> PResult a
type PEntry = (Bool, Expr, Id)
-- ==========================================================--
--
pgItem :: Lex -> Parser String
pgItem x env [] = PFail pgEOF
pgItem x env ((l, n, w, t):toks)
| x `eqLex` w = POk env toks t
| otherwise = PFail (l, n, w, t)
-- ==========================================================--
--
pgAlts :: [Parser a] -> Parser a
pgAlts ps env toks
= let
useAlts [] bestErrTok
= PFail bestErrTok
useAlts (p:ps) bestErrTok
= case p env toks of
PFail someErrTok -> useAlts ps (further someErrTok bestErrTok)
successful_parse -> successful_parse
further x1@(l1, n1, w1, t1) x2@(l2, n2, w2, t2)
= if l2 > l1 then x2
else if l1 > l2 then x1
else if n1 > n2 then x1
else x2
in
useAlts ps (head (toks ++ [pgEOF]))
-- ==========================================================--
--
pgThen2 :: (a -> b -> c) ->
Parser a ->
Parser b ->
Parser c
pgThen2 combine p1 p2 env toks
= case p1 env toks of
{
PFail tok1
-> PFail tok1 ;
POk env1 toks1 item1
-> case p2 env1 toks1 of
{
PFail tok2
-> PFail tok2 ;
POk env2 toks2 item2
-> POk env2 toks2 (combine item1 item2)
}
}
-- ==========================================================--
--
pgThen3 :: (a -> b -> c -> d) ->
Parser a ->
Parser b ->
Parser c ->
Parser d
pgThen3 combine p1 p2 p3 env toks
= case p1 env toks of
{
PFail tok1
-> PFail tok1 ;
POk env1 toks1 item1
-> case p2 env1 toks1 of
{
PFail tok2
-> PFail tok2 ;
POk env2 toks2 item2
-> case p3 env2 toks2 of
{
PFail tok3
-> PFail tok3 ;
POk env3 toks3 item3
-> POk env3 toks3 (combine item1 item2 item3)
}
}
}
-- ==========================================================--
--
pgThen4 :: (a -> b -> c -> d -> e) ->
Parser a ->
Parser b ->
Parser c ->
Parser d ->
Parser e
pgThen4 combine p1 p2 p3 p4 env toks
= case p1 env toks of
{
PFail tok1
-> PFail tok1 ;
POk env1 toks1 item1
-> case p2 env1 toks1 of
{
PFail tok2
-> PFail tok2 ;
POk env2 toks2 item2
-> case p3 env2 toks2 of
{
PFail tok3
-> PFail tok3 ;
POk env3 toks3 item3
-> case p4 env3 toks3 of
{
PFail tok4
-> PFail tok4 ;
POk env4 toks4 item4
-> POk env4 toks4 (combine item1 item2 item3 item4)
}
}
}
}
-- ==========================================================--
--
pgZeroOrMore :: Parser a -> Parser [a]
pgZeroOrMore p env toks
= case p env toks of
{
PFail tok1
-> POk env toks [] ;
POk env1 toks1 item1
-> case pgZeroOrMore p env1 toks1 of
{
PFail tok2
-> POk env1 toks1 [item1] ;
POk env2 toks2 item2_list
-> POk env2 toks2 (item1 : item2_list)
}
}
-- ==========================================================--
--
pgOneOrMore :: Parser a -> Parser [a]
pgOneOrMore p
= pgThen2 (:) p (pgZeroOrMore p)
-- ==========================================================--
--
pgApply :: (a -> b) -> Parser a -> Parser b
pgApply f p env toks
= case p env toks of
{
PFail tok1
-> PFail tok1 ;
POk env1 toks1 item1
-> POk env1 toks1 (f item1)
}
-- ==========================================================--
--
pgTwoOrMoreWithSep :: Parser a -> Parser b -> Parser [a]
pgTwoOrMoreWithSep p psep
= pgThen4
(\i1 s1 i2 rest -> i1:i2:rest)
p
psep
p
(pgZeroOrMore (pgThen2 (\sep x -> x) psep p))
-- ==========================================================--
--
pgOneOrMoreWithSep :: Parser a -> Parser b -> Parser [a]
pgOneOrMoreWithSep p psep
= pgThen2 (:) p (pgZeroOrMore (pgThen2 (\sep x -> x) psep p))
-- ==========================================================--
--
pgZeroOrMoreWithSep :: Parser a -> Parser b -> Parser [a]
pgZeroOrMoreWithSep p psep
= pgAlts
[
pgOneOrMoreWithSep p psep,
pgApply (\x -> x:[]) p,
pgEmpty []
]
-- ==========================================================--
--
pgOptional :: Parser a -> Parser (Maybe a)
pgOptional p env toks
= case p env toks of
{
PFail tok1
-> POk env toks Nothing ;
POk env2 toks2 item2
-> POk env2 toks2 (Just item2)
}
-- ==========================================================--
--
pgGetLineNumber :: Parser a -> Parser (Int, a)
pgGetLineNumber p env toks
= let
lineNo = case (head (toks ++ [pgEOF])) of (l, n, w, t) -> l
in
case p env toks of
{
PFail tok1
-> PFail tok1 ;
POk env2 toks2 item2
-> POk env2 toks2 (lineNo, item2)
}
-- ==========================================================--
--
pgEmpty :: a -> Parser a
pgEmpty item env toks
= POk env toks item
-- ==========================================================--
--
pgEOF :: Token
pgEOF = (88888, 88888, Lvar, "*** Unexpected end of source! ***")
-- ============================================================--
-- === Some kludgey stuff for implementing the offside rule ===--
-- ============================================================--
-- ==========================================================--
--
pgEatEnd :: Parser ()
pgEatEnd env []
= POk env [] ()
pgEatEnd env (tok@(l, n, w, t):toks)
| w `eqLex` Lsemi || w `eqLex` Lrbrace = POk env toks ()
| otherwise = POk env (tok:toks) ()
-- ==========================================================--
--
pgDeclList :: Parser a -> Parser [a]
pgDeclList p
= pgThen3 (\a b c -> b) (pgItem Llbrace)
(pgOneOrMoreWithSep p (pgItem Lsemi))
pgEatEnd
-- ==========================================================--
-- === end ParserGeneric.hs ===--
-- ==========================================================--
-- ==========================================================--
-- === The parser. ===--
-- === Parser.hs ===--
-- ==========================================================--
--module Parser where
{- FIX THESE UP -}
utLookupDef env k def
= head ( [ vv | (kk,vv) <- env, kk `eqString` k] ++ [def] )
panic = error
{- END FIXUPS -}
paLiteral :: Parser Literal
paLiteral
= pgAlts
[
pgApply (LiteralInt . leStringToInt) (pgItem Lintlit),
pgApply (LiteralChar . head) (pgItem Lcharlit),
pgApply LiteralString (pgItem Lstringlit)
]
paExpr
= pgAlts
[
paCaseExpr,
paLetExpr,
paLamExpr,
paIfExpr,
paUnaryMinusExpr,
hsDoExpr []
]
paUnaryMinusExpr
= pgThen2
(\minus (_, aexpr, _) ->
ExprApp (ExprApp (ExprVar "-") (ExprLiteral (LiteralInt 0))) aexpr)
paMinus
paAExpr
paCaseExpr
= pgThen4
(\casee expr off alts -> ExprCase expr alts)
(pgItem Lcase)
paExpr
(pgItem Lof)
(pgDeclList paAlt)
paAlt
= pgAlts
[
pgThen4
(\pat arrow expr wheres
-> MkExprCaseAlt pat (pa_MakeWhereExpr expr wheres))
paPat
(pgItem Larrow)
paExpr
(pgOptional paWhereClause),
pgThen3
(\pat agrdrhss wheres
-> MkExprCaseAlt pat
(pa_MakeWhereExpr (ExprGuards agrdrhss) wheres))
paPat
(pgOneOrMore paGalt)
(pgOptional paWhereClause)
]
paGalt
= pgThen4
(\bar guard arrow expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Larrow)
paExpr
paLamExpr
= pgThen4
(\lam patterns arrow rhs -> ExprLam patterns rhs)
(pgItem Lslash)
(pgZeroOrMore paAPat)
(pgItem Larrow)
paExpr
paLetExpr
= pgThen4
(\lett decls inn rhs -> ExprLetrec decls rhs)
(pgItem Llet)
paValdefs
(pgItem Lin)
paExpr
paValdefs
= pgApply pa_MergeValdefs (pgDeclList paValdef)
pa_MergeValdefs
= id
paLhs
= pgAlts
[
pgThen2 (\v ps -> LhsVar v ps) paVar (pgOneOrMore paPat),
pgApply LhsPat paPat
]
paValdef
= pgAlts
[
pgThen4
(\(line, lhs) eq rhs wheres
-> MkValBind line lhs (pa_MakeWhereExpr rhs wheres))
(pgGetLineNumber paLhs)
(pgItem Lequals)
paExpr
(pgOptional paWhereClause),
pgThen3
(\(line, lhs) grdrhss wheres
-> MkValBind line lhs
(pa_MakeWhereExpr (ExprGuards grdrhss) wheres))
(pgGetLineNumber paLhs)
(pgOneOrMore paGrhs)
(pgOptional paWhereClause)
]
pa_MakeWhereExpr expr Nothing
= expr
pa_MakeWhereExpr expr (Just whereClauses)
= ExprWhere expr whereClauses
paWhereClause
= pgThen2 (\x y -> y) (pgItem Lwhere) paValdefs
paGrhs
= pgThen4
(\bar guard equals expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Lequals)
paExpr
paAPat
= pgAlts
[
pgApply PatVar paVar,
pgApply (\id -> PatCon id []) paCon,
pgApply (const PatWild) (pgItem Lunder),
pgApply PatTuple
(pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrparen)),
pgApply PatList
(pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrbrack)),
pgThen3 (\l p r -> p)
(pgItem Llparen)
paPat
(pgItem Lrparen)
]
paPat
= pgAlts
[
pgThen2 (\c ps -> PatCon c ps)
paCon
(pgOneOrMore paAPat),
pgThen3 (\ap c pa -> PatCon c [ap,pa])
paAPat
paConop
paPat,
paAPat
]
paIfExpr
= pgThen4
(\iff c thenn (t,f) -> ExprIf c t f)
(pgItem Lif)
paExpr
(pgItem Lthen)
(pgThen3
(\t elsee f -> (t,f))
paExpr
(pgItem Lelse)
paExpr
)
paAExpr
= pgApply (\x -> (False, x, []))
(pgAlts
[
pgApply ExprVar paVar,
pgApply ExprCon paCon,
pgApply ExprLiteral paLiteral,
pgApply ExprList paListExpr,
pgApply ExprTuple paTupleExpr,
pgThen3 (\l e r -> e) (pgItem Llparen) paExpr (pgItem Lrparen)
]
)
paListExpr
= pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrbrack)
paTupleExpr
= pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrparen)
paVar = pgItem Lvar
paCon = pgItem Lcon
paVarop = pgItem Lvarop
paConop = pgItem Lconop
paMinus = pgItem Lminus
paOp
= pgAlts [
pgApply (\x -> (True, ExprVar x, x)) paVarop,
pgApply (\x -> (True, ExprCon x, x)) paConop,
pgApply (\x -> (True, ExprVar x, x)) paMinus
]
paDataDecl
= pgThen2
(\dataa useful -> useful)
(pgItem Ldata)
paDataDecl_main
paDataDecl_main
= pgThen4
(\name params eq drhs -> MkDataDecl name (params, drhs))
paCon
(pgZeroOrMore paVar)
(pgItem Lequals)
(pgOneOrMoreWithSep paConstrs (pgItem Lbar))
paConstrs
= pgThen2
(\con texprs -> (con, texprs))
paCon
(pgZeroOrMore paAType)
paType
= pgAlts
[
pgThen3
(\atype arrow typee -> TypeArr atype typee)
paAType
(pgItem Larrow)
paType,
pgThen2
TypeCon
paCon
(pgOneOrMore paAType),
paAType
]
paAType
= pgAlts
[
pgApply TypeVar paVar,
pgApply (\tycon -> TypeCon tycon []) paCon,
pgThen3
(\l t r -> t)
(pgItem Llparen)
paType
(pgItem Lrparen),
pgThen3
(\l t r -> TypeList t)
(pgItem Llbrack)
paType
(pgItem Lrbrack),
pgThen3
(\l t r -> TypeTuple t)
(pgItem Llparen)
(pgTwoOrMoreWithSep paType (pgItem Lcomma))
(pgItem Lrparen)
]
paInfixDecl env toks
= let dump (ExprVar v) = v
dump (ExprCon c) = c
in
pa_UpdateFixityEnv
(pgThen3
(\assoc prio name -> MkFixDecl name (assoc, prio))
paInfixWord
(pgApply leStringToInt (pgItem Lintlit))
(pgApply (\(_, op, _) -> dump op) paOp)
env
toks
)
paInfixWord
= pgAlts
[
pgApply (const InfixL) (pgItem Linfixl),
pgApply (const InfixR) (pgItem Linfixr),
pgApply (const InfixN) (pgItem Linfix)
]
pa_UpdateFixityEnv (PFail tok)
= PFail tok
pa_UpdateFixityEnv (POk env toks (MkFixDecl name assoc_prio))
= let
new_env = (name, assoc_prio) : env
in
POk new_env toks (MkFixDecl name assoc_prio)
paTopDecl
= pgAlts
[
pgApply MkTopF paInfixDecl,
pgApply MkTopD paDataDecl,
pgApply MkTopV paValdef
]
paModule
= pgThen4
(\modyule name wheree topdecls -> MkModule name topdecls)
(pgItem Lmodule)
paCon
(pgItem Lwhere)
(pgDeclList paTopDecl)
parser_test toks
= let parser_to_test
= --paPat
--paExpr
--paValdef
--pgZeroOrMore paInfixDecl
--paDataDecl
--paType
paModule
--pgTwoOrMoreWithSep (pgItem Lsemi) (pgItem Lcomma)
in
parser_to_test hsPrecTable toks
-- ==============================================--
-- === The Operator-Precedence parser (yuck!) ===--
-- ==============================================--
--
-- ==========================================================--
--
hsAExprOrOp
= pgAlts [paAExpr, paOp]
hsDoExpr :: [PEntry] -> Parser Expr
-- [PaEntry] is a stack of operators and atomic expressions
-- hsDoExpr uses a parser (hsAexpOrOp :: Parsr PaEntry) for atomic
-- expressions or operators
hsDoExpr stack env toks =
let
(validIn, restIn, parseIn, err)
= case hsAExprOrOp env toks of
POk env1 toks1 item1
-> (True, toks1, item1, panic "hsDoExpr(1)")
PFail err
-> (False, panic "hsDoExpr(2)", panic "hsDoExpr(3)", err)
(opIn, valueIn, nameIn)
= parseIn
(assocIn, priorIn)
= utLookupDef env nameIn (InfixL, 9)
shift
= hsDoExpr (parseIn:stack) env restIn
in
case stack of
s1:s2:s3:ss
| validIn && opS2 && opIn && priorS2 > priorIn
-> reduce
| validIn && opS2 && opIn && priorS2 == priorIn
-> if assocS2 `eqFixity` InfixL &&
assocIn `eqFixity` InfixL
then reduce
else
if assocS2 `eqFixity` InfixR &&
assocIn `eqFixity` InfixR
then shift
else PFail (head toks) -- Because of ambiguousness
| not validIn && opS2
-> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
(opS3, valueS3, nameS3) = s3
(assocS2, priorS2) = utLookupDef env nameS2 (InfixL, 9)
reduce = hsDoExpr ((False, ExprApp (ExprApp valueS2 valueS3)
valueS1, [])
: ss) env toks
s1:s2:ss
| validIn && (opS1 || opS2) -> shift
| otherwise -> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
reduce = hsDoExpr ((False, ExprApp valueS2 valueS1, []) : ss)
env toks
(s1:[])
| validIn -> shift
| otherwise -> POk env toks valueS1
where
(opS1, valueS1, nameS1) = s1
[]
| validIn -> shift
| otherwise -> PFail err
-- ==========================================================--
-- === end Parser.hs ===--
-- ==========================================================--
hsPrecTable :: PEnv
hsPrecTable = [
("-", (InfixL, 6)),
("+", (InfixL, 6)),
("*", (InfixL, 7)),
("div", (InfixN, 7)),
("mod", (InfixN, 7)),
("<", (InfixN, 4)),
("<=", (InfixN, 4)),
("==", (InfixN, 4)),
("/=", (InfixN, 4)),
(">=", (InfixN, 4)),
(">", (InfixN, 4)),
("C:", (InfixR, 5)),
("++", (InfixR, 5)),
("\\", (InfixN, 5)),
("!!", (InfixL, 9)),
(".", (InfixR, 9)),
("^", (InfixR, 8)),
("elem", (InfixN, 4)),
("notElem", (InfixN, 4)),
("||", (InfixR, 2)),
("&&", (InfixR, 3))]
getAll = do
c <- getChar
if c `eqChar` '#' then -- fake EOF
return [c]
else
do
cs <- getAll
return (c:cs)
main = do
cs <- getAll
let tokens = laMain cs
let parser_res = parser_test tokens
putStr (showx parser_res)
showx (PFail t)
= "\n\nFailed on token: " ++ showToken t ++ "\n\n"
showx (POk env toks result)
= "\n\nSucceeded, with:\n Size env = " ++ showInt (length env) ++
"\n Next token = " ++ showToken (head toks) ++
"\n\n Result = " ++ showModule result ++ "\n\n"
-- ==========================================================--
--
layn :: [[Char]] -> [Char]
layn x = f 1 x
where
f :: Int -> [[Char]] -> [Char]
f n [] = []
f n (a:x) = rjustify 4 (showInt n) ++") "++a++"\n"++f (n+1) x
-- ==========================================================--
--
rjustify :: Int -> [Char] -> [Char]
rjustify n s = spaces (n - length s)++s
where
spaces :: Int -> [Char]
spaces m = copy m ' '
copy :: Int -> a -> [a]
copy n x = take (max 0 n) xs where xs = x:xs
| roberth/uu-helium | test/simple/benchmarks/Main.hs | gpl-3.0 | 39,140 | 0 | 19 | 14,963 | 11,121 | 6,009 | 5,112 | 905 | 26 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Core.Rules.Tests
( tests
) where
--------------------------------------------------------------------------------
import Data.IORef (IORef, newIORef, readIORef,
writeIORef)
import qualified Data.Map as M
import qualified Data.Set as S
import System.FilePath ((</>))
import Test.Framework (Test, testGroup)
import Test.HUnit (Assertion, assert, (@=?))
--------------------------------------------------------------------------------
import Hakyll.Core.Compiler
import Hakyll.Core.File
import Hakyll.Core.Identifier
import Hakyll.Core.Identifier.Pattern
import Hakyll.Core.Routes
import Hakyll.Core.Rules
import Hakyll.Core.Rules.Internal
import Hakyll.Web.Pandoc
import TestSuite.Util
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Hakyll.Core.Rules.Tests" $ fromAssertions "runRules"
[case01]
--------------------------------------------------------------------------------
case01 :: Assertion
case01 = do
ioref <- newIORef False
store <- newTestStore
provider <- newTestProvider store
ruleSet <- runRules (rules01 ioref) provider
let identifiers = S.fromList $ map fst $ rulesCompilers ruleSet
routes = rulesRoutes ruleSet
checkRoute ex i =
runRoutes routes provider i >>= \(r, _) -> Just ex @=? r
-- Test that we have some identifiers and that the routes work out
S.fromList expected @=? identifiers
checkRoute "example.html" "example.md"
checkRoute "example.md" (sv "raw" "example.md")
checkRoute "example.md" (sv "nav" "example.md")
checkRoute "example.mv1" (sv "mv1" "example.md")
checkRoute "example.mv2" (sv "mv2" "example.md")
checkRoute "food/example.md" (sv "metadataMatch" "example.md")
readIORef ioref >>= assert
cleanTestEnv
where
sv g = setVersion (Just g)
expected =
[ "example.md"
, sv "raw" "example.md"
, sv "metadataMatch" "example.md"
, sv "nav" "example.md"
, sv "mv1" "example.md"
, sv "mv2" "example.md"
, "russian.md"
, sv "raw" "russian.md"
, sv "mv1" "russian.md"
, sv "mv2" "russian.md"
]
--------------------------------------------------------------------------------
rules01 :: IORef Bool -> Rules ()
rules01 ioref = do
-- Compile some posts
match "*.md" $ do
route $ setExtension "html"
compile pandocCompiler
-- Yeah. I don't know how else to test this stuff?
preprocess $ writeIORef ioref True
-- Compile them, raw
match "*.md" $ version "raw" $ do
route idRoute
compile getResourceString
version "metadataMatch" $
matchMetadata "*.md" (\md -> M.lookup "subblog" md == Just "food") $ do
route $ customRoute $ \id' -> "food" </> toFilePath id'
compile getResourceString
-- Regression test
version "nav" $ match (fromList ["example.md"]) $ do
route idRoute
compile copyFileCompiler
-- Another edge case: different versions in one match
match "*.md" $ do
version "mv1" $ do
route $ setExtension "mv1"
compile getResourceString
version "mv2" $ do
route $ setExtension "mv2"
compile getResourceString
| Minoru/hakyll | tests/Hakyll/Core/Rules/Tests.hs | bsd-3-clause | 3,836 | 0 | 14 | 1,163 | 780 | 390 | 390 | 76 | 1 |
{-# LANGUAGE TypeInType, ScopedTypeVariables, TypeOperators, GADTs #-}
{-# OPTIONS_GHC -Wno-overlapping-patterns #-} -- don't want erroneous warning in test output
-- if removing this doesn't change output, then
-- remove it!
module T13337 where
import Data.Typeable
import Data.Kind
f :: forall k (a :: k). (Typeable k, Typeable a) => Proxy a -> Proxy Int
f p = case eqT :: Maybe (k :~: Type) of
Nothing -> Proxy
Just Refl -> case eqT :: Maybe (a :~: Int) of
Nothing -> Proxy
Just Refl -> p
| ezyang/ghc | testsuite/tests/typecheck/should_compile/T13337.hs | bsd-3-clause | 602 | 0 | 11 | 196 | 133 | 73 | 60 | -1 | -1 |
{-# LANGUAGE MagicHash, UnboxedTuples #-}
module Main ( main ) where
import GHC.Exts
import GHC.Prim
import GHC.ST
main = putStr
(test_sizeofArray
++ "\n" ++ test_sizeofMutableArray
++ "\n"
)
test_sizeofArray :: String
test_sizeofArray = flip shows "\n" $ runST $ ST $ \ s# -> go 0 [] s#
where
go i@(I# i#) acc s#
| i < 1000 = case newArray# i# 0 s# of
(# s2#, marr# #) -> case unsafeFreezeArray# marr# s2# of
(# s3#, arr# #) -> case sizeofArray# arr# of
j# -> go (i+1) ((I# j#):acc) s3#
| otherwise = (# s#, reverse acc #)
test_sizeofMutableArray :: String
test_sizeofMutableArray = flip shows "\n" $ runST $ ST $ \ s# -> go 0 [] s#
where
go i@(I# i#) acc s#
| i < 1000 = case newArray# i# 0 s# of
(# s2#, marr# #) -> case sizeofMutableArray# marr# of
j# -> go (i+1) ((I# j#):acc) s2#
| otherwise = (# s#, reverse acc #)
| hferreiro/replay | testsuite/tests/codeGen/should_run/cgrun065.hs | bsd-3-clause | 982 | 0 | 21 | 320 | 374 | 190 | 184 | 24 | 1 |
add a b = a + b
| pauldoo/scratch | RealWorldHaskell/ch02/add.hs | isc | 17 | 0 | 5 | 8 | 16 | 7 | 9 | 1 | 1 |
module Parse (parse, parseExpr, lexSynonym) where
import Text.Parsec hiding (parse)
import qualified Text.Parsec as P
import Text.Parsec.String (Parser)
import LambdaWithSynonyms (Expr'(..))
import Data.Functor ((<$>))
import Control.Arrow (left)
import Control.Applicative ((<*))
parse :: String -> Either String Expr'
parse = transformError . P.parse parseAllExpr ""
transformError :: Either ParseError Expr' -> Either String Expr'
transformError = left show
parseAllExpr :: Parser Expr'
parseAllExpr = parseExpr <* eof
parseExpr :: Parser Expr'
parseExpr = (parseLambdaOrName <|> withParens parseExpr) `chainl1` return Ap'
parseLambdaOrName :: Parser Expr'
parseLambdaOrName = parseLambda <|> parseName <|> parseSynonym
parseLambda :: Parser Expr'
parseLambda = do
lexLambda
names <- lexNames
lexDot
expr <- parseExpr
return $ foldr L' expr names
parseName :: Parser Expr'
parseName = V' <$> lexName
parseSynonym :: Parser Expr'
parseSynonym = S' <$> lexSynonym
--lexers
lexLambda = char 'λ' <|> char '\\'
lexDot = char '.'
lexName = oneOf ['a'..'z']
lexNames = many1 lexName
lexSynonym = oneOf $ ['A'..'Z'] ++ ['0'..'9']
--helpers
withParens :: Parser a -> Parser a
withParens = between (char '(') (char ')') | hughfdjackson/abattoir | src/Parse.hs | mit | 1,234 | 0 | 8 | 191 | 405 | 219 | 186 | 36 | 1 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE TupleSections #-}
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Maybe as Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Helpers.Function
import Helpers.Grid (Grid, Point)
import qualified Helpers.Grid as Grid
main :: IO ()
main = do
levels <- Grid.fromDigits <$> getContents
let steps = iterate (step . fst) (levels, 0)
let answer = Maybe.fromJust $ List.findIndex (Grid.all (== 0) . fst) steps
print answer
step :: Grid Int -> (Grid Int, Int)
step startingLevels = step' (succ <$> startingLevels) Set.empty
where
step' :: Grid Int -> Set Point -> (Grid Int, Int)
step' levels flashed =
let updatedFlashed = Grid.pointsWhere (> 9) levels
newFlashed = updatedFlashed Set.\\ flashed
in if Set.size newFlashed == 0
then
let updates = map (,0) (Set.toList flashed)
in (levels Grid.// updates, Set.size flashed)
else
let updates =
Set.toList newFlashed
|> map (Map.fromSet (const 1) . (`Grid.neighboringPointsWithDiagonals` levels))
|> Map.unionsWith (+)
in step' (Grid.updateWith (+) updates levels) updatedFlashed
| SamirTalwar/advent-of-code | 2021/AOC_11_2.hs | mit | 1,308 | 0 | 19 | 355 | 429 | 231 | 198 | 30 | 2 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveGeneric #-}
-- | simple haskell interface for freetype2
--
-- for error codes: https://hackage.haskell.org/package/freetype2-0.1.1/src/include/freetype/fterrdef.h
module Graphics.Font
( module Graphics.Font
, module FontFace
, module FontLibrary
, module Graphics.Font.FontGlyph
) where
import GHC.Generics
import Data.Map.Strict hiding ( map )
import Data.Traversable ( sequenceA )
import Control.Applicative
import Graphics.Font.FontLibrary as FontLibrary ( FontLibrary
, withNewLibrary
, makeLibrary
, freeLibrary )
import Graphics.Font.FontFace as FontFace
import Graphics.Font.FontGlyph
import Graphics.Font.BitmapLoader
import Codec.Picture
pt :: Num a => a -> a
pt = (*) 64
data FontDescriptor = FontDescriptor
{ charSize :: CharSize -- | pt (1/64 pixel)
, deviceRes :: DeviceResolution -- | for dpi calculation
} deriving ( Show, Eq, Ord, Generic )
data Font = Font
{ fontName :: !String
, charMap :: !(Map Char FontGlyph)
, fontDescr :: !FontDescriptor
, fontFace :: !(FontFaceFPtr,FontFace)
, fontLib :: !(FontLibrary)
}
data FontLoadMode =
Gray8
| Monochrome
deriving ( Show, Eq, Ord, Enum, Generic )
loadFont :: FontLibrary -> FilePath -> FontDescriptor -> IO Font
loadFont flib fontfile descr@FontDescriptor{..} = do
(fpt,face) <- newFontFace flib fontfile 0
setFaceCharSize fpt charSize deviceRes
indices <- getAllFaceCharIndices fpt
cMap <- fromList <$> mapM (toGlyph fpt) indices
let fontName = familyName face ++ "-" ++ styleName face
return $ Font fontName cMap descr (fpt,face) flib
where
toGlyph face (gindex, char) = (char,) <$> loadGlyph face gindex [LoadDefault]
loadCharGlyph :: Font -> [LoadMode] -> Char -> IO FontGlyph
loadCharGlyph Font{fontFace} mode c =
getFaceGlyphIndex (fst fontFace) c >>= flip (loadGlyph (fst fontFace)) mode
generateCharImg :: Font -> FontLoadMode -> Char -> IO (Image Pixel8)
generateCharImg font mode char =
case mode of
Gray8 -> load grayLoader [LoadRender]
Monochrome -> load monoLoader [LoadRender, LoadMonochrome]
where
load loader flags = loadFaceCharImage (fst $ fontFace font) char flags loader
generateAllCharImgs :: Font -> FontLoadMode -> IO (Map Char (Image Pixel8))
generateAllCharImgs font mode = sequenceA $ mapWithKey (\c _ -> charImg c) (charMap font) where
charImg = generateCharImg font mode
| MaxDaten/typography-ft2 | Graphics/Font.hs | mit | 2,801 | 0 | 12 | 755 | 720 | 390 | 330 | 68 | 2 |
-- A Gift Well Spent
-- http://www.codewars.com/kata/54554846126a002d5b000854/
module Gift where
buy :: (Num a, Eq a) => a -> [a] -> Maybe (Int, Int)
buy c is = if null cs then Nothing else Just (head cs)
where cs = [(i, j) | i<-[0..length is - 1], j <- drop i [1..length is - 1], is!!i + is!!j == c]
| gafiatulin/codewars | src/7 kyu/Gift.hs | mit | 308 | 0 | 13 | 67 | 157 | 84 | 73 | 4 | 2 |
module Y2017.M07.D26.Exercise where
import Control.Monad.State
import Data.Map (Map)
-- below import available via 1HaskellADay git repository
import Relational.Scheme.Types
{--
Unification and freshness for today.
So, yesterday, we saw how to unify two atoms and how that reduced to lifting
their equivalence into the monadic domain.
Basically: unifying two ground terms is monadic guard.
Fine. But what are the rules for unifying variables to ground terms? What
are the rules for unifying variables to other variables, either of which may
be bound or free?
It turns out there are a lot of rules. And we're not even talking about the
occurs-check, yet.
So, like yesterday, where we broke it down: just unification on ground terms,
let's continue to break down the problem into manageable pieces.
There are many behaviors for unification with logic variables, so let's focus
on one aspect of unification at a time.
But even before that, we have to declare what a logic variable is.
What is a logic variable?
data LogicVariable = LV Sym Status
deriving Eq
The above is saying that a logic variable is named by its symbolic
representation and its status. What is its symbolic representation, and what
are the statii of a logic variable?
Well, digging deeper, a logic variable is not an independent thing, like an
atom, that can exist without some context. No, a logic variable exists in the
(logic) universe in which it subsides.
So, the above declaration is naïve. Really, a logic variable is a mapping from
its symbolic representation to its status.
Let's talk about the states of a logic variable.
A logic variable exists in three states:
free - it has not been bound to any value
bound - it has been bound to a ground term (e.g.: an atomic value)
linked - it has been linked to another logic variable in any state
(of course, if the other logic variable is free, it, too becomes linked to the
unifying logic variable).
So, let's model the statii of a logic variable:
--}
data Status = Free | Linked { forward, back :: [Symbol] } | Bound Atom
deriving (Eq, Show)
-- (please ignore the Linked status for the time being)
-- Okay, we know what an atom is (from the import). What's a symbol?
type Symbol = String
-- So we have the statii of logic variables. Now let's create the logic domain
-- for logic variables
type LogicDomain = Map Symbol Status
-- and there you have it. Everything you need have logic variables.
-- so: fresh.
fresh :: MonadPlus m => Symbol -> StateT LogicDomain m ()
fresh sym = undefined
{--
>>> runStateT (fresh "a") Map.empty
((),fromList [("a",Free)])
... what happens when you declare an already existing variable 'fresh'?
... what should happen?
--}
-- which means everything that you do with logic variables include the domain
-- ... including unification. So, let's get to it.
-- What happens when an atom is unified to a variable?
unifyAtom2LV :: MonadPlus m => Atom -> Symbol -> StateT LogicDomain m ()
unifyAtom2LV val var = undefined
{--
So, what needs to happen is:
If the logic variable is free, it needs to be bound to that value.
If the logic variable is bound to a value, it needs to be equal to that value.
... we won't look at linked logic variables today.
Question: What happens when a variable isn't in the domain? What should happen?
--}
-- What happens when a logic variable is unified to an atom?
unifyLV2Atom :: MonadPlus m => Symbol -> Atom -> StateT LogicDomain m ()
unifyLV2Atom var val = undefined
-- With the above definitions, unify the following:
logicVars :: [Symbol]
logicVars = words "a b c d"
vals :: [Atom]
vals = map read (words "5 #t #s Hi")
{--
>>> vals
[I 5,B True,L #s,S "Hi"]
--}
-- Now, with those unified variables (that is to say: keep the state active),
-- unify a, b, c, d against the below newvals. What are your results?
newvals :: [Atom]
newvals = map read (words "5 True #u hi")
{--
>>> newvals
[I 5,S "True",L #u,S "hi"]
--}
| geophf/1HaskellADay | exercises/HAD/Y2017/M07/D26/Exercise.hs | mit | 3,957 | 0 | 9 | 746 | 280 | 162 | 118 | 20 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.