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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
choose :: Integer -> Integer -> Integer
choose n 0 = 1
choose 0 k = 0
choose n k = choose (n-1) (k-1) * n `div` k
forAllR :: Integer -> [Integer]
forAllR n = map (\r -> choose n r) [1..n]
count p = length . filter p
larger1M = count ((<) 1000000)
main = do
print $ larger1M $ concatMap forAllR [1..100] | ulikoehler/ProjectEuler | Euler53.hs | apache-2.0 | 313 | 0 | 9 | 75 | 173 | 90 | 83 | 10 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QIntValidator.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QIntValidator (
QqIntValidator(..)
,qIntValidator_delete
,qIntValidator_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QIntValidator ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QIntValidator_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QIntValidator_userMethod" qtc_QIntValidator_userMethod :: Ptr (TQIntValidator a) -> CInt -> IO ()
instance QuserMethod (QIntValidatorSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QIntValidator_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QIntValidator ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QIntValidator_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QIntValidator_userMethodVariant" qtc_QIntValidator_userMethodVariant :: Ptr (TQIntValidator a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QIntValidatorSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QIntValidator_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqIntValidator x1 where
qIntValidator :: x1 -> IO (QIntValidator ())
instance QqIntValidator ((QObject t1)) where
qIntValidator (x1)
= withQIntValidatorResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator cobj_x1
foreign import ccall "qtc_QIntValidator" qtc_QIntValidator :: Ptr (TQObject t1) -> IO (Ptr (TQIntValidator ()))
instance QqIntValidator ((Int, Int, QObject t3)) where
qIntValidator (x1, x2, x3)
= withQIntValidatorResult $
withObjectPtr x3 $ \cobj_x3 ->
qtc_QIntValidator1 (toCInt x1) (toCInt x2) cobj_x3
foreign import ccall "qtc_QIntValidator1" qtc_QIntValidator1 :: CInt -> CInt -> Ptr (TQObject t3) -> IO (Ptr (TQIntValidator ()))
instance Qqbottom (QIntValidator a) (()) (IO (Int)) where
qbottom x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_bottom cobj_x0
foreign import ccall "qtc_QIntValidator_bottom" qtc_QIntValidator_bottom :: Ptr (TQIntValidator a) -> IO CInt
instance QqsetBottom (QIntValidator a) ((Int)) where
qsetBottom x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_setBottom cobj_x0 (toCInt x1)
foreign import ccall "qtc_QIntValidator_setBottom" qtc_QIntValidator_setBottom :: Ptr (TQIntValidator a) -> CInt -> IO ()
instance QsetRange (QIntValidator ()) ((Int, Int)) where
setRange x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_setRange_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QIntValidator_setRange_h" qtc_QIntValidator_setRange_h :: Ptr (TQIntValidator a) -> CInt -> CInt -> IO ()
instance QsetRange (QIntValidatorSc a) ((Int, Int)) where
setRange x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_setRange_h cobj_x0 (toCInt x1) (toCInt x2)
instance QqsetTop (QIntValidator a) ((Int)) where
qsetTop x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_setTop cobj_x0 (toCInt x1)
foreign import ccall "qtc_QIntValidator_setTop" qtc_QIntValidator_setTop :: Ptr (TQIntValidator a) -> CInt -> IO ()
instance Qqtop (QIntValidator a) (()) (IO (Int)) where
qtop x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_top cobj_x0
foreign import ccall "qtc_QIntValidator_top" qtc_QIntValidator_top :: Ptr (TQIntValidator a) -> IO CInt
qIntValidator_delete :: QIntValidator a -> IO ()
qIntValidator_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_delete cobj_x0
foreign import ccall "qtc_QIntValidator_delete" qtc_QIntValidator_delete :: Ptr (TQIntValidator a) -> IO ()
qIntValidator_deleteLater :: QIntValidator a -> IO ()
qIntValidator_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_deleteLater cobj_x0
foreign import ccall "qtc_QIntValidator_deleteLater" qtc_QIntValidator_deleteLater :: Ptr (TQIntValidator a) -> IO ()
instance QchildEvent (QIntValidator ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIntValidator_childEvent" qtc_QIntValidator_childEvent :: Ptr (TQIntValidator a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QIntValidatorSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QIntValidator ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QIntValidator_connectNotify" qtc_QIntValidator_connectNotify :: Ptr (TQIntValidator a) -> CWString -> IO ()
instance QconnectNotify (QIntValidatorSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QIntValidator ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIntValidator_customEvent" qtc_QIntValidator_customEvent :: Ptr (TQIntValidator a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QIntValidatorSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QIntValidator ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QIntValidator_disconnectNotify" qtc_QIntValidator_disconnectNotify :: Ptr (TQIntValidator a) -> CWString -> IO ()
instance QdisconnectNotify (QIntValidatorSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QIntValidator ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QIntValidator_event_h" qtc_QIntValidator_event_h :: Ptr (TQIntValidator a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QIntValidatorSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_event_h cobj_x0 cobj_x1
instance QeventFilter (QIntValidator ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QIntValidator_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QIntValidator_eventFilter_h" qtc_QIntValidator_eventFilter_h :: Ptr (TQIntValidator a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QIntValidatorSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QIntValidator_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QIntValidator ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QIntValidator_receivers" qtc_QIntValidator_receivers :: Ptr (TQIntValidator a) -> CWString -> IO CInt
instance Qreceivers (QIntValidatorSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIntValidator_receivers cobj_x0 cstr_x1
instance Qsender (QIntValidator ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_sender cobj_x0
foreign import ccall "qtc_QIntValidator_sender" qtc_QIntValidator_sender :: Ptr (TQIntValidator a) -> IO (Ptr (TQObject ()))
instance Qsender (QIntValidatorSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIntValidator_sender cobj_x0
instance QtimerEvent (QIntValidator ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIntValidator_timerEvent" qtc_QIntValidator_timerEvent :: Ptr (TQIntValidator a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QIntValidatorSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIntValidator_timerEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QIntValidator.hs | bsd-2-clause | 9,885 | 0 | 14 | 1,593 | 3,052 | 1,557 | 1,495 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsEllipseItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsEllipseItem_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 (QGraphicsEllipseItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsEllipseItem_unSetUserMethod" qtc_QGraphicsEllipseItem_unSetUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsEllipseItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setUserMethod" qtc_QGraphicsEllipseItem_setUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setUserMethodVariant" qtc_QGraphicsEllipseItem_setUserMethodVariant :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsEllipseItem_unSetHandler" qtc_QGraphicsEllipseItem_unSetHandler :: Ptr (TQGraphicsEllipseItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsEllipseItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler1" qtc_QGraphicsEllipseItem_setHandler1 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect" qtc_QGraphicsEllipseItem_boundingRect :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsEllipseItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect_qth" qtc_QGraphicsEllipseItem_boundingRect_qth :: Ptr (TQGraphicsEllipseItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler2" qtc_QGraphicsEllipseItem_setHandler2 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsEllipseItem_contains_qth" qtc_QGraphicsEllipseItem_contains_qth :: Ptr (TQGraphicsEllipseItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsEllipseItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsEllipseItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contains" qtc_QGraphicsEllipseItem_contains :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsEllipseItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler3" qtc_QGraphicsEllipseItem_setHandler3 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler4" qtc_QGraphicsEllipseItem_setHandler4 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy" qtc_QGraphicsEllipseItem_isObscuredBy :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem" qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler5" qtc_QGraphicsEllipseItem_setHandler5 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_opaqueArea" qtc_QGraphicsEllipseItem_opaqueArea :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsEllipseItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler6" qtc_QGraphicsEllipseItem_setHandler6 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem6 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((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_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsEllipseItem_paint1" qtc_QGraphicsEllipseItem_paint1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsEllipseItemSc 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_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsEllipseItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_shape" qtc_QGraphicsEllipseItem_shape :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsEllipseItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler7" qtc_QGraphicsEllipseItem_setHandler7 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_type" qtc_QGraphicsEllipseItem_type :: Ptr (TQGraphicsEllipseItem a) -> IO CInt
instance Qqtype_h (QGraphicsEllipseItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler8" qtc_QGraphicsEllipseItem_setHandler8 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8 :: (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_advance" qtc_QGraphicsEllipseItem_advance :: Ptr (TQGraphicsEllipseItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsEllipseItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler9" qtc_QGraphicsEllipseItem_setHandler9 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler10" qtc_QGraphicsEllipseItem_setHandler10 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem" qtc_QGraphicsEllipseItem_collidesWithItem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1" qtc_QGraphicsEllipseItem_collidesWithItem1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler11" qtc_QGraphicsEllipseItem_setHandler11 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler12" qtc_QGraphicsEllipseItem_setHandler12 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath" qtc_QGraphicsEllipseItem_collidesWithPath :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsEllipseItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath1" qtc_QGraphicsEllipseItem_collidesWithPath1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler13" qtc_QGraphicsEllipseItem_setHandler13 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contextMenuEvent" qtc_QGraphicsEllipseItem_contextMenuEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragEnterEvent" qtc_QGraphicsEllipseItem_dragEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragLeaveEvent" qtc_QGraphicsEllipseItem_dragLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragMoveEvent" qtc_QGraphicsEllipseItem_dragMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dropEvent" qtc_QGraphicsEllipseItem_dropEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusInEvent" qtc_QGraphicsEllipseItem_focusInEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusOutEvent" qtc_QGraphicsEllipseItem_focusOutEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverEnterEvent" qtc_QGraphicsEllipseItem_hoverEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverLeaveEvent" qtc_QGraphicsEllipseItem_hoverLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverMoveEvent" qtc_QGraphicsEllipseItem_hoverMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsEllipseItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodEvent" qtc_QGraphicsEllipseItem_inputMethodEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsEllipseItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler14" qtc_QGraphicsEllipseItem_setHandler14 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodQuery" qtc_QGraphicsEllipseItem_inputMethodQuery :: Ptr (TQGraphicsEllipseItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsEllipseItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler15" qtc_QGraphicsEllipseItem_setHandler15 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem15 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_itemChange" qtc_QGraphicsEllipseItem_itemChange :: Ptr (TQGraphicsEllipseItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsEllipseItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyPressEvent" qtc_QGraphicsEllipseItem_keyPressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyReleaseEvent" qtc_QGraphicsEllipseItem_keyReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseDoubleClickEvent" qtc_QGraphicsEllipseItem_mouseDoubleClickEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseMoveEvent" qtc_QGraphicsEllipseItem_mouseMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mousePressEvent" qtc_QGraphicsEllipseItem_mousePressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseReleaseEvent" qtc_QGraphicsEllipseItem_mouseReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler16" qtc_QGraphicsEllipseItem_setHandler16 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEvent" qtc_QGraphicsEllipseItem_sceneEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsEllipseItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler17" qtc_QGraphicsEllipseItem_setHandler17 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem17 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem_setHandler18" qtc_QGraphicsEllipseItem_setHandler18 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem 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_QGraphicsEllipseItem18 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem 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 (QGraphicsEllipseItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter" qtc_QGraphicsEllipseItem_sceneEventFilter :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc 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_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc 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_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_wheelEvent" qtc_QGraphicsEllipseItem_wheelEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QGraphicsEllipseItem_h.hs | bsd-2-clause | 100,155 | 0 | 18 | 20,812 | 30,664 | 14,671 | 15,993 | -1 | -1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QHeaderView.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:18
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QHeaderView (
QqHeaderView(..)
,cascadingSectionResizes
,defaultAlignment
,defaultSectionSize
,headerDataChanged
,hiddenSectionCount
,hideSection
,highlightSections
,Qinitialize(..)
,QinitializeSections(..)
,isClickable
,isSectionHidden
,isSortIndicatorShown
,logicalIndex
,QlogicalIndexAt(..), qlogicalIndexAt
,minimumSectionSize
,moveSection
,QpaintSection(..), QqpaintSection(..)
,resizeSection
,QresizeSections(..)
,sectionPosition
,sectionSize
,QsectionSizeFromContents(..), QqsectionSizeFromContents(..)
,sectionSizeHint
,sectionViewportPosition
,QsectionsAboutToBeRemoved(..)
,sectionsHidden
,QsectionsInserted(..)
,sectionsMoved
,setCascadingSectionResizes
,setClickable
,setDefaultAlignment
,setDefaultSectionSize
,setHighlightSections
,setMinimumSectionSize
,setOffsetToLastSection
,setOffsetToSectionPosition
,setSectionHidden
,setSortIndicatorShown
,setStretchLastSection
,showSection
,sortIndicatorOrder
,sortIndicatorSection
,stretchLastSection
,stretchSectionCount
,swapSections
,QupdateSection(..)
,visualIndex
,visualIndexAt
,qHeaderView_delete
,qHeaderView_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QItemSelectionModel
import Qtc.Enums.Gui.QAbstractItemView
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QHeaderView
import Qtc.Enums.Gui.QAbstractItemDelegate
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QHeaderView ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QHeaderView_userMethod" qtc_QHeaderView_userMethod :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QuserMethod (QHeaderViewSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QHeaderView_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QHeaderView ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QHeaderView_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QHeaderView_userMethodVariant" qtc_QHeaderView_userMethodVariant :: Ptr (TQHeaderView a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QHeaderViewSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QHeaderView_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqHeaderView x1 where
qHeaderView :: x1 -> IO (QHeaderView ())
instance QqHeaderView ((QtOrientation)) where
qHeaderView (x1)
= withQHeaderViewResult $
qtc_QHeaderView (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView" qtc_QHeaderView :: CLong -> IO (Ptr (TQHeaderView ()))
instance QqHeaderView ((QtOrientation, QWidget t2)) where
qHeaderView (x1, x2)
= withQHeaderViewResult $
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView1 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QHeaderView1" qtc_QHeaderView1 :: CLong -> Ptr (TQWidget t2) -> IO (Ptr (TQHeaderView ()))
cascadingSectionResizes :: QHeaderView a -> (()) -> IO (Bool)
cascadingSectionResizes x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_cascadingSectionResizes cobj_x0
foreign import ccall "qtc_QHeaderView_cascadingSectionResizes" qtc_QHeaderView_cascadingSectionResizes :: Ptr (TQHeaderView a) -> IO CBool
instance Qcount (QHeaderView a) (()) where
count x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_count cobj_x0
foreign import ccall "qtc_QHeaderView_count" qtc_QHeaderView_count :: Ptr (TQHeaderView a) -> IO CInt
instance QcurrentChanged (QHeaderView ()) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_currentChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_currentChanged" qtc_QHeaderView_currentChanged :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QcurrentChanged (QHeaderViewSc a) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_currentChanged cobj_x0 cobj_x1 cobj_x2
instance QdataChanged (QHeaderView ()) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_dataChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_dataChanged" qtc_QHeaderView_dataChanged :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QdataChanged (QHeaderViewSc a) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_dataChanged cobj_x0 cobj_x1 cobj_x2
defaultAlignment :: QHeaderView a -> (()) -> IO (Alignment)
defaultAlignment x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_defaultAlignment cobj_x0
foreign import ccall "qtc_QHeaderView_defaultAlignment" qtc_QHeaderView_defaultAlignment :: Ptr (TQHeaderView a) -> IO CLong
defaultSectionSize :: QHeaderView a -> (()) -> IO (Int)
defaultSectionSize x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_defaultSectionSize cobj_x0
foreign import ccall "qtc_QHeaderView_defaultSectionSize" qtc_QHeaderView_defaultSectionSize :: Ptr (TQHeaderView a) -> IO CInt
instance QdoItemsLayout (QHeaderView ()) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doItemsLayout_h cobj_x0
foreign import ccall "qtc_QHeaderView_doItemsLayout_h" qtc_QHeaderView_doItemsLayout_h :: Ptr (TQHeaderView a) -> IO ()
instance QdoItemsLayout (QHeaderViewSc a) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doItemsLayout_h cobj_x0
instance Qevent (QHeaderView ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_event_h" qtc_QHeaderView_event_h :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QHeaderViewSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_event_h cobj_x0 cobj_x1
headerDataChanged :: QHeaderView a -> ((QtOrientation, Int, Int)) -> IO ()
headerDataChanged x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_headerDataChanged cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QHeaderView_headerDataChanged" qtc_QHeaderView_headerDataChanged :: Ptr (TQHeaderView a) -> CLong -> CInt -> CInt -> IO ()
hiddenSectionCount :: QHeaderView a -> (()) -> IO (Int)
hiddenSectionCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_hiddenSectionCount cobj_x0
foreign import ccall "qtc_QHeaderView_hiddenSectionCount" qtc_QHeaderView_hiddenSectionCount :: Ptr (TQHeaderView a) -> IO CInt
hideSection :: QHeaderView a -> ((Int)) -> IO ()
hideSection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_hideSection cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_hideSection" qtc_QHeaderView_hideSection :: Ptr (TQHeaderView a) -> CInt -> IO ()
highlightSections :: QHeaderView a -> (()) -> IO (Bool)
highlightSections x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_highlightSections cobj_x0
foreign import ccall "qtc_QHeaderView_highlightSections" qtc_QHeaderView_highlightSections :: Ptr (TQHeaderView a) -> IO CBool
instance QhorizontalOffset (QHeaderView ()) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalOffset cobj_x0
foreign import ccall "qtc_QHeaderView_horizontalOffset" qtc_QHeaderView_horizontalOffset :: Ptr (TQHeaderView a) -> IO CInt
instance QhorizontalOffset (QHeaderViewSc a) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalOffset cobj_x0
instance QindexAt (QHeaderView ()) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QHeaderView_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QHeaderView_indexAt_qth" qtc_QHeaderView_indexAt_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt (QHeaderViewSc a) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QHeaderView_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt (QHeaderView ()) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_indexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_indexAt" qtc_QHeaderView_indexAt :: Ptr (TQHeaderView a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt (QHeaderViewSc a) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_indexAt cobj_x0 cobj_x1
instance QinitStyleOption (QHeaderView ()) ((QStyleOptionHeader t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_initStyleOption cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_initStyleOption" qtc_QHeaderView_initStyleOption :: Ptr (TQHeaderView a) -> Ptr (TQStyleOptionHeader t1) -> IO ()
instance QinitStyleOption (QHeaderViewSc a) ((QStyleOptionHeader t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_initStyleOption cobj_x0 cobj_x1
class Qinitialize x0 x1 where
initialize :: x0 -> x1 -> IO ()
instance Qinitialize (QHeaderView ()) (()) where
initialize x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initialize cobj_x0
foreign import ccall "qtc_QHeaderView_initialize" qtc_QHeaderView_initialize :: Ptr (TQHeaderView a) -> IO ()
instance Qinitialize (QHeaderViewSc a) (()) where
initialize x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initialize cobj_x0
class QinitializeSections x0 x1 where
initializeSections :: x0 -> x1 -> IO ()
instance QinitializeSections (QHeaderView ()) (()) where
initializeSections x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initializeSections cobj_x0
foreign import ccall "qtc_QHeaderView_initializeSections" qtc_QHeaderView_initializeSections :: Ptr (TQHeaderView a) -> IO ()
instance QinitializeSections (QHeaderViewSc a) (()) where
initializeSections x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initializeSections cobj_x0
instance QinitializeSections (QHeaderView ()) ((Int, Int)) where
initializeSections x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initializeSections1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_initializeSections1" qtc_QHeaderView_initializeSections1 :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance QinitializeSections (QHeaderViewSc a) ((Int, Int)) where
initializeSections x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_initializeSections1 cobj_x0 (toCInt x1) (toCInt x2)
isClickable :: QHeaderView a -> (()) -> IO (Bool)
isClickable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_isClickable cobj_x0
foreign import ccall "qtc_QHeaderView_isClickable" qtc_QHeaderView_isClickable :: Ptr (TQHeaderView a) -> IO CBool
instance QisIndexHidden (QHeaderView ()) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_isIndexHidden cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_isIndexHidden" qtc_QHeaderView_isIndexHidden :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> IO CBool
instance QisIndexHidden (QHeaderViewSc a) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_isIndexHidden cobj_x0 cobj_x1
instance QisMovable (QHeaderView a) (()) where
isMovable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_isMovable cobj_x0
foreign import ccall "qtc_QHeaderView_isMovable" qtc_QHeaderView_isMovable :: Ptr (TQHeaderView a) -> IO CBool
isSectionHidden :: QHeaderView a -> ((Int)) -> IO (Bool)
isSectionHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_isSectionHidden cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_isSectionHidden" qtc_QHeaderView_isSectionHidden :: Ptr (TQHeaderView a) -> CInt -> IO CBool
isSortIndicatorShown :: QHeaderView a -> (()) -> IO (Bool)
isSortIndicatorShown x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_isSortIndicatorShown cobj_x0
foreign import ccall "qtc_QHeaderView_isSortIndicatorShown" qtc_QHeaderView_isSortIndicatorShown :: Ptr (TQHeaderView a) -> IO CBool
instance Qqlength (QHeaderView a) (()) (IO (Int)) where
qlength x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_length cobj_x0
foreign import ccall "qtc_QHeaderView_length" qtc_QHeaderView_length :: Ptr (TQHeaderView a) -> IO CInt
logicalIndex :: QHeaderView a -> ((Int)) -> IO (Int)
logicalIndex x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_logicalIndex cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_logicalIndex" qtc_QHeaderView_logicalIndex :: Ptr (TQHeaderView a) -> CInt -> IO CInt
class QlogicalIndexAt x1 where
logicalIndexAt :: QHeaderView a -> x1 -> IO (Int)
instance QlogicalIndexAt ((Int)) where
logicalIndexAt x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_logicalIndexAt1 cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_logicalIndexAt1" qtc_QHeaderView_logicalIndexAt1 :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QlogicalIndexAt ((Int, Int)) where
logicalIndexAt x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_logicalIndexAt2 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_logicalIndexAt2" qtc_QHeaderView_logicalIndexAt2 :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO CInt
instance QlogicalIndexAt ((Point)) where
logicalIndexAt x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QHeaderView_logicalIndexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QHeaderView_logicalIndexAt_qth" qtc_QHeaderView_logicalIndexAt_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO CInt
qlogicalIndexAt :: QHeaderView a -> ((QPoint t1)) -> IO (Int)
qlogicalIndexAt x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_logicalIndexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_logicalIndexAt" qtc_QHeaderView_logicalIndexAt :: Ptr (TQHeaderView a) -> Ptr (TQPoint t1) -> IO CInt
minimumSectionSize :: QHeaderView a -> (()) -> IO (Int)
minimumSectionSize x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSectionSize cobj_x0
foreign import ccall "qtc_QHeaderView_minimumSectionSize" qtc_QHeaderView_minimumSectionSize :: Ptr (TQHeaderView a) -> IO CInt
instance QmouseDoubleClickEvent (QHeaderView ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseDoubleClickEvent_h" qtc_QHeaderView_mouseDoubleClickEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QHeaderView ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseMoveEvent_h" qtc_QHeaderView_mouseMoveEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QHeaderView ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mousePressEvent_h" qtc_QHeaderView_mousePressEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QHeaderViewSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QHeaderView ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_mouseReleaseEvent_h" qtc_QHeaderView_mouseReleaseEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QHeaderViewSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_mouseReleaseEvent_h cobj_x0 cobj_x1
instance QmoveCursor (QHeaderView ()) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QHeaderView_moveCursor" qtc_QHeaderView_moveCursor :: Ptr (TQHeaderView a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor (QHeaderViewSc a) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
moveSection :: QHeaderView a -> ((Int, Int)) -> IO ()
moveSection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_moveSection cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_moveSection" qtc_QHeaderView_moveSection :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance Qoffset (QHeaderView a) (()) (IO (Int)) where
offset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_offset cobj_x0
foreign import ccall "qtc_QHeaderView_offset" qtc_QHeaderView_offset :: Ptr (TQHeaderView a) -> IO CInt
instance Qorientation (QHeaderView a) (()) (IO (QtOrientation)) where
orientation x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_orientation cobj_x0
foreign import ccall "qtc_QHeaderView_orientation" qtc_QHeaderView_orientation :: Ptr (TQHeaderView a) -> IO CLong
instance QpaintEvent (QHeaderView ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_paintEvent_h" qtc_QHeaderView_paintEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QHeaderViewSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paintEvent_h cobj_x0 cobj_x1
class QpaintSection x0 x1 where
paintSection :: x0 -> x1 -> IO ()
class QqpaintSection x0 x1 where
qpaintSection :: x0 -> x1 -> IO ()
instance QqpaintSection (QHeaderView ()) ((QPainter t1, QRect t2, Int)) where
qpaintSection x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_paintSection cobj_x0 cobj_x1 cobj_x2 (toCInt x3)
foreign import ccall "qtc_QHeaderView_paintSection" qtc_QHeaderView_paintSection :: Ptr (TQHeaderView a) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> CInt -> IO ()
instance QqpaintSection (QHeaderViewSc a) ((QPainter t1, QRect t2, Int)) where
qpaintSection x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_paintSection cobj_x0 cobj_x1 cobj_x2 (toCInt x3)
instance QpaintSection (QHeaderView ()) ((QPainter t1, Rect, Int)) where
paintSection x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
qtc_QHeaderView_paintSection_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h (toCInt x3)
foreign import ccall "qtc_QHeaderView_paintSection_qth" qtc_QHeaderView_paintSection_qth :: Ptr (TQHeaderView a) -> Ptr (TQPainter t1) -> CInt -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QpaintSection (QHeaderViewSc a) ((QPainter t1, Rect, Int)) where
paintSection x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
qtc_QHeaderView_paintSection_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h (toCInt x3)
instance Qreset (QHeaderView ()) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_reset_h cobj_x0
foreign import ccall "qtc_QHeaderView_reset_h" qtc_QHeaderView_reset_h :: Ptr (TQHeaderView a) -> IO ()
instance Qreset (QHeaderViewSc a) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_reset_h cobj_x0
instance QresizeMode (QHeaderView a) ((Int)) (IO (QHeaderViewResizeMode)) where
resizeMode x0 (x1)
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeMode cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_resizeMode" qtc_QHeaderView_resizeMode :: Ptr (TQHeaderView a) -> CInt -> IO CLong
resizeSection :: QHeaderView a -> ((Int, Int)) -> IO ()
resizeSection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeSection cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_resizeSection" qtc_QHeaderView_resizeSection :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
class QresizeSections x0 x1 where
resizeSections :: x0 -> x1 -> IO ()
instance QresizeSections (QHeaderView ()) (()) where
resizeSections x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeSections cobj_x0
foreign import ccall "qtc_QHeaderView_resizeSections" qtc_QHeaderView_resizeSections :: Ptr (TQHeaderView a) -> IO ()
instance QresizeSections (QHeaderViewSc a) (()) where
resizeSections x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeSections cobj_x0
instance QresizeSections (QHeaderView ()) ((QHeaderViewResizeMode)) where
resizeSections x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeSections1 cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_resizeSections1" qtc_QHeaderView_resizeSections1 :: Ptr (TQHeaderView a) -> CLong -> IO ()
instance QresizeSections (QHeaderViewSc a) ((QHeaderViewResizeMode)) where
resizeSections x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resizeSections1 cobj_x0 (toCLong $ qEnum_toInt x1)
instance QrestoreState (QHeaderView a) ((QByteArray ())) where
restoreState x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_restoreState cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_restoreState" qtc_QHeaderView_restoreState :: Ptr (TQHeaderView a) -> Ptr (TQByteArray ()) -> IO CBool
instance QrowsInserted (QHeaderView ()) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QHeaderView_rowsInserted" qtc_QHeaderView_rowsInserted :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsInserted (QHeaderViewSc a) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QsaveState (QHeaderView a) (()) where
saveState x0 ()
= withQByteArrayResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_saveState cobj_x0
foreign import ccall "qtc_QHeaderView_saveState" qtc_QHeaderView_saveState :: Ptr (TQHeaderView a) -> IO (Ptr (TQByteArray ()))
instance QscrollContentsBy (QHeaderView ()) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_scrollContentsBy_h" qtc_QHeaderView_scrollContentsBy_h :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy (QHeaderViewSc a) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
instance QscrollTo (QHeaderView ()) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_scrollTo cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QHeaderView_scrollTo" qtc_QHeaderView_scrollTo :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo (QHeaderViewSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_scrollTo cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
sectionPosition :: QHeaderView a -> ((Int)) -> IO (Int)
sectionPosition x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sectionPosition" qtc_QHeaderView_sectionPosition :: Ptr (TQHeaderView a) -> CInt -> IO CInt
sectionSize :: QHeaderView a -> ((Int)) -> IO (Int)
sectionSize x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSize cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sectionSize" qtc_QHeaderView_sectionSize :: Ptr (TQHeaderView a) -> CInt -> IO CInt
class QsectionSizeFromContents x0 x1 where
sectionSizeFromContents :: x0 -> x1 -> IO (Size)
class QqsectionSizeFromContents x0 x1 where
qsectionSizeFromContents :: x0 -> x1 -> IO (QSize ())
instance QqsectionSizeFromContents (QHeaderView ()) ((Int)) where
qsectionSizeFromContents x0 (x1)
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSizeFromContents cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sectionSizeFromContents" qtc_QHeaderView_sectionSizeFromContents :: Ptr (TQHeaderView a) -> CInt -> IO (Ptr (TQSize ()))
instance QqsectionSizeFromContents (QHeaderViewSc a) ((Int)) where
qsectionSizeFromContents x0 (x1)
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSizeFromContents cobj_x0 (toCInt x1)
instance QsectionSizeFromContents (QHeaderView ()) ((Int)) where
sectionSizeFromContents x0 (x1)
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSizeFromContents_qth cobj_x0 (toCInt x1) csize_ret_w csize_ret_h
foreign import ccall "qtc_QHeaderView_sectionSizeFromContents_qth" qtc_QHeaderView_sectionSizeFromContents_qth :: Ptr (TQHeaderView a) -> CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QsectionSizeFromContents (QHeaderViewSc a) ((Int)) where
sectionSizeFromContents x0 (x1)
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSizeFromContents_qth cobj_x0 (toCInt x1) csize_ret_w csize_ret_h
sectionSizeHint :: QHeaderView a -> ((Int)) -> IO (Int)
sectionSizeHint x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionSizeHint cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sectionSizeHint" qtc_QHeaderView_sectionSizeHint :: Ptr (TQHeaderView a) -> CInt -> IO CInt
sectionViewportPosition :: QHeaderView a -> ((Int)) -> IO (Int)
sectionViewportPosition x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionViewportPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sectionViewportPosition" qtc_QHeaderView_sectionViewportPosition :: Ptr (TQHeaderView a) -> CInt -> IO CInt
class QsectionsAboutToBeRemoved x0 x1 where
sectionsAboutToBeRemoved :: x0 -> x1 -> IO ()
instance QsectionsAboutToBeRemoved (QHeaderView ()) ((QModelIndex t1, Int, Int)) where
sectionsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_sectionsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QHeaderView_sectionsAboutToBeRemoved" qtc_QHeaderView_sectionsAboutToBeRemoved :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QsectionsAboutToBeRemoved (QHeaderViewSc a) ((QModelIndex t1, Int, Int)) where
sectionsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_sectionsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
sectionsHidden :: QHeaderView a -> (()) -> IO (Bool)
sectionsHidden x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionsHidden cobj_x0
foreign import ccall "qtc_QHeaderView_sectionsHidden" qtc_QHeaderView_sectionsHidden :: Ptr (TQHeaderView a) -> IO CBool
class QsectionsInserted x0 x1 where
sectionsInserted :: x0 -> x1 -> IO ()
instance QsectionsInserted (QHeaderView ()) ((QModelIndex t1, Int, Int)) where
sectionsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_sectionsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QHeaderView_sectionsInserted" qtc_QHeaderView_sectionsInserted :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QsectionsInserted (QHeaderViewSc a) ((QModelIndex t1, Int, Int)) where
sectionsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_sectionsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
sectionsMoved :: QHeaderView a -> (()) -> IO (Bool)
sectionsMoved x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sectionsMoved cobj_x0
foreign import ccall "qtc_QHeaderView_sectionsMoved" qtc_QHeaderView_sectionsMoved :: Ptr (TQHeaderView a) -> IO CBool
setCascadingSectionResizes :: QHeaderView a -> ((Bool)) -> IO ()
setCascadingSectionResizes x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setCascadingSectionResizes cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setCascadingSectionResizes" qtc_QHeaderView_setCascadingSectionResizes :: Ptr (TQHeaderView a) -> CBool -> IO ()
setClickable :: QHeaderView a -> ((Bool)) -> IO ()
setClickable x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setClickable cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setClickable" qtc_QHeaderView_setClickable :: Ptr (TQHeaderView a) -> CBool -> IO ()
setDefaultAlignment :: QHeaderView a -> ((Alignment)) -> IO ()
setDefaultAlignment x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setDefaultAlignment cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QHeaderView_setDefaultAlignment" qtc_QHeaderView_setDefaultAlignment :: Ptr (TQHeaderView a) -> CLong -> IO ()
setDefaultSectionSize :: QHeaderView a -> ((Int)) -> IO ()
setDefaultSectionSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setDefaultSectionSize cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setDefaultSectionSize" qtc_QHeaderView_setDefaultSectionSize :: Ptr (TQHeaderView a) -> CInt -> IO ()
setHighlightSections :: QHeaderView a -> ((Bool)) -> IO ()
setHighlightSections x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setHighlightSections cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setHighlightSections" qtc_QHeaderView_setHighlightSections :: Ptr (TQHeaderView a) -> CBool -> IO ()
setMinimumSectionSize :: QHeaderView a -> ((Int)) -> IO ()
setMinimumSectionSize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setMinimumSectionSize cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setMinimumSectionSize" qtc_QHeaderView_setMinimumSectionSize :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QsetModel (QHeaderView ()) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setModel_h" qtc_QHeaderView_setModel_h :: Ptr (TQHeaderView a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel (QHeaderViewSc a) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setModel_h cobj_x0 cobj_x1
instance QsetMovable (QHeaderView a) ((Bool)) where
setMovable x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setMovable cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setMovable" qtc_QHeaderView_setMovable :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QsetOffset (QHeaderView a) ((Int)) where
setOffset x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setOffset cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setOffset" qtc_QHeaderView_setOffset :: Ptr (TQHeaderView a) -> CInt -> IO ()
setOffsetToLastSection :: QHeaderView a -> (()) -> IO ()
setOffsetToLastSection x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setOffsetToLastSection cobj_x0
foreign import ccall "qtc_QHeaderView_setOffsetToLastSection" qtc_QHeaderView_setOffsetToLastSection :: Ptr (TQHeaderView a) -> IO ()
setOffsetToSectionPosition :: QHeaderView a -> ((Int)) -> IO ()
setOffsetToSectionPosition x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setOffsetToSectionPosition cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setOffsetToSectionPosition" qtc_QHeaderView_setOffsetToSectionPosition :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QsetResizeMode (QHeaderView a) ((Int, QHeaderViewResizeMode)) where
setResizeMode x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setResizeMode1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QHeaderView_setResizeMode1" qtc_QHeaderView_setResizeMode1 :: Ptr (TQHeaderView a) -> CInt -> CLong -> IO ()
instance QsetResizeMode (QHeaderView a) ((QHeaderViewResizeMode)) where
setResizeMode x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setResizeMode cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_setResizeMode" qtc_QHeaderView_setResizeMode :: Ptr (TQHeaderView a) -> CLong -> IO ()
setSectionHidden :: QHeaderView a -> ((Int, Bool)) -> IO ()
setSectionHidden x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setSectionHidden cobj_x0 (toCInt x1) (toCBool x2)
foreign import ccall "qtc_QHeaderView_setSectionHidden" qtc_QHeaderView_setSectionHidden :: Ptr (TQHeaderView a) -> CInt -> CBool -> IO ()
instance QqsetSelection (QHeaderView ()) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QHeaderView_setSelection" qtc_QHeaderView_setSelection :: Ptr (TQHeaderView a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection (QHeaderViewSc a) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection (QHeaderView ()) ((Rect, SelectionFlags)) where
setSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QHeaderView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QHeaderView_setSelection_qth" qtc_QHeaderView_setSelection_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection (QHeaderViewSc a) ((Rect, SelectionFlags)) where
setSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QHeaderView_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSortIndicator (QHeaderView a) ((Int, SortOrder)) where
setSortIndicator x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setSortIndicator cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QHeaderView_setSortIndicator" qtc_QHeaderView_setSortIndicator :: Ptr (TQHeaderView a) -> CInt -> CLong -> IO ()
setSortIndicatorShown :: QHeaderView a -> ((Bool)) -> IO ()
setSortIndicatorShown x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setSortIndicatorShown cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setSortIndicatorShown" qtc_QHeaderView_setSortIndicatorShown :: Ptr (TQHeaderView a) -> CBool -> IO ()
setStretchLastSection :: QHeaderView a -> ((Bool)) -> IO ()
setStretchLastSection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setStretchLastSection cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setStretchLastSection" qtc_QHeaderView_setStretchLastSection :: Ptr (TQHeaderView a) -> CBool -> IO ()
showSection :: QHeaderView a -> ((Int)) -> IO ()
showSection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_showSection cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_showSection" qtc_QHeaderView_showSection :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QqsizeHint (QHeaderView ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_h cobj_x0
foreign import ccall "qtc_QHeaderView_sizeHint_h" qtc_QHeaderView_sizeHint_h :: Ptr (TQHeaderView a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QHeaderViewSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_h cobj_x0
instance QsizeHint (QHeaderView ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QHeaderView_sizeHint_qth_h" qtc_QHeaderView_sizeHint_qth_h :: Ptr (TQHeaderView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QHeaderViewSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
sortIndicatorOrder :: QHeaderView a -> (()) -> IO (SortOrder)
sortIndicatorOrder x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sortIndicatorOrder cobj_x0
foreign import ccall "qtc_QHeaderView_sortIndicatorOrder" qtc_QHeaderView_sortIndicatorOrder :: Ptr (TQHeaderView a) -> IO CLong
sortIndicatorSection :: QHeaderView a -> (()) -> IO (Int)
sortIndicatorSection x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sortIndicatorSection cobj_x0
foreign import ccall "qtc_QHeaderView_sortIndicatorSection" qtc_QHeaderView_sortIndicatorSection :: Ptr (TQHeaderView a) -> IO CInt
stretchLastSection :: QHeaderView a -> (()) -> IO (Bool)
stretchLastSection x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_stretchLastSection cobj_x0
foreign import ccall "qtc_QHeaderView_stretchLastSection" qtc_QHeaderView_stretchLastSection :: Ptr (TQHeaderView a) -> IO CBool
stretchSectionCount :: QHeaderView a -> (()) -> IO (Int)
stretchSectionCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_stretchSectionCount cobj_x0
foreign import ccall "qtc_QHeaderView_stretchSectionCount" qtc_QHeaderView_stretchSectionCount :: Ptr (TQHeaderView a) -> IO CInt
swapSections :: QHeaderView a -> ((Int, Int)) -> IO ()
swapSections x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_swapSections cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_swapSections" qtc_QHeaderView_swapSections :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance QupdateGeometries (QHeaderView ()) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateGeometries cobj_x0
foreign import ccall "qtc_QHeaderView_updateGeometries" qtc_QHeaderView_updateGeometries :: Ptr (TQHeaderView a) -> IO ()
instance QupdateGeometries (QHeaderViewSc a) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateGeometries cobj_x0
class QupdateSection x0 x1 where
updateSection :: x0 -> x1 -> IO ()
instance QupdateSection (QHeaderView ()) ((Int)) where
updateSection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateSection cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_updateSection" qtc_QHeaderView_updateSection :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QupdateSection (QHeaderViewSc a) ((Int)) where
updateSection x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateSection cobj_x0 (toCInt x1)
instance QverticalOffset (QHeaderView ()) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalOffset cobj_x0
foreign import ccall "qtc_QHeaderView_verticalOffset" qtc_QHeaderView_verticalOffset :: Ptr (TQHeaderView a) -> IO CInt
instance QverticalOffset (QHeaderViewSc a) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalOffset cobj_x0
instance QviewportEvent (QHeaderView ()) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_viewportEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_viewportEvent_h" qtc_QHeaderView_viewportEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent (QHeaderViewSc a) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_viewportEvent_h cobj_x0 cobj_x1
visualIndex :: QHeaderView a -> ((Int)) -> IO (Int)
visualIndex x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_visualIndex cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_visualIndex" qtc_QHeaderView_visualIndex :: Ptr (TQHeaderView a) -> CInt -> IO CInt
visualIndexAt :: QHeaderView a -> ((Int)) -> IO (Int)
visualIndexAt x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_visualIndexAt cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_visualIndexAt" qtc_QHeaderView_visualIndexAt :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QqvisualRect (QHeaderView ()) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRect cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_visualRect" qtc_QHeaderView_visualRect :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect (QHeaderViewSc a) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRect cobj_x0 cobj_x1
instance QvisualRect (QHeaderView ()) ((QModelIndex t1)) where
visualRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QHeaderView_visualRect_qth" qtc_QHeaderView_visualRect_qth :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect (QHeaderViewSc a) ((QModelIndex t1)) where
visualRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QvisualRegionForSelection (QHeaderView ()) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRegionForSelection cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_visualRegionForSelection" qtc_QHeaderView_visualRegionForSelection :: Ptr (TQHeaderView a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection (QHeaderViewSc a) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_visualRegionForSelection cobj_x0 cobj_x1
qHeaderView_delete :: QHeaderView a -> IO ()
qHeaderView_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_delete cobj_x0
foreign import ccall "qtc_QHeaderView_delete" qtc_QHeaderView_delete :: Ptr (TQHeaderView a) -> IO ()
qHeaderView_deleteLater :: QHeaderView a -> IO ()
qHeaderView_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_deleteLater cobj_x0
foreign import ccall "qtc_QHeaderView_deleteLater" qtc_QHeaderView_deleteLater :: Ptr (TQHeaderView a) -> IO ()
instance QcloseEditor (QHeaderView ()) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QHeaderView_closeEditor" qtc_QHeaderView_closeEditor :: Ptr (TQHeaderView a) -> Ptr (TQWidget t1) -> CLong -> IO ()
instance QcloseEditor (QHeaderViewSc a) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcommitData (QHeaderView ()) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_commitData cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_commitData" qtc_QHeaderView_commitData :: Ptr (TQHeaderView a) -> Ptr (TQWidget t1) -> IO ()
instance QcommitData (QHeaderViewSc a) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_commitData cobj_x0 cobj_x1
instance QdirtyRegionOffset (QHeaderView ()) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QHeaderView_dirtyRegionOffset_qth" qtc_QHeaderView_dirtyRegionOffset_qth :: Ptr (TQHeaderView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QdirtyRegionOffset (QHeaderViewSc a) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
instance QqdirtyRegionOffset (QHeaderView ()) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dirtyRegionOffset cobj_x0
foreign import ccall "qtc_QHeaderView_dirtyRegionOffset" qtc_QHeaderView_dirtyRegionOffset :: Ptr (TQHeaderView a) -> IO (Ptr (TQPoint ()))
instance QqdirtyRegionOffset (QHeaderViewSc a) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dirtyRegionOffset cobj_x0
instance QdoAutoScroll (QHeaderView ()) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doAutoScroll cobj_x0
foreign import ccall "qtc_QHeaderView_doAutoScroll" qtc_QHeaderView_doAutoScroll :: Ptr (TQHeaderView a) -> IO ()
instance QdoAutoScroll (QHeaderViewSc a) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_doAutoScroll cobj_x0
instance QdragEnterEvent (QHeaderView ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragEnterEvent_h" qtc_QHeaderView_dragEnterEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QHeaderViewSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QHeaderView ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragLeaveEvent_h" qtc_QHeaderView_dragLeaveEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QHeaderViewSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QHeaderView ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dragMoveEvent_h" qtc_QHeaderView_dragMoveEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QHeaderViewSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QHeaderView ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_dropEvent_h" qtc_QHeaderView_dropEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QHeaderViewSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_dropEvent_h cobj_x0 cobj_x1
instance QdropIndicatorPosition (QHeaderView ()) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dropIndicatorPosition cobj_x0
foreign import ccall "qtc_QHeaderView_dropIndicatorPosition" qtc_QHeaderView_dropIndicatorPosition :: Ptr (TQHeaderView a) -> IO CLong
instance QdropIndicatorPosition (QHeaderViewSc a) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_dropIndicatorPosition cobj_x0
instance Qedit (QHeaderView ()) ((QModelIndex t1, EditTrigger, QEvent t3)) (IO (Bool)) where
edit x0 (x1, x2, x3)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QHeaderView_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
foreign import ccall "qtc_QHeaderView_edit" qtc_QHeaderView_edit :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CLong -> Ptr (TQEvent t3) -> IO CBool
instance Qedit (QHeaderViewSc a) ((QModelIndex t1, EditTrigger, QEvent t3)) (IO (Bool)) where
edit x0 (x1, x2, x3)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QHeaderView_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
instance QeditorDestroyed (QHeaderView ()) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_editorDestroyed cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_editorDestroyed" qtc_QHeaderView_editorDestroyed :: Ptr (TQHeaderView a) -> Ptr (TQObject t1) -> IO ()
instance QeditorDestroyed (QHeaderViewSc a) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_editorDestroyed cobj_x0 cobj_x1
instance QexecuteDelayedItemsLayout (QHeaderView ()) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_executeDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QHeaderView_executeDelayedItemsLayout" qtc_QHeaderView_executeDelayedItemsLayout :: Ptr (TQHeaderView a) -> IO ()
instance QexecuteDelayedItemsLayout (QHeaderViewSc a) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_executeDelayedItemsLayout cobj_x0
instance QfocusInEvent (QHeaderView ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_focusInEvent_h" qtc_QHeaderView_focusInEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QHeaderViewSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextPrevChild (QHeaderView ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_focusNextPrevChild" qtc_QHeaderView_focusNextPrevChild :: Ptr (TQHeaderView a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QHeaderViewSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QHeaderView ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_focusOutEvent_h" qtc_QHeaderView_focusOutEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QHeaderViewSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_focusOutEvent_h cobj_x0 cobj_x1
instance QhorizontalScrollbarAction (QHeaderView ()) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_horizontalScrollbarAction" qtc_QHeaderView_horizontalScrollbarAction :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QhorizontalScrollbarAction (QHeaderViewSc a) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalScrollbarAction cobj_x0 (toCInt x1)
instance QhorizontalScrollbarValueChanged (QHeaderView ()) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_horizontalScrollbarValueChanged" qtc_QHeaderView_horizontalScrollbarValueChanged :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QhorizontalScrollbarValueChanged (QHeaderViewSc a) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QhorizontalStepsPerItem (QHeaderView ()) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalStepsPerItem cobj_x0
foreign import ccall "qtc_QHeaderView_horizontalStepsPerItem" qtc_QHeaderView_horizontalStepsPerItem :: Ptr (TQHeaderView a) -> IO CInt
instance QhorizontalStepsPerItem (QHeaderViewSc a) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_horizontalStepsPerItem cobj_x0
instance QinputMethodEvent (QHeaderView ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_inputMethodEvent" qtc_QHeaderView_inputMethodEvent :: Ptr (TQHeaderView a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QHeaderViewSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QHeaderView ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_inputMethodQuery_h" qtc_QHeaderView_inputMethodQuery_h :: Ptr (TQHeaderView a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QHeaderViewSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent (QHeaderView ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_keyPressEvent_h" qtc_QHeaderView_keyPressEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QHeaderViewSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyboardSearch (QHeaderView ()) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_keyboardSearch_h cobj_x0 cstr_x1
foreign import ccall "qtc_QHeaderView_keyboardSearch_h" qtc_QHeaderView_keyboardSearch_h :: Ptr (TQHeaderView a) -> CWString -> IO ()
instance QkeyboardSearch (QHeaderViewSc a) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_keyboardSearch_h cobj_x0 cstr_x1
instance QresizeEvent (QHeaderView ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_resizeEvent_h" qtc_QHeaderView_resizeEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QHeaderViewSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resizeEvent_h cobj_x0 cobj_x1
instance QrowsAboutToBeRemoved (QHeaderView ()) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QHeaderView_rowsAboutToBeRemoved" qtc_QHeaderView_rowsAboutToBeRemoved :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsAboutToBeRemoved (QHeaderViewSc a) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QscheduleDelayedItemsLayout (QHeaderView ()) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scheduleDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QHeaderView_scheduleDelayedItemsLayout" qtc_QHeaderView_scheduleDelayedItemsLayout :: Ptr (TQHeaderView a) -> IO ()
instance QscheduleDelayedItemsLayout (QHeaderViewSc a) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scheduleDelayedItemsLayout cobj_x0
instance QscrollDirtyRegion (QHeaderView ()) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_scrollDirtyRegion" qtc_QHeaderView_scrollDirtyRegion :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance QscrollDirtyRegion (QHeaderViewSc a) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
instance QselectAll (QHeaderView ()) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_selectAll_h cobj_x0
foreign import ccall "qtc_QHeaderView_selectAll_h" qtc_QHeaderView_selectAll_h :: Ptr (TQHeaderView a) -> IO ()
instance QselectAll (QHeaderViewSc a) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_selectAll_h cobj_x0
instance QselectionChanged (QHeaderView ()) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_selectionChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_selectionChanged" qtc_QHeaderView_selectionChanged :: Ptr (TQHeaderView a) -> Ptr (TQItemSelection t1) -> Ptr (TQItemSelection t2) -> IO ()
instance QselectionChanged (QHeaderViewSc a) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_selectionChanged cobj_x0 cobj_x1 cobj_x2
instance QselectionCommand (QHeaderView ()) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_selectionCommand cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_selectionCommand" qtc_QHeaderView_selectionCommand :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> IO CLong
instance QselectionCommand (QHeaderViewSc a) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_selectionCommand cobj_x0 cobj_x1
instance QselectionCommand (QHeaderView ()) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_selectionCommand1" qtc_QHeaderView_selectionCommand1 :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> Ptr (TQEvent t2) -> IO CLong
instance QselectionCommand (QHeaderViewSc a) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
instance QsetDirtyRegion (QHeaderView ()) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setDirtyRegion cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setDirtyRegion" qtc_QHeaderView_setDirtyRegion :: Ptr (TQHeaderView a) -> Ptr (TQRegion t1) -> IO ()
instance QsetDirtyRegion (QHeaderViewSc a) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setDirtyRegion cobj_x0 cobj_x1
instance QsetHorizontalStepsPerItem (QHeaderView ()) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setHorizontalStepsPerItem" qtc_QHeaderView_setHorizontalStepsPerItem :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QsetHorizontalStepsPerItem (QHeaderViewSc a) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
instance QsetRootIndex (QHeaderView ()) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setRootIndex_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setRootIndex_h" qtc_QHeaderView_setRootIndex_h :: Ptr (TQHeaderView a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex (QHeaderViewSc a) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setRootIndex_h cobj_x0 cobj_x1
instance QsetSelectionModel (QHeaderView ()) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelectionModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setSelectionModel_h" qtc_QHeaderView_setSelectionModel_h :: Ptr (TQHeaderView a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel (QHeaderViewSc a) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setSelectionModel_h cobj_x0 cobj_x1
instance QsetState (QHeaderView ()) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setState cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_setState" qtc_QHeaderView_setState :: Ptr (TQHeaderView a) -> CLong -> IO ()
instance QsetState (QHeaderViewSc a) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setState cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetVerticalStepsPerItem (QHeaderView ()) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVerticalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_setVerticalStepsPerItem" qtc_QHeaderView_setVerticalStepsPerItem :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QsetVerticalStepsPerItem (QHeaderViewSc a) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVerticalStepsPerItem cobj_x0 (toCInt x1)
instance QsizeHintForColumn (QHeaderView ()) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForColumn_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sizeHintForColumn_h" qtc_QHeaderView_sizeHintForColumn_h :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QsizeHintForColumn (QHeaderViewSc a) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForColumn_h cobj_x0 (toCInt x1)
instance QsizeHintForRow (QHeaderView ()) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForRow_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_sizeHintForRow_h" qtc_QHeaderView_sizeHintForRow_h :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QsizeHintForRow (QHeaderViewSc a) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sizeHintForRow_h cobj_x0 (toCInt x1)
instance QstartAutoScroll (QHeaderView ()) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_startAutoScroll cobj_x0
foreign import ccall "qtc_QHeaderView_startAutoScroll" qtc_QHeaderView_startAutoScroll :: Ptr (TQHeaderView a) -> IO ()
instance QstartAutoScroll (QHeaderViewSc a) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_startAutoScroll cobj_x0
instance QstartDrag (QHeaderView ()) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QHeaderView_startDrag" qtc_QHeaderView_startDrag :: Ptr (TQHeaderView a) -> CLong -> IO ()
instance QstartDrag (QHeaderViewSc a) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
instance Qstate (QHeaderView ()) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_state cobj_x0
foreign import ccall "qtc_QHeaderView_state" qtc_QHeaderView_state :: Ptr (TQHeaderView a) -> IO CLong
instance Qstate (QHeaderViewSc a) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_state cobj_x0
instance QstopAutoScroll (QHeaderView ()) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_stopAutoScroll cobj_x0
foreign import ccall "qtc_QHeaderView_stopAutoScroll" qtc_QHeaderView_stopAutoScroll :: Ptr (TQHeaderView a) -> IO ()
instance QstopAutoScroll (QHeaderViewSc a) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_stopAutoScroll cobj_x0
instance QtimerEvent (QHeaderView ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_timerEvent" qtc_QHeaderView_timerEvent :: Ptr (TQHeaderView a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QHeaderViewSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_timerEvent cobj_x0 cobj_x1
instance QupdateEditorData (QHeaderView ()) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateEditorData cobj_x0
foreign import ccall "qtc_QHeaderView_updateEditorData" qtc_QHeaderView_updateEditorData :: Ptr (TQHeaderView a) -> IO ()
instance QupdateEditorData (QHeaderViewSc a) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateEditorData cobj_x0
instance QupdateEditorGeometries (QHeaderView ()) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateEditorGeometries cobj_x0
foreign import ccall "qtc_QHeaderView_updateEditorGeometries" qtc_QHeaderView_updateEditorGeometries :: Ptr (TQHeaderView a) -> IO ()
instance QupdateEditorGeometries (QHeaderViewSc a) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateEditorGeometries cobj_x0
instance QverticalScrollbarAction (QHeaderView ()) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_verticalScrollbarAction" qtc_QHeaderView_verticalScrollbarAction :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QverticalScrollbarAction (QHeaderViewSc a) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalScrollbarAction cobj_x0 (toCInt x1)
instance QverticalScrollbarValueChanged (QHeaderView ()) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_verticalScrollbarValueChanged" qtc_QHeaderView_verticalScrollbarValueChanged :: Ptr (TQHeaderView a) -> CInt -> IO ()
instance QverticalScrollbarValueChanged (QHeaderViewSc a) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QverticalStepsPerItem (QHeaderView ()) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalStepsPerItem cobj_x0
foreign import ccall "qtc_QHeaderView_verticalStepsPerItem" qtc_QHeaderView_verticalStepsPerItem :: Ptr (TQHeaderView a) -> IO CInt
instance QverticalStepsPerItem (QHeaderViewSc a) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_verticalStepsPerItem cobj_x0
instance QviewOptions (QHeaderView ()) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_viewOptions cobj_x0
foreign import ccall "qtc_QHeaderView_viewOptions" qtc_QHeaderView_viewOptions :: Ptr (TQHeaderView a) -> IO (Ptr (TQStyleOptionViewItem ()))
instance QviewOptions (QHeaderViewSc a) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_viewOptions cobj_x0
instance QcontextMenuEvent (QHeaderView ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_contextMenuEvent_h" qtc_QHeaderView_contextMenuEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QHeaderViewSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_contextMenuEvent_h cobj_x0 cobj_x1
instance QqminimumSizeHint (QHeaderView ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QHeaderView_minimumSizeHint_h" qtc_QHeaderView_minimumSizeHint_h :: Ptr (TQHeaderView a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QHeaderViewSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QHeaderView ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QHeaderView_minimumSizeHint_qth_h" qtc_QHeaderView_minimumSizeHint_qth_h :: Ptr (TQHeaderView a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QHeaderViewSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetViewportMargins (QHeaderView ()) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QHeaderView_setViewportMargins" qtc_QHeaderView_setViewportMargins :: Ptr (TQHeaderView a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetViewportMargins (QHeaderViewSc a) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QsetupViewport (QHeaderView ()) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setupViewport cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setupViewport" qtc_QHeaderView_setupViewport :: Ptr (TQHeaderView a) -> Ptr (TQWidget t1) -> IO ()
instance QsetupViewport (QHeaderViewSc a) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setupViewport cobj_x0 cobj_x1
instance QwheelEvent (QHeaderView ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_wheelEvent_h" qtc_QHeaderView_wheelEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QHeaderViewSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_wheelEvent_h cobj_x0 cobj_x1
instance QchangeEvent (QHeaderView ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_changeEvent_h" qtc_QHeaderView_changeEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QHeaderViewSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_changeEvent_h cobj_x0 cobj_x1
instance QdrawFrame (QHeaderView ()) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_drawFrame cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_drawFrame" qtc_QHeaderView_drawFrame :: Ptr (TQHeaderView a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawFrame (QHeaderViewSc a) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_drawFrame cobj_x0 cobj_x1
instance QactionEvent (QHeaderView ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_actionEvent_h" qtc_QHeaderView_actionEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QHeaderViewSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QHeaderView ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_addAction" qtc_QHeaderView_addAction :: Ptr (TQHeaderView a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QHeaderViewSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_addAction cobj_x0 cobj_x1
instance QcloseEvent (QHeaderView ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_closeEvent_h" qtc_QHeaderView_closeEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QHeaderViewSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_closeEvent_h cobj_x0 cobj_x1
instance Qcreate (QHeaderView ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_create cobj_x0
foreign import ccall "qtc_QHeaderView_create" qtc_QHeaderView_create :: Ptr (TQHeaderView a) -> IO ()
instance Qcreate (QHeaderViewSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_create cobj_x0
instance Qcreate (QHeaderView ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_create1" qtc_QHeaderView_create1 :: Ptr (TQHeaderView a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QHeaderViewSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create1 cobj_x0 cobj_x1
instance Qcreate (QHeaderView ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QHeaderView_create2" qtc_QHeaderView_create2 :: Ptr (TQHeaderView a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QHeaderViewSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QHeaderView ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QHeaderView_create3" qtc_QHeaderView_create3 :: Ptr (TQHeaderView a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QHeaderViewSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QHeaderView ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy cobj_x0
foreign import ccall "qtc_QHeaderView_destroy" qtc_QHeaderView_destroy :: Ptr (TQHeaderView a) -> IO ()
instance Qdestroy (QHeaderViewSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy cobj_x0
instance Qdestroy (QHeaderView ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_destroy1" qtc_QHeaderView_destroy1 :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance Qdestroy (QHeaderViewSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QHeaderView ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QHeaderView_destroy2" qtc_QHeaderView_destroy2 :: Ptr (TQHeaderView a) -> CBool -> CBool -> IO ()
instance Qdestroy (QHeaderViewSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QHeaderView ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_devType_h cobj_x0
foreign import ccall "qtc_QHeaderView_devType_h" qtc_QHeaderView_devType_h :: Ptr (TQHeaderView a) -> IO CInt
instance QdevType (QHeaderViewSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_devType_h cobj_x0
instance QenabledChange (QHeaderView ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_enabledChange" qtc_QHeaderView_enabledChange :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QenabledChange (QHeaderViewSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QHeaderView ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_enterEvent_h" qtc_QHeaderView_enterEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QHeaderViewSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_enterEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QHeaderView ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusNextChild cobj_x0
foreign import ccall "qtc_QHeaderView_focusNextChild" qtc_QHeaderView_focusNextChild :: Ptr (TQHeaderView a) -> IO CBool
instance QfocusNextChild (QHeaderViewSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusNextChild cobj_x0
instance QfocusPreviousChild (QHeaderView ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusPreviousChild cobj_x0
foreign import ccall "qtc_QHeaderView_focusPreviousChild" qtc_QHeaderView_focusPreviousChild :: Ptr (TQHeaderView a) -> IO CBool
instance QfocusPreviousChild (QHeaderViewSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_focusPreviousChild cobj_x0
instance QfontChange (QHeaderView ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_fontChange" qtc_QHeaderView_fontChange :: Ptr (TQHeaderView a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QHeaderViewSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QHeaderView ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QHeaderView_heightForWidth_h" qtc_QHeaderView_heightForWidth_h :: Ptr (TQHeaderView a) -> CInt -> IO CInt
instance QheightForWidth (QHeaderViewSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QHeaderView ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_hideEvent_h" qtc_QHeaderView_hideEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QHeaderViewSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_hideEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QHeaderView ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_keyReleaseEvent_h" qtc_QHeaderView_keyReleaseEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QHeaderViewSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QHeaderView ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_languageChange cobj_x0
foreign import ccall "qtc_QHeaderView_languageChange" qtc_QHeaderView_languageChange :: Ptr (TQHeaderView a) -> IO ()
instance QlanguageChange (QHeaderViewSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_languageChange cobj_x0
instance QleaveEvent (QHeaderView ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_leaveEvent_h" qtc_QHeaderView_leaveEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QHeaderViewSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QHeaderView ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QHeaderView_metric" qtc_QHeaderView_metric :: Ptr (TQHeaderView a) -> CLong -> IO CInt
instance Qmetric (QHeaderViewSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance Qmove (QHeaderView ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_move1" qtc_QHeaderView_move1 :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance Qmove (QHeaderViewSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QHeaderView ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QHeaderView_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QHeaderView_move_qth" qtc_QHeaderView_move_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance Qmove (QHeaderViewSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QHeaderView_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QHeaderView ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_move cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_move" qtc_QHeaderView_move :: Ptr (TQHeaderView a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QHeaderViewSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_move cobj_x0 cobj_x1
instance QmoveEvent (QHeaderView ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_moveEvent_h" qtc_QHeaderView_moveEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QHeaderViewSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QHeaderView ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_paintEngine_h cobj_x0
foreign import ccall "qtc_QHeaderView_paintEngine_h" qtc_QHeaderView_paintEngine_h :: Ptr (TQHeaderView a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QHeaderViewSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_paintEngine_h cobj_x0
instance QpaletteChange (QHeaderView ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_paletteChange" qtc_QHeaderView_paletteChange :: Ptr (TQHeaderView a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QHeaderViewSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QHeaderView ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_repaint cobj_x0
foreign import ccall "qtc_QHeaderView_repaint" qtc_QHeaderView_repaint :: Ptr (TQHeaderView a) -> IO ()
instance Qrepaint (QHeaderViewSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_repaint cobj_x0
instance Qrepaint (QHeaderView ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QHeaderView_repaint2" qtc_QHeaderView_repaint2 :: Ptr (TQHeaderView a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QHeaderViewSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QHeaderView ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_repaint1" qtc_QHeaderView_repaint1 :: Ptr (TQHeaderView a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QHeaderViewSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QHeaderView ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resetInputContext cobj_x0
foreign import ccall "qtc_QHeaderView_resetInputContext" qtc_QHeaderView_resetInputContext :: Ptr (TQHeaderView a) -> IO ()
instance QresetInputContext (QHeaderViewSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resetInputContext cobj_x0
instance Qresize (QHeaderView ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QHeaderView_resize1" qtc_QHeaderView_resize1 :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance Qresize (QHeaderViewSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QHeaderView ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_resize" qtc_QHeaderView_resize :: Ptr (TQHeaderView a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QHeaderViewSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_resize cobj_x0 cobj_x1
instance Qresize (QHeaderView ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QHeaderView_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QHeaderView_resize_qth" qtc_QHeaderView_resize_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> IO ()
instance Qresize (QHeaderViewSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QHeaderView_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QHeaderView ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QHeaderView_setGeometry1" qtc_QHeaderView_setGeometry1 :: Ptr (TQHeaderView a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QHeaderViewSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QHeaderView ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_setGeometry" qtc_QHeaderView_setGeometry :: Ptr (TQHeaderView a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QHeaderViewSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QHeaderView ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QHeaderView_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QHeaderView_setGeometry_qth" qtc_QHeaderView_setGeometry_qth :: Ptr (TQHeaderView a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QHeaderViewSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QHeaderView_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QHeaderView ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setMouseTracking" qtc_QHeaderView_setMouseTracking :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QsetMouseTracking (QHeaderViewSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QHeaderView ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_setVisible_h" qtc_QHeaderView_setVisible_h :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QsetVisible (QHeaderViewSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QHeaderView ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_showEvent_h" qtc_QHeaderView_showEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QHeaderViewSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QHeaderView ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_tabletEvent_h" qtc_QHeaderView_tabletEvent_h :: Ptr (TQHeaderView a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QHeaderViewSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QHeaderView ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateMicroFocus cobj_x0
foreign import ccall "qtc_QHeaderView_updateMicroFocus" qtc_QHeaderView_updateMicroFocus :: Ptr (TQHeaderView a) -> IO ()
instance QupdateMicroFocus (QHeaderViewSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_updateMicroFocus cobj_x0
instance QwindowActivationChange (QHeaderView ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QHeaderView_windowActivationChange" qtc_QHeaderView_windowActivationChange :: Ptr (TQHeaderView a) -> CBool -> IO ()
instance QwindowActivationChange (QHeaderViewSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QHeaderView ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_childEvent" qtc_QHeaderView_childEvent :: Ptr (TQHeaderView a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QHeaderViewSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QHeaderView ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QHeaderView_connectNotify" qtc_QHeaderView_connectNotify :: Ptr (TQHeaderView a) -> CWString -> IO ()
instance QconnectNotify (QHeaderViewSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QHeaderView ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QHeaderView_customEvent" qtc_QHeaderView_customEvent :: Ptr (TQHeaderView a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QHeaderViewSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QHeaderView_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QHeaderView ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QHeaderView_disconnectNotify" qtc_QHeaderView_disconnectNotify :: Ptr (TQHeaderView a) -> CWString -> IO ()
instance QdisconnectNotify (QHeaderViewSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QHeaderView ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QHeaderView_eventFilter_h" qtc_QHeaderView_eventFilter_h :: Ptr (TQHeaderView a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QHeaderViewSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QHeaderView_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QHeaderView ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QHeaderView_receivers" qtc_QHeaderView_receivers :: Ptr (TQHeaderView a) -> CWString -> IO CInt
instance Qreceivers (QHeaderViewSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QHeaderView_receivers cobj_x0 cstr_x1
instance Qsender (QHeaderView ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sender cobj_x0
foreign import ccall "qtc_QHeaderView_sender" qtc_QHeaderView_sender :: Ptr (TQHeaderView a) -> IO (Ptr (TQObject ()))
instance Qsender (QHeaderViewSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QHeaderView_sender cobj_x0
| keera-studios/hsQt | Qtc/Gui/QHeaderView.hs | bsd-2-clause | 106,871 | 0 | 15 | 16,590 | 33,576 | 17,073 | 16,503 | -1 | -1 |
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-}
module Distribution.Server (
-- * Server control
Server(..),
ServerEnv(..),
initialise,
run,
shutdown,
checkpoint,
reloadDatafiles,
-- * Server configuration
ListenOn(..),
ServerConfig(..),
defaultServerConfig,
hasSavedState,
-- * Server state
serverState,
initState,
-- * Temporary server while loading data
setUpTemp,
tearDownTemp
) where
import Happstack.Server.SimpleHTTP
import Distribution.Server.Framework
import qualified Distribution.Server.Framework.BackupRestore as Import
import qualified Distribution.Server.Framework.BlobStorage as BlobStorage
import qualified Distribution.Server.Framework.Auth as Auth
import Distribution.Server.Framework.Templating (TemplatesMode(NormalMode))
import Distribution.Server.Framework.AuthTypes (PasswdPlain(..))
import Distribution.Server.Framework.HtmlFormWrapper (htmlFormWrapperHack)
import Distribution.Server.Framework.Feature as Feature
import qualified Distribution.Server.Features as Features
import Distribution.Server.Features.Users
import qualified Distribution.Server.Users.Types as Users
import qualified Distribution.Server.Users.Users as Users
import qualified Distribution.Server.Users.Group as Group
import Distribution.Text
import Distribution.Verbosity as Verbosity
import System.Directory (createDirectoryIfMissing, doesDirectoryExist)
import Control.Concurrent
import Network.URI (URI(..), URIAuth(URIAuth), nullURI)
import Network.BSD (getHostName)
import Data.List (foldl', nubBy)
import Data.Int (Int64)
import Control.Arrow (second)
import Data.Function (on)
import qualified System.Log.Logger as HsLogger
import Control.Exception.Lifted as Lifted
import Paths_hackage_server (getDataDir)
data ListenOn = ListenOn {
loPortNum :: Int,
loIP :: String
} deriving (Show)
data ServerConfig = ServerConfig {
confVerbosity :: Verbosity,
confHostUri :: URI,
confListenOn :: ListenOn,
confStateDir :: FilePath,
confStaticDir :: FilePath,
confTmpDir :: FilePath,
confCacheDelay:: Int
} deriving (Show)
confDbStateDir, confBlobStoreDir,
confStaticFilesDir, confTemplatesDir :: ServerConfig -> FilePath
confDbStateDir config = confStateDir config </> "db"
confBlobStoreDir config = confStateDir config </> "blobs"
confStaticFilesDir config = confStaticDir config </> "static"
confTemplatesDir config = confStaticDir config </> "templates"
defaultServerConfig :: IO ServerConfig
defaultServerConfig = do
hostName <- getHostName
dataDir <- getDataDir
let portnum = 8080 :: Int
return ServerConfig {
confVerbosity = Verbosity.normal,
confHostUri = nullURI {
uriScheme = "http:",
uriAuthority = Just (URIAuth "" hostName (':' : show portnum))
},
confListenOn = ListenOn {
loPortNum = 8080,
loIP = "0.0.0.0"
},
confStateDir = "state",
confStaticDir = dataDir,
confTmpDir = "state" </> "tmp",
confCacheDelay= 0
}
data Server = Server {
serverFeatures :: [HackageFeature],
serverUserFeature :: UserFeature,
serverListenOn :: ListenOn,
serverEnv :: ServerEnv
}
-- | If we made a server instance from this 'ServerConfig', would we find some
-- existing saved state or would it be a totally clean instance with no
-- existing state.
--
hasSavedState :: ServerConfig -> IO Bool
hasSavedState = doesDirectoryExist . confDbStateDir
mkServerEnv :: ServerConfig -> IO ServerEnv
mkServerEnv config@(ServerConfig verbosity hostURI _
stateDir _ tmpDir
cacheDelay) = do
createDirectoryIfMissing False stateDir
let blobStoreDir = confBlobStoreDir config
staticDir = confStaticFilesDir config
templatesDir = confTemplatesDir config
store <- BlobStorage.open blobStoreDir
cron <- newCron verbosity
let env = ServerEnv {
serverStaticDir = staticDir,
serverTemplatesDir = templatesDir,
serverTemplatesMode = NormalMode,
serverStateDir = stateDir,
serverBlobStore = store,
serverCron = cron,
serverTmpDir = tmpDir,
serverCacheDelay = cacheDelay * 1000000, --microseconds
serverBaseURI = hostURI,
serverVerbosity = verbosity
}
return env
-- | Make a server instance from the server configuration.
--
-- This does not yet run the server (see 'run') but it does setup the server
-- state system, making it possible to import data, and initializes the
-- features.
--
-- Note: the server instance must eventually be 'shutdown' or you'll end up
-- with stale lock files.
--
initialise :: ServerConfig -> IO Server
initialise config = do
env <- mkServerEnv config
-- do feature initialization
(features, userFeature) <- Features.initHackageFeatures env
return Server {
serverFeatures = features,
serverUserFeature = userFeature,
serverListenOn = confListenOn config,
serverEnv = env
}
-- | Actually run the server, i.e. start accepting client http connections.
--
run :: Server -> IO ()
run server@Server{ serverEnv = env } = do
-- We already check this in Main, so we expect this check to always
-- succeed, but just in case...
let staticDir = serverStaticDir (serverEnv server)
exists <- doesDirectoryExist staticDir
when (not exists) $ fail $ "The static files directory " ++ staticDir ++ " does not exist."
addCronJob (serverCron env) CronJob {
cronJobName = "Checkpoint all the server state",
cronJobFrequency = WeeklyJobFrequency,
cronJobOneShot = False,
cronJobAction = checkpoint server
}
runServer listenOn $ do
handlePutPostQuotas
setLogging
fakeBrowserHttpMethods (impl server)
where
listenOn = serverListenOn server
-- HS6 - Quotas should be configurable as well. Also there are places in
-- the code that want to work with the request body directly but maybe
-- fail if the request body has already been consumed. The body will only
-- be consumed if it is a POST/PUT request *and* the content-type is
-- multipart/form-data. If this does happen, you should get a clear error
-- message saying what happened.
handlePutPostQuotas = decodeBody bodyPolicy
where
tmpdir = serverTmpDir (serverEnv server)
quota = 50 * (1024 ^ (2 :: Int64))
-- setting quota at 50mb, though perhaps should be configurable?
bodyPolicy = defaultBodyPolicy tmpdir quota quota quota
setLogging =
liftIO $ HsLogger.updateGlobalLogger
"Happstack.Server"
(adjustLogLevel (serverVerbosity (serverEnv server)))
where
adjustLogLevel v
| v == Verbosity.normal = HsLogger.setLevel HsLogger.WARNING
| v == Verbosity.verbose = HsLogger.setLevel HsLogger.INFO
| v == Verbosity.deafening = HsLogger.setLevel HsLogger.DEBUG
| otherwise = id
-- This is a cunning hack to solve the problem that HTML forms do not
-- support PUT, DELETE, etc, they only support GET and POST. We don't want
-- to compromise the design of the whole server just because HTML does not
-- support HTTP properly, so we allow browsers using HTML forms to do
-- PUT/DELETE etc by POSTing with special body parameters.
fakeBrowserHttpMethods part =
msum [ do method POST
htmlFormWrapperHack part
-- or just do things the normal way
, part
]
-- | Perform a clean shutdown of the server.
--
shutdown :: Server -> IO ()
shutdown server =
Features.shutdownAllFeatures (serverFeatures server)
--TODO: stop accepting incomming connections,
-- wait for connections to be processed.
-- | Write out a checkpoint of the server state. This makes recovery quicker
-- because fewer logged transactions have to be replayed.
--
checkpoint :: Server -> IO ()
checkpoint server =
Features.checkpointAllFeatures (serverFeatures server)
reloadDatafiles :: Server -> IO ()
reloadDatafiles server =
mapM_ Feature.featureReloadFiles (serverFeatures server)
-- | Return /one/ abstract state component per feature
serverState :: Server -> [(String, AbstractStateComponent)]
serverState server = [ (featureName feature, mconcat (featureState feature))
| feature <- serverFeatures server
]
-- An alternative to an import: starts the server off to a sane initial state.
-- To accomplish this, we import a 'null' tarball, finalizing immediately after initializing import
initState :: Server -> (String, String) -> IO ()
initState server (admin, pass) = do
-- We take the opportunity to checkpoint all the acid-state components
-- upon first initialisation as this helps with migration problems later.
-- https://github.com/acid-state/acid-state/issues/20
checkpoint server
let store = serverBlobStore (serverEnv server)
void . Import.importBlank store $ map (second abstractStateRestore) (serverState server)
-- create default admin user
let UserFeature{updateAddUser, adminGroup} = serverUserFeature server
muid <- case simpleParse admin of
Just uname -> do
let userAuth = Auth.newPasswdHash Auth.hackageRealm uname (PasswdPlain pass)
updateAddUser uname (Users.UserAuth userAuth)
Nothing -> fail "Couldn't parse admin name (should be alphanumeric)"
case muid of
Right uid -> Group.addUserToGroup adminGroup uid
Left Users.ErrUserNameClash -> fail $ "Inconceivable!! failed to create admin user"
-- The top-level server part.
-- It collects resources from Distribution.Server.Features, collects
-- them into a path hierarchy, and serves them.
impl :: Server -> ServerPart Response
impl server = logExceptions $
runServerPartE $
handleErrorResponse (serveErrorResponse errHandlers Nothing) $
renderServerTree [] serverTree
`mplus`
fallbackNotFound
where
serverTree :: ServerTree (DynamicPath -> ServerPartE Response)
serverTree =
fmap (serveResource errHandlers)
-- ServerTree Resource
. foldl' (\acc res -> addServerNode (resourceLocation res) res acc) serverTreeEmpty
-- [Resource]
$ concatMap Feature.featureResources (serverFeatures server)
errHandlers = nubBy ((==) `on` fst)
. reverse
. (("txt", textErrorPage):)
. concatMap Feature.featureErrHandlers
$ serverFeatures server
-- This basic one be overridden in another feature but means even in a
-- minimal server we can provide content-negoticated text/plain errors
textErrorPage :: ErrorResponse -> ServerPartE Response
textErrorPage = return . toResponse
fallbackNotFound =
errNotFound "Page not found"
[MText "Sorry, it's just not here."]
logExceptions :: ServerPart Response -> ServerPart Response
logExceptions act = Lifted.catch act $ \e -> do
liftIO . lognotice verbosity $ "WARNING: Received exception: " ++ show e
Lifted.throwIO (e :: SomeException)
verbosity = serverVerbosity (serverEnv server)
data TempServer = TempServer ThreadId
setUpTemp :: ServerConfig -> Int -> IO TempServer
setUpTemp sconf secs = do
tid <- forkIO $ do
-- wait a certain amount of time before setting it up, because sometimes
-- happstack-state is very fast, and switching the servers has a time
-- cost to it
threadDelay $ secs*1000000
-- could likewise specify a mirror to redirect to for tarballs, and 503 for everything else
runServer listenOn $ (resp 503 $ setHeader "Content-Type" "text/html" $ toResponse html503)
return (TempServer tid)
where listenOn = confListenOn sconf
runServer :: (ToMessage a) => ListenOn -> ServerPartT IO a -> IO ()
runServer listenOn f
= do socket <- bindIPv4 (loIP listenOn) (loPortNum listenOn)
simpleHTTPWithSocket socket nullConf f
-- | Static 503 page, based on Happstack's 404 page.
html503 :: String
html503 =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">" ++
"<html><head><title>503 Service Unavailable</title></head><body><h1>" ++
"503 Service Unavailable</h1><p>The server is undergoing maintenance" ++
"<br>It'll be back soon</p></body></html>"
tearDownTemp :: TempServer -> IO ()
tearDownTemp (TempServer tid) = do
killThread tid
-- give the server enough time to release the bind
threadDelay $ 1000000
| chrisdotcode/hackage-server | Distribution/Server.hs | bsd-3-clause | 12,926 | 0 | 18 | 3,092 | 2,364 | 1,295 | 1,069 | 225 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeFamilies #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2013
-- License : BSD3
-- Maintainer: Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Control.Task.STM
( MonadSTM(..)
) where
import Control.Concurrent.STM
import Control.Monad.State.Lazy as Lazy
import Control.Monad.State.Strict as Strict
import Control.Monad.Reader
import Control.Monad.Writer.Lazy as Lazy
import Control.Monad.Writer.Strict as Strict
import Control.Monad.Cont
class Monad m => MonadSTM m where
stm :: STM a -> m a
#ifndef HLINT
default stm :: (MonadTrans t, MonadSTM n, m ~ t n) => STM a -> m a
stm = lift . stm
{-# INLINE stm #-}
#endif
newTV :: a -> m (TVar a)
#ifndef HLINT
default newTV :: (MonadTrans t, MonadSTM n, m ~ t n) => a -> m (TVar a)
newTV = lift . newTV
#endif
{-# INLINE newTV #-}
readTV :: TVar a -> m a
#ifndef HLINT
default readTV :: (MonadTrans t, MonadSTM n, m ~ t n) => TVar a -> m a
readTV = lift . readTV
#endif
{-# INLINE readTV #-}
newTMV :: a -> m (TMVar a)
#ifndef HLINT
default newTMV :: (MonadTrans t, MonadSTM n, m ~ t n) => a -> m (TMVar a)
newTMV = lift . newTMV
#endif
{-# INLINE newTMV #-}
newEmptyTMV :: m (TMVar a)
#ifndef HLINT
default newEmptyTMV :: (MonadTrans t, MonadSTM n, m ~ t n) => m (TMVar a)
newEmptyTMV = lift newEmptyTMV
#endif
{-# INLINE newEmptyTMV #-}
newTC :: m (TChan a)
#ifndef HLINT
default newTC :: (MonadTrans t, MonadSTM n, m ~ t n) => m (TChan a)
newTC = lift newTC
#endif
{-# INLINE newTC #-}
instance MonadSTM STM where
stm = id
{-# INLINE stm #-}
newTV = newTVar
{-# INLINE newTV #-}
readTV = readTVar
{-# INLINE readTV #-}
newTMV = newTMVar
{-# INLINE newTMV #-}
newEmptyTMV = newEmptyTMVar
{-# INLINE newEmptyTMV #-}
newTC = newTChan
{-# INLINE newTC #-}
instance MonadSTM IO where
stm = atomically
{-# INLINE stm #-}
newTV = newTVarIO
{-# INLINE newTV #-}
readTV = readTVarIO
{-# INLINE readTV #-}
newTMV = newTMVarIO
{-# INLINE newTMV #-}
newEmptyTMV = newEmptyTMVarIO
{-# INLINE newEmptyTMV #-}
newTC = newTChanIO
{-# INLINE newTC #-}
instance MonadSTM m => MonadSTM (Lazy.StateT s m)
instance MonadSTM m => MonadSTM (Strict.StateT s m)
instance MonadSTM m => MonadSTM (ReaderT e m)
instance (MonadSTM m, Monoid w) => MonadSTM (Lazy.WriterT w m)
instance (MonadSTM m, Monoid w) => MonadSTM (Strict.WriterT w m)
instance MonadSTM m => MonadSTM (ContT r m)
| ekmett/tasks | src/Control/Task/STM.hs | bsd-3-clause | 2,673 | 0 | 12 | 541 | 768 | 422 | 346 | 69 | 0 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Trans.Error
-- Copyright : (c) Michael Weber <[email protected]> 2001,
-- (c) Jeff Newbern 2003-2006,
-- (c) Andriy Palamarchuk 2006
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This monad transformer adds the ability to fail or throw exceptions
-- to a monad.
--
-- A sequence of actions succeeds, producing a value, only if all the
-- actions in the sequence are successful. If one fails with an error,
-- the rest of the sequence is skipped and the composite action fails
-- with that error.
--
-- If the value of the error is not required, the variant in
-- "Control.Monad.Trans.Maybe" may be used instead.
-----------------------------------------------------------------------------
module Control.Monad.Trans.Error (
-- * The ErrorT monad transformer
Error(..),
ErrorList(..),
ErrorT(..),
mapErrorT,
-- * Error operations
throwError,
catchError,
-- * Lifting other operations
liftCallCC,
liftListen,
liftPass,
-- * Examples
-- $examples
) where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Applicative
import Control.Exception (IOException)
import Control.Monad
import Control.Monad.Fix
import Control.Monad.Instances ()
import System.IO
instance MonadPlus IO where
mzero = ioError (userError "mzero")
m `mplus` n = m `catch` \_ -> n
-- | An exception to be thrown.
--
-- Minimal complete definition: 'noMsg' or 'strMsg'.
class Error a where
-- | Creates an exception without a message.
-- The default implementation is @'strMsg' \"\"@.
noMsg :: a
-- | Creates an exception with a message.
-- The default implementation of @'strMsg' s@ is 'noMsg'.
strMsg :: String -> a
noMsg = strMsg ""
strMsg _ = noMsg
instance Error IOException where
strMsg = userError
-- | A string can be thrown as an error.
instance ErrorList a => Error [a] where
strMsg = listMsg
-- | Workaround so that we can have a Haskell 98 instance @'Error' 'String'@.
class ErrorList a where
listMsg :: String -> [a]
instance ErrorList Char where
listMsg = id
-- ---------------------------------------------------------------------------
-- Our parameterizable error monad
#if !(MIN_VERSION_base(4,2,1))
-- These instances are in base-4.3
instance Applicative (Either e) where
pure = Right
Left e <*> _ = Left e
Right f <*> r = fmap f r
instance Monad (Either e) where
return = Right
Left l >>= _ = Left l
Right r >>= k = k r
instance MonadFix (Either e) where
mfix f = let
a = f $ case a of
Right r -> r
_ -> error "empty mfix argument"
in a
#endif /* base to 4.2.0.x */
instance (Error e) => Alternative (Either e) where
empty = Left noMsg
Left _ <|> n = n
m <|> _ = m
instance (Error e) => MonadPlus (Either e) where
mzero = Left noMsg
Left _ `mplus` n = n
m `mplus` _ = m
-- | The error monad transformer. It can be used to add error handling
-- to other monads.
--
-- The @ErrorT@ Monad structure is parameterized over two things:
--
-- * e - The error type.
--
-- * m - The inner monad.
--
-- The 'return' function yields a successful computation, while @>>=@
-- sequences two subcomputations, failing on the first error.
newtype ErrorT e m a = ErrorT { runErrorT :: m (Either e a) }
-- | Map the unwrapped computation using the given function.
--
-- * @'runErrorT' ('mapErrorT' f m) = f ('runErrorT' m@)
mapErrorT :: (m (Either e a) -> n (Either e' b))
-> ErrorT e m a
-> ErrorT e' n b
mapErrorT f m = ErrorT $ f (runErrorT m)
instance (Functor m) => Functor (ErrorT e m) where
fmap f = ErrorT . fmap (fmap f) . runErrorT
instance (Functor m, Monad m) => Applicative (ErrorT e m) where
pure a = ErrorT $ return (Right a)
f <*> v = ErrorT $ do
mf <- runErrorT f
case mf of
Left e -> return (Left e)
Right k -> do
mv <- runErrorT v
case mv of
Left e -> return (Left e)
Right x -> return (Right (k x))
instance (Functor m, Monad m, Error e) => Alternative (ErrorT e m) where
empty = mzero
(<|>) = mplus
instance (Monad m, Error e) => Monad (ErrorT e m) where
return a = ErrorT $ return (Right a)
m >>= k = ErrorT $ do
a <- runErrorT m
case a of
Left l -> return (Left l)
Right r -> runErrorT (k r)
fail msg = ErrorT $ return (Left (strMsg msg))
instance (Monad m, Error e) => MonadPlus (ErrorT e m) where
mzero = ErrorT $ return (Left noMsg)
m `mplus` n = ErrorT $ do
a <- runErrorT m
case a of
Left _ -> runErrorT n
Right r -> return (Right r)
instance (MonadFix m, Error e) => MonadFix (ErrorT e m) where
mfix f = ErrorT $ mfix $ \a -> runErrorT $ f $ case a of
Right r -> r
_ -> error "empty mfix argument"
instance (Error e) => MonadTrans (ErrorT e) where
lift m = ErrorT $ do
a <- m
return (Right a)
instance (Error e, MonadIO m) => MonadIO (ErrorT e m) where
liftIO = lift . liftIO
-- | Signal an error value @e@.
--
-- * @'runErrorT' ('throwErrorT' e) = 'return' ('Left' e)@
throwError :: (Monad m, Error e) => e -> ErrorT e m a
throwError l = ErrorT $ return (Left l)
-- | Handle an error.
catchError :: (Monad m, Error e) =>
ErrorT e m a -- ^ the inner computation
-> (e -> ErrorT e m a) -- ^ a handler for errors in the inner
-- computation
-> ErrorT e m a
m `catchError` h = ErrorT $ do
a <- runErrorT m
case a of
Left l -> runErrorT (h l)
Right r -> return (Right r)
-- | Lift a @callCC@ operation to the new monad.
liftCallCC :: (((Either e a -> m (Either e b)) -> m (Either e a)) ->
m (Either e a)) -> ((a -> ErrorT e m b) -> ErrorT e m a) -> ErrorT e m a
liftCallCC callCC f = ErrorT $
callCC $ \c ->
runErrorT (f (\a -> ErrorT $ c (Right a)))
-- | Lift a @listen@ operation to the new monad.
liftListen :: Monad m =>
(m (Either e a) -> m (Either e a,w)) -> ErrorT e m a -> ErrorT e m (a,w)
liftListen listen = mapErrorT $ \ m -> do
(a, w) <- listen m
return $! fmap (\ r -> (r, w)) a
-- | Lift a @pass@ operation to the new monad.
liftPass :: Monad m => (m (Either e a,w -> w) -> m (Either e a)) ->
ErrorT e m (a,w -> w) -> ErrorT e m a
liftPass pass = mapErrorT $ \ m -> pass $ do
a <- m
return $! case a of
Left l -> (Left l, id)
Right (r, f) -> (Right r, f)
{- $examples
Wrapping an IO action that can throw an error @e@:
> type ErrorWithIO e a = ErrorT e IO a
> ==> ErrorT (IO (Either e a))
An IO monad wrapped in @StateT@ inside of @ErrorT@:
> type ErrorAndStateWithIO e s a = ErrorT e (StateT s IO) a
> ==> ErrorT (StateT s IO (Either e a))
> ==> ErrorT (StateT (s -> IO (Either e a,s)))
-}
| ekmett/transformers | Control/Monad/Trans/Error.hs | bsd-3-clause | 7,290 | 0 | 21 | 2,061 | 2,051 | 1,065 | 986 | 131 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module Game.Monsters.MBrain where
import Control.Lens (use, preuse, ix, (.=), (^.), zoom, (-=), (%=), (+=), (&), (.~), (-~), (%~), (+~))
import Control.Monad (unless, when, liftM, void)
import Data.Bits ((.&.), (.|.), complement)
import Data.Maybe (isNothing)
import Linear (V3(..), _x, _z)
import qualified Data.Vector as V
import {-# SOURCE #-} Game.GameImportT
import Game.LevelLocalsT
import Game.GameLocalsT
import Game.CVarT
import Game.SpawnTempT
import Game.EntityStateT
import Game.EdictT
import Game.GClientT
import Game.MoveInfoT
import Game.ClientPersistantT
import Game.ClientRespawnT
import Game.MonsterInfoT
import Game.PlayerStateT
import Types
import QuakeRef
import QuakeState
import CVarVariables
import Game.Adapters
import qualified Constants
import qualified Game.GameAI as GameAI
import qualified Game.GameMisc as GameMisc
import qualified Game.GameWeapon as GameWeapon
import qualified Game.GameUtil as GameUtil
import qualified Util.Lib as Lib
modelScale :: Float
modelScale = 1.0
frameWalk101 :: Int
frameWalk101 = 0
frameWalk111 :: Int
frameWalk111 = 10
frameAttack101 :: Int
frameAttack101 = 53
frameAttack118 :: Int
frameAttack118 = 70
frameAttack201 :: Int
frameAttack201 = 71
frameAttack217 :: Int
frameAttack217 = 87
framePain101 :: Int
framePain101 = 88
framePain121 :: Int
framePain121 = 108
framePain201 :: Int
framePain201 = 109
framePain208 :: Int
framePain208 = 116
framePain301 :: Int
framePain301 = 117
framePain306 :: Int
framePain306 = 122
frameDeath101 :: Int
frameDeath101 = 123
frameDeath118 :: Int
frameDeath118 = 140
frameDeath201 :: Int
frameDeath201 = 141
frameDeath205 :: Int
frameDeath205 = 145
frameDuck01 :: Int
frameDuck01 = 146
frameDuck08 :: Int
frameDuck08 = 153
frameDefense01 :: Int
frameDefense01 = 154
frameDefense08 :: Int
frameDefense08 = 161
frameStand01 :: Int
frameStand01 = 162
frameStand30 :: Int
frameStand30 = 191
frameStand31 :: Int
frameStand31 = 192
frameStand60 :: Int
frameStand60 = 221
brainSight :: EntInteract
brainSight =
GenericEntInteract "brain_sight" $ \selfRef _ -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSight <- use $ mBrainGlobals.mBrainSoundSight
sound (Just selfRef) Constants.chanVoice soundSight 1 Constants.attnNorm 0
return True
brainSearch :: EntThink
brainSearch =
GenericEntThink "brain_search" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundSearch <- use $ mBrainGlobals.mBrainSoundSearch
sound (Just selfRef) Constants.chanVoice soundSearch 1 Constants.attnNorm 0
return True
brainFramesStand :: V.Vector MFrameT
brainFramesStand =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
brainMoveStand :: MMoveT
brainMoveStand = MMoveT "brainMoveStand" frameStand01 frameStand30 brainFramesStand Nothing
brainStand :: EntThink
brainStand =
GenericEntThink "brain_stand" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just brainMoveStand)
return True
brainFramesIdle :: V.Vector MFrameT
brainFramesIdle =
V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
, MFrameT (Just GameAI.aiStand) 0 Nothing
]
brainMoveIdle :: MMoveT
brainMoveIdle = MMoveT "brainMoveIdle" frameStand31 frameStand60 brainFramesIdle (Just brainStand)
brainIdle :: EntThink
brainIdle =
GenericEntThink "brain_idle" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundIdle3 <- use $ mBrainGlobals.mBrainSoundIdle3
sound (Just selfRef) Constants.chanAuto soundIdle3 1 Constants.attnIdle 0
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just brainMoveIdle)
return True
brainFramesWalk1 :: V.Vector MFrameT
brainFramesWalk1 =
V.fromList [ MFrameT (Just GameAI.aiWalk) 7 Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
, MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 3 Nothing
, MFrameT (Just GameAI.aiWalk) 1 Nothing
, MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 0 Nothing
, MFrameT (Just GameAI.aiWalk) 9 Nothing
, MFrameT (Just GameAI.aiWalk) (-4) Nothing
, MFrameT (Just GameAI.aiWalk) (-1) Nothing
, MFrameT (Just GameAI.aiWalk) 2 Nothing
]
brainMoveWalk1 :: MMoveT
brainMoveWalk1 = MMoveT "brainMoveWalk1" frameWalk101 frameWalk111 brainFramesWalk1 Nothing
-- walk2 is FUBAR, do not use
{-
- # if 0 void brain_walk2_cycle(edict_t self) { if (random() > 0.1)
- self.monsterinfo.nextframe= FRAME_walk220; }
-
- static mframe_t brain_frames_walk2[]= new mframe_t[] { new
- mframe_t(ai_walk, 3, null), new mframe_t(ai_walk, -2, null), new
- mframe_t(ai_walk, -4, null), new mframe_t(ai_walk, -3, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 1, null), new
- mframe_t(ai_walk, 12, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, -3, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, -2, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 1, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 10, null, // Cycle
- Start)
-
- new mframe_t(ai_walk, -1, null), new mframe_t(ai_walk, 7, null), new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 3, null), new
- mframe_t(ai_walk, -3, null), new mframe_t(ai_walk, 2, null), new
- mframe_t(ai_walk, 4, null), new mframe_t(ai_walk, -3, null), new
- mframe_t(ai_walk, 2, null), new mframe_t(ai_walk, 0, null), new
- mframe_t(ai_walk, 4, brain_walk2_cycle), new mframe_t(ai_walk, -1, null),
- new mframe_t(ai_walk, -1, null), new mframe_t(ai_walk, -8, null,) new
- mframe_t(ai_walk, 0, null), new mframe_t(ai_walk, 1, null), new
- mframe_t(ai_walk, 5, null), new mframe_t(ai_walk, 2, null), new
- mframe_t(ai_walk, -1, null), new mframe_t(ai_walk, -5, null)}; static
- mmove_t brain_move_walk2= new mmove_t(FRAME_walk201, FRAME_walk240,
- brain_frames_walk2, null);
- # endif
-}
brainWalk :: EntThink
brainWalk =
GenericEntThink "brain_walk" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just brainMoveWalk1)
return True
brainDuckDown :: EntThink
brainDuckDown =
GenericEntThink "brain_duck_down" $ \selfRef -> do
self <- readRef selfRef
if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiDucked /= 0
then
return True
else do
modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.|. Constants.aiDucked)
& eMaxs._z -~ 32
& eTakeDamage .~ Constants.damageYes)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
brainDuckHold :: EntThink
brainDuckHold =
GenericEntThink "brain_duck_hold" $ \selfRef -> do
self <- readRef selfRef
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
if levelTime >= (self^.eMonsterInfo.miPauseTime)
then modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.&. (complement Constants.aiHoldFrame)))
else modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.|. Constants.aiHoldFrame))
return True
brainDuckUp :: EntThink
brainDuckUp =
GenericEntThink "brain_duck_up" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMonsterInfo.miAIFlags %~ (.&. (complement Constants.aiDucked))
& eMaxs._z +~ 32
& eTakeDamage .~ Constants.damageAim)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
brainDodge :: EntDodge
brainDodge =
GenericEntDodge "brain_dodge" $ \selfRef attackerRef eta -> do
r <- Lib.randomF
unless (r > 0.25) $ do
self <- readRef selfRef
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
when (isNothing (self^.eEnemy)) $
modifyRef selfRef (\v -> v & eEnemy .~ Just attackerRef
& eMonsterInfo.miPauseTime .~ levelTime + eta + 0.5
& eMonsterInfo.miCurrentMove .~ Just brainMoveDuck)
brainFramesDeath2 :: V.Vector MFrameT
brainFramesDeath2 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 9 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
brainDead :: EntThink
brainDead =
GenericEntThink "brain_dead" $ \selfRef -> do
modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 (-8)
& eMoveType .~ Constants.moveTypeToss
& eSvFlags %~ (.|. Constants.svfDeadMonster)
& eNextThink .~ 0)
linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity
linkEntity selfRef
return True
brainMoveDeath2 :: MMoveT
brainMoveDeath2 = MMoveT "brainMoveDeath2" frameDeath201 frameDeath205 brainFramesDeath2 (Just brainDead)
brainFramesDeath1 :: V.Vector MFrameT
brainFramesDeath1 =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 9 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
brainMoveDeath1 :: MMoveT
brainMoveDeath1 = MMoveT "brainMoveDeath1" frameDeath101 frameDeath118 brainFramesDeath1 (Just brainDead)
brainSwingRight :: EntThink
brainSwingRight =
GenericEntThink "brain_swing_right" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundMelee1 <- use $ mBrainGlobals.mBrainSoundMelee1
sound (Just selfRef) Constants.chanBody soundMelee1 1 Constants.attnNorm 0
return True
brainHitRight :: EntThink
brainHitRight =
GenericEntThink "brain_hit_right" $ \selfRef -> do
self <- readRef selfRef
let aim = V3 (fromIntegral Constants.meleeDistance) (self^.eMaxs._x) 8
r <- Lib.rand
hit <- GameWeapon.fireHit selfRef aim (15 + (fromIntegral r `mod` 5)) 40
when hit $ do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundMelee <- use $ mBrainGlobals.mBrainSoundMelee3
sound (Just selfRef) Constants.chanWeapon soundMelee 1 Constants.attnNorm 0
return True
brainSwingLeft :: EntThink
brainSwingLeft =
GenericEntThink "brain_swing_left" $ \selfRef -> do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundMelee2 <- use $ mBrainGlobals.mBrainSoundMelee2
sound (Just selfRef) Constants.chanBody soundMelee2 1 Constants.attnNorm 0
return True
brainHitLeft :: EntThink
brainHitLeft =
GenericEntThink "brain_hit_left" $ \selfRef -> do
self <- readRef selfRef
let aim = V3 (fromIntegral Constants.meleeDistance) (self^.eMins._x) 8
r <- Lib.rand
hit <- GameWeapon.fireHit selfRef aim (15 + (fromIntegral r `mod` 5)) 40
when hit $ do
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundMelee <- use $ mBrainGlobals.mBrainSoundMelee3
sound (Just selfRef) Constants.chanWeapon soundMelee 1 Constants.attnNorm 0
return True
brainChestOpen :: EntThink
brainChestOpen =
GenericEntThink "brain_chest_open" $ \selfRef -> do
modifyRef selfRef (\v -> v & eSpawnFlags %~ (.&. (complement 65536))
& eMonsterInfo.miPowerArmorType .~ Constants.powerArmorNone)
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundChestOpen <- use $ mBrainGlobals.mBrainSoundChestOpen
sound (Just selfRef) Constants.chanBody soundChestOpen 1 Constants.attnNorm 0
return True
brainTentacleAttack :: EntThink
brainTentacleAttack =
GenericEntThink "brain_tentacle_attack" $ \selfRef -> do
let aim = V3 (fromIntegral Constants.meleeDistance) 0 8
r <- Lib.rand
hit <- GameWeapon.fireHit selfRef aim (10 + (fromIntegral r `mod` 5)) (-600)
when hit $
modifyRef selfRef (\v -> v & eSpawnFlags %~ (.|. 65536))
sound <- use $ gameBaseGlobals.gbGameImport.giSound
soundTentaclesRetract <- use $ mBrainGlobals.mBrainSoundTentaclesRetract
sound (Just selfRef) Constants.chanWeapon soundTentaclesRetract 1 Constants.attnNorm 0
return True
brainFramesAttack1 :: V.Vector MFrameT
brainFramesAttack1 =
V.fromList [ MFrameT (Just GameAI.aiCharge) 8 Nothing
, MFrameT (Just GameAI.aiCharge) 3 Nothing
, MFrameT (Just GameAI.aiCharge) 5 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-3) (Just brainSwingRight)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-5) Nothing
, MFrameT (Just GameAI.aiCharge) (-7) (Just brainHitRight)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 6 (Just brainSwingLeft)
, MFrameT (Just GameAI.aiCharge) 1 Nothing
, MFrameT (Just GameAI.aiCharge) 2 (Just brainHitLeft)
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 6 Nothing
, MFrameT (Just GameAI.aiCharge) (-1) Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) (-11) Nothing
]
brainChestClosed :: EntThink
brainChestClosed =
GenericEntThink "brain_chest_closed" $ \selfRef -> do
self <- readRef selfRef
modifyRef selfRef (\v -> v & eMonsterInfo.miPowerArmorType .~ Constants.powerArmorScreen)
when ((self^.eSpawnFlags) .&. 65536 /= 0) $
modifyRef selfRef (\v -> v & eSpawnFlags %~ (.&. (complement 65536))
& eMonsterInfo.miCurrentMove .~ Just brainMoveAttack1)
return True
brainFramesAttack2 :: V.Vector MFrameT
brainFramesAttack2 =
V.fromList [ MFrameT (Just GameAI.aiCharge) 5 Nothing
, MFrameT (Just GameAI.aiCharge) (-4) Nothing
, MFrameT (Just GameAI.aiCharge) (-4) Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) 0 (Just brainChestOpen)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 13 (Just brainTentacleAttack)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) (-9) (Just brainChestClosed)
, MFrameT (Just GameAI.aiCharge) 0 Nothing
, MFrameT (Just GameAI.aiCharge) 4 Nothing
, MFrameT (Just GameAI.aiCharge) 3 Nothing
, MFrameT (Just GameAI.aiCharge) 2 Nothing
, MFrameT (Just GameAI.aiCharge) (-3) Nothing
, MFrameT (Just GameAI.aiCharge) (-6) Nothing
]
brainMelee :: EntThink
brainMelee =
GenericEntThink "brain_melee" $ \selfRef -> do
r <- Lib.randomF
let action = if r <= 0.5
then brainMoveAttack1
else brainMoveAttack2
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
brainFramesRun :: V.Vector MFrameT
brainFramesRun =
V.fromList [ MFrameT (Just GameAI.aiRun) 9 Nothing
, MFrameT (Just GameAI.aiRun) 2 Nothing
, MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 3 Nothing
, MFrameT (Just GameAI.aiRun) 1 Nothing
, MFrameT (Just GameAI.aiRun) 0 Nothing
, MFrameT (Just GameAI.aiRun) 0 Nothing
, MFrameT (Just GameAI.aiRun) 10 Nothing
, MFrameT (Just GameAI.aiRun) (-4) Nothing
, MFrameT (Just GameAI.aiRun) (-1) Nothing
, MFrameT (Just GameAI.aiRun) 2 Nothing
]
brainMoveRun :: MMoveT
brainMoveRun = MMoveT "brainMoveRun" frameWalk101 frameWalk111 brainFramesRun Nothing
brainRun :: EntThink
brainRun =
GenericEntThink "brain_run" $ \selfRef -> do
self <- readRef selfRef
modifyRef selfRef (\v -> v & eMonsterInfo.miPowerArmorType .~ Constants.powerArmorScreen)
let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0
then brainMoveStand
else brainMoveRun
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action)
return True
brainFramesDefense :: V.Vector MFrameT
brainFramesDefense =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
]
brainMoveDefense :: MMoveT
brainMoveDefense = MMoveT "brainMoveDefense" frameDefense01 frameDefense08 brainFramesDefense Nothing
brainFramesPain3 :: V.Vector MFrameT
brainFramesPain3 =
V.fromList [ MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-4) Nothing
]
brainMovePain3 :: MMoveT
brainMovePain3 = MMoveT "brainMovePain3" framePain301 framePain306 brainFramesPain3 (Just brainRun)
brainFramesPain2 :: V.Vector MFrameT
brainFramesPain2 =
V.fromList [ MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
]
brainMovePain2 :: MMoveT
brainMovePain2 = MMoveT "brainMovePain2" framePain201 framePain208 brainFramesPain2 (Just brainRun)
brainFramesPain1 :: V.Vector MFrameT
brainFramesPain1 =
V.fromList [ MFrameT (Just GameAI.aiMove) (-6) Nothing
, MFrameT (Just GameAI.aiMove) (-2) Nothing
, MFrameT (Just GameAI.aiMove) (-6) Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 2 Nothing
, MFrameT (Just GameAI.aiMove) 1 Nothing
, MFrameT (Just GameAI.aiMove) 7 Nothing
, MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) 3 Nothing
, MFrameT (Just GameAI.aiMove) (-1) Nothing
]
brainMovePain1 :: MMoveT
brainMovePain1 = MMoveT "brainMovePain1" framePain101 framePain121 brainFramesPain1 (Just brainRun)
brainFramesDuck :: V.Vector MFrameT
brainFramesDuck =
V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing
, MFrameT (Just GameAI.aiMove) (-2) (Just brainDuckDown)
, MFrameT (Just GameAI.aiMove) 17 (Just brainDuckHold)
, MFrameT (Just GameAI.aiMove) (-3) Nothing
, MFrameT (Just GameAI.aiMove) (-1) (Just brainDuckUp)
, MFrameT (Just GameAI.aiMove) (-5) Nothing
, MFrameT (Just GameAI.aiMove) (-6) Nothing
, MFrameT (Just GameAI.aiMove) (-6) Nothing
]
brainMoveDuck :: MMoveT
brainMoveDuck = MMoveT "brainMoveDuck" frameDuck01 frameDuck08 brainFramesDuck (Just brainRun)
brainPain :: EntPain
brainPain =
GenericEntPain "brain_pain" $ \selfRef _ _ _ -> do
self <- readRef selfRef
when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $
modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1)
levelTime <- use $ gameBaseGlobals.gbLevel.llTime
unless (levelTime < (self^.ePainDebounceTime)) $ do
modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3)
skillValue <- liftM (^.cvValue) skillCVar
unless (skillValue == 3) $ do -- no pain anims in nightmare
r <- Lib.randomF
(soundPain, currentMove) <- if | r < 0.33 -> do
soundPain <- use $ mBrainGlobals.mBrainSoundPain1
return (soundPain, brainMovePain1)
| r < 0.66 -> do
soundPain <- use $ mBrainGlobals.mBrainSoundPain2
return (soundPain, brainMovePain2)
| otherwise -> do
soundPain <- use $ mBrainGlobals.mBrainSoundPain1
return (soundPain, brainMovePain3)
sound <- use $ gameBaseGlobals.gbGameImport.giSound
sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove)
brainDie :: EntDie
brainDie =
GenericEntDie "brain_die" $ \selfRef _ _ damage _ -> do
modifyRef selfRef (\v -> v & eEntityState.esEffects .~ 0
& eMonsterInfo.miPowerArmorType .~ Constants.powerArmorNone)
self <- readRef selfRef
gameImport <- use $ gameBaseGlobals.gbGameImport
let sound = gameImport^.giSound
soundIndex = gameImport^.giSoundIndex
if | (self^.eHealth) <= (self^.eGibHealth) -> do -- check for gib
soundIdx <- soundIndex (Just "misc/udeath.wav")
sound (Just selfRef) Constants.chanVoice soundIdx 1 Constants.attnNorm 0
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic
GameMisc.throwHead selfRef "models/objects/gibs/head2/tris.md2" damage Constants.gibOrganic
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead)
| (self^.eDeadFlag) == Constants.deadDead ->
return ()
| otherwise -> do -- regular death
soundDeath <- use $ mBrainGlobals.mBrainSoundDeath
sound (Just selfRef) Constants.chanVoice soundDeath 1 Constants.attnNorm 0
r <- Lib.randomF
let currentMove = if r <= 0.5
then brainMoveDeath1
else brainMoveDeath2
modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead
& eTakeDamage .~ Constants.damageYes
& eMonsterInfo.miCurrentMove .~ Just currentMove)
brainMoveAttack1 :: MMoveT
brainMoveAttack1 = MMoveT "brainMoveAttack1" frameAttack101 frameAttack118 brainFramesAttack1 (Just brainRun)
brainMoveAttack2 :: MMoveT
brainMoveAttack2 = MMoveT "brainMoveAttack2" frameAttack201 frameAttack217 brainFramesAttack2 (Just brainRun)
{-
- QUAKED monster_brain (1 .5 0) (-16 -16 -24) (16 16 32) Ambush
- Trigger_Spawn Sight
-}
spMonsterBrain :: Ref EdictT -> Quake ()
spMonsterBrain selfRef = do
deathmatchValue <- liftM (^.cvValue) deathmatchCVar
if deathmatchValue /= 0
then
GameUtil.freeEdict selfRef
else do
gameImport <- use $ gameBaseGlobals.gbGameImport
let soundIndex = gameImport^.giSoundIndex
modelIndex = gameImport^.giModelIndex
linkEntity = gameImport^.giLinkEntity
soundIndex (Just "brain/brnatck1.wav") >>= (mBrainGlobals.mBrainSoundChestOpen .=)
soundIndex (Just "brain/brnatck2.wav") >>= (mBrainGlobals.mBrainSoundTentaclesExtend .=)
soundIndex (Just "brain/brnatck3.wav") >>= (mBrainGlobals.mBrainSoundTentaclesRetract .=)
soundIndex (Just "brain/brndeth1.wav") >>= (mBrainGlobals.mBrainSoundDeath .=)
soundIndex (Just "brain/brnidle1.wav") >>= (mBrainGlobals.mBrainSoundIdle1 .=)
soundIndex (Just "brain/brnidle2.wav") >>= (mBrainGlobals.mBrainSoundIdle2 .=)
soundIndex (Just "brain/brnlens1.wav") >>= (mBrainGlobals.mBrainSoundIdle3 .=)
soundIndex (Just "brain/brnpain1.wav") >>= (mBrainGlobals.mBrainSoundPain1 .=)
soundIndex (Just "brain/brnpain2.wav") >>= (mBrainGlobals.mBrainSoundPain2 .=)
soundIndex (Just "brain/brnsght1.wav") >>= (mBrainGlobals.mBrainSoundSight .=)
soundIndex (Just "brain/brnsrch1.wav") >>= (mBrainGlobals.mBrainSoundSearch .=)
soundIndex (Just "brain/melee1.wav") >>= (mBrainGlobals.mBrainSoundMelee1 .=)
soundIndex (Just "brain/melee2.wav") >>= (mBrainGlobals.mBrainSoundMelee2 .=)
soundIndex (Just "brain/melee3.wav") >>= (mBrainGlobals.mBrainSoundMelee3 .=)
modelIdx <- modelIndex (Just "models/monsters/brain/tris.md2")
modifyRef selfRef (\v -> v & eMoveType .~ Constants.moveTypeStep
& eSolid .~ Constants.solidBbox
& eEntityState.esModelIndex .~ modelIdx
& eMins .~ V3 (-16) (-16) (-24)
& eMaxs .~ V3 16 16 32
& eHealth .~ 300
& eGibHealth .~ (-150)
& eMass .~ 400
& ePain .~ Just brainPain
& eDie .~ Just brainDie
& eMonsterInfo.miStand .~ Just brainStand
& eMonsterInfo.miWalk .~ Just brainWalk
& eMonsterInfo.miRun .~ Just brainRun
& eMonsterInfo.miDodge .~ Just brainDodge
& eMonsterInfo.miMelee .~ Just brainMelee
& eMonsterInfo.miSight .~ Just brainSight
& eMonsterInfo.miSearch .~ Just brainSearch
& eMonsterInfo.miIdle .~ Just brainIdle
& eMonsterInfo.miPowerArmorType .~ Constants.powerArmorScreen
& eMonsterInfo.miPowerArmorPower .~ 100)
linkEntity selfRef
modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just brainMoveStand
& eMonsterInfo.miScale .~ modelScale)
void $ think GameAI.walkMonsterStart selfRef
| ksaveljev/hake-2 | src/Game/Monsters/MBrain.hs | bsd-3-clause | 32,667 | 0 | 52 | 9,476 | 8,719 | 4,413 | 4,306 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module HPACK.HuffmanSpec where
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Char (toLower)
import Data.Hex
import Data.Maybe (fromJust)
import Network.HPACK
import Network.HPACK.Huffman
import Test.Hspec
import Test.Hspec.QuickCheck
testData :: [(ByteString, ByteString)]
testData = [
("", "")
, ("www.example.com", "f1e3c2e5f23a6ba0ab90f4ff")
, ("no-cache", "a8eb10649cbf")
, ("custom-key", "25a849e95ba97d7f")
, ("custom-value", "25a849e95bb8e8b4bf")
, ("private", "aec3771a4b")
, ("Mon, 21 Oct 2013 20:13:21 GMT", "d07abe941054d444a8200595040b8166e082a62d1bff")
, ("https://www.example.com", "9d29ad171863c78f0b97c8e9ae82ae43d3")
, ("Mon, 21 Oct 2013 20:13:22 GMT", "d07abe941054d444a8200595040b8166e084a62d1bff")
, ("gzip", "9bd9ab")
, ("foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007")
]
shouldBeEncoded :: ByteString -> ByteString -> Expectation
shouldBeEncoded inp out = enc inp `shouldBe` out
where
enc = BS.map toLower . hex . encode
shouldBeDecoded :: ByteString -> Either DecodeError ByteString -> Expectation
shouldBeDecoded inp out = dec inp `shouldBe` out
where
dec = decode . fromJust . unhex
spec :: Spec
spec = do
describe "encode and decode" $ do
prop "duality" $ \cs ->
let bs = BS.pack cs
in decode (encode bs) == Right bs
describe "encode" $ do
it "encodes" $ do
mapM_ (\(x,y) -> x `shouldBeEncoded` y) testData
describe "decode" $ do
it "decodes" $ do
"ff" `shouldBeDecoded` Left TooLongEos
"ffffea" `shouldBeDecoded` Right "\9"
"ffffeaff" `shouldBeDecoded` Left TooLongEos
mapM_ (\(x,y) -> y `shouldBeDecoded` Right x) testData
| bergmark/http2 | test/HPACK/HuffmanSpec.hs | bsd-3-clause | 1,902 | 0 | 17 | 368 | 497 | 277 | 220 | 45 | 1 |
module Controls where
import Data.Binary.Get
import Data.IORef
import System.IO.Unsafe
import Memory
import ImpossibleImports
import Methods
import Deserialize
import Serialize
getState :: Int -> State
getState index = ((!! index) . unsafePerformIO) $ readIORef states
readState :: Int -> IO State
readState stateIndex = (!! stateIndex) `fmap` readIORef states
readState' :: IO State
readState' = head `fmap` readIORef states
getState'' :: FilePath -> State
getState'' filePath = unsafePerformIO $ deserialize_ filePath
readState'' :: FilePath -> IO State
readState'' = deserialize_
writeState :: Int -> State -> IO ()
writeState index newState = ImpossibleImports.modifyIORef' states (replace' index newState)
writeState' :: State -> IO ()
writeState' = writeState 0
writeState'' :: FilePath -> IO ()
writeState'' filePath = deserialize filePath >> readState' >>= writeState'
visualize :: Int -> IO ()
visualize index = (getTypeDescriptors . (!! index)) `fmap` readIORef states >>= printTypeDescs
visualize' :: IO ()
visualize' = getTypeDescriptors `fmap` readState' >>= printTypeDescs
visualize'' :: FilePath -> IO ()
visualize'' filePath = getTypeDescriptors `fmap` readState'' filePath >>= printTypeDescs
serialize' :: FilePath -> IO ()
serialize' = serialize $ getState 0
serialize'' :: FilePath -> FilePath -> IO ()
serialize'' inPath outPath = readState'' inPath >>= \state -> serialize state outPath
getStrings :: State -> [String]
getStrings (strings,_,_) = strings
readStrings' :: IO [String]
readStrings' = getStrings `fmap` readState'
getStrings'' :: FilePath -> [String]
getStrings'' filePath = getStrings $ getState'' filePath
getUserTypes :: State -> [UserType]
getUserTypes (_,uTs,_) = uTs
readUserTypes' :: IO [UserType]
readUserTypes' = getUserTypes `fmap` readState'
getUserTypes'' :: FilePath -> [UserType]
getUserTypes'' filePath = getUserTypes $ getState'' filePath
getTypeDescriptors :: State -> [TD]
getTypeDescriptors (_,_,tDs) = tDs
readTypeDescriptors' :: IO [TD]
readTypeDescriptors' = getTypeDescriptors `fmap` readState'
getTypeDescriptors'' :: FilePath -> [TD]
getTypeDescriptors'' filePath = getTypeDescriptors $ getState'' filePath
| skill-lang/skill | deps/haskell/Controls.hs | bsd-3-clause | 2,188 | 0 | 9 | 310 | 676 | 366 | 310 | 53 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
-------------------------------------------------------------------------------
-- |
-- Module : Data.NBT.Types
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-------------------------------------------------------------------------------
module Data.NBT.Types
( NBT (..)
, TagType (..)
, NamelessNBT (..)
, NBTList (..)
) where
import Control.Applicative
import Control.DeepSeq
import Data.Data
import Data.Int
import qualified Data.Text as T
import Data.Typeable
import qualified Data.Vector.Unboxed as U
import GHC.Generics
data NBT
= TagByte T.Text Int8
| TagShort T.Text Int16
| TagInt T.Text Int32
| TagLong T.Text Int64
| TagFloat T.Text Float
| TagDouble T.Text Double
| TagByteArray T.Text (U.Vector Int8)
| TagString T.Text T.Text
| TagList T.Text NBTList
| TagCompound T.Text [NBT]
| TagIntArray T.Text (U.Vector Int32)
deriving (Show,Read,Eq,Typeable,Data,Generic)
instance NFData NBT
data NamelessNBT
= NTagByte Int8
| NTagShort Int16
| NTagInt Int32
| NTagLong Int64
| NTagFloat Float
| NTagDouble Double
| NTagByteArray (U.Vector Int8)
| NTagString T.Text
| NTagList NBTList
| NTagCompound [NBT]
| NTagIntArray (U.Vector Int32)
deriving (Show,Read,Eq,Typeable,Data,Generic)
instance NFData NamelessNBT
data NBTList = NBTList TagType [NamelessNBT] deriving (Show,Read,Eq,Typeable,Data,Generic)
instance NFData NBTList
data TagType
= TypeEnd
| TypeByte
| TypeShort
| TypeInt
| TypeLong
| TypeFloat
| TypeDouble
| TypeByteArray
| TypeString
| TypeList
| TypeCompound
| TypeIntArray
deriving (Show,Read,Eq,Enum,Typeable,Data,Generic)
instance NFData TagType
| oldmanmike/hs-minecraft-nbt | src/Data/NBT/Types.hs | bsd-3-clause | 2,048 | 0 | 9 | 494 | 494 | 287 | 207 | 60 | 0 |
{-# LANGUAGE NoBangPatterns, CPP, DeriveDataTypeable, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.CompactMap
-- Copyright : (c) David Himmelstrup 2008
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- An efficient implementation of maps from keys to values (dictionaries).
--
-- Since many function names (but not the type name) clash with
-- "Prelude" names, this module is usually imported @qualified@, e.g.
--
-- > import Data.CompactMap (Map)
-- > import qualified Data.CompactMap as Map
--
-- The implementation of 'Map' is based on /size balanced/ binary trees (or
-- trees of /bounded balance/) as described by:
--
-- * Stephen Adams, \"/Efficient sets: a balancing act/\",
-- Journal of Functional Programming 3(4):553-562, October 1993,
-- <http://www.swiss.ai.mit.edu/~adams/BB/>.
--
-- * J. Nievergelt and E.M. Reingold,
-- \"/Binary search trees of bounded balance/\",
-- SIAM journal of computing 2(1), March 1973.
--
-- Note that the implementation is /left-biased/ -- the elements of a
-- first argument are always preferred to the second, for example in
-- 'union' or 'insert'.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>.
-----------------------------------------------------------------------------
module Data.CompactMap
( -- * Map type
Map -- instance Eq,Show,Read
-- * Operators
, (!) --, (\\)
-- * Query
, null
, size
, member
, notMember
, lookup
, findWithDefault
-- * Construction
, empty
, singleton
-- ** Insertion
, insert
, insertWith, insertWithKey, insertLookupWithKey
-- ** Delete\/Update
, delete
, adjust
, adjustWithKey
, update
, updateWithKey
, updateLookupWithKey
, alter
-- * Combine
, union
, unionWith
, unionWithKey
, unions
, unionsWith{-
-- ** Difference
, difference
, differenceWith
, differenceWithKey
-- ** Intersection
, intersection
, intersectionWith
, intersectionWithKey-}
-- * Traversal
-- ** Map
, map
, mapWithKey{-
, mapAccum
, mapAccumWithKey-}
, mapKeys
, mapKeysWith
, mapKeysMonotonic
-- ** Fold
, fold
, foldWithKey
-- * Conversion
, elems
, keys
, keysSet
, assocs
-- ** Lists
, toList
, fromList
, fromListWith
, fromListWithKey
-- ** Ordered lists
, toAscList
, fromAscList
, fromAscListWith
, fromAscListWithKey
, fromDistinctAscList
-- * Filter
, filter
, filterWithKey
, partition
, partitionWithKey
, mapMaybe
, mapMaybeWithKey
, mapEither
, mapEitherWithKey{-
, split
, splitLookup
-- * Submap
, isSubmapOf, isSubmapOfBy
, isProperSubmapOf, isProperSubmapOfBy
-- * Indexed
, lookupIndex
, findIndex
, elemAt
, updateAt
, deleteAt-}
-- * Min\/Max
, findMin
, findMax
, deleteMin
-- , deleteMax
, deleteFindMin
-- , deleteFindMax
{- , updateMin
, updateMax
, updateMinWithKey
, updateMaxWithKey
, minView
, maxView
, minViewWithKey
, maxViewWithKey
-- * Debugging
, showTree
, showTreeWith
, valid-}
) where
import Data.Monoid (Monoid(..))
import Control.Concurrent
import Data.IORef
import Data.Binary
import Data.Typeable
import Data.List (foldl')
import System.IO.Unsafe
import qualified Data.Maybe as Maybe
import Data.Maybe (isJust)
import Foreign (nullPtr)
import Text.Read hiding (get)
import Control.Monad
import qualified Data.CompactMap.Index as Index
import Data.CompactMap.Types as Types
import qualified Data.Array.IArray as IArray
import qualified Data.Set as Set
import qualified Data.ByteString as Strict
import qualified Data.ByteString.Lazy as Lazy
import Prelude hiding (null,lookup,map,filter)
import qualified Prelude
import System.Mem.Weak
data Range = Range Int Int
-- | A Map from keys @k@ to values @a@.
data Map k a = Empty
| Existing
{ index :: !(MVar Index)
, uniq :: {-# UNPACK #-} !(IORef Int)
, range :: ![Range]
, mapSize :: {-# UNPACK #-} !Int
}
#if !defined(HPC)
deriving (Typeable)
#endif
{--------------------------------------------------------------------
Instances
--------------------------------------------------------------------}
instance (Eq k, Eq a, Binary k, Binary a) => Eq (Map k a) where
m1 == m2 = toList m1 == toList m2
instance (Ord k, Ord a, Binary k, Binary a) => Ord (Map k a) where
m1 `compare` m2 = toList m1 `compare` toList m2
instance (Binary k, Binary a, Show k, Show a) => Show (Map k a) where
showsPrec d m = showParen (d > 10) $
showString "fromList " . shows (toList m)
instance (Ord k, Binary k, Binary a, Read k, Read a) => Read (Map k a) where
#ifdef __GLASGOW_HASKELL__
readPrec = parens $ prec 10 $ do
Ident "fromList" <- lexP
xs <- readPrec
return (fromList xs)
readListPrec = readListPrecDefault
#else
readsPrec p = readParen (p > 10) $ \ r -> do
("fromList",s) <- lex r
(xs,t) <- reads s
return (fromList xs,t)
#endif
instance Binary (Map k a) where
put Empty = put (0::Int)
put Existing{index=index,range=range,mapSize=mapSize} =
let a = unsafePerformIO $ withMVar index $ Index.listKeyPointers
in do put mapSize
forM_ (IArray.elems a) $ \ptr ->
do let ls = unsafePerformIO $ Index.getDataFromPointer ptr
case findValue range ls of
Nothing -> return ()
Just val -> do let key = unsafePerformIO $ Index.getKeyFromPointer ptr
put (key,val)
unsafePerformIO $
do withMVar index Index.touchIndex
return $ return ()
get = do n <- get
ls <- replicateM n get
unsafePerformIO $
do idx <- Index.newIndex
forM_ ls $ \(k,v) -> do keyCursor <- Index.newKeyCursor (indexBuffer idx) (Lazy.fromChunks [k])
Index.insertLargestKeyCursor idx keyCursor
dataCursor <- Index.newDataCursor (indexBuffer idx) 0 (Just (Lazy.fromChunks [v]))
Index.pushNewDataCursor keyCursor dataCursor
--Index.insertBS idx (decodeStrict k :: k) 0 (Just (Lazy.fromChunks [v]))
uniq <- newIORef 1
index <- newMVar idx
return $ return $ Existing{index=index,uniq=uniq,range=addToRange 0 [],mapSize=n}
instance (Ord k, Binary k, Binary a) => Monoid (Map k a) where
mempty = empty
mappend = union
mconcat = unions
{--------------------------------------------------------------------
Methods
--------------------------------------------------------------------}
infixl 9 ! -- ,\\
-- | /O(log n)/. Find the value at a key.
-- Calls 'error' when the element can not be found.
--
-- > fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map
-- > fromList [(5,'a'), (3,'b')] ! 5 == 'a'
(!) :: (Ord k, Binary k, Binary a) => Map k a -> k -> a
m ! k = case lookup k m of
Nothing -> error "element not in the map"
Just x -> x
-- | /O(1)/. Is the map empty?
--
-- > Data.Map.null (empty) == True
-- > Data.Map.null (singleton 1 'a') == False
null :: Map k a -> Bool
null m = size m == 0
-- | /O(1)/. The number of elements in the map.
--
-- > size empty == 0
-- > size (singleton 1 'a') == 1
-- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
size :: Map k a -> Int
size Empty = 0
size Existing{mapSize=size} = size
-- | /O(log n)/. Is the key a member of the map? See also 'notMember'.
--
-- > member 5 (fromList [(5,'a'), (3,'b')]) == True
-- > member 1 (fromList [(5,'a'), (3,'b')]) == False
member :: (Ord k, Binary k) => k -> Map k a -> Bool
member k Empty = False
member k Existing{index=index,range=range}
= unsafePerformIO $ withMVar index $ \idx ->
do ls <- Index.lookupList idx k
return $ isJust $ findValue range ls
-- | /O(log n)/. Is the key not a member of the map? See also 'member'.
--
-- > notMember 5 (fromList [(5,'a'), (3,'b')]) == False
-- > notMember 1 (fromList [(5,'a'), (3,'b')]) == True
notMember :: (Ord k, Binary k) => k -> Map k a -> Bool
notMember k m = not (member k m)
-- | /O(log n)/. Lookup the value at a key in the map.
--
-- The function will return the corresponding value as @('Just' value)@,
-- or 'Nothing' if the key isn't in the map.
--
-- An example of using @lookup@:
--
-- > import Prelude hiding (lookup)
-- > import Data.CompactMap
-- >
-- > employeeDept = fromList([("John","Sales"), ("Bob","IT")])
-- > deptCountry = fromList([("IT","USA"), ("Sales","France")])
-- > countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")])
-- >
-- > employeeCurrency :: String -> Maybe String
-- > employeeCurrency name = do
-- > dept <- lookup name employeeDept
-- > country <- lookup dept deptCountry
-- > lookup country countryCurrency
-- >
-- > main = do
-- > putStrLn $ "John's currency: " ++ (show (employeeCurrency "John"))
-- > putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))
--
-- The output of this program:
--
-- > John's currency: Just "Euro"
-- > Pete's currency: Nothing
lookup :: (Ord k, Binary k, Binary a) => k -> Map k a -> Maybe a
lookup k Empty = Nothing
lookup k Existing{index=index,range=range}
= unsafePerformIO $ withMVar index $ \idx ->
do ls <- Index.lookupList idx k
case findValue range ls of
Nothing -> return Nothing
Just bs -> do mkWeak bs index Nothing
return $ Just (decodeStrict bs)
-- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
-- the value at key @k@ or returns default value @def@
-- when the key is not in the map.
--
-- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
-- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
findWithDefault :: (Ord k, Binary k, Binary a) => a -> k -> Map k a -> a
findWithDefault def k m = case lookup k m of
Nothing -> def
Just x -> x
-- | /O(1)/. The empty map.
--
-- > empty == fromList []
-- > size empty == 0
empty :: Map k a
empty = Empty
-- | /O(1)/. A map with a single element.
--
-- > singleton 1 'a' == fromList [(1, 'a')]
-- > size (singleton 1 'a') == 1
singleton :: (Ord k, Binary k, Binary a) => k -> a -> Map k a
singleton k a = insert k a empty
-- | /O(log n)/. Insert a new key and value in the map.
-- If the key is already present in the map, the associated value is
-- replaced with the supplied value. 'insert' is equivalent to
-- @'insertWith' 'const'@.
--
-- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
-- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
-- > insert 5 'x' empty == singleton 5 'x'
insert :: (Ord k, Binary k, Binary a) => k -> a -> Map k a -> Map k a
insert k a m
= unsafePerformIO $
withExisting m $ \Existing{index=index,uniq=uniq,range=range,mapSize=mapSize} ->
withMVar index $ \idx ->
do u <- readIORef uniq
modifyIORef uniq succ
ls <- Index.insert idx k u (Just a)
let newSize | haveOldValue range ls = mapSize
| otherwise = mapSize+1
return Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=newSize}
-- | /O(log n)/. Insert with a function, combining new value and old value.
-- @'insertWith' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key, f new_value old_value)@.
--
-- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
-- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
insertWith :: (Ord k, Binary k, Binary a) => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith f k x m
= insertWithKey (\_ x' y' -> f x' y') k x m
-- | /O(log n)/. Insert with a function, combining key, new value and old value.
-- @'insertWithKey' f key value mp@
-- will insert the pair (key, value) into @mp@ if key does
-- not exist in the map. If the key does exist, the function will
-- insert the pair @(key,f key new_value old_value)@.
-- Note that the key passed to f is the same key passed to 'insertWithKey'.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
-- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
-- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
insertWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWithKey f kx x Empty = singleton kx x
insertWithKey f kx x Existing{index=index,uniq=uniq,range=range,mapSize=mapSize}
= unsafePerformIO $ withMVar index $ \idx ->
do u <- readIORef uniq
modifyIORef uniq succ
keyCursor <- Index.insertKey idx kx
ls <- Index.getDataFromPointer keyCursor
let oldVal = findValue range ls
newVal = case oldVal of
Nothing -> x
Just old -> f kx x (decodeStrict old)
newSize = if isJust oldVal then mapSize else mapSize + 1
dataCursor <- Index.newDataCursor (indexBuffer idx) u (Just $ encode newVal)
Index.pushNewDataCursor keyCursor dataCursor
return $ Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=newSize}
-- | /O(log n)/. Combines insert operation with old value retrieval.
-- The expression (@'insertLookupWithKey' f k x map@)
-- is a pair where the first element is equal to (@'lookup' k map@)
-- and the second element equal to (@'insertWithKey' f k x map@).
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
-- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
-- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
--
-- This is how to define @insertLookup@ using @insertLookupWithKey@:
--
-- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
-- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
-- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
insertLookupWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
insertLookupWithKey f k a Empty = (Nothing, singleton k a)
insertLookupWithKey f k a Existing{index=index,uniq=uniq,range=range,mapSize=mapSize}
= unsafePerformIO $ withMVar index $ \idx ->
do u <- readIORef uniq
modifyIORef uniq succ
keyCursor <- Index.insertKey idx k
ls <- Index.getDataFromPointer keyCursor
let oldValBS = findValue range ls
oldVal = fmap decodeStrict oldValBS
newVal = case oldVal of
Nothing -> a
Just old -> f k a old
newSize = if isJust oldVal then mapSize else mapSize + 1
case oldValBS of Just val -> mkWeak val index Nothing>>return(); Nothing -> return ()
dataCursor <- Index.newDataCursor (indexBuffer idx) u (Just $ encode newVal)
Index.pushNewDataCursor keyCursor dataCursor
return $ (oldVal, Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=newSize})
-- | /O(log n)/. Delete a key and its value from the map. When the key is not
-- a member of the map, the original map is returned.
--
-- > delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > delete 5 empty == empty
delete :: (Ord k, Binary k) => k -> Map k a -> Map k a
delete k Empty = Empty
delete k Existing{index=index,uniq=uniq,range=range,mapSize=mapSize}
= unsafePerformIO $ withMVar index $ \idx ->
do u <- readIORef uniq
modifyIORef uniq succ
ls <- Index.insert idx k u (Nothing :: Maybe ())
let newSize | haveOldValue range ls = mapSize-1
| otherwise = mapSize
return Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=newSize}
-- | /O(log n)/. Update a value at a specific key with the result of the provided function.
-- When the key is not
-- a member of the map, the original map is returned.
--
-- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjust ("new " ++) 7 empty == empty
adjust :: (Ord k, Binary k, Binary a) => (a -> a) -> k -> Map k a -> Map k a
adjust f k m
= adjustWithKey (\_ x -> f x) k m
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
--
-- > let f key x = (show key) ++ ":new " ++ x
-- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > adjustWithKey f 7 empty == empty
adjustWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> a) -> k -> Map k a -> Map k a
adjustWithKey f k m
= updateWithKey (\k' x' -> Just (f k' x')) k m
-- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
-- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
-- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
update :: (Ord k, Binary k, Binary a) => (a -> Maybe a) -> k -> Map k a -> Map k a
update f k m
= updateWithKey (\_ x -> f x) k m
-- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
-- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
-- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
-- to the new value @y@.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
-- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
updateWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
updateWithKey f k m = snd (updateLookupWithKey f k m)
-- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
-- The function returns changed value, if it is updated.
-- Returns the original key value if the map entry is deleted.
--
-- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
-- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
-- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
-- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
updateLookupWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
updateLookupWithKey f k Empty = (Nothing,Empty)
updateLookupWithKey f k m@Existing{index=index,uniq=uniq,range=range,mapSize=mapSize}
= unsafePerformIO $ withMVar index $ \idx ->
do ls <- Index.lookupList idx k
case findValue range ls of
Nothing -> return (Nothing, m)
Just valBS -> do let val = decodeStrict valBS
newVal = f k val
mkWeak valBS index Nothing
u <- readIORef uniq
modifyIORef uniq succ
Index.insert idx k u newVal
let newSize = case isJust newVal of
False -> mapSize-1
True -> mapSize
return (newVal `mplus` Just val, Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=newSize})
-- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
-- 'alter' can be used to insert, delete, or update a value in a 'Map'.
-- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
--
-- > let f _ = Nothing
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- >
-- > let f _ = Just "c"
-- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
-- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
alter :: (Ord k, Binary k, Binary a) => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
alter f k m
= case f (lookup k m) of
Nothing -> delete k m
Just val -> insert k val m
-- | /O(log n*m)/.
-- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
-- It prefers @t1@ when duplicate keys are encountered,
-- i.e. (@'union' == 'unionWith' 'const'@).
--
-- > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]
union :: (Ord k, Binary k, Binary a) => Map k a -> Map k a -> Map k a
union = unionWith const
-- | /O(log n*m)/. Union with a combining function.
--
-- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
unionWith :: (Ord k, Binary k, Binary a) => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith f m1 m2
= unionWithKey (\_ x y -> f x y) m1 m2
-- | /O(log n*m)/.
-- Union with a combining function.
--
-- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
-- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
unionWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWithKey f t1 t2 = foldl' (\m (k,v) -> insertWithKey f k v m) t2 (toList t1)
-- | The union of a list of maps:
-- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
--
-- > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "b"), (5, "a"), (7, "C")]
-- > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
-- > == fromList [(3, "B3"), (5, "A3"), (7, "C")]
unions :: (Ord k, Binary k, Binary a) => [Map k a] -> Map k a
unions ts
= foldl' union empty ts
-- | The union of a list of maps, with a combining operation:
-- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
--
-- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
-- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
unionsWith :: (Ord k, Binary k, Binary a) => (a -> a -> a) -> [Map k a] -> Map k a
unionsWith f ts
= foldl' (unionWith f) empty ts
-- | /O(n)/. Map a function over all values in the map.
--
-- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
map :: (Ord k, Binary k, Binary a, Binary b) => (a -> b) -> Map k a -> Map k b
map f m
= mapWithKey (\_ x -> f x) m
-- | /O(n)/. Map a function over all values in the map.
--
-- > let f key x = (show key) ++ ":" ++ x
-- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
mapWithKey :: (Ord k, Binary k, Binary a, Binary b) => (k -> a -> b) -> Map k a -> Map k b
mapWithKey f m = fromDistinctAscList [ (k, f k x) | (k,x) <- toList m ]
-- | /O(n*log n)/.
-- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the value at the smallest of
-- these keys is retained.
--
-- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
-- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
-- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
mapKeys :: (Ord k2,Binary k1,Binary k2,Binary a) => (k1->k2) -> Map k1 a -> Map k2 a
mapKeys = mapKeysWith (\x _ -> x)
-- | /O(n*log n)/.
-- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
--
-- The size of the result may be smaller if @f@ maps two or more distinct
-- keys to the same new key. In this case the associated values will be
-- combined using @c@.
--
-- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
-- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
mapKeysWith :: (Ord k2, Binary k1, Binary k2, Binary a) => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
mapKeysWith c f m = fromListWith c [ (f x,y) | (x,y) <- toList m ]
-- | /O(n)/.
-- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
-- is strictly monotonic.
-- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
-- /The precondition is not checked./
-- Semi-formally, we have:
--
-- > and [x < y ==> f x < f y | x <- ls, y <- ls]
-- > ==> mapKeysMonotonic f s == mapKeys f s
-- > where ls = keys s
--
-- This means that @f@ maps distinct original keys to distinct resulting keys.
-- This function has better performance than 'mapKeys'.
--
-- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
-- > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
-- > valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == False
mapKeysMonotonic :: (Binary k1, Binary k2, Binary a) => (k1->k2) -> Map k1 a -> Map k2 a
mapKeysMonotonic f m = fromDistinctAscList [ (f x, y) | (x,y) <- toList m ]
-- | /O(n)/. Fold the values in the map, such that
-- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
-- For example,
--
-- > elems map = fold (:) [] map
--
-- > let f a len = len + (length a)
-- > fold f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
fold :: (Binary k, Binary a) => (a -> b -> b) -> b -> Map k a -> b
fold f z m
= foldWithKey (\_ x' z' -> f x' z') z m
-- | /O(n)/. Fold the keys and values in the map, such that
-- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
-- For example,
--
-- > keys map = foldWithKey (\k x ks -> k:ks) [] map
--
-- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
foldWithKey :: (Binary k, Binary a) => (k -> a -> b -> b) -> b -> Map k a -> b
foldWithKey f z = Prelude.foldr (uncurry f) z . toList
-- | /O(n)/.
-- Return all elements of the map in the ascending order of their keys.
--
-- > elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
-- > elems empty == []
elems :: (Binary k, Binary a) => Map k a -> [a]
elems = Prelude.map snd . toList
-- | /O(n)/. Return all keys of the map in ascending order.
--
-- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
-- > keys empty == []
keys :: (Binary k, Binary a) => Map k a -> [k]
keys = Prelude.map fst . toList
-- | /O(n)/. The set of all keys of the map.
--
-- > keysSet (fromList [(5,"a"), (3,"b")]) == Data.Set.fromList [3,5]
-- > keysSet empty == Data.Set.empty
keysSet :: (Ord k, Binary k, Binary a) => Map k a -> Set.Set k
keysSet m = Set.fromDistinctAscList (keys m)
-- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
--
-- > assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > assocs empty == []
assocs :: (Binary k, Binary a) => Map k a -> [(k,a)]
assocs m
= toList m
{-# SPECIALISE fromList :: (Binary a) => [(Strict.ByteString,a)] -> Map Strict.ByteString a #-}
{-# SPECIALISE fromList :: (Binary a) => [(Int,a)] -> Map Int a #-}
-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
-- If the list contains more than one value for the same key, the last value
-- for the key is retained.
--
-- > fromList [] == empty
-- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
-- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
fromList :: (Ord k, Binary k, Binary a) => [(k,a)] -> Map k a
fromList [] = Empty
fromList ls
= unsafePerformIO $
do idx <- Index.newIndex
let loop n _ | n `seq` False = undefined
loop n [] = return n
loop n ((k,v):rs) | k `seq` v `seq` True
= do keyCursor <- Index.insertKey idx k
oldData <- Index.peekKeyCursorData keyCursor
newData <- Index.newDataCursor (indexBuffer idx) 0 (Just (encode v))
Index.pushNewDataCursor keyCursor newData
loop (if oldData==nullPtr then n+1 else n) rs
size <- loop 0 ls
uniq <- newIORef 1
index <- newMVar idx
return $ Existing{index=index,uniq=uniq,range=addToRange 0 [],mapSize=size}
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
--
-- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
-- > fromListWith (++) [] == empty
fromListWith :: (Ord k, Binary k, Binary a) => (a -> a -> a) -> [(k,a)] -> Map k a
fromListWith f xs
= fromListWithKey (\_ x y -> f x y) xs
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
--
-- > let f k a1 a2 = (show k) ++ a1 ++ a2
-- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
-- > fromListWithKey f [] == empty
fromListWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromListWithKey f [] = empty
fromListWithKey f ls
= unsafePerformIO $
do idx <- Index.newIndex
let loop n _ | n `seq` False = undefined
loop n [] = return n
loop n ((k,v):rs)
= do keyCursor <- Index.insertKey idx k
oldData <- Index.getDataFromPointer keyCursor
let newVal = case oldData of
((_,Just old):_) -> f k v (decodeStrict old)
_ -> v
newData <- Index.newDataCursor (indexBuffer idx) 0 (Just (encode newVal))
Index.pushNewDataCursor keyCursor newData
loop (if Prelude.null oldData then n+1 else n) rs
size <- loop 0 ls
uniq <- newIORef 1
index <- newMVar idx
return $ Existing{index=index,uniq=uniq,range=addToRange 0 [],mapSize=size}
-- | /O(n)/. Convert to a list of key\/value pairs.
--
-- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > toList empty == []
toList :: (Binary k, Binary a) => Map k a -> [(k,a)]
toList Empty = []
toList Existing{index=index,range=range}
= unsafePerformIO $
do keys <- withMVar index $ Index.listKeyPointers
let loop [] = return [] -- withMVar index Index.touchIndex >> return []
loop (keyCursor:xs)
= unsafeInterleaveIO $
do mkWeak keyCursor index Nothing
ls <- Index.getDataFromPointer keyCursor
case findValue range ls of
Nothing -> loop xs
Just bs -> do key <- Index.getKeyFromPointer keyCursor
mkWeak bs index Nothing
mkWeak key index Nothing
let pair = (decodeStrict key, decodeStrict bs)
liftM (pair:) (loop xs)
loop (IArray.elems keys)
-- | /O(n)/. Convert to an ascending list.
--
-- > toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
toAscList :: (Binary k, Binary a) =>Map k a -> [(k,a)]
toAscList = toList
-- | /O(n)/. Build a map from an ascending list in linear time.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
-- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscList :: (Eq k, Binary k, Binary a) => [(k,a)] -> Map k a
fromAscList xs
= fromAscListWithKey (\_ x _ -> x) xs
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
-- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
-- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
fromAscListWith :: (Eq k, Binary k, Binary a) => (a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWith f xs
= fromAscListWithKey (\_ x y -> f x y) xs
-- | /O(n)/. Build a map from an ascending list in linear time with a
-- combining function for equal keys.
-- /The precondition (input list is ascending) is not checked./
--
-- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
-- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
-- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
-- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
fromAscListWithKey :: (Eq k, Binary k, Binary a) => (k -> a -> a -> a) -> [(k,a)] -> Map k a
fromAscListWithKey f xs
= fromDistinctAscList (combineEq f xs)
where
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
combineEq _ xs'
= case xs' of
[] -> []
[x] -> [x]
(x:xx) -> combineEq' x xx
combineEq' z [] = [z]
combineEq' z@(kz,zz) (x@(kx,xx):xs')
| kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs'
| otherwise = z:combineEq' x xs'
-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
-- /The precondition is not checked./
--
-- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
-- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
-- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
fromDistinctAscList :: (Binary k, Binary a) => [(k,a)] -> Map k a
fromDistinctAscList [] = Empty
fromDistinctAscList ls
= unsafePerformIO $
do idx <- Index.newIndex
n <- foldM (\s (k,v) -> do keyCursor <- Index.insertLargestKey idx k
dataCursor <- Index.newDataCursor (indexBuffer idx) 0 (Just $ encode v)
Index.pushNewDataCursor keyCursor dataCursor
return $! s+1) 0 ls
index <- newMVar idx
uniq <- newIORef 1
return Existing{index=index,uniq=uniq,range=addToRange 0 [],mapSize=n}
-- | /O(n)/. Filter all values that satisfy the predicate.
--
-- > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
-- > filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
-- > filter (< "a") (fromList [(5,"a"), (3,"b")]) == empty
filter :: (Ord k, Binary k, Binary a) => (a -> Bool) -> Map k a -> Map k a
filter p m
= filterWithKey (\_ x -> p x) m
-- FIXME: optimize this.
-- | /O(n)/. Filter all keys\/values that satisfy the predicate.
--
-- > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
filterWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> Bool) -> Map k a -> Map k a
filterWithKey p m = fromDistinctAscList [ (k, v) | (k,v) <- toList m, p k v ]
-- | /O(n)/. Partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
-- > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partition :: (Ord k, Binary k, Binary a) => (a -> Bool) -> Map k a -> (Map k a,Map k a)
partition p = partitionWithKey (\_ -> p)
-- | /O(n)/. Partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
--
-- > partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
-- > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
-- > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])
partitionWithKey :: (Ord k, Binary k, Binary a) => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
partitionWithKey p m = mapEitherWithKey (\k x -> if p k x then Left x else Right x) m
-- | /O(n)/. Map values and collect the 'Just' results.
--
-- > let f x = if x == "a" then Just "new a" else Nothing
-- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
mapMaybe :: (Ord k, Binary k, Binary a, Binary b) => (a -> Maybe b) -> Map k a -> Map k b
mapMaybe f m
= mapMaybeWithKey (\_ x -> f x) m
-- | /O(n)/. Map keys\/values and collect the 'Just' results.
--
-- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
-- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
mapMaybeWithKey :: (Ord k, Binary k, Binary a, Binary b) => (k -> a -> Maybe b) -> Map k a -> Map k b
mapMaybeWithKey f m = fromDistinctAscList [ (k, v) | (k,x) <- toList m, Just v <- [f k x] ]
-- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
--
-- > let f a = if a < "c" then Left a else Right a
-- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
-- >
-- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
mapEither :: (Ord k, Binary k, Binary a, Binary b, Binary c) => (a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEither f m
= mapEitherWithKey (\_ x -> f x) m
-- The key doesn't change. Don't re-encode it. Copy bytestring instead.
-- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
--
-- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
-- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
-- >
-- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
-- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
mapEitherWithKey :: (Ord k, Binary k, Binary a, Binary c, Binary b) =>
(k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
mapEitherWithKey f m
= unsafePerformIO $
do idxL <- Index.newIndex
idxR <- Index.newIndex
(s1,s2) <- foldM (\(s1,s2) (k,v) -> s1 `seq` s2 `seq`
do let cond = f k v
(idx,v',s1',s2') = case cond of
Left v' -> (idxL,encode v',s1+1,s2)
Right v' -> (idxR,encode v',s1,s2+1)
keyCursor <- Index.insertLargestKey idx k
dataCursor <- Index.newDataCursor (indexBuffer idx) 0 (Just v')
Index.pushNewDataCursor keyCursor dataCursor
return $! (s1',s2')) (0,0) (toList m)
indexL <- newMVar idxL
indexR <- newMVar idxR
uniqL <- newIORef 1
uniqR <- newIORef 1
return $ (Existing{index=indexL,uniq=uniqR,range=addToRange 0 [],mapSize=s1}
,Existing{index=indexR,uniq=uniqL,range=addToRange 0 [],mapSize=s2})
-- | /O(log n)/. The minimal key of the map. Calls 'error' is the map is empty.
--
-- > findMin (fromList [(5,"a"), (3,"b")]) == (3,"b")
-- > findMin empty Error: empty map has no minimal element
findMin :: (Binary k, Binary a) => Map k a -> (k,a)
findMin m = case m of
Empty -> err
Existing{index=index,range=range} ->
unsafePerformIO $ withMVar index $ \idx ->
do mbMin <- findMinKey idx range
case mbMin of
Nothing -> err
Just (keyCursor,val)
-> do key <- Index.getKeyFromPointer keyCursor
mkWeak key index Nothing
mkWeak val index Nothing
return (decodeStrict key, decodeStrict val)
where err = error "Map.findMin: empty map has no minimal element"
-- | /O(log n)/. The maximal key of the map. Calls 'error' is the map is empty.
--
-- > findMax (fromList [(5,"a"), (3,"b")]) == (5,"a")
-- > findMax empty Error: empty map has no maximal element
findMax :: (Binary k, Binary a) => Map k a -> (k,a)
findMax m = case m of
Empty -> err
Existing{index=index,range=range} ->
unsafePerformIO $ withMVar index $ \idx ->
do mbMin <- findMaxKey idx range
case mbMin of
Nothing -> err
Just (keyCursor,val)
-> do key <- Index.getKeyFromPointer keyCursor
mkWeak key index Nothing
mkWeak val index Nothing
return (decodeStrict key, decodeStrict val)
where err = error "Map.findMax: empty map has no maximal element"
-- | /O(log n)/. Delete the minimal key. Returns an empty map if the map is empty.
--
-- > deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")]
-- > deleteMin empty == empty
deleteMin :: (Binary k, Binary a) => Map k a -> Map k a
deleteMin = snd . deleteFindMin
-- | /O(log n)/. Delete and find the minimal element.
--
-- > deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")])
-- > deleteFindMin empty == (Error: can not return the minimal element of an empty map,empty)
deleteFindMin :: (Binary k, Binary a) => Map k a -> ((k,a), Map k a)
deleteFindMin m
= case m of
Empty -> (deleteFindMinErr, Empty)
Existing{index=index,uniq=uniq,range=range,mapSize=mapSize}
-> unsafePerformIO $ withMVar index $ \idx ->
do mbMin <- findMinKey idx range
case mbMin of
Nothing -> return (deleteFindMinErr, Empty)
Just (keyCursor,val)
-> do u <- readIORef uniq
modifyIORef uniq succ
dataCursor <- Index.newDataCursor (indexBuffer idx) u Nothing
Index.pushNewDataCursor keyCursor dataCursor
key <- Index.getKeyFromPointer keyCursor
mkWeak key index Nothing
mkWeak val index Nothing
return $ ((decodeStrict key,decodeStrict val),Existing{index=index,uniq=uniq,range=addToRange u range,mapSize=mapSize-1})
where deleteFindMinErr = error "Data.CompactMap.deleteFindMin: can not return the minimal element of an empty map"
findMinKey = findCornerKey Index.extractLeft Index.extractRight
findMaxKey = findCornerKey Index.extractRight Index.extractLeft
findCornerKey left right (Index orig buffer) range
= do s <- Index.getSize orig
if s == 0
then return Nothing
else do let loop ptr | ptr == nullPtr = return Nothing
loop ptr = do res <- loop =<< left ptr
case res of
Just val -> return $ Just val
Nothing -> do keyCursor <- Index.extractElemIdx ptr
ls <- Index.getDataFromPointer keyCursor
case findValue range ls of
Just val -> return $ Just (keyCursor, val)
_ -> loop =<< right ptr
loop orig
{--------------------------------------------------------------------
Utilities
--------------------------------------------------------------------}
decodeStrict bs = decode (Lazy.fromChunks [bs])
haveOldValue range ls
= isJust (findValue range ls)
withExisting Empty fn
= do idx <- newMVar =<< Index.newIndex
uniq <- newIORef 0
fn (Existing idx uniq [] 0)
withExisting m fn
= fn m
findValue range [] = Nothing
findValue range ((uniqId, value):rs)
| uniqId `isInRange` range = value
| otherwise = findValue range rs
isInRange :: Int -> [Range] -> Bool
isInRange i [] = False
isInRange i (Range x y:rs)
| i > x = False
| i < y = isInRange i rs
| otherwise = True
addToRange :: Int -> [Range] -> [Range]
addToRange i [] = [Range i i]
addToRange i (Range x y:rs)
= merge (Range i i:Range x y:rs)
merge [] = []
merge [x] = [x]
merge (Range x y:Range a b:rs)
| y == a+1 = merge (Range x b:rs)
| otherwise = Range x y:merge (Range a b:rs)
| dmjio/CompactMap | src/Data/CompactMap.hs | bsd-3-clause | 47,741 | 0 | 25 | 13,393 | 10,018 | 5,307 | 4,711 | 520 | 5 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Useful utilities for using Lucid with Yesod.
module Yesod.Lucid
(module Yesod.Lucid
,module Yesod
,module Control.Monad.Reader)
where
import Control.Monad.Identity
import Control.Monad.Reader
import Data.Text (Text)
import Lucid
import Lucid.Base
import Yesod (ToTypedContent, MonadHandler, ToContent, Route, HandlerSite,
TypedContent, HasContentType(..))
import qualified Yesod as Y
-- | Page information that the view renderer typically needs.
data Page y = Page
{ pageRender :: Route y -> Text
, pageRoute :: Maybe (Route y)
, pageCrumbs :: [(Route y, Text)]
}
-- | Output some lucid, passes a URL renderer to the continuation.
lucid :: (Y.YesodBreadcrumbs y) => HtmlT (Reader (Page y)) () -> Y.HandlerT y IO (Html ())
lucid m = do
render <- Y.getUrlRender
mroute <- Y.getCurrentRoute
(title, breadcrumbs) <- Y.breadcrumbs
return
(runReader
(do r <- runHtmlT m
return (HtmlT (Identity r)))
(Page
render
mroute
(breadcrumbs ++
[ (route, title)
| Just route <- [mroute] ])))
instance ToTypedContent (Html ()) where
toTypedContent m =
Y.TypedContent (getContentType (Just m))
(Y.toContent m)
instance ToContent (Html ()) where
toContent html =
Y.ContentBuilder (runIdentity (execHtmlT html))
Nothing
instance HasContentType (Html ()) where
getContentType _ = "text/html"
| haskell-lang/haskell-lang | src/Yesod/Lucid.hs | bsd-3-clause | 1,736 | 0 | 17 | 511 | 454 | 248 | 206 | 45 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.APPLE.VertexArrayObject
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.APPLE.VertexArrayObject (
-- * Extension Support
glGetAPPLEVertexArrayObject,
gl_APPLE_vertex_array_object,
-- * Enums
pattern GL_VERTEX_ARRAY_BINDING_APPLE,
-- * Functions
glBindVertexArrayAPPLE,
glDeleteVertexArraysAPPLE,
glGenVertexArraysAPPLE,
glIsVertexArrayAPPLE
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/APPLE/VertexArrayObject.hs | bsd-3-clause | 836 | 0 | 5 | 110 | 66 | 49 | 17 | 12 | 0 |
module System.Expect
(module System.Expect.ExpectInterface)
where
import System.Expect.ExpectInterface
| stroan/haskell-libexpect | System/Expect.hs | bsd-3-clause | 105 | 0 | 5 | 9 | 21 | 14 | 7 | 3 | 0 |
{-|
Module : MZBuiltIns
Description : MiniZinc built-in predicates, tests and functions
License : BSD3
Maintainer : Klara Marntirosian <[email protected]>
Stability : experimental
This module uses definitions of "Interfaces.MZAST" to provide an easy interface to
MiniZinc built-in calls. It might be missing built-in calls that have been added
in recent releases of MiniZinc.
-}
module Interfaces.MZBuiltIns (
opPrec,
-- * MiniZinc built-in operators
-- ** Comparison operators
(!=.), (>.), (>=.), (=.=), (<.), (<=.),
-- ** Arithmetic operators
(*.), (+.), plus_, (-.), minus_, (/.), _div_, _mod_,
-- ** Logical operators
not_, (->.), (/\.), (<-.), (<->.), (\/.), _xor_,
-- ** Set operators
(...), _diff_, _in_, _intersect_, _subset_, _superset_, _symdiff_, _union_,
-- ** Array operators
(++.),
-- * MiniZinc built-in calls
-- | All functions, predicates, tests and annotations are named after their MiniZinc
-- name prefixed by @mz_@. Operators' representation follows a different convention.
-- ** Arithmetic calls
mz_abs, mz_arg_max, mz_arg_min, mz_max, mz_min, mz_pow, mz_product, mz_sqrt, mz_sum,
-- ** Exponential and logarithmic calls
mz_exp, mz_ln, mz_log, mz_log10, mz_log2,
-- ** Trigonometric calls
mz_acos, mz_acosh, mz_asin, mz_asinh, mz_atan, mz_atanh, mz_cos, mz_cosh, mz_sin, mz_sinh, mz_tan,
mz_tanh,
-- ** Logical calls
mz_clause, mz_exists, mz_forall, mz_iffall, mz_xorall,
-- ** Set calls
mz_card, mz_array_intersect, mz_array_union,
-- ** Array calls
mz_array1d, mz_array2d, mz_array3d, mz_array4d, mz_array5d, mz_array6d, mz_arrayXd,
mz_col, mz_has_element, mz_has_index, mz_index_set, mz_index_set_1of2, mz_index_set_1of3,
mz_index_set_1of4, mz_index_set_1of5, mz_index_set_1of6, mz_index_set_2of2, mz_index_set_2of3,
mz_index_set_2of4, mz_index_set_2of5, mz_index_set_2of6, mz_index_set_3of3, mz_index_set_3of4,
mz_index_set_3of5, mz_index_set_3of6, mz_index_set_4of4, mz_index_set_4of5, mz_index_set_4of6,
mz_index_set_5of5, mz_index_set_5of6, mz_index_set_6of6, mz_index_sets_agree, mz_length,
mz_reverse, mz_row,
-- ** Array sorting calls
mz_arg_sort, mz_sort, mz_sort_by,
-- ** Coercion calls
mz_bool2float, mz_bool2int, mz_ceil, mz_floor, mz_int2float, mz_round, mz_set2array,
-- ** String calls
mz_concat, mz_file_path, mz_format, mz_join, mz_show, mz_show2d, mz_show3d, mz_showJSON,
mz_show_float, mz_show_int, mz_strig_length,
-- ** Reflection calls
mz_dom, mz_dom_array, mz_dom_bounds_array, mz_dom_size, mz_fix, mz_has_bounds, mz_has_ub_set,
mz_is_fixed, mz_lb, mz_lb_array, mz_ub, mz_ub_array,
-- ** Assertions and debugging calls
mz_abort, mz_assert, mz_trace, mz_trace_stdout,
-- ** Calls for @Enum@s
mz_enum_next, mz_enum_prev, mz_to_enum,
-- ** Calls for @Optional@s
mz_absent, mz_deopt, mz_occurs,
-- ** Random number generator calls
mz_bernoulli, mz_binomial, mz_cauchy, mz_chisquared, mz_discrete_distribution, mz_exponential,
mz_fdistribution, mz_gamma, mz_lognormal, mz_normal, mz_poisson, mz_tdistribution, mz_uniform,
mz_weibull,
-- ** Special constraints
mz_implied_constraint, mz_redundant_constraint, mz_symmetry_breaking_constraint,
-- ** Language information
mz_mzn_compiler_version, mz_mzn_version_to_string,
-- * MiniZinc global constraints
mz_all_different,
-- * MiniZinc annotations
-- ** General annotations
mz_add_to_output, mz_is_defined_var, mz_is_reverse_map, mz_maybe_partial, mz_output_var,
mz_promise_total, mz_var_is_introduced, mz_defines_var, mz_doc_comment, mz_output_array,
-- ** Propagation strength annotations
mz_bounds, mz_domain,
-- ** Search annotations
mz_bool_search, mz_float_search, mz_int_search, mz_seq_search, mz_set_search,
-- *** Variable selection annotations
mz_anti_first_fail, mz_dom_w_deg, mz_first_fail, mz_impact, mz_input_order, mz_largest,
mz_max_regret, mz_most_constrained, mz_occurrence, mz_smallest,
-- *** Value choice annotations
mz_indomain, mz_indomain_interval, mz_indomain_max, mz_indomain_median, mz_indomain_middle,
mz_indomain_min, mz_indomain_random, mz_indomain_reverse_split, mz_indomain_split,
mz_indomain_split_random, mz_outdomain_max, mz_outdomain_median, mz_outdomain_min,
mz_outdomain_random,
-- *** Exploration strategy annotations
mz_complete
) where
import Interfaces.MZAST (Expr(Bi, U), Op, infOp, prefCall, Annotation(Annotation))
-- MiniZinc calls
-- Arithmetic calls
mz_abs = prefCall "abs"
mz_arg_max = prefCall "arg_max"
mz_arg_min = prefCall "arg_min"
mz_max = prefCall "max"
mz_min = prefCall "min"
mz_pow = prefCall "pow"
mz_product = prefCall "product"
mz_sqrt = prefCall "sqrt"
mz_sum = prefCall "sum"
-- Exponential and logarithmic calls
mz_exp = prefCall "exp"
mz_ln = prefCall "ln"
mz_log = prefCall "log"
mz_log10 = prefCall "log10"
mz_log2 = prefCall "log2"
-- Trigonometric calls
mz_acos = prefCall "acos"
mz_acosh = prefCall "acosh"
mz_asin = prefCall "asin"
mz_asinh = prefCall "asinh"
mz_atan = prefCall "atan"
mz_atanh = prefCall "atanh"
mz_cos = prefCall "cos"
mz_cosh = prefCall "cosh"
mz_sin = prefCall "sin"
mz_sinh = prefCall "sinh"
mz_tan = prefCall "tan"
mz_tanh = prefCall "tanh"
-- Logical calls
mz_clause = prefCall "clause"
mz_exists = prefCall "exists"
mz_forall = prefCall "forall"
mz_iffall = prefCall "iffall"
mz_xorall = prefCall "xorall"
-- Set calls
mz_array_intersect = prefCall "array_intersect"
mz_array_union = prefCall "array_union"
mz_card = prefCall "card"
-- Array calls
mz_array1d = prefCall "array1d"
mz_array2d = prefCall "array2d"
mz_array3d = prefCall "array3d"
mz_array4d = prefCall "array4d"
mz_array5d = prefCall "array5d"
mz_array6d = prefCall "array6d"
mz_arrayXd = prefCall "arrayXd"
mz_col = prefCall "col"
mz_has_element = prefCall "has_element"
mz_has_index = prefCall "has_index"
mz_index_set = prefCall "index_set"
mz_index_set_1of2 = prefCall "index_set_1of2"
mz_index_set_1of3 = prefCall "index_set_1of3"
mz_index_set_1of4 = prefCall "index_set_1of4"
mz_index_set_1of5 = prefCall "index_set_1of5"
mz_index_set_1of6 = prefCall "index_set_1of6"
mz_index_set_2of2 = prefCall "index_set_2of2"
mz_index_set_2of3 = prefCall "index_set_2of3"
mz_index_set_2of4 = prefCall "index_set_2of4"
mz_index_set_2of5 = prefCall "index_set_2of5"
mz_index_set_2of6 = prefCall "index_set_2of6"
mz_index_set_3of3 = prefCall "index_set_3of3"
mz_index_set_3of4 = prefCall "index_set_3of4"
mz_index_set_3of5 = prefCall "index_set_3of5"
mz_index_set_3of6 = prefCall "index_set_3of6"
mz_index_set_4of4 = prefCall "index_set_4of4"
mz_index_set_4of5 = prefCall "index_set_4of5"
mz_index_set_4of6 = prefCall "index_set_4of6"
mz_index_set_5of5 = prefCall "index_set_5of5"
mz_index_set_5of6 = prefCall "index_set_5of6"
mz_index_set_6of6 = prefCall "index_set_6of6"
mz_index_sets_agree = prefCall "index_sets_agree"
mz_length = prefCall "length"
mz_reverse = prefCall "reverse"
mz_row = prefCall "row"
-- Array sorting calls
mz_arg_sort = prefCall "arg_sort"
mz_sort = prefCall "sort"
mz_sort_by = prefCall "sort_by"
-- Coercion calls
mz_bool2float = prefCall "bool2float"
mz_bool2int = prefCall "bool2int"
mz_ceil = prefCall "ceil"
mz_floor = prefCall "floor"
mz_int2float = prefCall "int2float"
mz_round = prefCall "round"
mz_set2array = prefCall "set2array"
-- String calls
mz_concat = prefCall "concat"
mz_file_path = prefCall "file_path"
mz_format = prefCall "format"
mz_join = prefCall "join"
mz_show = prefCall "show"
mz_show2d = prefCall "show2d"
mz_show3d = prefCall "show3d"
mz_showJSON = prefCall "showJSON"
mz_show_float = prefCall "show_float"
mz_show_int = prefCall "show_int"
mz_strig_length = prefCall "string_length"
-- Reflection calls
mz_dom = prefCall "dom"
mz_dom_array = prefCall "dom_array"
mz_dom_bounds_array = prefCall "dom_bounds_array"
mz_dom_size = prefCall "dom_size"
mz_fix = prefCall "fix"
mz_has_bounds = prefCall "has_bounds"
mz_has_ub_set = prefCall "has_ub_set"
mz_is_fixed = prefCall "is_fixed"
mz_lb = prefCall "lb"
mz_lb_array = prefCall "lb_array"
mz_ub = prefCall "ub"
mz_ub_array = prefCall "ub_array"
-- Assertions and debugging calls
mz_abort = prefCall "abort"
mz_assert = prefCall "assert"
mz_trace = prefCall "trace"
mz_trace_stdout = prefCall "trace_stdout"
-- Calls for @Enum@s
mz_enum_next = prefCall "enum_next"
mz_enum_prev = prefCall "enum_prev"
mz_to_enum = prefCall "to_enum"
-- Calls for Optionals
-- Random number generator calls
mz_bernoulli = prefCall "bernoulli"
mz_binomial = prefCall "binomial"
mz_cauchy = prefCall "cauchy"
mz_chisquared = prefCall "chisquared"
mz_discrete_distribution = prefCall "discrete_distribution"
mz_exponential = prefCall "exponential"
mz_fdistribution = prefCall "fdistribution"
mz_gamma = prefCall "gamma"
mz_lognormal = prefCall "lognormal"
mz_normal = prefCall "normal"
mz_poisson = prefCall "poisson"
mz_tdistribution = prefCall "tdistribution"
mz_uniform = prefCall "uniform"
mz_weibull = prefCall "weibull"
-- Special constraints
mz_implied_constraint = prefCall "implied_constraint"
mz_redundant_constraint = prefCall "redundant_constraint"
mz_symmetry_breaking_constraint = prefCall "symmetry_breaking_constraint"
-- Language information
mz_mzn_compiler_version = prefCall "mzn_compiler_version"
mz_mzn_version_to_string = prefCall "mzn_version_to_string"
-- MiniZinc operators
infixl 3 /\., <->., <-., ->., \/., `_xor_`
infix 4 <., <=., >., >=., =.=, !=.
infix 5 `_in_`, `_subset_`, `_superset_`
infixl 6 `_union_`, `_diff_`, `_symdiff_`, ...
infixl 7 +., -.
infixl 8 *., /., `_div_`, `_mod_`, `_intersect_`, ++.
mz_absent = prefCall "absent"
mz_deopt = prefCall "deopt"
mz_occurs = prefCall "occurs"
mz_regular = prefCall "regular"
-- Comparison operators
mz_neq = infOp "!="
mz_lt = infOp "<"
mz_lte = infOp "<="
mz_eq = infOp "="
mz_gt = infOp ">"
mz_gte = infOp ">="
-- | @!=@
(!=.) = Bi mz_neq
-- | @<@
(<.) = Bi mz_lt
-- | @<=@
(<=.) = Bi mz_lte
-- | @=@
(=.=) = Bi mz_eq
-- | @>@
(>.) = Bi mz_gt
-- | @>=@
(>=.) = Bi mz_gte
-- Arithmetic operators
mz_times = infOp "*"
mz_plus = infOp "+"
mz_minus = infOp "-"
mz_div = infOp "/"
mz_idiv = infOp "div"
mz_mod = infOp "mod"
-- | @*@
(*.) = Bi mz_times
-- | @+@ (the binary operator)
(+.) = Bi mz_plus
-- | @+@ (the unary operator)
plus_ = U mz_plus
-- | @-@ (the binary operator)
(-.) = Bi mz_minus
-- | @-@ (the unary operator)
minus_ = U mz_minus
-- | @/@
(/.) = Bi mz_div
-- | @div@
_div_ = Bi mz_idiv
-- | @mod@
_mod_ = Bi mz_mod
-- Logical operators
mz_rarrow = infOp "->"
mz_and = infOp "/\\"
mz_larrow = infOp "<-"
mz_lrarrow = infOp "<->"
mz_not = infOp "not"
mz_or = infOp "\\/"
mz_xor = infOp "xor"
-- | @->@
(->.) = Bi mz_rarrow
-- | @\/\\@
(/\.) = Bi mz_and
-- | @<-@
(<-.) = Bi mz_larrow
-- | @<->@
(<->.) = Bi mz_lrarrow
-- | @not@
not_ = U mz_not
-- | @\\\/@
(\/.) = Bi mz_or
-- | @xor@
_xor_ = Bi mz_xor
-- Set operators
mz_range = infOp ".."
mz_diff = infOp "diff"
mz_in = infOp "in"
mz_intersect = infOp "intersect"
mz_subset = infOp "subset"
mz_superset = infOp "superset"
mz_symdiff = infOp "symdiff"
mz_union = infOp "union"
-- | @..@
(...) = Bi mz_range
-- | @diff@
_diff_ = Bi mz_diff
-- | @in@
_in_ = Bi mz_in
-- | @intersect@
_intersect_ = Bi mz_intersect
-- | @subset@
_subset_ = Bi mz_subset
-- | @superset@
_superset_ = Bi mz_superset
-- | @symdiff@
_symdiff_ = Bi mz_symdiff
-- | @union@
_union_ = Bi mz_union
-- Array operators
mz_pp = infOp "++"
-- | @++@
(++.) = Bi mz_pp
-- | Returns the precedence of certain defined operators. This function is used for
-- reducing the parentheses when printing an expression.
opPrec :: Op -> Int
opPrec op
| op == mz_pp = 1
| op == mz_times = 2
| op == mz_div = 2
| op == mz_mod = 2
| op == mz_idiv = 2
| op == mz_intersect = 2
| op == mz_plus = 3
| op == mz_minus = 3
| op == mz_range = 4
| op == mz_union = 5
| op == mz_diff = 5
| op == mz_symdiff = 5
| op == mz_in = 6
| op == mz_subset = 6
| op == mz_superset = 6
| op == mz_neq = 7
| op == mz_lt = 7
| op == mz_lte = 7
| op == mz_eq = 7
| op == mz_gt = 7
| op == mz_gte = 7
| op == mz_and = 8
| op == mz_or = 9
| op == mz_xor = 9
| op == mz_rarrow = 10
| op == mz_larrow = 10
| op == mz_lrarrow = 11
| otherwise = 15
-- MiniZinf global constraints
mz_all_different = prefCall "all_different"
-- MiniZinc annotations
-- General annotations
mz_add_to_output = Annotation "add_to_output"
mz_is_defined_var = Annotation "is_defined_var"
mz_is_reverse_map = Annotation "is_reverse_map"
mz_maybe_partial = Annotation "maybe_partial"
mz_output_var = Annotation "output_var"
mz_promise_total = Annotation "promise_total"
mz_var_is_introduced = Annotation "var_is_introduced"
mz_defines_var = Annotation "defines_var"
mz_doc_comment = Annotation "doc_comment"
mz_output_array = Annotation "output_array"
-- Propagation strength annotations
mz_bounds = Annotation "bounds"
mz_domain = Annotation "domain"
-- Search annotations
mz_bool_search = Annotation "bool_search"
mz_float_search = Annotation "float_search"
mz_int_search = Annotation "int_search"
mz_seq_search = Annotation "seq_search"
mz_set_search = Annotation "set_search"
-- Variable selection annotations
mz_anti_first_fail = Annotation "anti_first_fail"
mz_dom_w_deg = Annotation "dom_w_deg"
mz_first_fail = Annotation "first_fail"
mz_impact = Annotation "impact"
mz_input_order = Annotation "input_order"
mz_largest = Annotation "largest"
mz_max_regret = Annotation "max_regret"
mz_most_constrained = Annotation "most_constrained"
mz_occurrence = Annotation "occurrence"
mz_smallest = Annotation "smallest"
-- Value choice annotations
mz_indomain = Annotation "indomain"
mz_indomain_interval = Annotation "indomain_interval"
mz_indomain_max = Annotation "indomain_max"
mz_indomain_median = Annotation "indomain_median"
mz_indomain_middle = Annotation "indomain_middle"
mz_indomain_min = Annotation "indomain_min"
mz_indomain_random = Annotation "indomain_random"
mz_indomain_reverse_split = Annotation "indomain_reverse_split"
mz_indomain_split = Annotation "indomain_split"
mz_indomain_split_random = Annotation "indomain_split_random"
mz_outdomain_max = Annotation "outdomain_max"
mz_outdomain_median = Annotation "outdomain_median"
mz_outdomain_min = Annotation "outdomain_min"
mz_outdomain_random = Annotation "outdomain_random"
-- Exploration strategy annotations
mz_complete = Annotation "complete"
| GRACeFUL-project/haskelzinc | src/Interfaces/MZBuiltIns.hs | bsd-3-clause | 15,238 | 0 | 8 | 2,955 | 3,171 | 1,787 | 1,384 | 316 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
-- Create a source distribution tarball
module Stack.SDist
( getSDistTarball
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Codec.Compression.GZip as GZip
import Control.Applicative
import Control.Concurrent.Execute (ActionContext(..))
import Control.Monad (when, void)
import Control.Monad.Catch (MonadMask)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, asks)
import Control.Monad.Trans.Control (liftBaseWith)
import Control.Monad.Trans.Resource
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Data (Data, Typeable, cast, gmapT)
import Data.Either (partitionEithers)
import Data.List
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TLE
import Distribution.Package (Dependency (..))
import Distribution.PackageDescription.PrettyPrint (showGenericPackageDescription)
import Distribution.Version (simplifyVersionRange, orLaterVersion, earlierVersion)
import Distribution.Version.Extra
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.IO
import Prelude -- Fix redundant import warnings
import Stack.Build (mkBaseConfigOpts)
import Stack.Build.Execute
import Stack.Build.Installed
import Stack.Build.Source (loadSourceMap, localFlags)
import Stack.Build.Target
import Stack.Constants
import Stack.Package
import Stack.Types
import Stack.Types.Internal
import qualified System.FilePath as FP
type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env)
-- | Given the path to a local package, creates its source
-- distribution tarball.
--
-- While this yields a 'FilePath', the name of the tarball, this
-- tarball is not written to the disk and instead yielded as a lazy
-- bytestring.
getSDistTarball :: M env m
=> Maybe PvpBounds -- ^ override Config value
-> Path Abs Dir
-> m (FilePath, L.ByteString)
getSDistTarball mpvpBounds pkgDir = do
config <- asks getConfig
let pvpBounds = fromMaybe (configPvpBounds config) mpvpBounds
tweakCabal = pvpBounds /= PvpBoundsNone
pkgFp = toFilePath pkgDir
lp <- readLocalPackage pkgDir
$logInfo $ "Getting file list for " <> T.pack pkgFp
(fileList, cabalfp) <- getSDistFileList lp
$logInfo $ "Building sdist tarball for " <> T.pack pkgFp
files <- normalizeTarballPaths (lines fileList)
-- NOTE: Could make this use lazy I/O to only read files as needed
-- for upload (both GZip.compress and Tar.write are lazy).
-- However, it seems less error prone and more predictable to read
-- everything in at once, so that's what we're doing for now:
let tarPath isDir fp = either error id
(Tar.toTarPath isDir (pkgId FP.</> fp))
packWith f isDir fp =
liftIO $ f (pkgFp FP.</> fp)
(tarPath isDir fp)
packDir = packWith Tar.packDirectoryEntry True
packFile fp
| tweakCabal && isCabalFp fp = do
lbs <- getCabalLbs pvpBounds $ toFilePath cabalfp
return $ Tar.fileEntry (tarPath False fp) lbs
| otherwise = packWith Tar.packFileEntry False fp
isCabalFp fp = toFilePath pkgDir FP.</> fp == toFilePath cabalfp
tarName = pkgId FP.<.> "tar.gz"
pkgId = packageIdentifierString (packageIdentifier (lpPackage lp))
dirEntries <- mapM packDir (dirsFromFiles files)
fileEntries <- mapM packFile files
return (tarName, GZip.compress (Tar.write (dirEntries ++ fileEntries)))
-- | Get the PVP bounds-enabled version of the given cabal file
getCabalLbs :: M env m => PvpBounds -> FilePath -> m L.ByteString
getCabalLbs pvpBounds fp = do
bs <- liftIO $ S.readFile fp
(_warnings, gpd) <- readPackageUnresolvedBS Nothing bs
(_, _, _, _, sourceMap) <- loadSourceMap AllowNoTargets defaultBuildOpts
menv <- getMinimalEnvOverride
(installedMap, _, _) <- getInstalled menv GetInstalledOpts
{ getInstalledProfiling = False
, getInstalledHaddock = False
}
sourceMap
let gpd' = gtraverseT (addBounds sourceMap installedMap) gpd
return $ TLE.encodeUtf8 $ TL.pack $ showGenericPackageDescription gpd'
where
addBounds :: SourceMap -> InstalledMap -> Dependency -> Dependency
addBounds sourceMap installedMap dep@(Dependency cname range) =
case lookupVersion (fromCabalPackageName cname) of
Nothing -> dep
Just version -> Dependency cname $ simplifyVersionRange
$ (if toAddUpper && not (hasUpper range) then addUpper version else id)
$ (if toAddLower && not (hasLower range) then addLower version else id)
range
where
lookupVersion name =
case Map.lookup name sourceMap of
Just (PSLocal lp) -> Just $ packageVersion $ lpPackage lp
Just (PSUpstream version _ _) -> Just version
Nothing ->
case Map.lookup name installedMap of
Just (version, _, _) -> Just version
Nothing -> Nothing
addUpper version = intersectVersionRanges
(earlierVersion $ toCabalVersion $ nextMajorVersion version)
addLower version = intersectVersionRanges
(orLaterVersion (toCabalVersion version))
(toAddLower, toAddUpper) =
case pvpBounds of
PvpBoundsNone -> (False, False)
PvpBoundsUpper -> (False, True)
PvpBoundsLower -> (True, False)
PvpBoundsBoth -> (True, True)
-- | Traverse a data type.
gtraverseT :: (Data a,Typeable b) => (Typeable b => b -> b) -> a -> a
gtraverseT f =
gmapT (\x -> case cast x of
Nothing -> gtraverseT f x
Just b -> fromMaybe x (cast (f b)))
-- Read in a 'LocalPackage' config. This makes some default decisions
-- about 'LocalPackage' fields that might not be appropriate for other
-- usecases.
--
-- TODO: Dedupe with similar code in "Stack.Build.Source".
readLocalPackage :: M env m => Path Abs Dir -> m LocalPackage
readLocalPackage pkgDir = do
econfig <- asks getEnvConfig
bconfig <- asks getBuildConfig
cabalfp <- getCabalFileName pkgDir
name <- parsePackageNameFromFilePath cabalfp
let config = PackageConfig
{ packageConfigEnableTests = False
, packageConfigEnableBenchmarks = False
, packageConfigFlags = localFlags Map.empty bconfig name
, packageConfigCompilerVersion = envConfigCompilerVersion econfig
, packageConfigPlatform = configPlatform $ getConfig bconfig
}
(warnings,package) <- readPackage config cabalfp
mapM_ (printCabalFileWarning cabalfp) warnings
return LocalPackage
{ lpPackage = package
, lpExeComponents = Nothing -- HACK: makes it so that sdist output goes to a log instead of a file.
, lpDir = pkgDir
, lpCabalFile = cabalfp
-- NOTE: these aren't the 'correct values, but aren't used in
-- the usage of this function in this module.
, lpTestDeps = Map.empty
, lpBenchDeps = Map.empty
, lpTestBench = Nothing
, lpDirtyFiles = Just Set.empty
, lpNewBuildCache = Map.empty
, lpFiles = Set.empty
, lpComponents = Set.empty
}
-- | Returns a newline-separate list of paths, and the absolute path to the .cabal file.
getSDistFileList :: M env m => LocalPackage -> m (String, Path Abs File)
getSDistFileList lp =
withCanonicalizedSystemTempDirectory (stackProgName <> "-sdist") $ \tmpdir -> do
menv <- getMinimalEnvOverride
let bopts = defaultBuildOpts
baseConfigOpts <- mkBaseConfigOpts bopts
(_, _mbp, locals, _extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts
runInBase <- liftBaseWith $ \run -> return (void . run)
withExecuteEnv menv bopts baseConfigOpts locals
[] -- provide empty list of globals. This is a hack around custom Setup.hs files
sourceMap $ \ee -> do
withSingleContext runInBase ac ee task Nothing (Just "sdist") $ \_package cabalfp _pkgDir cabal _announce _console _mlogFile -> do
let outFile = toFilePath tmpdir FP.</> "source-files-list"
cabal False ["sdist", "--list-sources", outFile]
contents <- liftIO (readFile outFile)
return (contents, cabalfp)
where
package = lpPackage lp
ac = ActionContext Set.empty
task = Task
{ taskProvides = PackageIdentifier (packageName package) (packageVersion package)
, taskType = TTLocal lp
, taskConfigOpts = TaskConfigOpts
{ tcoMissing = Set.empty
, tcoOpts = \_ -> ConfigureOpts [] []
}
, taskPresent = Map.empty
}
normalizeTarballPaths :: M env m => [FilePath] -> m [FilePath]
normalizeTarballPaths fps = do
--TODO: consider whether erroring out is better - otherwise the
--user might upload an incomplete tar?
when (not (null outsideDir)) $
$logWarn $ T.concat
[ "Warning: These files are outside of the package directory, and will be omitted from the tarball: "
, T.pack (show outsideDir)]
return files
where
(outsideDir, files) = partitionEithers (map pathToEither fps)
pathToEither fp = maybe (Left fp) Right (normalizePath fp)
normalizePath :: FilePath -> (Maybe FilePath)
normalizePath = fmap FP.joinPath . go . FP.splitDirectories . FP.normalise
where
go [] = Just []
go ("..":_) = Nothing
go (_:"..":xs) = go xs
go (x:xs) = (x :) <$> go xs
dirsFromFiles :: [FilePath] -> [FilePath]
dirsFromFiles dirs = Set.toAscList (Set.delete "." results)
where
results = foldl' (\s -> go s . FP.takeDirectory) Set.empty dirs
go s x
| Set.member x s = s
| otherwise = go (Set.insert x s) (FP.takeDirectory x)
| meiersi-11ce/stack | src/Stack/SDist.hs | bsd-3-clause | 10,829 | 0 | 21 | 2,925 | 2,621 | 1,390 | 1,231 | 197 | 10 |
-- http://adventofcode.com/2016/day/13
import Numeric
import Data.Char
import Control.Monad.Writer.Lazy
import Control.Monad.Trans.List
type Position = (Int, Int)
type Stack = ListT (Writer (Sum Int)) Position
seed :: Int
-- seed = 1350
seed = 10
main :: IO ()
main = do
print partOne
partOne :: Stack
partOne = until (\x -> (7, 4) `elem` positions x) (>>= move) init
where
init = return (1, 1)
positions = fst . runWriter . runListT
moves = getSum . execWriter . runListT
move :: Position -> Stack
move (x, y) = do
lift . tell $ (Sum 1)
ListT . return . filter (isOpen) $ [(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]
isOpen :: Position -> Bool
isOpen (x,y)
| x < 0 || y < 0 = False
| otherwise = even . length . filter (=='1') . binary $ go
where
go = (x*x + 3*x + 2*x*y + y + y*y) + seed
binary x = showIntAtBase 2 intToDigit x ""
| MaxwellBo/Advent_Of_Code_2016 | ListT_Diversion.hs | bsd-3-clause | 881 | 0 | 17 | 213 | 430 | 236 | 194 | 26 | 1 |
{-|
Module : MZAuxiliary
Description : Contains auxiliary definitions
License : BSD3
Maintainer : Klara Marntirosian <[email protected]>
Stability : experimental
This module handles the configuration needed to run constraint models.
-}
module Interfaces.MZAuxiliary(
Configuration(..),
parseConfig,
spaceFix
) where
import System.Process
import System.FilePath
import Text.Parsec.String (Parser)
import qualified Text.Parsec as P
import qualified Text.Parsec.Char as C
import qualified Text.Parsec.Combinator as C1
-- | A record containing the required paths for the constraint models to be run by
-- the solvers.
data Configuration
= Config { minizinc :: FilePath -- ^ Path to the directory of @mzn2fzn@ and
-- @flatzinc@ executables
, chocosolver :: FilePath -- ^ Path to the choco_solver java library
, chocoparser :: FilePath -- ^ Path to the choco_parser java library
, antlr_path :: FilePath -- ^ Path to the antlr java library
}
deriving Show
instance Monoid Configuration where
mempty = Config { minizinc = ""
, chocosolver = ""
, chocoparser = ""
, antlr_path = ""
}
mappend a b =
Config { minizinc = dropEmpty (minizinc a) (minizinc b)
, chocosolver = dropEmpty (chocosolver a) (chocosolver b)
, chocoparser = dropEmpty (chocoparser a) (chocoparser b)
, antlr_path = dropEmpty (antlr_path a) (antlr_path b)
}
dropEmpty :: String -> String -> String
dropEmpty "" "" = ""
dropEmpty a "" = a
dropEmpty "" b = b
makeConf :: Either (P.ParseError) (String, String) -> Configuration
makeConf (Right (name, path))
| name == conf_mz = Config { minizinc = path
, chocosolver = ""
, chocoparser = ""
, antlr_path = ""
}
| name == conf_cs = Config { minizinc = ""
, chocosolver = path
, chocoparser = ""
, antlr_path = ""
}
| name == conf_cp = Config { minizinc = ""
, chocosolver = ""
, chocoparser = path
, antlr_path = ""
}
| name == conf_an = Config { minizinc = ""
, chocosolver = ""
, chocoparser = ""
, antlr_path = path
}
makeConf (Right (_,_)) = mempty
makeConf (Left err) = mempty
-- Definitions
choco = "CHOCO_"
conf_mz = "MINIZINC_DIR"
conf_cs = "SOLVER"
conf_cp = "PARSER"
conf_an = "ANTLR"
parser_choco = string choco
parser_mz = string conf_mz
parser_cs = parser_choco >> string "SOLVER"
parser_cp = parser_choco >> string "PARSER"
parser_an = string conf_an
emptyConf = Config { minizinc = ""
, chocosolver = ""
, chocoparser = ""
, antlr_path = ""
}
confFile = joinPath ["HZconf", "conf.txt"]
-- | Parses the configuration file.
parseConfig = do
contents <- readFile confFile
return $ configure (lines contents)
parserLine :: Parser (String, String)
parserLine = do
left <- try parser_mz <|> (try parser_cs <|> parser_cp) <|> parser_an
C.spaces
char '='
C.spaces
right <- parserr
return (left,right)
parserr :: Parser String
parserr = manyTill anyChar eof
configure ls = mconcat (map (makeConf . (runParser parserLine)) ls)
-- | Wraps a path in quotes if it contains spaces.
spaceFix :: String -> String
spaceFix str = if elem ' ' str
then "\"" ++ str ++ "\""
else str
runParser :: Parser a -> String -> Either P.ParseError a
runParser p = P.parse (p <* eof) ""
parseWithLeftOver :: Parser a -> String -> Either P.ParseError (a,String)
parseWithLeftOver p = P.parse ((,) <$> p <*> leftOver) ""
where leftOver = manyTill anyToken eof
-- Needed definitions
manyTill = C1.manyTill
try = P.try
anyToken = C1.anyToken
anyChar :: Parser Char
anyChar = C.anyChar
endOfLine :: Parser Char
endOfLine = C.endOfLine
char = C.char
eof = C1.eof
(<|>) = (P.<|>)
string :: String -> Parser String
string = C.string | GRACeFUL-project/haskelzinc | src/Interfaces/MZAuxiliary.hs | bsd-3-clause | 4,422 | 0 | 12 | 1,487 | 1,063 | 592 | 471 | 100 | 2 |
module Matrix where
import Control.Applicative
import Data.Serialize (Serialize)
import Data.Vector.Unboxed (Unbox)
import qualified Data.Vector.Unboxed as V
import qualified Data.Matrix.Unboxed as M
import qualified Data.Serialize as Serialize
newtype Matrix a = Matrix { unMatrix :: M.Matrix a }
deriving (Show, Eq, Num)
instance (Unbox a, Serialize a) => Serialize (Matrix a) where
put = Serialize.put . M.toLists . unMatrix
get = Matrix . M.fromLists <$> Serialize.get
onMatrix :: Unbox a => (M.Matrix a -> M.Matrix a) -> Matrix a -> Matrix a
onMatrix f = Matrix . f . unMatrix
identity :: (Unbox a, Num a) => Int -> Matrix a
identity = Matrix . M.identity
prettyMatrix :: (Unbox a, Show a) => Matrix a -> String
prettyMatrix = M.prettyMatrix . unMatrix
transpose :: Unbox a => Matrix a -> Matrix a
transpose = onMatrix M.transpose
scaleMatrix :: (Unbox a, Num a) => a -> Matrix a -> Matrix a
scaleMatrix s = onMatrix (M.scaleMatrix s)
get :: Unbox a => Int -> Int -> Matrix a -> Maybe a
get i j m = M.safeGet i j $ unMatrix m
matrix :: Unbox a => Int -> Int -> (Int -> Int -> a) -> Matrix a
matrix i j f = Matrix $ M.matrix i j (uncurry f)
diagonal :: Unbox a => Matrix a -> V.Vector a
diagonal = M.getDiag . unMatrix
columns :: Unbox a => Matrix a -> Int
columns = M.ncols . unMatrix
rows :: Unbox a => Matrix a -> Int
rows = M.nrows . unMatrix
map :: (Unbox a, Unbox b) => (a -> b) -> Matrix a -> Matrix b
map f m = Matrix $ M.map f $ unMatrix m
toList :: Unbox a => Matrix a -> [a]
toList = M.toList . unMatrix
(!) :: Unbox a => Matrix a -> (Int, Int) -> a
(!) = (M.!) . unMatrix
submatrix :: Unbox a => Int -> Int -> Int -> Int -> Matrix a -> Matrix a
submatrix r1 r2 c1 c2 = Matrix . M.submatrix r1 r2 c1 c2 . unMatrix
(<|>) :: Unbox a => Matrix a -> Matrix a -> Matrix a
m1 <|> m2 = Matrix $ unMatrix m1 M.<|> unMatrix m2
(<->) :: Unbox a => Matrix a -> Matrix a -> Matrix a
m1 <-> m2 = Matrix $ unMatrix m1 M.<-> unMatrix m2
| intolerable/mpi | src/Matrix.hs | bsd-3-clause | 1,962 | 0 | 11 | 416 | 926 | 473 | 453 | 44 | 1 |
module Control.Distributed.Process.Global
(
-- * Cluster operations
addNode
, ResolutionMethod(..)
, ResolutionNotification(..)
, globalWhereis
, globalRegister
, globalUnregister
, globalReregister
-- * Locks
, GlobalNameServer
, LockName
, LockRequesterId
, LockId
, queryLock
, setLockKnown
, setLock
, setLockOpt
, delLock
, transKnown
, getKnown
, getKnownNameServers
-- * Remote call table
, __remoteTable
) where
import Control.Distributed.Process
import Control.Distributed.Process.Global.Types
import Control.Distributed.Process.Global.Server hiding (__remoteTable)
import qualified Control.Distributed.Process.Global.Server (__remoteTable)
import Control.Distributed.Process.Global.Merge
import Control.Distributed.Process.Platform hiding (__remoteTable)
import qualified Control.Distributed.Process.Platform (__remoteTable)
----------------------------------------------
-- * Remote table
----------------------------------------------
__remoteTable :: RemoteTable -> RemoteTable
__remoteTable =
Control.Distributed.Process.Global.Server.__remoteTable .
Control.Distributed.Process.Platform.__remoteTable
| jepst/distributed-process-global | src/Control/Distributed/Process/Global.hs | bsd-3-clause | 1,186 | 0 | 6 | 164 | 189 | 132 | 57 | 33 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE FlexibleInstances #-}
module PID where
import Ivory.Compile.C.CmdlineFrontend
import Ivory.Language
[ivory|
struct PID
{ pid_mv :: Stored IFloat
; pid_i :: Stored IFloat
; pid_err :: Stored IFloat
}
|]
type SP = IFloat -- Set point
type PV = IFloat -- Process (measured) value
type Time = IFloat
{-
void pid_update(struct PID * pid,
sp_t sp,
pv_t pv,
timeinc_t dt
)
{
float err = sp - pv;
float i = pid->i + err*dt;
float d = (err - pid->err) / dt;
pid->i = ki*i;
pid->mv = kp*err + pid->i + kd*d;
pid->err = err;
return;
}
-}
kp, ki, kd :: IFloat
kp = 1.0
ki = 0.1
kd = 0.1
pidUpdate :: Def ('[ Ref s ('Struct "PID")
, SP
, PV
, Time ]
':-> IFloat)
pidUpdate = proc "pid_update" $
\ pid sp pv dt ->
-- These are made up requires/ensures for testing purposes.
requires (checkStored (pid ~> pid_err) (\err -> err <? 1))
$ ensures (\res -> checkStored (pid ~> pid_err) (\err -> err <? res))
$ body
$ do
err <- assign (sp - pv)
i <- deref $ pid ~> pid_i
i' <- assign $ ki * (i + err*dt)
prevErr <- deref $ pid ~> pid_err
d <- assign $ (err - prevErr) / dt
store (pid ~> pid_i) i'
store (pid ~> pid_mv) (kp*err + i' + kd*d)
store (pid ~> pid_err) err
ret err
foo :: Def ('[ Ref s ('Array 3 ('Stored Uint32))
, Ref s ('Array 3 ('Stored Uint32)) ] ':-> ())
foo = proc "foo" $ \a b ->
-- requires (*a!0 < *b!0)
requires (checkStored (a ! 0)
(\v -> (checkStored (b ! 0)
(\v1 -> v <? v1))))
$ body $ do
retVoid
runPID :: IO ()
runPID = runCompiler [cmodule] []
initialOpts { outDir = Nothing, bitShiftCheck = True, divZero = True }
cmodule :: Module
cmodule = package "PID" $ do
incl foobar
-- defStruct (Proxy :: Proxy "PID")
-- incl pidUpdate
-- incl alloc_test
foobar :: Def ('[Uint8] ':-> Uint8)
foobar = proc "foobar" $ \x -> body $ do
ret (x `iShiftR` (3 `iDiv` 2))
alloc_test :: Def ('[] ':-> IFloat)
alloc_test = proc "alloc_test" $ body $ do
pid <- local (istruct [pid_i .= ival 1])
ret =<< deref (pid ~> pid_i)
| GaloisInc/ivory | ivory-examples/examples/PID.hs | bsd-3-clause | 2,393 | 0 | 18 | 744 | 760 | 408 | 352 | 57 | 1 |
{-# LANGUAGE PatternGuards, FlexibleInstances, StandaloneDeriving #-}
module TypedValue
( Any(..)
, prettyval
) where
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid hiding (Any)
import Pretty
import SrcLoc
import Var
import ParseOps
import Memory
import Type
import Prims
import Value
-- | Pretty printing for values
prettyval :: TypeVal -> Value -> Doc'
prettyval t v | t == typeInt = pretty' (unsafeUnvalue v :: Int)
prettyval t v | t == typeChar = pretty' (show (unsafeUnvalue v :: Char))
prettyval (TyCons d [t]) v | V "List" == dataName d && t == typeChar =
pretty' (show (unsafeUnvalue v :: String))
prettyval (TyCons d [t]) v | V "List" == dataName d = pretty' $
brackets $ 3 #> punctuate ',' (map (prettyval t) v')
where v' = unsafeUnvalue v :: [Value]
prettyval (TyFun _) v
| ValClosure v types args <- unsafeUnvalue v
= prettyop v (zipWith prettyval types args)
prettyval (TyCons d [t]) _
| d == datatypeType = pretty' t
| d == datatypeDelay = pretty' "<delay>"
prettyval (TyCons d args) v = case dataInfo d of
DataAlgebraic conses -> prettyop c (zipWith prettyval tl' values) where
(L _ c,tl) = conses !! unsafeTag v
tenv = Map.fromList (zip (dataTyVars d) args)
tl' = map (substVoid tenv) tl
values = unsafeUnvalConsN (length tl) v
DataPrim _ -> error ("don't know how to print primitive datatype "++show (quoted d))
prettyval (TyStatic (Any t _)) d = prettyval t d
prettyval TyVoid _ = error "found an impossible Void value in prettyval"
instance Pretty Any where
pretty' (Any t v) = 2 #> prettyval t v <+> "::" <+> t
instance (Ord k, Pretty k) => Pretty (Map k TypeVal, Map k Value) where
pretty' (t, v) = pretty' $ Map.intersectionWith Any t v
compareval :: TypeVal -> Value -> Value -> Ordering
compareval (TyCons d args) v1 v2 = cmpd (dataInfo d) where
cmpd (DataAlgebraic conses) =
compare c1 (unsafeTag v2) `mappend`
mconcat (zipWith3 compareval tl' vl1 vl2) where
c1 = unsafeTag v1
(_,tl) = conses !! c1
tenv = Map.fromList (zip (dataTyVars d) args)
tl' = map (substVoid tenv) tl
vl1 = unsafeUnvalConsN (length tl) v1
vl2 = unsafeUnvalConsN (length tl) v2
cmpd (DataPrim 0) = EQ
cmpd (DataPrim z)
| z == wordSize = compare v1 v2
| otherwise = error $ "compare: unhandled primitive size " ++ show z
compareval (TyFun _) v1 v2 =
compare f1 f2 `mappend`
mconcat (zipWith compare (tv tl1 vl1) (tv tl2 vl2)) where
tv = zipWith Any
ValClosure f1 tl1 vl1 = unsafeUnvalue v1
ValClosure f2 tl2 vl2 = unsafeUnvalue v2
compareval (TyStatic (Any t _)) v1 v2 = compareval t v1 v2
compareval TyVoid _ _ = error "compare: impossible Void value"
instance Ord Any where
compare (Any t1 v1) (Any t2 v2) =
compare t1 t2 `mappend` compareval t1 v1 v2
instance Eq Any where
Any t1 v1 == Any t2 v2 = t1 == t2 && compareval t1 v1 v2 == EQ
-- now we can do these:
instance Pretty TypeVal where
pretty' (TyStatic tv) = prettyap Static [tv]
pretty' t = pretty' $ singleton t
deriving instance Eq TypeVal
deriving instance Ord TypeVal
| girving/duck | duck/TypedValue.hs | bsd-3-clause | 3,088 | 0 | 14 | 664 | 1,275 | 632 | 643 | 75 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Module : Network.Socks5
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
-- This is an implementation of SOCKS5 as defined in RFC 1928
--
-- In Wikipedia's words:
--
-- SOCKet Secure (SOCKS) is an Internet protocol that routes network packets
-- between a client and server through a proxy server. SOCKS5 additionally
-- provides authentication so only authorized users may access a server.
-- Practically, a SOCKS server will proxy TCP connections to an arbitrary IP
-- address as well as providing a means for UDP packets to be forwarded.
--
-- BIND and UDP ASSOCIATE messages are not implemented.
-- However main usage of SOCKS is covered in this implementation.
--
module Network.Socks5
(
-- * Types
SocksAddress(..)
, SocksHostAddress(..)
, SocksReply(..)
, SocksError(..)
-- * Configuration
, module Network.Socks5.Conf
-- * Methods
, socksConnectWithSocket
, socksConnect
-- * Variants
, socksConnectAddr
, socksConnectName
, socksConnectTo
, socksConnectWith
) where
import Control.Monad
import Control.Exception
import qualified Data.ByteString.Char8 as BC
import Network.Socket ( sClose, Socket, SocketType(..), SockAddr(..), Family(..)
, socket, socketToHandle, connect)
import Network.BSD
import Network (PortID(..))
import qualified Network.Socks5.Command as Cmd
import Network.Socks5.Conf
import Network.Socks5.Types
import Network.Socks5.Lowlevel
import System.IO
-- | connect a user specified new socket to the socks server,
-- and connect the stream on the server side to the 'SockAddress' specified.
--
-- |socket|-----sockServer----->|server|----destAddr----->|destination|
--
socksConnectWithSocket :: Socket -- ^ Socket to use.
-> SocksConf -- ^ SOCKS configuration for the server.
-> SocksAddress -- ^ SOCKS Address to connect to.
-> IO (SocksHostAddress, PortNumber)
socksConnectWithSocket sock serverConf destAddr = do
serverAddr <- resolveToSockAddr (socksServer serverConf)
connect sock serverAddr
r <- Cmd.establish sock [SocksMethodNone]
when (r == SocksMethodNotAcceptable) $ error "cannot connect with no socks method of authentication"
Cmd.rpc_ sock (Connect destAddr)
-- | connect a new socket to a socks server and connect the stream on the
-- server side to the 'SocksAddress' specified.
socksConnect :: SocksConf -- ^ SOCKS configuration for the server.
-> SocksAddress -- ^ SOCKS Address to connect to.
-> IO (Socket, (SocksHostAddress, PortNumber))
socksConnect serverConf destAddr =
getProtocolNumber "tcp" >>= \proto ->
bracketOnError (socket AF_INET Stream proto) sClose $ \sock -> do
ret <- socksConnectWithSocket sock serverConf destAddr
return (sock, ret)
-- | connect a new socket to the socks server, and connect the stream on the server side
-- to the sockaddr specified. the sockaddr need to be SockAddrInet or SockAddrInet6.
--
-- a unix sockaddr will raises an exception.
--
-- |socket|-----sockServer----->|server|----destAddr----->|destination|
{-# DEPRECATED socksConnectAddr "use socksConnectWithSocket" #-}
socksConnectAddr :: Socket -> SockAddr -> SockAddr -> IO ()
socksConnectAddr sock sockserver destaddr =
socksConnectWithSocket sock
(defaultSocksConfFromSockAddr sockserver)
(socksServer $ defaultSocksConfFromSockAddr destaddr) >>
return ()
-- | connect a new socket to the socks server, and connect the stream to a FQDN
-- resolved on the server side.
socksConnectName :: Socket -> SockAddr -> String -> PortNumber -> IO ()
socksConnectName sock sockserver destination port = do
socksConnectWithSocket sock
(defaultSocksConfFromSockAddr sockserver)
(SocksAddress (SocksAddrDomainName $ BC.pack destination) port)
>> return ()
-- | create a new socket and connect in to a destination through the specified
-- SOCKS configuration.
socksConnectWith :: SocksConf -- ^ SOCKS configuration
-> String -- ^ destination hostname
-> PortID -- ^ destination port
-> IO Socket
socksConnectWith socksConf desthost destport = do
dport <- resolvePortID destport
proto <- getProtocolNumber "tcp"
bracketOnError (socket AF_INET Stream proto) sClose $ \sock -> do
sockaddr <- resolveToSockAddr (socksServer socksConf)
socksConnectName sock sockaddr desthost dport
return sock
-- | similar to Network connectTo but use a socks proxy with default socks configuration.
socksConnectTo :: String -> PortID -> String -> PortID -> IO Handle
socksConnectTo sockshost socksport desthost destport = do
sport <- resolvePortID socksport
let socksConf = defaultSocksConf sockshost sport
sock <- socksConnectWith socksConf desthost destport
socketToHandle sock ReadWriteMode
resolvePortID (Service serv) = getServicePortNumber serv
resolvePortID (PortNumber n) = return n
resolvePortID _ = error "unsupported unix PortID"
| erikd/hs-socks | Network/Socks5.hs | bsd-3-clause | 5,329 | 0 | 14 | 1,183 | 833 | 458 | 375 | 78 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Day16 where
import Control.Lens
import Control.Monad
import Control.Monad.ST
import Data.Propagator
import Data.Propagator.Cell
-- boilerplate
link' :: Cell s a -> Prism' a b -> Cell s b -> ST s ()
link' outer prsm inner = do
watch outer $ \outerVal -> write' (outerVal ^? prsm) inner
watch inner $ \innerVal -> write outer (innerVal ^. re prsm)
linkTy :: Cell s Term -> Cell s Term -> ST s ()
linkTy tmCell tyCell = do
watch tmCell $ \tmVal -> write' (tmVal ^. tyL) tyCell
watch tyCell $ \tyVal ->
watch tmCell $ \tmVal -> write tmCell (tmVal & tyL .~ Just tyVal)
-- | Write only when the cell is not @Nothing@.
write' :: Maybe a -> Cell s a -> ST s ()
write' val c = maybe (return ()) (write c) val
withCell :: Propagated a => (Cell s a -> ST s ()) -> ST s (Cell s a)
withCell f = do
x <- cell
f x
return x
-- orphans!
instance Propagated a => Propagated (Maybe a) where
merge (Just a) (Just b) = Just <$> merge a b
merge a@(Just _) Nothing = Change False a
merge Nothing b@(Just _) = Change True b
merge n _ = Change False n
instance Propagated String where
-- our terms
data Term
= BVar { _bVarI :: Maybe Int, _ty :: Maybe Term }
| FVar { _fVarS :: Maybe String, _ty :: Maybe Term }
| Abs { _absTm :: Maybe Term, _ty :: Maybe Term }
| App { _appTm1 :: Maybe Term, _appTm2 :: Maybe Term, _ty :: Maybe Term }
| TyFun { _tyFunDom :: Maybe Term, _tyFunCodom :: Maybe Term, _ty :: Maybe Term }
| Type
deriving Show
instance Propagated Term where
merge (BVar i1 ty1) (BVar i2 ty2) =
BVar <$> merge i1 i2 <*> merge ty1 ty2
merge (FVar s1 ty1) (FVar s2 ty2) =
FVar <$> merge s1 s2 <*> merge ty1 ty2
merge (Abs t1 ty1) (Abs t2 ty2) =
Abs <$> merge t1 t2 <*> merge ty1 ty2
merge (App t11 t12 ty1) (App t21 t22 ty2) = do
ty1' <- merge ty1 (Just (TyFun Nothing Nothing (Just Type)))
mergedTys <- merge ty1' ty2
App <$> merge t11 t21 <*> merge t12 t22 <*> pure mergedTys
merge (TyFun dom1 codom1 ty1) (TyFun dom2 codom2 ty2) =
TyFun <$> merge dom1 dom2 <*> merge codom1 codom2 <*> merge ty1 ty2
merge (TyFun dom codom funTy) x = do
merge
merge x y@(TyFun _ _ _) = merge y x
merge Type Type = Change False Type
merge l r = Contradiction mempty ("term merge: " ++ show (l, r))
-- lenses / prisms
-- idea: we could make these all lenses by indexing Term...
tyL :: Lens' Term (Maybe Term)
tyL f tm = case tm of
BVar i ty -> BVar i <$> f ty
FVar s ty -> FVar s <$> f ty
Abs subTm ty -> Abs subTm <$> f ty
App t1 t2 ty -> App t1 t2 <$> f ty
TyFun dom codom ty -> TyFun dom codom <$> f ty
Type -> const Type <$> f Nothing
tiP :: Prism' Term Int
tiP = prism' (\tm -> BVar (Just tm) Nothing) _bVarI
tsP :: Prism' Term String
tsP = prism' (\tm -> FVar (Just tm) Nothing) _fVarS
absP :: Prism' Term Term
absP = prism' (\tm -> Abs (Just tm) Nothing) (\(Abs tm _) -> tm)
t1P, t2P :: Prism' Term Term
t1P = prism' (\t1 -> App (Just t1) Nothing Nothing) (\(App t1 _ _) -> t1)
t2P = prism' (\t2 -> App Nothing (Just t2) Nothing) (\(App _ t2 _) -> t2)
domP, codomP :: Prism' Term Term
domP = prism' (\dom -> TyFun (Just dom) Nothing Nothing) (\(TyFun dom _ _) -> dom)
codomP = prism' (\codom -> TyFun Nothing (Just codom) Nothing) (\(TyFun _ codom _) -> codom)
-- smart constructors / links
mkBVar :: Cell s Int -> Cell s Term -> ST s (Cell s Term)
mkBVar iCell tyCell = withCell $ \c -> do
link' c tiP iCell
linkTy c tyCell
mkFVar :: Cell s String -> Cell s Term -> ST s (Cell s Term)
mkFVar sCell tyCell = withCell $ \c -> do
link' c tsP sCell
linkTy c tyCell
mkAbs :: Cell s Term -> Cell s Term -> ST s (Cell s Term)
mkAbs subTmCell tyCell = withCell $ \c -> do
link' c absP subTmCell
linkTy c tyCell
mkApp :: Cell s Term -> Cell s Term -> Cell s Term -> ST s (Cell s Term)
mkApp t1Cell t2Cell tyCell = withCell $ \c -> do
link' c t1P t1Cell
link' c t2P t2Cell
linkTy c tyCell
mkTyFun :: Cell s Term -> Cell s Term -> ST s (Cell s Term)
mkTyFun domCell codomCell = withCell $ \c -> do
write c (TyFun Nothing Nothing (Just Type))
link' c domP domCell
link' c codomP codomCell
mkType :: ST s (Cell s Term)
mkType = known Type
-- finally, examples!
main :: IO ()
main = do
print $ runST $ do
-- can't yet express this. (we don't have a way to attach a type to a hole)
-- f x : hole
-- hole : A
-- (+) : Int -> Int -> Int
-- f (+) : Int
-- =>
-- f : (Int -> Int -> Int) -> Int
intTy <- join $ mkFVar <$> known "Int" <*> mkType
plusTy <- join $ mkTyFun <$> mkTyFun intTy intTy <*> pure intTy
plus <- join $ mkFVar <$> known "+" <*> pure plusTy
fTy <- cell -- mkTyFun plusTy intTy
f <- join $ mkFVar <$> known "f" <*> pure fTy
app <- mkApp f plus intTy
content app
-- trying to infer type `Int` (because we applied it to plus)
content fTy
print $ runST $ do
a <- join $ mkFVar <$> known "a" <*> mkType
a' <- join $ mkFVar <$> known "a" <*> mkType
unify a a'
(,) <$> content a <*> content a'
print $ runST $ do
[hole1, hole2] <- replicateM 2 cell
a <- join $ mkFVar <$> known "a" <*> mkType
b <- join $ mkFVar <$> known "b" <*> mkType
c <- join $ mkFVar <$> known "c" <*> mkType
x <- mkApp a hole1 c
y <- mkApp hole2 b c
unify x y
(,) <$> content x <*> content y
| joelburget/daily-typecheckers | src/Day16.hs | bsd-3-clause | 5,463 | 0 | 15 | 1,385 | 2,413 | 1,176 | 1,237 | 127 | 6 |
module Graphics.Efl.Widgets.Button where
import Graphics.Efl.Widgets.Reactive
import Graphics.Efl.Widgets.Window
import Graphics.Efl.Widgets.Rectangle
import Graphics.Efl.Widgets.Text
import Graphics.Efl.Widgets.Widget
import Graphics.Efl.Widgets.Layout
import qualified Graphics.Efl.Canvas as Peer
data Button = Button {
buttonBackground :: Rectangle,
buttonLabel :: Text,
buttonPosition :: Property (Int,Int),
buttonSize :: Property (Int,Int),
buttonVisible :: Property Bool,
buttonText :: Property String,
buttonPressed :: Property Bool
}
instance Widget Button where
widgetSize = buttonSize
widgetPosition = buttonPosition
widgetVisible = buttonVisible
createButton :: Window -> IO Button
createButton win = do
bg <- createRectangle win
label <- createText win
-- Button pressed automaton
let pressedAutomaton = Auto [
rectangleMouseDown bg -@> const (const True),
rectangleMouseUp bg -@> const (const False)
]
btn <- Button bg label
<$> newIORefProperty (0,0)
<*> newIORefProperty (40,15)
<*> newIORefProperty True
<*> newIORefProperty "Press me"
<*> runAutomaton pressedAutomaton id False
rectangleSize bg =& readProperty (buttonSize btn)
rectanglePosition bg =& readProperty (buttonPosition btn)
rectangleVisible bg =& readProperty (buttonVisible btn)
textString label =& readProperty (buttonText btn)
textVisible label =& readProperty (buttonVisible btn)
label `alignCenter` btn
textPassEvents label =& return True
textStyle label =& return (Peer.TextStylePlain, Peer.TextStyleShadowDirectionBottomRight)
textFont label =& return ("DejaVu", 14)
textColor label =& return (50,50,50,255)
rectangleColor bg =& do
press <- readProperty (buttonPressed btn)
return $ if press then (200,200,200,255) else (240,240,240,255)
return btn
| hsyl20/graphics-efl | src/Graphics/Efl/Widgets/Button.hs | bsd-3-clause | 1,906 | 0 | 15 | 373 | 569 | 294 | 275 | 47 | 2 |
{-# LANGUAGE GADTs, OverloadedStrings, RecordWildCards #-}
module Main where
import Common (fromHandleForever, lineByLine, withSerial, zmqConsumer, parseForever, encodeToMsgPack, getConfigFor)
import qualified System.IO as SysIO
import qualified System.Hardware.Serialport as S
import qualified System.ZMQ4 as Z
import Control.Monad (forever)
import Control.Applicative
import Data.Attoparsec.Text
import qualified Data.MessagePack as M
import qualified Data.HashMap as HM
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime(..))
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Time.LocalTime (TimeOfDay(..), timeOfDayToTime)
import Pipes
import qualified Pipes.Prelude as P
import qualified Pipes.Text.IO as PT
type Velocity = Int
type Pressure = Int
type OdmWave = (Double, Velocity, Pressure)
data OdmNomogram = Adult | Paediatric | Dog | None
deriving (Show)
data OdmCalc = OdmCalc { timestamp :: Double
, nomogram :: OdmNomogram
, co :: Float
, sv :: Int
, hr :: Int
, md :: Int
, sd :: Float
, ftc :: Int
, fttp :: Int
, ma :: Float
, pv :: Float
, ci :: Float
, svi :: Float
} deriving (Show)
nomogramParser :: Parser OdmNomogram
nomogramParser =
(char 'A' >> return Adult)
<|> (char 'C' >> return Paediatric)
<|> (char 'D' >> return Dog)
<|> (char 'L' >> return None)
-- #yyyymmddhhmmss:
-- $yyyymmddhhmmss.mmm:
dateTimeParser :: Parser Double
dateTimeParser = do
year <- count 4 digit
month <- count 2 digit
day <- count 2 digit
hour <- count 2 digit
minute <- count 2 digit
seconds <- double
let utctime = UTCTime { utctDay = fromGregorian (read year) (read month) (read day)
, utctDayTime = timeOfDayToTime $ TimeOfDay (read hour) (read minute) (realToFrac seconds)
}
return $ (realToFrac.utcTimeToPOSIXSeconds) utctime
parseOdmCalc :: Parser OdmCalc
parseOdmCalc = do
char '#'
dt <- dateTimeParser
char ':'
nom <- nomogramParser
char ','
co <- rational
char ','
sv <- decimal
char ','
hr <- decimal
char ','
md <- decimal
char ','
sd <- rational
char ','
ftc <- decimal
char ','
fttp <- decimal
char ','
ma <- rational
char ','
pv <- rational
char ','
ci <- rational
char ','
svi <- rational
return $ OdmCalc dt nom co sv hr md sd ftc fttp ma pv ci svi
parseOdmWave :: Parser [OdmWave]
parseOdmWave = do
char '$'
dt <- dateTimeParser
char ':'
pudata <- many1 $ do
char ','
velocity <- decimal
char ';'
pressure <- decimal
-- Bug makes ODM spit out velocity * 4
let velcorr = quot velocity 4
return (velcorr, pressure)
let timedeltas = (+ dt) . (/ 180) <$> [0..]
let injecttime d (v, p) = zip3 d v p
return $ injecttime timedeltas (unzip pudata)
parseEither :: Parser (Either OdmCalc [OdmWave])
parseEither = skipSpace -- handle newline
>> (Left <$> parseOdmCalc)
<|> (Right <$> parseOdmWave)
odmSerialSettings :: S.SerialPortSettings
odmSerialSettings = S.SerialPortSettings S.CS57600 8 S.One S.NoParity S.NoFlowControl 1
main :: IO ()
main = do
config <- getConfigFor "odm"
case "device" `HM.lookup` config of
Just devpath -> withSerial devpath odmSerialSettings pipeline
Nothing -> ioError $ userError "No COM device defined"
keepCalc :: (MonadIO m) => Pipe (Either OdmCalc [OdmWave]) OdmCalc m ()
keepCalc = forever $ do
v <- await
case v of
Right _ -> return ()
Left c -> yield c
keepWave :: (MonadIO m) => Pipe (Either OdmCalc [OdmWave]) [OdmWave] m ()
keepWave = forever $ do
v <- await
case v of
Right c -> yield c
Left _ -> return ()
pipeline :: SysIO.Handle -> IO ()
pipeline hIn = Z.withContext $ \ctx
-> PT.runSafeT . runEffect $ parseForever parseEither (lineByLine $ fromHandleForever hIn)
>-> P.tee (consumeCalc ctx) >-> consumeWave ctx
where
odmEncodeWith = encodeToMsgPack "odm"
consumeCalc ctx = keepCalc >-> odmEncodeWith calcMsgPack >-> zmqConsumer ctx "tcp://127.0.0.1:4201"
consumeWave ctx = keepWave >-> P.concat >-> odmEncodeWith waveMsgPack >-> zmqConsumer ctx "tcp://127.0.0.1:4202"
calcMsgPack :: OdmCalc -> M.Assoc [(String, M.Object)]
calcMsgPack OdmCalc{..} = M.Assoc [("co", M.toObject co),
("sv", M.toObject sv),
("hr", M.toObject hr),
("md", M.toObject md),
("sd", M.toObject sd),
("ftc", M.toObject ftc),
("fttp", M.toObject fttp),
("ma", M.toObject ma),
("pv", M.toObject pv),
("ci", M.toObject ci),
("svi", M.toObject svi)]
waveMsgPack :: OdmWave -> M.Assoc [(String, M.Object)]
waveMsgPack (dt, u, p) = M.Assoc [("dt", M.toObject dt),
("p", M.toObject p),
("u", M.toObject u)]
| jaj42/hsmedstream | haskell/src/OdmStream.hs | isc | 5,620 | 0 | 15 | 1,931 | 1,709 | 891 | 818 | 145 | 2 |
module Fuml.Base.LinearRegression where
import Numeric.LinearAlgebra
-- | Ordinary least squares
ols :: [(Vector Double, Double)] -> Vector Double
ols xys =
let x = fromRows $ map fst xys
y = col $ map snd xys
betaMat = inv (tr' x <> x) <> tr' x <> y
in tr' betaMat ! 0
-- | Weighted ordinary least squares
wols :: Vector Double -> [(Vector Double, Double)] -> Vector Double
wols wvs xys =
let w = diag wvs
x = fromRows $ map fst xys
y = col $ map snd xys
betaMat = inv (tr' x <> w <> x) <> tr' x <> w <> y
in tr' betaMat ! 0
-- | Ridge regression
ridge :: Matrix Double -> [(Vector Double, Double)] -> Vector Double
ridge gamma xys =
let x = fromRows $ map fst xys
y = col $ map snd xys
betaMat = inv (tr' x <> x + tr' gamma <> gamma) <> tr' x <> y
in tr' betaMat ! 0
| diffusionkinetics/open | fuml/lib/Fuml/Base/LinearRegression.hs | mit | 827 | 0 | 16 | 228 | 366 | 182 | 184 | 21 | 1 |
module StatExpr where
f = do "koe"
| roberth/uu-helium | test/typeerrors/Examples/StatExpr.hs | gpl-3.0 | 36 | 0 | 6 | 8 | 12 | 7 | 5 | 2 | 1 |
{-# LANGUAGE OverloadedLists #-}
module Nirum.Constructs.ModulePathSpec where
import Control.Exception (evaluate)
import Data.List (sort)
import GHC.Exts (IsList (fromList, toList))
import System.FilePath ((</>))
import Test.Hspec.Meta
import Nirum.Constructs (Construct (toCode))
import Nirum.Constructs.ModulePath ( ModulePath (ModuleName, ModulePath)
, hierarchy
, hierarchies
, fromFilePath
, fromIdentifiers
, replacePrefix
)
spec :: Spec
spec =
describe "ModulePath" $ do
let foo = ModuleName "foo"
fooBar = ModulePath (ModuleName "foo") "bar"
fooBarBaz = ModulePath (ModulePath (ModuleName "foo") "bar") "baz"
fooBarBaz2 = ModulePath (ModuleName "foo") "bar-baz2"
specify "fromIdentifiers" $ do
fromIdentifiers [] `shouldBe` Nothing
fromIdentifiers ["foo"] `shouldBe` Just foo
fromIdentifiers ["Foo"] `shouldBe` Just foo
fromIdentifiers ["FOO"] `shouldBe` Just foo
fromIdentifiers ["foo", "bar"] `shouldBe` Just fooBar
fromIdentifiers ["foo", "bar", "baz"] `shouldBe` Just fooBarBaz
fromIdentifiers ["Foo", "BAR", "baZ"] `shouldBe` Just fooBarBaz
fromIdentifiers ["foo", "bar-baz2"] `shouldBe` Just fooBarBaz2
fromIdentifiers ["FOO", "bar_baz2"] `shouldBe` Just fooBarBaz2
specify "fromFilePath" $ do
fromFilePath "" `shouldBe` Nothing
fromFilePath "foo.nrm" `shouldBe` Just foo
fromFilePath "FOO.NRM" `shouldBe` Just foo
fromFilePath "Foo.Nrm" `shouldBe` Just foo
fromFilePath ("foo" </> "bar.nrm") `shouldBe` Just fooBar
fromFilePath ("FOO" </> "bar.NRM") `shouldBe` Just fooBar
fromFilePath ("foo" </> "bar" </> "baz.nrm") `shouldBe`
Just fooBarBaz
fromFilePath ("foo" </> "BAR" </> "baz.nrm") `shouldBe`
Just fooBarBaz
fromFilePath ("foo" </> "bar-baz2.nrm") `shouldBe` Just fooBarBaz2
fromFilePath ("foo" </> "bar_baz2.NRM") `shouldBe` Just fooBarBaz2
specify "hierarchy" $ do
hierarchy ["foo", "bar", "baz"] `shouldBe`
[ ["foo"]
, ["foo", "bar"]
, ["foo", "bar", "baz"]
]
hierarchy ["foo"] `shouldBe` [["foo"]]
specify "hierarchies" $
hierarchies [ ["foo", "bar", "baz"], ["tar", "gz"] ] `shouldBe`
[ ["foo"]
, ["foo", "bar"]
, ["foo", "bar", "baz"]
, ["tar"]
, ["tar", "gz"]
]
specify "replacePrefix" $ do
replacePrefix ["foo"] ["qux"] ["foo"] `shouldBe` ["qux"]
replacePrefix ["foo"] ["qux"] ["foo", "bar"] `shouldBe`
["qux", "bar"]
replacePrefix ["foo"] ["qux"] ["bar", "foo"] `shouldBe`
["bar", "foo"]
replacePrefix ["foo"] ["qux", "quz"] ["foo"] `shouldBe`
["qux", "quz"]
replacePrefix ["foo"] ["qux", "quz"] ["foo", "bar"] `shouldBe`
["qux", "quz", "bar"]
replacePrefix ["foo"] ["qux", "quz"] ["bar", "foo"] `shouldBe`
["bar", "foo"]
replacePrefix ["foo", "bar"] ["qux"] ["foo"] `shouldBe` ["foo"]
replacePrefix ["foo", "bar"] ["qux"] ["foo", "bar"] `shouldBe`
["qux"]
replacePrefix ["foo", "bar"] ["qux"] ["foo", "bar", "baz"]
`shouldBe` ["qux", "baz"]
replacePrefix ["foo", "bar"] ["qux"] ["bar", "foo"] `shouldBe`
["bar", "foo"]
context "Construct" $
specify "toCode" $ do
toCode foo `shouldBe` "foo"
toCode fooBar `shouldBe` "foo.bar"
toCode fooBarBaz `shouldBe` "foo.bar.baz"
toCode fooBarBaz2 `shouldBe` "foo.bar-baz2"
context "IsList" $ do
specify "fromList" $ do
evaluate (fromList [] :: ModulePath) `shouldThrow`
errorCall "ModulePath cannot be empty"
fromList ["foo"] `shouldBe` foo
fromList ["foo", "bar"] `shouldBe` fooBar
fromList ["foo", "bar", "baz"] `shouldBe` fooBarBaz
fromList ["foo", "bar-baz2"] `shouldBe` fooBarBaz2
specify "toList" $ do
toList foo `shouldBe` ["foo"]
toList fooBar `shouldBe` ["foo", "bar"]
toList fooBarBaz `shouldBe` ["foo", "bar", "baz"]
toList fooBarBaz2 `shouldBe` ["foo", "bar-baz2"]
context "Ord" $
specify "<=" $ do
["abc"] `shouldSatisfy` (<= foo)
foo `shouldSatisfy` (<= fooBar)
fooBar `shouldNotSatisfy` (<= foo)
fooBar `shouldSatisfy` (<= fooBarBaz)
fooBarBaz `shouldNotSatisfy` (<= fooBar)
fooBarBaz `shouldSatisfy` (<= fooBarBaz2)
fooBarBaz2 `shouldNotSatisfy` (<= fooBarBaz)
sort [["abc"], foo, fooBar, fooBarBaz, fooBarBaz2]
`shouldBe` [["abc"], foo, fooBar, fooBarBaz, fooBarBaz2]
| spoqa/nirum | test/Nirum/Constructs/ModulePathSpec.hs | gpl-3.0 | 5,410 | 0 | 18 | 1,926 | 1,533 | 850 | 683 | 106 | 1 |
module Paths_MipsPreprocessor (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version {versionBranch = [0,1,0,0], versionTags = []}
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/christianbeasley/MipsPreprocessor/.cabal-sandbox/bin"
libdir = "/Users/christianbeasley/MipsPreprocessor/.cabal-sandbox/lib/x86_64-osx-ghc-7.8.3/MipsPreprocessor-0.1.0.0"
datadir = "/Users/christianbeasley/MipsPreprocessor/.cabal-sandbox/share/x86_64-osx-ghc-7.8.3/MipsPreprocessor-0.1.0.0"
libexecdir = "/Users/christianbeasley/MipsPreprocessor/.cabal-sandbox/libexec"
sysconfdir = "/Users/christianbeasley/MipsPreprocessor/.cabal-sandbox/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "MipsPreprocessor_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "MipsPreprocessor_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "MipsPreprocessor_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "MipsPreprocessor_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "MipsPreprocessor_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| yyttr3/Mips_Preprocessor | dist/dist-sandbox-b8f9eba6/build/autogen/Paths_MipsPreprocessor.hs | gpl-3.0 | 1,592 | 0 | 10 | 182 | 371 | 213 | 158 | 28 | 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.RDS.ListTagsForResource
-- 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)
--
-- Lists all tags on an Amazon RDS resource.
--
-- For an overview on tagging an Amazon RDS resource, see
-- <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.Tagging.html Tagging Amazon RDS Resources>.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_ListTagsForResource.html AWS API Reference> for ListTagsForResource.
module Network.AWS.RDS.ListTagsForResource
(
-- * Creating a Request
listTagsForResource
, ListTagsForResource
-- * Request Lenses
, ltfrFilters
, ltfrResourceName
-- * Destructuring the Response
, listTagsForResourceResponse
, ListTagsForResourceResponse
-- * Response Lenses
, ltfrrsTagList
, ltfrrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.RDS.Types
import Network.AWS.RDS.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'listTagsForResource' smart constructor.
data ListTagsForResource = ListTagsForResource'
{ _ltfrFilters :: !(Maybe [Filter])
, _ltfrResourceName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListTagsForResource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltfrFilters'
--
-- * 'ltfrResourceName'
listTagsForResource
:: Text -- ^ 'ltfrResourceName'
-> ListTagsForResource
listTagsForResource pResourceName_ =
ListTagsForResource'
{ _ltfrFilters = Nothing
, _ltfrResourceName = pResourceName_
}
-- | This parameter is not currently supported.
ltfrFilters :: Lens' ListTagsForResource [Filter]
ltfrFilters = lens _ltfrFilters (\ s a -> s{_ltfrFilters = a}) . _Default . _Coerce;
-- | The Amazon RDS resource with tags to be listed. This value is an Amazon
-- Resource Name (ARN). For information about creating an ARN, see
-- <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html#USER_Tagging.ARN Constructing an RDS Amazon Resource Name (ARN)>.
ltfrResourceName :: Lens' ListTagsForResource Text
ltfrResourceName = lens _ltfrResourceName (\ s a -> s{_ltfrResourceName = a});
instance AWSRequest ListTagsForResource where
type Rs ListTagsForResource =
ListTagsForResourceResponse
request = postQuery rDS
response
= receiveXMLWrapper "ListTagsForResourceResult"
(\ s h x ->
ListTagsForResourceResponse' <$>
(x .@? "TagList" .!@ mempty >>=
may (parseXMLList "Tag"))
<*> (pure (fromEnum s)))
instance ToHeaders ListTagsForResource where
toHeaders = const mempty
instance ToPath ListTagsForResource where
toPath = const "/"
instance ToQuery ListTagsForResource where
toQuery ListTagsForResource'{..}
= mconcat
["Action" =: ("ListTagsForResource" :: ByteString),
"Version" =: ("2014-10-31" :: ByteString),
"Filters" =:
toQuery (toQueryList "Filter" <$> _ltfrFilters),
"ResourceName" =: _ltfrResourceName]
-- |
--
-- /See:/ 'listTagsForResourceResponse' smart constructor.
data ListTagsForResourceResponse = ListTagsForResourceResponse'
{ _ltfrrsTagList :: !(Maybe [Tag])
, _ltfrrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListTagsForResourceResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltfrrsTagList'
--
-- * 'ltfrrsResponseStatus'
listTagsForResourceResponse
:: Int -- ^ 'ltfrrsResponseStatus'
-> ListTagsForResourceResponse
listTagsForResourceResponse pResponseStatus_ =
ListTagsForResourceResponse'
{ _ltfrrsTagList = Nothing
, _ltfrrsResponseStatus = pResponseStatus_
}
-- | List of tags returned by the ListTagsForResource operation.
ltfrrsTagList :: Lens' ListTagsForResourceResponse [Tag]
ltfrrsTagList = lens _ltfrrsTagList (\ s a -> s{_ltfrrsTagList = a}) . _Default . _Coerce;
-- | The response status code.
ltfrrsResponseStatus :: Lens' ListTagsForResourceResponse Int
ltfrrsResponseStatus = lens _ltfrrsResponseStatus (\ s a -> s{_ltfrrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-rds/gen/Network/AWS/RDS/ListTagsForResource.hs | mpl-2.0 | 5,042 | 0 | 15 | 1,033 | 681 | 406 | 275 | 84 | 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.EFS.DescribeTags
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the tags associated with a file system. The order of tags
-- returned in the response of one 'DescribeTags' call, and the order of
-- tags returned across the responses of a multi-call iteration (when using
-- pagination), is unspecified.
--
-- This operation requires permission for the
-- 'elasticfilesystem:DescribeTags' action.
--
-- /See:/ <http://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeTags.html AWS API Reference> for DescribeTags.
module Network.AWS.EFS.DescribeTags
(
-- * Creating a Request
describeTags
, DescribeTags
-- * Request Lenses
, dtMarker
, dtMaxItems
, dtFileSystemId
-- * Destructuring the Response
, describeTagsResponse
, DescribeTagsResponse
-- * Response Lenses
, dtrsMarker
, dtrsNextMarker
, dtrsResponseStatus
, dtrsTags
) where
import Network.AWS.EFS.Types
import Network.AWS.EFS.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'describeTags' smart constructor.
data DescribeTags = DescribeTags'
{ _dtMarker :: !(Maybe Text)
, _dtMaxItems :: !(Maybe Nat)
, _dtFileSystemId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeTags' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtMarker'
--
-- * 'dtMaxItems'
--
-- * 'dtFileSystemId'
describeTags
:: Text -- ^ 'dtFileSystemId'
-> DescribeTags
describeTags pFileSystemId_ =
DescribeTags'
{ _dtMarker = Nothing
, _dtMaxItems = Nothing
, _dtFileSystemId = pFileSystemId_
}
-- | Optional. String. Opaque pagination token returned from a previous
-- 'DescribeTags' operation. If present, it specifies to continue the list
-- from where the previous call left off.
dtMarker :: Lens' DescribeTags (Maybe Text)
dtMarker = lens _dtMarker (\ s a -> s{_dtMarker = a});
-- | Optional. Maximum number of file system tags to return in the response.
-- It must be an integer with a value greater than zero.
dtMaxItems :: Lens' DescribeTags (Maybe Natural)
dtMaxItems = lens _dtMaxItems (\ s a -> s{_dtMaxItems = a}) . mapping _Nat;
-- | The ID of the file system whose tag set you want to retrieve.
dtFileSystemId :: Lens' DescribeTags Text
dtFileSystemId = lens _dtFileSystemId (\ s a -> s{_dtFileSystemId = a});
instance AWSRequest DescribeTags where
type Rs DescribeTags = DescribeTagsResponse
request = get eFS
response
= receiveJSON
(\ s h x ->
DescribeTagsResponse' <$>
(x .?> "Marker") <*> (x .?> "NextMarker") <*>
(pure (fromEnum s))
<*> (x .?> "Tags" .!@ mempty))
instance ToHeaders DescribeTags where
toHeaders = const mempty
instance ToPath DescribeTags where
toPath DescribeTags'{..}
= mconcat
["/2015-02-01/tags/", toBS _dtFileSystemId, "/"]
instance ToQuery DescribeTags where
toQuery DescribeTags'{..}
= mconcat
["Marker" =: _dtMarker, "MaxItems" =: _dtMaxItems]
-- | /See:/ 'describeTagsResponse' smart constructor.
data DescribeTagsResponse = DescribeTagsResponse'
{ _dtrsMarker :: !(Maybe Text)
, _dtrsNextMarker :: !(Maybe Text)
, _dtrsResponseStatus :: !Int
, _dtrsTags :: ![Tag]
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeTagsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtrsMarker'
--
-- * 'dtrsNextMarker'
--
-- * 'dtrsResponseStatus'
--
-- * 'dtrsTags'
describeTagsResponse
:: Int -- ^ 'dtrsResponseStatus'
-> DescribeTagsResponse
describeTagsResponse pResponseStatus_ =
DescribeTagsResponse'
{ _dtrsMarker = Nothing
, _dtrsNextMarker = Nothing
, _dtrsResponseStatus = pResponseStatus_
, _dtrsTags = mempty
}
-- | If the request included a 'Marker', the response returns that value in
-- this field.
dtrsMarker :: Lens' DescribeTagsResponse (Maybe Text)
dtrsMarker = lens _dtrsMarker (\ s a -> s{_dtrsMarker = a});
-- | If a value is present, there are more tags to return. In a subsequent
-- request, you can provide the value of 'NextMarker' as the value of the
-- 'Marker' parameter in your next request to retrieve the next set of
-- tags.
dtrsNextMarker :: Lens' DescribeTagsResponse (Maybe Text)
dtrsNextMarker = lens _dtrsNextMarker (\ s a -> s{_dtrsNextMarker = a});
-- | The response status code.
dtrsResponseStatus :: Lens' DescribeTagsResponse Int
dtrsResponseStatus = lens _dtrsResponseStatus (\ s a -> s{_dtrsResponseStatus = a});
-- | Returns tags associated with the file system as an array of 'Tag'
-- objects.
dtrsTags :: Lens' DescribeTagsResponse [Tag]
dtrsTags = lens _dtrsTags (\ s a -> s{_dtrsTags = a}) . _Coerce;
| fmapfmapfmap/amazonka | amazonka-efs/gen/Network/AWS/EFS/DescribeTags.hs | mpl-2.0 | 5,716 | 0 | 14 | 1,243 | 874 | 521 | 353 | 102 | 1 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Data/Aeson/Parser/Unescape.hs" #-}
{-# LANGUAGE CPP #-}
module Data.Aeson.Parser.Unescape
(
unescapeText
) where
import Data.Aeson.Parser.UnescapePure (unescapeText)
| phischu/fragnix | tests/packages/scotty/Data.Aeson.Parser.Unescape.hs | bsd-3-clause | 313 | 0 | 5 | 128 | 28 | 20 | 8 | 7 | 0 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -Wall -Werror -funbox-strict-fields #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances,
MultiParamTypeClasses, UndecidableInstances #-}
-- | A pretty printer implementation, based loosely on the
-- Wadler-Leijin pretty printer, but redesigned to facilitate a
-- dynamic programming optimal layout algorithm.
--
-- This pretty printer module trades some of the generality of the
-- Wadler-Leijin scheme in order to facilitate an efficient optimizing
-- layout engine. The nesting, column, and width combinators are
-- removed.
module Text.Format(
-- * Basic Definitions
-- ** Types
Doc,
Graphics(..),
-- ** Type Classes
Format(..),
FormatM(..),
-- * Creating @Doc@s
-- ** Constructors
-- *** Basic
empty,
line,
linebreak,
hardline,
softline,
softbreak,
-- *** From datatypes
char,
string,
bytestring,
lazyBytestring,
-- *** Literals
lparen,
rparen,
lbrack,
rbrack,
lbrace,
rbrace,
langle,
rangle,
squote,
dquote,
backquote,
comma,
semi,
colon,
dot,
backslash,
equals,
space,
-- *** Derived
nest,
indent,
alignOffset,
align,
squoted,
dquoted,
parens,
brackets,
braces,
angles,
list,
-- *** Graphics Mode
graphics,
dullWhite,
dullRed,
dullYellow,
dullGreen,
dullBlue,
dullCyan,
dullMagenta,
dullBlack,
vividWhite,
vividRed,
vividYellow,
vividGreen,
vividBlue,
vividCyan,
vividMagenta,
vividBlack,
dullWhiteBackground,
dullRedBackground,
dullYellowBackground,
dullGreenBackground,
dullBlueBackground,
dullCyanBackground,
dullMagentaBackground,
dullBlackBackground,
vividWhiteBackground,
vividRedBackground,
vividYellowBackground,
vividGreenBackground,
vividBlueBackground,
vividCyanBackground,
vividMagentaBackground,
vividBlackBackground,
bold,
debold,
underline,
deunderline,
-- ** Combining @Doc@s
-- *** Basic
beside,
concat,
choose,
-- *** Derived
(<>),
(<+>),
(<!>),
(<$>),
(<$$>),
(</>),
(<//>),
hsep,
hcat,
vsep,
vcat,
sep,
cat,
fillSep,
fillCat,
enclose,
punctuate,
encloseSep,
-- ** Transforming @Doc@s
flatten,
group,
-- * Rendering @Doc@s
-- ** Single-Line Render
renderOneLine,
buildOneLine,
putOneLine,
-- ** Fast Render
renderFast,
buildFast,
putFast,
-- ** Optimal Render
renderOptimal,
buildOptimal,
putOptimal,
-- ** Greedy Render
renderGreedy,
buildGreedy,
putGreedy
) where
import Blaze.ByteString.Builder
import Blaze.ByteString.Builder.Char.Utf8
import Control.Arrow((***))
import Control.Monad
import Data.Hashable
import Data.List(intersperse, minimumBy, sort, sortBy)
import Data.Maybe
import Data.Monoid
import Data.Word
import Prelude hiding ((<$>), concat, maximum, minimum)
import System.Console.ANSI
import System.IO
import qualified Data.ByteString as Strict
import qualified Data.ByteString.UTF8 as Strict.UTF8
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.ByteString.Lazy.Char8 as Lazy.Char8
import qualified Data.ByteString.Lazy.UTF8 as Lazy.UTF8
--import Debug.Trace
debug :: String -> a -> a
--debug = trace
debug _ = id
-- | Datatype representing a formatted document.
data LineKind =
-- | Unerasable linebreak
Hard
-- | Linebreak replaced with nothing
| Soft
-- | Linebreak replaced with a space
| Break
deriving (Ord, Eq, Enum, Show)
-- Docs are organized into a tree structure whose nodes dictate the
-- formatting of the generated text. These are rendered by the
-- various rendering engines into a Builder (from the blaze-builder
-- library).
data Doc =
-- | A single character. Cannot be a newline.
Char { charContent :: !Char }
-- | A raw Builder that constructs a string containing no
-- newlines. This is used to represent basic text.
| Content {
-- | Length of the text that gets built.
contentLength :: !Int,
-- | A Builder that constructs the text.
contentString :: !Lazy.ByteString
}
-- | An erasable newline.
| Line {
-- | Whether to insert a space when undone by a group.
lineKind :: !LineKind
}
-- | Concatenated documents. An empty list here represents an empty @Doc@.
| Cat {
catDocs :: [Doc]
}
-- | Increase the nesting level of a document.
| Nest {
-- | Amount by which to increase nesting.
nestLevel :: !Int,
-- | Whether to align to the current column, or the base nesting
-- level.
nestAlign :: !Bool,
-- | Whether the indentation is delayed, or takes place immediately.
nestDelay :: !Bool,
-- | Document whose nesting should be increased.
nestDoc :: Doc
}
-- | Choose the \"best\" from among a list of options.
| Choose {
-- | The list of options.
chooseOptions :: [Doc]
}
-- | Set graphics mode options when rendering the child @Doc@.
| Graphics {
-- | Graphics mode to set.
graphicsSGR :: !Graphics,
-- | Document to render with graphic mode.
graphicsDoc :: Doc
}
deriving (Eq, Show)
instance Monoid Doc where
mempty = empty
mappend = beside
mconcat = concat
-- | Graphics options for ANSI terminals. All options are wrapped in
-- the 'Maybe' datatype, with 'Nothing' meaning \"leave this option
-- as-is\".
data Graphics =
-- | Set options on the terminal, or keep the current setting in
-- the case of 'Nothing'.
Options {
-- | Console intensity.
consoleIntensity :: !(Maybe ConsoleIntensity),
-- | Underlining.
underlining :: !(Maybe Underlining),
-- | Blinking speed.
blinkSpeed :: !(Maybe BlinkSpeed),
-- | Foreground color and intensity.
foreground :: !(Maybe (Color, ColorIntensity)),
-- | Background color and intensity.
background :: !(Maybe (Color, ColorIntensity)),
-- | Whether or not to swap the foreground and background.
swapForegroundBackground :: !(Maybe Bool)
}
-- | Reset the terminal in this mode.
| Default
deriving (Ord, Eq, Show)
instance Monoid Graphics where
mempty = Options { consoleIntensity = Nothing, underlining = Nothing,
swapForegroundBackground = Nothing, foreground = Nothing,
background = Nothing, blinkSpeed = Nothing }
mappend Default opts = opts
mappend opts Default = opts
mappend Options { consoleIntensity = consIntensity1,
swapForegroundBackground = swap1,
underlining = underline1,
foreground = fore1,
background = back1,
blinkSpeed = blink1 }
Options { consoleIntensity = consIntensity2,
swapForegroundBackground = swap2,
underlining = underline2,
foreground = fore2,
background = back2,
blinkSpeed = blink2 } =
Options { consoleIntensity = case consIntensity1 of
consIntensity @ (Just _) -> consIntensity
Nothing -> consIntensity2,
swapForegroundBackground = case swap1 of
swap @ (Just _) -> swap
Nothing -> swap2,
underlining = case underline1 of
uline @ (Just _) -> uline
Nothing -> underline2,
foreground = case fore1 of
fore @ (Just _) -> fore
Nothing -> fore2,
background = case back1 of
back @ (Just _) -> back
Nothing -> back2,
blinkSpeed = case blink1 of
blink @ (Just _) -> blink
Nothing -> blink2 }
instance Ord Doc where
compare Char { charContent = c1 } Char { charContent = c2 } = compare c1 c2
compare Char {} _ = LT
compare _ Char {} = GT
compare Content { contentString = str1 } Content { contentString = str2 } =
compare str1 str2
compare Content {} _ = LT
compare _ Content {} = GT
compare Line { lineKind = kind1 } Line { lineKind = kind2 } =
compare kind1 kind2
compare Line {} _ = LT
compare _ Line {} = GT
compare Cat { catDocs = docs1 } Cat { catDocs = docs2 } = compare docs1 docs2
compare Cat {} _ = LT
compare _ Cat {} = GT
compare Nest { nestLevel = lvl1, nestAlign = al1,
nestDelay = delay1, nestDoc = doc1 }
Nest { nestLevel = lvl2, nestAlign = al2,
nestDelay = delay2, nestDoc = doc2 } =
case compare lvl1 lvl2 of
EQ -> case compare al1 al2 of
EQ -> case compare delay1 delay2 of
EQ -> compare doc1 doc2
out -> out
out -> out
out -> out
compare Nest {} _ = LT
compare _ Nest {} = GT
compare Choose { chooseOptions = opts1 } Choose { chooseOptions = opts2 } =
compare opts1 opts2
compare Choose {} _ = LT
compare _ Choose {} = GT
compare Graphics { graphicsSGR = sgr1, graphicsDoc = doc1 }
Graphics { graphicsSGR = sgr2, graphicsDoc = doc2 } =
case compare sgr1 sgr2 of
EQ -> compare doc1 doc2
out -> out
instance Hashable LineKind where
hashWithSalt s = hashWithSalt s . fromEnum
instance Hashable Doc where
hashWithSalt s Char { charContent = c } =
s `hashWithSalt` (0 :: Int) `hashWithSalt` c
hashWithSalt s Content { contentLength = len, contentString = str } =
s `hashWithSalt` (1 :: Int) `hashWithSalt` len `hashWithSalt` str
hashWithSalt s Line { lineKind = kind } =
s `hashWithSalt` (2 :: Int) `hashWithSalt` kind
hashWithSalt s Cat { catDocs = docs } =
s `hashWithSalt` (3 :: Int) `hashWithSalt` docs
hashWithSalt s Nest { nestLevel = lvl, nestAlign = al,
nestDelay = delay, nestDoc = doc } =
s `hashWithSalt` (4 :: Int) `hashWithSalt` lvl `hashWithSalt`
al `hashWithSalt` delay `hashWithSalt` doc
hashWithSalt s Choose { chooseOptions = opts } =
s `hashWithSalt` (5 :: Int) `hashWithSalt` sort opts
hashWithSalt s Graphics { graphicsSGR = sgr, graphicsDoc = doc } =
s `hashWithSalt` (6 :: Int) `hashWithSalt` sgr `hashWithSalt` doc
instance Hashable Graphics where
hashWithSalt s Options { consoleIntensity = consIntensity,
swapForegroundBackground = swap,
underlining = uline,
foreground = fore,
background = back,
blinkSpeed = blink } =
s `hashWithSalt` (0 :: Int) `hashWithSalt`
fmap fromEnum consIntensity `hashWithSalt`
fmap fromEnum swap `hashWithSalt` fmap fromEnum uline `hashWithSalt`
fmap (fromEnum *** fromEnum) fore `hashWithSalt`
fmap (fromEnum *** fromEnum) back `hashWithSalt` fmap fromEnum blink
hashWithSalt s Default = s `hashWithSalt` (1 :: Int)
-- | Generate a 'Doc' representing a graphics mode switch.
switchGraphics :: Graphics -> Graphics -> Builder
switchGraphics _ Default = fromString (setSGRCode [Reset])
switchGraphics Default Options { consoleIntensity = consIntensity,
swapForegroundBackground = swap,
underlining = uline,
foreground = fore,
background = back,
blinkSpeed = blink } =
let
withConsIntensity = maybe [] ((: []) . SetConsoleIntensity) consIntensity
withUnderline = maybe withConsIntensity ((: withConsIntensity) .
SetUnderlining)
uline
withBlink = maybe withUnderline ((: withUnderline) . SetBlinkSpeed) blink
withSwap = maybe withBlink ((: withBlink) . SetSwapForegroundBackground)
swap
withForeground =
maybe withSwap (\(color, intensity) -> SetColor Foreground intensity
color : withSwap) fore
withBackground =
maybe withForeground (\(color, intensity) -> SetColor Background intensity
color : withForeground) back
in
fromString (setSGRCode withBackground)
switchGraphics Options { consoleIntensity = consIntensity1,
swapForegroundBackground = swap1,
underlining = underline1,
foreground = fore1,
background = back1,
blinkSpeed = blink1 }
Options { consoleIntensity = consIntensity2,
swapForegroundBackground = swap2,
underlining = underline2,
foreground = fore2,
background = back2,
blinkSpeed = blink2 } =
let
withConsIntensity =
if consIntensity1 /= consIntensity2
then maybe [] ((: []) . SetConsoleIntensity) consIntensity2
else []
withUnderline =
if underline1 /= underline2
then maybe withConsIntensity ((: withConsIntensity) . SetUnderlining)
underline2
else withConsIntensity
withBlink =
if blink1 /= blink2
then maybe withUnderline ((: withUnderline) . SetBlinkSpeed) blink2
else withUnderline
withSwap =
if swap1 /= swap2
then maybe withBlink ((: withBlink) . SetSwapForegroundBackground) swap2
else withBlink
withForeground =
if fore1 /= fore2
then maybe withSwap (\(color, intensity) ->
SetColor Foreground intensity color : withSwap)
fore2
else withSwap
withBackground =
if back1 /= back2
then maybe withSwap (\(color, intensity) ->
SetColor Background intensity color :
withForeground) back2
else withForeground
in
fromString (setSGRCode withBackground)
-- | An empty 'Doc'.
empty :: Doc
empty = Cat { catDocs = [] }
-- | A 'Doc' consisting of a linebreak, that is not turned into a
-- space when erased by a 'group'.
line :: Doc
line = Line { lineKind = Soft }
-- | A 'Doc' consisting of a linebreak, that is turned into a space
-- when erased by a 'group'.
linebreak :: Doc
linebreak = Line { lineKind = Break }
-- | A 'Doc' consisting of a linebreak that cannot be erased by a 'group'.
hardline :: Doc
hardline = Line { lineKind = Hard }
-- | A 'Doc' consisting of a space character, that can be turned into
-- a linebreak in order to break lines that are too long.
softline :: Doc
softline = Choose { chooseOptions = [ char ' ', linebreak ] }
-- | An empty 'Doc' that can be turned into a linebreak in order to
-- break lines that are too long.
softbreak :: Doc
softbreak = Choose { chooseOptions = [ empty, line ] }
-- | A 'Doc' containing a single character.
char :: Char -> Doc
char '\n' = line
char chr = Char { charContent = chr }
-- | Create a 'Doc' containing a string.
string :: String -> Doc
string str = Content { contentString = Lazy.UTF8.fromString str,
contentLength = length str }
-- | Create a 'Doc' containing a bytestring.
bytestring :: Strict.ByteString -> Doc
bytestring txt
| Strict.null txt = empty
| otherwise = Content { contentLength = Strict.UTF8.length txt,
contentString = Lazy.fromStrict txt }
-- | Create a 'Doc' containing a lazy bytestring
lazyBytestring :: Lazy.ByteString -> Doc
lazyBytestring txt
| Lazy.null txt = empty
| otherwise = Content { contentLength = Lazy.UTF8.length txt,
contentString = txt }
-- | The character @(@
lparen :: Doc
lparen = char '('
-- | The character @)@
rparen :: Doc
rparen = char ')'
-- | The character @[@
lbrack :: Doc
lbrack = char '['
-- | The character @]@
rbrack :: Doc
rbrack = char ']'
-- | The character @{@
lbrace :: Doc
lbrace = char '{'
-- | The character @}@
rbrace :: Doc
rbrace = char '}'
-- | The character @<@
langle :: Doc
langle = char '<'
-- | The character @>@
rangle :: Doc
rangle = char '>'
-- | The character @'@
squote :: Doc
squote = char '\''
-- | The character @"@
dquote :: Doc
dquote = char '"'
-- | The character @`@
backquote :: Doc
backquote = char '`'
-- | The character @,@
comma :: Doc
comma = char ','
-- | The character @;@
semi :: Doc
semi = char ';'
-- | The character @:@
colon :: Doc
colon = char ':'
-- | The character @.@
dot :: Doc
dot = char '.'
-- | The character @\@
backslash :: Doc
backslash = char '\\'
-- | A space character.
space :: Doc
space = char ' '
-- | The character @=@
equals :: Doc
equals = char '='
-- | Increase the indentation level of a document by some amount.
nest :: Int -> Doc -> Doc
nest _ c @ Cat { catDocs = [] } = c
nest lvl n @ Nest { nestLevel = lvl' } = n { nestLevel = lvl + lvl' }
nest lvl doc = Nest { nestDelay = True, nestAlign = False,
nestLevel = lvl, nestDoc = doc }
-- | Increase the indentation level of a document by some amount.
indent :: Int -> Doc -> Doc
indent _ c @ Cat { catDocs = [] } = c
indent lvl n @ Nest { nestLevel = lvl' } = n { nestLevel = lvl + lvl' }
indent lvl doc = Nest { nestDelay = False, nestAlign = False,
nestLevel = lvl, nestDoc = doc }
-- | Set the indentation level to the current column. This is
-- equivalent to @alignOffset 0@.
align :: Doc -> Doc
align = alignOffset 0
-- | Set the indetation level to the current column, plus some offset.
alignOffset :: Int
-- ^ Offset to current column. Can be negative.
-> Doc
-- ^ The @Doc@ to align.
-> Doc
alignOffset offset inner = Nest { nestDelay = True, nestAlign = True,
nestLevel = offset, nestDoc = inner }
-- | Enclose a 'Doc' in single quotes
squoted :: Doc -> Doc
squoted = enclose squote squote
-- | Enclose a 'Doc' in double quotes
dquoted :: Doc -> Doc
dquoted = enclose dquote dquote
-- | Enclose a 'Doc' in paretheses
parens :: Doc -> Doc
parens = enclose lparen rparen
-- | Enclose a 'Doc' in brackets
brackets :: Doc -> Doc
brackets = enclose lbrack rbrack
-- | Enclose a 'Doc' in braces
braces :: Doc -> Doc
braces = enclose lbrace rbrace
-- | Enclose a 'Doc' in angles
angles :: Doc -> Doc
angles = enclose langle rangle
-- | Set the graphics mode on a document.
graphics :: Graphics -> Doc -> Doc
graphics sgr1 Graphics { graphicsDoc = doc, graphicsSGR = sgr2 } =
Graphics { graphicsDoc = doc, graphicsSGR = sgr1 <> sgr2 }
graphics sgr doc = Graphics { graphicsDoc = doc, graphicsSGR = sgr }
-- | Color a 'Doc' dull white.
dullWhite :: Doc -> Doc
dullWhite = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (White, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull red.
dullRed :: Doc -> Doc
dullRed = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Red, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull yellow.
dullYellow :: Doc -> Doc
dullYellow = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Yellow, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull green.
dullGreen :: Doc -> Doc
dullGreen = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Green, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull blue.
dullBlue :: Doc -> Doc
dullBlue = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Blue, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull cyan.
dullCyan :: Doc -> Doc
dullCyan = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Cyan, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull magenta.
dullMagenta :: Doc -> Doc
dullMagenta = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Magenta, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' dull black.
dullBlack :: Doc -> Doc
dullBlack = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Black, Dull),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid white.
vividWhite :: Doc -> Doc
vividWhite = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (White, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid red.
vividRed :: Doc -> Doc
vividRed = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Red, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid yellow.
vividYellow :: Doc -> Doc
vividYellow = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Yellow, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid green.
vividGreen :: Doc -> Doc
vividGreen = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Green, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid blue.
vividBlue :: Doc -> Doc
vividBlue = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Blue, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid cyan.
vividCyan :: Doc -> Doc
vividCyan = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Cyan, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid magenta.
vividMagenta :: Doc -> Doc
vividMagenta = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Magenta, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc' vivid black.
vividBlack :: Doc -> Doc
vividBlack = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
foreground = Just (Black, Vivid),
background = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull white.
dullWhiteBackground :: Doc -> Doc
dullWhiteBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (White, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull red.
dullRedBackground :: Doc -> Doc
dullRedBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Red, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull yellow.
dullYellowBackground :: Doc -> Doc
dullYellowBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Yellow, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull green.
dullGreenBackground :: Doc -> Doc
dullGreenBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Green, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull blue.
dullBlueBackground :: Doc -> Doc
dullBlueBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Blue, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull cyan.
dullCyanBackground :: Doc -> Doc
dullCyanBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Cyan, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull magenta.
dullMagentaBackground :: Doc -> Doc
dullMagentaBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Magenta, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background dull black.
dullBlackBackground :: Doc -> Doc
dullBlackBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Black, Dull),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid white.
vividWhiteBackground :: Doc -> Doc
vividWhiteBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (White, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid red.
vividRedBackground :: Doc -> Doc
vividRedBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Red, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid yellow.
vividYellowBackground :: Doc -> Doc
vividYellowBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Yellow, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid green.
vividGreenBackground :: Doc -> Doc
vividGreenBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Green, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid blue.
vividBlueBackground :: Doc -> Doc
vividBlueBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Blue, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid cyan.
vividCyanBackground :: Doc -> Doc
vividCyanBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Cyan, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid magenta.
vividMagentaBackground :: Doc -> Doc
vividMagentaBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Magenta, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Color a 'Doc's background vivid black.
vividBlackBackground :: Doc -> Doc
vividBlackBackground = graphics Options { consoleIntensity = Nothing,
underlining = Nothing,
blinkSpeed = Nothing,
background = Just (Black, Vivid),
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Set the terminal to bold.
bold :: Doc -> Doc
bold = graphics Options { consoleIntensity = Just BoldIntensity,
underlining = Nothing,
blinkSpeed = Nothing,
background = Nothing,
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Unset the terminal from bold.
debold :: Doc -> Doc
debold = graphics Options { consoleIntensity = Just NormalIntensity,
underlining = Nothing,
blinkSpeed = Nothing,
background = Nothing,
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Unset the terminal from bold.
underline :: Doc -> Doc
underline = graphics Options { consoleIntensity = Nothing,
underlining = Just SingleUnderline,
blinkSpeed = Nothing,
background = Nothing,
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Unset the terminal from bold.
deunderline :: Doc -> Doc
deunderline = graphics Options { consoleIntensity = Nothing,
underlining = Just NoUnderline,
blinkSpeed = Nothing,
background = Nothing,
foreground = Nothing,
swapForegroundBackground = Nothing }
-- | Join two 'Doc's with a space in between them.
(<+>) :: Doc -> Doc -> Doc
left <+> right = concat [left, space, right]
-- | Join two 'Doc's with a 'hardline' in between them.
(<!>) :: Doc -> Doc -> Doc
left <!> right = concat [left, hardline, right]
-- | Join two 'Doc's with a 'line' in between them.
(<$>) :: Doc -> Doc -> Doc
left <$> right = concat [left, line, right]
-- | Join two 'Doc's with a 'linebreak' in between them.
(<$$>) :: Doc -> Doc -> Doc
left <$$> right = concat [left, linebreak, right]
-- | Join two 'Doc's with a 'softline' in between them.
(</>) :: Doc -> Doc -> Doc
left </> right = concat [left, softline, right]
-- | Join two 'Doc's with a 'softbreak' in between them.
(<//>) :: Doc -> Doc -> Doc
left <//> right = concat [left, softbreak, right]
-- | Joun 'Doc's with no space in between them.
beside :: Doc -> Doc -> Doc
beside Cat { catDocs = left } Cat { catDocs = right } =
Cat { catDocs = left ++ right }
beside left Cat { catDocs = right } = Cat { catDocs = left : right }
beside Cat { catDocs = left } right = Cat { catDocs = left ++ [right] }
beside left right = Cat { catDocs = [left, right] }
-- | Concatenate a list of 'Doc's. This is generally more efficient
-- than repeatedly using 'beside' or '<>'.
concat :: [Doc] -> Doc
concat docs = Cat { catDocs = docs }
-- | A choice of several options. Only one of these will be chosen
-- and used to render the final document.
choose :: [Doc] -> Doc
choose [] = empty
choose [doc] = doc
choose docs = Choose { chooseOptions = docs }
-- | Concatenate a list of 'Doc's. This is generally more efficient
-- than repeatedly using 'beside' or '<>'.
hcat :: [Doc] -> Doc
hcat docs = Cat { catDocs = docs }
-- | Join a list of 'Doc's with spaces in between each. This is
-- generally more efficient than repeatedly using '<+>'.
hsep :: [Doc] -> Doc
hsep = concat . intersperse space
-- | Join a list of 'Doc's with 'line's in between each. This is
-- generally more efficient than repeatedly using '<$$>'.
vsep :: [Doc] -> Doc
vsep = concat . intersperse line
-- | Join a list of 'Doc's with 'linebreak's in between each. This is
-- generally more efficient than repeatedly using '<$>'.
vcat :: [Doc] -> Doc
vcat = concat . intersperse linebreak
-- | Join a list of 'Doc's using either 'hsep' or 'vsep'.
sep :: [Doc] -> Doc
sep docs = Choose { chooseOptions = [hsep docs, vsep docs] }
-- | Join a list of 'Doc's using either 'hcat' or 'vcat'.
cat :: [Doc] -> Doc
cat docs = Choose { chooseOptions = [hcat docs, vcat docs] }
-- | Join a list of 'Doc's with 'softline's in between each. This is
-- generally more efficient than repeatedly using '</>'.
fillSep :: [Doc] -> Doc
fillSep = concat . intersperse softline
-- | Join a list of 'Doc's with 'softbreak's in between each. This is
-- generally more efficient than repeatedly using '<//>'.
fillCat :: [Doc] -> Doc
fillCat = concat . intersperse softbreak
-- | Enclose a 'Doc' within two other 'Doc's
enclose :: Doc -> Doc -> Doc -> Doc
enclose left right middle = hcat [left, middle, right]
-- | Concatenate a list of 'Doc's into a single doc, with each element
-- separated from the others by a given 'Doc' representing
-- punctuation.
punctuate :: Doc -> [Doc] -> [Doc]
punctuate punc (first : rest @ (_ : _)) = first <> punc : punctuate punc rest
punctuate _ doc = doc
-- | Enclose a list of 'Doc's, separated by punctuation, and align
-- nesting of the contents to the end of the left enclosing 'Doc'
encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc
encloseSep left right _ [] = left <> right
encloseSep left right _ [doc] = left <> doc <> right
encloseSep left right middle docs =
left <> align (concat (punctuate middle docs)) <> right
-- | Render a list, enclosed in brackets and separated by commas.
list :: [Doc] -> Doc
list = group . encloseSep lbrack rbrack (comma <> line)
-- | Erase all linebreaks in a 'Doc' and replace them with either
-- spaces or nothing, depending on the kind of linebreak.
flatten :: Doc -> Maybe Doc
flatten Line { lineKind = Hard } = Nothing
flatten Line { lineKind = Break } = Just Char { charContent = ' ' }
flatten Line { lineKind = Soft } = Just empty
flatten Cat { catDocs = docs } =
case mapMaybe flatten docs of
[] -> Nothing
flatinner -> Just Cat { catDocs = flatinner }
flatten Choose { chooseOptions = docs } =
case mapMaybe flatten docs of
[] -> Nothing
flatdocs -> Just Choose { chooseOptions = flatdocs }
flatten n @ Nest { nestDoc = inner } =
do
flatinner <- flatten inner
return n { nestDoc = flatinner }
flatten doc = Just doc
-- | A 'Doc' that 'choose's between the unmodified argument, or the
-- 'flatten'ed version of the argument.
group :: Doc -> Doc
group doc = case flatten doc of
Just flatdoc -> Choose { chooseOptions = [ doc, flatdoc ] }
Nothing -> doc
-- | Produce a 'Builder' that renders the 'Doc' to one line.
buildOneLine :: Doc -> Builder
buildOneLine Char { charContent = chr } = fromChar chr
buildOneLine Content { contentString = builder } = fromLazyByteString builder
buildOneLine Line { lineKind = Break } = fromChar ' '
buildOneLine Line { lineKind = Soft } = mempty
buildOneLine Line { lineKind = Hard } = fromChar '\n'
buildOneLine Cat { catDocs = docs } = mconcat (map buildOneLine docs)
buildOneLine Nest { nestDoc = inner } = buildOneLine inner
buildOneLine Choose { chooseOptions = opts } = buildOneLine (head opts)
buildOneLine Graphics { graphicsDoc = inner } = buildOneLine inner
-- | Render the entire 'Doc' to one line. Good for output that
-- will be read only by a machine, where newlines are not important at all
renderOneLine :: Doc -> Lazy.ByteString
renderOneLine = toLazyByteString . buildOneLine
-- | Output the entire 'Doc', as rendered by 'renderOneLine' to the
-- given 'Handle'.
putOneLine :: Handle -> Doc -> IO ()
putOneLine handle =
toByteStringIO (Strict.hPut handle) . buildOneLine
-- | Produce a 'Builder' that renders the 'Doc' quickly.
buildFast :: Doc -> Builder
buildFast Char { charContent = chr } = fromChar chr
buildFast Content { contentString = builder } = fromLazyByteString builder
buildFast Line {} = fromChar '\n'
buildFast Cat { catDocs = docs } = mconcat (map buildFast docs)
buildFast Nest { nestDoc = inner } = buildFast inner
buildFast Choose { chooseOptions = opts } = buildFast (head opts)
buildFast Graphics { graphicsDoc = inner } = buildFast inner
-- | Render the entire 'Doc', preserving newlines, but without any
-- indentation. Good for output that will be read only by machine,
-- but where newlines matter.
renderFast :: Doc -> Lazy.ByteString
renderFast = toLazyByteString . buildFast
-- | Output the entire 'Doc', as rendered by 'renderFast' to the
-- given 'Handle'.
putFast :: Handle -> Doc -> IO ()
putFast handle =
toByteStringIO (Strict.hPut handle) . buildFast
-- | A description of the ending.
data Ending =
-- | Ended with a newline, so do a full indent.
Indent
-- | Ended with normal content, so no indent.
| None
deriving (Eq, Show)
-- | A rendering of a document.
data Render =
Render {
-- | Number of extra spaces to generate.
renderNesting :: !Int,
-- | Width: Number of columns at the widest point in the complete
-- lines.
renderWidth :: !Int,
-- | Ending line fragment width.
renderEndWidth :: !Int,
-- | The number of lines in the document.
renderLines :: !Word,
-- | A builder that constructs the document.
renderBuilder :: Builder,
-- | Indentation mode for the next document.
renderEnding :: !Ending,
-- | Finish function. Allows for resetting of some state when
-- done with an inner document.
renderFinish :: !(Render -> Render)
}
instance Show Render where
show Render { renderWidth = mwidth, renderEndWidth = ewidth,
renderLines = lns, renderBuilder = builder,
renderEnding = end, renderNesting = nesting } =
"Render { renderNesting = " ++ show nesting ++
", renderWidth = " ++ show mwidth ++
", renderEndWidth = " ++ show ewidth ++
", renderLines = " ++ show lns ++
", renderEnding = " ++ show end ++
", renderBuilder = " ++ show (toLazyByteString builder) ++
" }"
-- | Determine whether the first 'Render' is strictly better than the second.
subsumes :: Render -> Render -> Bool
-- Simple comparisons: if the width is subsumed and the lines are less
subsumes Render { renderWidth = width1, renderLines = lines1,
renderEndWidth = ewidth1 }
Render { renderWidth = width2, renderLines = lines2,
renderEndWidth = ewidth2 }=
lines1 <= lines2 && width1 <= width2 && ewidth1 <= ewidth2
newtype Frontier = Frontier { frontierRenders :: [Render] }
deriving Show
instance Monoid Frontier where
mempty = Frontier { frontierRenders = [] }
mappend front1 @ Frontier { frontierRenders = renders1 }
front2 @ Frontier { frontierRenders = renders2 } =
if length renders1 < length renders2
then foldl insertRender front2 renders1
else foldl insertRender front1 renders2
mapFrontier :: (Render -> Render) -> Frontier -> Frontier
mapFrontier func f @ Frontier { frontierRenders = renders } =
f { frontierRenders = map func renders }
-- Add a 'Render' into a result set, ensuring that any subsumed
-- renders are dropped.
--
-- TODO: The asymptotic runtime of this could likely be improved by some
-- kind of tree structure; however, the design of this structure is
-- nontrivial, due to the 3+-dimensional nature of subsumption, and
-- the wierd interactions between the various kinds of column offsets.
insertRender :: Frontier -> Render -> Frontier
insertRender Frontier { frontierRenders = renders } ins
-- If the inserted element is subsumed by anything in the
-- list, then don't insert it at all.
| any (`subsumes` ins) renders = Frontier { frontierRenders = renders }
-- Otherwise, add the element to the list, and drop everything it subsumes.
| otherwise =
Frontier { frontierRenders = ins : filter (not . subsumes ins) renders }
-- | A result. This is split into 'Single' and 'Multi' in order to
-- optimize for the common case of a single possible rendering.
-- Otherwise, it would be perfectly fine to represent everything as a
-- HashMap.
data Result =
-- | A single possible rendering.
Single {
-- | The rendered document.
singleRender :: !Render
}
-- | Multiple possible renderings.
| Multi {
-- | A multi-level map. The first map is indexed by the column
-- upper-bound (meaning the first column at which using any of
-- the contents will cause an overrun). The second map is
-- indexed by the ending column.
multiOptions :: !Frontier
}
deriving Show
mapResult :: (Render -> Render) -> Result -> Result
mapResult func Single { singleRender = render } =
Single { singleRender = func render }
mapResult func Multi { multiOptions = opts } =
Multi { multiOptions = mapFrontier func opts }
-- | Generate n spaces
makespaces :: Int -> Builder
makespaces n = fromLazyByteString (Lazy.Char8.replicate (fromIntegral n) ' ')
-- If a result only has one possibility, convert it to a Single.
-- Otherwise, leave it.
packResult :: Frontier -> Result
packResult Frontier { frontierRenders = [opt] } = Single { singleRender = opt }
packResult Frontier { frontierRenders = opts } =
Multi { multiOptions = Frontier { frontierRenders = opts } }
-- | Combine two results into a Multi. This achieves the same result
-- as HashMap.unionWith bestRender (meaning, union these maps,
-- combining using bestRender to pick when both maps have a given
-- index), but handles Singles as well.
mergeResults :: Result -> Result -> Result
-- Single is equivalent to a single-entry HashMap
mergeResults s1 @ Single { singleRender = r1 }
s2 @ Single { singleRender = r2 }
| subsumes r1 r2 = s1
| subsumes r2 r1 = s2
| otherwise = Multi { multiOptions = Frontier { frontierRenders = [r1, r2] } }
mergeResults Single { singleRender = render }
Multi { multiOptions = opts } =
packResult (insertRender opts render)
-- This operation is commutative
mergeResults m @ Multi {} s @ Single {} = mergeResults s m
-- Otherwise it's a straightaway HashMap union
mergeResults Multi { multiOptions = opts1 } Multi { multiOptions = opts2 } =
packResult (opts1 <> opts2)
-- | Produce a 'Builder' that renders the 'Doc' using the optimal
-- layout engine.
appendContent :: Int -> Builder -> Render -> Render
appendContent len content r @ Render { renderEnding = Indent,
renderNesting = lvl,
renderBuilder = builder,
renderEndWidth = ewidth } =
let
ind = max 0 (lvl - ewidth)
in
r { renderBuilder = builder <> makespaces ind <> content,
renderEnding = None, renderEndWidth = ewidth + ind + len }
appendContent len content r @ Render { renderBuilder = builder,
renderEndWidth = ewidth } =
r { renderBuilder = builder <> content,
renderEnding = None, renderEndWidth = ewidth + len }
appendLine :: Render -> Render
appendLine r @ Render { renderBuilder = builder, renderLines = l,
renderWidth = width, renderEndWidth = ewidth } =
r { renderBuilder = builder <> fromChar '\n', renderWidth = max width ewidth,
renderLines = l + 1, renderEnding = Indent, renderEndWidth = 0 }
-- | Core algorithm. Walks forward in the Doc, maintaining a dynamic
-- programming frontier consisting of all renders that aren't subsumed
-- by other renders (possibly with a limit on the size)
buildDynamic :: Maybe Int
-- ^ The maximum frontier size
-> Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> Builder
buildDynamic fsize maxcol ansiterm doc =
let
build :: Graphics -> Result -> [Doc] -> Result
build _ accum [] = mapResult (\r @ Render { renderFinish = f } -> f r) accum
build _ accum d
| debug ("build\n " ++ show accum ++ "\n " ++ show d ++ " =") False =
undefined
-- For content, append to the accumulated values and continue.
build sgr accum (Char { charContent = chr } : rest) =
let
withcontent = mapResult (appendContent 1 (fromChar chr)) accum
in
build sgr withcontent rest
build sgr accum (Content { contentString = txt,
contentLength = len } : rest) =
let
withcontent =
mapResult (appendContent len (fromLazyByteString txt)) accum
in
build sgr withcontent rest
build sgr accum (Line {} : rest) =
let
withcontent = mapResult appendLine accum
in
build sgr withcontent rest
-- Build the inner docs, then continue
build sgr accum (Cat { catDocs = docs } : rest) =
build sgr accum (docs ++ rest)
-- Non-aligning, delayed indent
build sgr accum (Nest { nestDelay = True, nestAlign = False,
nestDoc = inner, nestLevel = off } : rest) =
let
setNesting r @ Render { renderFinish = oldfinish,
renderNesting = lvl } =
let
finish r' = r' { renderNesting = lvl, renderFinish = oldfinish }
in
r { renderNesting = lvl + off, renderFinish = finish }
in
build sgr (build sgr (mapResult setNesting accum) [inner]) rest
-- Non-aligning, immediate indent
build sgr accum (Nest { nestDelay = False, nestAlign = False,
nestDoc = inner, nestLevel = off } : rest) =
let
setNesting r @ Render { renderFinish = oldfinish,
renderNesting = lvl } =
let
finish r' = r' { renderNesting = lvl, renderFinish = oldfinish }
in
r { renderNesting = lvl + off, renderFinish = finish,
renderEnding = Indent }
in
build sgr (build sgr (mapResult setNesting accum) [inner]) rest
-- Aligning, delayed indent
build sgr accum (Nest { nestDelay = True, nestAlign = True,
nestDoc = inner, nestLevel = off } : rest) =
let
setNesting r @ Render { renderFinish = oldfinish, renderNesting = lvl,
renderEndWidth = ewidth } =
let
finish r' = r' { renderNesting = lvl, renderFinish = oldfinish }
in
r { renderNesting = ewidth + off, renderFinish = finish }
in
build sgr (build sgr (mapResult setNesting accum) [inner]) rest
-- Aligning, immediate indent
build sgr accum (Nest { nestDelay = False, nestAlign = True,
nestDoc = inner, nestLevel = off } : rest) =
let
setNesting r @ Render { renderFinish = oldfinish, renderNesting = lvl,
renderEndWidth = ewidth } =
let
finish r' = r' { renderNesting = lvl, renderFinish = oldfinish }
in
r { renderNesting = ewidth + off, renderFinish = finish,
renderEnding = Indent }
in
build sgr (build sgr (mapResult setNesting accum) [inner]) rest
-- For choose, render each choice, then fold all the choices
-- together and combine them into a single frontier.
build sgr accum (Choose { chooseOptions = options } : rest) =
let
setRestore r @ Render { renderFinish = oldfinish } =
let
finish r' = r' { renderFinish = oldfinish }
in
r { renderFinish = finish }
withrestore = mapResult setRestore accum
-- Build up all the components
results = map (build sgr withrestore . (: [])) options
-- Now merge them into an minimal set of options
merged = foldl1 mergeResults results
-- Reduce the results by some amount
reduced = case fsize of
Just fsize' -> reduce fsize' merged
Nothing -> merged
in
build sgr reduced rest
-- For graphics, generate the control sequences before and after
-- the inner document.
build sgr1 accum (Graphics { graphicsDoc = inner,
graphicsSGR = sgr2 } : rest)
-- Only do graphics if the ansiterm flag is set.
| ansiterm =
let
appendControl :: Render -> Render
appendControl r @ Render { renderBuilder = builder,
renderFinish = oldfinish } =
let
finish r' @ Render { renderBuilder = builder' } =
r' { renderBuilder = builder' <> switchGraphics sgr2 sgr1,
renderFinish = oldfinish }
in
r { renderBuilder = builder <> switchGraphics sgr1 sgr2,
renderFinish = finish }
in
build sgr1 (build sgr2 (mapResult appendControl accum) [inner]) rest
-- Otherwise, skip it entirely
| otherwise = build sgr1 accum (inner : rest)
-- | Calculate the overrun of a width.
overrun :: Int -> Int
overrun col = max 0 (col - maxcol)
-- | Compare two Renders. Less than means better.
compareRenders Render { renderLines = lines1, renderWidth = width1,
renderEndWidth = ewidth1 }
Render { renderLines = lines2, renderWidth = width2,
renderEndWidth = ewidth2 } =
let
width1' = max width1 ewidth1
width2' = max width2 ewidth2
in case compare (overrun width1') (overrun width2') of
EQ -> compare lines1 lines2
out -> out
-- Pick the best result out of a set of results. Used at the end to
-- pick the final result.
bestRenderInOpts :: [Render] -> Render
bestRenderInOpts = minimumBy compareRenders
reduce :: Int -> Result -> Result
reduce _ s @ Single {} = s
reduce size Multi { multiOptions = Frontier { frontierRenders = opts } } =
let
sorted = sortBy compareRenders opts
in
Multi { multiOptions = Frontier { frontierRenders = take size sorted } }
start = Render { renderWidth = 0, renderEnding = Indent, renderLines = 0,
renderBuilder = mempty, renderFinish = id,
renderEndWidth = 0, renderNesting = 0 }
-- Call build, get the result, then pick the best one.
Render { renderBuilder = result } =
case build Default Single { singleRender = start } [doc] of
Single { singleRender = render } -> render
Multi { multiOptions = Frontier { frontierRenders = opts } } ->
bestRenderInOpts opts
in
result
-- | Render a 'Doc' as a 'Builder' using an optimal layout rendering
-- engine. The engine will render the document in the fewest number
-- of lines possible without exceeding the maximum column width.
buildOptimal :: Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> Builder
buildOptimal = buildDynamic Nothing
-- | Render a 'Doc' as a lazy bytestring using an optimal layout
-- rendering engine. The engine will render the document in the
-- fewest number of lines possible without exceeding the maximum
-- column width.
renderOptimal :: Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> Lazy.ByteString
renderOptimal cols color = toLazyByteString . buildOptimal cols color
-- | Output the entire 'Doc', as rendered by 'renderOptimal' to the
-- given 'Handle'.
putOptimal :: Handle
-- ^ The 'Handle' to which to write output
-> Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> IO ()
putOptimal handle cols color =
toByteStringIO (Strict.hPut handle) . buildOptimal cols color
-- | Render a 'Doc' as a 'Builder' using an optimal layout engine with
-- a constrained frontier size. Larger frontier sizes will result in
-- a better rendering, at the cost of more execution time. As the
-- frontier size increases, this algorithm's behavior will converge
-- towards 'renderOptimal'.
buildGreedy :: Word
-- ^ The maximum frontier size
-> Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> Builder
buildGreedy 0 = error "Frontier size cannot be zero"
buildGreedy fsize = buildDynamic $! Just $! fromIntegral fsize
-- | Render a 'Doc' as a lazy bytestring using an optimal layout engine with
-- a constrained frontier size. Larger frontier sizes will result in
-- a better rendering, at the cost of more execution time. As the
-- frontier size increases, this algorithm's behavior will converge
-- towards 'renderOptimal'.
renderGreedy :: Word
-- ^ The maximum frontier size
-> Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> Lazy.ByteString
renderGreedy fsize cols color = toLazyByteString . buildGreedy fsize cols color
-- | Output the entire 'Doc', as rendered by 'renderOptimal' to the
-- given 'Handle'.
putGreedy :: Handle
-- ^ The 'Handle' to which to write output
-> Word
-- ^ The maximum frontier size
-> Int
-- ^ The maximum number of columns.
-> Bool
-- ^ Whether or not to render with ANSI terminal options.
-> Doc
-- ^ The document to render.
-> IO ()
putGreedy handle fsize cols color =
toByteStringIO (Strict.hPut handle) . buildGreedy fsize cols color
-- | A class representing datatypes that can be formatted as 'Doc's.
class Format item where
-- | Format an @item@ as a 'Doc'
format :: item -> Doc
-- | Format a list of @item@s as a 'Doc'
formatList :: [item] -> Doc
formatList = list . map format
-- | A class representing datatypes that can be formatted as 'Doc's
-- inside a monad.
class Monad m => FormatM m item where
-- | Format an @item@ as a 'Doc' inside an @m@ monad
formatM :: item -> m Doc
-- | Format a list of @item@s as a 'Doc' inside an @m@ monad
formatListM :: [item] -> m Doc
formatListM = liftM list . mapM formatM
instance Format a => Format [a] where
format = formatList
instance Format Doc where
format = id
instance Format String where
format = string
instance Format Strict.ByteString where
format = bytestring
instance Format Lazy.ByteString where
format = lazyBytestring
instance Format Int where
format = string . show
instance Format Integer where
format = string . show
instance Format Word where
format = string . show
instance Format Float where
format = string . show
instance Format Double where
format = string . show
| saltlang/dynamic-pprint | src/Text/Format.hs | bsd-3-clause | 62,580 | 33 | 21 | 21,333 | 11,824 | 6,794 | 5,030 | 1,125 | 16 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "pure/Data/Aeson/Parser/UnescapePure.hs" #-}
-- WARNING: This file is security sensitive as it uses unsafeWrite which does
-- not check bounds. Any changes should be made with care and we would love to
-- get informed about them, just cc us in any PR targetting this file: @eskimor @jprider63
-- We would be happy to review the changes!
-- The security check at the end (pos > length) only works if pos grows
-- monotonously, if this condition does not hold, the check is flawed.
module Data.Aeson.Parser.UnescapePure
(
unescapeText
) where
import Control.Exception (evaluate, throw, try)
import Control.Monad (when)
import Data.ByteString as B
import Data.Bits (Bits, shiftL, shiftR, (.&.), (.|.))
import Data.Text (Text)
import qualified Data.Text.Array as A
import Data.Text.Encoding.Error (UnicodeException (..))
import Data.Text.Internal.Private (runText)
import Data.Text.Unsafe (unsafeDupablePerformIO)
import Data.Word (Word8, Word16, Word32)
import GHC.ST (ST)
-- Different UTF states.
data Utf =
UtfGround
| UtfTail1
| UtfU32e0
| UtfTail2
| UtfU32ed
| Utf843f0
| UtfTail3
| Utf843f4
deriving (Eq)
data State =
StateNone
| StateUtf !Utf !Word32
| StateBackslash
| StateU0
| StateU1 !Word16
| StateU2 !Word16
| StateU3 !Word16
| StateS0
| StateS1
| StateSU0
| StateSU1 !Word16
| StateSU2 !Word16
| StateSU3 !Word16
deriving (Eq)
-- References:
-- http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
-- https://github.com/jwilm/vte/blob/master/utf8parse/src/table.rs.in
setByte1 :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte1 point word = point .|. fromIntegral (word .&. 0x3f)
{-# INLINE setByte1 #-}
setByte2 :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte2 point word = point .|. (fromIntegral (word .&. 0x3f) `shiftL` 6)
{-# INLINE setByte2 #-}
setByte2Top :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte2Top point word = point .|. (fromIntegral (word .&. 0x1f) `shiftL` 6)
{-# INLINE setByte2Top #-}
setByte3 :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte3 point word = point .|. (fromIntegral (word .&. 0x3f) `shiftL` 12)
{-# INLINE setByte3 #-}
setByte3Top :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte3Top point word = point .|. (fromIntegral (word .&. 0xf) `shiftL` 12)
{-# INLINE setByte3Top #-}
setByte4 :: (Num a, Bits b, Bits a, Integral b) => a -> b -> a
setByte4 point word = point .|. (fromIntegral (word .&. 0x7) `shiftL` 18)
{-# INLINE setByte4 #-}
decode :: Utf -> Word32 -> Word8 -> (Utf, Word32)
decode UtfGround point word = case word of
w | 0x00 <= w && w <= 0x7f -> (UtfGround, fromIntegral word)
w | 0xc2 <= w && w <= 0xdf -> (UtfTail1, setByte2Top point word)
0xe0 -> (UtfU32e0, setByte3Top point word)
w | 0xe1 <= w && w <= 0xec -> (UtfTail2, setByte3Top point word)
0xed -> (UtfU32ed, setByte3Top point word)
w | 0xee <= w && w <= 0xef -> (UtfTail2, setByte3Top point word)
0xf0 -> (Utf843f0, setByte4 point word)
w | 0xf1 <= w && w <= 0xf3 -> (UtfTail3, setByte4 point word)
0xf4 -> (Utf843f4, setByte4 point word)
_ -> throwDecodeError
decode UtfU32e0 point word = case word of
w | 0xa0 <= w && w <= 0xbf -> (UtfTail1, setByte2 point word)
_ -> throwDecodeError
decode UtfU32ed point word = case word of
w | 0x80 <= w && w <= 0x9f -> (UtfTail1, setByte2 point word)
_ -> throwDecodeError
decode Utf843f0 point word = case word of
w | 0x90 <= w && w <= 0xbf -> (UtfTail2, setByte3 point word)
_ -> throwDecodeError
decode Utf843f4 point word = case word of
w | 0x80 <= w && w <= 0x8f -> (UtfTail2, setByte3 point word)
_ -> throwDecodeError
decode UtfTail3 point word = case word of
w | 0x80 <= w && w <= 0xbf -> (UtfTail2, setByte3 point word)
_ -> throwDecodeError
decode UtfTail2 point word = case word of
w | 0x80 <= w && w <= 0xbf -> (UtfTail1, setByte2 point word)
_ -> throwDecodeError
decode UtfTail1 point word = case word of
w | 0x80 <= w && w <= 0xbf -> (UtfGround, setByte1 point word)
_ -> throwDecodeError
{-# INLINE decode #-}
decodeHex :: Word8 -> Word16
decodeHex 48 = 0 -- '0'
decodeHex 49 = 1 -- '1'
decodeHex 50 = 2 -- '2'
decodeHex 51 = 3 -- '3'
decodeHex 52 = 4 -- '4'
decodeHex 53 = 5 -- '5'
decodeHex 54 = 6 -- '6'
decodeHex 55 = 7 -- '7'
decodeHex 56 = 8 -- '8'
decodeHex 57 = 9 -- '9'
decodeHex 65 = 10 -- 'A'
decodeHex 97 = 10 -- 'a'
decodeHex 66 = 11 -- 'B'
decodeHex 98 = 11 -- 'b'
decodeHex 67 = 12 -- 'C'
decodeHex 99 = 12 -- 'c'
decodeHex 68 = 13 -- 'D'
decodeHex 100 = 13 -- 'd'
decodeHex 69 = 14 -- 'E'
decodeHex 101 = 14 -- 'e'
decodeHex 70 = 15 -- 'F'
decodeHex 102 = 15 -- 'f'
decodeHex _ = throwDecodeError
{-# INLINE decodeHex #-}
unescapeText' :: ByteString -> Text
unescapeText' bs = runText $ \done -> do
dest <- A.new len
(pos, finalState) <- B.foldl' (f' dest) (return (0, StateNone)) bs
-- Check final state. Currently pos gets only increased over time, so this check should catch overflows.
when ( finalState /= StateNone || pos > len)
throwDecodeError
done dest pos -- TODO: pos, pos-1??? XXX
where
len = B.length bs
runUtf dest pos st point c = case decode st point c of
(UtfGround, 92) -> -- Backslash
return (pos, StateBackslash)
(UtfGround, w) | w <= 0xffff ->
writeAndReturn dest pos (fromIntegral w) StateNone
(UtfGround, w) -> do
write dest pos (0xd7c0 + fromIntegral (w `shiftR` 10))
writeAndReturn dest (pos + 1) (0xdc00 + fromIntegral (w .&. 0x3ff)) StateNone
(st', p) ->
return (pos, StateUtf st' p)
{-# INLINE runUtf #-}
f' dest m c = m >>= \s -> f dest s c
{-# INLINE f' #-}
-- No pending state.
f dest (pos, StateNone) c = runUtf dest pos UtfGround 0 c
-- In the middle of parsing a UTF string.
f dest (pos, StateUtf st point) c = runUtf dest pos st point c
-- In the middle of escaping a backslash.
f dest (pos, StateBackslash) 34 = writeAndReturn dest pos 34 StateNone -- "
f dest (pos, StateBackslash) 92 = writeAndReturn dest pos 92 StateNone -- Backslash
f dest (pos, StateBackslash) 47 = writeAndReturn dest pos 47 StateNone -- /
f dest (pos, StateBackslash) 98 = writeAndReturn dest pos 8 StateNone -- b
f dest (pos, StateBackslash) 102 = writeAndReturn dest pos 12 StateNone -- f
f dest (pos, StateBackslash) 110 = writeAndReturn dest pos 10 StateNone -- n
f dest (pos, StateBackslash) 114 = writeAndReturn dest pos 13 StateNone -- r
f dest (pos, StateBackslash) 116 = writeAndReturn dest pos 9 StateNone -- t
f _ (pos, StateBackslash) 117 = return (pos, StateU0) -- u
f _ ( _, StateBackslash) _ = throwDecodeError
-- Processing '\u'.
f _ (pos, StateU0) c =
let w = decodeHex c in
return (pos, StateU1 (w `shiftL` 12))
f _ (pos, StateU1 w') c =
let w = decodeHex c in
return (pos, StateU2 (w' .|. (w `shiftL` 8)))
f _ (pos, StateU2 w') c =
let w = decodeHex c in
return (pos, StateU3 (w' .|. (w `shiftL` 4)))
f dest (pos, StateU3 w') c =
let w = decodeHex c in
let u = w' .|. w in
-- Get next state based on surrogates.
let st
| u >= 0xd800 && u <= 0xdbff = -- High surrogate.
StateS0
| u >= 0xdc00 && u <= 0xdfff = -- Low surrogate.
throwDecodeError
| otherwise =
StateNone
in
writeAndReturn dest pos u st
-- Handle surrogates.
f _ (pos, StateS0) 92 = return (pos, StateS1) -- Backslash
f _ ( _, StateS0) _ = throwDecodeError
f _ (pos, StateS1) 117 = return (pos, StateSU0) -- u
f _ ( _, StateS1) _ = throwDecodeError
f _ (pos, StateSU0) c =
let w = decodeHex c in
return (pos, StateSU1 (w `shiftL` 12))
f _ (pos, StateSU1 w') c =
let w = decodeHex c in
return (pos, StateSU2 (w' .|. (w `shiftL` 8)))
f _ (pos, StateSU2 w') c =
let w = decodeHex c in
return (pos, StateSU3 (w' .|. (w `shiftL` 4)))
f dest (pos, StateSU3 w') c =
let w = decodeHex c in
let u = w' .|. w in
-- Check if not low surrogate.
if u < 0xdc00 || u > 0xdfff then
throwDecodeError
else
writeAndReturn dest pos u StateNone
{-# INLINE f #-}
write :: A.MArray s -> Int -> Word16 -> ST s ()
write dest pos char =
A.unsafeWrite dest pos char
{-# INLINE write #-}
writeAndReturn :: A.MArray s -> Int -> Word16 -> t -> ST s (Int, t)
writeAndReturn dest pos char res = do
write dest pos char
return (pos + 1, res)
{-# INLINE writeAndReturn #-}
throwDecodeError :: a
throwDecodeError =
let desc = "Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream" in
throw (DecodeError desc Nothing)
{-# INLINE throwDecodeError #-}
unescapeText :: ByteString -> Either UnicodeException Text
unescapeText = unsafeDupablePerformIO . try . evaluate . unescapeText'
{-# INLINE unescapeText #-}
| phischu/fragnix | tests/packages/scotty/Data.Aeson.Parser.UnescapePure.hs | bsd-3-clause | 9,616 | 0 | 20 | 2,791 | 3,140 | 1,668 | 1,472 | 224 | 28 |
{- | Module : $Header$
- Description : Implementation of logic instance of disjoint union of features
- Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : [email protected]
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the matching functions of disjoint union of features.
-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module GMP.Logics.DisjUnion where
import Data.List
import Data.Ratio
import Data.Maybe
import Debug.Trace
import Text.ParserCombinators.Parsec
import GMP.Logics.Generic
import GMP.Parser
{- ------------------------------------------------------------------------------
instance of feature for Disjoint union of features
------------------------------------------------------------------------------ -}
data DisjUnion a b c = DisjUnion (a c, b c) deriving (Eq, Ord, Show)
instance (Feature a (c (d e)), Feature b (c (d e)), Eq (a (c (d e))),
Eq (b (c (d e))), SigFeature c d e, Eq (d e)) =>
NonEmptyFeature (DisjUnion a b) c d e where
nefMatch flags seq =
let fstposlits = [ Mod p | Mod (DisjUnion (p, q)) <- seq ]
fstneglits = [ Neg (Mod p) | Neg (Mod (DisjUnion (p, q))) <- seq ]
sndposlits = [ Mod q | Mod (DisjUnion (p, q)) <- seq ]
sndneglits = [ Neg (Mod q) | Neg (Mod (DisjUnion (p, q))) <- seq ]
in if flags !! 1
then trace ("\n [+-matching this:] " ++ pretty_list seq) $
[[Sequent (fstposlits ++ fstneglits)]] :
[[[Sequent (sndposlits ++ sndneglits)]]]
else [[Sequent (fstposlits ++ fstneglits)]] :
[[[Sequent (sndposlits ++ sndneglits)]]]
nefPretty d = case d of
DisjUnion (p, q) -> "[DisjUnion](" ++ fPretty p ++ fPretty q ++ ")"
nefDisj2Conj (Mod (DisjUnion (p, q))) =
Mod (DisjUnion ((\ (Mod phi) -> phi) (fDisj2Conj (Mod p)),
(\ (Mod phi) -> phi) (fDisj2Conj (Mod q))))
nefNegNorm (Mod (DisjUnion (p, q))) =
Mod (DisjUnion ((\ (Mod phi) -> phi) (fNegNorm (Mod p)),
(\ (Mod phi) -> phi) (fNegNorm (Mod q))))
nefFeatureFromSignature (DisjUnion (p, q)) phi =
DisjUnion (fFeatureFromSignature p phi,
fFeatureFromSignature q phi)
nefStripFeature (DisjUnion (p, q)) = fStripFeature p
nefParser (DisjUnion (p, q)) = return (\ (phi : psi : _) ->
DisjUnion (fFeatureFromSignature p [phi],
fFeatureFromSignature q [psi]))
nefSeparator sig = "+"
nefFeatureFromFormula = error $ "nefFeatureFromFormula is not implemented " ++
"for instance NonEmptyFeature (DisjUnion a b) c d e"
{- ------------------------------------------------------------------------------
instance of sigFeature for disjoint union of features
------------------------------------------------------------------------------ -}
instance (Eq (b (c (d e))), Eq (a (c (d e))), Feature b (c (d e)), Feature a (c (d e)),
SigFeature c d e, Eq (d e)) => NonEmptySigFeature (DisjUnion a b) c d e where
neGoOn = genericPGoOn
| keithodulaigh/Hets | GMP/GMP-CoLoSS/GMP/Logics/DisjUnion.hs | gpl-2.0 | 3,217 | 0 | 18 | 730 | 1,040 | 549 | 491 | 45 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module ApiAnnotation (
getAnnotation, getAndRemoveAnnotation,
getAnnotationComments,getAndRemoveAnnotationComments,
ApiAnns,
ApiAnnKey,
AnnKeywordId(..),
AnnotationComment(..),
IsUnicodeSyntax(..),
unicodeAnn,
HasE(..),
LRdrName -- Exists for haddocks only
) where
import RdrName
import Outputable
import SrcLoc
import qualified Data.Map as Map
import Data.Data
{-
Note [Api annotations]
~~~~~~~~~~~~~~~~~~~~~~
In order to do source to source conversions using the GHC API, the
locations of all elements of the original source needs to be tracked.
This includes keywords such as 'let' / 'in' / 'do' etc as well as
punctuation such as commas and braces, and also comments.
These are captured in a structure separate from the parse tree, and
returned in the pm_annotations field of the ParsedModule type.
The non-comment annotations are stored indexed to the SrcSpan of the
AST element containing them, together with a AnnKeywordId value
identifying the specific keyword being captured.
> type ApiAnnKey = (SrcSpan,AnnKeywordId)
>
> Map.Map ApiAnnKey SrcSpan
So
> let x = 1 in 2 *x
would result in the AST element
L span (HsLet (binds for x = 1) (2 * x))
and the annotations
(span,AnnLet) having the location of the 'let' keyword
(span,AnnIn) having the location of the 'in' keyword
The comments are indexed to the SrcSpan of the lowest AST element
enclosing them
> Map.Map SrcSpan [Located AnnotationComment]
So the full ApiAnns type is
> type ApiAnns = ( Map.Map ApiAnnKey SrcSpan
> , Map.Map SrcSpan [Located AnnotationComment])
This is done in the lexer / parser as follows.
The PState variable in the lexer has the following variables added
> annotations :: [(ApiAnnKey,[SrcSpan])],
> comment_q :: [Located AnnotationComment],
> annotations_comments :: [(SrcSpan,[Located AnnotationComment])]
The first and last store the values that end up in the ApiAnns value
at the end via Map.fromList
The comment_q captures comments as they are seen in the token stream,
so that when they are ready to be allocated via the parser they are
available.
The parser interacts with the lexer using the function
> addAnnotation :: SrcSpan -> AnnKeywordId -> SrcSpan -> P ()
which takes the AST element SrcSpan, the annotation keyword and the
target SrcSpan.
This adds the annotation to the `annotations` field of `PState` and
transfers any comments in `comment_q` to the `annotations_comments`
field.
Parser
------
The parser implements a number of helper types and methods for the
capture of annotations
> type AddAnn = (SrcSpan -> P ())
>
> mj :: AnnKeywordId -> Located e -> (SrcSpan -> P ())
> mj a l = (\s -> addAnnotation s a (gl l))
AddAnn represents the addition of an annotation a to a provided
SrcSpan, and `mj` constructs an AddAnn value.
> ams :: Located a -> [AddAnn] -> P (Located a)
> ams a@(L l _) bs = (mapM_ (\a -> a l) bs) >> return a
So the production in Parser.y for the HsLet AST element is
| 'let' binds 'in' exp {% ams (sLL $1 $> $ HsLet (snd $ unLoc $2) $4)
(mj AnnLet $1:mj AnnIn $3
:(fst $ unLoc $2)) }
This adds an AnnLet annotation for 'let', an AnnIn for 'in', as well
as any annotations that may arise in the binds. This will include open
and closing braces if they are used to delimit the let expressions.
The wiki page describing this feature is
https://ghc.haskell.org/trac/ghc/wiki/ApiAnnotations
-}
-- ---------------------------------------------------------------------
type ApiAnns = ( Map.Map ApiAnnKey [SrcSpan]
, Map.Map SrcSpan [Located AnnotationComment])
type ApiAnnKey = (SrcSpan,AnnKeywordId)
-- | Retrieve a list of annotation 'SrcSpan's based on the 'SrcSpan'
-- of the annotated AST element, and the known type of the annotation.
getAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId -> [SrcSpan]
getAnnotation (anns,_) span ann
= case Map.lookup (span,ann) anns of
Nothing -> []
Just ss -> ss
-- | Retrieve a list of annotation 'SrcSpan's based on the 'SrcSpan'
-- of the annotated AST element, and the known type of the annotation.
-- The list is removed from the annotations.
getAndRemoveAnnotation :: ApiAnns -> SrcSpan -> AnnKeywordId
-> ([SrcSpan],ApiAnns)
getAndRemoveAnnotation (anns,cs) span ann
= case Map.lookup (span,ann) anns of
Nothing -> ([],(anns,cs))
Just ss -> (ss,(Map.delete (span,ann) anns,cs))
-- |Retrieve the comments allocated to the current 'SrcSpan'
--
-- Note: A given 'SrcSpan' may appear in multiple AST elements,
-- beware of duplicates
getAnnotationComments :: ApiAnns -> SrcSpan -> [Located AnnotationComment]
getAnnotationComments (_,anns) span =
case Map.lookup span anns of
Just cs -> cs
Nothing -> []
-- |Retrieve the comments allocated to the current 'SrcSpan', and
-- remove them from the annotations
getAndRemoveAnnotationComments :: ApiAnns -> SrcSpan
-> ([Located AnnotationComment],ApiAnns)
getAndRemoveAnnotationComments (anns,canns) span =
case Map.lookup span canns of
Just cs -> (cs,(anns,Map.delete span canns))
Nothing -> ([],(anns,canns))
-- --------------------------------------------------------------------
-- | API Annotations exist so that tools can perform source to source
-- conversions of Haskell code. They are used to keep track of the
-- various syntactic keywords that are not captured in the existing
-- AST.
--
-- The annotations, together with original source comments are made
-- available in the @'pm_annotations'@ field of @'GHC.ParsedModule'@.
-- Comments are only retained if @'Opt_KeepRawTokenStream'@ is set in
-- @'DynFlags.DynFlags'@ before parsing.
--
-- The wiki page describing this feature is
-- https://ghc.haskell.org/trac/ghc/wiki/ApiAnnotations
--
-- Note: in general the names of these are taken from the
-- corresponding token, unless otherwise noted
-- See note [Api annotations] above for details of the usage
data AnnKeywordId
= AnnAs
| AnnAt
| AnnBang -- ^ '!'
| AnnBackquote -- ^ '`'
| AnnBy
| AnnCase -- ^ case or lambda case
| AnnClass
| AnnClose -- ^ '\#)' or '\#-}' etc
| AnnCloseC -- ^ '}'
| AnnCloseP -- ^ ')'
| AnnCloseS -- ^ ']'
| AnnColon
| AnnComma -- ^ as a list separator
| AnnCommaTuple -- ^ in a RdrName for a tuple
| AnnDarrow -- ^ '=>'
| AnnDarrowU -- ^ '=>', unicode variant
| AnnData
| AnnDcolon -- ^ '::'
| AnnDcolonU -- ^ '::', unicode variant
| AnnDefault
| AnnDeriving
| AnnDo
| AnnDot -- ^ '.'
| AnnDotdot -- ^ '..'
| AnnElse
| AnnEqual
| AnnExport
| AnnFamily
| AnnForall
| AnnForallU -- ^ Unicode variant
| AnnForeign
| AnnFunId -- ^ for function name in matches where there are
-- multiple equations for the function.
| AnnGroup
| AnnHeader -- ^ for CType
| AnnHiding
| AnnIf
| AnnImport
| AnnIn
| AnnInfix -- ^ 'infix' or 'infixl' or 'infixr'
| AnnInstance
| AnnLam
| AnnLarrow -- ^ '<-'
| AnnLarrowU -- ^ '<-', unicode variant
| AnnLet
| AnnMdo
| AnnMinus -- ^ '-'
| AnnModule
| AnnNewtype
| AnnName -- ^ where a name loses its location in the AST, this carries it
| AnnOf
| AnnOpen -- ^ '(\#' or '{-\# LANGUAGE' etc
| AnnOpenC -- ^ '{'
| AnnOpenE -- ^ '[e|' or '[e||'
| AnnOpenP -- ^ '('
| AnnOpenPE -- ^ '$('
| AnnOpenPTE -- ^ '$$('
| AnnOpenS -- ^ '['
| AnnPackageName
| AnnPattern
| AnnProc
| AnnQualified
| AnnRarrow -- ^ '->'
| AnnRarrowU -- ^ '->', unicode variant
| AnnRec
| AnnRole
| AnnSafe
| AnnSemi -- ^ ';'
| AnnSimpleQuote -- ^ '''
| AnnStatic -- ^ 'static'
| AnnThen
| AnnThIdSplice -- ^ '$'
| AnnThIdTySplice -- ^ '$$'
| AnnThTyQuote -- ^ double '''
| AnnTilde -- ^ '~'
| AnnTildehsh -- ^ '~#'
| AnnType
| AnnUnit -- ^ '()' for types
| AnnUsing
| AnnVal -- ^ e.g. INTEGER
| AnnValStr -- ^ String value, will need quotes when output
| AnnVbar -- ^ '|'
| AnnWhere
| Annlarrowtail -- ^ '-<'
| AnnlarrowtailU -- ^ '-<', unicode variant
| Annrarrowtail -- ^ '->'
| AnnrarrowtailU -- ^ '->', unicode variant
| AnnLarrowtail -- ^ '-<<'
| AnnLarrowtailU -- ^ '-<<', unicode variant
| AnnRarrowtail -- ^ '>>-'
| AnnRarrowtailU -- ^ '>>-', unicode variant
| AnnEofPos
deriving (Eq, Ord, Data, Typeable, Show)
instance Outputable AnnKeywordId where
ppr x = text (show x)
-- ---------------------------------------------------------------------
data AnnotationComment =
-- Documentation annotations
AnnDocCommentNext String -- ^ something beginning '-- |'
| AnnDocCommentPrev String -- ^ something beginning '-- ^'
| AnnDocCommentNamed String -- ^ something beginning '-- $'
| AnnDocSection Int String -- ^ a section heading
| AnnDocOptions String -- ^ doc options (prune, ignore-exports, etc)
| AnnDocOptionsOld String -- ^ doc options declared "-- # ..."-style
| AnnLineComment String -- ^ comment starting by "--"
| AnnBlockComment String -- ^ comment in {- -}
deriving (Eq, Ord, Data, Typeable, Show)
-- Note: these are based on the Token versions, but the Token type is
-- defined in Lexer.x and bringing it in here would create a loop
instance Outputable AnnotationComment where
ppr x = text (show x)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnTildehsh',
-- 'ApiAnnotation.AnnTilde'
-- - May have 'ApiAnnotation.AnnComma' when in a list
type LRdrName = Located RdrName
-- | Certain tokens can have alternate representations when unicode syntax is
-- enabled. This flag is attached to those tokens in the lexer so that the
-- original source representation can be reproduced in the corresponding
-- 'ApiAnnotation'
data IsUnicodeSyntax = UnicodeSyntax | NormalSyntax
deriving (Eq, Ord, Data, Typeable, Show)
-- | Convert a normal annotation into its unicode equivalent one
unicodeAnn :: AnnKeywordId -> AnnKeywordId
unicodeAnn AnnForall = AnnForallU
unicodeAnn AnnDcolon = AnnDcolonU
unicodeAnn AnnLarrow = AnnLarrowU
unicodeAnn AnnRarrow = AnnRarrowU
unicodeAnn AnnDarrow = AnnDarrowU
unicodeAnn Annlarrowtail = AnnlarrowtailU
unicodeAnn Annrarrowtail = AnnrarrowtailU
unicodeAnn AnnLarrowtail = AnnLarrowtailU
unicodeAnn AnnRarrowtail = AnnRarrowtailU
unicodeAnn ann = ann
-- | Some template haskell tokens have two variants, one with an `e` the other
-- not:
--
-- > [| or [e|
-- > [|| or [e||
--
-- This type indicates whether the 'e' is present or not.
data HasE = HasE | NoE
deriving (Eq, Ord, Data, Typeable, Show)
| nushio3/ghc | compiler/parser/ApiAnnotation.hs | bsd-3-clause | 11,033 | 0 | 11 | 2,517 | 1,174 | 731 | 443 | 165 | 2 |
-- GSoC 2015 - Haskell bindings for OpenCog.
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DataKinds #-}
-- | This Module defines the main functions to interact with the Pattern Matcher.
module OpenCog.AtomSpace.Query (
cogBind
) where
import Control.Monad.IO.Class (liftIO)
import Foreign.C.Types (CULong(..))
import OpenCog.AtomSpace.Api (getByUUID,getWithUUID)
import OpenCog.AtomSpace.Internal (fromRawGen,toRaw,UUID)
import OpenCog.AtomSpace.Types (AtomGen,Atom)
import OpenCog.AtomSpace.AtomType (AtomType(BindT))
import OpenCog.AtomSpace.Env (AtomSpaceRef(..),AtomSpace,getAtomSpace)
--------------------------------------------------------------------------------
foreign import ccall "PatternMatcher_BindLink"
c_pmatcher_bindlink :: AtomSpaceRef
-> UUID
-> IO UUID
-- | 'cogBind' calls the pattern matcher with the given bindLink.
-- (you should insert the bindlink to the atomspace before using this function).
cogBind :: Atom BindT -> AtomSpace (Maybe AtomGen)
cogBind at = do
m <- getWithUUID $ toRaw at
case m of
Just (_,handle) -> do
asRef <- getAtomSpace
handleRes <- liftIO $ c_pmatcher_bindlink asRef handle
mraw <- getByUUID handleRes
return $ mraw >>= fromRawGen
Nothing -> return Nothing
| UIKit0/atomspace | opencog/haskell/OpenCog/AtomSpace/Query.hs | agpl-3.0 | 1,396 | 0 | 14 | 321 | 268 | 152 | 116 | 25 | 2 |
{-# LANGUAGE TypeApplications #-}
module T11313 where
x = fmap @(*)
-- test error message output, which was quite silly before
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/T11313.hs | bsd-3-clause | 130 | 0 | 7 | 24 | 19 | 12 | 7 | -1 | -1 |
{-# LANGUAGE CPP, GADTs, UnboxedTuples #-}
-----------------------------------------------------------------------------
--
-- Monad for Stg to C-- code generation
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
module StgCmmMonad (
FCode, -- type
initC, runC, thenC, thenFC, listCs,
returnFC, fixC,
newUnique, newUniqSupply,
newLabelC, emitLabel,
emit, emitDecl, emitProc,
emitProcWithConvention, emitProcWithStackFrame,
emitOutOfLine, emitAssign, emitStore, emitComment,
emitTick, emitUnwind,
getCmm, aGraphToGraph,
getCodeR, getCode, getCodeScoped, getHeapUsage,
mkCmmIfThenElse, mkCmmIfThen, mkCmmIfGoto,
mkCall, mkCmmCall,
forkClosureBody, forkLneBody, forkAlts, codeOnly,
ConTagZ,
Sequel(..), ReturnKind(..),
withSequel, getSequel,
setTickyCtrLabel, getTickyCtrLabel,
tickScope, getTickScope,
withUpdFrameOff, getUpdFrameOff, initUpdFrameOff,
HeapUsage(..), VirtualHpOffset, initHpUsage,
getHpUsage, setHpUsage, heapHWM,
setVirtHp, getVirtHp, setRealHp,
getModuleName,
-- ideally we wouldn't export these, but some other modules access internal state
getState, setState, getSelfLoop, withSelfLoop, getInfoDown, getDynFlags, getThisPackage,
-- more localised access to monad state
CgIdInfo(..),
getBinds, setBinds,
-- out of general friendliness, we also export ...
CgInfoDownwards(..), CgState(..) -- non-abstract
) where
#include "HsVersions.h"
import Cmm
import StgCmmClosure
import DynFlags
import Hoopl
import Maybes
import MkGraph
import BlockId
import CLabel
import SMRep
import Module
import Id
import VarEnv
import OrdList
import Unique
import UniqSupply
import FastString
import Outputable
import qualified Control.Applicative as A
import Control.Monad
import Data.List
import Prelude hiding( sequence, succ )
infixr 9 `thenC` -- Right-associative!
infixr 9 `thenFC`
--------------------------------------------------------
-- The FCode monad and its types
--
-- FCode is the monad plumbed through the Stg->Cmm code generator, and
-- the Cmm parser. It contains the following things:
--
-- - A writer monad, collecting:
-- - code for the current function, in the form of a CmmAGraph.
-- The function "emit" appends more code to this.
-- - the top-level CmmDecls accumulated so far
--
-- - A state monad with:
-- - the local bindings in scope
-- - the current heap usage
-- - a UniqSupply
--
-- - A reader monad, for CgInfoDownwards, containing
-- - DynFlags,
-- - the current Module
-- - the update-frame offset
-- - the ticky counter label
-- - the Sequel (the continuation to return to)
-- - the self-recursive tail call information
--------------------------------------------------------
newtype FCode a = FCode (CgInfoDownwards -> CgState -> (# a, CgState #))
instance Functor FCode where
fmap f (FCode g) = FCode $ \i s -> case g i s of (# a, s' #) -> (# f a, s' #)
instance A.Applicative FCode where
pure = return
(<*>) = ap
instance Monad FCode where
(>>=) = thenFC
return = returnFC
{-# INLINE thenC #-}
{-# INLINE thenFC #-}
{-# INLINE returnFC #-}
initC :: IO CgState
initC = do { uniqs <- mkSplitUniqSupply 'c'
; return (initCgState uniqs) }
runC :: DynFlags -> Module -> CgState -> FCode a -> (a,CgState)
runC dflags mod st fcode = doFCode fcode (initCgInfoDown dflags mod) st
returnFC :: a -> FCode a
returnFC val = FCode (\_info_down state -> (# val, state #))
thenC :: FCode () -> FCode a -> FCode a
thenC (FCode m) (FCode k) =
FCode $ \info_down state -> case m info_down state of
(# _,new_state #) -> k info_down new_state
listCs :: [FCode ()] -> FCode ()
listCs [] = return ()
listCs (fc:fcs) = do
fc
listCs fcs
thenFC :: FCode a -> (a -> FCode c) -> FCode c
thenFC (FCode m) k = FCode $
\info_down state ->
case m info_down state of
(# m_result, new_state #) ->
case k m_result of
FCode kcode -> kcode info_down new_state
fixC :: (a -> FCode a) -> FCode a
fixC fcode = FCode (
\info_down state ->
let
(v,s) = doFCode (fcode v) info_down state
in
(# v, s #)
)
--------------------------------------------------------
-- The code generator environment
--------------------------------------------------------
-- This monadery has some information that it only passes
-- *downwards*, as well as some ``state'' which is modified
-- as we go along.
data CgInfoDownwards -- information only passed *downwards* by the monad
= MkCgInfoDown {
cgd_dflags :: DynFlags,
cgd_mod :: Module, -- Module being compiled
cgd_updfr_off :: UpdFrameOffset, -- Size of current update frame
cgd_ticky :: CLabel, -- Current destination for ticky counts
cgd_sequel :: Sequel, -- What to do at end of basic block
cgd_self_loop :: Maybe SelfLoopInfo,-- Which tail calls can be compiled
-- as local jumps? See Note
-- [Self-recursive tail calls] in
-- StgCmmExpr
cgd_tick_scope:: CmmTickScope -- Tick scope for new blocks & ticks
}
type CgBindings = IdEnv CgIdInfo
data CgIdInfo
= CgIdInfo
{ cg_id :: Id -- Id that this is the info for
-- Can differ from the Id at occurrence sites by
-- virtue of being externalised, for splittable C
-- See Note [Externalise when splitting]
, cg_lf :: LambdaFormInfo
, cg_loc :: CgLoc -- CmmExpr for the *tagged* value
}
-- Note [Externalise when splitting]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- If we're splitting the object with -fsplit-objs, we need to
-- externalise *all* the top-level names, and then make sure we only
-- use the externalised one in any C label we use which refers to this
-- name.
instance Outputable CgIdInfo where
ppr (CgIdInfo { cg_id = id, cg_loc = loc })
= ppr id <+> ptext (sLit "-->") <+> ppr loc
-- Sequel tells what to do with the result of this expression
data Sequel
= Return Bool -- Return result(s) to continuation found on the stack.
-- True <=> the continuation is update code (???)
| AssignTo
[LocalReg] -- Put result(s) in these regs and fall through
-- NB: no void arguments here
--
Bool -- Should we adjust the heap pointer back to
-- recover space that's unused on this path?
-- We need to do this only if the expression
-- may allocate (e.g. it's a foreign call or
-- allocating primOp)
-- See Note [sharing continuations] below
data ReturnKind
= AssignedDirectly
| ReturnedTo BlockId ByteOff
-- Note [sharing continuations]
--
-- ReturnKind says how the expression being compiled returned its
-- results: either by assigning directly to the registers specified
-- by the Sequel, or by returning to a continuation that does the
-- assignments. The point of this is we might be able to re-use the
-- continuation in a subsequent heap-check. Consider:
--
-- case f x of z
-- True -> <True code>
-- False -> <False code>
--
-- Naively we would generate
--
-- R2 = x -- argument to f
-- Sp[young(L1)] = L1
-- call f returns to L1
-- L1:
-- z = R1
-- if (z & 1) then Ltrue else Lfalse
-- Ltrue:
-- Hp = Hp + 24
-- if (Hp > HpLim) then L4 else L7
-- L4:
-- HpAlloc = 24
-- goto L5
-- L5:
-- R1 = z
-- Sp[young(L6)] = L6
-- call stg_gc_unpt_r1 returns to L6
-- L6:
-- z = R1
-- goto L1
-- L7:
-- <True code>
-- Lfalse:
-- <False code>
--
-- We want the gc call in L4 to return to L1, and discard L6. Note
-- that not only can we share L1 and L6, but the assignment of the
-- return address in L4 is unnecessary because the return address for
-- L1 is already on the stack. We used to catch the sharing of L1 and
-- L6 in the common-block-eliminator, but not the unnecessary return
-- address assignment.
--
-- Since this case is so common I decided to make it more explicit and
-- robust by programming the sharing directly, rather than relying on
-- the common-block elimiantor to catch it. This makes
-- common-block-elimianteion an optional optimisation, and furthermore
-- generates less code in the first place that we have to subsequently
-- clean up.
--
-- There are some rarer cases of common blocks that we don't catch
-- this way, but that's ok. Common-block-elimination is still available
-- to catch them when optimisation is enabled. Some examples are:
--
-- - when both the True and False branches do a heap check, we
-- can share the heap-check failure code L4a and maybe L4
--
-- - in a case-of-case, there might be multiple continuations that
-- we can common up.
--
-- It is always safe to use AssignedDirectly. Expressions that jump
-- to the continuation from multiple places (e.g. case expressions)
-- fall back to AssignedDirectly.
--
initCgInfoDown :: DynFlags -> Module -> CgInfoDownwards
initCgInfoDown dflags mod
= MkCgInfoDown { cgd_dflags = dflags
, cgd_mod = mod
, cgd_updfr_off = initUpdFrameOff dflags
, cgd_ticky = mkTopTickyCtrLabel
, cgd_sequel = initSequel
, cgd_self_loop = Nothing
, cgd_tick_scope= GlobalScope }
initSequel :: Sequel
initSequel = Return False
initUpdFrameOff :: DynFlags -> UpdFrameOffset
initUpdFrameOff dflags = widthInBytes (wordWidth dflags) -- space for the RA
--------------------------------------------------------
-- The code generator state
--------------------------------------------------------
data CgState
= MkCgState {
cgs_stmts :: CmmAGraph, -- Current procedure
cgs_tops :: OrdList CmmDecl,
-- Other procedures and data blocks in this compilation unit
-- Both are ordered only so that we can
-- reduce forward references, when it's easy to do so
cgs_binds :: CgBindings,
cgs_hp_usg :: HeapUsage,
cgs_uniqs :: UniqSupply }
data HeapUsage -- See Note [Virtual and real heap pointers]
= HeapUsage {
virtHp :: VirtualHpOffset, -- Virtual offset of highest-allocated word
-- Incremented whenever we allocate
realHp :: VirtualHpOffset -- realHp: Virtual offset of real heap ptr
-- Used in instruction addressing modes
}
type VirtualHpOffset = WordOff
{- Note [Virtual and real heap pointers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The code generator can allocate one or more objects contiguously, performing
one heap check to cover allocation of all the objects at once. Let's call
this little chunk of heap space an "allocation chunk". The code generator
will emit code to
* Perform a heap-exhaustion check
* Move the heap pointer to the end of the allocation chunk
* Allocate multiple objects within the chunk
The code generator uses VirtualHpOffsets to address words within a
single allocation chunk; these start at one and increase positively.
The first word of the chunk has VirtualHpOffset=1, the second has
VirtualHpOffset=2, and so on.
* The field realHp tracks (the VirtualHpOffset) where the real Hp
register is pointing. Typically it'll be pointing to the end of the
allocation chunk.
* The field virtHp gives the VirtualHpOffset of the highest-allocated
word so far. It starts at zero (meaning no word has been allocated),
and increases whenever an object is allocated.
The difference between realHp and virtHp gives the offset from the
real Hp register of a particular word in the allocation chunk. This
is what getHpRelOffset does. Since the returned offset is relative
to the real Hp register, it is valid only until you change the real
Hp register. (Changing virtHp doesn't matter.)
-}
initCgState :: UniqSupply -> CgState
initCgState uniqs
= MkCgState { cgs_stmts = mkNop
, cgs_tops = nilOL
, cgs_binds = emptyVarEnv
, cgs_hp_usg = initHpUsage
, cgs_uniqs = uniqs }
stateIncUsage :: CgState -> CgState -> CgState
-- stateIncUsage@ e1 e2 incorporates in e1
-- the heap high water mark found in e2.
stateIncUsage s1 s2@(MkCgState { cgs_hp_usg = hp_usg })
= s1 { cgs_hp_usg = cgs_hp_usg s1 `maxHpHw` virtHp hp_usg }
`addCodeBlocksFrom` s2
addCodeBlocksFrom :: CgState -> CgState -> CgState
-- Add code blocks from the latter to the former
-- (The cgs_stmts will often be empty, but not always; see codeOnly)
s1 `addCodeBlocksFrom` s2
= s1 { cgs_stmts = cgs_stmts s1 MkGraph.<*> cgs_stmts s2,
cgs_tops = cgs_tops s1 `appOL` cgs_tops s2 }
-- The heap high water mark is the larger of virtHp and hwHp. The latter is
-- only records the high water marks of forked-off branches, so to find the
-- heap high water mark you have to take the max of virtHp and hwHp. Remember,
-- virtHp never retreats!
--
-- Note Jan 04: ok, so why do we only look at the virtual Hp??
heapHWM :: HeapUsage -> VirtualHpOffset
heapHWM = virtHp
initHpUsage :: HeapUsage
initHpUsage = HeapUsage { virtHp = 0, realHp = 0 }
maxHpHw :: HeapUsage -> VirtualHpOffset -> HeapUsage
hp_usg `maxHpHw` hw = hp_usg { virtHp = virtHp hp_usg `max` hw }
--------------------------------------------------------
-- Operators for getting and setting the state and "info_down".
--------------------------------------------------------
getState :: FCode CgState
getState = FCode $ \_info_down state -> (# state, state #)
setState :: CgState -> FCode ()
setState state = FCode $ \_info_down _ -> (# (), state #)
getHpUsage :: FCode HeapUsage
getHpUsage = do
state <- getState
return $ cgs_hp_usg state
setHpUsage :: HeapUsage -> FCode ()
setHpUsage new_hp_usg = do
state <- getState
setState $ state {cgs_hp_usg = new_hp_usg}
setVirtHp :: VirtualHpOffset -> FCode ()
setVirtHp new_virtHp
= do { hp_usage <- getHpUsage
; setHpUsage (hp_usage {virtHp = new_virtHp}) }
getVirtHp :: FCode VirtualHpOffset
getVirtHp
= do { hp_usage <- getHpUsage
; return (virtHp hp_usage) }
setRealHp :: VirtualHpOffset -> FCode ()
setRealHp new_realHp
= do { hp_usage <- getHpUsage
; setHpUsage (hp_usage {realHp = new_realHp}) }
getBinds :: FCode CgBindings
getBinds = do
state <- getState
return $ cgs_binds state
setBinds :: CgBindings -> FCode ()
setBinds new_binds = do
state <- getState
setState $ state {cgs_binds = new_binds}
withState :: FCode a -> CgState -> FCode (a,CgState)
withState (FCode fcode) newstate = FCode $ \info_down state ->
case fcode info_down newstate of
(# retval, state2 #) -> (# (retval,state2), state #)
newUniqSupply :: FCode UniqSupply
newUniqSupply = do
state <- getState
let (us1, us2) = splitUniqSupply (cgs_uniqs state)
setState $ state { cgs_uniqs = us1 }
return us2
newUnique :: FCode Unique
newUnique = do
state <- getState
let (u,us') = takeUniqFromSupply (cgs_uniqs state)
setState $ state { cgs_uniqs = us' }
return u
------------------
getInfoDown :: FCode CgInfoDownwards
getInfoDown = FCode $ \info_down state -> (# info_down,state #)
getSelfLoop :: FCode (Maybe SelfLoopInfo)
getSelfLoop = do
info_down <- getInfoDown
return $ cgd_self_loop info_down
withSelfLoop :: SelfLoopInfo -> FCode a -> FCode a
withSelfLoop self_loop code = do
info_down <- getInfoDown
withInfoDown code (info_down {cgd_self_loop = Just self_loop})
instance HasDynFlags FCode where
getDynFlags = liftM cgd_dflags getInfoDown
getThisPackage :: FCode PackageKey
getThisPackage = liftM thisPackage getDynFlags
withInfoDown :: FCode a -> CgInfoDownwards -> FCode a
withInfoDown (FCode fcode) info_down = FCode $ \_ state -> fcode info_down state
doFCode :: FCode a -> CgInfoDownwards -> CgState -> (a,CgState)
doFCode (FCode fcode) info_down state =
case fcode info_down state of
(# a, s #) -> ( a, s )
-- ----------------------------------------------------------------------------
-- Get the current module name
getModuleName :: FCode Module
getModuleName = do { info <- getInfoDown; return (cgd_mod info) }
-- ----------------------------------------------------------------------------
-- Get/set the end-of-block info
withSequel :: Sequel -> FCode a -> FCode a
withSequel sequel code
= do { info <- getInfoDown
; withInfoDown code (info {cgd_sequel = sequel, cgd_self_loop = Nothing }) }
getSequel :: FCode Sequel
getSequel = do { info <- getInfoDown
; return (cgd_sequel info) }
-- ----------------------------------------------------------------------------
-- Get/set the size of the update frame
-- We keep track of the size of the update frame so that we
-- can set the stack pointer to the proper address on return
-- (or tail call) from the closure.
-- There should be at most one update frame for each closure.
-- Note: I'm including the size of the original return address
-- in the size of the update frame -- hence the default case on `get'.
withUpdFrameOff :: UpdFrameOffset -> FCode a -> FCode a
withUpdFrameOff size code
= do { info <- getInfoDown
; withInfoDown code (info {cgd_updfr_off = size }) }
getUpdFrameOff :: FCode UpdFrameOffset
getUpdFrameOff
= do { info <- getInfoDown
; return $ cgd_updfr_off info }
-- ----------------------------------------------------------------------------
-- Get/set the current ticky counter label
getTickyCtrLabel :: FCode CLabel
getTickyCtrLabel = do
info <- getInfoDown
return (cgd_ticky info)
setTickyCtrLabel :: CLabel -> FCode a -> FCode a
setTickyCtrLabel ticky code = do
info <- getInfoDown
withInfoDown code (info {cgd_ticky = ticky})
-- ----------------------------------------------------------------------------
-- Manage tick scopes
-- | The current tick scope. We will assign this to generated blocks.
getTickScope :: FCode CmmTickScope
getTickScope = do
info <- getInfoDown
return (cgd_tick_scope info)
-- | Places blocks generated by the given code into a fresh
-- (sub-)scope. This will make sure that Cmm annotations in our scope
-- will apply to the Cmm blocks generated therein - but not the other
-- way around.
tickScope :: FCode a -> FCode a
tickScope code = do
info <- getInfoDown
if not (gopt Opt_Debug (cgd_dflags info)) then code else do
u <- newUnique
let scope' = SubScope u (cgd_tick_scope info)
withInfoDown code info{ cgd_tick_scope = scope' }
--------------------------------------------------------
-- Forking
--------------------------------------------------------
forkClosureBody :: FCode () -> FCode ()
-- forkClosureBody compiles body_code in environment where:
-- - sequel, update stack frame and self loop info are
-- set to fresh values
-- - state is set to a fresh value, except for local bindings
-- that are passed in unchanged. It's up to the enclosed code to
-- re-bind the free variables to a field of the closure.
forkClosureBody body_code
= do { dflags <- getDynFlags
; info <- getInfoDown
; us <- newUniqSupply
; state <- getState
; let body_info_down = info { cgd_sequel = initSequel
, cgd_updfr_off = initUpdFrameOff dflags
, cgd_self_loop = Nothing }
fork_state_in = (initCgState us) { cgs_binds = cgs_binds state }
((),fork_state_out) = doFCode body_code body_info_down fork_state_in
; setState $ state `addCodeBlocksFrom` fork_state_out }
forkLneBody :: FCode a -> FCode a
-- 'forkLneBody' takes a body of let-no-escape binding and compiles
-- it in the *current* environment, returning the graph thus constructed.
--
-- The current environment is passed on completely unchanged to
-- the successor. In particular, any heap usage from the enclosed
-- code is discarded; it should deal with its own heap consumption.
forkLneBody body_code
= do { info_down <- getInfoDown
; us <- newUniqSupply
; state <- getState
; let fork_state_in = (initCgState us) { cgs_binds = cgs_binds state }
(result, fork_state_out) = doFCode body_code info_down fork_state_in
; setState $ state `addCodeBlocksFrom` fork_state_out
; return result }
codeOnly :: FCode () -> FCode ()
-- Emit any code from the inner thing into the outer thing
-- Do not affect anything else in the outer state
-- Used in almost-circular code to prevent false loop dependencies
codeOnly body_code
= do { info_down <- getInfoDown
; us <- newUniqSupply
; state <- getState
; let fork_state_in = (initCgState us) { cgs_binds = cgs_binds state
, cgs_hp_usg = cgs_hp_usg state }
((), fork_state_out) = doFCode body_code info_down fork_state_in
; setState $ state `addCodeBlocksFrom` fork_state_out }
forkAlts :: [FCode a] -> FCode [a]
-- (forkAlts' bs d) takes fcodes 'bs' for the branches of a 'case', and
-- an fcode for the default case 'd', and compiles each in the current
-- environment. The current environment is passed on unmodified, except
-- that the virtual Hp is moved on to the worst virtual Hp for the branches
forkAlts branch_fcodes
= do { info_down <- getInfoDown
; us <- newUniqSupply
; state <- getState
; let compile us branch
= (us2, doFCode branch info_down branch_state)
where
(us1,us2) = splitUniqSupply us
branch_state = (initCgState us1) {
cgs_binds = cgs_binds state
, cgs_hp_usg = cgs_hp_usg state }
(_us, results) = mapAccumL compile us branch_fcodes
(branch_results, branch_out_states) = unzip results
; setState $ foldl stateIncUsage state branch_out_states
-- NB foldl. state is the *left* argument to stateIncUsage
; return branch_results }
-- collect the code emitted by an FCode computation
getCodeR :: FCode a -> FCode (a, CmmAGraph)
getCodeR fcode
= do { state1 <- getState
; (a, state2) <- withState fcode (state1 { cgs_stmts = mkNop })
; setState $ state2 { cgs_stmts = cgs_stmts state1 }
; return (a, cgs_stmts state2) }
getCode :: FCode a -> FCode CmmAGraph
getCode fcode = do { (_,stmts) <- getCodeR fcode; return stmts }
-- | Generate code into a fresh tick (sub-)scope and gather generated code
getCodeScoped :: FCode a -> FCode (a, CmmAGraphScoped)
getCodeScoped fcode
= do { state1 <- getState
; ((a, tscope), state2) <-
tickScope $
flip withState state1 { cgs_stmts = mkNop } $
do { a <- fcode
; scp <- getTickScope
; return (a, scp) }
; setState $ state2 { cgs_stmts = cgs_stmts state1 }
; return (a, (cgs_stmts state2, tscope)) }
-- 'getHeapUsage' applies a function to the amount of heap that it uses.
-- It initialises the heap usage to zeros, and passes on an unchanged
-- heap usage.
--
-- It is usually a prelude to performing a GC check, so everything must
-- be in a tidy and consistent state.
--
-- Note the slightly subtle fixed point behaviour needed here
getHeapUsage :: (VirtualHpOffset -> FCode a) -> FCode a
getHeapUsage fcode
= do { info_down <- getInfoDown
; state <- getState
; let fstate_in = state { cgs_hp_usg = initHpUsage }
(r, fstate_out) = doFCode (fcode hp_hw) info_down fstate_in
hp_hw = heapHWM (cgs_hp_usg fstate_out) -- Loop here!
; setState $ fstate_out { cgs_hp_usg = cgs_hp_usg state }
; return r }
-- ----------------------------------------------------------------------------
-- Combinators for emitting code
emitCgStmt :: CgStmt -> FCode ()
emitCgStmt stmt
= do { state <- getState
; setState $ state { cgs_stmts = cgs_stmts state `snocOL` stmt }
}
emitLabel :: BlockId -> FCode ()
emitLabel id = do tscope <- getTickScope
emitCgStmt (CgLabel id tscope)
emitComment :: FastString -> FCode ()
#if 0 /* def DEBUG */
emitComment s = emitCgStmt (CgStmt (CmmComment s))
#else
emitComment _ = return ()
#endif
emitTick :: CmmTickish -> FCode ()
emitTick = emitCgStmt . CgStmt . CmmTick
emitUnwind :: GlobalReg -> CmmExpr -> FCode ()
emitUnwind g e = do
dflags <- getDynFlags
when (gopt Opt_Debug dflags) $
emitCgStmt $ CgStmt $ CmmUnwind g e
emitAssign :: CmmReg -> CmmExpr -> FCode ()
emitAssign l r = emitCgStmt (CgStmt (CmmAssign l r))
emitStore :: CmmExpr -> CmmExpr -> FCode ()
emitStore l r = emitCgStmt (CgStmt (CmmStore l r))
newLabelC :: FCode BlockId
newLabelC = do { u <- newUnique
; return $ mkBlockId u }
emit :: CmmAGraph -> FCode ()
emit ag
= do { state <- getState
; setState $ state { cgs_stmts = cgs_stmts state MkGraph.<*> ag } }
emitDecl :: CmmDecl -> FCode ()
emitDecl decl
= do { state <- getState
; setState $ state { cgs_tops = cgs_tops state `snocOL` decl } }
emitOutOfLine :: BlockId -> CmmAGraphScoped -> FCode ()
emitOutOfLine l (stmts, tscope) = emitCgStmt (CgFork l stmts tscope)
emitProcWithStackFrame
:: Convention -- entry convention
-> Maybe CmmInfoTable -- info table?
-> CLabel -- label for the proc
-> [CmmFormal] -- stack frame
-> [CmmFormal] -- arguments
-> CmmAGraphScoped -- code
-> Bool -- do stack layout?
-> FCode ()
emitProcWithStackFrame _conv mb_info lbl _stk_args [] blocks False
= do { dflags <- getDynFlags
; emitProc_ mb_info lbl [] blocks (widthInBytes (wordWidth dflags)) False
}
emitProcWithStackFrame conv mb_info lbl stk_args args (graph, tscope) True
-- do layout
= do { dflags <- getDynFlags
; let (offset, live, entry) = mkCallEntry dflags conv args stk_args
graph' = entry MkGraph.<*> graph
; emitProc_ mb_info lbl live (graph', tscope) offset True
}
emitProcWithStackFrame _ _ _ _ _ _ _ = panic "emitProcWithStackFrame"
emitProcWithConvention :: Convention -> Maybe CmmInfoTable -> CLabel
-> [CmmFormal]
-> CmmAGraphScoped
-> FCode ()
emitProcWithConvention conv mb_info lbl args blocks
= emitProcWithStackFrame conv mb_info lbl [] args blocks True
emitProc :: Maybe CmmInfoTable -> CLabel -> [GlobalReg] -> CmmAGraphScoped
-> Int -> FCode ()
emitProc mb_info lbl live blocks offset
= emitProc_ mb_info lbl live blocks offset True
emitProc_ :: Maybe CmmInfoTable -> CLabel -> [GlobalReg] -> CmmAGraphScoped
-> Int -> Bool -> FCode ()
emitProc_ mb_info lbl live blocks offset do_layout
= do { dflags <- getDynFlags
; l <- newLabelC
; let
blks = labelAGraph l blocks
infos | Just info <- mb_info = mapSingleton (g_entry blks) info
| otherwise = mapEmpty
sinfo = StackInfo { arg_space = offset
, updfr_space = Just (initUpdFrameOff dflags)
, do_layout = do_layout }
tinfo = TopInfo { info_tbls = infos
, stack_info=sinfo}
proc_block = CmmProc tinfo lbl live blks
; state <- getState
; setState $ state { cgs_tops = cgs_tops state `snocOL` proc_block } }
getCmm :: FCode () -> FCode CmmGroup
-- Get all the CmmTops (there should be no stmts)
-- Return a single Cmm which may be split from other Cmms by
-- object splitting (at a later stage)
getCmm code
= do { state1 <- getState
; ((), state2) <- withState code (state1 { cgs_tops = nilOL })
; setState $ state2 { cgs_tops = cgs_tops state1 }
; return (fromOL (cgs_tops state2)) }
mkCmmIfThenElse :: CmmExpr -> CmmAGraph -> CmmAGraph -> FCode CmmAGraph
mkCmmIfThenElse e tbranch fbranch = do
tscp <- getTickScope
endif <- newLabelC
tid <- newLabelC
fid <- newLabelC
return $ catAGraphs [ mkCbranch e tid fid
, mkLabel tid tscp, tbranch, mkBranch endif
, mkLabel fid tscp, fbranch, mkLabel endif tscp ]
mkCmmIfGoto :: CmmExpr -> BlockId -> FCode CmmAGraph
mkCmmIfGoto e tid = do
endif <- newLabelC
tscp <- getTickScope
return $ catAGraphs [ mkCbranch e tid endif, mkLabel endif tscp ]
mkCmmIfThen :: CmmExpr -> CmmAGraph -> FCode CmmAGraph
mkCmmIfThen e tbranch = do
endif <- newLabelC
tid <- newLabelC
tscp <- getTickScope
return $ catAGraphs [ mkCbranch e tid endif
, mkLabel tid tscp, tbranch, mkLabel endif tscp ]
mkCall :: CmmExpr -> (Convention, Convention) -> [CmmFormal] -> [CmmActual]
-> UpdFrameOffset -> [CmmActual] -> FCode CmmAGraph
mkCall f (callConv, retConv) results actuals updfr_off extra_stack = do
dflags <- getDynFlags
k <- newLabelC
tscp <- getTickScope
let area = Young k
(off, _, copyin) = copyInOflow dflags retConv area results []
copyout = mkCallReturnsTo dflags f callConv actuals k off updfr_off extra_stack
return $ catAGraphs [copyout, mkLabel k tscp, copyin]
mkCmmCall :: CmmExpr -> [CmmFormal] -> [CmmActual] -> UpdFrameOffset
-> FCode CmmAGraph
mkCmmCall f results actuals updfr_off
= mkCall f (NativeDirectCall, NativeReturn) results actuals updfr_off []
-- ----------------------------------------------------------------------------
-- turn CmmAGraph into CmmGraph, for making a new proc.
aGraphToGraph :: CmmAGraphScoped -> FCode CmmGraph
aGraphToGraph stmts
= do { l <- newLabelC
; return (labelAGraph l stmts) }
| urbanslug/ghc | compiler/codeGen/StgCmmMonad.hs | bsd-3-clause | 30,891 | 0 | 15 | 8,210 | 5,848 | 3,197 | 2,651 | 466 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module T5358 where
import Language.Haskell.TH
t1, t2 :: Int
t1 x = x
t2 x = x
prop_x1 x = t1 x == t2 x
$(return [])
runTests = $( do VarI _ t _ _ <- reify (mkName "prop_x1")
error $ ("runTest called error: " ++ pprint t)
)
| green-haskell/ghc | testsuite/tests/th/T5358.hs | bsd-3-clause | 290 | 0 | 12 | 88 | 115 | 58 | 57 | 10 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
-- !!! Functional dependencies
-- This broke an early impl of functional dependencies
-- (complaint about ambiguity)
module ShouldCompile where
class C a b | a -> b where f :: a -> b
g :: (C a b, Eq b) => a -> Bool
g x = f x == f x
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/tc112.hs | bsd-3-clause | 299 | 0 | 7 | 62 | 78 | 43 | 35 | 5 | 1 |
module MLCore where
import Stats.Types
import Linear
import Control.Monad.State.Strict
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Generic as G
import Data.Vector.Unboxed (Unbox)
import Data.Vector.Unboxed.Deriving (derivingUnbox)
type MLModel vp vs =
( LinAlg vp Double, LinAlg vs Double )
data MLConfig vp vs where
MLConfig :: MLModel vp vs => MLConfig vp vs
derivingUnbox "MLConfig"
[t| forall vp vs. MLModel vp vs => MLConfig vp vs -> () |]
[| \(MLConfig) -> () |]
[| \() -> MLConfig |]
calc_zs :: ( LinAlg s Double
, G.Vector vec (s Double) )
=> vec (s Double) -> State Int (vec (s Double))
calc_zs ys = do
(G.mapM . mapM) (const $ return 0) ys
{-# INLINE calc_zs #-}
calc_sums :: forall vp vs. MLModel vp vs
=> VU.Vector (vp Double)
-> VU.Vector (vp Double)
-> VU.Vector (vs Double)
calc_sums xs zs =
let n = G.length xs
in VU.replicate (n + 1) (pure 0)
{-# INLINE calc_sums #-}
guessStates' :: forall vp vs. MLModel vp vs => MLConfig vp vs -> VU.Vector (vs Double)
guessStates' params =
let
n = 10
xs = G.replicate n (pure 0)
ys = VU.replicate n (pure 0 :: vp Double)
in flip evalState 0 $ do
zs <- calc_zs ys
return $ calc_sums xs zs
{-# INLINE guessStates' #-}
guessStates :: MLModel V1 vs => MLConfig V1 vs -> VU.Vector (vs Double)
guessStates params =
guessStates' params -- needed to trigger bug!
{-# INLINE guessStates #-}
class ModelObs obs vs where
fitModel :: MLModel V1 vs => [obs] -> VU.Vector (vs Double)
instance (MLModel V1 vs) => ModelObs (V1 Double, VU.Vector (V1 Double)) vs where
fitModel allRsTL =
guessStates MLConfig
{-# INLINE fitModel #-}
fitModel2 :: (MLModel V1 vs, ModelObs obs vs) => [obs] -> VU.Vector (vs Double)
fitModel2 obsTL = -- this is needed to trigger bug! If Main.hs calls `fitModel` directly <<loop>> does not happen.
fitModel obsTL
{-# NOINLINE fitModel2 #-} | yongqli/ghctestcase | src/MLCore.hs | isc | 1,970 | 0 | 11 | 452 | 668 | 351 | 317 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, ImplicitParams, LambdaCase, MultiParamTypeClasses, MultiWayIf, TemplateHaskell, TypeSynonymInstances #-}
{-
_________
/\/\/ \/\/\
/\/\/\ /\/\/\
\ \ \ | / / /
\ \ |\ | /| / /
\\ | \ | / | //
\| \|/ |/
\ | /
\|/
-}
module Formura.MPICxx.Cut where
import Algebra.Lattice.Levitated
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.IO.Class
import Data.Bits(xor)
import Data.List (sort, groupBy, sortBy)
import Data.Data
import Data.Foldable
import Data.Function (on)
import qualified Data.Map as M
import qualified Data.Sequence as Q
import qualified Data.Set as S
import Data.Maybe
import Text.Trifecta (failed, raiseErr)
import qualified Formura.Annotation as A
import Formura.Annotation.Boundary
import Formura.CommandLineOption
import Formura.Syntax(IdentName)
import Formura.Vec
import Formura.Geometry
import Formura.GlobalEnvironment
import Formura.OrthotopeMachine.Graph
import Formura.NumericalConfig
import Formura.Compiler
import qualified Formura.MPICxx.Language as C
import System.IO.Unsafe
newtype MPIRank = MPIRank (Vec Int) deriving (Eq, Ord, Show, Read, Num, Data)
data IRank = IRank IRankComparator (Vec Int) deriving (Eq, Show, Read, Data)
data IRankComparator = IRankCompareStraight | IRankCompareReverse deriving (Eq, Show, Read, Data)
instance Ord IRank where
(IRank c (Vec xs)) `compare` (IRank _ (Vec ys)) =
case c of IRankCompareStraight -> xs `compare` ys
IRankCompareReverse -> reverse xs `compare` reverse ys
compare _ _ = error "Comparison between IRank (PureVec _) is undefined"
data ResourceT a b = ResourceStatic IdentName a | ResourceOMNode OMNodeID b
deriving (Eq, Ord, Show, Read, Typeable, Data)
type Resource = ResourceT () ()
type ConcreteResource = ResourceT (MPIRank, Box) (MPIRank, IRank, Box)
data RidgeID = RidgeID { _ridgeDeltaMPI :: MPIRank, _ridgeDelta :: ResourceT () (IRank, IRank)}
deriving (Eq, Ord, Show, Read, Typeable, Data)
makeLenses ''RidgeID
doesRidgeNeedMPI :: RidgeID -> Bool
doesRidgeNeedMPI r = r ^.ridgeDeltaMPI /= MPIRank 0
type Ridge = (RidgeID, Box)
data FacetID = FacetID { _facetDeltaMPI :: MPIRank, _facetIRSrc :: IRank, _facetIRDest :: IRank}
deriving (Eq, Ord, Show, Read, Typeable, Data)
makeLenses ''FacetID
data DistributedInst
= CommunicationWait FacetID -- receive a facet via MPI
| Unstage RidgeID -- copy from ridge to slice
| Computation (IRank, OMNodeID) ArrayResourceKey -- compute a region slice and store them into the resource
| FreeResource ArrayResourceKey -- mark the end of use for given resource
| Stage RidgeID -- copy from slice to ridge
| CommunicationSendRecv FacetID -- send a facet via MPI
deriving (Eq, Ord, Show, Read, Typeable, Data)
type ArrayResourceKey = ResourceT () IRank
newtype ResourceSharingID = ResourceSharingID {fromResourceSharingID :: Int}
deriving (Eq, Ord, Read, Data, Num, Enum)
instance Show ResourceSharingID where show = show . fromResourceSharingID
data SendOrRecv = Send | Recv | SendRecv
deriving (Eq, Ord, Show, Read, Data, Enum)
data MPIPlan = MPIPlan
{ _planArrayAlloc :: M.Map ArrayResourceKey Box
, _planRidgeAlloc :: M.Map RidgeID Box
, _planFacetAssignment :: M.Map RidgeID FacetID
, _planFacetAlloc :: M.Map FacetID [RidgeID]
, _planRegionAlloc :: M.Map (IRank, OMNodeID) Box
, _planDistributedProgram :: [DistributedInst]
, _planSystemOffset :: Vec Int
, _planResourceSharing :: M.Map ArrayResourceKey ResourceSharingID
, _planSharedResourceExtent :: Box
, _planResourceNames :: M.Map ArrayResourceKey C.Src
, _planSharedResourceNames :: M.Map ResourceSharingID C.Src
, _planRidgeNames :: M.Map (RidgeID, SendOrRecv) C.Src
, _planFacetMPITag :: M.Map FacetID Int
, _planMPIRequestNames :: M.Map FacetID C.Src
}
makeClassy ''MPIPlan
data PlanRead = PlanRead
{ _prNumericalConfig :: NumericalConfig
, _prMMProgram :: MMProgram
}
makeClassy ''PlanRead
instance HasMachineProgram PlanRead MMInstruction OMNodeType where
machineProgram = prMMProgram
instance HasGlobalEnvironment PlanRead where
globalEnvironment = omGlobalEnvironment -- via HasMachineProgram
instance HasNumericalConfig PlanRead where
numericalConfig = prNumericalConfig
data PlanState = PlanState
{ _psSyntacticState :: CompilerSyntacticState
, _psDistributedProgramQ :: Q.Seq DistributedInst
, _psAlreadyIssuedInst :: S.Set DistributedInst
, _psResourceSharing :: M.Map ArrayResourceKey ResourceSharingID
, _psFreeResourceSharingID :: [ResourceSharingID]
}
makeClassy ''PlanState
instance HasCompilerSyntacticState PlanState where
compilerSyntacticState = psSyntacticState
type PlanM = CompilerMonad PlanRead () PlanState
makePlan :: WithCommandLineOption => NumericalConfig -> MMProgram -> IO MPIPlan
makePlan nc prog0 = do
let pr = PlanRead
{ _prNumericalConfig = nc
, _prMMProgram = prunedProg
}
ps = PlanState
{ _psSyntacticState = defaultCompilerSyntacticState {_compilerStage = "MPI Planning"}
, _psDistributedProgramQ = Q.empty
, _psAlreadyIssuedInst = S.empty
, _psResourceSharing = M.empty
, _psFreeResourceSharingID = [0..]
}
prunedProg = prog0
& omStepGraph %~ pruneMMGraph
(ret, _, _) <- runCompilerRight cut pr ps
return ret
pruneMMGraph :: MMGraph -> MMGraph
pruneMMGraph = M.map (nodeInst %~ pruneMMInst)
pruneMMInst :: MMInstruction -> MMInstruction
pruneMMInst = M.filter (\nd -> case A.viewMaybe nd of
Just (NBUSpine True) -> True
_ -> False)
getVecAccessor :: PlanM (Vec a -> IdentName -> a)
getVecAccessor = do
Vec xs <- view axesNames
let indmap = zip xs [0..]
go (PureVec y) _ = y
go (Vec ys) x' = let Just i = lookup x' indmap in ys!!i
return go
type Walls = Vec [Partition]
initialWalls :: PlanM Walls
initialWalls = do
axes <- view axesNames
iwparam <- view ncInitialWalls
intraShape <- view ncIntraNodeShape
(!) <- getVecAccessor
maybeInv <- view ncWallInverted
let inverted0 = maybeInv == Just True :: Bool
let boundOfAxis :: String -> Bool -> Int -> Vec (Levitated Int, Levitated Int)
boundOfAxis x ascending n = flip fmap axes $ \y ->
if | x == y && (ascending`xor`inverted0) -> (Levitate n, Bottom)
| x == y -> (Top , Levitate n)
| otherwise -> (Top , Bottom)
mkWall :: String -> Bool -> Int -> Partition
mkWall x a n = let ret = boundOfAxis x a n in Orthotope (fmap fst ret) (fmap snd ret)
forM axes $ \ x -> do
case M.lookup x iwparam of
Nothing -> raiseErr $ failed $ "cannot find initial_wall numerical configuration for axis: " ++ x
Just [] -> raiseErr $ failed $ "at least 1 element is needed for initial_wall numerical configuration for axis: " ++ x
Just ws -> do
let ws2
| inverted0 = reverse $ map (upperWall-) ws
| otherwise = ws
upperWall = intraShape ! x
return $
[mkWall x True 0] ++
map (mkWall x False) ws2 ++
[mkWall x True upperWall]
evalPartition :: Partition -> Int
evalPartition w = case foldMap (maybeToList . touchdown) w of
[x] -> x
_ -> error $ "malformed wall: " ++ show w
cut :: WithCommandLineOption => PlanM MPIPlan
cut = do
dim <- view dimension
let zeroVec = Vec $ replicate dim 0
walls0 <- initialWalls
-- liftIO $ print (walls0 :: Walls)
let wvs = fmap (fmap evalPartition) walls0
-- liftIO $ print (wvs :: Vec [Int])
stepGraph <- view omStepGraph
ncOpts <- view ncOptionStrings
let wallMap :: M.Map OMNodeID Walls
wallMap = M.mapWithKey go stepGraph
go :: OMNodeID -> MMNode -> Walls
go i mmNode = let
mmInst :: MMInstruction
mmInst = mmNode ^. nodeInst
--microInsts :: [MMInstF MMNodeID]
--microInsts = map (^. nodeInst) $ M.elems mmInst
in foldr1 (&&&) (map listBounds $ M.elems mmInst)
infinityWall = fmap (fmap (const (mempty :: Partition))) walls0
listBounds :: MicroNode -> Walls
listBounds microNd =
case microNd ^. nodeInst of
LoadCursorStatic v _ -> move (negate v) walls0
LoadCursor v nid -> let Just w_of_n = M.lookup nid wallMap
in move (negate v) w_of_n
_ -> infinityWall
-- assign the same wall for all the Static nodes
let wallMap2 = flip M.mapWithKey wallMap $ \nid0 wall0 ->
case head $ mmInstTails $ (fromJust $ M.lookup nid0 stepGraph) ^. nodeInst of
Store _ _ -> staticWallConsensus
_ -> wall0
staticWalls :: [Walls]
staticWalls =
[ fromJust $ M.lookup nid0 wallMap
| (nid0, mmNode) <- M.toList stepGraph
, Store _ _ <- mmInstTails $ mmNode ^. nodeInst
]
staticWallConsensus :: Walls
staticWallConsensus = minimum staticWalls
systemOffset0 :: Vec Int
systemOffset0 = fmap head $ fmap (fmap evalPartition) staticWallConsensus
let wallEvolution :: M.Map OMNodeID (Vec [Int])
wallEvolution = fmap (fmap (fmap evalPartition)) wallMap2
-- liftIO $ print (wallEvolution :: M.Map OMNodeID (Vec [Int]))
intraShape0 <- view ncIntraNodeShape
maybeInv <- view ncWallInverted
let inverted0 = maybeInv == Just True :: Bool
let iRanks0 :: [IRank]
iRanks0 =
(if inverted0 then reverse else id) $
sort $
map (IRank iRankComparator) $
sequence $
fmap (\partitions0 -> [0..length partitions0-2]) walls0
iRankComparator
| "irank-order-f" `elem` ncOpts = IRankCompareStraight
| otherwise = IRankCompareReverse
boxAt :: IRank -> Vec [Int] -> Box
boxAt (IRank _ vi) vw = Orthotope (liftVec2 (\i xs-> xs!!i) vi vw) (liftVec2 (\i xs-> xs!!(i+1)) vi vw)
iRankMap :: M.Map OMNodeID (M.Map IRank Box)
iRankMap = flip fmap wallEvolution $ \vi -> M.fromList
[(ir, boxAt ir vi)| ir <- iRanks0]
boxAssignment :: MPIRank -> IRank -> OMNodeID -> Box
boxAssignment (MPIRank mpir) ir nid = fromJust $ do
m <- M.lookup nid iRankMap
ret <- M.lookup ir m
return $ move (mpir*intraShape0) ret
mpiRanks0 :: [MPIRank]
mpiRanks0 =
map MPIRank $
(sequence :: Vec [Int] -> [Vec Int]) $
Vec $
replicate dim [-1,0,1]
mpiRankOrigin :: MPIRank
mpiRankOrigin = MPIRank $ zeroVec
mpiBox0 :: Box
mpiBox0 = Orthotope zeroVec intraShape0
{-
liftIO $ forM_ (M.keys stepGraph) $ \nid -> do
putStrLn $ "NODE: " ++ show nid
forM_ iRanks0 $ \ir -> do
putStrLn $ " IR: " ++ show ir
putStrLn $ " " ++ show (boxAssignment mpiRankOrigin ir nid)
-}
let supportMap :: M.Map (IRank, OMNodeID) (M.Map Resource Box)
supportMap = M.fromList [((ir, nid), go ir nid (fromJust $ M.lookup nid stepGraph))
| ir <- iRanks0, nid <- M.keys stepGraph]
go :: IRank -> OMNodeID -> MMNode -> M.Map Resource Box
go ir nid mmNode = let
mmInst :: MMInstruction
mmInst = mmNode ^. nodeInst
microInsts :: [MMInstF MMNodeID]
microInsts = map (^. nodeInst) $ M.elems mmInst
b0 = boxAssignment mpiRankOrigin ir nid
in M.unionsWith (|||) (map (listSupport b0) microInsts)
listSupport :: Box -> MMInstF MMNodeID -> M.Map Resource Box
listSupport b0 (LoadCursorStatic v snName) = M.singleton (ResourceStatic snName ()) (move v b0)
listSupport b0 (LoadCursor v nid) =
M.singleton (ResourceOMNode nid ()) (move v b0)
listSupport _ _ = M.empty
{-
liftIO $ forM_ iRanks0 $ \ir -> do
putStrLn $ "IR: " ++ show ir
forM_ (M.keys stepGraph) $ \nid -> do
putStrLn $ " NODE: " ++ show nid
putStrLn $ " " ++ show (M.lookup (ir,nid) supportMap)
-}
let locateSources :: IRank -> (Resource, Box) -> [ConcreteResource]
locateSources irDest (ResourceOMNode nid (),b0) =
[ ResourceOMNode nid (mpir, ir, b01)
| (mpir,ir,b1) <- fromJust $ M.lookup nid allPossibleSources
, mpir /= mpiRankOrigin || ir /= irDest
, let b01 = b0 &&& b1
, volume b01 > 0]
locateSources _ (ResourceStatic snName (),b0) =
[ ResourceStatic snName (mpir, b01)
| (mpir,b1) <- allPossibleSourcesStatic
, mpir /= mpiRankOrigin
, let b01 = b0 &&& b1
, volume b01 > 0
]
allPossibleSources :: M.Map OMNodeID [(MPIRank, IRank, Box)]
allPossibleSources = M.fromList
[ (nid, [(mpir, ir, boxAssignment mpir ir nid)
| mpir <- mpiRanks0
, ir <- iRanks0])
| nid <- M.keys stepGraph
]
allPossibleSourcesStatic :: [(MPIRank, Box)]
allPossibleSourcesStatic =
[ (mpir,b)
| mpir@(MPIRank mpiVec) <- mpiRanks0
, let b = move (mpiVec*intraShape0) mpiBox0
]
let ridgeAndBoxRequest :: M.Map (IRank, OMNodeID) [Ridge]
ridgeAndBoxRequest = M.mapWithKey go supportMap
ridgeRequest :: M.Map (IRank, OMNodeID) [RidgeID]
ridgeRequest = M.map (map fst) ridgeAndBoxRequest
ridgeFirstNeededAt :: M.Map RidgeID IRank
ridgeFirstNeededAt = M.unionsWith (\a _ -> a)
[ M.singleton rid ir
| ir <- iRanks0
, nid <- M.keys stepGraph
, rid <- maybe [] id $ M.lookup (ir, nid) ridgeRequest
]
go :: (IRank, OMNodeID) -> M.Map Resource Box -> [Ridge]
go (ir, nid) rbmap =
[ mkRidge ir crsc
| (rsc,b0) <- M.toList rbmap
, crsc <- locateSources ir (rsc,b0)
]
mkRidge :: IRank -> ConcreteResource -> Ridge
mkRidge _ (ResourceStatic sn (mpir, b)) = (RidgeID mpir (ResourceStatic sn ()) ,b)
mkRidge irDest (ResourceOMNode nid (mpir, irSrc, b)) = (RidgeID mpir (ResourceOMNode nid (irSrc, irDest)) ,b)
allRidges :: M.Map RidgeID Box
allRidges = M.unionsWith (|||) $ map (uncurry M.singleton) $ concat $ M.elems ridgeAndBoxRequest
let ridgeProvide :: M.Map (ResourceT () IRank) [RidgeID]
ridgeProvide = foldr (M.unionWith (++)) M.empty $ map mkProvide $ M.keys $ allRidges
mkProvide :: RidgeID -> M.Map (ResourceT () IRank) [RidgeID]
mkProvide ridge0@(RidgeID dmpi drsc) = case drsc of
ResourceStatic sn () -> M.singleton (ResourceStatic sn ()) [ridge0]
ResourceOMNode nid (iSrc,_) -> M.singleton (ResourceOMNode nid iSrc) [ridge0]
facetAssignment :: M.Map RidgeID FacetID
facetAssignment = M.fromList
[ (r, FacetID (r ^. ridgeDeltaMPI) irSrc irDest)
| r <- M.keys allRidges
, doesRidgeNeedMPI r
, let Just irDest = M.lookup r ridgeFirstNeededAt
, let irSrc = case r ^. ridgeDelta of
ResourceStatic _ _ -> head $ iRanks0
ResourceOMNode _ (x,_) -> x]
allFacets :: M.Map FacetID [RidgeID]
allFacets = M.unionsWith (++) [M.singleton f [r] | (r,f) <- M.toList facetAssignment]
let insert :: DistributedInst -> PlanM ()
insert inst = do
psAlreadyIssuedInst %= (S.insert inst)
psDistributedProgramQ %= (Q.|> inst)
insertOnce :: DistributedInst -> PlanM ()
insertOnce inst = do
aii <- use psAlreadyIssuedInst
when (not $ S.member inst aii) $ insert inst
stateSignature0 <- view omStateSignature
forM_ (M.keys stateSignature0) $ \snName -> do
let outRidges = fromMaybe [] $ M.lookup (ResourceStatic snName ()) ridgeProvide
forM_ outRidges $ \rdg0 -> insertOnce $ Stage rdg0
forM_ iRanks0 $ \ir -> do
sequence [ insert $ CommunicationWait f
| f <- M.keys allFacets
, f ^. facetIRDest == ir]
forM_ (M.keys stepGraph) $ \nid -> do
let inRidges = fromMaybe [] $ M.lookup (ir,nid) ridgeRequest
outRidges = fromMaybe [] $ M.lookup (ResourceOMNode nid ir) ridgeProvide
forM_ inRidges $ \rdg0 -> insertOnce $ Unstage rdg0
let tailRsc :: ArrayResourceKey
tailRsc = case head $ mmInstTails mmInst of
Store snName _ -> ResourceStatic snName ()
_ -> ResourceOMNode nid ir
mmInst = fromJust (M.lookup nid stepGraph) ^. nodeInst
insert $ Computation (ir, nid) tailRsc
forM_ outRidges $ \rdg0 -> insertOnce $ Stage rdg0
sequence [ insert $ CommunicationSendRecv f
| f <- M.keys allFacets
, f ^. facetIRSrc == ir]
let allAllocs :: M.Map (ResourceT () IRank) Box
allAllocs = M.unionsWith (|||) $ basicAllocStatic : basicAllocOMNode : ridgeMargins
basicAllocStatic = M.fromList [(ResourceStatic sn (), mpiBox0) | sn <- M.keys stateSignature0]
basicAllocOMNode = M.fromList [(ResourceOMNode nid ir, boxAssignment mpiRankOrigin ir nid)
| ir <- iRanks0, nid <- M.keys stepGraph ]
ridgeMargins = map mkRidgeMargin $ M.toList allRidges
mkRidgeMargin :: Ridge -> M.Map (ResourceT () IRank) Box
mkRidgeMargin (RidgeID _ drsc, box0) = case drsc of
ResourceStatic sn () -> M.singleton (ResourceStatic sn ()) box0
ResourceOMNode nid (_,iDest) -> M.singleton (ResourceOMNode nid iDest) box0
dProg0 <- toList <$> use psDistributedProgramQ
-- insert Free
let numberedProg :: [(Double, DistributedInst)]
numberedProg = zip [0..] dProg0
lastUsed :: M.Map ArrayResourceKey Double
lastUsed = M.unionsWith max
[ M.singleton (ResourceOMNode nid2 ir) ln
| (ln, Computation (ir,nid) _) <- numberedProg
, Just rscmap <- [M.lookup (ir,nid) supportMap]
, ResourceOMNode nid2 () <- M.keys rscmap
]
numberedFrees = [ (ln+0.5, FreeResource ark)
| (ark, ln) <- M.toList lastUsed]
dProg1 = map snd $ sort $ numberedProg ++ numberedFrees
-- simulate resource alloc/free and assign ResourceSharingID
forM_ dProg1 $ \case
FreeResource rsc -> do
rsmap <- use psResourceSharing
case M.lookup rsc rsmap of
Just id0 -> psFreeResourceSharingID %= (id0:)
Nothing -> return ()
Computation _ destRsc@(ResourceOMNode _ _) -> do
rsmap <- use psResourceSharing
case M.lookup destRsc rsmap of
Just _ -> return ()
Nothing -> do
(id0:ids) <- use psFreeResourceSharingID
psResourceSharing %= M.insert destRsc id0
psFreeResourceSharingID .= ids
_ -> return ()
resourceSharing0 <- use psResourceSharing
let largestBox :: Box
largestBox = maximum
[ Orthotope 0 (u-l)
| (ResourceOMNode _ _, Orthotope l u) <- M.toList allAllocs ]
when (?commandLineOption ^. verbose) $ liftIO $ do
putStrLn "#### Allocation List ####"
forM_ (M.toList allAllocs) $ \(rsc, box0) -> do
print rsc
putStrLn $ " " ++ show box0
putStrLn "#### Resource Sharing ####"
let s = M.unionsWith (++) [ M.singleton i [r] | (r,i) <- M.toList resourceSharing0]
forM_ (M.toList s) $ \(i, rs) -> do
print i
forM_ rs $ \rsc -> putStrLn $ " " ++ show rsc
putStrLn "#### Ridge List ####"
forM_ (M.toList allRidges) $ \(rid, box) -> do
putStrLn $ show rid
putStrLn $ " " ++ show box
putStrLn "#### Facet List ####"
forM_ (M.toList allFacets) $ \(f,rs) -> do
putStrLn $ show f
putStrLn $ " " ++ show rs
putStrLn "#### Program ####"
mapM_ print dProg1
return MPIPlan
{ _planArrayAlloc = allAllocs
, _planRidgeAlloc = allRidges
, _planFacetAlloc = allFacets
, _planFacetAssignment = facetAssignment
, _planRegionAlloc = M.fromList
[ ((ir,nid), boxAssignment mpiRankOrigin ir nid)
| ir <- iRanks0
, nid <- M.keys stepGraph
]
, _planDistributedProgram = optimizeCommunicationsOrder $ dProg1
, _planSystemOffset = systemOffset0
, _planResourceSharing = resourceSharing0
, _planSharedResourceExtent = largestBox
, _planResourceNames = M.empty
, _planSharedResourceNames = M.empty
, _planRidgeNames = M.empty
, _planFacetMPITag = M.fromList $ zip (M.keys allFacets) [0..]
, _planMPIRequestNames = M.empty
}
optimizeCommunicationsOrder :: [DistributedInst] -> [DistributedInst]
optimizeCommunicationsOrder dprog = dprog1
where
waitOrder :: M.Map FacetID Int
waitOrder = M.fromList [(fid, i)| (i, CommunicationWait fid) <- zip [0..] dprog ]
groupedProg :: [[DistributedInst]]
groupedProg = groupBy bothComm dprog
dprog1 = concat $ map (sortBy (compare `on` maybeWaitOrder)) groupedProg
bothComm (CommunicationSendRecv _) (CommunicationSendRecv _) = True
bothComm _ _ = False
maybeWaitOrder :: DistributedInst -> Maybe Int
maybeWaitOrder (CommunicationSendRecv fid) = M.lookup fid waitOrder
maybeWaitOrder _ = Nothing
| nushio3/formura | src/Formura/MPICxx/Cut.hs | mit | 21,777 | 10 | 31 | 6,057 | 6,624 | 3,411 | 3,213 | 431 | 17 |
module FrameWithProcessEvent (
frameWithProcessEvent
) where
import Graphics.UI.WXCore
import Graphics.UI.WX.Types
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Layout
import Graphics.UI.WX.Classes
import Graphics.UI.WX.Window
import Graphics.UI.WX.TopLevelWindow
import Graphics.UI.WX.Events
import Graphics.UI.WX.Frame
import Graphics.UI.WXCore.WxcClassesAL
import qualified Data.ByteString as B (ByteString, useAsCStringLen)
import qualified Data.ByteString.Lazy as LB (ByteString, length, unpack)
import System.IO.Unsafe( unsafePerformIO )
import Foreign.C.Types(CInt(..), CWchar(..), CChar(..), CDouble(..))
import Graphics.UI.WXCore.WxcTypes
import Graphics.UI.WXCore.WxcClassTypes
-- this is basicly copied from wxHaskell.
-- Only difference is, that not a wxFrame but a frameWithProcessEvents is created.
-- See frameWithProcessEvent.cpp for details.
-- | Create a top-level frame window.
frameWithProcessEvent :: [Prop (Frame ())] -> IO (Frame ())
frameWithProcessEvent props
= frameWithProcessEventEx frameDefaultStyle props objectNull
-- | Create a top-level frame window in a custom style.
frameWithProcessEventEx :: Style -> [Prop (Frame ())] -> Window a -> IO (Frame ())
frameWithProcessEventEx style props parent
= feed2 props style $
initialFrame $ \id rect txt -> \props style ->
do f <- frameWithProcessEventCreate parent id txt rect style
let initProps = (if (containsProperty visible props)
then [] else [visible := True]) ++
(if (containsProperty bgcolor props)
then [] else [bgcolor := colorSystem Color3DFace])
set f initProps
set f props
return f
-- | usage: (@frameWithProcessEventCreate prt id txt lfttopwdthgt stl@).
frameWithProcessEventCreate :: Window a -> Id -> String -> Rect -> Style -> IO (Frame ())
frameWithProcessEventCreate _prt _id _txt _lfttopwdthgt _stl
= withObjectResult $
withObjectPtr _prt $ \cobj__prt ->
withStringPtr _txt $ \cobj__txt ->
wxFrameWithProcessEvent_Create cobj__prt (toCInt _id) cobj__txt (toCIntRectX _lfttopwdthgt) (toCIntRectY _lfttopwdthgt)(toCIntRectW _lfttopwdthgt) (toCIntRectH _lfttopwdthgt) (toCInt _stl)
foreign import ccall "frameWithProcessEvent.h wxFrameWithProcessEvent_Create" wxFrameWithProcessEvent_Create :: Ptr (TWindow a) -> CInt -> Ptr (TWxString c) -> CInt -> CInt -> CInt -> CInt -> CInt -> IO (Ptr (TFrame ()))
| RudolfVonKrugstein/BiVision | FrameWithProcessEvent.hs | mit | 2,453 | 0 | 19 | 424 | 643 | 356 | 287 | 40 | 3 |
module Framework.LangFramework where
type Var = String
type Label = String
type Name = String
data Op = Plus
| Minus
| Times
| Divide
deriving (Show, Eq)
data Prim = I Int
| V Var
| L Label
| True
| False
| Fn Name
| Void
deriving (Show, Eq)
| cgswords/Grift | Framework/LangFramework.hs | mit | 361 | 0 | 6 | 170 | 95 | 58 | 37 | 17 | 0 |
import Game.Cosanostra.Glue.Instances.JSON ()
import Game.Cosanostra.Game
import Game.Cosanostra.Plan
import Game.Cosanostra.Lenses
import Control.Lens
import Control.Monad.Except
import Control.Monad.State
import qualified Data.ByteString.Char8 as BS
import Data.Yaml hiding ((.=))
import System.Environment
main :: IO ()
main = do
[gamePath, actionGroupsPath, planPath] <- getArgs
game <- either error id <$> decodeEither <$> BS.readFile gamePath
groups <- either error id <$> decodeEither <$> BS.readFile actionGroupsPath
p <- either error id <$> decodeEither <$> BS.readFile planPath
let ((p', _), game') = process game groups p
game' `seq` BS.writeFile gamePath $ encode game'
p' `seq` BS.writeFile planPath $ encode p'
where
process game groups p = (`runState` game) $ do
rng <- use gameRng
(((), rng'), p') <- either (error . show) id <$> runPlanner (runStateT (finishPlan groups) rng)
p
gameRng .= rng'
acts <- either error id <$> (runExceptT $ runNight p')
return (p', acts)
| rfw/cosanostra | glue/run-night.hs | mit | 1,133 | 0 | 16 | 286 | 386 | 203 | 183 | 26 | 1 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package turtle --package exceptions
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveAnyClass #-}
module Main where
import Prelude hiding (FilePath)
import Turtle
import qualified Data.Text as T
import Control.Monad.Catch
import Control.Arrow
main :: IO ()
main = do
(dir, placement) <- (id *** placementFromBool) <$> options "safely add an existing directory to $PATH" parser
Just envPath <- need "PATH"
safePathAdd dir placement envPath
safePathAdd :: (MonadThrow io, MonadIO io) => FilePath -> Placement -> Text -> io ()
safePathAdd dir place path =
getSafePathAdd dir place path
>>= maybe (return ()) (export "PATH")
getSafePathAdd :: (MonadThrow io, MonadIO io) => FilePath -> Placement -> Text -> io (Maybe Text)
getSafePathAdd dir place path = do
dirpath <- getExpandedPath dir
checkPath dirpath
case existsInPath [dirpath, dir] of
True -> return . Just $ appendPath place . format fp $ dirpath
_ -> return Nothing
where
appendPath :: Placement -> Text -> Text
appendPath Cons dir' = dir' <> ":" <> path
appendPath Snoc dir' = path <> ":" <> dir'
existsInPath :: [FilePath] -> Bool
existsInPath dirs = null . filter (`elem` possible) . T.splitOn ":" $ path
where
possible :: [Text]
possible = format fp <$> dirs
getExpandedPath :: MonadIO io => FilePath -> io FilePath
getExpandedPath p = do
(ExitSuccess, fulldir) <- getFirst <$> shellStrict ("echo " <> format fp p) (return "")
realpath fulldir
where
getFirst = (id *** (fromText . head . T.lines))
data Placement = Cons | Snoc
deriving Enum
placementFromBool :: Bool -> Placement
placementFromBool = toEnum . fromEnum
type IsFolder = Bool
type IsFile = Bool
checkPath :: (MonadThrow io, MonadIO io) => FilePath -> io ()
checkPath p = liftM2M checkPathGuard (testdir p) (testfile p)
checkPathGuard :: (MonadThrow io, MonadIO io) => IsFolder -> IsFile -> io ()
checkPathGuard True _ = return ()
checkPathGuard _ True = throwM FoundFileNotDirectory
checkPathGuard _ False = throwM InvalidPath
parser :: Parser (FilePath, Bool)
parser = (,)
<$> argPath "dir" "directory to add to PATH"
<*> switch "tail" 't' "place the directory at the end of the path (defaults to the front)"
liftM2M :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
liftM2M fn ma mb = do { a <- ma; b <- mb; fn a b }
data SafePathAddExceptions
= FoundFileNotDirectory
| InvalidPath
| NoPATHFound
deriving (Show, Exception)
test :: IO ()
test = do
Just path <- need "PATH"
print ("these should work" :: Text)
let canAdd = checkSPA path (Just True)
let cantAdd = checkSPA path Nothing
canAdd "."
canAdd ".."
cantAdd "/bin"
cantAdd "/usr/bin"
cantAdd "$HOME/.local/bin"
cantAdd "~/.local/bin"
print ("these should not work" ::Text)
checkErr path "foobar" $ \(SomeException e) -> return ()
checkErr path "/foobar" $ \(SomeException e) -> return ()
checkErr path "./stack.yaml" $ \FoundFileNotDirectory -> return ()
where
checkErr path p expect =
catch (getSafePathAdd p Cons path >> return ()) $ \e -> expect e >> print True
checkSPA path expect p = do
rdir <- format fp <$> getExpandedPath p
out <- getSafePathAdd p Cons path
let res = not . null . filter (== rdir) . T.splitOn ":" <$> out
print $ res == expect
| stites/scripts | hs/exe/SafePathAdd.hs | mit | 3,478 | 0 | 16 | 769 | 1,198 | 595 | 603 | 84 | 3 |
-- | Based on «Scrap Your Zippers: A Generic Zipper for Heterogeneous Types.
-- Michael D. Adams. WGP '10: Proceedings of the 2010 ACM SIGPLAN
-- workshop on Generic programming, 2010»
-- (<http://michaeldadams.org/papers/scrap_your_zippers/>).
--
-- Compared to the original @syz@ package, this implementation (based on
-- 'GTraversable') gives more flexibility as to where a zipper may point
-- to and what is considered as siblings.
--
-- Specifically, a zipper may point to any element which `gtraverse`
-- applies its function to.
--
-- == Example
-- === syz
-- Consider the classical example: lists. With syz, a list is interpreted as a right-balanced
-- tree.
--
-- >>> let z = fromJust . down' $ toZipper ['a'..'d']
-- >>> getHole z :: Maybe Char
-- Just 'a'
--
-- The zipper @z@ points to the first element of the list. Now let's
-- move to the right:
--
-- >>> let z' = fromJust . right $ z
-- >>> getHole z' :: Maybe Char
-- Nothing
-- >>> getHole z' :: Maybe [Char]
-- Just "bcd"
--
-- Instead of pointing to the second element of the list, as one might
-- expect, the zipper @z\'@ points to the tail of the list. In order to
-- actually move to the second element, we need another 'down'':
--
-- >>> let z'' = fromJust . down' $ z'
-- >>> getHole z'' :: Maybe Char
-- Just 'b'
--
-- === traverse-with-class
-- 'GTraversable'-based zippers behave more intuitively in this regard,
-- thanks to the uniform instance for lists.
--
-- >>> let z = fromJust . down' $ toZipper ['a'..'d'] :: Zipper Typeable [Char]
-- >>> getHole z :: Maybe Char
-- Just 'a'
--
-- So far it's more or less the same as with syz. We needed to add a type
-- annotation for the zipper itself to clarify the context which should
-- be available at each hole ('Typeable' in this case). Now let's see
-- what's to the right of us:
--
-- >>> let z' = fromJust . right $ z
-- >>> getHole z' :: Maybe Char
-- Just 'b'
--
-- That is, we jumped right to the second element of the list. Likewise,
--
-- >>> let z'' = rightmost z
-- >>> getHole z'' :: Maybe Char
-- Just 'd'
--
-- So, unlike in @syz@, all of the list elements are siblings.
{-# LANGUAGE GADTs #-}
module Data.Generics.Traversable.Zipper (
-- * Core types
Zipper(),
-- * Core interface
-- ** Injection and projection
toZipper, fromZipper,
-- ** Basic movement
left, right, down, down', up, leftmost, rightmost,
-- ** Basic hole manipulation
query,
trans,
transM,
-- * Convenience hole manipulation interface
-- | It does not appear easy to make these functions polymorphic over the constraint @c@.
--
-- If you want these functions for your own constraint (which entails
-- 'Typeable'), you need to copy their definitions and change 'Typeable'
-- to your constraint in the 'Zipper' \'s argument.
getHole,
setHole,
setHole'
) where
import Control.Monad (liftM)
import Data.Generics.Traversable
import Data.Typeable (Typeable, cast)
import GHC.Exts (Constraint)
-- Core types
-- | A generic zipper with a root object of type @root@.
data Zipper (c :: * -> Constraint) root =
forall hole. (Rec c hole) =>
Zipper hole (Context c hole root)
---- Internal types and functions
data Context c hole root where
CtxtNull :: Context c a a
CtxtCons ::
forall hole root rights parent c. (Rec c parent) =>
Left c (hole -> rights)
-> Right c rights parent
-> Context c parent root
-> Context c hole root
combine :: Left c (hole -> rights)
-> hole
-> Right c rights parent
-> parent
combine lefts hole rights =
fromRight ((fromLeft lefts) hole) rights
-- Left is essentially Ørjan Johansen’s free applicative functor.
-- (see http://ro-che.info/articles/2013-03-31-flavours-of-free-applicative-functors.html)
--
-- This allows us to convert any GTraversable value to a zipper.
data Left c expects
= LeftUnit expects
| forall b. (Rec c b) => LeftCons (Left c (b -> expects)) b
instance Functor (Left c) where
fmap f (LeftUnit x) = LeftUnit $ f x
fmap f (LeftCons lft x) = LeftCons (fmap (f .) lft) x
instance Applicative (Left c) where
pure = LeftUnit
tx <*> LeftUnit e = fmap ($ e) tx
tx <*> LeftCons ty az = LeftCons ((.) <$> tx <*> ty) az
unit :: Rec c b => b -> Left c b
unit = LeftCons (LeftUnit id)
toLeft :: forall a c . (Rec c a) => a -> Left c a
toLeft = gtraverse @(Rec c) unit
fromLeft :: Left c r -> r
fromLeft (LeftUnit a) = a
fromLeft (LeftCons f b) = fromLeft f b
data Right c provides parent where
RightNull :: Right c parent parent
RightCons ::
(Rec c b) => b -> Right c a t -> Right c (b -> a) t
fromRight :: r -> Right c r parent -> parent
fromRight f (RightNull) = f
fromRight f (RightCons b r) = fromRight (f b) r
-- Core interface
---- Injection and projection
-- | Move up a zipper to the root and return the root object.
fromZipper :: Zipper c a -> a
fromZipper (Zipper hole CtxtNull) = hole
fromZipper (Zipper hole (CtxtCons l r ctxt)) =
fromZipper (Zipper (combine l hole r) ctxt)
-- | Create a zipper. The focus starts at the root of the object.
toZipper :: Rec c a => a -> Zipper c a
toZipper x = Zipper x CtxtNull
---- Basic movement
-- | Move left. Returns 'Nothing' iff already at leftmost sibling.
left :: Zipper c a -> Maybe (Zipper c a)
left (Zipper _ CtxtNull) = Nothing
left (Zipper _ (CtxtCons (LeftUnit _) _ _)) = Nothing
left (Zipper h (CtxtCons (LeftCons l h') r c)) =
Just (Zipper h' (CtxtCons l (RightCons h r) c))
-- | Move right. Returns 'Nothing' iff already at rightmost sibling.
right :: Zipper c a -> Maybe (Zipper c a)
right (Zipper _ CtxtNull) = Nothing
right (Zipper _ (CtxtCons _ RightNull _)) = Nothing
right (Zipper h (CtxtCons l (RightCons h' r) c)) =
Just (Zipper h' (CtxtCons (LeftCons l h) r c))
-- | Move down. Moves to rightmost immediate child. Returns 'Nothing' iff at a leaf and thus no children exist.
down :: forall a c . Zipper c a -> Maybe (Zipper c a)
down (Zipper (hole :: holeT) ctxt) =
case toLeft hole :: Left c holeT of
LeftUnit _ -> Nothing
LeftCons l hole' ->
Just (Zipper hole' (CtxtCons l RightNull ctxt))
-- | Move down. Move to the leftmost immediate child. Returns 'Nothing' iff at a leaf and thus no children exist.
down' :: Zipper c a -> Maybe (Zipper c a)
down' z = liftM leftmost (down z)
-- | Move up. Returns 'Nothing' iff already at root and thus no parent exists.
up :: Zipper c a -> Maybe (Zipper c a)
up (Zipper _ CtxtNull) = Nothing
up (Zipper hole (CtxtCons l r ctxt)) =
Just (Zipper (combine l hole r) ctxt)
---- Basic hole manipulation
-- | Apply a generic query to the hole.
query
:: (forall d . Rec c d => d -> b)
-> Zipper c a -> b
query f (Zipper hole _ctxt) = f hole
-- | Apply a generic transformation to the hole.
trans
:: (forall d . Rec c d => d -> d)
-> Zipper c a -> Zipper c a
trans f (Zipper hole ctxt) = Zipper (f hole) ctxt
-- | Apply a generic monadic transformation to the hole
transM
:: Monad m
=> (forall d . Rec c d => d -> m d)
-> Zipper c a -> m (Zipper c a)
transM f (Zipper hole ctxt) = do
hole' <- f hole
return (Zipper hole' ctxt)
-- Convenience hole manipulation interface
-- | Get the value in the hole. Returns 'Nothing' iff @a@ is not the type of the value in the hole.
getHole :: (Typeable b) => Zipper Typeable a -> Maybe b
getHole = query cast
-- | Set the value in the hole. Does nothing iff @a@ is not the type of the value in the hole.
setHole :: (Typeable a) => a -> Zipper Typeable b -> Zipper Typeable b
setHole h z = trans (maybe id const $ cast h) z
-- | Set the value in the hole. Returns 'Nothing' iff @a@ is not the type of the value in the hole.
setHole' :: (Typeable a) => a -> Zipper Typeable b -> Maybe (Zipper Typeable b)
setHole' h z = transM (const (cast h)) z
-- Generic zipper traversals
---- Traversal helpers
-- | A movement operation such as 'left', 'right', 'up', or 'down'.
type Move c a = Zipper c a -> Maybe (Zipper c a)
-- | Apply a generic query using the specified movement operation.
moveQ :: Move c a -- ^ Move operation
-> b -- ^ Default if can't move
-> (Zipper c a -> b) -- ^ Query if can move
-> Zipper c a -- ^ Zipper
-> b
moveQ move b f z = case move z of
Nothing -> b
Just z' -> f z'
------ Query
-- | Apply a generic query to the left sibling if one exists.
leftQ :: b -- ^ Value to return of no left sibling exists.
-> (Zipper c a -> b) -> Zipper c a -> b
leftQ b f z = moveQ left b f z
-- | Apply a generic query to the right sibling if one exists.
rightQ :: b -- ^ Value to return if no right sibling exists.
-> (Zipper c a -> b) -> Zipper c a -> b
rightQ b f z = moveQ right b f z
-- | Move to the leftmost sibling.
leftmost :: Zipper c a -> Zipper c a
leftmost z = leftQ z leftmost z
-- | Move to the rightmost sibling.
rightmost :: Zipper c a -> Zipper c a
rightmost z = rightQ z rightmost z
| feuerbach/traverse-with-class | Data/Generics/Traversable/Zipper.hs | mit | 8,921 | 0 | 12 | 2,023 | 2,180 | 1,161 | 1,019 | -1 | -1 |
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
data Foo = Foo {a :: Int, b :: Int}
foo Foo{b, ..} = a
| Pnom/haskell-ast-pretty | Test/examples/RecordWildcards.hs | mit | 106 | 0 | 8 | 22 | 40 | 23 | 17 | 3 | 1 |
module Q27 where
combineWithRest :: [a] -> Int -> [([a],[a])]
combineWithRest [] _ = []
combineWithRest (p:q) 1 =
let
rest = combineWithRest q 1
in
([p],q):(map (\(x, y) -> (x, p:y)) rest)
combineWithRest (p:q) r =
let
restTake = (combineWithRest q (r-1))
restDrop = (combineWithRest q r)
in
(map (\(x, y) -> (p:x, y)) restTake) ++ (map (\(x, y) -> (x, p:y)) restDrop)
group :: [Int] -> [a] -> [[[a]]]
group [] x = [[]]
group (p:q) x = foldr (++) [] (map (\(x, y) -> map (\g -> x:g) (group q y)) (combineWithRest x p)) | cshung/MiscLab | Haskell99/q27.hs | mit | 558 | 0 | 13 | 136 | 379 | 212 | 167 | 15 | 1 |
{-# htermination lookup :: (Eq a, Eq k) => (Either a k) -> [((Either a k),b)] -> Maybe b #-}
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Prelude_lookup_11.hs | mit | 93 | 0 | 2 | 20 | 3 | 2 | 1 | 1 | 0 |
{-
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
OpenAPI Version: 3.0.0
OEML - REST API API version: v1
Contact: [email protected]
Generated by OpenAPI Generator (https://openapi-generator.tech)
-}
{-|
Module : OEML-REST.Client
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports #-}
module OEML-REST.Client where
import OEML-REST.Core
import OEML-REST.Logging
import OEML-REST.MimeTypes
import qualified Control.Exception.Safe as E
import qualified Control.Monad.IO.Class as P
import qualified Control.Monad as P
import qualified Data.Aeson.Types as A
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Char8 as BCL
import qualified Data.Proxy as P (Proxy(..))
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Client as NH
import qualified Network.HTTP.Client.MultipartFormData as NH
import qualified Network.HTTP.Types as NH
import qualified Web.FormUrlEncoded as WH
import qualified Web.HttpApiData as WH
import Data.Function ((&))
import Data.Monoid ((<>))
import Data.Text (Text)
import GHC.Exts (IsString(..))
-- * Dispatch
-- ** Lbs
-- | send a request returning the raw http response
dispatchLbs
:: (Produces req accept, MimeType contentType)
=> NH.Manager -- ^ http-client Connection manager
-> OEML-RESTConfig -- ^ config
-> OEML-RESTRequest req contentType res accept -- ^ request
-> IO (NH.Response BCL.ByteString) -- ^ response
dispatchLbs manager config request = do
initReq <- _toInitRequest config request
dispatchInitUnsafe manager config initReq
-- ** Mime
-- | pair of decoded http body and http response
data MimeResult res =
MimeResult { mimeResult :: Either MimeError res -- ^ decoded http body
, mimeResultResponse :: NH.Response BCL.ByteString -- ^ http response
}
deriving (Show, Functor, Foldable, Traversable)
-- | pair of unrender/parser error and http response
data MimeError =
MimeError {
mimeError :: String -- ^ unrender/parser error
, mimeErrorResponse :: NH.Response BCL.ByteString -- ^ http response
} deriving (Show)
-- | send a request returning the 'MimeResult'
dispatchMime
:: forall req contentType res accept. (Produces req accept, MimeUnrender accept res, MimeType contentType)
=> NH.Manager -- ^ http-client Connection manager
-> OEML-RESTConfig -- ^ config
-> OEML-RESTRequest req contentType res accept -- ^ request
-> IO (MimeResult res) -- ^ response
dispatchMime manager config request = do
httpResponse <- dispatchLbs manager config request
let statusCode = NH.statusCode . NH.responseStatus $ httpResponse
parsedResult <-
runConfigLogWithExceptions "Client" config $
do if (statusCode >= 400 && statusCode < 600)
then do
let s = "error statusCode: " ++ show statusCode
_log "Client" levelError (T.pack s)
pure (Left (MimeError s httpResponse))
else case mimeUnrender (P.Proxy :: P.Proxy accept) (NH.responseBody httpResponse) of
Left s -> do
_log "Client" levelError (T.pack s)
pure (Left (MimeError s httpResponse))
Right r -> pure (Right r)
return (MimeResult parsedResult httpResponse)
-- | like 'dispatchMime', but only returns the decoded http body
dispatchMime'
:: (Produces req accept, MimeUnrender accept res, MimeType contentType)
=> NH.Manager -- ^ http-client Connection manager
-> OEML-RESTConfig -- ^ config
-> OEML-RESTRequest req contentType res accept -- ^ request
-> IO (Either MimeError res) -- ^ response
dispatchMime' manager config request = do
MimeResult parsedResult _ <- dispatchMime manager config request
return parsedResult
-- ** Unsafe
-- | like 'dispatchReqLbs', but does not validate the operation is a 'Producer' of the "accept" 'MimeType'. (Useful if the server's response is undocumented)
dispatchLbsUnsafe
:: (MimeType accept, MimeType contentType)
=> NH.Manager -- ^ http-client Connection manager
-> OEML-RESTConfig -- ^ config
-> OEML-RESTRequest req contentType res accept -- ^ request
-> IO (NH.Response BCL.ByteString) -- ^ response
dispatchLbsUnsafe manager config request = do
initReq <- _toInitRequest config request
dispatchInitUnsafe manager config initReq
-- | dispatch an InitRequest
dispatchInitUnsafe
:: NH.Manager -- ^ http-client Connection manager
-> OEML-RESTConfig -- ^ config
-> InitRequest req contentType res accept -- ^ init request
-> IO (NH.Response BCL.ByteString) -- ^ response
dispatchInitUnsafe manager config (InitRequest req) = do
runConfigLogWithExceptions src config $
do _log src levelInfo requestLogMsg
_log src levelDebug requestDbgLogMsg
res <- P.liftIO $ NH.httpLbs req manager
_log src levelInfo (responseLogMsg res)
_log src levelDebug ((T.pack . show) res)
return res
where
src = "Client"
endpoint =
T.pack $
BC.unpack $
NH.method req <> " " <> NH.host req <> NH.path req <> NH.queryString req
requestLogMsg = "REQ:" <> endpoint
requestDbgLogMsg =
"Headers=" <> (T.pack . show) (NH.requestHeaders req) <> " Body=" <>
(case NH.requestBody req of
NH.RequestBodyLBS xs -> T.decodeUtf8 (BL.toStrict xs)
_ -> "<RequestBody>")
responseStatusCode = (T.pack . show) . NH.statusCode . NH.responseStatus
responseLogMsg res =
"RES:statusCode=" <> responseStatusCode res <> " (" <> endpoint <> ")"
-- * InitRequest
-- | wraps an http-client 'Request' with request/response type parameters
newtype InitRequest req contentType res accept = InitRequest
{ unInitRequest :: NH.Request
} deriving (Show)
-- | Build an http-client 'Request' record from the supplied config and request
_toInitRequest
:: (MimeType accept, MimeType contentType)
=> OEML-RESTConfig -- ^ config
-> OEML-RESTRequest req contentType res accept -- ^ request
-> IO (InitRequest req contentType res accept) -- ^ initialized request
_toInitRequest config req0 =
runConfigLogWithExceptions "Client" config $ do
parsedReq <- P.liftIO $ NH.parseRequest $ BCL.unpack $ BCL.append (configHost config) (BCL.concat (rUrlPath req0))
req1 <- P.liftIO $ _applyAuthMethods req0 config
P.when
(configValidateAuthMethods config && (not . null . rAuthTypes) req1)
(E.throw $ AuthMethodException $ "AuthMethod not configured: " <> (show . head . rAuthTypes) req1)
let req2 = req1 & _setContentTypeHeader & _setAcceptHeader
params = rParams req2
reqHeaders = ("User-Agent", WH.toHeader (configUserAgent config)) : paramsHeaders params
reqQuery = let query = paramsQuery params
queryExtraUnreserved = configQueryExtraUnreserved config
in if B.null queryExtraUnreserved
then NH.renderQuery True query
else NH.renderQueryPartialEscape True (toPartialEscapeQuery queryExtraUnreserved query)
pReq = parsedReq { NH.method = rMethod req2
, NH.requestHeaders = reqHeaders
, NH.queryString = reqQuery
}
outReq <- case paramsBody params of
ParamBodyNone -> pure (pReq { NH.requestBody = mempty })
ParamBodyB bs -> pure (pReq { NH.requestBody = NH.RequestBodyBS bs })
ParamBodyBL bl -> pure (pReq { NH.requestBody = NH.RequestBodyLBS bl })
ParamBodyFormUrlEncoded form -> pure (pReq { NH.requestBody = NH.RequestBodyLBS (WH.urlEncodeForm form) })
ParamBodyMultipartFormData parts -> NH.formDataBody parts pReq
pure (InitRequest outReq)
-- | modify the underlying Request
modifyInitRequest :: InitRequest req contentType res accept -> (NH.Request -> NH.Request) -> InitRequest req contentType res accept
modifyInitRequest (InitRequest req) f = InitRequest (f req)
-- | modify the underlying Request (monadic)
modifyInitRequestM :: Monad m => InitRequest req contentType res accept -> (NH.Request -> m NH.Request) -> m (InitRequest req contentType res accept)
modifyInitRequestM (InitRequest req) f = fmap InitRequest (f req)
-- ** Logging
-- | Run a block using the configured logger instance
runConfigLog
:: P.MonadIO m
=> OEML-RESTConfig -> LogExec m a
runConfigLog config = configLogExecWithContext config (configLogContext config)
-- | Run a block using the configured logger instance (logs exceptions)
runConfigLogWithExceptions
:: (E.MonadCatch m, P.MonadIO m)
=> T.Text -> OEML-RESTConfig -> LogExec m a
runConfigLogWithExceptions src config = runConfigLog config . logExceptions src
| coinapi/coinapi-sdk | oeml-sdk/haskell-http-client/lib/OEML-REST/Client.hs | mit | 9,415 | 4 | 21 | 1,863 | 2,192 | 1,157 | 1,035 | -1 | -1 |
module System.AtomicWrite.Writer.TextSpec (spec) where
import Test.Hspec (it, describe, shouldBe, Spec)
import System.AtomicWrite.Writer.Text (atomicWriteFile, atomicWriteFileWithMode)
import System.IO.Temp (withSystemTempDirectory)
import System.FilePath.Posix (joinPath)
import System.PosixCompat.Files
(setFileMode, setFileCreationMask, getFileStatus, fileMode)
import Data.Text (pack)
spec :: Spec
spec = do
describe "atomicWriteFile" $ do
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFile path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
it "preserves the permissions of original file, regardless of umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let filePath = joinPath [tmpDir, "testFile"]
writeFile filePath "initial contents"
setFileMode filePath 0o100644
newStat <- getFileStatus filePath
fileMode newStat `shouldBe` 0o100644
-- New files are created with 100600 perms.
_ <- setFileCreationMask 0o100066
-- Create a new file once different mask is set and make sure that mask
-- is applied.
writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask"
sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"]
fileMode sanityCheckStat `shouldBe` 0o100600
-- Since we move, this makes the new file assume the filemask of 0600
atomicWriteFile filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- Fails when using atomic mv command unless apply perms on initial file
fileMode resultStat `shouldBe` 0o100644
it "creates a new file with permissions based on active umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let
filePath = joinPath [tmpDir, "testFile"]
sampleFilePath = joinPath [tmpDir, "sampleFile"]
-- Set somewhat distinctive defaults for test
_ <- setFileCreationMask 0o100171
-- We don't know what the default file permissions are, so create a
-- file to sample them.
writeFile sampleFilePath "I'm being written to sample permissions"
newStat <- getFileStatus sampleFilePath
fileMode newStat `shouldBe` 0o100606
atomicWriteFile filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- The default tempfile permissions are 0600, so this fails unless we
-- make sure that the default umask is relied on for creation of the
-- tempfile.
fileMode resultStat `shouldBe` 0o100606
describe "atomicWriteFileWithMode" $ do
it "writes contents to a file" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let path = joinPath [ tmpDir, "writeTest.tmp" ]
atomicWriteFileWithMode 0o100777 path $ pack "just testing"
contents <- readFile path
contents `shouldBe` "just testing"
it "changes the permissions of a previously created file, regardless of umask" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let filePath = joinPath [tmpDir, "testFile"]
writeFile filePath "initial contents"
setFileMode filePath 0o100644
newStat <- getFileStatus filePath
fileMode newStat `shouldBe` 0o100644
-- New files are created with 100600 perms.
_ <- setFileCreationMask 0o100066
-- Create a new file once different mask is set and make sure that mask
-- is applied.
writeFile (joinPath [tmpDir, "sanityCheck"]) "with sanity check mask"
sanityCheckStat <- getFileStatus $ joinPath [tmpDir, "sanityCheck"]
fileMode sanityCheckStat `shouldBe` 0o100600
-- Since we move, this makes the new file assume the filemask of 0600
atomicWriteFileWithMode 0o100655 filePath $ pack "new contents"
resultStat <- getFileStatus filePath
-- reset mask to not break subsequent specs
_ <- setFileCreationMask 0o100022
-- Fails when using atomic mv command unless apply perms on initial file
fileMode resultStat `shouldBe` 0o100655
it "creates a new file with specified permissions" $
withSystemTempDirectory "atomicFileTest" $ \tmpDir -> do
let
filePath = joinPath [tmpDir, "testFile"]
atomicWriteFileWithMode 0o100606 filePath $ pack "new contents"
resultStat <- getFileStatus filePath
fileMode resultStat `shouldBe` 0o100606
| stackbuilders/atomic-write | spec/System/AtomicWrite/Writer/TextSpec.hs | mit | 4,883 | 0 | 18 | 1,240 | 882 | 431 | 451 | 74 | 1 |
module Feature.Comment.PG where
import ClassyPrelude
import Feature.Comment.Types
import Feature.Auth.Types
import Platform.PG
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple
findComments :: PG r m => Maybe UserId -> Slug -> Maybe CommentId -> m [Comment]
findComments mayUserId slug mayCommentId =
withConn $ \conn -> query conn qry arg
where
qry = [sql|
with profiles as (
select
id, name, bio, image, exists(select 1 from followings where user_id = id and followed_by = ?) as following
from
users
), formatted_comments as (
select
c.article_id, c.id, c.created_at, c.updated_at, c.body,
p.name as pname, p.bio as pbio, p.image as pimage, p.following as pfollowing
from
comments c join profiles p on p.id = c.author_id
)
select
c.id, c.created_at, c.updated_at, c.body,
cast (c.pname as text), c.pbio, c.pimage, c.pfollowing
from
formatted_comments c join articles a on c.article_id = a.id
where
a.slug = ? and
coalesce(c.id = ?, true)
|]
arg = (mayUserId, slug, mayCommentId)
addCommentToSlug :: PG r m => UserId -> Slug -> Text -> m CommentId
addCommentToSlug uId slug comment = do
results <- withConn $ \conn -> query conn qry arg
return $ case results of
[Only cmtId] -> cmtId
_ -> -1
where
qry = "with cte as ( \
\ select id from articles where slug = ? limit 1 \
\) \
\insert into comments (article_id, created_at, updated_at, body, author_id) \
\(select id, now(), now(), ?, ? from cte) \
\returning id"
arg = (slug, comment, uId)
isCommentExist :: PG r m => CommentId -> m Bool
isCommentExist cId = do
results <- withConn $ \conn -> query conn qry arg
return $ results == [Only True]
where
qry = "select true from comments where id = ? limit 1"
arg = (Only cId)
isCommentOwnedBy :: PG r m => UserId -> CommentId -> m Bool
isCommentOwnedBy uId cId = do
results <- withConn $ \conn -> query conn qry arg
return $ results == [Only True]
where
qry = "select true from comments where author_id = ? and id = ? limit 1"
arg = (uId, cId)
delCommentById :: PG r m => CommentId -> m ()
delCommentById cId =
void . withConn $ \conn -> execute conn qry (Only cId)
where
qry = "delete from comments where id = ?"
| eckyputrady/haskell-scotty-realworld-example-app | src/Feature/Comment/PG.hs | mit | 2,552 | 0 | 12 | 783 | 491 | 257 | 234 | -1 | -1 |
import Declar
import Environment
import Parser
import Syntax
import Typing
import Control.Exception
import System.IO
importFile :: String -> IO Handle
importFile s = openFile ("lib/" ++ s ++ ".hs") ReadMode
driverLoop :: Handle -> Handle
-> TyState -> TyEnv -> Env
-> IO (TyState, TyEnv, Env)
driverLoop input output tystate tyenv env = do
eof <- hIsEOF input
if eof
then return (tystate, tyenv, env)
else do
str <- hGetLine input
case parseStmt str of
Left er -> do
hPutStrLn stderr er
driverLoop input output tystate tyenv env
Right st -> catch (catch ( do
let (ntystate, (ntyenv, t)) = typing tyenv st tystate
case st of
Import s -> do
ninput <- importFile s
(a, b, c) <- driverLoop ninput stderr ntystate ntyenv env
driverLoop input output a b c
_ -> do
let l = decl env st
mapM_ (hPutStrLn output) (map (\(_, s, e) -> concat [s, " = ", show e, " :: ", show t]) l)
let (nenv, _, _) = last l
driverLoop input output ntystate ntyenv nenv ) err) ioerr
where err e = do
hPutStrLn stderr ("Error: " ++ show (e :: ErrorCall))
driverLoop input output tystate tyenv env
ioerr e = do
hPutStrLn stderr ("Error: " ++ show (e :: IOException))
driverLoop input output tystate tyenv env
main :: IO()
main = do
prelude <- importFile "Prelude"
(tystate, tyenv, env) <- driverLoop prelude stderr 0 [] Environment.empty
(_, _, _) <- driverLoop stdin stdout tystate tyenv env
return()
| asi1024/haling | src-exec/main.hs | mit | 1,656 | 0 | 31 | 533 | 624 | 308 | 316 | 46 | 4 |
{-# LANGUAGE TypeFamilies,StandaloneDeriving,CPP #-}
module UnitB.UnitB
( module UnitB.Syntax
, module UnitB.UnitB
, theory_po )
where
-- Modules
import UnitB.Expr
import UnitB.PO
import UnitB.Syntax
import Logic.Expr.Scope
import Logic.Proof
import Logic.Proof.Tactics hiding (assert)
--import Logic.Proof.POGenerator hiding ( variables )
--import qualified Logic.Proof.POGenerator as POG
--import Logic.Theory
--import Logic.WellDefinedness
import Z3.Z3
-- Libraries
import Control.DeepSeq
import Control.Invariant
import Control.Lens hiding (indices,Context,Context',(.=))
import Control.Lens.Misc
import Control.Monad hiding (guard)
import Control.Precondition
import Data.Default
import Data.Compressed
import Data.Either.Validation
#if MIN_VERSION_transformers(0,5,0)
import Prelude.Extras hiding (Lift1)
import qualified Data.Functor.Classes as F
#else
import Data.Functor.Classes
#endif
import Data.Functor.Compose
import Data.List as L hiding (inits, union,insert)
import Data.Map as M hiding
( map, (!)
, delete, filter, null
, (\\), mapMaybe )
import qualified Data.Map as M
import Data.Serialize
import qualified Data.Set as S
import GHC.Generics (Generic1)
import GHC.Generics.Instances
import Test.QuickCheck.ZoomEq
import Text.Printf.TH as Printf
import Utilities.Syntactic
type Machine' = Compose Checked MachinePO'
type RawMachine = Machine' RawExpr
type Machine = Machine' Expr
type SystemSyntax' expr = SystemBase (MachineWithProofs' expr)
type SystemSyntax = SystemSyntax' RawExpr
type SystemSemantics' expr = System' (Machine' expr)
type SystemSemantics = SystemSemantics' RawExpr
type System = System' Machine
type CompressedSystem = Compressed (Compose SystemBase MachineWithProofs') RawExpr
type RawSystem = System' (Machine' RawExpr)
type MachineWithProofs = MachineWithProofs' RawExpr
data MachineWithProofs' expr = MachineWithProofs
(MachineBase expr)
(Map Label (ProofBase expr))
deriving (Functor,Foldable,Traversable,Generic)
type Key = (Label,Label)
type SeqMap = Map Key (Sequent,Maybe Bool)
data MachinePO' expr = MachinePO
{ _syntax :: MachineAST' expr
, _proofs :: Map Label Proof
, _raw_proof_obligation_field :: Box (Map Label Sequent)
, _proof_obligation_field :: MemBox (Map Label Sequent) }
deriving (Functor,Foldable,Traversable,Show,Generic,Generic1,Eq)
newtype Box a = Box (() -> a)
deriving (Generic)
newtype MemBox a = MemBox a
deriving (Eq,Default,NFData,Generic)
class IsBox f where
box :: (() -> a) -> f a
unbox :: f a -> a
instance IsBox Box where
unbox (Box f) = f ()
box = Box
instance IsBox MemBox where
unbox (MemBox x) = x
box = MemBox . ($ ())
instance Show a => Show (Box a) where
show (Box f) = show $ f ()
instance Eq a => Eq (Box a) where
Box f == Box g = f () == g ()
instance Default a => Default (Box a) where
def = Box $ const def
instance Show a => Show (MemBox a) where
show (MemBox f) = show f
makeLenses ''MachinePO'
po_table :: SystemSemantics' expr -> SeqMap
po_table sys = fmap (,Nothing) . uncurryMap $ proof_obligation <$> (mapKeys as_label $ sys!.machines)
_machineSyntax :: Prism' MachineWithProofs RawMachine
_machineSyntax = prism'
(\m -> MachineWithProofs (m!.syntax.content') (m!.proofs))
(\(MachineWithProofs m ps) -> rightToMaybe $ withProofs ps $ check m)
_Syntax :: Prism' SystemSyntax SystemSemantics
_Syntax = below _machineSyntax.from content
compressingSystem :: Prism' CompressedSystem SystemSemantics
compressingSystem = packaged._Wrapped._Syntax
makeMachinePO' :: MachineAST' expr -> MachinePO' expr
makeMachinePO' x = MachinePO x def def def
raw_proof_obligation :: Controls machine (MachinePO' expr)
=> machine -> Map Label Sequent
raw_proof_obligation = view $ content'.raw_proof_obligation_field.to unbox
proof_obligation :: Controls machine (MachinePO' expr)
=> machine -> Map Label Sequent
proof_obligation = view (content'.proof_obligation_field.to unbox)
instance Controls (MachinePO' expr) (MachinePO' expr) where
--instance IsExpr expr => IsChecked (MachineAST' expr) (MachineAST' expr) where
-- check arse m = fromRight'' arse $ withPO _ _
-- content arse = _
--func =
instance (HasExpr expr,ZoomEq expr) => HasMachineBase (MachinePO' expr) expr where
machineBase = syntax.content
instance (HasExpr expr,ZoomEq expr) => HasAbs_vars (MachinePO' expr) (Map Name Var) where
abs_vars = machineBase.abs_vars
instance HasName (MachinePO' expr) Name where
name = syntax.content'.name
instance (HasExpr expr,ZoomEq expr) => HasMachine (Machine' expr) expr where
type Internal (Machine' expr) expr = MachinePO' expr
empty_machine = fromSyntax . empty_machine
instance (HasExpr expr,ZoomEq expr) => HasMachine (MachinePO' expr) expr where
type Internal (MachinePO' expr) expr = MachinePO' expr
empty_machine = view content' . fromSyntax . empty_machine
instance (HasExpr expr,ZoomEq expr) => HasDefs (MachinePO' expr) (Map Name expr) where
defs = machineBase.defs
instance HasExpr expr => HasInvariant (MachinePO' expr) where
invariant m = do
"inv1" ## keysSet (m^.proofs) `S.isSubsetOf` keysSet (raw_proof_obligation m)
updateCache m = m
{ _raw_proof_obligation_field = b
, _proof_obligation_field = box $
\() -> fromRight' $ proof_obligation' pos
(fmap getExpr <$> m^.proofs)
(getExpr <$> m^.syntax) }
where
b = box $ \() -> raw_machine_pos' $ m^.syntax
pos = unbox b
#if MIN_VERSION_transformers(0,5,0)
instance F.Eq1 MachinePO' where
liftEq = genericLiftEq
instance F.Show1 MachinePO' where
liftShowsPrec = genericLiftShowsPrec
#else
instance Eq1 MachinePO' where
eq1 = (==)
#endif
instance PrettyPrintable expr => PrettyPrintable (MachinePO' expr) where
instance NFData expr => NFData (MachinePO' expr) where
instance NFData expr => NFData (MachineWithProofs' expr) where
instance Serialize expr => Serialize (MachineWithProofs' expr) where
instance Show1 MachinePO' where
showsPrec1 = showsPrec
instance NFData (Box a) where
rnf x = seq x ()
deriving instance ZoomEq a => ZoomEq (MemBox a)
instance ZoomEq a => ZoomEq (Box a) where
Box f .== Box g = f () .== g ()
instance ZoomEq expr => ZoomEq (MachinePO' expr) where
fromSyntax :: HasExpr expr => MachineAST' expr -> Machine' expr
fromSyntax m = check $ makeMachinePO' m
withProofs :: IsExpr expr
=> Map Label (ProofBase expr)
-> MachineAST' expr
-> Either [Error] (Machine' expr)
withProofs p m = fmap check' $ do
let poBox = box $ \() -> raw_machine_pos' m
pos = unbox poBox
pos <- proof_obligation' pos p m
return $ MachinePO m p poBox (box $ \() -> pos)
withProofs' :: (IsExpr expr,Pre)
=> Map Label Proof
-> MachineAST' expr
-> Machine' expr
withProofs' p m = check $ makeMachinePO' m & proofs .~ p
withPOs :: HasExpr expr
=> Map Label (Tactic Proof,LineInfo)
-> MachineAST' expr
-> Either [Error] (Machine' expr)
withPOs ps m = fmap check' $ do
let poBox = box $ \() -> raw_machine_pos' m
pos = unbox poBox
p = intersectionWith (\s (t,li) -> eitherToValidation $ runTactic li s t) pos ps
f lbl (_,li) = Error ([Printf.s|proof obligation does not exist: %s\n\n%s|]
(pretty lbl) (unlines $ map pretty $ M.keys pos)) li
errs = concat (p^.partsOf (traverse._Failure)) ++ elems (mapWithKey f $ ps `difference` pos)
errs' | null errs = sequenceA p
| otherwise = Failure errs
p <- validationToEither errs'
pos <- proof_obligation' pos (fmap getExpr <$> p) (getExpr <$> m)
return $ MachinePO m p poBox (box $ \() -> pos)
--proof_obligation_field (const $ box . const <$> proof_obligation' pos m) m'
verify_changes :: Machine -> Map Label (Bool,Sequent) -> IO (Map Label (Bool,Sequent), String,Int)
verify_changes m old_pos = do
let pos = proof_obligation m
new_pos = differenceWith f pos old_pos
res <- verify_all new_pos
let { h k p0 = (
case M.lookup k res of
Just b -> (b,p0)
Nothing -> old_pos ! k) }
let all_pos = M.mapWithKey h pos
(res,_,_) <- format_result (M.map fst all_pos)
return (all_pos,res, M.size new_pos)
where
f p0 (_,p1)
| p0 == p1 = Nothing
| otherwise = Just p0
str_verify_machine :: HasExpr expr => Machine' expr -> IO (String,Int,Int)
str_verify_machine = str_verify_machine_with (const Just)
str_verify_machine_with :: HasExpr expr
=> (Label -> Sequent -> Maybe Sequent)
-> Machine' expr
-> IO (String,Int,Int)
str_verify_machine_with opt m = do
let pos = mapMaybeWithKey opt $ proof_obligation m
xs <- verify_all pos
format_result xs
smoke_test_machine :: Machine -> IO (String)
smoke_test_machine m = do
let pos = proof_obligation m
rs <- flip filterM (M.toList pos) $ \(lbl,po) -> do
r <- smoke_test lbl po
return $ r == Valid
return $ L.unlines $ L.map (show . fst) rs
verify_machine :: Machine -> IO (Int, Int)
verify_machine m = do
(s,i,j) <- str_verify_machine m
putStrLn s
return (i,j)
format_result :: Map Label Bool -> IO (String,Int,Int)
format_result xs' = do
let rs = L.map f $ M.toAscList xs'
total = L.length rs
passed = L.length $ L.filter fst rs
xs = "passed " ++ (show passed) ++ " / " ++ show total
ys = L.map snd rs ++ [xs]
return (L.unlines ys, passed, total)
where
f (y,True) = (True, " o " ++ pretty y)
f (y,False) = (False," xxx " ++ pretty y)
| literate-unitb/literate-unitb | src/UnitB/UnitB.hs | mit | 10,287 | 0 | 17 | 2,666 | 3,317 | 1,722 | 1,595 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Services.TextAndImages
( routes
) where
import Control.Monad (replicateM_)
import Snap.Blaze (blaze)
import Simulation.Node.Service.Http
( HttpService
, Routes (..)
, putResponse
)
import Simulation.Node.Service.Http.Server
( static
, mkPrefixFunc
, htmlResponse
, loremIpsum
)
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
routes :: Routes ()
routes = Routes [ ( "1.html", page "Page 1" 4 ["2.html", "3.html", "4.html"]
allImages )
, ( "2.html", page "Page 2" 8 ["1.html", "3.html", "4.html"]
allImages )
, ( "3.html", page "Page 3" 7 ["1.html", "2.html", "4.html"]
allImages )
, ( "4.html", page "Page 4" 13 ["1.html", "2.html", "3.html"]
allImages )
, ( "static", static) ]
page :: H.Html -> Int -> [String] -> [String] -> HttpService ()
page theTitle paragrafs links images = do
putResponse htmlResponse
prefix <- mkPrefixFunc
blaze $ do
H.docType
H.head $ do
H.title theTitle
H.script ! A.src (prefix "static/textandimages.js") $ ""
H.link ! A.href (prefix "static/textandimages.css")
H.body $ do
replicateM_ paragrafs $ H.p loremIpsum
mapM_ (\l -> H.a ! A.href (prefix l) $ (H.toHtml l)) links
mapM_ (\img -> H.img ! A.src (prefix img)) images
allImages :: [String]
allImages = [ "static/image1.jpg", "static/image2.jpg", "static/image3.jpg"
, "static/image4.jpg", "static/image5.jpg" ]
| kosmoskatten/programmable-endpoint-demo | src/Services/TextAndImages.hs | mit | 1,759 | 0 | 20 | 548 | 507 | 281 | 226 | 44 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGLinearGradientElement
(js_getX1, getX1, js_getY1, getY1, js_getX2, getX2, js_getY2,
getY2, SVGLinearGradientElement, castToSVGLinearGradientElement,
gTypeSVGLinearGradientElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"x1\"]" js_getX1 ::
SVGLinearGradientElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGLinearGradientElement.x1 Mozilla SVGLinearGradientElement.x1 documentation>
getX1 ::
(MonadIO m) =>
SVGLinearGradientElement -> m (Maybe SVGAnimatedLength)
getX1 self = liftIO (nullableToMaybe <$> (js_getX1 (self)))
foreign import javascript unsafe "$1[\"y1\"]" js_getY1 ::
SVGLinearGradientElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGLinearGradientElement.y1 Mozilla SVGLinearGradientElement.y1 documentation>
getY1 ::
(MonadIO m) =>
SVGLinearGradientElement -> m (Maybe SVGAnimatedLength)
getY1 self = liftIO (nullableToMaybe <$> (js_getY1 (self)))
foreign import javascript unsafe "$1[\"x2\"]" js_getX2 ::
SVGLinearGradientElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGLinearGradientElement.x2 Mozilla SVGLinearGradientElement.x2 documentation>
getX2 ::
(MonadIO m) =>
SVGLinearGradientElement -> m (Maybe SVGAnimatedLength)
getX2 self = liftIO (nullableToMaybe <$> (js_getX2 (self)))
foreign import javascript unsafe "$1[\"y2\"]" js_getY2 ::
SVGLinearGradientElement -> IO (Nullable SVGAnimatedLength)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGLinearGradientElement.y2 Mozilla SVGLinearGradientElement.y2 documentation>
getY2 ::
(MonadIO m) =>
SVGLinearGradientElement -> m (Maybe SVGAnimatedLength)
getY2 self = liftIO (nullableToMaybe <$> (js_getY2 (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGLinearGradientElement.hs | mit | 2,745 | 24 | 10 | 365 | 638 | 377 | 261 | 43 | 1 |
module JSON(JValue(..), JSONSerializable(..), isNull, prettifiedJSONString) where
import JSON.Type(JValue(..), JSONSerializable(..), isNull)
import JSON.Parser
import JSON.Prettify
prettifiedJSONString :: String -> String
prettifiedJSONString str = either show prettyJSON $ parseJSON str
| zsedem/haskell-playground | json-parser/src/JSON.hs | mit | 289 | 0 | 6 | 29 | 89 | 54 | 35 | 6 | 1 |
module Ruab.Backend
-- exports {{{1
(
module Ruab.Backend.GDB
, setup
) where
-- imports {{{1
import Ruab.Backend.GDB hiding (setup)
import qualified Ruab.Backend.GDB as B
import Ruab.Options (Options(optGdbLog, optBinary))
setup :: Options -> Callback -> IO Context -- {{{1
setup opt callback = B.setup (optGdbLog opt) (optBinary opt) callback
| copton/ocram | ruab/src/Ruab/Backend.hs | gpl-2.0 | 353 | 0 | 7 | 56 | 105 | 64 | 41 | 9 | 1 |
{- |
Module : $Header$
Description : RDF Morphism
Copyright : (c) Francisc-Nicolae Bungiu, Felix Gabriel Mance, 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Morphisms for RDF
-}
module RDF.Morphism where
import Common.DocUtils
import Common.Doc
{-
import Common.Lib.State
import Common.Lib.MapSet (setToMap)
import Common.Result
import OWL2.AS
import RDF.AS
-}
import RDF.Sign
import RDF.Function
{- import RDF.StaticAnalysis
import RDF.Symbols -}
import RDF.Print ()
{- }
import Control.Monad
import Data.Maybe
-}
import qualified Data.Map as Map
import qualified Data.Set as Set
data RDFMorphism = RDFMorphism
{ osource :: Sign
, otarget :: Sign
, mmaps :: MorphMap
} deriving (Show, Eq, Ord)
{- }
inclRDFMorphism :: Sign -> Sign -> RDFMorphism
inclRDFMorphism s t = RDFMorphism
{ osource = s
, otarget = t
, mmaps = Map.empty }
symMap :: MorphMap -> Map.Map RDFEntity RDFEntity
symMap = Map.mapWithKey (\ (RDFEntity ty _) -> RDFEntity ty)
inducedElems :: MorphMap -> [RDFEntity]
inducedElems = Map.elems . symMap
inducedSign :: MorphMap -> Sign -> Sign
inducedSign m = execState (do
mapM_ (modEntity Set.delete) $ Map.keys m
mapM_ (modEntity Set.insert) $ inducedElems m)
inducedFromMor :: Map.Map RawSymb RawSymb -> Sign -> Result RDFMorphism
inducedFromMor rm sig = do
let syms = symOf sig
mm <- foldM (\ m p -> case p of
(ASymbol s@(RDFEntity _ v), ASymbol (RDFEntity _ u)) ->
if Set.member s syms
then return $ if u == v then m else Map.insert s u m
else fail $ "unknown symbol: " ++ showDoc s "\n" ++ shows sig ""
(AnUri v, AnUri u) -> case filter (`Set.member` syms)
$ map (`RDFEntity` v) rdfEntityTypes of
[] -> fail $ "unknown symbol: " ++ showDoc v "\n" ++ shows sig ""
l -> return $ if u == v then m else foldr (`Map.insert` u) m l
_ -> error "RDF.Morphism.inducedFromMor") Map.empty $ Map.toList rm
return RDFMorphism
{ osource = sig
, otarget = inducedSign mm sig
, mmaps = mm }
symMapOf :: RDFMorphism -> Map.Map RDFEntity RDFEntity
symMapOf mor = Map.union (symMap $ mmaps mor) $ setToMap $ symOf $ osource mor
-}
isRDFInclusion :: RDFMorphism -> Bool
isRDFInclusion m = Map.null (mmaps m) && isSubSign (osource m) (otarget m)
instance Pretty RDFMorphism where
pretty m = let
s = osource m
srcD = specBraces $ space <> pretty s
t = otarget m
in fsep $ if isRDFInclusion m then
if isSubSign t s then
[text "identity morphism over", srcD]
else
[ text "inclusion morphism of"
, srcD
, text "extended with"
, pretty $ Set.difference (symOf t) $ symOf s ]
else
[ pretty $ mmaps m
, colon <+> srcD, mapsto <+> specBraces (space <> pretty t) ]
{-
legalMor :: RDFMorphism -> Result ()
legalMor m = let mm = mmaps m in unless
(Set.isSubsetOf (Map.keysSet mm) (symOf $ osource m)
&& Set.isSubsetOf (Set.fromList $ inducedElems mm) (symOf $ otarget m))
$ fail "illegal RDF morphism"
composeMor :: RDFMorphism -> RDFMorphism -> Result RDFMorphism
composeMor m1 m2 =
let nm = Set.fold (\ s@(RDFEntity ty u) -> let
t = getIri ty u $ mmaps m1
r = getIri ty t $ mmaps m2
in if r == u then id else Map.insert s r) Map.empty
. symOf $ osource m1
in return m1
{ otarget = otarget m2
, mmaps = nm }
cogeneratedSign :: Set.Set RDFEntity -> Sign -> Result RDFMorphism
cogeneratedSign s sign =
let sig2 = execState (mapM_ (modEntity Set.delete) $ Set.toList s) sign
in if isSubSign sig2 sign then return $ inclRDFMorphism sig2 sign else
fail "non RDF subsignatures for (co)generatedSign"
generatedSign :: Set.Set RDFEntity -> Sign -> Result RDFMorphism
generatedSign s sign = cogeneratedSign (Set.difference (symOf sign) s) sign
matchesSym :: RDFEntity -> RawSymb -> Bool
matchesSym e@(RDFEntity _ u) r = case r of
ASymbol s -> s == e
AnUri s -> s == u || namePrefix u == localPart s && null (namePrefix s)
statSymbItems :: [SymbItems] -> [RawSymb]
statSymbItems = concatMap
$ \ (SymbItems m us) -> case m of
Nothing -> map AnUri us
Just ty -> map (ASymbol . RDFEntity ty) us
statSymbMapItems :: [SymbMapItems] -> Result (Map.Map RawSymb RawSymb)
statSymbMapItems =
foldM (\ m (s, t) -> case Map.lookup s m of
Nothing -> return $ Map.insert s t m
Just u -> case (u, t) of
(AnUri su, ASymbol (RDFEntity _ tu)) | su == tu ->
return $ Map.insert s t m
(ASymbol (RDFEntity _ su), AnUri tu) | su == tu -> return m
_ -> if u == t then return m else
fail $ "differently mapped symbol: " ++ showDoc s "\nmapped to "
++ showDoc u " and " ++ showDoc t "")
Map.empty
. concatMap (\ (SymbMapItems m us) ->
let ps = map (\ (u, v) -> (u, fromMaybe u v)) us in
case m of
Nothing -> map (\ (s, t) -> (AnUri s, AnUri t)) ps
Just ty ->
let mS = ASymbol . RDFEntity ty
in map (\ (s, t) -> (mS s, mS t)) ps)
mapSen :: RDFMorphism -> Axiom -> Result Axiom
mapSen m a = return $ function Rename (MorphMap $ mmaps m) a
-}
| nevrenato/HetsAlloy | RDF/Morphism.hs | gpl-2.0 | 5,335 | 0 | 16 | 1,414 | 315 | 173 | 142 | 29 | 1 |
{-# LANGUAGE TypeFamilies #-}
{- Cheap and cheesy lists with sizes in their types.
- Copyright : (C)opyright 2006, 2011 peteg42 at gmail dot com
- License : GPL (see COPYING for details)
-
- We count from /1/ to /n/, i.e. the first element of the list has index 1.
-}
module ADHOC.Data.SizedLists where
-------------------------------------------------------------------
-- Dependencies.
-------------------------------------------------------------------
import Prelude hiding ( id, (.) )
import Control.Monad ( liftM )
import Test.QuickCheck ( Arbitrary(..), vectorOf )
import ADHOC.Circuits
import ADHOC.Generics
import ADHOC.Patterns
-------------------------------------------------------------------
-- Lists with a static sized type.
-------------------------------------------------------------------
newtype SizedList size a = SizedList { unSizedList :: [a] }
deriving (Eq, Show)
instance (Card size, Arbitrary a) => Arbitrary (SizedList size a) where
arbitrary = fmap SizedList (vectorOf width arbitrary)
where width = c2num (undefined :: size) :: Int
idSL :: (Card size, Category (~>)) => size -> SizedList size a ~> SizedList size a
idSL = const id
-- | Similar to 'asTypeOf', but just for 'SizedList' lengths.
asLengthOf :: SizedList size a -> SizedList size b -> SizedList size a
asLengthOf = const
-- | Similar to 'asLengthOf', but uses just a size.
withLength :: SizedList size a -> size -> SizedList size a
withLength = const
-- | An arrowized version of the constructor, unsafe, not exported to the end user.
sizedListA :: Arrow arrow => arrow [a] (SizedList size a)
sizedListA = arr SizedList
unSizedListA :: Arrow arrow => arrow (SizedList size a) [a]
unSizedListA = arr unSizedList
instance (Card size, Zero (~>) a) => Zero (~>) (SizedList size a) where
zeroA = zeroA >>> replicateSL
instance (Card size, StructureDest s a) => StructureDest s (SizedList size a) where
destructure = concat . map destructure . unSizedList
instance (Card size, Structure s a) => Structure s (SizedList size a) where
type SIwidth s (SizedList size a) = CardMul size (SIwidth s a)
structure = SizedList <$> for [1..width] (const structure)
where
width = c2num (undefined :: size) :: Integer
-------------------------------------------------------------------
-- Constructor: replicateL.
-------------------------------------------------------------------
-- | FIXME: grotty, run-time errors
mkSizedListA :: forall (~>) size a. (Arrow (~>), Card size) => [a] ~> SizedList size a
mkSizedListA = proc xs ->
do let
width = c2num (undefined :: size) :: Int
l = length xs
returnA -< if l /= width
then error $ "mkSizedList: list has length " ++ show l ++ " /= size " ++ show width
else SizedList xs
-- | Fan out a value.
replicateSL :: forall (~>) size a. (Arrow (~>), Card size)
=> a ~> SizedList size a
replicateSL = arr (SizedList . replicate (c2num (undefined :: size)))
-- | Make a 'SizedList' using a function. The 'size' measures the list
-- length, i.e. list element indices start at 1.
mkSizedListf :: forall size a. (Card size)
=> (Integer -> a) -> SizedList size a
mkSizedListf f = SizedList [ f i | i <- [1 .. c2num (undefined :: size) :: Integer] ]
-- | Make a 'SizedList' using a function, arrow command combinator
-- edition. The 'size' measures the list length., i.e. list element
-- indices start at 1.
mkSizedListAC :: forall (~>) size env a. (Arrow (~>), Card size)
=> (Integer -> env ~> a) -> env ~> SizedList size a
mkSizedListAC f = mkL 1 >>> sizedListA
where
width = c2num (undefined :: size)
mkL :: Integer -> env ~> [a]
mkL i | i == succ width = arr (const [])
| otherwise = proc env ->
do a <- f i -< env
as <- mkL (succ i) -< env
returnA -< a : as
-- | Make a 'SizedList' using a function. The 'size' measures the list
-- length, i.e. list element indices start at 1. We also thread a
-- value through the constructor ala 'rowSLn'.
fanoutSL :: forall (~>) size a b env. (Arrow (~>), Card size)
=> (Integer -> (env, a) ~> (a, b)) -> (env, a) ~> (a, SizedList size b)
fanoutSL f = mkL 1 >>> second sizedListA
where
width = c2num (undefined :: size)
mkL :: Integer -> (env, a) ~> (a, [b])
mkL i | i == succ width = arr (\(_env, a) -> (a, []))
| otherwise = proc (env, a) ->
do (a', b) <- f i -< (env, a)
(a'', bs) <- mkL (succ i) -< (env, a')
returnA -< (a'', b : bs)
mkSizedListSingletonA :: forall (~>) a. Arrow (~>)
=> a ~> SizedList One a
mkSizedListSingletonA = arr (SizedList . (:[]))
-------------------------------------------------------------------
-- Operations.
-------------------------------------------------------------------
foldrSL :: forall arrow size b c. (Arrow arrow, Card size)
=> arrow (b, c) b
-> arrow () b
-> arrow (SizedList size c) b
foldrSL f z = unSizedListA >>> foldrA (c2num (undefined :: size)) f z
foldr1SL :: forall (~>) size b. (Arrow (~>), Card size)
=> (b, b) ~> b
-> SizedList size b ~> b
foldr1SL f = unSizedListA >>> foldr1A (c2num (undefined :: size)) f
mapSL :: forall (~>) size b c. (Arrow (~>), Card size)
=> b ~> c
-> SizedList size b ~> SizedList size c
mapSL f = unSizedListA >>> mapA (c2num (undefined :: size)) f >>> sizedListA
mapSLn :: forall (~>) size b c. (Arrow (~>), Card size)
=> (Integer -> b ~> c) -> SizedList size b ~> SizedList size c
mapSLn f = unSizedListA >>> mapAn (c2num (undefined :: size)) f >>> sizedListA
mapSLC :: forall (~>) size b c env. (Arrow (~>), Card size)
=> (env, b) ~> c
-> (env, SizedList size b) ~> SizedList size c
mapSLC f = id *** unSizedListA >>> mapAC (c2num (undefined :: size)) f >>> sizedListA
-- | FIXME a semi-static?? map.
mapSLs :: forall (~>) size b c env. (Arrow (~>), Card size)
=> (b -> (env ~> c))
-> SizedList size b
-> env ~> SizedList size c
mapSLs f sl = foldr f' z (unSizedListA sl) >>> sizedListA
where
f' b rarr = liftA2 (:) (f b) rarr
z = arr (const [])
rowSLn :: forall arrow size a b c .
(Arrow arrow, Card size)
=> (Integer -> arrow (a, b) (a, c))
-> arrow (a, SizedList size b) (a, SizedList size c)
rowSLn f =
second unSizedListA
>>> rowAn (c2num (undefined :: size)) f
>>> second sizedListA
rotateSL :: forall (~>) size b. (Arrow (~>), Card size)
=> SizedList size b ~> SizedList size b
rotateSL = unSizedListA >>> arr rotate >>> sizedListA
where
rotate [] = []
rotate (x:xs) = xs ++ [x]
sequenceSL :: forall (~>) size b m. (Arrow (~>), Card size, Monad m)
=> SizedList size (m b) ~> m (SizedList size b)
sequenceSL = unSizedListA >>> arr (liftM sizedListA . sequence)
zipWithSL :: forall (~>) b c d size . (Arrow (~>), Card size)
=> (b, c) ~> d
-> (SizedList size b, SizedList size c) ~> (SizedList size d)
zipWithSL f = (unSizedListA *** unSizedListA) >>> zipWithA n f >>> sizedListA
where n = c2num (undefined :: size)
-- | FIXME a semi-static?? 'zipWith'. This is some form of currying.
zipWithSLs :: forall (~>) size b c d. (Arrow (~>), Card size)
=> (b -> (c ~> d))
-> SizedList size b
-> (SizedList size c ~> SizedList size d)
zipWithSLs f sl = unSizedListA >>> foldr f' z (unSizedListA sl) >>> sizedListA
where
f' b rarr = proc (c:cs) ->
do d <- f b -< c
ds <- rarr -< cs
returnA -< d : ds
z = arr (const [])
conjoinSL :: forall (~>) size. (Arrow (~>), ArrowComb (~>), Card size)
=> SizedList size (B (~>)) ~> B (~>)
conjoinSL = unSizedListA >>> conjoinA (c2num (undefined :: size))
disjoinSL :: forall (~>) size. (Arrow (~>), ArrowComb (~>), Card size)
=> SizedList size (B (~>)) ~> B (~>)
disjoinSL = unSizedListA >>> disjoinA (c2num (undefined :: size))
| peteg/ADHOC | ADHOC/Data/SizedLists.hs | gpl-2.0 | 8,079 | 154 | 14 | 1,979 | 1,919 | 1,267 | 652 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Lib.Set
( filterA, partitionA
) where
import Prelude.Compat
import Data.Set (Set)
import qualified Data.Set as S
import qualified Lib.List as L
filterA :: (Applicative f, Ord k) => (k -> f Bool) -> Set k -> f (Set k)
filterA p = fmap S.fromAscList . L.filterA p . S.toAscList
partitionA :: (Applicative f, Ord k) => (k -> f Bool) -> Set k -> f (Set k, Set k)
partitionA p = fmap mconcat . traverse onEach . S.toAscList
where
onEach x = partitionOne x <$> p x
partitionOne x True = (S.singleton x, S.empty)
partitionOne x False = (S.empty, S.singleton x)
| da-x/buildsome | src/Lib/Set.hs | gpl-2.0 | 622 | 0 | 10 | 133 | 270 | 141 | 129 | 14 | 2 |
base :: [Integer]
base = [1..9]
seqs :: (Num a1, Ord a1) => a1 -> [a] -> [[a]]
seqs n [] = if n > 0 then [] else [[]]
seqs n (x:s)
| n == 0 = [[]]
| True = map (x:) (seqs (n-1) s) ++ seqs n s
diagNeg :: [[Integer]] -> [[Integer]]
diagNeg = zipWith (zipWith (*)) . (repeat 1:) . iterate (1:) $ (negate 1:repeat 1)
seqsNeg :: (Num a, Ord a) => [Integer] -> a -> [[Integer]]
seqsNeg s n = concatMap (\ t -> diagNeg $ t : map (const t) t) $ seqs n s
positive :: [Integer] -> Bool
positive = all (>0)
negative :: [Integer] -> Bool
negative = any (<0)
hasAbs n = any ((==) n . abs)
has n = any ((==) n)
doesntHaveAbs n = not . hasAbs n
sumIs n = (==) n . sum
magic :: [a -> Bool] -> [a] -> [a]
magic = foldr (.) id . map filter
or' :: [b -> Bool] -> b -> Bool
or' s x = or $ map (flip id x) s
and' :: [b -> Bool] -> b -> Bool
and' s x = and $ map (flip id x) s
requestedSolution = sum [4,6, 2,6,8,9, 4,5,6, 1,6,4,7, 9,7, 1,4,2, 6,8,1,4, 1,5,4, 6,7,4,1, 6,4]
solution =
[ " 7 8 9 _ _ _ 5 4 6-1" -- -1
, " 1 2 7 _ 3 4 6-5 8 9" -- -5
, " 4-9 5 _ 1 3 2 6 7 _" -- -9
, " 3 1 6-2 4 5 7 8 9 _" -- -2
, " 2 4 8 9 _ 7-1 _ _ _" -- -1
, " _ _ _ 1-9 _ 4 3 2 5" -- -9
, " _ 5 2 7 6 8 9 1-3 4" -- -3
, " _ 3 1 8 5-2 _ 7 4 6" -- -2
, " 6 7-3 4 2 1 _ 9 5 8" -- -3
, "-5 6 4 3 _ _ _ 2 1 7" -- -5
]
-- read from bottom to top...
example = magic
[ positive -- all numbers are positive
, doesntHaveAbs 4 -- there is no +-4
, doesntHaveAbs 5 -- there is no +-5
, doesntHaveAbs 9 -- there is no +-9
, has 6 -- there is 6
, sumIs 19 -- sum is 19
] -- where
$ seqsNeg base 5 -- 5 digit sequences of 1..9
| xkollar/handy-haskell | other/js-2016-07/js-2016-07.hs | gpl-3.0 | 1,711 | 0 | 12 | 556 | 789 | 445 | 344 | 45 | 2 |
{-# LANGUAGE FlexibleInstances
, UndecidableInstances
#-}
module Data.Pickle
( encode
, decode
, Picklable(..))
where
import Data.ByteString
import qualified Data.Serialize as S
class Picklable a where
dumps :: a -> ByteString
loads :: ByteString -> Either String a
-- aliases
encode :: Picklable a => a -> ByteString
encode = dumps
decode :: Picklable a => ByteString -> Either String a
decode = loads
-- Serialize is picklable
instance S.Serialize a => Picklable a where
dumps = S.encode
loads = S.decode
| br0ns/hindsight | src/Data/Pickle.hs | gpl-3.0 | 565 | 0 | 8 | 139 | 147 | 82 | 65 | 18 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Schema.Platform.V0 where
import Data.Text (Text)
import qualified Database.Persist.Sql as Sql
import Database.Persist.TH (persistUpperCase)
import qualified Database.Persist.TH as TH
TH.share [TH.mkPersist TH.sqlSettings, TH.mkSave "schema"] [persistUpperCase|
GPU
name Text
prettyName Text Maybe
UniqGPU name
deriving Eq Show
|]
| merijn/GPU-benchmarks | benchmark-analysis/src/Schema/Platform/V0.hs | gpl-3.0 | 725 | 0 | 8 | 99 | 89 | 60 | 29 | 17 | 0 |
module System.DevUtils.Base.Url.Session (
Session(..),
defaultSession
) where
import qualified System.DevUtils.Base.Url.Auth as A
import qualified System.DevUtils.Base.Url.Connection as C
data Session = Session {
_auth :: Maybe A.Auth,
_con :: C.Connection
} deriving (Show, Read)
defaultSession :: Session
defaultSession = Session { _auth = Nothing, _con = C.defaultConnection }
| adarqui/DevUtils-Base | src/System/DevUtils/Base/Url/Session.hs | gpl-3.0 | 387 | 0 | 10 | 54 | 108 | 71 | 37 | 11 | 1 |
#!/usr/bin/runhaskell
import Distribution.Simple
main :: IO ()
main = defaultMain
| styx/gtc | Setup.hs | gpl-3.0 | 83 | 0 | 6 | 11 | 22 | 12 | 10 | 3 | 1 |
module Country where
import Data.SafeCopy
import Data.Typeable
import qualified Data.Map as M
import qualified Data.Aeson as J
import qualified Data.Text.Lazy.Encoding as E
import qualified Data.Text.Lazy as L
import Data.Time.Clock
import GHC.Generics
import Network.URL
type IsoCodeAlpha2 = String
data Country = Country { isoCode :: IsoCodeAlpha2,
name :: String,
url :: String,
description :: String}
deriving (Show, Typeable, Generic, Eq, Ord)
data SubdivisionType = Emirate | State | Province | District | Other
deriving (Show, Typeable, Generic, Eq, Ord)
data Subdivision = Subdivision {sdivName :: String,
sdivType :: SubdivisionType}
deriving (Show, Typeable, Generic, Eq, Ord)
data CountrySubDivision = CountrySubdivision {
parentCountry :: Country,
subdivision :: Subdivision
} deriving (Show, Typeable, Generic, Eq, Ord)
getURL :: Country -> Maybe URL
getURL (Country _ _ url _) = importURL url
updateURL :: Country -> URL -> Country
updateURL aCountry aURL = aCountry {url = exportURL aURL}
instance J.ToJSON Subdivision
instance J.FromJSON Subdivision
instance J.ToJSON SubdivisionType
instance J.FromJSON SubdivisionType
instance J.ToJSON CountrySubDivision
instance J.ToJSON Country
instance J.FromJSON Country
$(deriveSafeCopy 0 'base ''Country)
$(deriveSafeCopy 0 'base ''Subdivision)
$(deriveSafeCopy 0 'base ''SubdivisionType)
$(deriveSafeCopy 0 'base ''CountrySubDivision) | dservgun/erp | src/common/Country.hs | gpl-3.0 | 1,559 | 0 | 8 | 345 | 457 | 252 | 205 | -1 | -1 |
module Data.IntSet (module X) where
import "containers" Data.IntSet as X
| wdanilo/container | src/Data/IntSet.hs | apache-2.0 | 74 | 0 | 4 | 11 | 20 | 14 | 6 | -1 | -1 |
--
-- Copyright : (c) T.Mishima 2014
-- License : Apache-2.0
--
{-# LANGUAGE BangPatterns #-}
module Bindings.OculusRift where
import Foreign.Ptr
import Foreign.C.String
import Foreign.C.Types
import Foreign.Storable
import Foreign.Marshal.Array
import Foreign.Marshal.Alloc
import Data.Word
import Bindings.OculusRift.Types
--import Debug.Trace
-- |
-- convert ovrBool to Bool
--
-- >>> ovrBool2Bool '1'
-- True
ovrBool2Bool :: OvrBool -> Bool
ovrBool2Bool = ('0' /= ).castCCharToChar
bool2OvrBool :: Bool -> OvrBool
bool2OvrBool False = castCharToCChar '0'
bool2OvrBool _ = castCharToCChar '1'
-- |
-- castTo OvrHmdDesc
--
castToOvrHmdDesc :: Ptr OvrHmdDesc -> IO OvrHmdDesc
castToOvrHmdDesc pHmd = peek pHmd
-- |
-- printHmdDesc
--
printHmdDesc :: OvrHmdDesc -> IO ()
printHmdDesc hmd = do
putStrLn $ "Hmdtype : " ++ (show $ hmdtype hmd)
putStrLn $ "ProductName : " ++ (productName hmd)
putStrLn $ "Manufacturer : " ++ (manufacturer hmd)
putStrLn $ "VendorID(USB) : " ++ (show $ vendorId hmd)
putStrLn $ "ProductID(USB) : " ++ (show $ productId hmd)
putStrLn $ "SerialNumber : " ++ (serialNumber hmd)
putStrLn $ "Version Num : " ++ (show $ firmwareMajor hmd)
++ "." ++ (show $ firmwareMinor hmd)
putStrLn $ "CameraFrustumHFovInRadians : " ++
(show $ cameraFrustumHFovInRadians hmd)
putStrLn $ "CameraFrustumVFovInRadians : " ++
(show $ cameraFrustumVFovInRadians hmd)
putStrLn $ "CameraFrustumNearZInMeters : " ++
(show $ cameraFrustumNearZInMeters hmd)
putStrLn $ "CameraFrustumFarZInMeters : " ++
(show $ cameraFrustumFarZInMeters hmd)
putStrLn $ "HmdCaps : " ++ (show $ hmdCaps hmd)
putStrLn $ "TrackingCaps : " ++ (show $ trackingCaps hmd)
putStrLn $ "DistortionCaps : " ++ (show $ distortionCaps hmd)
putStrLn $ "DefaultEyeFov : " ++ (show $ defaultEyeFov hmd)
putStrLn $ "MaxEyeFov : " ++ (show $ maxEyeFov hmd)
putStrLn $ "EyeRenderOrder : " ++ (show $ eyeRenderOrder hmd)
putStrLn $ "Resolution : " ++ (show $ resolution hmd)
putStrLn $ "WindowsPos : " ++ (show $ windowsPos hmd)
putStrLn $ "DisplayDeviceName : " ++ (displayDeviceName hmd)
putStrLn $ "DisplayId : " ++ (show $ displayId hmd)
-- | ovr_InitializeRenderingShim initializes the rendering shim appart from everything
-- else in LibOVR. This may be helpful if the application prefers to avoid
-- creating any OVR resources (allocations, service connections, etc) at this point.
-- ovr_InitializeRenderingShim does not bring up anything within LibOVR except the
-- necessary hooks to enable the Direct-to-Rift functionality.
--
-- Either ovr_InitializeRenderingShim() or ovr_Initialize() must be called before any
-- Direct3D or OpenGL initilization is done by applictaion (creation of devices, etc).
-- ovr_Initialize() must still be called after to use the rest of LibOVR APIs.
ovr_InitializeRenderingShim :: IO Bool
ovr_InitializeRenderingShim = fmap ovrBool2Bool c_ovr_InitializeRenderingShim
-- | Library init/shutdown, must be called around all other OVR code.
-- No other functions calls are allowed before ovr_Initialize succeeds or after ovr_Shutdown.
-- Initializes all Oculus functionality.
--
ovr_Initialize :: IO Bool
ovr_Initialize = fmap ovrBool2Bool c_ovr_Initialize
-- | Shuts down all Oculus functionality.
--
ovr_Shutdown :: IO ()
ovr_Shutdown = c_ovr_Shutdown
-- | Returns version string representing libOVR version. Static, so
-- string remains valid for app lifespan
--
ovr_GetVersionString :: IO String
ovr_GetVersionString = peekCString c_ovr_GetVersionString
-- | Detects or re-detects HMDs and reports the total number detected.
-- Users can get information about each HMD by calling ovrHmd_Create with an index.
--
ovrHmd_Detect :: IO Int
ovrHmd_Detect = fmap fromIntegral c_ovrHmd_Detect
-- | Creates a handle to an HMD which doubles as a description structure.
-- Index can [0 .. ovrHmd_Detect()-1]. Index mappings can cange after each ovrHmd_Detect call.
-- If not null, then the returned handle must be freed with ovrHmd_Destroy.
ovrHmd_Create :: Int -> IO (Maybe OvrHmd)
ovrHmd_Create idx = do
hdl <- c_ovrHmd_Create $ fromIntegral idx
return $ if hdl /= nullPtr
then Just hdl
else Nothing
ovrHmd_Destroy :: OvrHmd -> IO ()
ovrHmd_Destroy = c_ovrHmd_Destroy
-- | Creates a 'fake' HMD used for debugging only. This is not tied to specific hardware,
-- but may be used to debug some of the related rendering.
--
ovrHmd_CreateDebug :: OvrHmdType -> IO OvrHmd
ovrHmd_CreateDebug (OvrHmdType t) = c_ovrHmd_CreateDebug $ fromIntegral t
-- | Returns last error for HMD state. Returns null for no error.
-- String is valid until next call or GetLastError or HMD is destroyed.
-- Pass null hmd to get global errors (during create etc).
--
ovrHmd_GetLastError :: OvrHmd -> IO String
ovrHmd_GetLastError hmd = peekCString =<< c_ovrHmd_GetLastError hmd
-- | Platform specific function to specify the application window whose output will be
-- displayed on the HMD. Only used if the ovrHmdCap_ExtendDesktop flag is false.
-- Windows: SwapChain associated with this window will be displayed on the HMD.
-- Specify 'destMirrorRect' in window coordinates to indicate an area
-- of the render target output that will be mirrored from 'sourceRenderTargetRect'.
-- Null pointers mean "full size".
-- @note Source and dest mirror rects are not yet implemented.
--
ovrHmd_AttachToWindow :: OvrHmd -> HWND -> Maybe OvrRecti -> Maybe OvrRecti
-> IO Bool
ovrHmd_AttachToWindow hmd win destMirrorRect sourceRenderTargetRect =
alloca $ \ destMirrorRect' ->
alloca $ \ sourceRenderTargetRect' -> do
pd <- case destMirrorRect of
Just d -> poke destMirrorRect' d >> return destMirrorRect'
Nothing -> return nullPtr
ps <- case sourceRenderTargetRect of
Just s -> poke sourceRenderTargetRect' s
>> return sourceRenderTargetRect'
Nothing -> return nullPtr
fmap ovrBool2Bool (c_ovrHmd_AttachToWindow hmd win pd ps)
-------------------------------------------------------------------------------------
-- | Returns capability bits that are enabled at this time as described by ovrHmdCaps.
-- Note that this value is different font ovrHmdDesc::HmdCaps, which describes what
-- capabilities are available for that HMD.
--
ovrHmd_GetEnabledCaps :: OvrHmd -> IO OvrHmdCaps
ovrHmd_GetEnabledCaps hmd = do
(CUInt caps) <- c_ovrHmd_GetEnabledCaps hmd
return $ OvrHmdCaps (fromIntegral caps)
-- | Modifies capability bits described by ovrHmdCaps that can be modified,
-- such as ovrHmd_LowPersistance.
--
ovrHmd_SetEnabledCaps :: OvrHmd -> OvrHmdCaps -> IO ()
ovrHmd_SetEnabledCaps hmd (OvrHmdCaps caps) =
c_ovrHmd_SetEnabledCaps hmd (CUInt caps)
-------------------------------------------------------------------------------------
-- ***** Tracking Interface
-- | All tracking interface functions are thread-safe, allowing tracking state to be sampled
-- from different threads.
-- ConfigureTracking starts sensor sampling, enabling specified capabilities,
-- described by ovrTrackingCaps.
-- - supportedTrackingCaps specifies support that is requested. The function will succeed
-- even if these caps are not available (i.e. sensor or camera is unplugged). Support
-- will automatically be enabled if such device is plugged in later. Software should
-- check ovrTrackingState.StatusFlags for real-time status.
-- - requiredTrackingCaps specify sensor capabilities required at the time of the call.
-- If they are not available, the function will fail. Pass 0 if only specifying
-- supportedTrackingCaps.
-- - Pass 0 for both supportedTrackingCaps and requiredTrackingCaps to disable tracking.
--
--
ovrHmd_ConfigureTracking :: OvrHmd -> OvrTrackingCaps -> OvrTrackingCaps
-> IO Bool
ovrHmd_ConfigureTracking hmd (OvrTrackingCaps supportedTrackingCaps)
(OvrTrackingCaps requiredTrackingCaps) =
fmap ovrBool2Bool $
c_ovrHmd_ConfigureTracking hmd (CUInt supportedTrackingCaps)
(CUInt requiredTrackingCaps)
-- | Re-centers the sensor orientation.
-- Normally this will recenter the (x,y,z) translational components and the yaw
-- component of orientation.
--
ovrHmd_RecenterPose :: OvrHmd -> IO ()
ovrHmd_RecenterPose = c_ovrHmd_RecenterPose
-- | Returns tracking state reading based on the specified absolute system time.
-- Pass an absTime value of 0.0 to request the most recent sensor reading. In this case
-- both PredictedPose and SamplePose will have the same value.
-- ovrHmd_GetEyePose relies on this internally.
-- This may also be used for more refined timing of FrontBuffer rendering logic, etc.
--
ovrHmd_GetTrackingState :: OvrHmd -> Double -> IO OvrTrackingState
ovrHmd_GetTrackingState hmd absTime = do
peek =<< c_ovrHmd_GetTrackingState hmd (CDouble absTime)
-------------------------------------------------------------------------------------
-- ***** Graphics Setup
-- | Calculates the recommended texture size for rendering a given eye within the HMD
-- with a given FOV cone. Higher FOV will generally require larger textures to
-- maintain quality.
-- - pixelsPerDisplayPixel specifies the ratio of the number of render target pixels
-- to display pixels at the center of distortion. 1.0 is the default value. Lower
-- values can improve performance.
--
ovrHmd_GetFovTextureSize :: OvrHmd -> OvrEyeType -> Ptr OvrFovPort
-> Float -> IO OvrSizei
ovrHmd_GetFovTextureSize hmd (OvrEyeType et) fovp pixelsPerDisplayPixel =
peek =<<
c_ovrHmd_GetFovTextureSize hmd et fovp (CFloat pixelsPerDisplayPixel)
ovrHmd_GetDefaultFovTextureSize :: OvrHmd -> OvrEyeType
-> Float -> IO OvrSizei
ovrHmd_GetDefaultFovTextureSize hmd (OvrEyeType et)
pixelsPerDisplayPixel = do
peek =<<
c_ovrHmd_GetFovTextureSize hmd et fovp (CFloat pixelsPerDisplayPixel)
where
fovp = getDefaultEyeFovPtr hmd (OvrEyeType et)
ovrHmd_GetDefaultFov :: OvrHmd -> OvrEyeType -> IO OvrFovPort
ovrHmd_GetDefaultFov hmd et = peek fovp
where fovp = getDefaultEyeFovPtr hmd et
-------------------------------------------------------------------------------------
-- | ***** SDK Distortion Rendering Functions
-- These functions support rendering of distortion by the SDK through direct
-- access to the underlying rendering API, such as D3D or GL.
-- This is the recommended approach since it allows better support for future
-- Oculus hardware, and enables a range of low-level optimizations.
-- Configures rendering and fills in computed render parameters.
-- This function can be called multiple times to change rendering settings.
-- eyeRenderDescOut is a pointer to an array of two ovrEyeRenderDesc structs
-- that are used to return complete rendering information for each eye.
--
-- - apiConfig provides D3D/OpenGL specific parameters. Pass null
-- to shutdown rendering and release all resources.
-- - distortionCaps describe desired distortion settings.
--
ovrHmd_ConfigureRendering :: OvrHmd -> Maybe OvrRenderAPIConfig
-> OvrDistortionCaps -> [OvrFovPort]
-> IO (Bool,[OvrEyeRenderDesc])
ovrHmd_ConfigureRendering hmd (Just renderAPIconfig)
(OvrDistortionCaps distortionCaps') eyeFovIn = do
alloca $ \ racPtr ->
alloca $ \ fovPtr -> do
alloca $ \ rdPtr -> do
poke racPtr renderAPIconfig
pokeArray fovPtr eyeFovIn
ret <- fmap ovrBool2Bool $
c_ovrHmd_ConfigureRendering hmd racPtr (CUInt distortionCaps')
fovPtr rdPtr
eyeRenderDescOut <- if rdPtr /= nullPtr
then peekArray 2 rdPtr
else return []
return (ret,eyeRenderDescOut)
ovrHmd_ConfigureRendering hmd Nothing (OvrDistortionCaps distortionCaps')
eyeFovIn = do
alloca $ \ fovPtr ->
alloca $ \ rdPtr -> do
pokeArray fovPtr eyeFovIn
ret <- fmap ovrBool2Bool $
c_ovrHmd_ConfigureRendering hmd nullPtr (CUInt distortionCaps')
fovPtr rdPtr
eyeRenderDescOut <- if rdPtr /= nullPtr
then peekArray 2 rdPtr
else return []
return (ret,eyeRenderDescOut)
-- | Begins a frame, returning timing information.
-- This should be called at the beginning of the game rendering loop (on the render thread).
-- Pass 0 for the frame index if not using ovrHmd_GetFrameTiming.
--
ovrHmd_BeginFrame :: OvrHmd -> Word32 -> IO OvrFrameTiming
ovrHmd_BeginFrame hmd frameIndex = do
peek =<<
c_ovrHmd_BeginFrame hmd (CUInt frameIndex)
-- | Ends a frame, submitting the rendered textures to the frame buffer.
-- - RenderViewport within each eyeTexture can change per frame if necessary.
-- - 'renderPose' will typically be the value returned from ovrHmd_GetEyePose,
-- but can be different if a different head pose was used for rendering.
-- - This may perform distortion and scaling internally, assuming is it not
-- delegated to another thread.
-- - Must be called on the same thread as BeginFrame.
-- - *** This Function will call Present/SwapBuffers and potentially wait for GPU Sync ***.
--
ovrHmd_EndFrame :: OvrHmd -> [OvrPosef] -> [OvrTexture] -> IO ()
ovrHmd_EndFrame hmd renderPose eyeTexture = do
alloca $ \ rp ->
alloca $ \ et -> do
pokeArray rp renderPose
pokeArray et eyeTexture
c_ovrHmd_EndFrame hmd rp et
-- |
-- Returns predicted head pose in outHmdTrackingState and offset eye poses in outEyePoses
-- as an atomic operation. Caller need not worry about applying HmdToEyeViewOffset to the
-- returned outEyePoses variables.
-- - Thread-safe function where caller should increment frameIndex with every frame
-- and pass the index where applicable to functions called on the rendering thread.
-- - hmdToEyeViewOffset[2] can be ovrEyeRenderDesc.HmdToEyeViewOffset returned from
-- ovrHmd_ConfigureRendering or ovrHmd_GetRenderDesc. For monoscopic rendering,
-- use a vector that is the average of the two vectors for both eyes.
-- - If frameIndex is not being used, pass in 0.
-- - Assuming outEyePoses are used for rendering, it should be passed into ovrHmd_EndFrame.
-- - If called doesn't need outHmdTrackingState, it can be NULL
--
ovrHmd_GetEyePoses :: OvrHmd -> Word32 -> [OvrVector3f]
-> IO [OvrPosef]
ovrHmd_GetEyePoses hmd frameIndex hmdToEyeViewOffset' =
alloca $ \ viewOffset -> do
pokeArray viewOffset hmdToEyeViewOffset'
peekArray 2 =<<
c_ovrHmd_GetEyePoses hmd (CUInt frameIndex) viewOffset nullPtr
ovrHmd_GetEyePosesWithTrackingState :: OvrHmd -> Word32 -> [OvrVector3f]
-> IO (OvrTrackingState, [OvrPosef])
ovrHmd_GetEyePosesWithTrackingState hmd frameIndex hmdToEyeViewOffset' =
alloca $ \ viewOffset ->
alloca $ \ st -> do
pokeArray viewOffset hmdToEyeViewOffset'
po <- c_ovrHmd_GetEyePoses hmd (CUInt frameIndex) viewOffset st
status <- peek st
pose <- peekArray 2 po
return (status,pose)
-- | Returns the predicted head pose to use when rendering the specified eye.
-- - Must be called between ovrHmd_BeginFrameTiming and ovrHmd_EndFrameTiming.
-- - If the pose is used for rendering the eye, it should be passed to ovrHmd_EndFrame.
--
ovrHmd_GetHmdPosePerEye :: OvrHmd -> OvrEyeType -> IO OvrPosef
ovrHmd_GetHmdPosePerEye hmd (OvrEyeType et) = do
peek =<< c_ovrHmd_GetHmdPosePerEye hmd et
-------------------------------------------------------------------------------------
-- ***** Client Distortion Rendering Functions
--
-- These functions provide the distortion data and render timing support necessary to allow
-- client rendering of distortion. Client-side rendering involves the following steps:
--
-- 1. Setup ovrEyeDesc based on the desired texture size and FOV.
-- Call ovrHmd_GetRenderDesc to get the necessary rendering parameters for each eye.
--
-- 2. Use ovrHmd_CreateDistortionMesh to generate the distortion mesh.
--
-- 3. Use ovrHmd_BeginFrameTiming, ovrHmd_GetEyePose, and ovrHmd_BeginFrameTiming
-- in the rendering loop to obtain timing and predicted head orientation when
-- rendering each eye.
-- - When using timewarp, use ovr_WaitTillTime after the rendering and gpu flush, followed
-- by ovrHmd_GetEyeTimewarpMatrices to obtain the timewarp matrices used
-- by the distortion pixel shader. This will minimize latency.
--
-- | Computes the distortion viewport, view adjust, and other rendering parameters for
-- the specified eye. This can be used instead of ovrHmd_ConfigureRendering to do
-- setup for client rendered distortion.
--
--foreign import ccall unsafe "_ovrHmd_GetRenderDesc" c_ovrHmd_GetRenderDesc :: OvrHmd -> OvrEyeType -> Ptr OvrPosef -> IO (Ptr OvrEyeRenderDesc)
-- | Generate distortion mesh per eye.
-- Distortion capabilities will depend on 'distortionCaps' flags. Users should
-- render using the appropriate shaders based on their settings.
-- Distortion mesh data will be allocated and written into the ovrDistortionMesh data structure,
-- which should be explicitly freed with ovrHmd_DestroyDistortionMesh.
-- Users should call ovrHmd_GetRenderScaleAndOffset to get uvScale and Offset values for rendering.
-- The function shouldn't fail unless theres is a configuration or memory error, in which case
-- ovrDistortionMesh values will be set to null.
-- This is the only function in the SDK reliant on eye relief, currently imported from profiles,
-- or overriden here.
--
{-
ovrHmd_CreateDistortionMesh :: OvrHmd -> OvrEyeType
-> Ptr OvrPosef -> CUInt
-> Ptr OvrDistortionMesh -> IO OvrBool
ovrHmd_CreateDistortionMesh hmd eyeType pOvrPose
c_ovrHmd_CreateDistortionMesh
-}
-- | Used to free the distortion mesh allocated by ovrHmd_GenerateDistortionMesh. meshData elements
-- are set to null and zeroes after the call.
--
--foreign import ccall unsafe "_ovrHmd_DestroyDistortionMesh" c_ovrHmd_DestroyDistortionMesh :: Ptr OvrDistortionMesh -> IO ()
-- | Computes updated 'uvScaleOffsetOut' to be used with a distortion if render target size or
-- viewport changes after the fact. This can be used to adjust render size every frame if desired.
--
--foreign import ccall unsafe "_ovrHmd_GetRenderScaleAndOffset" c_ovrHmd_GetRenderScaleAndOffset :: Ptr OvrFovPort -> Ptr OvrSizei -> Ptr OvrSizei -> Ptr OvrVector2f -> IO ()
-- | Thread-safe timing function for the main thread. Caller should increment frameIndex
-- with every frame and pass the index where applicable to functions called on the
-- rendering thread.
--
--foreign import ccall unsafe "_ovrHmd_GetFrameTiming" c_ovrHmd_GetFrameTiming :: OvrHmd -> CUInt -> IO (Ptr OvrFrameTiming)
-- | Called at the beginning of the frame on the rendering thread.
-- Pass frameIndex == 0 if ovrHmd_GetFrameTiming isn't being used. Otherwise,
-- pass the same frame index as was used for GetFrameTiming on the main thread.
--
--foreign import ccall unsafe "_ovrHmd_BeginFrameTiming" c_ovrHmd_BeginFrameTiming :: OvrHmd -> CUInt -> IO (Ptr OvrFrameTiming)
-- | Marks the end of client distortion rendered frame, tracking the necessary timing information.
-- This function must be called immediately after Present/SwapBuffers + GPU sync. GPU sync is
-- important before this call to reduce latency and ensure proper timing.
--
--foreign import ccall unsafe "_ovrHmd_EndFrameTiming" c_ovrHmd_EndFrameTiming :: OvrHmd -> IO ()
-- | Initializes and resets frame time tracking. This is typically not necessary, but
-- is helpful if game changes vsync state or video mode. vsync is assumed to be on if this
-- isn't called. Resets internal frame index to the specified number.
--
--foreign import ccall unsafe "_ovrHmd_ResetFrameTiming" c_ovrHmd_ResetFrameTiming :: OvrHmd -> CUInt -> IO ()
-- | Computes timewarp matrices used by distortion mesh shader, these are used to adjust
-- for head orientation change since the last call to ovrHmd_GetEyePose when rendering
-- this eye. The ovrDistortionVertex::TimeWarpFactor is used to blend between the
-- matrices, usually representing two different sides of the screen.
-- Must be called on the same thread as ovrHmd_BeginFrameTiming.
--
--foreign import ccall unsafe "_ovrHmd_GetEyeTimewarpMatrices" c_ovrHmd_GetEyeTimewarpMatrices :: OvrHmd -> OvrEyeType -> Ptr OvrPosef -> Ptr OvrMatrix4f -> IO ()
-------------------------------------------------------------------------------------
-- ***** Stateless math setup functions
-- | Used to generate projection from ovrEyeDesc::Fov.
--
ovrMatrix4f_Projection :: OvrFovPort -> Float -> Float -> Bool
-> IO OvrMatrix4f
ovrMatrix4f_Projection fov' znear zfar rightHanded = peek =<<
(alloca $ \ f' -> do
poke f' fov'
c_ovrMatrix4f_Projection f' (CFloat znear) (CFloat zfar)
(bool2OvrBool rightHanded))
-- | Used for 2D rendering, Y is down
-- orthoScale = 1.0f / pixelsPerTanAngleAtCenter
-- orthoDistance = distance from camera, such as 0.8m
--
ovrMatrix4f_OrthoSubProjection :: OvrMatrix4f -> OvrVector2f
-> Float -> Float -> IO OvrMatrix4f
ovrMatrix4f_OrthoSubProjection projection orthoScale orthoDistance
eyeViewAdjustX = peek =<<
(alloca $ \ pro' ->
alloca $ \ sc' -> do
poke pro' projection
poke sc' orthoScale
c_ovrMatrix4f_OrthoSubProjection pro' sc' (CFloat orthoDistance)
(CFloat eyeViewAdjustX))
-- | Returns global, absolute high-resolution time in seconds.
-- This is the same
-- value as used in sensor messages.
ovr_GetTimeInSeconds :: IO Double
ovr_GetTimeInSeconds = fmap realToFrac c_ovr_GetTimeInSeconds
-- | Waits until the specified absolute time.
--
ovr_WaitTillTime :: Double -> IO Double
ovr_WaitTillTime = (fmap realToFrac) . (c_ovr_WaitTillTime . realToFrac)
-----------------------------------------------------------------------------------
-- ***** Latency Test interface
-- | Does latency test processing and returns 'TRUE' if specified rgb color should
-- be used to clear the screen.
--
--foreign import ccall unsafe "_ovrHmd_ProcessLatencyTest" c_ovrHmd_ProcessLatencyTest :: OvrHmd -> Ptr CUChar -> IO OvrBool
-- | Returns non-null string once with latency test result, when it is available.
-- Buffer is valid until next call.
--
--foreign import ccall unsafe "_ovrHmd_GetLatencyTestResult" c_ovrHmd_GetLatencyTestResult :: OvrHmd -> IO CString
-----------------------------------------------------------------------------------
-- ***** Health and Safety Warning Display interface
-- | Returns the current state of the HSW display. If the application is doing the rendering of
-- the HSW display then this function serves to indicate that the the warning should be
-- currently displayed. If the application is using SDK-based eye rendering then the SDK by
-- default automatically handles the drawing of the HSW display. An application that uses
-- application-based eye rendering should use this function to know when to start drawing the
-- HSW display itself and can optionally use it in conjunction with ovrhmd_DismissHSWDisplay
-- as described below.
--
-- Example usage for application-based rendering:
-- bool HSWDisplayCurrentlyDisplayed = false; // global or class member variable
-- ovrHSWDisplayState hswDisplayState;
-- ovrhmd_GetHSWDisplayState(Hmd, &hswDisplayState);
--
-- if (hswDisplayState.Displayed && !HSWDisplayCurrentlyDisplayed) {
-- <insert model into the scene that stays in front of the user>
-- HSWDisplayCurrentlyDisplayed = true;
-- }
--
ovrHmd_GetHSWDisplayState :: OvrHmd -> IO OvrHSWDisplayState
ovrHmd_GetHSWDisplayState hmd =
peek =<< c_ovrHmd_GetHSWDisplayState hmd
-- | Dismisses the HSW display if the warning is dismissible and the earliest dismissal time
-- has occurred. Returns true if the display is valid and could be dismissed. The application
-- should recognize that the HSW display is being displayed (via ovrhmd_GetHSWDisplayState)
-- and if so then call this function when the appropriate user input to dismiss the warning
-- occurs.
--
-- Example usage :
-- void ProcessEvent(int key) {
-- if(key == escape) {
-- ovrHSWDisplayState hswDisplayState;
-- ovrhmd_GetHSWDisplayState(hmd, &hswDisplayState);
--
-- if(hswDisplayState.Displayed && ovrhmd_DismissHSWDisplay(hmd)) {
-- <remove model from the scene>
-- HSWDisplayCurrentlyDisplayed = false;
-- }
-- }
-- }
--
ovrHmd_DismissHSWDisplay :: OvrHmd -> IO Bool
ovrHmd_DismissHSWDisplay hmd =
fmap ovrBool2Bool $ c_ovrHmd_DismissHSWDisplay hmd
-----------------------------------------------------------------------------------
-- ***** Property Access
-- | Get boolean property. Returns first element if property is a boolean array.
-- | Returns defaultValue if property doesn't exist.
--
--foreign import ccall unsafe "_ovrHmd_GetBool" c_ovrHmd_GetBool :: OvrHmd -> CString -> OvrBool -> IO OvrBool
-- | Modify bool property; false if property doesn't exist or is readonly.
--
--foreign import ccall unsafe "_ovrHmd_SetBool" c_ovrHmd_SetBool :: OvrHmd -> CString -> OvrBool -> IO OvrBool
-- | Get integer property. Returns first element if property is an integer array.
-- Returns defaultValue if property doesn't exist.
--foreign import ccall unsafe "_ovrHmd_GetInt" c_ovrHmd_GetInt :: OvrHmd -> CString -> CInt -> IO CInt
-- | Modify integer property; false if property doesn't exist or is readonly.
--
--foreign import ccall unsafe "_ovrHmd_SetInt" c_ovrHmd_SetInt :: OvrHmd -> CString -> CInt -> IO OvrBool
-- | Get float property. Returns first element if property is a float array.
-- Returns defaultValue if property doesn't exist.
--
--foreign import ccall unsafe "_ovrHmd_GetFloat" c_ovrHmd_GetFloat :: OvrHmd -> CString -> CFloat -> IO CFloat
-- | Modify float property; false if property doesn't exist or is readonly.
--
--foreign import ccall unsafe "_ovrHmd_SetFloat" c_ovrHmd_SetFloat :: OvrHmd -> CString -> CFloat -> IO OvrBool
-- | Get float[] property. Returns the number of elements filled in, 0 if property doesn't exist.
-- Maximum of arraySize elements will be written.
--
--foreign import ccall unsafe "_ovrHmd_GetFloatArray" c_ovrHmd_GetFloatArray :: OvrHmd -> CString -> Ptr CFloat -> CUInt -> IO CUInt
-- | Modify float[] property; false if property doesn't exist or is readonly.
--
--foreign import ccall unsafe "_ovrHmd_SetFloatArray" c_ovrHmd_SetFloatArray :: OvrHmd -> CString -> Ptr CFloat -> CUInt -> IO OvrBool
-- | Get string property. Returns first element if property is a string array.
-- Returns defaultValue if property doesn't exist.
-- String memory is guaranteed to exist until next call to GetString or GetStringArray, or HMD is destroyed.
--
--foreign import ccall unsafe "_ovrHmd_GetString" c_ovrHmd_GetString :: OvrHmd -> CString -> CString -> IO CString
-- | Set string property
--
--foreign import ccall unsafe "_ovrHmd_SetString" c_ovrHmd_SetString :: OvrHmd -> CString -> CString -> IO OvrBool
| tmishima/bindings-Oculus | Bindings/OculusRift.hs | apache-2.0 | 27,373 | 0 | 21 | 5,162 | 2,703 | 1,479 | 1,224 | 201 | 3 |
{-# LANGUAGE LambdaCase, NoMonomorphismRestriction, OverloadedStrings #-}
import Control.Applicative ((<$),(<$>),(<*),(<*>),(*>))
import Control.Monad
import Data.Aeson
import Data.Char
import System.Environment
import Text.Parsec
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.HashMap.Lazy as H
import qualified Data.Text as T
import qualified Data.Vector as V
any_of predicates x = any ($ x) predicates
vMapMaybe f = V.foldl (\a e -> maybe a (a `V.snoc`) (f e)) V.empty
data AccessPathElement = DotNotation T.Text | BracketSubscript Int | Wildcard | Concat [[AccessPathElement]] deriving Show
derefByPath ((DotNotation property):xs) (Object obj) = (H.lookup property obj) >>= (derefByPath xs)
derefByPath ((BracketSubscript idx):xs) (Array arr) = (arr V.!? idx) >>= (derefByPath xs)
derefByPath (Wildcard:xs) (Array arr) = Just . Array $ vMapMaybe (derefByPath xs) arr
derefByPath ((Concat paths):xs) obj = derefByPath xs . Array . vMapMaybe (flip derefByPath obj) $ V.fromList paths
derefByPath [] x = Just x
derefByPath _ _ = Nothing
-- http://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names
js_id_start = any_of [(`elem` [UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter, OtherLetter, LetterNumber]) . generalCategory, (`elem` "$_")]
js_id_rest = any_of [js_id_start, (`elem` [NonSpacingMark, SpacingCombiningMark, DecimalNumber, ConnectorPunctuation]) . generalCategory]
parseJSIdentifier = ((:) <$> satisfy js_id_start <*> many (satisfy js_id_rest)) <?> "javascriptIdentifier"
parseDotNotation = char '.' *> ((DotNotation . T.pack <$> parseJSIdentifier) <|> (Wildcard <$ char '*'))
parseSubscript = BracketSubscript . read <$> (char '[' *> many1 (satisfy isDigit) <* char ']')
parseConcat = char '<' *> (Concat <$> (parseAccessPath `sepBy` (char ','))) <* char '>'
parseAccessPath = ((many1 (parseDotNotation <|> parseSubscript <|> parseConcat)) <|> (eof *> return []))
showHelp progName =
putStr $ unlines [concat ["Usage: ", progName, " PATHSPEC"],
"PATHSPEC = '.' javascriptIdentifer | '[' number ']' | '.*' | '<' PATHSPEC (',' PATHSPEC)* '>'",
"(e.g. \".foo[1]\", \".bar\", \"[13]\", \"[42].__testing__\", \"[0].*.foo\", \"<[0].*.foo,[1].bar[1]>)"]
main = getArgs >>= \case
[path] -> either print main' $ parse parseAccessPath "" path
_ -> getProgName >>= showHelp
interactBytestringLines f = interact (unlines . map (L.unpack . f . L.pack) . lines)
main' path = interactBytestringLines $ maybe "null" (encode . derefByPath path) . decode
| aweinstock314/haskell-ropc | jsonderef.hs | apache-2.0 | 2,563 | 0 | 13 | 356 | 847 | 469 | 378 | 36 | 2 |
module Sarsi.Processor where
import qualified Codec.GHC.Log as GHC
import Codec.Sarsi (Message)
import Codec.Sarsi.GHC (fromGHCLog)
import qualified Codec.Sarsi.Nix as Nix
import qualified Codec.Sarsi.Rust as Rust
import qualified Codec.Sarsi.SBT.Machine as SBT
import qualified Codec.Sarsi.Scala as Scala
import Data.Attoparsec.Text (Parser)
import Data.Attoparsec.Text.Machine (streamParser)
import Data.Machine (ProcessT, asParts, auto, flattened, (<~))
import Data.Machine.Fanout (fanout)
import Data.Maybe (maybeToList)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import Rosetta (LanguageTag (..), ProjectTag, languageTags, projectLanguages)
import Sarsi (Topic (..))
data Processor = Processor {language :: LanguageTag, process :: Topic -> ProcessT IO Text Message}
instance Eq Processor where
a == b = (language a) == (language b)
instance Ord Processor where
compare a b = compare (language a) (language b)
projectProcessors :: ProjectTag -> Set Processor
-- projectProcessors DOTNET = processDotnet
projectProcessors project = Set.fromList $ g =<< f <$> projectLanguages project
where
f l = (\p -> (l, p)) <$> languageProcess l
g (Just (l, p)) = [Processor {language = l, process = p}]
g Nothing = []
languageProcess :: LanguageTag -> Maybe (Topic -> ProcessT IO Text Message)
languageProcess HS = Just $ const processHaskell
languageProcess NX = Just . const $ processMessage Nix.messageParser
languageProcess RS = Just . const $ processMessage Rust.messageParser
languageProcess SC = Just $ \(Topic _ _ root) -> (processMessage $ Scala.messageParser root) <~ SBT.cleaningCursesSBT
languageProcess _ = Nothing
processAll :: [Topic -> ProcessT IO Text Message] -> Topic -> ProcessT IO Text Message
processAll xs t = flattened <~ (fanout $ (\p -> (auto (\x -> [x])) <~ p t) <$> xs)
processAny :: Topic -> ProcessT IO Text Message
processAny = processAll $ languageTags >>= (maybeToList . languageProcess)
processHaskell :: ProcessT IO Text Message
processHaskell = asParts <~ auto unpack <~ streamParser GHC.messageParser
where
unpack (Right msg) = [fromGHCLog msg]
unpack (Left _) = []
processMessage :: Parser Message -> ProcessT IO Text Message
processMessage parser = asParts <~ auto unpack <~ streamParser parser
where
unpack (Right msg) = [msg]
unpack (Left _) = []
| aloiscochard/sarsi | src/Sarsi/Processor.hs | apache-2.0 | 2,363 | 0 | 16 | 377 | 830 | 458 | 372 | 46 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Copyright : (C) 2015, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
Synchronizer circuits for safe clock domain crossings
-}
module CLaSH.Prelude.Synchronizer
( -- * Bit-synchronizers
dualFlipFlopSynchronizer
-- * Word-synchronizers
, asyncFIFOSynchronizer
)
where
import Data.Bits (complement, shiftR, xor)
import GHC.TypeLits (KnownNat, type (+))
import CLaSH.Class.BitPack (pack)
import CLaSH.Class.Resize (zeroExtend)
import CLaSH.Prelude.BitIndex (slice)
import CLaSH.Prelude.Mealy (mealyB')
import CLaSH.Prelude.RAM (asyncRam')
import CLaSH.Promoted.Nat (SNat, powSNat, subSNat)
import CLaSH.Promoted.Nat.Literals (d0, d1, d2)
import CLaSH.Signal ((.&&.), not1)
import CLaSH.Signal.Explicit (Signal', SClock, register',
unsafeSynchronizer)
import CLaSH.Sized.BitVector (BitVector, (++#))
-- * Dual flip-flop synchronizer
-- | Synchroniser based on two sequentially connected flip-flops.
--
-- * __NB__: This synchroniser can be used for __bit__-synchronization.
--
-- * __NB__: Although this synchroniser does reduce metastability, it does
-- not guarantee the proper synchronisation of a whole __word__. For
-- example, given that the output is sampled twice as fast as the input is
-- running, and we have two samples in the input stream that look like:
--
-- @[0111,1000]@
--
-- But the circuit driving the input stream has a longer propagation delay
-- on __msb__ compared to the __lsb__s. What can happen is an output stream
-- that looks like this:
--
-- @[0111,0111,0000,1000]@
--
-- Where the level-change of the __msb__ was not captured, but the level
-- change of the __lsb__s were.
--
-- If you want to have /safe/ __word__-synchronisation use
-- 'asyncFIFOSynchronizer'.
dualFlipFlopSynchronizer :: SClock clk1 -- ^ 'Clock' to which the incoming
-- data is synchronised
-> SClock clk2 -- ^ 'Clock' to which the outgoing
-- data is synchronised
-> a -- ^ Initial value of the two
-- synchronisation registers
-> Signal' clk1 a -- ^ Incoming data
-> Signal' clk2 a -- ^ Outgoing, synchronised, data
dualFlipFlopSynchronizer clk1 clk2 i = register' clk2 i
. register' clk2 i
. unsafeSynchronizer clk1 clk2
-- * Asynchronous FIFO synchronizer
fifoMem :: _
=> SClock wclk
-> SClock rclk
-> SNat addrSize
-> Signal' wclk (BitVector addrSize)
-> Signal' rclk (BitVector addrSize)
-> Signal' wclk Bool
-> Signal' wclk Bool
-> Signal' wclk a
-> Signal' rclk a
fifoMem wclk rclk addrSize waddr raddr winc wfull wdata =
asyncRam' wclk rclk
(d2 `powSNat` addrSize)
waddr raddr
(winc .&&. not1 wfull)
wdata
boolToBV :: (KnownNat n, KnownNat (n+1)) => Bool -> BitVector (n + 1)
boolToBV = zeroExtend . pack
ptrCompareT :: _
=> SNat addrSize
-> (BitVector (addrSize + 1) -> BitVector (addrSize + 1) -> Bool)
-> (BitVector (addrSize + 1), BitVector (addrSize + 1), Bool)
-> (BitVector (addrSize + 1), Bool)
-> ((BitVector (addrSize + 1), BitVector (addrSize + 1), Bool)
,(Bool, BitVector addrSize, BitVector (addrSize + 1)))
ptrCompareT addrSize flagGen (bin,ptr,flag) (s_ptr,inc) = ((bin',ptr',flag')
,(flag,addr,ptr))
where
-- GRAYSTYLE2 pointer
bin' = bin + boolToBV (inc && not flag)
ptr' = (bin' `shiftR` 1) `xor` bin'
addr = slice (addrSize `subSNat` d1) d0 bin
flag' = flagGen ptr' s_ptr
-- FIFO full: when next pntr == synchonized {~wptr[addrSize:addrSize-1],wptr[addrSize-1:0]}
isFull :: _
=> SNat addrSize
-> BitVector (addrSize + 1)
-> BitVector (addrSize + 1)
-> Bool
isFull addrSize ptr s_ptr =
ptr == (complement (slice addrSize (addrSize `subSNat` d1) s_ptr) ++#
slice (addrSize `subSNat` d2) d0 s_ptr)
-- | Synchroniser implemented as a FIFO around an asynchronous RAM. Based on the
-- design described in "CLaSH.Tutorial#multiclock", which is itself based on the
-- design described in <http://www.sunburst-design.com/papers/CummingsSNUG2002SJ_FIFO1.pdf>.
--
-- __NB__: This synchroniser can be used for __word__-synchronization.
asyncFIFOSynchronizer :: _
=> SNat addrSize -- ^ Size of the internally used
-- addresses, the FIFO contains
-- @2^addrSize@ elements.
-> SClock wclk -- ^ 'Clock' to which the write port
-- is synchronised
-> SClock rclk -- ^ 'Clock' to which the read port
-- is synchronised
-> Signal' wclk a -- ^ Element to insert
-> Signal' wclk Bool -- ^ Write request
-> Signal' rclk Bool -- ^ Read request
-> (Signal' rclk a, Signal' rclk Bool, Signal' wclk Bool)
-- ^ (Oldest element in the FIFO, @empty@ flag, @full@ flag)
asyncFIFOSynchronizer addrSize wclk rclk wdata winc rinc = (rdata,rempty,wfull)
where
s_rptr = dualFlipFlopSynchronizer rclk wclk 0 rptr
s_wptr = dualFlipFlopSynchronizer wclk rclk 0 wptr
rdata = fifoMem wclk rclk addrSize waddr raddr winc wfull wdata
(rempty,raddr,rptr) = mealyB' rclk (ptrCompareT addrSize (==)) (0,0,True)
(s_wptr,rinc)
(wfull,waddr,wptr) = mealyB' wclk (ptrCompareT addrSize (isFull addrSize))
(0,0,False) (s_rptr,winc)
| Ericson2314/clash-prelude | src/CLaSH/Prelude/Synchronizer.hs | bsd-2-clause | 6,526 | 0 | 14 | 2,126 | 1,180 | 670 | 510 | -1 | -1 |
module Pkgs.Main where
import Control.Monad.Except
import Data.Either
import Text.Parsec (ParseError)
import Pkgs.Parser
import Pkgs.Syntax
import Pkgs.Pretty
import Pkgs.Repository
import Pkgs.TypeCheck
import Pkgs.Eval
type Compiler = ExceptT Error IO
data Error = ParsingError String | TypingError String | EvaluationError String
instance Show Error where
show (ParsingError s) = "Parsing error: " ++ s
show (TypingError s) = "Typing error: " ++ s
show (EvaluationError s) = "Evaluation error: " ++ s
runCompiler :: Compiler a -> IO (Either Error a)
runCompiler = runExceptT
----------
-- | Parse, type-check and run a file, with pkgName as the name of the
-- package entry point (must have a 'main : Unit -> tau' function)
runFile :: PVName -> FilePath -> Compiler Expr
runFile pkgName filename
= processFile emptyRepo filename >>= flip evalPkg pkgName
-- | Parse and typecheck a file
processFile :: Repo -> FilePath -> Compiler Repo
processFile repo fname
= do contents <- liftIO $ readFile fname
defs <- parseFile fname contents
repo' <- foldM check repo defs
liftIO $ putStrLn $ "Successfully processed: " ++ fname
return repo'
parseFile :: FilePath -> String -> Compiler [Toplevel]
parseFile fname contents
= case parse parseAll fname contents of
Left err -> throwError $ ParsingError $ show err
Right defs -> return defs
check :: Repo -> Toplevel -> Compiler Repo
check repo def
= do result <- liftIO $ runTypeChecker repo $ checkToplevel def
case result of
Left err -> throwError $ TypingError $ show err
Right repo' -> return $ addToRepo repo def
evalPkg :: Repo -> String -> Compiler Expr
evalPkg repo pkgName
| Just pkg <- findPkg repo pkgName
= case runEvalM repo $ eval repo pkg of
Left (EvalError s) -> throwError $ EvaluationError s
Right expr -> return expr
| otherwise
= throwError $ EvaluationError $
"Cannot find package " ++ pkgName ++ " in repo " ++ show repo
----------------
failWhen :: Bool -> String -> IO ()
failWhen True s = fail s
failWhen _ s = return ()
failEither :: Show a => Either a b -> IO b
failEither x = failWhen (isLeft x) (show $ getLeft x) >> return (getRight x)
getLeft (Left x) = x
getRight (Right y) = y
| markflorisson/packages | Pkgs/Main.hs | bsd-3-clause | 2,365 | 0 | 11 | 584 | 739 | 360 | 379 | 55 | 2 |
{-# LANGUAGE DeriveFunctor #-}
module Drive.HTTP.Types
( HttpF (..)
, HttpUriF (..)
, HttpHeaderF (..)
, HttpError (..)
) where
import qualified Data.ByteString.Lazy as BS
import qualified Network.Wreq as Wreq
type Uri = String
data HttpError
= RequestError String
| NoContent
deriving (Show)
data HttpF a
= Get Wreq.Options Uri (BS.ByteString -> a)
deriving (Functor)
data HttpUriF x a
= GetUri Wreq.Options (x -> Uri) (Either HttpError BS.ByteString -> a)
deriving (Functor)
data HttpHeaderF y a
= GetOptions (y -> Wreq.Options) Uri (BS.ByteString -> a)
deriving (Functor)
| palf/free-driver | packages/drive-http/lib/Drive/HTTP/Types.hs | bsd-3-clause | 623 | 0 | 10 | 135 | 197 | 121 | 76 | 22 | 0 |
{-# LANGUAGE RankNTypes #-}
module Core.Tag where
import Utilities
import Core.FreeVars
import Core.Size
import Core.Syntax
tagTerm :: IdSupply -> Term -> TaggedTerm
tagTerm = mkTagger (\i f (I e) -> Tagged (mkTag (hashedId i)) (f e))
tagFVedTerm :: IdSupply -> SizedFVedTerm -> TaggedSizedFVedTerm
tagFVedTerm = mkTagger (\i f e -> Comp (Tagged (mkTag (hashedId i)) (fmap f e)))
{-# INLINE mkTagger #-}
mkTagger :: (forall a b. Id -> (a -> b) -> ann a -> ann' b)
-> IdSupply -> ann (TermF ann) -> ann' (TermF ann')
mkTagger rec = term
where
term ids = rec i (term' ids')
where (ids', i) = stepIdSupply ids
term' ids e = case e of
Var x -> Var x
Value v -> Value (value ids v)
App e x -> App (term ids e) x
PrimOp pop es -> PrimOp pop (zipWith term idss' es)
where idss' = splitIdSupplyL ids
Case e alts -> Case (term ids0' e) (alternatives ids1' alts)
where (ids0', ids1') = splitIdSupply ids
LetRec xes e -> LetRec (zipWith (\ids'' (x, e) -> (x, term ids'' e)) idss' xes) (term ids1' e)
where (ids0', ids1') = splitIdSupply ids
idss' = splitIdSupplyL ids0'
value ids v = case v of
Indirect x -> Indirect x
Lambda x e -> Lambda x (term ids e)
Data dc xs -> Data dc xs
Literal l -> Literal l
alternatives = zipWith alternative . splitIdSupplyL
alternative ids (con, e) = (con, term ids e)
(taggedTermToTerm, taggedAltsToAlts, taggedValueToValue, taggedValue'ToValue') = mkDetag (\f e -> I (f (tagee e)))
(fVedTermToTerm, fVedAltsToAlts, fVedValueToValue, fVedValue'ToValue') = mkDetag (\f e -> I (f (fvee e)))
(taggedSizedFVedTermToTerm, taggedSizedFVedAltsToAlts, taggedSizedFVedValueToValue, taggedSizedFVedValue'ToValue') = mkDetag (\f e -> I (f (fvee (sizee (unComp (tagee (unComp e)))))))
(taggedSizedFVedTermToFVedTerm, taggedSizedFVedAltsToFVedAlts, taggedSizedFVedValueToFVedValue, taggedSizedFVedValue'ToFVedValue') = mkDetag (\f e -> FVed (freeVars (sizee (unComp (tagee (unComp e))))) (f (extract e)))
{-# INLINE mkDetag #-}
mkDetag :: (forall a b. (a -> b) -> ann a -> ann' b)
-> (ann (TermF ann) -> ann' (TermF ann'),
[AltF ann] -> [AltF ann'],
ann (ValueF ann) -> ann' (ValueF ann'),
ValueF ann -> ValueF ann')
mkDetag rec = (term, alternatives, value, value')
where
term = rec term'
term' e = case e of
Var x -> Var x
Value v -> Value (value' v)
App e x -> App (term e) x
PrimOp pop es -> PrimOp pop (map term es)
Case e alts -> Case (term e) (alternatives alts)
LetRec xes e -> LetRec (map (second term) xes) (term e)
value = rec value'
value' (Indirect x) = Indirect x
value' (Lambda x e) = Lambda x (term e)
value' (Data dc xs) = Data dc xs
value' (Literal l) = Literal l
alternatives = map (second term)
| batterseapower/chsc | Core/Tag.hs | bsd-3-clause | 3,121 | 0 | 20 | 950 | 1,273 | 641 | 632 | 59 | 9 |
-- |
-- Module: $HEADER$
-- Description: Provide exclusive access to a resource using lock file.
-- Copyright: (c) 2013 Peter Trsko
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: portable
--
-- Provide exclusive access to a resource using lock file.
module System.IO.LockFile.Resource
(
-- * Locking primitives
acquireLockFile
-- * Configuration
, LockingParameters(..)
, RetryStrategy(..)
-- * Exceptions
, LockingException(..)
)
where
import Control.Applicative ((<$>))
import Control.Monad.TaggedException (hide)
import Control.Monad.Trans.Resource
( MonadResource(liftResourceT)
, ReleaseKey
, allocate
)
import System.IO.LockFile.Internal
( LockingException(..)
, LockingParameters(..)
, RetryStrategy(..)
, lock
, unlock
)
acquireLockFile
:: MonadResource m
=> LockingParameters
-> FilePath
-> m ReleaseKey
acquireLockFile params lockFileName =
liftResourceT $ fst <$> allocate lock' unlock'
where
lock' = hide $ lock params lockFileName
unlock' = hide . unlock lockFileName
| trskop/lock-file-resourcet | src/System/IO/LockFile/Resource.hs | bsd-3-clause | 1,174 | 0 | 8 | 272 | 203 | 129 | 74 | 27 | 1 |
-- Implementation of the variable elimination algorithm
-- from the paper
-- Toward Good Elimination Orders for Symbolic SAT Solving
-- by Jinbo Huang and Adnan Darwiche
{-# LANGUAGE BangPatterns #-}
module VariableEliminationOBDD
( variableEliminationOBDD
, variableEliminationOBDDUsingDTree
) where
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Ord ( comparing )
import Debug.Trace ( trace )
import Dimacs ( Dimacs , VarId , variableCounts
, leastFrequentVariables )
import OBDD ( OBDD
, mostOccuringPlusNeighboursHeuristic
, mkObddWithOrderX
, variableOrderComparer
, conjoin
, quantifyVariable
, isTrue
, isFalse
, obddVars
)
import PrettyClassExt ( printPretty )
import Text.PrettyPrint.HughesPJClass ( prettyShow )
import DTreeHGP ( DTree , dtreeVars
, DTreevs(DNodevs, DLeafvs), dvars )
type Buckets = M.Map VarId Bucket
type Bucket = [OBDD]
variableEliminationOBDD :: Dimacs -> (Bool, [(VarId, OBDD)])
variableEliminationOBDD cnf =
variableEliminationEOVO
cnf
(leastFrequentVariables cnf)
(mostOccuringPlusNeighboursHeuristic cnf)
variableEliminationEOVO
:: Dimacs -> [VarId] -> [VarId] -> (Bool, [(VarId, OBDD)])
variableEliminationEOVO cnf eliminationOrder variableOrder =
eliminate obuckets eliminationOrder []
where elordIdxMap = M.fromList $ zip eliminationOrder [1..]
elordIdx = (elordIdxMap M.!)
varsBucket = L.minimumBy (comparing elordIdx)
clauseBucket = varsBucket . map abs
buckets = M.fromListWith (++)
[ (clauseBucket cl, [cl]) | cl <- cnf]
cmp = variableOrderComparer variableOrder
obddForSingleClause cl = mkObddWithOrderX variableOrder [cl]
conjoinX = conjoin cmp variableOrder
conjoinClauses :: Dimacs -> OBDD
conjoinClauses = L.foldl1' conjoinX . map obddForSingleClause
obuckets = M.map conjoinClauses buckets
eliminate !buckets [] btrace = (True, btrace)
eliminate !buckets (var:eliminationOrder) btrace =
case M.lookup var buckets of
Nothing -> eliminate buckets eliminationOrder btrace
Just b1 ->
let b2 = quantifyVariable cmp variableOrder var b1
btrace2 = (var, b1) : btrace
in trace (prettyShow("elim var", var, b2)) $
case (isTrue b2, isFalse b2, obddVars b2) of
(True, _, _) -> eliminate buckets eliminationOrder
btrace2
(_, True, _) -> (False, btrace2)
(_, _, vars) ->
let bu = varsBucket $ S.toList vars
b3 = case M.lookup bu buckets of
Nothing -> b2
Just x -> conjoinX b2 x
in eliminate
(M.insert bu b3 buckets)
eliminationOrder
btrace2
variableEliminationOBDDUsingDTree :: Dimacs -> DTree
-> (Bool, [(VarId, OBDD)])
variableEliminationOBDDUsingDTree cnf dt =
let eo = eliminationOrderFromDTree dt
in
trace ("elimination order:\n" ++ prettyShow eo) $
trace ("missing vars:\n"
++ prettyShow (S.difference
(S.fromList $ map abs $ concat cnf)
(S.fromList eo))) $
trace ("dtreeVars:\n"
++ prettyShow (dtreeVars dt)) $
variableEliminationEOVO
cnf
eo
(mostOccuringPlusNeighboursHeuristic cnf)
eliminationOrderFromDTree dt = recur (dtreeVars dt) S.empty
where
recur (DNodevs vs l r) parentCutset =
let vsl = S.difference (dvars l) parentCutset
vsr = S.difference (dvars r) parentCutset
cutset = (S.intersection vsl vsr)
pc = S.union parentCutset cutset
in recur r pc
++ recur l pc
++ S.toList cutset
recur (DLeafvs vs) parentCutset =
S.toList (S.difference vs parentCutset)
| malie/drolesat | VariableEliminationOBDD.hs | bsd-3-clause | 4,172 | 0 | 23 | 1,353 | 1,064 | 571 | 493 | 95 | 6 |
;
; HSP help managerp HELP\[Xt@C
; (檪u;vÌsÍRgƵijêÜ·)
;
%type
g£½ß
%ver
3.3
%note
llmod3.hsp,misc.hspðCN[h·é
%date
2009/08/01
%author
tom
%dll
llmod3
%url
http://www5b.biglobe.ne.jp/~diamond/hsp/hsp2file.htm
%index
tooltip
c[`bvðt¯é
%group
IuWFNg§ä½ß
%prm
n1,n2,n3
n1 : button,input,treeboxÈÇÌID
n2 : c[`bvãÉ\¦·é¶ñ
n3 : c[`bvÌwiF (IE3.0Èã)
%inst
IuWFNgÉc[`bvðt¯Ü·B
c[`bvÆÍ}EXJ[\ªbuttonÈÇÌIuWFNgãÅêèÔâ~µ½Æ«É»ê鬳ÈEBhEÅ·B
%sample
button "test",label : btn_id=0
tooltip btn_id,"eXgµÜ·"
*label
stop
%index
strtoint
¶ñðlÉÏ·
%group
IuWFNg§ä½ß
%prm
s1,n2
s1 : lÉÏ··é¶ñ
n2 : î(2`36)
%inst
¶ñðlÉÏ·µÜ·B
%sample
strtoint "111101",2 ;2iÆÝȵÄÏ·
mes stat
strtoint "0x1F" ;檪"0x"¾Æ16iÆÝȳêé(BaseȪ)
mes stat
strtoint "0376" ;檪"0"¾Æ8iÆÝȳêé(BaseȪ)
mes stat
strtoint "23413",7 ;7iÆÝȵÄÏ·
mes stat
strtoint "za",36 ;36iÆÝȵÄÏ·
mes stat
stop
%index
btnimg
buttonÉæð\è¯é
%group
IuWFNg§ä½ß
%prm
n1, n2, n3, n4, n5, n6
n1 : C[Wð\è¯é{^ÌID(0`63)
n2 : C[Wª`æ³êÄ¢éEBhEÌID(0`7)
n3 : C[WÌÊu
n4 : C[WÌÊu
n5 : C[WÌ
n6 : C[W̳
%inst
buttonÉæð\è¯ܷB
%sample
buffer 1
picload "mybmp.bmp" ;EBhEID 1 Érbg}bvð\¦
bmp_w=winx:bmp_h=winy
gsel 0
button "",*label : btn_id=0
^
;EBhEID 1Ì(0,0)-(bmp_w,bmp_h)ÌÍÍÌæð{^É`æ·é
btnimg btn_id,1,0,0,bmp_w,bmp_h
*label
stop
| zakki/openhsp | package/hsphelp/llmod3_misc.hs | bsd-3-clause | 1,833 | 667 | 16 | 304 | 1,595 | 871 | 724 | -1 | -1 |
module Tests.Testframe where
import Test.HUnit
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.ByteString as B
import Text.ParserCombinators.Parsec
import Control.Applicative ((*>),(<*),(<*>),(<$>))
import Data.Word (Word8)
import Control.Monad (void)
import Data.Int (Int64)
import Text.Printf (printf)
import System.FilePath ((</>))
--import qualified Data.Digest.JH224 as JH224
--import qualified Data.Digest.JH256 as JH256
--import qualified Data.Digest.JH384 as JH384
--import qualified Data.Digest.JH512 as JH512
import qualified Data.Digest.Groestl224 as G224
import qualified Data.Digest.Groestl256 as G256
import qualified Data.Digest.Groestl384 as G384
import qualified Data.Digest.Groestl512 as G512
-- The hash function to test.
hashFunc :: Int64 -> L.ByteString -> L.ByteString
--hashFunc = JH224.jh224
--hashFunc = JH224.jh256
--hashFunc = JH384.jh384
--hashFunc = JH512.jh512
hashFunc = G224.groestl224
--hashFunc = G256.groestl256
--hashFunc = G384.groestl384
--hashFunc = G512.groestl512
cryptoAPIDigest = G224.Digest
cryptoAPIHash = G224.hash
--cryptoAPIDigest = G256.Digest
--cryptoAPIHash = G256.hash
--cryptoAPIDigest = G384.Digest
--cryptoAPIHash = G384.hash
--cryptoAPIDigest = G512.Digest
--cryptoAPIHash = G512.hash
xExtreme = xG384
--xLength = 100000 * 64
xLength = 1000000 * 64
--xLength = 16777216 * 64
runExtreme :: Bool -> IO ()
runExtreme False =
void . runTestTT . TestCase $
assertEqual "Extremely long" (printAsHex xExtreme) (printAsHex $ hashFunc (8 * xLength) extreme)
runExtreme True =
void . runTestTT . TestCase $
assertEqual "Extremely long" (cryptoAPIDigest xExtreme) (cryptoAPIHash extreme)
run :: String -> FilePath -> Bool -> IO ()
run alg testFile byteAligned = do
file <- readFile $ "./Tests/KAT_MCT" </> alg </> testFile
let p_result = parse p_KATFile testFile file
case p_result of
Left parseError -> print parseError
Right katFile -> void . runTestTT $ makeTests byteAligned katFile
----------------------------- Create a test suite --------------------------
makeTests :: Bool -> KATFile -> Test
makeTests True = TestList . map makeAlignedTest . dropUnaligned . kats
makeTests False = TestList . map makeUnalignedTest . kats
dropUnaligned :: [KAT] -> [KAT]
dropUnaligned = filter (\(KAT len _ _) -> len `mod` 8 == 0)
makeAlignedTest :: KAT -> Test
makeAlignedTest kat =
TestCase $ assertEqual ("Len = " ++ show dataLen)
expectedDigest
(cryptoAPIHash message)
where dataLen = len kat
expectedDigest = cryptoAPIDigest $ digest kat
message = msg kat
makeUnalignedTest :: KAT -> Test
makeUnalignedTest kat =
TestCase $ assertEqual ("Len = " ++ show dataLen)
(printAsHex expectedDigest)
(printAsHex $ hashFunc dataLen message)
where dataLen = len kat
expectedDigest = digest kat
message = msg kat
---------------------------- Some types for specifying tests -----------
data KATFile = KATFile {
header :: Header,
kats :: [KAT]
} deriving (Show)
data Header = Header {
fName :: String,
algName :: String
} deriving (Show)
data KAT = KAT {
len :: Int64,
msg :: L.ByteString,
digest :: L.ByteString
}
instance Show KAT where
show (KAT dataLen msg _) = show (dataLen, printAsHex $ L.take 5 msg)
----------------------------- Parse test vector files --------------------------
p_KATFile :: GenParser Char st KATFile
p_KATFile = KATFile <$>
(p_header <* eol) <*> endBy p_KAT (optional eol)
p_header :: GenParser Char st Header
p_header = do
tfn <- string "# " *> manyTill anyChar (string ".txt" <* eol)
alg <- string "# Algorithm Name: " *> manyTill anyChar eol
manyTill anyChar eol
return $ Header tfn alg
p_KAT :: GenParser Char st KAT
p_KAT = do len <- p "Len = " read digit
msg <- p "Msg = " (if len == 0 then \_ -> L.empty else L.pack) p_hexNumber
digest <- p "MD = " L.pack p_hexNumber
return $ KAT len msg digest
where
p prefix reader format = reader <$> (string prefix *> manyTill format eol)
p_hexNumber :: GenParser Char st Word8
p_hexNumber = read . ("0x" ++) <$> count 2 hexDigit
eol = choice [try (string "\n\r"), try (string "\r\n"), try (string "\n"), try (string "\r")]
<?> "end of line"
printAsHex :: L.ByteString -> String
printAsHex = concat . ("0x" :) . map (printf "%02x") . L.unpack
readAsHex :: String -> L.ByteString
readAsHex = L.pack . map (read . ("0x"++)) . take2
take2 :: [a] -> [[a]]
take2 (a:b:rest) = [a,b] : take2 rest
take2 _ = []
extreme :: L.ByteString
extreme = L.take xLength . L.cycle $ C.pack "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
xJH224 = readAsHex "B4ABC2827D3547D19B517C673DE2DF2666AE95A0E73ECB213E5C95D4"
xJH256 = readAsHex "58FFBDE520764DFC03B29598ACD70655BB2C245A3D73FDD6EB9E1BC221AF579B"
xJH384 = readAsHex "836EC726CA5280BBC490A25389D1F507CECED047E9E3DAF0ED3DAA5D9AEDE2DDA89C8B7995F7855A3354AFBFFF1B4935"
xJH512 = readAsHex "A3053657024A43187CF8C1C82194D5D944A7408EE3B584801309292DEFF8080F88183B5642318456C7C05998C9A70D0F784E4C42D9EBCBA7F2CA25B3FBDE2CE5"
xG224 = readAsHex "E0ABD47D755D0D5AE5853F1253C46AA574E896D6705AEF9944BFEA8D"
xG256 = readAsHex "5F87F9404C1142B9E701076DD047386162213A896560C1656C62BBFEDFBEDDB6"
xG384 = readAsHex "742C6BBDA24B3DD7F41799B7565A1189E03B406DCF4C4697C3FBA3B7DEA1F65A7F15CAEA841C3FE1B252893D3F918066"
| hakoja/SHA3 | Tests/testframe.hs | bsd-3-clause | 5,678 | 0 | 12 | 1,153 | 1,432 | 773 | 659 | 106 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module LambdaHive.AI where
import AI.Minimax
import Control.DeepSeq
import qualified Data.Bimap as Bimap
import Data.Bool
import qualified Data.IGraph as IG
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Time.Clock
import GHC.Generics (Generic)
import LambdaHive.Types
import System.Random
data HiveAI = RandomAI | Minimax ScoreWeights Int (ScoreWeights -> GameState -> Value)
instance Eq HiveAI where
(==) RandomAI RandomAI = True
(==) Minimax{} Minimax{} = True
(==) _ _ = False
instance Show HiveAI where
show RandomAI = "RandomAI"
show (Minimax _ d _) = "Minimax - depth: " ++ show d
aiMove :: HiveAI -> GameState -> IO (HiveMove, GameState)
aiMove ai gs
| null allMoves = return (NoOp,unsafeSkipTurn gs)
| otherwise = go ai
where
allMoves = validPlayerMoves gs
go RandomAI = do
r <- randomRIO (0, length allMoves -1)
let mv = allMoves !! r
putStrLn "Random Move"
return (mv, fromJust $ makeMove gs mv)
go (Minimax sw d s) = do
t <- getCurrentTime
let (mv, score) = searchMove (alphaBeta (s sw)) d gs
let newState = fromJust $ makeMove gs mv
print score
t2 <- getCurrentTime
print $ diffUTCTime t2 t
return (mv, newState)
data ScoreWeights = ScoreWeights
{ swPlayerArtPoints :: Int
, swOppArtPoints :: Int
, swOppQBreathing :: Int
, swPlayerQBreathing :: Int
, swPiecesToWin :: Int
, swPlayerPiecesOnTop:: Int
, swOppPiecesOnTop :: Int
}
deriving (Show, Eq, Read, Generic, NFData)
score1 :: ScoreWeights -> GameState -> Value
score1 sw gs = case prog of
Win wp -> if wp == p then maxBound-1 else minBound+1
Draw -> 0
InProgress -> Value $
(swPlayerArtPoints sw * (-1) * getPieceWeightSum playerArtPoints)
+ (swOppArtPoints sw * getPieceWeightSum oposingArtPoints)
+ (swOppQBreathing sw * fromMaybe 0 ((-) 6 <$> opposingQueenBreathingRoom))
+ (swPlayerQBreathing sw * (-1) * fromMaybe 0 ((-) 6 . breathingRoom gs <$> queen p))
+ (swPiecesToWin sw * fromMaybe 0 (bool (-1) 1 <$> enoughPiecesToWin))
+ (swPlayerPiecesOnTop sw * pieceOnTopSum gs p)
+ (swOppPiecesOnTop sw * pieceOnTopSum gs oposingPlayer)
where
p = gsCurrPlayer gs
prog = gsStatus gs
bs = gsBoard gs
idMap = bsIdMap bs
coords = bsCoords bs
oposingPlayer
| p == Player1 = Player2
| otherwise = Player1
queen pl = (Bimap.!>) (bsIdMap bs) <$> maybeQueen pl
maybeQueen pl = Bimap.lookup (playerText pl <> "Q") $ bsCannonicalIdMap bs
artPoints = map (\pId -> coords Map.! (idMap Bimap.! pId)) $ Set.toList $ bsArticulationPoints bs
playerArtPoints = filter (\piece -> hPlayer piece == p) artPoints
oposingArtPoints = filter (\piece -> hPlayer piece /= p) artPoints
opposingQueenBreathingRoom = breathingRoom gs <$> queen oposingPlayer
enoughPiecesToWin = (>=) (piecesFreeToAttck gs p) <$> opposingQueenBreathingRoom
getPieceWeightSum = sum . map (pieceWeight . hPieceType)
pieceWeight :: PieceType -> Int
pieceWeight Spider = 1
pieceWeight Beetle = 3
pieceWeight Grasshopper = 2
pieceWeight Ant = 3
pieceWeight Queen = 6
mapSum :: (Num a) => (k -> b -> a) -> Map.Map k b -> a
mapSum f = Map.foldlWithKey' (\s k v -> s + f k v) 0
pieceOnTopSum :: GameState -> HivePlayer -> Int
pieceOnTopSum gs p = sumWeightOfTrapped $ Map.filterWithKey onTopPiece coords
where
bs = gsBoard gs
coords = bsCoords bs
sumWeightOfTrapped = mapSum (\pc _ -> mapSum (\ _ p2 -> pieceScore p2) (othersInStack pc))
pieceScore p1 = pieceWeight (hPieceType p1) * bool 10 1 (hPlayer p1 == p)
othersInStack pc = Map.filterWithKey (axialEqNotSame pc) coords
axialEqNotSame pc@(_,_,h) pc1@(_,_,h2) _ = axialEq pc pc1 && h /= h2
onTopPiece pc@(_,_,h) p1 = hPlayer p1 == p
&& h > 0
&& topOfTheStack bs pc
piecesFreeToAttck :: GameState -> HivePlayer -> Int
piecesFreeToAttck gs p = Map.size $ Map.filterWithKey freeToAttack coords
where
bs = gsBoard gs
coords = bsCoords bs
adjacency = bsAdjacency bs
idMap = bsIdMap bs
connMap = bsCannonicalIdMap bs
queenText = playerText oposingPlayer <> "Q"
queenExists = Bimap.member queenText connMap
queenId = idMap Bimap.!> (connMap Bimap.! queenText)
adjacentToQueen = if queenExists
then IG.neighbours queenId adjacency
else []
oposingPlayer
| p == Player1 = Player2
| otherwise = Player1
freeToAttack pc pl = (hPlayer pl == p)
&& (hPieceId pl `notElem` adjacentToQueen)
&& not (null $ validPieceMoves gs pc)
breathingRoom :: GameState -> PieceId -> Int
breathingRoom gs pId = 6 - Set.size intersections
where
bs = gsBoard gs
heights = Map.keysSet $ bsStackHeights bs
pc = bsIdMap bs Bimap.! pId
intersections = Set.intersection neighbors heights
neighbors = Set.fromList $ map ((\(x,y,_) -> (x,y)) . getNeighbor pc) allDirections
| z0isch/lambda-hive | src/LambdaHive/AI.hs | bsd-3-clause | 5,389 | 0 | 19 | 1,451 | 1,815 | 939 | 876 | 125 | 4 |
{-
parse-dimacs is free software: it is released under the BSD3 open source
license. You can find details of this license in the file LICENSE at the
root of the source tree.
Copyright 2008 Denis Bueno
-}
-- | A simple module for parsing CNF files in DIMACS format.
module Language.CNF.Parse.ParseDIMACS
( parseByteString
, parseFile
, CNF(..)
, Clause )
where
import Control.Monad
import Data.Array.Unboxed
import Data.ByteString.Lazy( ByteString )
import Prelude hiding (readFile, map)
import Text.Parsec( ParseError, SourceName )
import Text.Parsec.ByteString.Lazy
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.Prim( try, unexpected, runParser )
import qualified Text.Parsec.Token as T
data CNF = CNF
{ numVars :: !Int
-- ^ The number of variables in the problem as reported by the cnf header.
, numClauses :: !Int
-- ^ The number of clauses in the problem as reported by the cnf header.
, clauses :: ![Clause] } deriving Show
type Clause = UArray Int Int
-- | Parse a file containing DIMACS CNF data.
parseFile :: FilePath -> IO (Either ParseError CNF)
parseFile = parseFromFile cnf
-- | Parse a byte string containing DIMACS CNF data. The source name is only
-- | used in error messages and may be the empty string.
parseByteString :: SourceName -> ByteString -> Either ParseError CNF
parseByteString = runParser cnf ()
-- A DIMACS CNF file contains a header of the form "p cnf <numVars>
-- <numClauses>" and then a bunch of 0-terminated clauses.
cnf :: Parser CNF
cnf = uncurry CNF `fmap` cnfHeader `ap` lexeme (many1 clause)
-- Parses into `(numVars, numClauses)'.
cnfHeader :: Parser (Int, Int)
cnfHeader = do
whiteSpace
char 'p' >> many1 space -- Can't use symbol here because it uses
-- whiteSpace, which will treat the following
-- "cnf" as a comment.
symbol "cnf"
(,) `fmap` natural `ap` natural
clause :: Parser (UArray Int Int)
clause = do ints <- lexeme int `manyTill` try (symbol "0")
return $ listArray (0, length ints - 1) ints
-- token parser
tp = T.makeTokenParser $ T.LanguageDef
{ T.commentStart = ""
, T.commentEnd = ""
, T.commentLine = "c"
, T.nestedComments = False
, T.identStart = unexpected "ParseDIMACS bug: shouldn't be parsing identifiers..."
, T.identLetter = unexpected "ParseDIMACS bug: shouldn't be parsing identifiers..."
, T.opStart = unexpected "ParseDIMACS bug: shouldn't be parsing operators..."
, T.opLetter = unexpected "ParseDIMACS bug: shouldn't be parsing operators..."
, T.reservedNames = ["p", "cnf"]
, T.reservedOpNames = []
, T.caseSensitive = True
}
natural :: Parser Int
natural = fromIntegral `fmap` T.natural tp
int :: Parser Int
int = fromIntegral `fmap` T.integer tp
symbol = T.symbol tp
whiteSpace = T.whiteSpace tp
lexeme = T.lexeme tp | rbonifacio/funsat | etc/parse-dimacs/Language/CNF/Parse/ParseDIMACS.hs | bsd-3-clause | 2,921 | 0 | 11 | 633 | 605 | 347 | 258 | 60 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Fakemain where
import Brick.Main
import Brick.BChan
import Control.Concurrent
import Control.Monad
import Graphics.Vty
import Data.Default
import Network.Wreq
import Control.Lens
import System.Environment.XDG.BaseDir
import Network.HTTP.Conduit
import Data.Scientific
import Text.Read
import Data.Maybe (isJust, fromJust)
import System.Posix.Files
import System.Directory
import Player
import UI
import Types
import Constant
updateTimeLine :: IO (ThreadId, BChan CustomEvent)
updateTimeLine = do
chan <- newBChan 100
tid <- forkIO $ forever $ do
writeBChan chan UpdateTimeline
threadDelay 500000
return (tid, chan)
main' :: IO ()
main' = do
mp <- startMplayer
(tid1, chan) <- updateTimeLine
tid2 <- forkIO $ forever $ do
writeBChan chan UpdateSong
threadDelay 1000000
opt <- defOpt
cache <- getUserCacheFile "hnem" "cache"
cacheDir <- getUserCacheDir "hnem"
db <- doesDirectoryExist cacheDir
b <- fileExist cache
unless db $ createDirectory cacheDir
unless b $ writeFile cache "this is your first login"
(uid': cookieJar') <- lines <$> readFile cache
let cookiejar = readMaybe (concat cookieJar') :: Maybe CookieJar
uid = readMaybe uid' :: Maybe Scientific
st = if isJust cookiejar && isJust uid then
let opt' = opt & cookies .~ cookiejar
in initialSt & stlog . option .~ opt'
& stlog . userId .~ uid
& stlogined .~ True
else initialSt & stlog . option .~ opt
void $ customMain (mkVty defaultConfig) (Just chan) theApp st
{ _stmplayer = Just mp,
_stupdaterId = [tid1, tid2],
_stcachefile = cache
}
terminateMplayer mp
mapM_ killThread [tid2, tid2]
| Frefreak/hnem | src/Fakemain.hs | bsd-3-clause | 1,878 | 0 | 20 | 518 | 540 | 272 | 268 | -1 | -1 |
module Language.SystemF.Parser where
import Language.SystemF.Syntax
import Text.ParserCombinators.Parsec hiding (runParser,char,string,space)
import qualified Text.ParserCombinators.Parsec as P
import Data.Char
import Data.List
import Control.Monad
import Data.Maybe
------------------------------------------------------------------------------
parseName :: Parser String
parseName = lexeme $ primParseName
parseContextName :: Parser String
parseContextName = lexeme $ primParseContextName
parseLit :: Parser String
parseLit = lexeme $ primParseLit
symbol :: Char -> Parser ()
symbol ch = lexeme (do P.char ch ; return ())
-- add a keyword combinator
symbol' :: String -> Parser ()
symbol' str = lexeme (do P.string str ; return ())
parseSemi :: Parser ()
parseSemi = symbol ';'
parseOpenParen :: Parser ()
parseOpenParen = symbol '('
parseCloseParen :: Parser ()
parseCloseParen = symbol ')'
parseExp :: Parser Exp
parseExp = (do exp <- parseAExp
aexps <- many (liftM Right parseAExp <|>
(do symbol '<'
t <- liftM Left parseType
symbol '>'
return t))
return $ foldl mkAPP exp aexps)
<|> (do symbol '\\'
args <- many1 parseNameWithType
symbol' "->"
exp <- parseExp
return $ foldr (\ (e,t) -> Lam e t) exp args)
<|> (do symbol' "/\\"
nms <- many1 parseName
symbol' "->"
exp <- parseExp
return $ foldr LAM exp nms)
<|> (do symbol' "let"
binds <- parseBinding
symbol' "in"
exp <- parseExp
return $ Let binds exp)
<|> (do symbol' "case"
e <- parseExp
symbol' "of"
symbol' "{"
alts <- sepBy
(option Nothing (liftM Just parseAlt))
(symbol ';')
extra <- option Nothing $ do
symbol' "_"
symbol' "->"
e <- parseExp
return $ Just e
symbol '}'
return (Case e (catMaybes alts) extra)
)
parseNameWithType :: Parser (Name,Type)
parseNameWithType = (do
n <- parseName
symbol' "::"
t <- parseType
return (n,t))
<|> (do symbol '(' ; nt <- parseNameWithType ; symbol ')' ; return nt)
-- AExp == Atomic Expression
parseAExp :: Parser Exp
parseAExp =
(liftM Var parseName)
<|> (liftM Lit parseLit)
<|> (do symbol '(' ; e <- parseExp ; symbol ')' ; return e)
parseType :: Parser Type
parseType = do
do t <- parseType'
option t (do symbol' "->"
t2 <- parseType
return $ TyCon "->" [t,t2])
parseType' :: Parser Type
parseType' =
(liftM TyVar parseName)
<|> (do lit <- parseLit
tys <- many parseType'
return $ TyCon lit tys)
<|> (do symbol' "forall"
n <- parseName
symbol '.'
ty <- parseType
return (TyForAll n ty))
<|> (do symbol '(' ; t <- parseType ; symbol ')' ; return t)
mkAPP e1 (Right e2) = App e1 e2
mkAPP e1 (Left t2) = APP e1 t2
parseBind :: Parser Bind
parseBind = do nm <- parseName
symbol' "::"
ty <- parseType
symbol' "="
exp <- parseExp
return $ (nm,(ty,exp))
parseBinding :: Parser Binding
parseBinding = liftM RecBindings
$ liftM catMaybes
$ sepBy
(option Nothing (liftM Just parseBind))
(symbol ';')
parseProgram :: Parser Program
parseProgram = do
binds <- parseBinding
-- single recusive group
return $ Program [] [binds]
--parseContext :: Parser (Name,Context)
--parseContext =
parseAlt :: Parser (Pat,Exp)
parseAlt = do
consName <- parseLit
args <- many $ parseParens $ do
n <- parseName
symbol' "::"
t <- parseType
return (n,t)
symbol' "->"
e <- parseExp
return (Pat consName args,e)
------------------------------------------------------------------------------
parseParens :: Parser a -> Parser a
parseParens p = do
symbol '('
r <- p
symbol ')'
return r
------------------------------------------------------------------------------
whiteSpace :: Parser ()
whiteSpace = skipMany (P.space <|> comment)
where
comment = try (P.string "--" >> many (noneOf "\n") >> P.char '\n')
lexeme :: Parser a -> Parser a
lexeme p = do { r <- try p; whiteSpace; return r }
primParseName :: Parser String
primParseName = do c <- satisfy first
cs <- many $ satisfy rest
if (c:cs) `elem` keywords
then fail "keywords"
else return ()
return $ c : cs
where
first c = isLower c || c == '_'
rest c = first c || isDigit c || isUpper c
primParseContextName :: Parser String
primParseContextName = do c <- P.char '$'
cs <- many1 $ satisfy rest
if (c:cs) `elem` keywords
then fail "keywords"
else return ()
return $ c : cs
where
rest c = isLower c || isDigit c || isUpper c
primParseLit :: Parser String
primParseLit = (do c <- satisfy first
cs <- many $ satisfy rest
return $ c : cs)
<|> (do many1 $ digit)
where
first c = isUpper c
rest c = first c || isDigit c || isLower c || c == '_'
symChars = "!#$%^&*-_+=|<>.?/'"
keywords = ["case","of","let","in","forall"] -- ids that are not allowed as ids
symbols = ["="] -- symbolic names that are also not allowed
------------------------------------------------------------------------------
testParser :: Parser a -> String -> Either ParseError a
testParser p input = parse (do { whiteSpace ; r<- p ; eof ; return r}) "" input
runParser :: Parser a -> String -> IO a
runParser p input
= case testParser p input of
Left err -> do{ putStr "parse error at "
; print err
; error "done"
}
Right x -> return x
| andygill/er-systemf | Language/SystemF/Parser.hs | bsd-3-clause | 6,533 | 0 | 20 | 2,421 | 2,010 | 961 | 1,049 | 168 | 2 |
-- some tests for behaviors.
module Main
( main
) where
import Sirea.Prelude
bHelloWorld = bconst "Hello, World!" >>> bprint
main :: IO ()
main =
print "before hw app (ctrl+c to halt)" >>
runSireaApp bHelloWorld >>
print "after hw app"
| dmbarbour/Sirea | tst/Hello.hs | bsd-3-clause | 268 | 0 | 7 | 73 | 59 | 31 | 28 | 9 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
[@ISO639-1@] -
[@ISO639-2@] -
[@ISO639-3@] kmr
[@Native name@] -
[@English name@] Kurmanji
-}
module Text.Numeral.Language.KMR.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Prelude ( Num )
import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
{-
Sources:
http://www.languagesandnumbers.com/how-to-count-in-northern-kurdish/en/kmr/
-}
cardinals ∷ (Num i) ⇒ TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (0, "sifir")
, (1, "yek")
, (2, "du")
, (3, "sê")
, (4, "çar")
, (5, "pênc")
, (6, "şeş")
, (7, "heft")
, (8, "heşt")
, (9, "neh")
, (10, "deh")
, (11, "yanzdeh")
, (12, "dwanzdeh")
, (13, "sêzdeh")
, (14, "çardeh")
, (15, "panzdeh")
, (16, "şanzdeh")
, (17, "hivdeh")
, (18, "hijdeh")
, (19, "nozdeh")
, (20, "bîst")
, (21, "bîst û yek")
, (22, "bîst û du")
, (23, "bîst û sê")
, (24, "bîst û çar")
, (25, "bîst û pênc")
, (26, "bîst û şeş")
, (27, "bîst û heft")
, (28, "bîst û heşt")
, (29, "bîst û neh")
, (30, "sî")
, (31, "sî û yek")
, (32, "sî û du")
, (33, "sî û sê")
, (34, "sî û çar")
, (35, "sî û pênc")
, (36, "sî û şeş")
, (37, "sî û heft")
, (38, "sî û heşt")
, (39, "sî û neh")
, (40, "çil")
, (41, "çil û yek")
, (42, "çil û du")
, (43, "çil û sê")
, (44, "çil û çar")
, (45, "çil û pênc")
, (46, "çil û şeş")
, (47, "çil û heft")
, (48, "çil û heşt")
, (49, "çil û neh")
, (50, "pêncî")
, (51, "pêncî û yek")
, (52, "pêncî û du")
, (53, "pêncî û sê")
, (54, "pêncî û çar")
, (55, "pêncî û pênc")
, (56, "pêncî û şeş")
, (57, "pêncî û heft")
, (58, "pêncî û heşt")
, (59, "pêncî û neh")
, (60, "şêst")
, (61, "şêst û yek")
, (62, "şêst û du")
, (63, "şêst û sê")
, (64, "şêst û çar")
, (65, "şêst û pênc")
, (66, "şêst û şeş")
, (67, "şêst û heft")
, (68, "şêst û heşt")
, (69, "şêst û neh")
, (70, "heftê")
, (71, "heftê û yek")
, (72, "heftê û du")
, (73, "heftê û sê")
, (74, "heftê û çar")
, (75, "heftê û pênc")
, (76, "heftê û şeş")
, (77, "heftê û heft")
, (78, "heftê û heşt")
, (79, "heftê û neh")
, (80, "heştê")
, (81, "heştê û yek")
, (82, "heştê û du")
, (83, "heştê û sê")
, (84, "heştê û çar")
, (85, "heştê û pênc")
, (86, "heştê û şeş")
, (87, "heştê û heft")
, (88, "heştê û heşt")
, (89, "heştê û neh")
, (90, "nod")
, (91, "nod û yek")
, (92, "nod û du")
, (93, "nod û sê")
, (94, "nod û çar")
, (95, "nod û pênc")
, (96, "nod û şeş")
, (97, "nod û heft")
, (98, "nod û heşt")
, (99, "nod û neh")
, (100, "sed")
, (101, "sed û yek")
, (102, "sed û du")
, (103, "sed û sê")
, (104, "sed û çar")
, (105, "sed û pênc")
, (106, "sed û şeş")
, (107, "sed û heft")
, (108, "sed û heşt")
, (109, "sed û neh")
, (110, "sed û deh")
, (123, "sed û bîst û sê")
, (200, "dused")
, (300, "sêsed")
, (321, "sêsed û bîst û yek")
, (400, "çarsed")
, (500, "pêncsed")
, (600, "şeşsed")
, (700, "heftsed")
, (800, "heştsed")
, (900, "nehsed")
, (909, "nehsed û neh")
, (990, "nehsed û nod")
, (999, "nehsed û nod û neh")
, (1000, "hezar")
, (1001, "hezar û yek")
, (1008, "hezar û heşt")
, (1234, "hezar û dused û sî û çar")
, (2000, "du hezar")
, (3000, "sê hezar")
, (4000, "çar hezar")
, (4321, "çar hezar û sêsed û bîst û yek")
, (5000, "pênc hezar")
, (6000, "şeş hezar")
, (7000, "heft hezar")
, (8000, "heşt hezar")
, (9000, "neh hezar")
, (10000, "deh hezar")
, (12345, "dwanzdeh hezar û sêsed û çil û pênc")
, (20000, "bîst hezar")
, (30000, "sî hezar")
, (40000, "çil hezar")
, (50000, "pêncî hezar")
, (54321, "pêncî û çar hezar û sêsed û bîst û yek")
, (60000, "şêst hezar")
, (70000, "heftê hezar")
, (80000, "heştê hezar")
, (90000, "nod hezar")
, (100000, "sed hezar")
, (123456, "sed û bîst û sê hezar û çarsed û pêncî û şeş")
, (200000, "dused hezar")
, (300000, "sêsed hezar")
, (400000, "çarsed hezar")
, (500000, "pêncsed hezar")
, (600000, "şeşsed hezar")
, (654321, "şeşsed û pêncî û çar hezar û sêsed û bîst û yek")
, (700000, "heftsed hezar")
, (800000, "heştsed hezar")
, (900000, "nehsed hezar")
, (1000000, "milyon")
, (1000001, "milyon û yek")
, (1234567, "milyon û dused û sî û çar hezar û pêncsed û şêst û heft")
, (2000000, "du milyon")
, (3000000, "sê milyon")
, (4000000, "çar milyon")
, (5000000, "pênc milyon")
, (6000000, "şeş milyon")
, (7000000, "heft milyon")
, (7654321, "heft milyon û şeşsed û pêncî û çar hezar û sêsed û bîst û yek")
, (8000000, "heşt milyon")
, (9000000, "neh milyon")
]
)
]
| telser/numerals | src-test/Text/Numeral/Language/KMR/TestData.hs | bsd-3-clause | 6,274 | 0 | 8 | 1,985 | 1,633 | 1,091 | 542 | 183 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| type Vec a N = {v:[a] | len v = N } |]
[lq| ok :: Vec Int 3 |]
ok = [1,2,3] :: [Int]
[lq| ok' :: Vec _ 3 |] -- would be nice to support the hole in the application..
ok' = [1,2,3]
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/hole-app.hs | bsd-3-clause | 250 | 0 | 5 | 68 | 61 | 41 | 20 | 7 | 1 |
module Control.Bind where
import Control.Apply
class Apply f => Bind f where
(=<<) ::
(a -> f b)
-> f a
-> f b
| tonymorris/lens-proposal | src/Control/Bind.hs | bsd-3-clause | 127 | 0 | 10 | 40 | 58 | 30 | 28 | 7 | 0 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
module Fragment.Annotation.Ast.Term (
TmFAnnotation
, AsTmAnnotation(..)
) where
import Data.Functor.Classes (Eq1(..), Ord1(..), Show1(..), showsBinaryWith)
import Bound (Bound(..))
import Control.Lens.Prism (Prism')
import Control.Lens.Wrapped (_Wrapped, _Unwrapped)
import Control.Lens.TH (makePrisms)
import Data.Deriving (makeLiftEq, makeLiftCompare, makeLiftShowsPrec)
import Ast.Type
import Ast.Term
import Data.Bitransversable
import Data.Functor.Rec
import Util.Prisms
data TmFAnnotation (ki :: (* -> *) -> * -> *) (ty :: ((* -> *) -> * -> *) -> (* -> *) -> * -> *) (pt :: (* -> *) -> * -> *) k a =
TmAnnotationF (k a) (k a)
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
makePrisms ''TmFAnnotation
instance (Eq1 f, Monad f) => Eq1 (TmFAnnotation ki ty pt f) where
liftEq = $(makeLiftEq ''TmFAnnotation)
instance (Ord1 f, Monad f) => Ord1 (TmFAnnotation ki ty pt f) where
liftCompare = $(makeLiftCompare ''TmFAnnotation)
instance (Show1 f) => Show1 (TmFAnnotation ki ty pt f) where
liftShowsPrec = $(makeLiftShowsPrec ''TmFAnnotation)
instance EqRec (TmFAnnotation ki ty pt) where
liftEqRec eR _ (TmAnnotationF ty1 tm1) (TmAnnotationF ty2 tm2) =
eR ty1 ty2 && eR tm1 tm2
instance OrdRec (TmFAnnotation ki ty pt) where
liftCompareRec cR _ (TmAnnotationF ty1 tm1) (TmAnnotationF ty2 tm2) =
case cR ty1 ty2 of
EQ -> cR tm1 tm2
z -> z
instance ShowRec (TmFAnnotation ki ty pt) where
liftShowsPrecRec sR _ _ _ n (TmAnnotationF ty tm) =
showsBinaryWith sR sR "TmAnnotationF" n ty tm
instance Bound (TmFAnnotation ki ty pt) where
TmAnnotationF ty tm >>>= f = TmAnnotationF (ty >>= f) (tm >>= f)
instance Bitransversable (TmFAnnotation ki ty pt) where
bitransverse fT fL (TmAnnotationF ty tm) = TmAnnotationF <$> fT fL ty <*> fT fL tm
class (TmAstBound ki ty pt tm, TmAstTransversable ki ty pt tm) => AsTmAnnotation ki ty pt tm where
_TmAnnotationP :: Prism' (tm ki ty pt f a) (TmFAnnotation ki ty pt f a)
_TmAnnotation :: Prism' (Term ki ty pt tm a) (Type ki ty a, Term ki ty pt tm a)
_TmAnnotation = _Wrapped . _TmAstTerm . _TmAnnotationP . _TmAnnotationF . mkPair _TmType _Unwrapped
instance (Bound ki, Bound (ty ki), Bound pt, Bitransversable ki, Bitransversable (ty ki), Bitransversable pt) => AsTmAnnotation ki ty pt TmFAnnotation where
_TmAnnotationP = id
instance {-# OVERLAPPABLE #-} (Bound (x ki ty pt), Bitransversable (x ki ty pt), AsTmAnnotation ki ty pt (TmSum xs)) => AsTmAnnotation ki ty pt (TmSum (x ': xs)) where
_TmAnnotationP = _TmNext . _TmAnnotationP
instance {-# OVERLAPPING #-} (Bound ki, Bound (ty ki), Bound pt, Bound (TmSum xs ki ty pt), Bitransversable ki, Bitransversable (ty ki), Bitransversable pt, Bitransversable (TmSum xs ki ty pt)) => AsTmAnnotation ki ty pt (TmSum (TmFAnnotation ': xs)) where
_TmAnnotationP = _TmNow . _TmAnnotationP
| dalaing/type-systems | src/Fragment/Annotation/Ast/Term.hs | bsd-3-clause | 3,348 | 0 | 10 | 590 | 1,186 | 631 | 555 | 59 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.PrettyPrint.Annotated
-- Copyright : (c) Trevor Elliott <[email protected]> 2015
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : David Terei <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- This module provides a version of pretty that allows for annotations to be
-- attached to documents. Annotations are arbitrary pieces of metadata that can
-- be attached to sub-documents.
--
-- This module should be used as opposed to the
-- 'Text.PrettyPrint.Annotated.HughesPJ' module. Both are equivalent though as
-- this module simply re-exports the other.
--
-----------------------------------------------------------------------------
module Text.PrettyPrint.Annotated (
-- * The document type
Doc,
-- * Constructing documents
-- ** Converting values into documents
char, text, ptext, sizedText, zeroWidthText,
int, integer, float, double, rational,
-- ** Simple derived documents
semi, comma, colon, space, equals,
lparen, rparen, lbrack, rbrack, lbrace, rbrace,
-- ** Wrapping documents in delimiters
parens, brackets, braces, quotes, doubleQuotes,
-- ** Combining documents
empty,
(<>), (<+>), hcat, hsep,
($$), ($+$), vcat,
sep, cat,
fsep, fcat,
nest,
hang, punctuate,
-- ** Annotating documents
annotate,
-- * Predicates on documents
isEmpty,
-- * Rendering documents
-- ** Default rendering
render,
-- ** Annotation rendering
renderSpans, Span(..),
-- ** Rendering with a particular style
Style(..),
style,
renderStyle,
-- ** General rendering
fullRender,
fullRenderAnn,
Mode(..), TextDetails(..)
) where
import Text.PrettyPrint.Annotated.HughesPJ
| ddssff/pretty-listlike | src/Text/PrettyPrint/Annotated.hs | bsd-3-clause | 2,026 | 0 | 5 | 552 | 234 | 171 | 63 | 25 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Language.C.Inline.FunPtr
( mkFunPtr
, mkFunPtrFromName
, peekFunPtr
, uniqueFfiImportName
) where
import Foreign.Ptr (FunPtr)
import qualified Language.Haskell.TH as TH
import qualified Language.Haskell.TH.Syntax as TH
------------------------------------------------------------------------
-- FFI wrappers
-- | @$('mkFunPtr' [t| 'CDouble' -> 'IO' 'CDouble' |] @ generates a foreign import
-- wrapper of type
--
-- @
-- ('CDouble' -> 'IO' 'CDouble') -> 'IO' ('FunPtr' ('CDouble' -> 'IO' 'CDouble'))
-- @
--
-- And invokes it.
mkFunPtr :: TH.TypeQ -> TH.ExpQ
mkFunPtr hsTy = do
ffiImportName <- uniqueFfiImportName
dec <- TH.forImpD TH.CCall TH.Safe "wrapper" ffiImportName [t| $(hsTy) -> IO (FunPtr $(hsTy)) |]
TH.addTopDecls [dec]
TH.varE ffiImportName
-- | @$('mkFunPtrFromName' 'foo)@, if @foo :: 'CDouble' -> 'IO'
-- 'CDouble'@, splices in an expression of type @'IO' ('FunPtr'
-- ('CDouble' -> 'IO' 'CDouble'))@.
mkFunPtrFromName :: TH.Name -> TH.ExpQ
mkFunPtrFromName name = do
i <- TH.reify name
case i of
#if MIN_VERSION_template_haskell(2,11,0)
TH.VarI _ ty _ -> [| $(mkFunPtr (return ty)) $(TH.varE name) |]
#else
TH.VarI _ ty _ _ -> [| $(mkFunPtr (return ty)) $(TH.varE name) |]
#endif
_ -> fail "mkFunPtrFromName: expecting a variable as argument."
-- | @$('peekFunPtr' [t| 'CDouble' -> 'IO' 'CDouble' |])@ generates a foreign import
-- dynamic of type
--
-- @
-- 'FunPtr' ('CDouble' -> 'IO' 'CDouble') -> ('CDouble' -> 'IO' 'CDouble')
-- @
--
-- And invokes it.
peekFunPtr :: TH.TypeQ -> TH.ExpQ
peekFunPtr hsTy = do
ffiImportName <- uniqueFfiImportName
dec <- TH.forImpD TH.CCall TH.Safe "dynamic" ffiImportName [t| FunPtr $(hsTy) -> $(hsTy) |]
TH.addTopDecls [dec]
TH.varE ffiImportName
-- TODO absurdly, I need to 'newName' twice for things to work. I found
-- this hack in language-c-inline. Why is this?
uniqueFfiImportName :: TH.Q TH.Name
uniqueFfiImportName = TH.newName . show =<< TH.newName "inline_c_ffi"
| Teaspot-Studio/inline-c | src/Language/C/Inline/FunPtr.hs | mit | 2,080 | 0 | 11 | 352 | 329 | 188 | 141 | 31 | 2 |
{-# LANGUAGE BangPatterns #-}
module LocalRef where
import Prelude hiding (lookup)
--
difference a b = foldlWithKey' go
where
go = case "oaeu" of
"oeu" -> "oqeju"
_ -> "oeuoeu"
{-# INLINABLE difference #-}
--
intersection a b = foldlWithKey' go (5 :: Int) 3 1
where
go x y z = x + y + z
{-# INLINABLE intersection #-}
foldlWithKey' = id
| google/haskell-indexer | haskell-indexer-backend-ghc/testdata/basic/LocalRef.hs | apache-2.0 | 392 | 0 | 9 | 119 | 106 | 59 | 47 | 10 | 2 |
{-# LANGUAGE TemplateHaskell, FunctionalDependencies #-}
{-| Implementation of the Ganeti Disk config object.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Objects.Disk where
import Prelude ()
import Ganeti.Prelude
import qualified Data.ByteString.UTF8 as UTF8
import Data.Char (isAsciiLower, isAsciiUpper, isDigit)
import Data.List (isPrefixOf, isInfixOf)
import Language.Haskell.TH.Syntax
import Text.JSON (showJSON, readJSON, JSValue(..))
import qualified Text.JSON as J
import Ganeti.JSON (Container, fromObj)
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Types
import Ganeti.Utils.Validate
-- | Constant for the dev_type key entry in the disk config.
devType :: String
devType = "dev_type"
-- | The disk parameters type.
type DiskParams = Container JSValue
-- | An alias for DRBD secrets
type DRBDSecret = String
-- Represents a group name and a volume name.
--
-- From @man lvm@:
--
-- The following characters are valid for VG and LV names: a-z A-Z 0-9 + _ . -
--
-- VG and LV names cannot begin with a hyphen. There are also various reserved
-- names that are used internally by lvm that can not be used as LV or VG names.
-- A VG cannot be called anything that exists in /dev/ at the time of
-- creation, nor can it be called '.' or '..'. A LV cannot be called '.' '..'
-- 'snapshot' or 'pvmove'. The LV name may also not contain the strings '_mlog'
-- or '_mimage'
data LogicalVolume = LogicalVolume { lvGroup :: String
, lvVolume :: String
}
deriving (Eq, Ord)
instance Show LogicalVolume where
showsPrec _ (LogicalVolume g v) =
showString g . showString "/" . showString v
-- | Check the constraints for VG\/LV names (except the @\/dev\/@ check).
instance Validatable LogicalVolume where
validate (LogicalVolume g v) = do
let vgn = "Volume group name"
-- Group name checks
nonEmpty vgn g
validChars vgn g
notStartsDash vgn g
notIn vgn g [".", ".."]
-- Volume name checks
let lvn = "Volume name"
nonEmpty lvn v
validChars lvn v
notStartsDash lvn v
notIn lvn v [".", "..", "snapshot", "pvmove"]
reportIf ("_mlog" `isInfixOf` v) $ lvn ++ " must not contain '_mlog'."
reportIf ("_mimage" `isInfixOf` v) $ lvn ++ "must not contain '_mimage'."
where
nonEmpty prefix x = reportIf (null x) $ prefix ++ " must be non-empty"
notIn prefix x =
mapM_ (\y -> reportIf (x == y)
$ prefix ++ " must not be '" ++ y ++ "'")
notStartsDash prefix x = reportIf ("-" `isPrefixOf` x)
$ prefix ++ " must not start with '-'"
validChars prefix x =
reportIf (not . all validChar $ x)
$ prefix ++ " must consist only of [a-z][A-Z][0-9][+_.-]"
validChar c = isAsciiLower c || isAsciiUpper c || isDigit c
|| (c `elem` "+_.-")
instance J.JSON LogicalVolume where
showJSON = J.showJSON . show
readJSON (J.JSString s) | (g, _ : l) <- break (== '/') (J.fromJSString s) =
either fail return . evalValidate . validate' $ LogicalVolume g l
readJSON v = fail $ "Invalid JSON value " ++ show v
++ " for a logical volume"
-- | The disk configuration type. This includes the disk type itself,
-- for a more complete consistency. Note that since in the Python
-- code-base there's no authoritative place where we document the
-- logical id, this is probably a good reference point. There is a bijective
-- correspondence between the 'DiskLogicalId' constructors and 'DiskTemplate'.
data DiskLogicalId
= LIDPlain LogicalVolume -- ^ Volume group, logical volume
| LIDDrbd8 String String Int Int Int (Private DRBDSecret)
-- ^ NodeA, NodeB, Port, MinorA, MinorB, Secret
| LIDFile FileDriver String -- ^ Driver, path
| LIDSharedFile FileDriver String -- ^ Driver, path
| LIDGluster FileDriver String -- ^ Driver, path
| LIDBlockDev BlockDriver String -- ^ Driver, path (must be under /dev)
| LIDRados String String -- ^ Unused, path
| LIDExt String String -- ^ ExtProvider, unique name
deriving (Show, Eq)
-- | Mapping from a logical id to a disk type.
lidDiskType :: DiskLogicalId -> DiskTemplate
lidDiskType (LIDPlain {}) = DTPlain
lidDiskType (LIDDrbd8 {}) = DTDrbd8
lidDiskType (LIDFile {}) = DTFile
lidDiskType (LIDSharedFile {}) = DTSharedFile
lidDiskType (LIDGluster {}) = DTGluster
lidDiskType (LIDBlockDev {}) = DTBlock
lidDiskType (LIDRados {}) = DTRbd
lidDiskType (LIDExt {}) = DTExt
-- | Builds the extra disk_type field for a given logical id.
lidEncodeType :: DiskLogicalId -> [(String, JSValue)]
lidEncodeType v = [(devType, showJSON . lidDiskType $ v)]
-- | Returns the storage path or the unique name for a given logical id if
-- present
getStorageId :: DiskLogicalId -> Maybe String
getStorageId dlid =
case dlid of
LIDPlain lv -> Just $ lvGroup lv ++ "/" ++ lvVolume lv
LIDDrbd8 {} -> Nothing
LIDFile _ path -> Just path
LIDSharedFile _ path -> Just path
LIDGluster _ path -> Just path
LIDBlockDev _ path -> Just path
LIDRados _ path -> Just path
LIDExt _ uniqueName -> Just uniqueName
-- | Returns the provider for ExtStorage and Nothing otherwise
getExtProvider :: DiskLogicalId -> Maybe String
getExtProvider (LIDExt provider _) = Just provider
getExtProvider _ = Nothing
-- | Custom encoder for DiskLogicalId (logical id only).
encodeDLId :: DiskLogicalId -> JSValue
encodeDLId (LIDPlain (LogicalVolume vg lv)) =
JSArray [showJSON vg, showJSON lv]
encodeDLId (LIDDrbd8 nodeA nodeB port minorA minorB key) =
JSArray [ showJSON nodeA, showJSON nodeB, showJSON port
, showJSON minorA, showJSON minorB, showJSON key ]
encodeDLId (LIDRados pool name) = JSArray [showJSON pool, showJSON name]
encodeDLId (LIDFile driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDSharedFile driver name) =
JSArray [showJSON driver, showJSON name]
encodeDLId (LIDGluster driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDBlockDev driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDExt extprovider name) =
JSArray [showJSON extprovider, showJSON name]
-- | Custom encoder for DiskLogicalId, composing both the logical id
-- and the extra disk_type field.
encodeFullDLId :: DiskLogicalId -> (JSValue, [(String, JSValue)])
encodeFullDLId v = (encodeDLId v, lidEncodeType v)
-- | Custom decoder for DiskLogicalId. This is manual for now, since
-- we don't have yet automation for separate-key style fields.
decodeDLId :: [(String, JSValue)] -> JSValue -> J.Result DiskLogicalId
decodeDLId obj lid = do
dtype <- fromObj obj devType
case dtype of
DTDrbd8 ->
case lid of
JSArray [nA, nB, p, mA, mB, k] ->
LIDDrbd8
<$> readJSON nA
<*> readJSON nB
<*> readJSON p
<*> readJSON mA
<*> readJSON mB
<*> readJSON k
_ -> fail "Can't read logical_id for DRBD8 type"
DTPlain ->
case lid of
JSArray [vg, lv] -> LIDPlain <$>
(LogicalVolume <$> readJSON vg <*> readJSON lv)
_ -> fail "Can't read logical_id for plain type"
DTFile ->
case lid of
JSArray [driver, path] ->
LIDFile
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for file type"
DTSharedFile ->
case lid of
JSArray [driver, path] ->
LIDSharedFile
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for shared file type"
DTGluster ->
case lid of
JSArray [driver, path] ->
LIDGluster
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for shared file type"
DTBlock ->
case lid of
JSArray [driver, path] ->
LIDBlockDev
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for blockdev type"
DTRbd ->
case lid of
JSArray [driver, path] ->
LIDRados
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for rdb type"
DTExt ->
case lid of
JSArray [extprovider, name] ->
LIDExt
<$> readJSON extprovider
<*> readJSON name
_ -> fail "Can't read logical_id for extstorage type"
DTDiskless ->
fail "Retrieved 'diskless' disk."
-- | Disk data structure.
$(buildObjectWithForthcoming "Disk" "disk" $
[ customField 'decodeDLId 'encodeFullDLId ["dev_type"] $
simpleField "logical_id" [t| DiskLogicalId |]
, defaultField [| [] |]
$ simpleField "children" (return . AppT ListT . ConT $ mkName "Disk")
, defaultField [| [] |] $ simpleField "nodes" [t| [String] |]
, defaultField [| "" |] $ simpleField "iv_name" [t| String |]
, simpleField "size" [t| Int |]
, defaultField [| DiskRdWr |] $ simpleField "mode" [t| DiskMode |]
, optionalField $ simpleField "name" [t| String |]
, optionalField $ simpleField "spindles" [t| Int |]
, optionalField $ simpleField "params" [t| DiskParams |]
]
++ uuidFields
++ serialFields
++ timeStampFields)
instance TimeStampObject Disk where
cTimeOf = diskCtime
mTimeOf = diskMtime
instance UuidObject Disk where
uuidOf = UTF8.toString . diskUuid
instance SerialNoObject Disk where
serialOf = diskSerial
instance ForthcomingObject Disk where
isForthcoming = diskForthcoming
-- | Determines whether a disk or one of his children has the given logical id
-- (determined by the volume group name and by the logical volume name).
-- This can be true only for DRBD or LVM disks.
includesLogicalId :: LogicalVolume -> Disk -> Bool
includesLogicalId lv disk =
case diskLogicalId disk of
Just (LIDPlain lv') -> lv' == lv
Just (LIDDrbd8 {}) ->
any (includesLogicalId lv) $ diskChildren disk
_ -> False
| onponomarev/ganeti | src/Ganeti/Objects/Disk.hs | bsd-2-clause | 11,302 | 0 | 19 | 2,698 | 2,391 | 1,255 | 1,136 | 202 | 17 |
-- |
-- Module : Codec.Binary.DataEncoding
-- Copyright : (c) 2007 Magnus Therning
-- License : BSD3
--
-- This module exposes several instances of 'DataCodec', one for each data
-- encoding implemented in the library without causing the name clashing that
-- would result from importing the individual encoding modules.
--
-- Further documentation and information can be found at
-- <http://www.haskell.org/haskellwiki/Library/Data_encoding>.
module Codec.Binary.DataEncoding
( DataCodec
, base16
, base32
, base32Hex
, base64
, base64Url
, base85
, chop
, decode
, encode
, py
, qp
, unchop
, url
, uu
, xx
)
where
import Data.Word
import qualified Codec.Binary.Base16 as Base16
import qualified Codec.Binary.Base32 as Base32
import qualified Codec.Binary.Base32Hex as Base32Hex
import qualified Codec.Binary.Base64 as Base64
import qualified Codec.Binary.Base64Url as Base64Url
import qualified Codec.Binary.Base85 as Base85
import qualified Codec.Binary.Url as Url
import qualified Codec.Binary.Uu as Uu
import qualified Codec.Binary.Xx as Xx
import qualified Codec.Binary.QuotedPrintable as QP
import qualified Codec.Binary.PythonString as Py
-- {{{1 DataCodec
-- | Used to group a specific data encoding's functions.
data DataCodec = DataCodec {
encode :: [Word8] -> String,
decode :: String -> Maybe [Word8],
chop :: Int -> String -> [String],
unchop :: [String] -> String
}
-- {{{1 base16
-- | Base16 encoding, see "Codec.Binary.Base16" for more details on
-- the individual functions.
base16 :: DataCodec
base16 = DataCodec {
encode=Base16.encode,
decode=Base16.decode,
chop=Base16.chop,
unchop=Base16.unchop
}
-- {{{1 base32
-- | Base32 encoding, see "Codec.Binary.Base32" for more details on
-- the individual functions.
base32 :: DataCodec
base32 = DataCodec {
encode=Base32.encode,
decode=Base32.decode,
chop=Base32.chop,
unchop=Base32.unchop
}
-- {{{1 base32Hex
-- | Base32Hex encoding, see "Codec.Binary.Base32Hex" for more details
-- on the individual functions.
base32Hex :: DataCodec
base32Hex = DataCodec {
encode=Base32Hex.encode,
decode=Base32Hex.decode,
chop=Base32Hex.chop,
unchop=Base32Hex.unchop
}
-- {{{1 base64
-- | Base64 encoding, see "Codec.Binary.Base64" for more details on
-- the individual functions.
base64 :: DataCodec
base64 = DataCodec {
encode=Base64.encode,
decode=Base64.decode,
chop=Base64.chop,
unchop=Base64.unchop
}
-- {{{1 base64Url
-- | Base64Url encoding, see "Codec.Binary.Base64Url" for more details
-- on the individual functions.
base64Url :: DataCodec
base64Url = DataCodec {
encode=Base64Url.encode,
decode=Base64Url.decode,
chop=Base64Url.chop,
unchop=Base64Url.unchop
}
-- {{{1 base85
-- | Base85 encoding, see "Codec.Binary.Base85" for more details
-- on the individual functions.
base85 :: DataCodec
base85 = DataCodec {
encode=Base85.encode,
decode=Base85.decode,
chop=Base85.chop,
unchop=Base85.unchop
}
-- {{{1 uu
-- | Uuencoding, see "Codec.Binary.Uu" for more details on the
-- individual functions.
uu :: DataCodec
uu = DataCodec {
encode=Uu.encode,
decode=Uu.decode,
chop=Uu.chop,
unchop=Uu.unchop
}
-- {{{1 xx
-- | Xxencoding, see "Codec.Binary.Xx" for more details on the
-- individual functions.
xx :: DataCodec
xx = DataCodec {
encode=Xx.encode,
decode=Xx.decode,
chop=Xx.chop,
unchop=Xx.unchop
}
-- {{{1 quoted-printable
-- | Quoted-printable, see "Codec.Binary.QuotedPrintable" for more details on
-- the individual functions.
qp :: DataCodec
qp = DataCodec
{ encode = QP.encode
, decode = QP.decode
, chop = QP.chop
, unchop = QP.unchop
}
-- {{{1 python string
-- | Quoted-printable, see "Codec.Binary.PythonString" for more details on
-- the individual functions.
py :: DataCodec
py = DataCodec
{ encode = Py.encode
, decode = Py.decode
, chop = Py.chop
, unchop = Py.unchop
}
-- {{{1 url encoding
-- | URL encoding, see "Codec.Binary.Url" for more details on the individual
-- functions.
url :: DataCodec
url = DataCodec
{ encode = Url.encode
, decode = Url.decode
, chop = Url.chop
, unchop = Url.unchop
}
| magthe/dataenc | src/Codec/Binary/DataEncoding.hs | bsd-3-clause | 4,310 | 0 | 11 | 877 | 759 | 501 | 258 | 100 | 1 |
module System.Console.GetOpt.Generics.Modifier.Types where
data Modifiers = Modifiers {
shortOptions :: [(String, [Char])],
renaming :: String -> String,
positionalArgumentsField :: Maybe (String, String),
_helpTexts :: [(String, String)],
version :: Maybe String
}
getVersion :: Modifiers -> Maybe String
getVersion modifiers = version modifiers
isPositionalArgumentsField :: Modifiers -> String -> Bool
isPositionalArgumentsField modifiers field =
maybe False ((field ==) . fst) (positionalArgumentsField modifiers)
getPositionalArgumentType :: Modifiers -> Maybe String
getPositionalArgumentType = fmap snd . positionalArgumentsField
| kosmikus/getopt-generics | src/System/Console/GetOpt/Generics/Modifier/Types.hs | bsd-3-clause | 655 | 0 | 11 | 91 | 180 | 103 | 77 | 14 | 1 |
module Halfs.File
( FileHandle (..) -- fhInode, fhReadable, fhWritable)
, createFile
, fofReadOnly
, fofWriteOnly
, fofReadWrite
, getFHINR_lckd
, openFilePrim
, closeFilePrim
, removeFile
)
where
import Halfs.BlockMap
import Halfs.Classes
import Halfs.Directory
import Halfs.Errors
import Halfs.HalfsState
import Halfs.Inode
import Halfs.Monad
import Halfs.MonadUtils
import Halfs.Protection
import Halfs.Types
import Halfs.Utils
import System.Device.BlockDevice
-- import Debug.Trace
type HalfsM b r l m a = HalfsT HalfsError (Maybe (HalfsState b r l m)) m a
--------------------------------------------------------------------------------
-- File creation and manipulation functions
createFile :: HalfsCapable b t r l m =>
DirHandle r l
-> FilePath
-> UserID
-> GroupID
-> FileMode
-> HalfsM b r l m InodeRef
createFile parentDH fname usr grp mode = do
dev <- hasks hsBlockDev
bm <- hasks hsBlockMap
mfileIR <- fmap blockAddrToInodeRef `fmap` lift (alloc1 bm)
case mfileIR of
Nothing -> throwError HE_AllocFailed
Just fileIR -> do
withDHLock parentDH $ do
pIR <- getDHINR_lckd parentDH
n <- lift $ buildEmptyInodeEnc
dev
RegularFile
mode
fileIR
pIR
usr
grp
lift $ bdWriteBlock dev (inodeRefToBlockAddr fileIR) n
addDirEnt_lckd parentDH fname fileIR usr grp mode RegularFile
numNodesRsc <- hasks hsNumFileNodes
atomicModifyLockedRscRef numNodesRsc (+1)
return $ fileIR
removeFile :: HalfsCapable b t r l m =>
Maybe String -- ^ name to remove from parent directory's content
-- map (when Nothing, leaves the parent directory's
-- content map alone)
-> InodeRef -- ^ inr of file to remove
-> HalfsM b r l m ()
removeFile mfname inr = do
case mfname of
Nothing -> return ()
Just fname -> do
-- Purge the filename from the parent directory
dhMap <- hasks hsDHMap
withLockedRscRef dhMap $ \dhMapRef -> do
pinr <- atomicReadInode inr inoParent
pdh <- lookupRM pinr dhMapRef >>= maybe (newDirHandle pinr) return
rmDirEnt pdh fname
-- Decrement link count & register deallocation callback
hbracket (openFilePrim fofReadOnly inr) closeFilePrim $ \fh -> do
fhMap <- hasks hsFHMap
withLockedRscRef fhMap $ \fhMapRef -> do
atomicModifyInode inr $ \nd -> do
when (inoNumLinks nd == 1) $ do
-- We're removing the last link, so we inject a callback into the fhmap
-- that will be invoked when all processes have closed the filehandle
-- associated with inr. The callback invalidates the filehandle and
-- releases its inode. NB: The callback must assume that both the fhmap
-- and fh locks are held when it is executed.
mfhData <- lookupRM inr fhMapRef
case mfhData of
Just (_, c, _) -> insertRM inr (fh, c, cb) fhMapRef
where cb = invalidateFH fh >> freeInode inr
Nothing -> error "fh not found for open file, cannot happen"
return nd{ inoNumLinks = inoNumLinks nd - 1 }
openFilePrim :: HalfsCapable b t r l m =>
FileOpenFlags -> InodeRef -> HalfsM b r l m (FileHandle r l)
openFilePrim oflags@FileOpenFlags{ openMode = omode } inr = do
fhMap <- hasks hsFHMap
withLockedRscRef fhMap $ \fhMapRef -> do
mfh <- lookupRM inr fhMapRef
case mfh of
Just (fh, c, onFinalClose) -> do
insertRM inr (fh, c + 1, onFinalClose) fhMapRef
return fh
Nothing -> do
fh <- FH (omode /= WriteOnly) (omode /= ReadOnly) oflags
`fmap` newRef (Just inr)
`ap` newLock
insertRM inr (fh, 1, invalidateFH fh) fhMapRef
return fh
closeFilePrim :: HalfsCapable b t r l m =>
FileHandle r l
-> HalfsM b r l m ()
closeFilePrim fh = do
fhMap <- hasks hsFHMap
withLock (fhLock fh) $ do
withLockedRscRef fhMap $ \fhMapRef -> do
inr <- getFHINR_lckd fh
mfh <- lookupRM inr fhMapRef
case mfh of
Nothing -> return ()
-- Remove FH from the map when the current open count is 1, otherwise
-- just decrement it. When FH is removed from the map, execute the
-- 'onFinalClose' callback from the fhmap (which, by default, simply
-- invalidates the FH, but may also, e.g., deallocate resources for the
-- file if a function like rmlink needs to defer resource release). NB:
-- onFinalClose may assume that both fh and fhmap locks are held!
--
-- TODO: We may want to do this on a per-process basis (e.g., by mapping
-- an inr to a pid -> open count map) to disallow accidental multiple
-- closes across multiple processes resulting in incorrect open counts.
-- At the very least, we should work through the ramifications should
-- this multiple-close scenario occur. This includes dealing with
-- per-process FH invalidation as well. E.g., in the current scheme, if
-- two processes p1 and p2 have the FH and p1 closes it, FH invalidation
-- does not occur (it would occur only after p1 and p2 closed the FH)
-- and so p1 can still use the FH which is not intended.
--
Just (_, c, onFinalClose)
| c == 1 -> deleteRM inr fhMapRef >> onFinalClose
| otherwise -> insertRM inr (fh, c - 1, onFinalClose) fhMapRef
-- Get file handle's inode reference
getFHINR_lckd :: HalfsCapable b t r l m =>
FileHandle r l
-> HalfsM b r l m InodeRef
getFHINR_lckd fh =
-- Precond: (fhLock fh) has been acquried (TODO: can we assert this?)
readRef (fhInode fh) >>= maybe (throwError HE_InvalidFileHandle) return
invalidateFH :: HalfsCapable b t r l m =>
FileHandle r l
-> HalfsM b r l m ()
invalidateFH fh = writeRef (fhInode fh) Nothing
fofReadOnly :: FileOpenFlags
fofReadOnly = FileOpenFlags False False ReadOnly
fofWriteOnly, fofReadWrite :: Bool -> FileOpenFlags
fofWriteOnly app = FileOpenFlags app False WriteOnly
fofReadWrite app = FileOpenFlags app False ReadWrite
| hackern/halfs | Halfs/File.hs | bsd-3-clause | 6,496 | 0 | 28 | 2,000 | 1,396 | 697 | 699 | 120 | 3 |
module Graphics.Vty.UnicodeWidthTable.Types
( UnicodeWidthTable(..)
, WidthTableRange(..)
)
where
import Data.Word (Word8, Word32)
-- | A range of code points in a width table.
data WidthTableRange =
WidthTableRange { rangeStart :: Word32
-- ^ The range's starting code point.
, rangeSize :: Word32
-- ^ The number of code points in the contiguous
-- range, beginning with the starting code point
-- ('rangeStart').
, rangeColumns :: Word8
-- ^ The terminal width, in columns, of all of the
-- characters corresponding to the code points in
-- this range.
}
deriving (Eq, Show)
-- | A run-length-encoded table of Unicode character widths.
data UnicodeWidthTable =
UnicodeWidthTable { unicodeWidthTableRanges :: [WidthTableRange]
-- ^ The ranges in the table.
}
deriving (Show)
| jtdaugherty/vty | src/Graphics/Vty/UnicodeWidthTable/Types.hs | bsd-3-clause | 1,046 | 0 | 9 | 388 | 110 | 73 | 37 | 12 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.