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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DNS.ManagedZones.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Update an existing ManagedZone.
--
-- /See:/ <https://developers.google.com/cloud-dns Google Cloud DNS API Reference> for @dns.managedZones.update@.
module Network.Google.Resource.DNS.ManagedZones.Update
(
-- * REST Resource
ManagedZonesUpdateResource
-- * Creating a Request
, managedZonesUpdate
, ManagedZonesUpdate
-- * Request Lenses
, mzuProject
, mzuPayload
, mzuManagedZone
, mzuClientOperationId
) where
import Network.Google.DNS.Types
import Network.Google.Prelude
-- | A resource alias for @dns.managedZones.update@ method which the
-- 'ManagedZonesUpdate' request conforms to.
type ManagedZonesUpdateResource =
"dns" :>
"v2beta1" :>
"projects" :>
Capture "project" Text :>
"managedZones" :>
Capture "managedZone" Text :>
QueryParam "clientOperationId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ManagedZone :> Put '[JSON] Operation
-- | Update an existing ManagedZone.
--
-- /See:/ 'managedZonesUpdate' smart constructor.
data ManagedZonesUpdate = ManagedZonesUpdate'
{ _mzuProject :: !Text
, _mzuPayload :: !ManagedZone
, _mzuManagedZone :: !Text
, _mzuClientOperationId :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ManagedZonesUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mzuProject'
--
-- * 'mzuPayload'
--
-- * 'mzuManagedZone'
--
-- * 'mzuClientOperationId'
managedZonesUpdate
:: Text -- ^ 'mzuProject'
-> ManagedZone -- ^ 'mzuPayload'
-> Text -- ^ 'mzuManagedZone'
-> ManagedZonesUpdate
managedZonesUpdate pMzuProject_ pMzuPayload_ pMzuManagedZone_ =
ManagedZonesUpdate'
{ _mzuProject = pMzuProject_
, _mzuPayload = pMzuPayload_
, _mzuManagedZone = pMzuManagedZone_
, _mzuClientOperationId = Nothing
}
-- | Identifies the project addressed by this request.
mzuProject :: Lens' ManagedZonesUpdate Text
mzuProject
= lens _mzuProject (\ s a -> s{_mzuProject = a})
-- | Multipart request metadata.
mzuPayload :: Lens' ManagedZonesUpdate ManagedZone
mzuPayload
= lens _mzuPayload (\ s a -> s{_mzuPayload = a})
-- | Identifies the managed zone addressed by this request. Can be the
-- managed zone name or id.
mzuManagedZone :: Lens' ManagedZonesUpdate Text
mzuManagedZone
= lens _mzuManagedZone
(\ s a -> s{_mzuManagedZone = a})
-- | For mutating operation requests only. An optional identifier specified
-- by the client. Must be unique for operation resources in the Operations
-- collection.
mzuClientOperationId :: Lens' ManagedZonesUpdate (Maybe Text)
mzuClientOperationId
= lens _mzuClientOperationId
(\ s a -> s{_mzuClientOperationId = a})
instance GoogleRequest ManagedZonesUpdate where
type Rs ManagedZonesUpdate = Operation
type Scopes ManagedZonesUpdate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/ndev.clouddns.readwrite"]
requestClient ManagedZonesUpdate'{..}
= go _mzuProject _mzuManagedZone
_mzuClientOperationId
(Just AltJSON)
_mzuPayload
dNSService
where go
= buildClient
(Proxy :: Proxy ManagedZonesUpdateResource)
mempty
|
rueshyna/gogol
|
gogol-dns/gen/Network/Google/Resource/DNS/ManagedZones/Update.hs
|
mpl-2.0
| 4,307
| 0
| 16
| 1,017
| 547
| 325
| 222
| 87
| 1
|
module Mechanism.Examples.PublicProject where
import qualified Data.Foldable as F
import Data.Functor ((<$>))
import Data.Set (Set)
import qualified Data.Set as S
import Mechanism
import Mechanism.Profile.Sequence (Coll)
import qualified Mechanism.Profile.Sequence as P
data Project = Completed { perCapitaCost :: Util Double }
| Failed
deriving (Eq, Ord, Show)
players :: Profile Coll Int
players = P.fromList [0, 1]
cost :: Util Double
cost = Util 50
typeSet :: Set (Type (Util Double))
typeSet = S.fromList [20, 60]
actionSet :: Set (Action (Util Double))
actionSet = S.fromList [20, 60]
outcomes :: Set (Outcome Project)
outcomes =
S.fromList $ Outcome <$>
[Completed (cost / fromIntegral (P.length players)), Failed]
valuation' :: Valuation Project (Util Double) (Util Double) Double
valuation' = valuation go
where
go (Outcome out) (Type ty) =
case out of
(Completed cs) -> ty - cs
Failed -> 0
allocator :: Allocator (Util Double) Project
allocator acs =
Outcome $ if F.sum acs >= Action cost
then Completed (cost / fromIntegral (P.length acs))
else Failed
choice :: SocialChoice (Util Double) (QuasiOutcome Project Double)
choice acs =
Outcome $ QuasiOutcome (allocator acs)
(clarkes allocator (P.replicate (P.length acs) valuation') $ honest' <$> acs)
mechanism :: DirectMechanism (Util Double) (QuasiOutcome Project Double)
mechanism = directMechanism (P.replicate (P.length players) typeSet) choice
utilities :: QuasiUtilities Project (Util Double) (Util Double) Double
utilities = quasiUtility 0 valuation' <$> players
game :: DirectQuasiGame Project (Util Double) Double
game = Game utilities mechanism
shapleys :: Types (Util Double) -> Utils Double
shapleys tys = P.imap go tys
where
go i ty = shapleyValue ((\ty' -> Agent (actionSet, (valuation', ty'))) <$> exclude i tys)
(characteristic allocator) $ Agent (actionSet, (valuation', ty))
clarkes' :: Types (Util Double) -> Transfers Double
clarkes' tys = clarkes allocator (P.replicate (P.length tys) valuation') tys
exPostRational' :: Bool
exPostRational' =
exPostRational fs choice $ matches tyss acss
where
Game fs (Mechanism acss tyss _) = game
budget' :: BudgetBalance
budget' = budget . S.map (sc . snd . P.unzip) $ matches tyss acss
where
Mechanism acss tyss sc = mechanism
allocative' :: Bool
allocative' =
allocativelyEfficient
outcomes
(P.replicate (P.length players) valuation')
(runAllocation . runOutcome . sc)
(profiles tyss)
where
Mechanism _ tyss sc = mechanism
|
pseudonom/haskell-mechanism
|
src/Mechanism/Examples/PublicProject.hs
|
agpl-3.0
| 2,739
| 0
| 15
| 652
| 967
| 503
| 464
| 65
| 2
|
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Grains (square, total)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList grainsTests ]
grainsTests :: [Test]
grainsTests =
[ testCase "square 1" $
1 @=? square 1
, testCase "square 2" $
2 @=? square 2
, testCase "square 3" $
4 @=? square 3
, testCase "square 4" $
8 @=? square 4
, testCase "square 16" $
32768 @=? square 16
, testCase "square 32" $
2147483648 @=? square 32
, testCase "square 64" $
9223372036854775808 @=? square 64
, testCase "total grains" $
18446744073709551615 @=? total
]
|
mscoutermarsh/exercism_coveralls
|
assignments/haskell/grains/grains_test.hs
|
agpl-3.0
| 962
| 0
| 12
| 218
| 341
| 176
| 165
| 30
| 2
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGLContext.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Opengl.QGLContext (
QqGLContext(..)
,QqGLContext_nf(..)
,QchooseContext(..)
,QcolorIndex(..)
,qGLContextCurrentContext
,QdeviceIsPixmap(..)
,QgenerateFontDisplayLists(..)
,getProcAddress
,Qinitialized(..)
,overlayTransparentColor
,requestedFormat
,QsetInitialized(..)
,qGLContextSetTextureCacheLimit
,QsetWindowCreated(..)
,qGLContextTextureCacheLimit
,QwindowCreated(..)
,qGLContext_delete, qGLContext_delete1
)
where
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
import Qtc.Classes.Opengl
import Qtc.ClassTypes.Opengl
instance QuserMethod (QGLContext ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QGLContext_userMethod" qtc_QGLContext_userMethod :: Ptr (TQGLContext a) -> CInt -> IO ()
instance QuserMethod (QGLContextSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QGLContext ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLContext_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QGLContext_userMethodVariant" qtc_QGLContext_userMethodVariant :: Ptr (TQGLContext a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QGLContextSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QGLContext_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqGLContext x1 where
qGLContext :: x1 -> IO (QGLContext ())
instance QqGLContext ((QGLFormat t1)) where
qGLContext (x1)
= withQGLContextResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext cobj_x1
foreign import ccall "qtc_QGLContext" qtc_QGLContext :: Ptr (TQGLFormat t1) -> IO (Ptr (TQGLContext ()))
instance QqGLContext ((QGLFormat t1, QPaintDevice t2)) where
qGLContext (x1, x2)
= withQGLContextResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLContext1 cobj_x1 cobj_x2
foreign import ccall "qtc_QGLContext1" qtc_QGLContext1 :: Ptr (TQGLFormat t1) -> Ptr (TQPaintDevice t2) -> IO (Ptr (TQGLContext ()))
instance QqGLContext ((QGLFormat t1, QWidget t2)) where
qGLContext (x1, x2)
= withQGLContextResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLContext1_widget cobj_x1 cobj_x2
foreign import ccall "qtc_QGLContext1_widget" qtc_QGLContext1_widget :: Ptr (TQGLFormat t1) -> Ptr (TQWidget t2) -> IO (Ptr (TQGLContext ()))
class QqGLContext_nf x1 where
qGLContext_nf :: x1 -> IO (QGLContext ())
instance QqGLContext_nf ((QGLFormat t1)) where
qGLContext_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext cobj_x1
instance QqGLContext_nf ((QGLFormat t1, QPaintDevice t2)) where
qGLContext_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLContext1 cobj_x1 cobj_x2
instance QqGLContext_nf ((QGLFormat t1, QWidget t2)) where
qGLContext_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGLContext1_widget cobj_x1 cobj_x2
instance QbindTexture (QGLContext a) ((QImage t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_bindTexture" qtc_QGLContext_bindTexture :: Ptr (TQGLContext a) -> Ptr (TQImage t1) -> IO CUInt
instance QbindTexture (QGLContext a) ((QImage t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture3 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLContext_bindTexture3" qtc_QGLContext_bindTexture3 :: Ptr (TQGLContext a) -> Ptr (TQImage t1) -> CInt -> IO CUInt
instance QbindTexture (QGLContext a) ((QImage t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture5 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLContext_bindTexture5" qtc_QGLContext_bindTexture5 :: Ptr (TQGLContext a) -> Ptr (TQImage t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLContext a) ((QPixmap t1)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_bindTexture1" qtc_QGLContext_bindTexture1 :: Ptr (TQGLContext a) -> Ptr (TQPixmap t1) -> IO CUInt
instance QbindTexture (QGLContext a) ((QPixmap t1, Int)) where
bindTexture x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture4 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLContext_bindTexture4" qtc_QGLContext_bindTexture4 :: Ptr (TQGLContext a) -> Ptr (TQPixmap t1) -> CInt -> IO CUInt
instance QbindTexture (QGLContext a) ((QPixmap t1, Int, Int)) where
bindTexture x0 (x1, x2, x3)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_bindTexture6 cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QGLContext_bindTexture6" qtc_QGLContext_bindTexture6 :: Ptr (TQGLContext a) -> Ptr (TQPixmap t1) -> CInt -> CInt -> IO CUInt
instance QbindTexture (QGLContext a) ((String)) where
bindTexture x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLContext_bindTexture2 cobj_x0 cstr_x1
foreign import ccall "qtc_QGLContext_bindTexture2" qtc_QGLContext_bindTexture2 :: Ptr (TQGLContext a) -> CWString -> IO CUInt
class QchooseContext x0 x1 where
chooseContext :: x0 -> x1 -> IO (Bool)
instance QchooseContext (QGLContext ()) (()) where
chooseContext x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_chooseContext_h cobj_x0
foreign import ccall "qtc_QGLContext_chooseContext_h" qtc_QGLContext_chooseContext_h :: Ptr (TQGLContext a) -> IO CBool
instance QchooseContext (QGLContextSc a) (()) where
chooseContext x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_chooseContext_h cobj_x0
instance QchooseContext (QGLContext ()) ((QGLContext t1)) where
chooseContext x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_chooseContext1_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_chooseContext1_h" qtc_QGLContext_chooseContext1_h :: Ptr (TQGLContext a) -> Ptr (TQGLContext t1) -> IO CBool
instance QchooseContext (QGLContextSc a) ((QGLContext t1)) where
chooseContext x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_chooseContext1_h cobj_x0 cobj_x1
class QcolorIndex x0 x1 where
colorIndex :: x0 -> x1 -> IO (Int)
instance QcolorIndex (QGLContext ()) ((QColor t1)) where
colorIndex x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_colorIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_colorIndex" qtc_QGLContext_colorIndex :: Ptr (TQGLContext a) -> Ptr (TQColor t1) -> IO CUInt
instance QcolorIndex (QGLContextSc a) ((QColor t1)) where
colorIndex x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_colorIndex cobj_x0 cobj_x1
instance Qcreate (QGLContext ()) (()) (IO (Bool)) where
create x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_create_h cobj_x0
foreign import ccall "qtc_QGLContext_create_h" qtc_QGLContext_create_h :: Ptr (TQGLContext a) -> IO CBool
instance Qcreate (QGLContextSc a) (()) (IO (Bool)) where
create x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_create_h cobj_x0
instance Qcreate (QGLContext ()) ((QGLContext t1)) (IO (Bool)) where
create x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_create1_h cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_create1_h" qtc_QGLContext_create1_h :: Ptr (TQGLContext a) -> Ptr (TQGLContext t1) -> IO CBool
instance Qcreate (QGLContextSc a) ((QGLContext t1)) (IO (Bool)) where
create x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_create1_h cobj_x0 cobj_x1
qGLContextCurrentContext :: (()) -> IO (QGLContext ())
qGLContextCurrentContext ()
= withObjectRefResult $
qtc_QGLContext_currentContext
foreign import ccall "qtc_QGLContext_currentContext" qtc_QGLContext_currentContext :: IO (Ptr (TQGLContext ()))
instance QdeleteTexture (QGLContext a) ((Int)) where
deleteTexture x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_deleteTexture cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QGLContext_deleteTexture" qtc_QGLContext_deleteTexture :: Ptr (TQGLContext a) -> CUInt -> IO ()
instance Qdevice (QGLContext a) (()) (IO (QPaintDevice ())) where
device x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_device cobj_x0
foreign import ccall "qtc_QGLContext_device" qtc_QGLContext_device :: Ptr (TQGLContext a) -> IO (Ptr (TQPaintDevice ()))
class QdeviceIsPixmap x0 x1 where
deviceIsPixmap :: x0 -> x1 -> IO (Bool)
instance QdeviceIsPixmap (QGLContext ()) (()) where
deviceIsPixmap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_deviceIsPixmap cobj_x0
foreign import ccall "qtc_QGLContext_deviceIsPixmap" qtc_QGLContext_deviceIsPixmap :: Ptr (TQGLContext a) -> IO CBool
instance QdeviceIsPixmap (QGLContextSc a) (()) where
deviceIsPixmap x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_deviceIsPixmap cobj_x0
instance QdoneCurrent (QGLContext ()) (()) (IO ()) where
doneCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_doneCurrent_h cobj_x0
foreign import ccall "qtc_QGLContext_doneCurrent_h" qtc_QGLContext_doneCurrent_h :: Ptr (TQGLContext a) -> IO ()
instance QdoneCurrent (QGLContextSc a) (()) (IO ()) where
doneCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_doneCurrent_h cobj_x0
instance Qformat (QGLContext a) (()) (IO (QGLFormat ())) where
format x0 ()
= withQGLFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_format cobj_x0
foreign import ccall "qtc_QGLContext_format" qtc_QGLContext_format :: Ptr (TQGLContext a) -> IO (Ptr (TQGLFormat ()))
class QgenerateFontDisplayLists x0 x1 where
generateFontDisplayLists :: x0 -> x1 -> IO ()
instance QgenerateFontDisplayLists (QGLContext ()) ((QFont t1, Int)) where
generateFontDisplayLists x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_generateFontDisplayLists cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QGLContext_generateFontDisplayLists" qtc_QGLContext_generateFontDisplayLists :: Ptr (TQGLContext a) -> Ptr (TQFont t1) -> CInt -> IO ()
instance QgenerateFontDisplayLists (QGLContextSc a) ((QFont t1, Int)) where
generateFontDisplayLists x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_generateFontDisplayLists cobj_x0 cobj_x1 (toCInt x2)
getProcAddress :: QGLContext a -> ((String)) -> IO (QVoid ())
getProcAddress x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QGLContext_getProcAddress cobj_x0 cstr_x1
foreign import ccall "qtc_QGLContext_getProcAddress" qtc_QGLContext_getProcAddress :: Ptr (TQGLContext a) -> CWString -> IO (Ptr (TQVoid ()))
class Qinitialized x0 x1 where
initialized :: x0 -> x1 -> IO (Bool)
instance Qinitialized (QGLContext ()) (()) where
initialized x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_initialized cobj_x0
foreign import ccall "qtc_QGLContext_initialized" qtc_QGLContext_initialized :: Ptr (TQGLContext a) -> IO CBool
instance Qinitialized (QGLContextSc a) (()) where
initialized x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_initialized cobj_x0
instance QisSharing (QGLContext a) (()) where
isSharing x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_isSharing cobj_x0
foreign import ccall "qtc_QGLContext_isSharing" qtc_QGLContext_isSharing :: Ptr (TQGLContext a) -> IO CBool
instance QqisValid (QGLContext ()) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_isValid cobj_x0
foreign import ccall "qtc_QGLContext_isValid" qtc_QGLContext_isValid :: Ptr (TQGLContext a) -> IO CBool
instance QqisValid (QGLContextSc a) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_isValid cobj_x0
instance QmakeCurrent (QGLContext ()) (()) (IO ()) where
makeCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_makeCurrent_h cobj_x0
foreign import ccall "qtc_QGLContext_makeCurrent_h" qtc_QGLContext_makeCurrent_h :: Ptr (TQGLContext a) -> IO ()
instance QmakeCurrent (QGLContextSc a) (()) (IO ()) where
makeCurrent x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_makeCurrent_h cobj_x0
overlayTransparentColor :: QGLContext a -> (()) -> IO (QColor ())
overlayTransparentColor x0 ()
= withQColorResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_overlayTransparentColor cobj_x0
foreign import ccall "qtc_QGLContext_overlayTransparentColor" qtc_QGLContext_overlayTransparentColor :: Ptr (TQGLContext a) -> IO (Ptr (TQColor ()))
requestedFormat :: QGLContext a -> (()) -> IO (QGLFormat ())
requestedFormat x0 ()
= withQGLFormatResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_requestedFormat cobj_x0
foreign import ccall "qtc_QGLContext_requestedFormat" qtc_QGLContext_requestedFormat :: Ptr (TQGLContext a) -> IO (Ptr (TQGLFormat ()))
instance Qreset (QGLContext a) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_reset cobj_x0
foreign import ccall "qtc_QGLContext_reset" qtc_QGLContext_reset :: Ptr (TQGLContext a) -> IO ()
instance QsetDevice (QGLContext ()) ((QPaintDevice t1)) where
setDevice x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_setDevice cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_setDevice" qtc_QGLContext_setDevice :: Ptr (TQGLContext a) -> Ptr (TQPaintDevice t1) -> IO ()
instance QsetDevice (QGLContextSc a) ((QPaintDevice t1)) where
setDevice x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_setDevice cobj_x0 cobj_x1
instance QsetDevice (QGLContext ()) ((QWidget t1)) where
setDevice x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_setDevice_widget cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_setDevice_widget" qtc_QGLContext_setDevice_widget :: Ptr (TQGLContext a) -> Ptr (TQWidget t1) -> IO ()
instance QsetDevice (QGLContextSc a) ((QWidget t1)) where
setDevice x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_setDevice_widget cobj_x0 cobj_x1
instance QsetFormat (QGLContext a) ((QGLFormat t1)) where
setFormat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_setFormat cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_setFormat" qtc_QGLContext_setFormat :: Ptr (TQGLContext a) -> Ptr (TQGLFormat t1) -> IO ()
class QsetInitialized x0 x1 where
setInitialized :: x0 -> x1 -> IO ()
instance QsetInitialized (QGLContext ()) ((Bool)) where
setInitialized x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setInitialized cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLContext_setInitialized" qtc_QGLContext_setInitialized :: Ptr (TQGLContext a) -> CBool -> IO ()
instance QsetInitialized (QGLContextSc a) ((Bool)) where
setInitialized x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setInitialized cobj_x0 (toCBool x1)
qGLContextSetTextureCacheLimit :: ((Int)) -> IO ()
qGLContextSetTextureCacheLimit (x1)
= qtc_QGLContext_setTextureCacheLimit (toCInt x1)
foreign import ccall "qtc_QGLContext_setTextureCacheLimit" qtc_QGLContext_setTextureCacheLimit :: CInt -> IO ()
instance QsetValid (QGLContext ()) ((Bool)) where
setValid x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setValid cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLContext_setValid" qtc_QGLContext_setValid :: Ptr (TQGLContext a) -> CBool -> IO ()
instance QsetValid (QGLContextSc a) ((Bool)) where
setValid x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setValid cobj_x0 (toCBool x1)
class QsetWindowCreated x0 x1 where
setWindowCreated :: x0 -> x1 -> IO ()
instance QsetWindowCreated (QGLContext ()) ((Bool)) where
setWindowCreated x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setWindowCreated cobj_x0 (toCBool x1)
foreign import ccall "qtc_QGLContext_setWindowCreated" qtc_QGLContext_setWindowCreated :: Ptr (TQGLContext a) -> CBool -> IO ()
instance QsetWindowCreated (QGLContextSc a) ((Bool)) where
setWindowCreated x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_setWindowCreated cobj_x0 (toCBool x1)
instance QswapBuffers (QGLContext ()) (()) where
swapBuffers x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_swapBuffers_h cobj_x0
foreign import ccall "qtc_QGLContext_swapBuffers_h" qtc_QGLContext_swapBuffers_h :: Ptr (TQGLContext a) -> IO ()
instance QswapBuffers (QGLContextSc a) (()) where
swapBuffers x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_swapBuffers_h cobj_x0
qGLContextTextureCacheLimit :: (()) -> IO (Int)
qGLContextTextureCacheLimit ()
= withIntResult $
qtc_QGLContext_textureCacheLimit
foreign import ccall "qtc_QGLContext_textureCacheLimit" qtc_QGLContext_textureCacheLimit :: IO CInt
class QwindowCreated x0 x1 where
windowCreated :: x0 -> x1 -> IO (Bool)
instance QwindowCreated (QGLContext ()) (()) where
windowCreated x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_windowCreated cobj_x0
foreign import ccall "qtc_QGLContext_windowCreated" qtc_QGLContext_windowCreated :: Ptr (TQGLContext a) -> IO CBool
instance QwindowCreated (QGLContextSc a) (()) where
windowCreated x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_windowCreated cobj_x0
qGLContext_delete :: QGLContext a -> IO ()
qGLContext_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_delete cobj_x0
foreign import ccall "qtc_QGLContext_delete" qtc_QGLContext_delete :: Ptr (TQGLContext a) -> IO ()
qGLContext_delete1 :: QGLContext a -> IO ()
qGLContext_delete1 x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_delete1 cobj_x0
foreign import ccall "qtc_QGLContext_delete1" qtc_QGLContext_delete1 :: Ptr (TQGLContext a) -> IO ()
|
uduki/hsQt
|
Qtc/Opengl/QGLContext.hs
|
bsd-2-clause
| 20,136
| 0
| 14
| 3,262
| 6,390
| 3,251
| 3,139
| -1
| -1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTreeWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTreeWidget (
QqTreeWidget(..)
,addTopLevelItem
,collapseItem
,expandItem
,headerItem
,indexOfTopLevelItem
,insertTopLevelItem
,isFirstItemColumnSpanned
,isItemExpanded
,itemAbove
,itemBelow
,setFirstItemColumnSpanned
,setHeaderItem
,setHeaderLabel
,setHeaderLabels
,setItemExpanded
,sortColumn
,takeTopLevelItem
,topLevelItemCount
,qTreeWidget_delete
,qTreeWidget_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.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 (QTreeWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QTreeWidget_userMethod" qtc_QTreeWidget_userMethod :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QuserMethod (QTreeWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QTreeWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTreeWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QTreeWidget_userMethodVariant" qtc_QTreeWidget_userMethodVariant :: Ptr (TQTreeWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QTreeWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTreeWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqTreeWidget x1 where
qTreeWidget :: x1 -> IO (QTreeWidget ())
instance QqTreeWidget (()) where
qTreeWidget ()
= withQTreeWidgetResult $
qtc_QTreeWidget
foreign import ccall "qtc_QTreeWidget" qtc_QTreeWidget :: IO (Ptr (TQTreeWidget ()))
instance QqTreeWidget ((QWidget t1)) where
qTreeWidget (x1)
= withQTreeWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget1 cobj_x1
foreign import ccall "qtc_QTreeWidget1" qtc_QTreeWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQTreeWidget ()))
addTopLevelItem :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO ()
addTopLevelItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_addTopLevelItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_addTopLevelItem" qtc_QTreeWidget_addTopLevelItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance Qclear (QTreeWidget a) (()) where
clear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_clear cobj_x0
foreign import ccall "qtc_QTreeWidget_clear" qtc_QTreeWidget_clear :: Ptr (TQTreeWidget a) -> IO ()
instance QclosePersistentEditor (QTreeWidget a) ((QTreeWidgetItem t1)) where
closePersistentEditor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closePersistentEditor cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_closePersistentEditor" qtc_QTreeWidget_closePersistentEditor :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QclosePersistentEditor (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
closePersistentEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closePersistentEditor1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_closePersistentEditor1" qtc_QTreeWidget_closePersistentEditor1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO ()
collapseItem :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO ()
collapseItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_collapseItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_collapseItem" qtc_QTreeWidget_collapseItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QcolumnCount (QTreeWidget a) (()) where
columnCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnCount cobj_x0
foreign import ccall "qtc_QTreeWidget_columnCount" qtc_QTreeWidget_columnCount :: Ptr (TQTreeWidget a) -> IO CInt
instance QcurrentColumn (QTreeWidget a) (()) where
currentColumn x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_currentColumn cobj_x0
foreign import ccall "qtc_QTreeWidget_currentColumn" qtc_QTreeWidget_currentColumn :: Ptr (TQTreeWidget a) -> IO CInt
instance QcurrentItem (QTreeWidget a) (()) (IO (QTreeWidgetItem ())) where
currentItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_currentItem cobj_x0
foreign import ccall "qtc_QTreeWidget_currentItem" qtc_QTreeWidget_currentItem :: Ptr (TQTreeWidget a) -> IO (Ptr (TQTreeWidgetItem ()))
instance QdropEvent (QTreeWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dropEvent_h" qtc_QTreeWidget_dropEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QTreeWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent_h cobj_x0 cobj_x1
instance QdropMimeData (QTreeWidget ()) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
foreign import ccall "qtc_QTreeWidget_dropMimeData_h" qtc_QTreeWidget_dropMimeData_h :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQMimeData t3) -> CLong -> IO CBool
instance QdropMimeData (QTreeWidgetSc a) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData_h cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
instance QeditItem (QTreeWidget a) ((QTreeWidgetItem t1)) where
editItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_editItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_editItem" qtc_QTreeWidget_editItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QeditItem (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
editItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_editItem1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_editItem1" qtc_QTreeWidget_editItem1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO ()
instance Qevent (QTreeWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_event_h" qtc_QTreeWidget_event_h :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QTreeWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event_h cobj_x0 cobj_x1
expandItem :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO ()
expandItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_expandItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_expandItem" qtc_QTreeWidget_expandItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QfindItems (QTreeWidget a) ((String, MatchFlags)) (IO ([QTreeWidgetItem ()])) where
findItems x0 (x1, x2)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_findItems cobj_x0 cstr_x1 (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QTreeWidget_findItems" qtc_QTreeWidget_findItems :: Ptr (TQTreeWidget a) -> CWString -> CLong -> Ptr (Ptr (TQTreeWidgetItem ())) -> IO CInt
instance QfindItems (QTreeWidget a) ((String, MatchFlags, Int)) (IO ([QTreeWidgetItem ()])) where
findItems x0 (x1, x2, x3)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_findItems1 cobj_x0 cstr_x1 (toCLong $ qFlags_toInt x2) (toCInt x3) arr
foreign import ccall "qtc_QTreeWidget_findItems1" qtc_QTreeWidget_findItems1 :: Ptr (TQTreeWidget a) -> CWString -> CLong -> CInt -> Ptr (Ptr (TQTreeWidgetItem ())) -> IO CInt
headerItem :: QTreeWidget a -> (()) -> IO (QTreeWidgetItem ())
headerItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_headerItem cobj_x0
foreign import ccall "qtc_QTreeWidget_headerItem" qtc_QTreeWidget_headerItem :: Ptr (TQTreeWidget a) -> IO (Ptr (TQTreeWidgetItem ()))
instance QindexFromItem (QTreeWidget ()) ((QTreeWidgetItem t1)) where
indexFromItem x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexFromItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexFromItem" qtc_QTreeWidget_indexFromItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO (Ptr (TQModelIndex ()))
instance QindexFromItem (QTreeWidgetSc a) ((QTreeWidgetItem t1)) where
indexFromItem x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexFromItem cobj_x0 cobj_x1
instance QindexFromItem (QTreeWidget ()) ((QTreeWidgetItem t1, Int)) where
indexFromItem x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexFromItem1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_indexFromItem1" qtc_QTreeWidget_indexFromItem1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexFromItem (QTreeWidgetSc a) ((QTreeWidgetItem t1, Int)) where
indexFromItem x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexFromItem1 cobj_x0 cobj_x1 (toCInt x2)
indexOfTopLevelItem :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO (Int)
indexOfTopLevelItem x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexOfTopLevelItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexOfTopLevelItem" qtc_QTreeWidget_indexOfTopLevelItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO CInt
insertTopLevelItem :: QTreeWidget a -> ((Int, QTreeWidgetItem t2)) -> IO ()
insertTopLevelItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_insertTopLevelItem cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QTreeWidget_insertTopLevelItem" qtc_QTreeWidget_insertTopLevelItem :: Ptr (TQTreeWidget a) -> CInt -> Ptr (TQTreeWidgetItem t2) -> IO ()
instance QinvisibleRootItem (QTreeWidget a) (()) (IO (QTreeWidgetItem ())) where
invisibleRootItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_invisibleRootItem cobj_x0
foreign import ccall "qtc_QTreeWidget_invisibleRootItem" qtc_QTreeWidget_invisibleRootItem :: Ptr (TQTreeWidget a) -> IO (Ptr (TQTreeWidgetItem ()))
isFirstItemColumnSpanned :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO (Bool)
isFirstItemColumnSpanned x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isFirstItemColumnSpanned cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_isFirstItemColumnSpanned" qtc_QTreeWidget_isFirstItemColumnSpanned :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO CBool
isItemExpanded :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO (Bool)
isItemExpanded x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isItemExpanded cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_isItemExpanded" qtc_QTreeWidget_isItemExpanded :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO CBool
instance QisItemHidden (QTreeWidget a) ((QTreeWidgetItem t1)) where
isItemHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isItemHidden cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_isItemHidden" qtc_QTreeWidget_isItemHidden :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO CBool
instance QisItemSelected (QTreeWidget a) ((QTreeWidgetItem t1)) where
isItemSelected x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isItemSelected cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_isItemSelected" qtc_QTreeWidget_isItemSelected :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO CBool
instance QisSortingEnabled (QTreeWidget ()) (()) where
isSortingEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_isSortingEnabled cobj_x0
foreign import ccall "qtc_QTreeWidget_isSortingEnabled" qtc_QTreeWidget_isSortingEnabled :: Ptr (TQTreeWidget a) -> IO CBool
instance QisSortingEnabled (QTreeWidgetSc a) (()) where
isSortingEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_isSortingEnabled cobj_x0
itemAbove :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO (QTreeWidgetItem ())
itemAbove x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemAbove cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_itemAbove" qtc_QTreeWidget_itemAbove :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO (Ptr (TQTreeWidgetItem ()))
instance QitemAt (QTreeWidget a) ((Int, Int)) (IO (QTreeWidgetItem ())) where
itemAt x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_itemAt1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_itemAt1" qtc_QTreeWidget_itemAt1 :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (Ptr (TQTreeWidgetItem ()))
instance QitemAt (QTreeWidget a) ((Point)) (IO (QTreeWidgetItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_itemAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTreeWidget_itemAt_qth" qtc_QTreeWidget_itemAt_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (Ptr (TQTreeWidgetItem ()))
instance QqitemAt (QTreeWidget a) ((QPoint t1)) (IO (QTreeWidgetItem ())) where
qitemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemAt cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_itemAt" qtc_QTreeWidget_itemAt :: Ptr (TQTreeWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQTreeWidgetItem ()))
itemBelow :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO (QTreeWidgetItem ())
itemBelow x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemBelow cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_itemBelow" qtc_QTreeWidget_itemBelow :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO (Ptr (TQTreeWidgetItem ()))
instance QitemFromIndex (QTreeWidget ()) ((QModelIndex t1)) (IO (QTreeWidgetItem ())) where
itemFromIndex x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemFromIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_itemFromIndex" qtc_QTreeWidget_itemFromIndex :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQTreeWidgetItem ()))
instance QitemFromIndex (QTreeWidgetSc a) ((QModelIndex t1)) (IO (QTreeWidgetItem ())) where
itemFromIndex x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemFromIndex cobj_x0 cobj_x1
instance QitemWidget (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
itemWidget x0 (x1, x2)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_itemWidget cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_itemWidget" qtc_QTreeWidget_itemWidget :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO (Ptr (TQWidget ()))
instance QopenPersistentEditor (QTreeWidget a) ((QTreeWidgetItem t1)) where
openPersistentEditor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_openPersistentEditor cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_openPersistentEditor" qtc_QTreeWidget_openPersistentEditor :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QopenPersistentEditor (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
openPersistentEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_openPersistentEditor1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_openPersistentEditor1" qtc_QTreeWidget_openPersistentEditor1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO ()
instance QremoveItemWidget (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
removeItemWidget x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_removeItemWidget cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_removeItemWidget" qtc_QTreeWidget_removeItemWidget :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO ()
instance QscrollToItem (QTreeWidget a) ((QTreeWidgetItem t1)) where
scrollToItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollToItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_scrollToItem" qtc_QTreeWidget_scrollToItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QscrollToItem (QTreeWidget a) ((QTreeWidgetItem t1, ScrollHint)) where
scrollToItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollToItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_scrollToItem1" qtc_QTreeWidget_scrollToItem1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CLong -> IO ()
instance QselectedItems (QTreeWidget a) (()) (IO ([QTreeWidgetItem ()])) where
selectedItems x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectedItems cobj_x0 arr
foreign import ccall "qtc_QTreeWidget_selectedItems" qtc_QTreeWidget_selectedItems :: Ptr (TQTreeWidget a) -> Ptr (Ptr (TQTreeWidgetItem ())) -> IO CInt
instance QsetColumnCount (QTreeWidget a) ((Int)) where
setColumnCount x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setColumnCount cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_setColumnCount" qtc_QTreeWidget_setColumnCount :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QsetCurrentItem (QTreeWidget a) ((QTreeWidgetItem t1)) where
setCurrentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setCurrentItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setCurrentItem" qtc_QTreeWidget_setCurrentItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
instance QsetCurrentItem (QTreeWidget a) ((QTreeWidgetItem t1, Int)) where
setCurrentItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setCurrentItem1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QTreeWidget_setCurrentItem1" qtc_QTreeWidget_setCurrentItem1 :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> IO ()
setFirstItemColumnSpanned :: QTreeWidget a -> ((QTreeWidgetItem t1, Bool)) -> IO ()
setFirstItemColumnSpanned x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setFirstItemColumnSpanned cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTreeWidget_setFirstItemColumnSpanned" qtc_QTreeWidget_setFirstItemColumnSpanned :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CBool -> IO ()
setHeaderItem :: QTreeWidget a -> ((QTreeWidgetItem t1)) -> IO ()
setHeaderItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setHeaderItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setHeaderItem" qtc_QTreeWidget_setHeaderItem :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO ()
setHeaderLabel :: QTreeWidget a -> ((String)) -> IO ()
setHeaderLabel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_setHeaderLabel cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_setHeaderLabel" qtc_QTreeWidget_setHeaderLabel :: Ptr (TQTreeWidget a) -> CWString -> IO ()
setHeaderLabels :: QTreeWidget a -> (([String])) -> IO ()
setHeaderLabels x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QTreeWidget_setHeaderLabels cobj_x0 cqlistlen_x1 cqliststr_x1
foreign import ccall "qtc_QTreeWidget_setHeaderLabels" qtc_QTreeWidget_setHeaderLabels :: Ptr (TQTreeWidget a) -> CInt -> Ptr (Ptr CWchar) -> IO ()
setItemExpanded :: QTreeWidget a -> ((QTreeWidgetItem t1, Bool)) -> IO ()
setItemExpanded x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setItemExpanded cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTreeWidget_setItemExpanded" qtc_QTreeWidget_setItemExpanded :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CBool -> IO ()
instance QsetItemHidden (QTreeWidget a) ((QTreeWidgetItem t1, Bool)) where
setItemHidden x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setItemHidden cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTreeWidget_setItemHidden" qtc_QTreeWidget_setItemHidden :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CBool -> IO ()
instance QsetItemSelected (QTreeWidget a) ((QTreeWidgetItem t1, Bool)) where
setItemSelected x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setItemSelected cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTreeWidget_setItemSelected" qtc_QTreeWidget_setItemSelected :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CBool -> IO ()
instance QsetItemWidget (QTreeWidget a) ((QTreeWidgetItem t1, Int, QWidget t3)) where
setItemWidget x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_setItemWidget cobj_x0 cobj_x1 (toCInt x2) cobj_x3
foreign import ccall "qtc_QTreeWidget_setItemWidget" qtc_QTreeWidget_setItemWidget :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQWidget t3) -> IO ()
instance QsetSortingEnabled (QTreeWidget ()) ((Bool)) where
setSortingEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setSortingEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_setSortingEnabled" qtc_QTreeWidget_setSortingEnabled :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QsetSortingEnabled (QTreeWidgetSc a) ((Bool)) where
setSortingEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setSortingEnabled cobj_x0 (toCBool x1)
sortColumn :: QTreeWidget a -> (()) -> IO (Int)
sortColumn x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sortColumn cobj_x0
foreign import ccall "qtc_QTreeWidget_sortColumn" qtc_QTreeWidget_sortColumn :: Ptr (TQTreeWidget a) -> IO CInt
instance QsortItems (QTreeWidget a) ((Int, SortOrder)) where
sortItems x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sortItems cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_sortItems" qtc_QTreeWidget_sortItems :: Ptr (TQTreeWidget a) -> CInt -> CLong -> IO ()
instance QsupportedDropActions (QTreeWidget ()) (()) where
supportedDropActions x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions_h cobj_x0
foreign import ccall "qtc_QTreeWidget_supportedDropActions_h" qtc_QTreeWidget_supportedDropActions_h :: Ptr (TQTreeWidget a) -> IO CLong
instance QsupportedDropActions (QTreeWidgetSc a) (()) where
supportedDropActions x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions_h cobj_x0
takeTopLevelItem :: QTreeWidget a -> ((Int)) -> IO (QTreeWidgetItem ())
takeTopLevelItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_takeTopLevelItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_takeTopLevelItem" qtc_QTreeWidget_takeTopLevelItem :: Ptr (TQTreeWidget a) -> CInt -> IO (Ptr (TQTreeWidgetItem ()))
instance QtopLevelItem (QTreeWidget a) ((Int)) (IO (QTreeWidgetItem ())) where
topLevelItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_topLevelItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_topLevelItem" qtc_QTreeWidget_topLevelItem :: Ptr (TQTreeWidget a) -> CInt -> IO (Ptr (TQTreeWidgetItem ()))
topLevelItemCount :: QTreeWidget a -> (()) -> IO (Int)
topLevelItemCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_topLevelItemCount cobj_x0
foreign import ccall "qtc_QTreeWidget_topLevelItemCount" qtc_QTreeWidget_topLevelItemCount :: Ptr (TQTreeWidget a) -> IO CInt
instance QqvisualItemRect (QTreeWidget a) ((QTreeWidgetItem t1)) where
qvisualItemRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualItemRect cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualItemRect" qtc_QTreeWidget_visualItemRect :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> IO (Ptr (TQRect ()))
instance QvisualItemRect (QTreeWidget a) ((QTreeWidgetItem t1)) where
visualItemRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualItemRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTreeWidget_visualItemRect_qth" qtc_QTreeWidget_visualItemRect_qth :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qTreeWidget_delete :: QTreeWidget a -> IO ()
qTreeWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_delete cobj_x0
foreign import ccall "qtc_QTreeWidget_delete" qtc_QTreeWidget_delete :: Ptr (TQTreeWidget a) -> IO ()
qTreeWidget_deleteLater :: QTreeWidget a -> IO ()
qTreeWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_deleteLater cobj_x0
foreign import ccall "qtc_QTreeWidget_deleteLater" qtc_QTreeWidget_deleteLater :: Ptr (TQTreeWidget a) -> IO ()
instance QcolumnCountChanged (QTreeWidget ()) ((Int, Int)) where
columnCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnCountChanged cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_columnCountChanged" qtc_QTreeWidget_columnCountChanged :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance QcolumnCountChanged (QTreeWidgetSc a) ((Int, Int)) where
columnCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnCountChanged cobj_x0 (toCInt x1) (toCInt x2)
instance QcolumnMoved (QTreeWidget ()) (()) where
columnMoved x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnMoved cobj_x0
foreign import ccall "qtc_QTreeWidget_columnMoved" qtc_QTreeWidget_columnMoved :: Ptr (TQTreeWidget a) -> IO ()
instance QcolumnMoved (QTreeWidgetSc a) (()) where
columnMoved x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnMoved cobj_x0
instance QcolumnResized (QTreeWidget ()) ((Int, Int, Int)) where
columnResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_columnResized" qtc_QTreeWidget_columnResized :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> IO ()
instance QcolumnResized (QTreeWidgetSc a) ((Int, Int, Int)) where
columnResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_columnResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
instance QcurrentChanged (QTreeWidget ()) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_currentChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_currentChanged" qtc_QTreeWidget_currentChanged :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QcurrentChanged (QTreeWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_currentChanged cobj_x0 cobj_x1 cobj_x2
instance QdataChanged (QTreeWidget ()) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_dataChanged_h" qtc_QTreeWidget_dataChanged_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QdataChanged (QTreeWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged_h cobj_x0 cobj_x1 cobj_x2
instance QdoItemsLayout (QTreeWidget ()) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout_h cobj_x0
foreign import ccall "qtc_QTreeWidget_doItemsLayout_h" qtc_QTreeWidget_doItemsLayout_h :: Ptr (TQTreeWidget a) -> IO ()
instance QdoItemsLayout (QTreeWidgetSc a) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout_h cobj_x0
instance QdragMoveEvent (QTreeWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragMoveEvent_h" qtc_QTreeWidget_dragMoveEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QTreeWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QqdrawBranches (QTreeWidget ()) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches_h" qtc_QTreeWidget_drawBranches_h :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QqdrawBranches (QTreeWidgetSc a) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QdrawBranches (QTreeWidget ()) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches 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 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth_h cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches_qth_h" qtc_QTreeWidget_drawBranches_qth_h :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> CInt -> CInt -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawBranches (QTreeWidgetSc a) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches 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 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth_h cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
instance QdrawRow (QTreeWidget ()) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawRow_h" qtc_QTreeWidget_drawRow_h :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawRow (QTreeWidgetSc a) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow_h cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QdrawTree (QTreeWidget ()) ((QPainter t1, QRegion t2)) where
drawTree x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_drawTree cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_drawTree" qtc_QTreeWidget_drawTree :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQRegion t2) -> IO ()
instance QdrawTree (QTreeWidgetSc a) ((QPainter t1, QRegion t2)) where
drawTree x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_drawTree cobj_x0 cobj_x1 cobj_x2
instance QhorizontalOffset (QTreeWidget ()) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset_h cobj_x0
foreign import ccall "qtc_QTreeWidget_horizontalOffset_h" qtc_QTreeWidget_horizontalOffset_h :: Ptr (TQTreeWidget a) -> IO CInt
instance QhorizontalOffset (QTreeWidgetSc a) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset_h cobj_x0
instance QhorizontalScrollbarAction (QTreeWidget ()) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_horizontalScrollbarAction" qtc_QTreeWidget_horizontalScrollbarAction :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QhorizontalScrollbarAction (QTreeWidgetSc a) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalScrollbarAction cobj_x0 (toCInt x1)
instance QindexAt (QTreeWidget ()) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTreeWidget_indexAt_qth_h" qtc_QTreeWidget_indexAt_qth_h :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt (QTreeWidgetSc a) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt (QTreeWidget ()) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexAt_h" qtc_QTreeWidget_indexAt_h :: Ptr (TQTreeWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt (QTreeWidgetSc a) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt_h cobj_x0 cobj_x1
instance QindexRowSizeHint (QTreeWidget ()) ((QModelIndex t1)) where
indexRowSizeHint x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexRowSizeHint cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexRowSizeHint" qtc_QTreeWidget_indexRowSizeHint :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO CInt
instance QindexRowSizeHint (QTreeWidgetSc a) ((QModelIndex t1)) where
indexRowSizeHint x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexRowSizeHint cobj_x0 cobj_x1
instance QisIndexHidden (QTreeWidget ()) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isIndexHidden cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_isIndexHidden" qtc_QTreeWidget_isIndexHidden :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO CBool
instance QisIndexHidden (QTreeWidgetSc a) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_isIndexHidden cobj_x0 cobj_x1
instance QkeyPressEvent (QTreeWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyPressEvent_h" qtc_QTreeWidget_keyPressEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyboardSearch (QTreeWidget ()) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch_h cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_keyboardSearch_h" qtc_QTreeWidget_keyboardSearch_h :: Ptr (TQTreeWidget a) -> CWString -> IO ()
instance QkeyboardSearch (QTreeWidgetSc a) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch_h cobj_x0 cstr_x1
instance QmouseDoubleClickEvent (QTreeWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseDoubleClickEvent_h" qtc_QTreeWidget_mouseDoubleClickEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QTreeWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseMoveEvent_h" qtc_QTreeWidget_mouseMoveEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QTreeWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mousePressEvent_h" qtc_QTreeWidget_mousePressEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QTreeWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QTreeWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseReleaseEvent_h" qtc_QTreeWidget_mouseReleaseEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance QmoveCursor (QTreeWidget ()) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor_h cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_moveCursor_h" qtc_QTreeWidget_moveCursor_h :: Ptr (TQTreeWidget a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor (QTreeWidgetSc a) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor_h cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QpaintEvent (QTreeWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_paintEvent_h" qtc_QTreeWidget_paintEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QTreeWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent_h cobj_x0 cobj_x1
instance Qreexpand (QTreeWidget ()) (()) where
reexpand x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reexpand cobj_x0
foreign import ccall "qtc_QTreeWidget_reexpand" qtc_QTreeWidget_reexpand :: Ptr (TQTreeWidget a) -> IO ()
instance Qreexpand (QTreeWidgetSc a) (()) where
reexpand x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reexpand cobj_x0
instance Qreset (QTreeWidget ()) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset_h cobj_x0
foreign import ccall "qtc_QTreeWidget_reset_h" qtc_QTreeWidget_reset_h :: Ptr (TQTreeWidget a) -> IO ()
instance Qreset (QTreeWidgetSc a) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset_h cobj_x0
instance QrowHeight (QTreeWidget ()) ((QModelIndex t1)) where
rowHeight x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowHeight cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_rowHeight" qtc_QTreeWidget_rowHeight :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO CInt
instance QrowHeight (QTreeWidgetSc a) ((QModelIndex t1)) where
rowHeight x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowHeight cobj_x0 cobj_x1
instance QrowsAboutToBeRemoved (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved_h cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsAboutToBeRemoved_h" qtc_QTreeWidget_rowsAboutToBeRemoved_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsAboutToBeRemoved (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved_h cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QrowsInserted (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted_h cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsInserted_h" qtc_QTreeWidget_rowsInserted_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsInserted (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted_h cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QrowsRemoved (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsRemoved" qtc_QTreeWidget_rowsRemoved :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsRemoved (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QscrollContentsBy (QTreeWidget ()) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_scrollContentsBy_h" qtc_QTreeWidget_scrollContentsBy_h :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy (QTreeWidgetSc a) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
instance QscrollTo (QTreeWidget ()) ((QModelIndex t1)) where
scrollTo x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_scrollTo_h" qtc_QTreeWidget_scrollTo_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QscrollTo (QTreeWidgetSc a) ((QModelIndex t1)) where
scrollTo x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo_h cobj_x0 cobj_x1
instance QscrollTo (QTreeWidget ()) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_scrollTo1_h" qtc_QTreeWidget_scrollTo1_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo (QTreeWidgetSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QselectAll (QTreeWidget ()) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll_h cobj_x0
foreign import ccall "qtc_QTreeWidget_selectAll_h" qtc_QTreeWidget_selectAll_h :: Ptr (TQTreeWidget a) -> IO ()
instance QselectAll (QTreeWidgetSc a) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll_h cobj_x0
instance QselectionChanged (QTreeWidget ()) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_selectionChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_selectionChanged" qtc_QTreeWidget_selectionChanged :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelection t1) -> Ptr (TQItemSelection t2) -> IO ()
instance QselectionChanged (QTreeWidgetSc a) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_selectionChanged cobj_x0 cobj_x1 cobj_x2
instance QsetModel (QTreeWidget ()) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setModel_h" qtc_QTreeWidget_setModel_h :: Ptr (TQTreeWidget a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel (QTreeWidgetSc a) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel_h cobj_x0 cobj_x1
instance QsetRootIndex (QTreeWidget ()) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setRootIndex_h" qtc_QTreeWidget_setRootIndex_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex (QTreeWidgetSc a) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex_h cobj_x0 cobj_x1
instance QqsetSelection (QTreeWidget ()) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection_h cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection_h" qtc_QTreeWidget_setSelection_h :: Ptr (TQTreeWidget a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection (QTreeWidgetSc a) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection_h cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection (QTreeWidget ()) ((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_QTreeWidget_setSelection_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection_qth_h" qtc_QTreeWidget_setSelection_qth_h :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection (QTreeWidgetSc 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_QTreeWidget_setSelection_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSelectionModel (QTreeWidget ()) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setSelectionModel_h" qtc_QTreeWidget_setSelectionModel_h :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel (QTreeWidgetSc a) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel_h cobj_x0 cobj_x1
instance QsizeHintForColumn (QTreeWidget ()) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_sizeHintForColumn" qtc_QTreeWidget_sizeHintForColumn :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QsizeHintForColumn (QTreeWidgetSc a) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForColumn cobj_x0 (toCInt x1)
instance QtimerEvent (QTreeWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_timerEvent" qtc_QTreeWidget_timerEvent :: Ptr (TQTreeWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QTreeWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_timerEvent cobj_x0 cobj_x1
instance QupdateGeometries (QTreeWidget ()) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateGeometries cobj_x0
foreign import ccall "qtc_QTreeWidget_updateGeometries" qtc_QTreeWidget_updateGeometries :: Ptr (TQTreeWidget a) -> IO ()
instance QupdateGeometries (QTreeWidgetSc a) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateGeometries cobj_x0
instance QverticalOffset (QTreeWidget ()) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset_h cobj_x0
foreign import ccall "qtc_QTreeWidget_verticalOffset_h" qtc_QTreeWidget_verticalOffset_h :: Ptr (TQTreeWidget a) -> IO CInt
instance QverticalOffset (QTreeWidgetSc a) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset_h cobj_x0
instance QviewportEvent (QTreeWidget ()) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_viewportEvent_h" qtc_QTreeWidget_viewportEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent (QTreeWidgetSc a) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent_h cobj_x0 cobj_x1
instance QqvisualRect (QTreeWidget ()) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRect_h" qtc_QTreeWidget_visualRect_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect (QTreeWidgetSc a) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_h cobj_x0 cobj_x1
instance QvisualRect (QTreeWidget ()) ((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_QTreeWidget_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTreeWidget_visualRect_qth_h" qtc_QTreeWidget_visualRect_qth_h :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect (QTreeWidgetSc 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_QTreeWidget_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QvisualRegionForSelection (QTreeWidget ()) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRegionForSelection_h" qtc_QTreeWidget_visualRegionForSelection_h :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection (QTreeWidgetSc a) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection_h cobj_x0 cobj_x1
instance QcloseEditor (QTreeWidget ()) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_closeEditor" qtc_QTreeWidget_closeEditor :: Ptr (TQTreeWidget a) -> Ptr (TQWidget t1) -> CLong -> IO ()
instance QcloseEditor (QTreeWidgetSc a) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcommitData (QTreeWidget ()) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_commitData cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_commitData" qtc_QTreeWidget_commitData :: Ptr (TQTreeWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QcommitData (QTreeWidgetSc a) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_commitData cobj_x0 cobj_x1
instance QdirtyRegionOffset (QTreeWidget ()) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QTreeWidget_dirtyRegionOffset_qth" qtc_QTreeWidget_dirtyRegionOffset_qth :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QdirtyRegionOffset (QTreeWidgetSc a) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
instance QqdirtyRegionOffset (QTreeWidget ()) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dirtyRegionOffset cobj_x0
foreign import ccall "qtc_QTreeWidget_dirtyRegionOffset" qtc_QTreeWidget_dirtyRegionOffset :: Ptr (TQTreeWidget a) -> IO (Ptr (TQPoint ()))
instance QqdirtyRegionOffset (QTreeWidgetSc a) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dirtyRegionOffset cobj_x0
instance QdoAutoScroll (QTreeWidget ()) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doAutoScroll cobj_x0
foreign import ccall "qtc_QTreeWidget_doAutoScroll" qtc_QTreeWidget_doAutoScroll :: Ptr (TQTreeWidget a) -> IO ()
instance QdoAutoScroll (QTreeWidgetSc a) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doAutoScroll cobj_x0
instance QdragEnterEvent (QTreeWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragEnterEvent_h" qtc_QTreeWidget_dragEnterEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QTreeWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QTreeWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragLeaveEvent_h" qtc_QTreeWidget_dragLeaveEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QTreeWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdropIndicatorPosition (QTreeWidget ()) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dropIndicatorPosition cobj_x0
foreign import ccall "qtc_QTreeWidget_dropIndicatorPosition" qtc_QTreeWidget_dropIndicatorPosition :: Ptr (TQTreeWidget a) -> IO CLong
instance QdropIndicatorPosition (QTreeWidgetSc a) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_dropIndicatorPosition cobj_x0
instance Qedit (QTreeWidget ()) ((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_QTreeWidget_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
foreign import ccall "qtc_QTreeWidget_edit" qtc_QTreeWidget_edit :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CLong -> Ptr (TQEvent t3) -> IO CBool
instance Qedit (QTreeWidgetSc 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_QTreeWidget_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
instance QeditorDestroyed (QTreeWidget ()) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_editorDestroyed cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_editorDestroyed" qtc_QTreeWidget_editorDestroyed :: Ptr (TQTreeWidget a) -> Ptr (TQObject t1) -> IO ()
instance QeditorDestroyed (QTreeWidgetSc a) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_editorDestroyed cobj_x0 cobj_x1
instance QexecuteDelayedItemsLayout (QTreeWidget ()) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_executeDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QTreeWidget_executeDelayedItemsLayout" qtc_QTreeWidget_executeDelayedItemsLayout :: Ptr (TQTreeWidget a) -> IO ()
instance QexecuteDelayedItemsLayout (QTreeWidgetSc a) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_executeDelayedItemsLayout cobj_x0
instance QfocusInEvent (QTreeWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusInEvent_h" qtc_QTreeWidget_focusInEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextPrevChild (QTreeWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_focusNextPrevChild" qtc_QTreeWidget_focusNextPrevChild :: Ptr (TQTreeWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QTreeWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QTreeWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusOutEvent_h" qtc_QTreeWidget_focusOutEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QhorizontalScrollbarValueChanged (QTreeWidget ()) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_horizontalScrollbarValueChanged" qtc_QTreeWidget_horizontalScrollbarValueChanged :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QhorizontalScrollbarValueChanged (QTreeWidgetSc a) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QhorizontalStepsPerItem (QTreeWidget ()) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalStepsPerItem cobj_x0
foreign import ccall "qtc_QTreeWidget_horizontalStepsPerItem" qtc_QTreeWidget_horizontalStepsPerItem :: Ptr (TQTreeWidget a) -> IO CInt
instance QhorizontalStepsPerItem (QTreeWidgetSc a) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalStepsPerItem cobj_x0
instance QinputMethodEvent (QTreeWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_inputMethodEvent" qtc_QTreeWidget_inputMethodEvent :: Ptr (TQTreeWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QTreeWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QTreeWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTreeWidget_inputMethodQuery_h" qtc_QTreeWidget_inputMethodQuery_h :: Ptr (TQTreeWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QTreeWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QresizeEvent (QTreeWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_resizeEvent_h" qtc_QTreeWidget_resizeEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QTreeWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent_h cobj_x0 cobj_x1
instance QscheduleDelayedItemsLayout (QTreeWidget ()) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scheduleDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QTreeWidget_scheduleDelayedItemsLayout" qtc_QTreeWidget_scheduleDelayedItemsLayout :: Ptr (TQTreeWidget a) -> IO ()
instance QscheduleDelayedItemsLayout (QTreeWidgetSc a) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scheduleDelayedItemsLayout cobj_x0
instance QscrollDirtyRegion (QTreeWidget ()) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_scrollDirtyRegion" qtc_QTreeWidget_scrollDirtyRegion :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance QscrollDirtyRegion (QTreeWidgetSc a) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
instance QselectionCommand (QTreeWidget ()) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_selectionCommand cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_selectionCommand" qtc_QTreeWidget_selectionCommand :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO CLong
instance QselectionCommand (QTreeWidgetSc a) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_selectionCommand cobj_x0 cobj_x1
instance QselectionCommand (QTreeWidget ()) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_selectionCommand1" qtc_QTreeWidget_selectionCommand1 :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQEvent t2) -> IO CLong
instance QselectionCommand (QTreeWidgetSc a) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
instance QsetDirtyRegion (QTreeWidget ()) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setDirtyRegion cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setDirtyRegion" qtc_QTreeWidget_setDirtyRegion :: Ptr (TQTreeWidget a) -> Ptr (TQRegion t1) -> IO ()
instance QsetDirtyRegion (QTreeWidgetSc a) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setDirtyRegion cobj_x0 cobj_x1
instance QsetHorizontalStepsPerItem (QTreeWidget ()) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_setHorizontalStepsPerItem" qtc_QTreeWidget_setHorizontalStepsPerItem :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QsetHorizontalStepsPerItem (QTreeWidgetSc a) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
instance QsetState (QTreeWidget ()) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setState cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTreeWidget_setState" qtc_QTreeWidget_setState :: Ptr (TQTreeWidget a) -> CLong -> IO ()
instance QsetState (QTreeWidgetSc a) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setState cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetVerticalStepsPerItem (QTreeWidget ()) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVerticalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_setVerticalStepsPerItem" qtc_QTreeWidget_setVerticalStepsPerItem :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QsetVerticalStepsPerItem (QTreeWidgetSc a) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVerticalStepsPerItem cobj_x0 (toCInt x1)
instance QsizeHintForRow (QTreeWidget ()) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_sizeHintForRow_h" qtc_QTreeWidget_sizeHintForRow_h :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QsizeHintForRow (QTreeWidgetSc a) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow_h cobj_x0 (toCInt x1)
instance QstartAutoScroll (QTreeWidget ()) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_startAutoScroll cobj_x0
foreign import ccall "qtc_QTreeWidget_startAutoScroll" qtc_QTreeWidget_startAutoScroll :: Ptr (TQTreeWidget a) -> IO ()
instance QstartAutoScroll (QTreeWidgetSc a) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_startAutoScroll cobj_x0
instance QstartDrag (QTreeWidget ()) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QTreeWidget_startDrag" qtc_QTreeWidget_startDrag :: Ptr (TQTreeWidget a) -> CLong -> IO ()
instance QstartDrag (QTreeWidgetSc a) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
instance Qstate (QTreeWidget ()) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_state cobj_x0
foreign import ccall "qtc_QTreeWidget_state" qtc_QTreeWidget_state :: Ptr (TQTreeWidget a) -> IO CLong
instance Qstate (QTreeWidgetSc a) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_state cobj_x0
instance QstopAutoScroll (QTreeWidget ()) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_stopAutoScroll cobj_x0
foreign import ccall "qtc_QTreeWidget_stopAutoScroll" qtc_QTreeWidget_stopAutoScroll :: Ptr (TQTreeWidget a) -> IO ()
instance QstopAutoScroll (QTreeWidgetSc a) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_stopAutoScroll cobj_x0
instance QupdateEditorData (QTreeWidget ()) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateEditorData cobj_x0
foreign import ccall "qtc_QTreeWidget_updateEditorData" qtc_QTreeWidget_updateEditorData :: Ptr (TQTreeWidget a) -> IO ()
instance QupdateEditorData (QTreeWidgetSc a) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateEditorData cobj_x0
instance QupdateEditorGeometries (QTreeWidget ()) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateEditorGeometries cobj_x0
foreign import ccall "qtc_QTreeWidget_updateEditorGeometries" qtc_QTreeWidget_updateEditorGeometries :: Ptr (TQTreeWidget a) -> IO ()
instance QupdateEditorGeometries (QTreeWidgetSc a) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateEditorGeometries cobj_x0
instance QverticalScrollbarAction (QTreeWidget ()) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_verticalScrollbarAction" qtc_QTreeWidget_verticalScrollbarAction :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QverticalScrollbarAction (QTreeWidgetSc a) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalScrollbarAction cobj_x0 (toCInt x1)
instance QverticalScrollbarValueChanged (QTreeWidget ()) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_verticalScrollbarValueChanged" qtc_QTreeWidget_verticalScrollbarValueChanged :: Ptr (TQTreeWidget a) -> CInt -> IO ()
instance QverticalScrollbarValueChanged (QTreeWidgetSc a) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QverticalStepsPerItem (QTreeWidget ()) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalStepsPerItem cobj_x0
foreign import ccall "qtc_QTreeWidget_verticalStepsPerItem" qtc_QTreeWidget_verticalStepsPerItem :: Ptr (TQTreeWidget a) -> IO CInt
instance QverticalStepsPerItem (QTreeWidgetSc a) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalStepsPerItem cobj_x0
instance QviewOptions (QTreeWidget ()) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_viewOptions cobj_x0
foreign import ccall "qtc_QTreeWidget_viewOptions" qtc_QTreeWidget_viewOptions :: Ptr (TQTreeWidget a) -> IO (Ptr (TQStyleOptionViewItem ()))
instance QviewOptions (QTreeWidgetSc a) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_viewOptions cobj_x0
instance QcontextMenuEvent (QTreeWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_contextMenuEvent_h" qtc_QTreeWidget_contextMenuEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QTreeWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance QqminimumSizeHint (QTreeWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QTreeWidget_minimumSizeHint_h" qtc_QTreeWidget_minimumSizeHint_h :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QTreeWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QTreeWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_minimumSizeHint_qth_h" qtc_QTreeWidget_minimumSizeHint_qth_h :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QTreeWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetViewportMargins (QTreeWidget ()) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTreeWidget_setViewportMargins" qtc_QTreeWidget_setViewportMargins :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetViewportMargins (QTreeWidgetSc a) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QsetupViewport (QTreeWidget ()) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setupViewport cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setupViewport" qtc_QTreeWidget_setupViewport :: Ptr (TQTreeWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QsetupViewport (QTreeWidgetSc a) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setupViewport cobj_x0 cobj_x1
instance QqsizeHint (QTreeWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QTreeWidget_sizeHint_h" qtc_QTreeWidget_sizeHint_h :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QTreeWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_h cobj_x0
instance QsizeHint (QTreeWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_sizeHint_qth_h" qtc_QTreeWidget_sizeHint_qth_h :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QTreeWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent (QTreeWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_wheelEvent_h" qtc_QTreeWidget_wheelEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QTreeWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent_h cobj_x0 cobj_x1
instance QchangeEvent (QTreeWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_changeEvent_h" qtc_QTreeWidget_changeEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QTreeWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent_h cobj_x0 cobj_x1
instance QdrawFrame (QTreeWidget ()) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_drawFrame cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_drawFrame" qtc_QTreeWidget_drawFrame :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawFrame (QTreeWidgetSc a) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_drawFrame cobj_x0 cobj_x1
instance QactionEvent (QTreeWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_actionEvent_h" qtc_QTreeWidget_actionEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QTreeWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QTreeWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_addAction" qtc_QTreeWidget_addAction :: Ptr (TQTreeWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QTreeWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_addAction cobj_x0 cobj_x1
instance QcloseEvent (QTreeWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_closeEvent_h" qtc_QTreeWidget_closeEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QTreeWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent_h cobj_x0 cobj_x1
instance Qcreate (QTreeWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_create cobj_x0
foreign import ccall "qtc_QTreeWidget_create" qtc_QTreeWidget_create :: Ptr (TQTreeWidget a) -> IO ()
instance Qcreate (QTreeWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_create cobj_x0
instance Qcreate (QTreeWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_create1" qtc_QTreeWidget_create1 :: Ptr (TQTreeWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QTreeWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QTreeWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTreeWidget_create2" qtc_QTreeWidget_create2 :: Ptr (TQTreeWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QTreeWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QTreeWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QTreeWidget_create3" qtc_QTreeWidget_create3 :: Ptr (TQTreeWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QTreeWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QTreeWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy cobj_x0
foreign import ccall "qtc_QTreeWidget_destroy" qtc_QTreeWidget_destroy :: Ptr (TQTreeWidget a) -> IO ()
instance Qdestroy (QTreeWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy cobj_x0
instance Qdestroy (QTreeWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_destroy1" qtc_QTreeWidget_destroy1 :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance Qdestroy (QTreeWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QTreeWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QTreeWidget_destroy2" qtc_QTreeWidget_destroy2 :: Ptr (TQTreeWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QTreeWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QTreeWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType_h cobj_x0
foreign import ccall "qtc_QTreeWidget_devType_h" qtc_QTreeWidget_devType_h :: Ptr (TQTreeWidget a) -> IO CInt
instance QdevType (QTreeWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType_h cobj_x0
instance QenabledChange (QTreeWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_enabledChange" qtc_QTreeWidget_enabledChange :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QenabledChange (QTreeWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QTreeWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_enterEvent_h" qtc_QTreeWidget_enterEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QTreeWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QTreeWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QTreeWidget_focusNextChild" qtc_QTreeWidget_focusNextChild :: Ptr (TQTreeWidget a) -> IO CBool
instance QfocusNextChild (QTreeWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusNextChild cobj_x0
instance QfocusPreviousChild (QTreeWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QTreeWidget_focusPreviousChild" qtc_QTreeWidget_focusPreviousChild :: Ptr (TQTreeWidget a) -> IO CBool
instance QfocusPreviousChild (QTreeWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_focusPreviousChild cobj_x0
instance QfontChange (QTreeWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_fontChange" qtc_QTreeWidget_fontChange :: Ptr (TQTreeWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QTreeWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QTreeWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_heightForWidth_h" qtc_QTreeWidget_heightForWidth_h :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QheightForWidth (QTreeWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QTreeWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_hideEvent_h" qtc_QTreeWidget_hideEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QTreeWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QTreeWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyReleaseEvent_h" qtc_QTreeWidget_keyReleaseEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QTreeWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_languageChange cobj_x0
foreign import ccall "qtc_QTreeWidget_languageChange" qtc_QTreeWidget_languageChange :: Ptr (TQTreeWidget a) -> IO ()
instance QlanguageChange (QTreeWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_languageChange cobj_x0
instance QleaveEvent (QTreeWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_leaveEvent_h" qtc_QTreeWidget_leaveEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QTreeWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QTreeWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTreeWidget_metric" qtc_QTreeWidget_metric :: Ptr (TQTreeWidget a) -> CLong -> IO CInt
instance Qmetric (QTreeWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance Qmove (QTreeWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_move1" qtc_QTreeWidget_move1 :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QTreeWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QTreeWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTreeWidget_move_qth" qtc_QTreeWidget_move_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QTreeWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QTreeWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_move" qtc_QTreeWidget_move :: Ptr (TQTreeWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QTreeWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QTreeWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_moveEvent_h" qtc_QTreeWidget_moveEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QTreeWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QTreeWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QTreeWidget_paintEngine_h" qtc_QTreeWidget_paintEngine_h :: Ptr (TQTreeWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QTreeWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine_h cobj_x0
instance QpaletteChange (QTreeWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_paletteChange" qtc_QTreeWidget_paletteChange :: Ptr (TQTreeWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QTreeWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QTreeWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_repaint cobj_x0
foreign import ccall "qtc_QTreeWidget_repaint" qtc_QTreeWidget_repaint :: Ptr (TQTreeWidget a) -> IO ()
instance Qrepaint (QTreeWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_repaint cobj_x0
instance Qrepaint (QTreeWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTreeWidget_repaint2" qtc_QTreeWidget_repaint2 :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QTreeWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QTreeWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_repaint1" qtc_QTreeWidget_repaint1 :: Ptr (TQTreeWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QTreeWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QTreeWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QTreeWidget_resetInputContext" qtc_QTreeWidget_resetInputContext :: Ptr (TQTreeWidget a) -> IO ()
instance QresetInputContext (QTreeWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_resetInputContext cobj_x0
instance Qresize (QTreeWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_resize1" qtc_QTreeWidget_resize1 :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QTreeWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QTreeWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_resize" qtc_QTreeWidget_resize :: Ptr (TQTreeWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QTreeWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resize cobj_x0 cobj_x1
instance Qresize (QTreeWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QTreeWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QTreeWidget_resize_qth" qtc_QTreeWidget_resize_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QTreeWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QTreeWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QTreeWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTreeWidget_setGeometry1" qtc_QTreeWidget_setGeometry1 :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QTreeWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QTreeWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setGeometry" qtc_QTreeWidget_setGeometry :: Ptr (TQTreeWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QTreeWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QTreeWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTreeWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QTreeWidget_setGeometry_qth" qtc_QTreeWidget_setGeometry_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QTreeWidgetSc 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_QTreeWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QTreeWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_setMouseTracking" qtc_QTreeWidget_setMouseTracking :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QTreeWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QTreeWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_setVisible_h" qtc_QTreeWidget_setVisible_h :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QsetVisible (QTreeWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QTreeWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_showEvent_h" qtc_QTreeWidget_showEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QTreeWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QTreeWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_tabletEvent_h" qtc_QTreeWidget_tabletEvent_h :: Ptr (TQTreeWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QTreeWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QTreeWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QTreeWidget_updateMicroFocus" qtc_QTreeWidget_updateMicroFocus :: Ptr (TQTreeWidget a) -> IO ()
instance QupdateMicroFocus (QTreeWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_updateMicroFocus cobj_x0
instance QwindowActivationChange (QTreeWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_windowActivationChange" qtc_QTreeWidget_windowActivationChange :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QTreeWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QTreeWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_childEvent" qtc_QTreeWidget_childEvent :: Ptr (TQTreeWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QTreeWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QTreeWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_connectNotify" qtc_QTreeWidget_connectNotify :: Ptr (TQTreeWidget a) -> CWString -> IO ()
instance QconnectNotify (QTreeWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QTreeWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_customEvent" qtc_QTreeWidget_customEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QTreeWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QTreeWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_disconnectNotify" qtc_QTreeWidget_disconnectNotify :: Ptr (TQTreeWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QTreeWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QTreeWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_eventFilter_h" qtc_QTreeWidget_eventFilter_h :: Ptr (TQTreeWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QTreeWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QTreeWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_receivers" qtc_QTreeWidget_receivers :: Ptr (TQTreeWidget a) -> CWString -> IO CInt
instance Qreceivers (QTreeWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_receivers cobj_x0 cstr_x1
instance Qsender (QTreeWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sender cobj_x0
foreign import ccall "qtc_QTreeWidget_sender" qtc_QTreeWidget_sender :: Ptr (TQTreeWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QTreeWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sender cobj_x0
|
keera-studios/hsQt
|
Qtc/Gui/QTreeWidget.hs
|
bsd-2-clause
| 111,031
| 0
| 16
| 17,392
| 35,358
| 17,929
| 17,429
| -1
| -1
|
{-# LANGUAGE RecordWildCards #-}
-- | Testing AVM->Tree and Tree->Graph compilation.
module NLP.FeatureStructure.AVM.Tests where
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT(..))
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Maybe (isJust)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Test.HUnit (Assertion, (@?=))
import Test.Tasty.HUnit (testCase)
import NLP.FeatureStructure.Core
import qualified NLP.FeatureStructure.AVM as A
import qualified NLP.FeatureStructure.Graph as G
import qualified NLP.FeatureStructure.Tree as T
import qualified NLP.FeatureStructure.Unify as U
import qualified NLP.FeatureStructure.Join as J
-- import qualified NLP.FeatureStructure.Graph.Tests as GT
--------------------------------------------------------------------
-- Test tree
--------------------------------------------------------------------
-- | The actual test set.
tests :: TestTree
tests = testGroup "NLP.FeatureStructure.AVM"
[ testCase "testEmpty" testEmpty
, testCase "testCycle" testCycle
, testCase "testOther" testOther
, testCase "testFrontDup" testFrontDup
]
--------------------------------------------------------------------
-- Unit tests
--------------------------------------------------------------------
-- | Test if empty AVM is equal to (almost) empty graph.
testEmpty :: Assertion
testEmpty = onJust $ do
(g, i) <- maybeT $ fromAVM A.empty
lift $ G.equal g i h 1 @?= True
where
h = mkG [(1, mkI [])]
-- | Test a simple cyclic graph.
testCycle :: Assertion
testCycle = onJust $ do
(g, i) <- maybeT $ fromAVM a
lift $ G.equal g i h 1 @?= True
where
a = do
A.label 1
A.feat 'a' $ A.label 1
h = mkG [(1, mkI [('a', 1)])]
-- | Test a slightly more complex example.
testOther :: Assertion
testOther = onJust $ do
(g, i) <- maybeT $ fromAVM a
lift $ G.equal g i h 1 @?= True
where
a = do
A.label 1
A.feat 'a' $ do
A.label 2
A.feat 'a' $ A.label 1
A.feat 'b' $ A.label 2
h = mkG
[ (1, mkI [('a', 2)])
, (2, mkI
[('a', 1), ('b', 2)]) ]
-- | Test if there are no frontier duplicates in the compiled
-- graph. TODO: We could have a QuickCheck property for that
-- as well.
testFrontDup :: Assertion
testFrontDup = onJust $ do
(g, i) <- maybeT $ fromAVM a
lift $ G.equal g i h 1 @?= True
lift $ G.equal g i h' 1 @?= False
where
a = do
A.feat 'a' $ do
A.label 2
A.feat 'a' $ A.atom 'x'
A.feat 'b' $ A.label 2
A.feat 'b' $ A.atom 'x'
h = mkG
[ (1, mkI [('a', 2), ('b', 3)])
, (2, mkI
[('a', 3), ('b', 2)])
, (3, mkF 'x') ]
h' = mkG
[ (1, mkI [('a', 2), ('b', 3)])
, (2, mkI
[('a', 4), ('b', 2)])
, (3, mkF 'x')
, (4, mkF 'x') ]
--------------------------------------------------------------------
-- Utilities
--------------------------------------------------------------------
-- | Locally used AVM type.
type AVM = A.AVM Int Char Char
-- | Locally used graph type.
type Graph = G.Graph Int Char Char
-- | Locally used node type.
type Node = G.Node Int Char Char
mkG :: [(Int, Node)] -> Graph
mkG = G.Graph . M.fromList
mkI :: [(Char, Int)] -> Node
mkI = G.Interior . M.fromList
mkF :: Char -> Node
mkF = G.Frontier
unify :: Graph -> Int -> Graph -> Int -> Maybe (Graph, Int)
unify g i h j = case U.unify g h [(i, j)] of
Nothing -> Nothing
Just J.Res{..} -> Just (resGraph, convID $ Left i)
maybeT :: Monad m => Maybe a -> MaybeT m a
maybeT = MaybeT . return
-- | Assertion from a MaybeT computation which fails if the
-- MaybeT transformer returns Nothing.
onJust :: MaybeT IO a -> Assertion
onJust m = do
x <- runMaybeT m
case x of
Nothing -> fail "MaybeT returned Nothing"
Just _ -> return ()
-- | Convert a given AVM to a graph.
fromAVM :: AVM -> Maybe (Graph, ID)
fromAVM m = do
(i, J.Res{..}) <- T.runCon $ T.fromFN $ A.avm m
return (resGraph, convID i)
|
kawu/feature-structure
|
src/NLP/FeatureStructure/AVM/Tests.hs
|
bsd-2-clause
| 4,389
| 0
| 14
| 1,172
| 1,371
| 755
| 616
| 99
| 2
|
module QACG.CircGen.Cordic
(
cordic
,mkCosSin
,mkLog
,mkSqrt
)
where
import QACG.CircUtils.Circuit
import Control.Monad.State
import QACG.CircUtils.CircuitState
import QACG.CircGen.Add.SimpleRipple(simpleModRipple)
import QACG.CircGen.Misc(setNum)
-- K(n) = \prod_{i=0}^{n-1} 1/\sqrt{1 + 2^{-2i}}
k :: Int -> Float
k n = product [1 / sqrt (1+2**(-2*(fromIntegral i))) | i <- [0..n]]
toBin :: Int -> [Bool]
toBin 0 = []
toBin n = (mod n 2 == 1) : toBin (div n 2)
mkLog:: Int -> [String] -> Circuit
mkLog iters v = circ {gates = gates circ ++ reverse (gates circ)}
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 100]] , Circuit (LineInfo [] [] [] []) [] [])
go = do z <- getConst $ length v
setNum 1 z
sqrtOut <- cordicLog iters v z
_ <- initLines v
setOutputs $ sqrtOut
mkSqrt:: Int -> [String] -> Circuit
mkSqrt iters v = circ {gates = gates circ ++ reverse (gates circ)}
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 100]] , Circuit (LineInfo [] [] [] []) [] [])
go = do v1Init <- getConst $ length v
v2Init <- getConst $ length v
z <- getConst $ length v
c <- getConst $ length v
setNum (25*10^(length v - 3)) c
(_,v1) <- simpleModRipple c v1Init
invert c
(_,v2) <- simpleModRipple c v2Init
invert c
setNum (25*10^(length v - 3)) c
freeConst c
(sqrtOut,_) <- cordic iters v1 v2 z
_ <- initLines v
setOutputs $ sqrtOut
mkCosSin:: Int -> [String] -> Circuit
mkCosSin iters beta = circ {gates = gates circ ++ reverse (gates circ)}
where (_,(_,_,circ)) = runState go ([], ['c':show x|x<-[0::Int .. 100]] , Circuit (LineInfo [] [] [] []) [] [])
go = do v1Init <- getConst $ length beta
v2Init <- getConst $ length beta
invert v1Init
(cosOut,sinOut) <- cordic iters v1Init v2Init beta
_ <- initLines beta
setOutputs $ cosOut ++ sinOut
cordicLog :: Int -> [String] -> [String] -> CircuitState [String]
cordicLog iters xInit vInit = iteration 0 xInit vInit
where iteration :: Int -> [String] -> [String] -> CircuitState [String]
iteration n x z
| n < iters = do sign <- getSign x
zC <- copy z
cInvert sign z
c <- getConst n
(_,z') <- simpleModRipple (drop n zC ++ c) z
freeConst c
x' <- updateAng sign x n
iteration (n+1) x' z'
| otherwise = return z
getSign b = do cs <- getConst 1
cnot (last b) (head cs)
return (head cs)
updateAng s a iter = do c <- getConst $ length a
setNum (floor $ logs (fromIntegral iter)*10^length a) c
invert c
cInvert s c
(_,a') <- simpleModRipple c a
cInvert s c
invert c
setNum (floor $ logs (fromIntegral iter)*10^length a) c
freeConst c
return a'
logs n = log (2**(-n))
-- Computes sin and cos for an angle 'beta' where -pi/2 < beta < pi/2
cordic :: Int -> [String] -> [String] -> [String] -> CircuitState ([String],[String])
cordic iters v1Init v2Init beta = iteration 0 v1Init v2Init beta
where iteration :: Int -> [String] -> [String] -> [String] -> CircuitState ([String],[String])
iteration n v1 v2 ang
| n < iters = do sign <- getSign ang
v1C <- copy v1
v2C <- copy v2
cInvert sign v1C
cInvert sign v2C
invert v2C
c1 <- getConst n
c2 <- getConst n
(_,v1') <- simpleModRipple (drop n v2C ++ c1) v1
(_,v2') <- simpleModRipple (drop n v1C ++ c2) v2
freeConst c1
freeConst c2
ang' <- updateAng sign ang n
iteration (n+1) v1' v2' ang'
| otherwise = return (v1,v2)
getSign b = do cs <- getConst 1
cnot (last b) (head cs)
return (head cs)
updateAng s a iter = do c <- getConst $ length a
setNum (floor $ angles (fromIntegral iter)*10^length a) c
invert c
cInvert s c
(_,a') <- simpleModRipple c a
cInvert s c
invert c
setNum (floor $ angles (fromIntegral iter)*10^length a) c
freeConst c
return a'
angles n = atan (2**(-n))
invert :: [String] -> CircuitState ()
invert (x:xs) = do notgate x
invert xs
invert [] = return ()
cInvert :: String -> [String] -> CircuitState ()
cInvert c (x:xs) = do cnot c x
cInvert c xs
cInvert _ [] = return ()
copy :: [String] -> CircuitState [String]
copy x = do res <- getConst $ length x
applyCopy x res
return res
where applyCopy (a:as) (b:bs) = do cnot a b
applyCopy as bs
applyCopy _ _ = return ()
|
aparent/qacg
|
src/QACG/CircGen/Cordic.hs
|
bsd-3-clause
| 6,217
| 0
| 16
| 2,953
| 2,230
| 1,084
| 1,146
| 125
| 2
|
module Main where
import Criterion (bgroup,bench,whnfIO,whnf,nf)
import Criterion.Main (defaultMain)
import qualified HaskellImageProcessingBenchmark.Friday as Friday (
readPng,threshold,mean)
import qualified HaskellImageProcessingBenchmark.UnmHip as UnmHip (
readPgm,threshold,mean)
import qualified HaskellImageProcessingBenchmark.Yarr as Yarr (
readPng,force,threshold,mean)
import qualified HaskellImageProcessingBenchmark.Repa as Repa (
readPng,force,threshold,mean)
import qualified HaskellImageProcessingBenchmark.OpenCV as OpenCV (
readPng,threshold,mean)
main :: IO ()
main = do
fridayImage <- Friday.readPng "koblenz.png"
unmHipImage <- UnmHip.readPgm "koblenz.pgm"
yarrImage <- Yarr.readPng "koblenz.png"
repaImage <- Repa.readPng "koblenz.png"
openCVImage <- OpenCV.readPng "koblenz.png"
defaultMain [
bgroup "readPng" [
bench "Friday" (whnfIO (Friday.readPng "koblenz.png")),
bench "Yarr" (whnfIO (Yarr.readPng "koblenz.png")),
bench "Repa" (whnfIO (Repa.readPng "koblenz.png")),
bench "OpenCV" (whnfIO (OpenCV.readPng "koblenz.png"))],
bgroup "threshold" [
bench "Friday" (whnf Friday.threshold fridayImage),
bench "UnmHip" (nf UnmHip.threshold unmHipImage),
bench "Yarr" (whnfIO (Yarr.force (Yarr.threshold yarrImage))),
bench "Repa" (whnfIO (Repa.force (Repa.threshold repaImage))),
bench "OpenCV" (whnfIO (OpenCV.threshold openCVImage))],
bgroup "mean" [
bench "Friday" (whnf Friday.mean fridayImage),
-- too slow bench "UnmHip" (nf UnmHip.mean unmHipImage),
bench "Yarr" (whnfIO (Yarr.mean yarrImage)),
bench "Repa" (whnfIO (Repa.mean repaImage)),
bench "OpenCV" (whnfIO (OpenCV.mean openCVImage))]]
|
phischu/haskell-image-processing-benchmark
|
src/Main.hs
|
bsd-3-clause
| 1,892
| 0
| 18
| 430
| 531
| 284
| 247
| 37
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Apps.X.Client
( mainBase
, mainRepl
, mainProgrammatic
) where
import Control.Concurrent.MVar
import Control.Concurrent.Lifted (threadDelay)
import qualified Control.Concurrent.Lifted as CL
import Control.Concurrent.Chan.Unagi
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as BSC
import Data.Either ()
import qualified Data.Map as Map
import System.IO
import GHC.Int (Int64)
import Juno.Spec.Simple
import Juno.Types
import Apps.X.Parser
promptIn :: String
promptIn = "\ESC[0;31min>> \ESC[0m"
promptOut :: String
promptOut = "\ESC[0;32mout>> \ESC[0m"
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
promptRead :: IO String
promptRead = flushStr promptIn >> getLine
-- should we poll here till we get a result?
showResult :: CommandMVarMap -> RequestId -> Maybe Int64 -> IO ()
showResult cmdStatusMap' rId Nothing =
threadDelay 1000 >> do
(CommandMap _ m) <- readMVar cmdStatusMap'
case Map.lookup rId m of
Nothing -> print $ "RequestId [" ++ show rId ++ "] not found."
Just (CmdApplied (CommandResult x) _) -> putStrLn $ promptOut ++ BSC.unpack x
-- not applied yet, loop and wait
Just _ -> showResult cmdStatusMap' rId Nothing
showResult cmdStatusMap' rId pgm@(Just cnt) =
threadDelay 1000 >> do
(CommandMap _ m) <- readMVar cmdStatusMap'
case Map.lookup rId m of
Nothing -> print $ "RequestId [" ++ show rId ++ "] not found."
Just (CmdApplied (CommandResult _x) lat) -> putStrLn $ intervalOfNumerous cnt lat
-- not applied yet, loop and wait
Just _ -> showResult cmdStatusMap' rId pgm
-- -> OutChan CommandResult
runREPL :: InChan (RequestId, [CommandEntry]) -> CommandMVarMap -> IO ()
runREPL toCommands' cmdStatusMap' = do
cmd <- promptRead
case cmd of
"" -> runREPL toCommands' cmdStatusMap'
"program" -> runProgram toCommands' cmdStatusMap'
_ -> do
let cmd' = BSC.pack cmd
case readX cmd' of
Left err -> putStrLn cmd >> putStrLn err >> runREPL toCommands' cmdStatusMap'
Right _ -> do
rId <- liftIO $ setNextCmdRequestId cmdStatusMap'
writeChan toCommands' (rId, [CommandEntry cmd'])
showResult cmdStatusMap' rId Nothing
runREPL toCommands' cmdStatusMap'
runProgram :: InChan (RequestId, [CommandEntry]) -> CommandMVarMap -> IO ()
runProgram toCommands' cmdStatusMap' = runProgram' (0::Int) (0::Int)
where
runProgram' i j = do
threadDelay 15000 -- 1000000
rId <- liftIO $ setNextCmdRequestId cmdStatusMap'
writeChan toCommands' (rId, [CommandEntry entry])
showResult cmdStatusMap' rId Nothing
runProgram' (i+1) (if i `mod` 4 == 0 then j+1 else j)
where
entry = BSC.pack $ case i `mod` 4 of
0 -> "create " ++ show (j+1)
1 -> "showone " ++ show j
2 -> "adjust " ++ show j ++ " " ++ show j
_ -> "showone " ++ show j
intervalOfNumerous :: Int64 -> Int64 -> String
intervalOfNumerous cnt mics = let
interval = fromIntegral mics / 1000000
perSec = ceiling (fromIntegral cnt / interval)
in "Completed in " ++ show (interval :: Double) ++ "sec (" ++ show (perSec::Integer) ++ " per sec)"
-- | Runs a 'Raft nt String String mt'.
-- Simple fixes nt to 'HostPort' and mt to 'String'.
mainRepl :: IO ()
mainRepl = mainBase runREPL
mainProgrammatic :: IO ()
mainProgrammatic = mainBase runProgram
mainBase
:: (InChan (RequestId, [CommandEntry]) -> CommandMVarMap -> IO ())
-> IO ()
mainBase driver = do
(toCommands, fromCommands) <- newChan
-- `toResult` is unused. There seem to be API's that use/block on fromResult.
-- Either we need to kill this channel full stop or `toResult` needs to be used.
cmdStatusMap' <- initCommandMap
let -- getEntry :: (IO et)
getEntries :: IO (RequestId, [CommandEntry])
getEntries = readChan fromCommands
-- applyFn :: et -> IO rt
applyFn :: Command -> IO CommandResult
applyFn _x = return $ CommandResult "Failure"
void $ CL.fork $ runClient applyFn getEntries cmdStatusMap'
threadDelay 100000
driver toCommands cmdStatusMap'
|
haroldcarr/juno
|
src/Apps/X/Client.hs
|
bsd-3-clause
| 4,127
| 0
| 20
| 876
| 1,212
| 614
| 598
| 92
| 5
|
{-# OPTIONS -Wall -Werror #-}
module Main where
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar
longYear :: Integer -> Bool
longYear year = case toWeekDate (fromGregorian year 12 31) of
(_,53,_) -> True
_ -> False
showLongYear :: Integer -> IO ()
showLongYear year = putStrLn ((show year) ++ ": " ++ (if isLeapYear year then "L" else " ") ++ (if longYear year then "*" else " "))
main :: IO ()
main = do
mapM_ showLongYear [1901 .. 2050]
|
FranklinChen/hugs98-plus-Sep2006
|
packages/time/time/test/LongWeekYears.hs
|
bsd-3-clause
| 497
| 0
| 11
| 88
| 183
| 101
| 82
| 14
| 3
|
-- | Assorted types used in linguistics.
module Linguistics.Types where
import Data.Text (Text)
import GHC.Generics (Generic)
import Data.Serialize (Serialize)
import Data.Binary (Binary)
import Data.Aeson (FromJSON,ToJSON)
import Data.Serialize.Text ()
-- * Connectivity with @LingPy@.
--
-- <http://lingulist.de/lingpy/tutorial/formats.html>
-- | Concept
--
-- TODO ???
newtype Concept = Concept { getConcept :: Text }
deriving (Eq,Ord,Generic)
instance Binary Concept
instance Serialize Concept
instance FromJSON Concept
instance ToJSON Concept
-- |
--
-- TODO ???
newtype Counterpart = Counterpart { getCountpart :: Text }
deriving (Eq,Ord,Generic)
instance Binary Counterpart
instance Serialize Counterpart
instance FromJSON Counterpart
instance ToJSON Counterpart
-- | A word in phonetic @IPA@ notation.
newtype IPA = IPA { getIPA :: Text }
deriving (Eq,Ord,Generic)
instance Binary IPA
instance Serialize IPA
instance FromJSON IPA
instance ToJSON IPA
-- |
--
-- TODO ???
newtype Doculect = Doculect { getDoculect :: Text }
deriving (Eq,Ord,Generic)
instance Binary Doculect
instance Serialize Doculect
instance FromJSON Doculect
instance ToJSON Doculect
|
choener/LinguisticsTypes
|
Linguistics/Types.hs
|
bsd-3-clause
| 1,234
| 0
| 6
| 227
| 306
| 172
| 134
| 31
| 0
|
{-|
Module : AERN2.MP.DyadicSpec
Description : hspec tests for Dyadic
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
-}
module AERN2.MP.DyadicSpec (spec) where
-- import MixedTypesNumPrelude
import AERN2.MP.Dyadic
import Test.Hspec
spec :: Spec
spec = specDyadic
|
michalkonecny/aern2
|
aern2-mp/test/AERN2/MP/DyadicSpec.hs
|
bsd-3-clause
| 398
| 0
| 4
| 99
| 35
| 23
| 12
| 5
| 1
|
module HTaggerSpec (main, spec) where
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should work fine" $ do
True `shouldBe` False
|
KevinCotrone/htag
|
test/HTaggerSpec.hs
|
bsd-3-clause
| 204
| 0
| 13
| 49
| 74
| 39
| 35
| 9
| 1
|
{-# LANGUAGE RankNTypes #-}
-- A classic test for type inference
-- Taken from "Haskell and principal types", Section 3
-- by Faxen, in the Haskell Workshop 2003, pp88-97
module ShouldCompile where
import Data.OldList (null)
import Prelude hiding (null)
class HasEmpty a where
isEmpty :: a -> Bool
instance HasEmpty [a] where
isEmpty x = null x
instance HasEmpty (Maybe a) where
isEmpty Nothing = True
isEmpty (Just x) = False
test1 y
= (null y)
|| (let f :: forall d. d -> Bool
f x = isEmpty (y >> return x)
in f y)
test2 y
= (let f :: forall d. d -> Bool
f x = isEmpty (y >> return x)
in f y)
|| (null y)
|
jstolarek/ghc
|
testsuite/tests/typecheck/should_compile/faxen.hs
|
bsd-3-clause
| 688
| 4
| 14
| 202
| 237
| 123
| 114
| 21
| 1
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[ListSetOps]{Set-like operations on lists}
-}
{-# LANGUAGE CPP #-}
module ListSetOps (
unionLists, minusList, deleteBys,
-- Association lists
Assoc, assoc, assocMaybe, assocUsing, assocDefault, assocDefaultUsing,
-- Duplicate handling
hasNoDups, removeDups, findDupsEq,
equivClasses,
-- Indexing
getNth
) where
#include "HsVersions.h"
import GhcPrelude
import Outputable
import Util
import Data.List
import qualified Data.List.NonEmpty as NE
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Set as S
getNth :: Outputable a => [a] -> Int -> a
getNth xs n = ASSERT2( xs `lengthExceeds` n, ppr n $$ ppr xs )
xs !! n
deleteBys :: (a -> a -> Bool) -> [a] -> [a] -> [a]
-- (deleteBys eq xs ys) returns xs-ys, using the given equality function
-- Just like 'Data.List.delete' but with an equality function
deleteBys eq xs ys = foldl' (flip (deleteBy eq)) xs ys
{-
************************************************************************
* *
Treating lists as sets
Assumes the lists contain no duplicates, but are unordered
* *
************************************************************************
-}
-- | Assumes that the arguments contain no duplicates
unionLists :: (HasDebugCallStack, Outputable a, Eq a) => [a] -> [a] -> [a]
-- We special case some reasonable common patterns.
unionLists xs [] = xs
unionLists [] ys = ys
unionLists [x] ys
| isIn "unionLists" x ys = ys
| otherwise = x:ys
unionLists xs [y]
| isIn "unionLists" y xs = xs
| otherwise = y:xs
unionLists xs ys
= WARN(lengthExceeds xs 100 || lengthExceeds ys 100, ppr xs $$ ppr ys)
[x | x <- xs, isn'tIn "unionLists" x ys] ++ ys
-- | Calculate the set difference of two lists. This is
-- /O((m + n) log n)/, where we subtract a list of /n/ elements
-- from a list of /m/ elements.
--
-- Extremely short cases are handled specially:
-- When /m/ or /n/ is 0, this takes /O(1)/ time. When /m/ is 1,
-- it takes /O(n)/ time.
minusList :: Ord a => [a] -> [a] -> [a]
-- There's no point building a set to perform just one lookup, so we handle
-- extremely short lists specially. It might actually be better to use
-- an O(m*n) algorithm when m is a little longer (perhaps up to 4 or even 5).
-- The tipping point will be somewhere in the area of where /m/ and /log n/
-- become comparable, but we probably don't want to work too hard on this.
minusList [] _ = []
minusList xs@[x] ys
| x `elem` ys = []
| otherwise = xs
-- Using an empty set or a singleton would also be silly, so let's not.
minusList xs [] = xs
minusList xs [y] = filter (/= y) xs
-- When each list has at least two elements, we build a set from the
-- second argument, allowing us to filter the first argument fairly
-- efficiently.
minusList xs ys = filter (`S.notMember` yss) xs
where
yss = S.fromList ys
{-
************************************************************************
* *
\subsection[Utils-assoc]{Association lists}
* *
************************************************************************
Inefficient finite maps based on association lists and equality.
-}
-- A finite mapping based on equality and association lists
type Assoc a b = [(a,b)]
assoc :: (Eq a) => String -> Assoc a b -> a -> b
assocDefault :: (Eq a) => b -> Assoc a b -> a -> b
assocUsing :: (a -> a -> Bool) -> String -> Assoc a b -> a -> b
assocMaybe :: (Eq a) => Assoc a b -> a -> Maybe b
assocDefaultUsing :: (a -> a -> Bool) -> b -> Assoc a b -> a -> b
assocDefaultUsing _ deflt [] _ = deflt
assocDefaultUsing eq deflt ((k,v) : rest) key
| k `eq` key = v
| otherwise = assocDefaultUsing eq deflt rest key
assoc crash_msg list key = assocDefaultUsing (==) (panic ("Failed in assoc: " ++ crash_msg)) list key
assocDefault deflt list key = assocDefaultUsing (==) deflt list key
assocUsing eq crash_msg list key = assocDefaultUsing eq (panic ("Failed in assoc: " ++ crash_msg)) list key
assocMaybe alist key
= lookup alist
where
lookup [] = Nothing
lookup ((tv,ty):rest) = if key == tv then Just ty else lookup rest
{-
************************************************************************
* *
\subsection[Utils-dups]{Duplicate-handling}
* *
************************************************************************
-}
hasNoDups :: (Eq a) => [a] -> Bool
hasNoDups xs = f [] xs
where
f _ [] = True
f seen_so_far (x:xs) = if x `is_elem` seen_so_far
then False
else f (x:seen_so_far) xs
is_elem = isIn "hasNoDups"
equivClasses :: (a -> a -> Ordering) -- Comparison
-> [a]
-> [NonEmpty a]
equivClasses _ [] = []
equivClasses _ [stuff] = [stuff :| []]
equivClasses cmp items = NE.groupBy eq (sortBy cmp items)
where
eq a b = case cmp a b of { EQ -> True; _ -> False }
removeDups :: (a -> a -> Ordering) -- Comparison function
-> [a]
-> ([a], -- List with no duplicates
[NonEmpty a]) -- List of duplicate groups. One representative
-- from each group appears in the first result
removeDups _ [] = ([], [])
removeDups _ [x] = ([x],[])
removeDups cmp xs
= case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
(xs', dups) }
where
collect_dups :: [NonEmpty a] -> NonEmpty a -> ([NonEmpty a], a)
collect_dups dups_so_far (x :| []) = (dups_so_far, x)
collect_dups dups_so_far dups@(x :| _) = (dups:dups_so_far, x)
findDupsEq :: (a->a->Bool) -> [a] -> [NonEmpty a]
findDupsEq _ [] = []
findDupsEq eq (x:xs) | null eq_xs = findDupsEq eq xs
| otherwise = (x :| eq_xs) : findDupsEq eq neq_xs
where (eq_xs, neq_xs) = partition (eq x) xs
|
sdiehl/ghc
|
compiler/utils/ListSetOps.hs
|
bsd-3-clause
| 6,386
| 0
| 11
| 1,851
| 1,633
| 885
| 748
| -1
| -1
|
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, FlexibleInstances, GADTs #-}
{-# LANGUAGE MultiParamTypeClasses, NoMonomorphismRestriction, PatternGuards #-}
{-# LANGUAGE RankNTypes, TemplateHaskell, TupleSections, TypeFamilies #-}
module Puzzle (Direction(..), Board, GameState(..), toLists, fromLists, newBlock
, shift, shiftGS, blanks, randomPlace, newBoard, board, score, withIndex
) where
import Control.Applicative ((<$>))
import Control.Arrow (second)
import Control.Eff (Eff, Member)
import Control.Eff.Exception (Exc, runExc, throwExc)
import Control.Eff.Random hiding (next)
import Control.Lens (Index, IxValue, Ixed (..), makeLenses, (&), (.~))
import Control.Monad (liftM, when)
import Control.Monad.Writer (Writer, runWriter, tell)
import Data.List (transpose)
import Data.Maybe (catMaybes, isNothing)
import Data.Monoid (Sum (..))
import Data.Typeable
newtype Board =
Board { _getBoard :: [[Maybe Int]]
} deriving (Eq, Read, Ord, Typeable)
toLists :: Board -> [[Maybe Int]]
toLists = _getBoard
instance Show Board where
show = init . unlines . map (unwords . map (maybe "_" show)) . toLists
data GameState = GS { _board :: Board
, _score :: Int
} deriving (Read, Show, Eq, Ord, Typeable)
makeLenses ''GameState
newBoard :: (Member Rand r) => Eff r Board
newBoard = fromRightU <$> runExc (randomPlace =<< randomPlace (fromLists []))
fromRightU :: Either () t -> t
fromRightU (Right a) = a
fromRightU (Left ()) = error "fromRightU"
randomPlace :: (Member (Exc ()) r, Member Rand r) => Board -> Eff r Board
randomPlace b = do
let xs = blanks b
when (null xs) $ throwExc ()
idx <- fromList $ map (,1) xs
new <- newBlock
return $ b & ix idx .~ Just new
newBlock :: (Num a, Member Rand r) => Eff r a
newBlock = fromList [(2, 0.9), (4, 0.1)]
fromLists :: [[Maybe Int]] -> Board
fromLists rss =
Board $ take 4 $
map (take 4 . (++ repeat Nothing)) rss ++ repeat (replicate 4 Nothing)
data Direction = LeftD | RightD | UpD | DownD
deriving (Read, Show, Eq, Ord, Enum)
shift' :: [Maybe Int] -> Writer (Sum Int) [Maybe Int]
shift' xs = do
ans <- step $ catMaybes xs
return $ take 4 $ map Just ans ++ repeat Nothing
where
step [] = return []
step [a] = return [a]
step (a : b : bs)
| a == b = tell (Sum $ 2 * a) >> (2 * a :) <$> step bs
| otherwise = (a :) <$> step (b:bs)
shiftGS :: Direction -> GameState -> GameState
shiftGS dir (GS bd sc) =
let (bd', sc') = shift dir bd
in GS bd' (sc+sc')
shift :: Direction -> Board -> (Board, Int)
shift dir b = second getSum $ runWriter $ do
fromLists . modifier <$> mapM (liftM rev . shift' . rev) (modifier $ toLists b)
where
(rev, modifier)
| LeftD <- dir = (id, id)
| RightD <- dir = (reverse, id)
| UpD <- dir = (id, transpose)
| otherwise = (reverse, transpose)
blanks :: Board -> [(Int, Int)]
blanks =
map fst . filter (isNothing . snd) . withIndex
withIndex :: Board -> [((Int,Int), Maybe Int)]
withIndex (Board rbs) = concat $ zipWith (flip zipWith [0..] . ((,) .) . (,)) [0..] $ rbs
type instance IxValue Board = Maybe Int
type instance Index Board = (Int, Int)
instance Ixed Board where
ix (i, j) f (Board rbs) = Board <$> (ix i . ix j) f rbs
|
konn/FRP2048
|
Puzzle.hs
|
bsd-3-clause
| 3,393
| 0
| 13
| 831
| 1,431
| 770
| 661
| 78
| 3
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.ClipVolumeHint
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions and tokens from the EXT_clip_volume_hint extension, see
-- <http://www.opengl.org/registry/specs/EXT/clip_volume_hint.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.ClipVolumeHint (
-- * Tokens
gl_CLIP_VOLUME_CLIPPING_HINT
) where
import Graphics.Rendering.OpenGL.Raw.Core32
gl_CLIP_VOLUME_CLIPPING_HINT :: GLenum
gl_CLIP_VOLUME_CLIPPING_HINT = 0x80F0
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/ClipVolumeHint.hs
|
bsd-3-clause
| 789
| 0
| 4
| 95
| 48
| 38
| 10
| 5
| 1
|
tax = \n -> n * 108 `div` 100
sec h m s = h*3600 + m*60 + s
func fun n = fun(fun(fun n))
|
YoshikuniJujo/shinjukuhs
|
events/event_004/DaichiSaitoTT/func2.hs
|
bsd-3-clause
| 89
| 1
| 9
| 25
| 78
| 38
| 40
| 3
| 1
|
module ContMT (HasCont(..), MT(..), at, Z, S,
removeCont, runCont, WithCont) where
import MT
import Monad(liftM,MonadPlus(..))
import Control_Monad_Fix
import ImpUtils
newtype WithCont o m i = C { ($$) :: (i -> m o) -> m o }
removeCont :: WithCont o m i -> (i -> m o) -> m o
removeCont = ($$)
runCont :: Monad m => WithCont i m i -> m i
runCont k = k $$ return
--------------------------------------------------------------------------------
instance Monad m => Functor (WithCont o m) where
fmap = liftM
instance Monad m => Monad (WithCont o m) where
return x = C ($ x)
C m >>= f = C $ \k -> m $ \a -> f a $$ k
instance MT (WithCont o) where
lift m = C (m >>=)
instance MonadPlus m => MonadPlus (WithCont o m) where
mzero = lift mzero
C m1 `mplus` C m2 = C $ \k -> m1 k `mplus` m2 k
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
instance HasEnv m ix e => HasEnv (WithCont o m) ix e where
getEnv ix = lift (getEnv ix)
inModEnv ix f (C m) = C (inModEnv ix f . m)
instance HasState m ix s => HasState (WithCont o m) ix s where
updSt ix = lift . updSt ix
instance HasOutput m ix o => HasOutput (WithCont ans m) ix o where
outputTree ix = lift . outputTree ix
instance HasExcept m x => HasExcept (WithCont o m) x where
raise = lift . raise
handle f m = C $ \k -> handle (\x -> f x $$ k) (m $$ k)
instance Monad m => HasCont (WithCont o m) where
callcc f = C $ \k -> f (\a -> C $ \d -> k a) $$ k
--------------------------------------------------------------------------------
instance HasBaseMonad m n => HasBaseMonad (WithCont o m) n where
inBase = lift . inBase
instance HasRefs m r => HasRefs (WithCont () m) r where
newRef = lift . newRef
readRef = lift . readRef
writeRef r = lift . writeRef r
-- Magnus' fixpoint implementation
instance (MonadFix m, HasRefs m r) => MonadFix (WithCont () m) where
mfix m = C $ \k -> do x <- newRef Nothing
let xcases j n = readRef x >>= maybe n j
k' b' = xcases (const (k b')) (writeRef x (Just b'))
mfix $ \b -> do m b $$ k'
xcases return (return (error "mfix in ContMT is bottom"))
xcases k (return ())
shift :: Monad m => ((a -> WithCont o m o) -> WithCont o m o) -> WithCont o m a
shift f = C (\k -> runCont $ f (\a -> C (\k' -> k' =<< k a)))
reset :: Monad m => WithCont o m o -> WithCont o m o
reset m = C (\k -> k =<< runCont m)
test1 :: WithCont String IO String
test1 = do x <- reset $ do y <- shift (\f -> do z <- f "100"
f z)
return ("10 + " ++ y)
inBase (print "hello")
return $ "1 + " ++ x
{-
test2 = liftM ("1 + " ++) $ reset $ liftM ("10 + " ++) $ shift (\f -> return "100")
test3 = liftM ("1 + " ++) $ reset $ liftM ("10 + " ++) $ shift $ \f -> liftM2 (\x y -> x ++ " + " ++ y) (f "100") (f "1000")
-}
|
forste/haReFork
|
tools/base/lib/Monads/ContMT.hs
|
bsd-3-clause
| 3,289
| 98
| 14
| 1,091
| 1,200
| 631
| 569
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
import qualified System.Directory as Dir
import qualified Text.Printf
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Network.HTTP.Types as HTTPTypes
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
main :: IO ()
main = do
pwd <- Dir.getCurrentDirectory
print "Serving your current directory on port: 8080 - Be Safe!"
Warp.run port staticServe
where
port = 8080
{- Doesn't list drectories or do anything fancy
-
- Maybe do MIME types later -}
staticServe :: Wai.Application
staticServe req = do
return $ Wai.responseLBS (HTTPTypes.status200) []
$ B.pack "Hey"
|
strangemonad/quickserve
|
Main.hs
|
bsd-3-clause
| 705
| 0
| 11
| 146
| 146
| 85
| 61
| 17
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Snap.Snaplet.Internal.RST where
import Control.Applicative (Alternative (..),
Applicative (..))
import Control.Monad
import Control.Monad.Base (MonadBase (..))
import qualified Control.Monad.Fail as Fail
import Control.Monad.Reader (MonadReader (..))
import Control.Monad.State.Class (MonadState (..))
import Control.Monad.Trans (MonadIO (..), MonadTrans (..))
import Control.Monad.Trans.Control (ComposeSt, MonadBaseControl (..),
MonadTransControl (..),
defaultLiftBaseWith,
defaultRestoreM)
import Snap.Core (MonadSnap (..))
------------------------------------------------------------------------------
-- like RWST, but no writer to bog things down. Also assured strict, inlined
-- monad bind, etc
newtype RST r s m a = RST { runRST :: r -> s -> m (a, s) }
evalRST :: Monad m => RST r s m a -> r -> s -> m a
evalRST m r s = do
(a,_) <- runRST m r s
return a
{-# INLINE evalRST #-}
execRST :: Monad m => RST r s m a -> r -> s -> m s
execRST m r s = do
(_,!s') <- runRST m r s
return s'
{-# INLINE execRST #-}
withRST :: Monad m => (r' -> r) -> RST r s m a -> RST r' s m a
withRST f m = RST $ \r' s -> runRST m (f r') s
{-# INLINE withRST #-}
instance (Monad m) => MonadReader r (RST r s m) where
ask = RST $ \r s -> return (r,s)
local f m = RST $ \r s -> runRST m (f r) s
instance (Functor m) => Functor (RST r s m) where
fmap f m = RST $ \r s -> fmap (\(a,s') -> (f a, s')) $ runRST m r s
instance (Functor m, Monad m) => Applicative (RST r s m) where
pure = return
(<*>) = ap
instance (Functor m, MonadPlus m) => Alternative (RST r s m) where
empty = mzero
(<|>) = mplus
instance (Monad m) => MonadState s (RST r s m) where
get = RST $ \_ s -> return (s,s)
put x = RST $ \_ _ -> return ((),x)
mapRST :: (m (a, s) -> n (b, s)) -> RST r s m a -> RST r s n b
mapRST f m = RST $ \r s -> f (runRST m r s)
instance (MonadSnap m) => MonadSnap (RST r s m) where
liftSnap s = lift $ liftSnap s
rwsBind :: Monad m =>
RST r s m a
-> (a -> RST r s m b)
-> RST r s m b
rwsBind m f = RST go
where
go r !s = do
(a, !s') <- runRST m r s
runRST (f a) r s'
{-# INLINE rwsBind #-}
instance (Monad m) => Monad (RST r s m) where
return a = RST $ \_ s -> return (a, s)
(>>=) = rwsBind
#if !MIN_VERSION_base(4,13,0)
fail msg = RST $ \_ _ -> fail msg
#endif
instance Fail.MonadFail m => Fail.MonadFail (RST r s m) where
fail msg = RST $ \_ _ -> Fail.fail msg
instance (MonadPlus m) => MonadPlus (RST r s m) where
mzero = RST $ \_ _ -> mzero
m `mplus` n = RST $ \r s -> runRST m r s `mplus` runRST n r s
instance (MonadIO m) => MonadIO (RST r s m) where
liftIO = lift . liftIO
instance MonadTrans (RST r s) where
lift m = RST $ \_ s -> do
a <- m
return $ s `seq` (a, s)
instance MonadBase b m => MonadBase b (RST r s m) where
liftBase = lift . liftBase
instance MonadBaseControl b m => MonadBaseControl b (RST r s m) where
type StM (RST r s m) a = ComposeSt (RST r s) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
{-# INLINE liftBaseWith #-}
{-# INLINE restoreM #-}
instance MonadTransControl (RST r s) where
type StT (RST r s) a = (a, s)
liftWith f = RST $ \r s -> do
res <- f $ \(RST g) -> g r s
return (res, s)
restoreT k = RST $ \_ _ -> k
{-# INLINE liftWith #-}
{-# INLINE restoreT #-}
|
snapframework/snap
|
src/Snap/Snaplet/Internal/RST.hs
|
bsd-3-clause
| 3,977
| 0
| 14
| 1,297
| 1,585
| 850
| 735
| 91
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : FRP.UISF.Render.GLUT
-- Copyright : (c) Daniel Winograd-Cort 2015
-- License : see the LICENSE file in the distribution
--
-- Maintainer : dwc@cs.yale.edu
-- Stability : experimental
module FRP.UISF.Render.GLUT (
-- $glut
Window,
WindowData (..),
openWindow,
closeWindow,
-- * Rendering Graphics in OpenGL
renderGraphicInOpenGL,
glutKeyToKey
) where
import Graphics.UI.GLUT hiding (Key(..), SpecialKey(..), MouseButton(..), vertex, Rect)
import qualified Graphics.UI.GLUT as GLUT
import qualified Graphics.Rendering.OpenGL as GL
import Graphics.Rendering.OpenGL (($=), GLfloat)
import Control.Concurrent
import Control.Concurrent.MVar
import Control.Concurrent.STM.TChan
import Control.Exception (catch,IOException)
import Control.Monad.STM (atomically)
import Control.Monad (when)
import Data.IORef
import Data.List (unfoldr)
import FRP.UISF.UITypes
import FRP.UISF.Graphics
import FRP.UISF.Graphics.Graphic (Graphic(..))
import FRP.UISF.Graphics.Text (uitextLines)
{- $glut
This module provides the functions for UISF's direct interface with
GLUT and the GUI window itself. The main function for this is
'openWindow', and once a window is open, almost all communication is
handled through the returned 'WindowData' object. The one exception
to this is that one can externally close the window,
terminating the GUI altogether (although this requires the window
object, which is found in the WindowData).
Note that the values in WindowData are all IO actions. Thus, to get
the "current" value of the window's dimensions, one should run the
'windowDim' action "now".
Note also that the 'Window' type is being re-exported here as it is
used in the 'WindowData' type.
-}
-------------------
-- Window Functions
-------------------
-- | The WindowData object is used for communication between the
-- logic (UISF) and the window (GLUT).
data WindowData = WindowData {
setGraphics :: (Graphic, DirtyBit) -> IO (),
-- ^ This action allows a caller to set the current Graphic to display
-- along with a 'DirtyBit' indicating if the Graphic needs to be
-- redrawn.
getWindow :: IO (Maybe Window),
-- ^ This action retrieves the active window. For now, this is used
-- both to check if the GUI is still running (a result of Nothing
-- indicates that it is not) and to externally close the window.
-- Note that if GLUT closes the window (e.g. the user clicks the
-- close button), this reference will be updated to Nothing to
-- prevent double closure.
getWindowDim :: IO Dimension,
-- ^ This action retrieves the window's current dimensions. There
-- is no way to set this value outside of the initial dimension
-- provided by openWindow (perhaps a future feature).
getNextEvent :: IO UIEvent,
-- ^ This action retrieves the next keyboard/mouse event to be
-- processed. In the case that there is no new event, NoUIEvent
-- is provided.
peekNextEvent :: IO UIEvent,
-- ^ This action peeks at the next keyboard/mouse event to be
-- processed. In the case that there is no new event, NoUIEvent
-- is provided. This was added for a potential performance boost.
getElapsedGUITime :: IO Double
-- ^ This action retrieves the number of real time seconds that have
-- elapsed since the GUI began.
}
-- | This function creates the GUI window. It takes as arguments
-- a default background color, a title for the window, and the initial
-- dimensions for the window; it produces a WindowData object to use
-- as communication to the window.
--
-- Note that the main GLUT loop is run in a separate OS thread produced
-- by forkOS.
openWindow :: RGB -> String -> Dimension -> IO WindowData
openWindow rgb title (x,y) = do
gRef <- newIORef (nullGraphic, False)
wRef <- newIORef Nothing
wdRef <- newIORef (x,y)
eChan <- atomically newTChan
continue <- newEmptyMVar
let w = WindowData (writeIORef gRef) (readIORef wRef)
(readIORef wdRef) (nextEvent tryReadTChan eChan)
(nextEvent tryPeekTChan eChan) guiTime
-- REMARK: forkIO seems to work fine, but if GLUT starts misbehaving,
-- this may need to change to forkOS.
forkIO (f gRef wRef wdRef eChan continue)
takeMVar continue
return w
where
nextEvent r c = do
me <- atomically $ r c
case me of
Nothing -> return NoUIEvent
Just e -> return e
f gRef wRef wdRef eChan continue = do
-- Initialize and create the window.
(_progName, otherArgs) <- getArgsAndInitialize
initialDisplayMode $= [DoubleBuffered]
w <- createWindow title
windowSize $= Size (fromIntegral x) (fromIntegral y)
-- Update the WindowData Window reference to point to this new window.
writeIORef wRef (Just w)
-- We want the program to be able to continue when the window closes.
catch (actionOnWindowClose $= ContinueExecution)
(const (return ())::IOException->IO())
-- Set the default background color.
setBackgroundColor rgb
-- Set up the various call back functions.
displayCallback $= displayCB gRef
idleCallback $= Just (idleCB gRef)
reshapeCallback $= Just (reshapeCB wdRef)
keyboardMouseCallback $= Just (keyboardMouseCB eChan)
motionCallback $= Just (motionCB eChan)
passiveMotionCallback $= Just (motionCB eChan)
catch (closeCallback $= Just (closeCB wRef))
(const (return ())::IOException->IO())
-- These 4 settings are pulled from elsewhere.
-- They're probably good?
lineSmooth $= Enabled
blend $= Enabled
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
lineWidth $= 1.5
-- Indicate to the main thread that the window is good to go.
putMVar continue ()
-- Begin the main loop.
mainLoop
-- | When provided with an active window, this function will close
-- the window.
closeWindow :: Window -> IO ()
closeWindow = destroyWindow
-- | Set the default background color for the GUI window.
setBackgroundColor :: RGB -> IO ()
setBackgroundColor rgb = clearColor $= Color4 r g b 0
where (r',g',b') = extractRGB rgb
r = fromIntegral r' / 255
g = fromIntegral g' / 255
b = fromIntegral b' / 255
-- | The callback to update the display.
displayCB :: IORef (Graphic, DirtyBit) -> DisplayCallback
displayCB ref = do
(g, _) <- readIORef ref
loadIdentity
clear [ColorBuffer, StencilBuffer]
(Size x y) <- get windowSize
renderGraphicInOpenGL (fromIntegral x, fromIntegral y) g
swapBuffers
postRedisplay Nothing
-- | When the GUI is idle, we should check if the dirty bit is set.
-- If so, we signal a redraw of the display.
idleCB :: IORef (Graphic, DirtyBit) -> IdleCallback
idleCB ref = do
db <- atomicModifyIORef ref (\(g,db) -> ((g,False),db))
when db $ postRedisplay Nothing
-- | When the window is resized, we perform this mess to make sure
-- everything is drawn properly. This model assumes no stretching
-- and instead forces the user to deal with exact pixel sizes.
reshapeCB :: IORef Dimension -> ReshapeCallback
reshapeCB wdref size@(Size w h) = do
writeIORef wdref (fromIntegral w, fromIntegral h)
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 (realToFrac w) (realToFrac h) 0
matrixMode $= Modelview 0
loadIdentity
postRedisplay Nothing
-- | When a keyboard or mouse event comes in, send it to the 'WindowData'
-- object for external processing. Also, update the global keyState so
-- that 'isKeyPressed' and the has***Modifier functions work as expected.
keyboardMouseCB :: TChan UIEvent -> KeyboardMouseCallback
keyboardMouseCB chan key d modifiers (Position x y) = do
let k = glutKeyToKey key
down = (d == Down)
p = (fromIntegral x, fromIntegral y)
mods <- updateKeyState k down
case k of
(Char c) ->
atomically $ writeTChan chan Key{ char = c, modifiers = mods, isDown = down}
(SpecialKey sk) ->
atomically $ writeTChan chan SKey{ skey = sk, modifiers = mods, isDown = down}
(MouseButton mb) ->
atomically $ writeTChan chan Button{ pt = p, mbutton = mb, isDown = down}
-- | When the mouse moves at all, add an event to the 'WindowData' for
-- external processing.
motionCB :: TChan UIEvent -> MotionCallback
motionCB chan (Position x y) =
atomically $ writeTChan chan MouseMove{ pt = (fromIntegral x, fromIntegral y)}
-- | When the window closes, update the window stored in the 'WindowData'.
closeCB :: IORef (Maybe Window) -> CloseCallback
closeCB ref = writeIORef ref Nothing
-- | Converts the GUI's elapsed time from GLUT's integral millisecond
-- standard into floating point seconds.
guiTime :: IO Double
guiTime = do
mills <- get elapsedTime
return $ fromIntegral mills / 1000
------------------------------------------------------------
-- Rendering Graphics in OpenGL
------------------------------------------------------------
-- | This function takes the current dimensions of the window
-- (necessary for the bounding operation 'boundGraphic') and a Graphic
-- and produces the OpenGL IO action that actually performs the
-- rendering. Two notes about it:
--
-- - Currently, it is using 'Graphics.UI.GLUT.Fixed8By13' for
-- rendering text.
--
-- - I have had some trouble with nesting uses of PreservingMatrix
-- and scissoring, so bounded graphics (and perhaps other graphic
-- transformations in general) may be a little buggy.
renderGraphicInOpenGL :: Dimension -> Graphic -> IO ()
renderGraphicInOpenGL _ NoGraphic = return ()
renderGraphicInOpenGL s (GColor rgb graphic) = (GL.color color >> renderGraphicInOpenGL s graphic) where
(r,g,b) = extractRGB rgb
color = GL.Color3 (c2f r) (c2f g) (c2f b) :: GL.Color3 GLfloat
c2f i = fromIntegral i / 255
renderGraphicInOpenGL _ (GText (x,y) uistr) =
let tlines = zip (uitextLines uistr) [0..]
drawLine (s,i) = do
-- We need to zipWith like this to get the String x-offsets.
let ss = unfoldr buildList (0,unwrapUIT s)
buildList (_,[]) = Nothing
buildList (x,(c,f,str):rest) = Just ((x,c,f,str), (x+textWidth' f str, rest))
th = textHeight s
yoff = (i * th) + (th `div` 2) + 3
mapM_ (drawStr yoff) ss
drawStr yoff (xoff, c, f, str) = GL.preservingMatrix $ do
case c of
Nothing -> return ()
Just rgb -> GL.color color where
(r,g,b) = extractRGB rgb
color = GL.Color3 (c2f r) (c2f g) (c2f b) :: GL.Color3 GLfloat
c2f i = fromIntegral i / 255
-- This code is used for Bitmap fonts (raster offset values may need to be adjusted)
GL.currentRasterPosition $= GLUT.Vertex4
(fromIntegral $ x + xoff)
(fromIntegral $ y + yoff) 0 1
GLUT.renderString f str
-- This code is used for Stroke fonts (scale and translate values may need to be adjusted)
-- GL.translate (vector (x, y+16*(i+1)))
-- GL.scale 0.12 (-0.12) (1::GLfloat)
-- GLUT.renderString GLUT.MonoRoman s
in mapM_ drawLine tlines
renderGraphicInOpenGL _ (GPolyLine ps) =
GL.renderPrimitive GL.LineStrip (mapM_ vertex ps)
renderGraphicInOpenGL _ (GPolygon ps) =
GL.renderPrimitive GL.Polygon (mapM_ vertex ps)
renderGraphicInOpenGL _ (GEllipse rect) = GL.preservingMatrix $ do
let ((x, y), (width, height)) = normaliseRect rect
r@(r1,r2) = (width / 2, height / 2)
GL.translate $ vectorR (x + r1, y + r2) --r
GL.renderPrimitive GL.Polygon $ mapM_ vertexR
[ (r1 * cos i, r2 * sin i) | i <- segment 0 (2 * pi) (6 / (r1 + r2)) ]
renderGraphicInOpenGL _ (GArc rect start extent) = GL.preservingMatrix $ do
let ((x, y), (width, height)) = normaliseRect rect
r@(r1, r2) = (width / 2, height / 2)
GL.translate $ vectorR (x + r1, y + r2)
GL.renderPrimitive GL.LineStrip $ mapM_ vertexR
[ (r1 * cos i, r2 * sin i) | i <- segment (-(start + extent) * pi / 180)
(-start * pi / 180) (6 / (r1 + r2)) ]
renderGraphicInOpenGL _ (GBezier []) = return ()
renderGraphicInOpenGL s (GBezier ps) = renderGraphicInOpenGL s (GPolyLine ps') where
ps' = map (bezier ps) (segment 0 1 dt)
dt = 1 / (lineLength ps / 8)
lineLength :: [Point] -> Double
lineLength ((x1,y1):(x2,y2):ps') =
let dx = fromIntegral $ x2 - x1
dy = fromIntegral $ y2 - y1
in sqrt (dx * dx + dy * dy) + lineLength ((x2,y2):ps')
lineLength _ = 0
bezier :: [Point] -> Double -> Point
bezier [(x1,y1)] _t = (x1, y1)
bezier [(x1,y1),(x2,y2)] t = (x1 + round (fromIntegral (x2 - x1) * t),
y1 + round (fromIntegral (y2 - y1) * t))
bezier ps t = bezier (map (\ (p, q) -> bezier [p,q] t) (zip ps (tail ps))) t
renderGraphicInOpenGL s (GTranslate (x,y) g) =
GL.translate (vector (x,y)) >> renderGraphicInOpenGL s g >> GL.translate (vector (0-x,0-y))
--renderGraphicInOpenGL (GTranslate p g) =
-- GL.preservingMatrix $ GL.translate (vector p) >> renderGraphicInOpenGL g
renderGraphicInOpenGL s@(_,windowY) (GBounded ((x,y), (w,h)) g) = do
let [x', y', w', h'] = map fromIntegral [x, windowY-y-h, w, h]
oldScissor <- GL.get GL.scissor
let ((x'',y''),(w'',h'')) = maybe ((x',y'),(w',h'))
(\(GL.Position a b, GL.Size c d) -> intersect ((x',y'),(w',h')) ((a,b),(c,d))) oldScissor
-- FIXME: This intersection of scissors may not be right, but I'm not sure what's better
GL.scissor $= Just (GL.Position x'' y'', GL.Size w'' h'')
renderGraphicInOpenGL s g
GL.scissor $= oldScissor
where
intersect ((x,y),(w,h)) ((x',y'),(w',h')) = ((x'',y''),(w'',h'')) where
x'' = min x x'
y'' = min y y'
w'' = max 0 $ (min (x+w) (x'+w')) - x''
h'' = max 0 $ (min (y+h) (y'+h')) - y''
renderGraphicInOpenGL s (GRotate p a' g) =
GL.preservingMatrix $ GL.rotate a (vector p) >> renderGraphicInOpenGL s g
-- GL.rotate a (vector p) >> renderGraphicInOpenGL g >> GL.rotate (0-a) (vector p)
where a = realToFrac a'
renderGraphicInOpenGL s (GScale x' y' g) =
GL.preservingMatrix $ GL.scale x y (1::GLfloat) >> renderGraphicInOpenGL s g
-- GL.scale x y (1::GLfloat) >> renderGraphicInOpenGL g >> GL.scale (1/x) (1/y) (1::GLfloat)
where x = realToFrac x'
y = realToFrac y'
renderGraphicInOpenGL s (OverGraphic over base) =
renderGraphicInOpenGL s base >> renderGraphicInOpenGL s over
------------------------------------------------------------
-- Helper functions
------------------------------------------------------------
normaliseRect :: Rect -> ((Double, Double),(Double, Double))
normaliseRect ((x, y), (w, h)) = ((fromIntegral x', fromIntegral y'), (fromIntegral w', fromIntegral h'))
where (x',w') = if w < 0 then (x+w, 0-w) else (x, w)
(y',h') = if h < 0 then (y+h, 0-h) else (y, h)
segment :: (Num t, Ord t) => t -> t -> t -> [t]
segment start stop step = ts start
where ts i = if i >= stop then [stop] else i : ts (i + step)
vertex :: Point -> IO ()
vertex (x,y) = GL.vertex $ GL.Vertex3 (fromIntegral x) (fromIntegral y) (0::GLfloat)
vertexR :: (Double,Double) -> IO ()
vertexR (x,y) = GL.vertex $ GL.Vertex3 (realToFrac x) (realToFrac y) (0::GLfloat)
vector :: (Int, Int) -> GL.Vector3 GLfloat
vector (x,y) = GL.Vector3 (fromIntegral x) (fromIntegral y) 0
vectorR :: (Double,Double) -> GL.Vector3 GLfloat
vectorR (x,y) = GL.Vector3 (realToFrac x) (realToFrac y) 0
------------------------------------------------------------
-- Key support
------------------------------------------------------------
-- | Convert GLUT's key codes to UISF's internal ones.
glutKeyToKey :: GLUT.Key -> Key
glutKeyToKey key
= case key of
GLUT.Char '\13' -> SpecialKey KeyEnter
GLUT.Char '\9' -> SpecialKey KeyTab
GLUT.Char '\ESC' -> SpecialKey KeyEsc
GLUT.Char '\DEL' -> SpecialKey KeyDelete
GLUT.Char '\BS' -> SpecialKey KeyBackspace
GLUT.Char c -> Char c
GLUT.SpecialKey GLUT.KeyF1 -> SpecialKey KeyF1
GLUT.SpecialKey GLUT.KeyF2 -> SpecialKey KeyF2
GLUT.SpecialKey GLUT.KeyF3 -> SpecialKey KeyF3
GLUT.SpecialKey GLUT.KeyF4 -> SpecialKey KeyF4
GLUT.SpecialKey GLUT.KeyF5 -> SpecialKey KeyF5
GLUT.SpecialKey GLUT.KeyF6 -> SpecialKey KeyF6
GLUT.SpecialKey GLUT.KeyF7 -> SpecialKey KeyF7
GLUT.SpecialKey GLUT.KeyF8 -> SpecialKey KeyF8
GLUT.SpecialKey GLUT.KeyF9 -> SpecialKey KeyF9
GLUT.SpecialKey GLUT.KeyF10 -> SpecialKey KeyF10
GLUT.SpecialKey GLUT.KeyF11 -> SpecialKey KeyF11
GLUT.SpecialKey GLUT.KeyF12 -> SpecialKey KeyF12
GLUT.SpecialKey GLUT.KeyLeft -> SpecialKey KeyLeft
GLUT.SpecialKey GLUT.KeyUp -> SpecialKey KeyUp
GLUT.SpecialKey GLUT.KeyRight -> SpecialKey KeyRight
GLUT.SpecialKey GLUT.KeyDown -> SpecialKey KeyDown
GLUT.SpecialKey GLUT.KeyPageUp -> SpecialKey KeyPageUp
GLUT.SpecialKey GLUT.KeyPageDown -> SpecialKey KeyPageDown
GLUT.SpecialKey GLUT.KeyHome -> SpecialKey KeyHome
GLUT.SpecialKey GLUT.KeyEnd -> SpecialKey KeyEnd
GLUT.SpecialKey GLUT.KeyInsert -> SpecialKey KeyInsert
GLUT.SpecialKey GLUT.KeyNumLock -> SpecialKey KeyNumLock
GLUT.SpecialKey GLUT.KeyBegin -> SpecialKey KeyBegin
GLUT.SpecialKey GLUT.KeyDelete -> SpecialKey KeyDelete
GLUT.SpecialKey (GLUT.KeyUnknown i) -> SpecialKey (KeyUnknown i)
GLUT.SpecialKey GLUT.KeyShiftL -> SpecialKey KeyShiftL
GLUT.SpecialKey GLUT.KeyShiftR -> SpecialKey KeyShiftR
GLUT.SpecialKey GLUT.KeyCtrlL -> SpecialKey KeyCtrlL
GLUT.SpecialKey GLUT.KeyCtrlR -> SpecialKey KeyCtrlR
GLUT.SpecialKey GLUT.KeyAltL -> SpecialKey KeyAltL
GLUT.SpecialKey GLUT.KeyAltR -> SpecialKey KeyAltR
GLUT.MouseButton GLUT.LeftButton -> MouseButton LeftButton
GLUT.MouseButton GLUT.MiddleButton -> MouseButton MiddleButton
GLUT.MouseButton GLUT.RightButton -> MouseButton RightButton
GLUT.MouseButton GLUT.WheelUp -> MouseButton WheelUp
GLUT.MouseButton GLUT.WheelDown -> MouseButton WheelDown
GLUT.MouseButton (GLUT.AdditionalButton i) -> MouseButton (AdditionalButton i)
|
dwincort/UISF
|
FRP/UISF/Render/GLUT.hs
|
bsd-3-clause
| 18,956
| 0
| 19
| 4,627
| 5,038
| 2,627
| 2,411
| 268
| 43
|
{-|
Module : Idris.TypeSearch
Description : A Hoogle for Idris.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE ScopedTypeVariables #-}
module Idris.TypeSearch (
searchByType
, searchPred
, defaultScoreFunction
) where
import Control.Applicative (Applicative (..), (<$>), (<*>), (<|>))
import Control.Arrow (first, second, (&&&), (***))
import Control.Monad (when, guard)
import Data.List (find, partition, (\\))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (catMaybes, fromMaybe, isJust, maybeToList, mapMaybe)
import Data.Monoid (Monoid (mempty, mappend))
import Data.Ord (comparing)
import qualified Data.PriorityQueue.FingerTree as Q
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Text as T (pack, isPrefixOf)
import Data.Traversable (traverse)
import Idris.AbsSyntax (addUsingConstraints, addImpl, getIState, putIState, implicit, logLvl)
import Idris.AbsSyntaxTree (interface_implementations, InterfaceInfo, defaultSyntax, eqTy, Idris
, IState (idris_interfaces, idris_docstrings, tt_ctxt, idris_outputmode),
implicitAllowed, OutputMode(..), PTerm, toplevel)
import Idris.Core.Evaluate (Context (definitions), Def (Function, TyDecl, CaseOp), normaliseC)
import Idris.Core.TT hiding (score)
import Idris.Core.Unify (match_unify)
import Idris.Delaborate (delabTy)
import Idris.Docstrings (noDocs, overview)
import Idris.Elab.Type (elabType)
import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderError, iRenderResult, prettyDocumentedIst)
import Idris.IBC
import Prelude hiding (pred)
import Util.Pretty (text, char, vsep, (<>), Doc, annotate)
searchByType :: [String] -> PTerm -> Idris ()
searchByType pkgs pterm = do
i <- getIState -- save original
when (not (null pkgs)) $
iputStrLn $ "Searching packages: " ++ showSep ", " pkgs
mapM_ loadPkgIndex pkgs
pterm' <- addUsingConstraints syn emptyFC pterm
pterm'' <- implicit toplevel syn name pterm'
let pterm''' = addImpl [] i pterm''
ty <- elabType toplevel syn (fst noDocs) (snd noDocs) emptyFC [] name NoFC pterm'
let names = searchUsing searchPred i ty
let names' = take numLimit names
let docs =
[ let docInfo = (n, delabTy i n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings i))) in
displayScore theScore <> char ' ' <> prettyDocumentedIst i docInfo
| (n, theScore) <- names']
if (not (null docs))
then case idris_outputmode i of
RawOutput _ -> do mapM_ iRenderOutput docs
iPrintResult ""
IdeMode _ _ -> iRenderResult (vsep docs)
else iRenderError $ text "No results found"
putIState i -- don't actually make any changes
where
numLimit = 50
syn = defaultSyntax { implicitAllowed = True } -- syntax
name = sMN 0 "searchType" -- name
-- | Conduct a type-directed search using a given match predicate
searchUsing :: (IState -> Type -> [(Name, Type)] -> [(Name, a)])
-> IState -> Type -> [(Name, a)]
searchUsing pred istate ty = pred istate nty . concat . M.elems $
M.mapWithKey (\key -> M.toAscList . M.mapMaybe (f key)) (definitions ctxt)
where
nty = normaliseC ctxt [] ty
ctxt = tt_ctxt istate
f k x = do
guard $ not (special k)
type2 <- typeFromDef x
return $ normaliseC ctxt [] type2
special :: Name -> Bool
special (NS n _) = special n
special (SN _) = True
special (UN n) = T.pack "default#" `T.isPrefixOf` n
|| n `elem` map T.pack ["believe_me", "really_believe_me"]
special _ = False
-- | Our default search predicate.
searchPred :: IState -> Type -> [(Name, Type)] -> [(Name, Score)]
searchPred istate ty1 = matcher where
maxScore = 100
matcher = matchTypesBulk istate maxScore ty1
typeFromDef :: (Def, i, b, c, d) -> Maybe Type
typeFromDef (def, _, _, _, _) = get def where
get :: Def -> Maybe Type
get (Function ty _) = Just ty
get (TyDecl _ ty) = Just ty
-- get (Operator ty _ _) = Just ty
get (CaseOp _ ty _ _ _ _) = Just ty
get _ = Nothing
-- Replace all occurences of `Delayed s t` with `t` in a type
unLazy :: Type -> Type
unLazy typ = case typ of
App _ (App _ (P _ lazy _) _) ty | lazy == sUN "Delayed" -> unLazy ty
Bind name binder ty -> Bind name (fmap unLazy binder) (unLazy ty)
App s t1 t2 -> App s (unLazy t1) (unLazy t2)
Proj ty i -> Proj (unLazy ty) i
_ -> typ
-- | reverse the edges for a directed acyclic graph
reverseDag :: Ord k => [((k, a), Set k)] -> [((k, a), Set k)]
reverseDag xs = map f xs where
f ((k, v), _) = ((k, v), S.fromList . map (fst . fst) $ filter (S.member k . snd) xs)
-- run vToP first!
-- | Compute a directed acyclic graph corresponding to the
-- arguments of a function.
-- returns [(the name and type of the bound variable
-- the names in the type of the bound variable)]
computeDagP :: Ord n
=> (TT n -> Bool) -- ^ filter to remove some arguments
-> TT n
-> ([((n, TT n), Set n)], [(n, TT n)], TT n)
computeDagP removePred t = (reverse (map f arguments), reverse theRemovedArgs , retTy) where
f (n, ty) = ((n, ty), M.keysSet (usedVars ty))
(arguments, theRemovedArgs, retTy) = go [] [] t
-- NOTE : args are in reverse order
go args removedArgs (Bind n (Pi _ ty _) sc) = let arg = (n, ty) in
if removePred ty
then go args (arg : removedArgs) sc
else go (arg : args) removedArgs sc
go args removedArgs sc = (args, removedArgs, sc)
-- | Collect the names and types of all the free variables
-- The Boolean indicates those variables which are determined due to injectivity
-- I have not given nearly enough thought to know whether this is correct
usedVars :: Ord n => TT n -> Map n (TT n, Bool)
usedVars = f True where
f b (P Bound n t) = M.singleton n (t, b) `M.union` f b t
f b (Bind n binder t2) = (M.delete n (f b t2) `M.union`) $ case binder of
Let t v -> f b t `M.union` f b v
Guess t v -> f b t `M.union` f b v
bind -> f b (binderTy bind)
f b (App _ t1 t2) = f b t1 `M.union` f (b && isInjective t1) t2
f b (Proj t _) = f b t
f _ (V _) = error "unexpected! run vToP first"
f _ _ = M.empty
-- | Remove a node from a directed acyclic graph
deleteFromDag :: Ord n => n -> [((n, TT n), (a, Set n))] -> [((n, TT n), (a, Set n))]
deleteFromDag name [] = []
deleteFromDag name (((name2, ty), (ix, set)) : xs) = (if name == name2
then id
else (((name2, ty) , (ix, S.delete name set)) :) ) (deleteFromDag name xs)
deleteFromArgList :: Ord n => n -> [(n, TT n)] -> [(n, TT n)]
deleteFromArgList n = filter ((/= n) . fst)
-- | Asymmetric modifications to keep track of
data AsymMods = Mods
{ argApp :: !Int
, interfaceApp :: !Int
, interfaceIntro :: !Int
} deriving (Eq, Show)
-- | Homogenous tuples
data Sided a = Sided
{ left :: !a
, right :: !a
} deriving (Eq, Show)
sided :: (a -> a -> b) -> Sided a -> b
sided f (Sided l r) = f l r
-- | Could be a functor instance, but let's avoid name overloading
both :: (a -> b) -> Sided a -> Sided b
both f (Sided l r) = Sided (f l) (f r)
-- | Keeps a record of the modifications made to match one type
-- signature with another
data Score = Score
{ transposition :: !Int -- ^ transposition of arguments
, equalityFlips :: !Int -- ^ application of symmetry of equality
, asymMods :: !(Sided AsymMods) -- ^ "directional" modifications
} deriving (Eq, Show)
displayScore :: Score -> Doc OutputAnnotation
displayScore score = case both noMods (asymMods score) of
Sided True True -> annotated EQ "=" -- types are isomorphic
Sided True False -> annotated LT "<" -- found type is more general than searched type
Sided False True -> annotated GT ">" -- searched type is more general than found type
Sided False False -> text "_"
where
annotated ordr = annotate (AnnSearchResult ordr) . text
noMods (Mods app tcApp tcIntro) = app + tcApp + tcIntro == 0
-- | This allows the search to stop expanding on a certain state if its
-- score is already too high. Returns 'True' if the algorithm should keep
-- exploring from this state, and 'False' otherwise.
scoreCriterion :: Score -> Bool
scoreCriterion (Score _ _ amods) = not
( sided (&&) (both ((> 0) . argApp) amods)
|| sided (+) (both argApp amods) > 4
|| sided (||) (both (\(Mods _ tcApp tcIntro) -> tcApp > 3 || tcIntro > 3) amods)
)
-- | Convert a 'Score' to an 'Int' to provide an order for search results.
-- Lower scores are better.
defaultScoreFunction :: Score -> Int
defaultScoreFunction (Score trans eqFlip amods) =
trans + eqFlip + linearPenalty + upAndDowncastPenalty
where
-- prefer finding a more general type to a less general type
linearPenalty = (\(Sided l r) -> 3 * l + r)
(both (\(Mods app tcApp tcIntro) -> 3 * app + 4 * tcApp + 2 * tcIntro) amods)
-- it's very bad to have *both* upcasting and downcasting
upAndDowncastPenalty = 100 *
sided (*) (both (\(Mods app tcApp tcIntro) -> 2 * app + tcApp + tcIntro) amods)
instance Ord Score where
compare = comparing defaultScoreFunction
instance Monoid a => Monoid (Sided a) where
mempty = Sided mempty mempty
(Sided l1 r1) `mappend` (Sided l2 r2) = Sided (l1 `mappend` l2) (r1 `mappend` r2)
instance Monoid AsymMods where
mempty = Mods 0 0 0
(Mods a b c) `mappend` (Mods a' b' c') = Mods (a + a') (b + b') (c + c')
instance Monoid Score where
mempty = Score 0 0 mempty
(Score t e mods) `mappend` (Score t' e' mods') = Score (t + t') (e + e') (mods `mappend` mods')
-- | A directed acyclic graph representing the arguments to a function
-- The 'Int' represents the position of the argument (1st argument, 2nd, etc.)
type ArgsDAG = [((Name, Type), (Int, Set Name))]
-- | A list of interface constraints
type Interfaces = [(Name, Type)]
-- | The state corresponding to an attempted match of two types.
data State = State
{ holes :: ![(Name, Type)] -- ^ names which have yet to be resolved
, argsAndInterfaces :: !(Sided (ArgsDAG, Interfaces))
-- ^ arguments and interface constraints for each type which have yet to be resolved
, score :: !Score -- ^ the score so far
, usedNames :: ![Name] -- ^ all names that have been used
} deriving Show
modifyTypes :: (Type -> Type) -> (ArgsDAG, Interfaces) -> (ArgsDAG, Interfaces)
modifyTypes f = modifyDag *** modifyList
where
modifyDag = map (first (second f))
modifyList = map (second f)
findNameInArgsDAG :: Name -> ArgsDAG -> Maybe (Type, Maybe Int)
findNameInArgsDAG name = fmap ((snd . fst) &&& (Just . fst . snd)) . find ((name ==) . fst . fst)
findName :: Name -> (ArgsDAG, Interfaces) -> Maybe (Type, Maybe Int)
findName n (args, interfaces) = findNameInArgsDAG n args <|> ((,) <$> lookup n interfaces <*> Nothing)
deleteName :: Name -> (ArgsDAG, Interfaces) -> (ArgsDAG, Interfaces)
deleteName n (args, interfaces) = (deleteFromDag n args, filter ((/= n) . fst) interfaces)
tcToMaybe :: TC a -> Maybe a
tcToMaybe (OK x) = Just x
tcToMaybe (Error _) = Nothing
inArgTys :: (Type -> Type) -> ArgsDAG -> ArgsDAG
inArgTys = map . first . second
interfaceUnify :: Ctxt InterfaceInfo -> Context -> Type -> Type -> Maybe [(Name, Type)]
interfaceUnify interfaceInfo ctxt ty tyTry = do
res <- tcToMaybe $ match_unify ctxt [] (ty, Nothing) (retTy, Nothing) [] theHoles []
guard $ null (theHoles \\ map fst res)
let argTys' = map (second $ foldr (.) id [ subst n t | (n, t) <- res ]) tcArgs
return argTys'
where
tyTry' = vToP tyTry
theHoles = map fst nonTcArgs
retTy = getRetTy tyTry'
(tcArgs, nonTcArgs) = partition (isInterfaceArg interfaceInfo . snd) $ getArgTys tyTry'
isInterfaceArg :: Ctxt InterfaceInfo -> Type -> Bool
isInterfaceArg interfaceInfo ty = not (null (getInterfaceName clss >>= flip lookupCtxt interfaceInfo)) where
(clss, args) = unApply ty
getInterfaceName (P (TCon _ _) interfaceName _) = [interfaceName]
getInterfaceName _ = []
-- | Compute the power set
subsets :: [a] -> [[a]]
subsets [] = [[]]
subsets (x : xs) = let ss = subsets xs in map (x :) ss ++ ss
-- not recursive (i.e., doesn't flip iterated identities) at the moment
-- recalls the number of flips that have been made
flipEqualities :: Type -> [(Int, Type)]
flipEqualities t = case t of
eq1@(App _ (App _ (App _ (App _ eq@(P _ eqty _) tyL) tyR) valL) valR) | eqty == eqTy ->
[(0, eq1), (1, app (app (app (app eq tyR) tyL) valR) valL)]
Bind n binder sc -> (\bind' (j, sc') -> (fst (binderTy bind') + j, Bind n (fmap snd bind') sc'))
<$> traverse flipEqualities binder <*> flipEqualities sc
App _ f x -> (\(i, f') (j, x') -> (i + j, app f' x'))
<$> flipEqualities f <*> flipEqualities x
t' -> [(0, t')]
where app = App Complete
--DONT run vToP first!
-- | Try to match two types together in a unification-like procedure.
-- Returns a list of types and their minimum scores, sorted in order
-- of increasing score.
matchTypesBulk :: forall info. IState -> Int -> Type -> [(info, Type)] -> [(info, Score)]
matchTypesBulk istate maxScore type1 types = getAllResults startQueueOfQueues where
getStartQueues :: (info, Type) -> Maybe (Score, (info, Q.PQueue Score State))
getStartQueues nty@(info, type2) = case mapMaybe startStates ty2s of
[] -> Nothing
xs -> Just (minimum (map fst xs), (info, Q.fromList xs))
where
ty2s = (\(i, dag) (j, retTy) -> (i + j, dag, retTy))
<$> flipEqualitiesDag dag2 <*> flipEqualities retTy2
flipEqualitiesDag dag = case dag of
[] -> [(0, [])]
((n, ty), (pos, deps)) : xs ->
(\(i, ty') (j, xs') -> (i + j , ((n, ty'), (pos, deps)) : xs'))
<$> flipEqualities ty <*> flipEqualitiesDag xs
startStates (numEqFlips, sndDag, sndRetTy) = do
state <- unifyQueue (State startingHoles
(Sided (dag1, interfaceArgs1) (sndDag, interfaceArgs2))
(mempty { equalityFlips = numEqFlips }) usedns) [(retTy1, sndRetTy)]
return (score state, state)
(dag2, interfaceArgs2, retTy2) = makeDag (uniqueBinders (map fst argNames1) type2)
argNames2 = map fst dag2
usedns = map fst startingHoles
startingHoles = argNames1 ++ argNames2
startingTypes = [(retTy1, retTy2)]
startQueueOfQueues :: Q.PQueue Score (info, Q.PQueue Score State)
startQueueOfQueues = Q.fromList $ mapMaybe getStartQueues types
getAllResults :: Q.PQueue Score (info, Q.PQueue Score State) -> [(info, Score)]
getAllResults q = case Q.minViewWithKey q of
Nothing -> []
Just ((nextScore, (info, stateQ)), q') ->
if defaultScoreFunction nextScore <= maxScore
then case nextStepsQueue stateQ of
Nothing -> getAllResults q'
Just (Left stateQ') -> case Q.minViewWithKey stateQ' of
Nothing -> getAllResults q'
Just ((newQscore,_), _) -> getAllResults (Q.add newQscore (info, stateQ') q')
Just (Right theScore) -> (info, theScore) : getAllResults q'
else []
ctxt = tt_ctxt istate
interfaceInfo = idris_interfaces istate
(dag1, interfaceArgs1, retTy1) = makeDag type1
argNames1 = map fst dag1
makeDag :: Type -> (ArgsDAG, Interfaces, Type)
makeDag = first3 (zipWith (\i (ty, deps) -> (ty, (i, deps))) [0..] . reverseDag) .
computeDagP (isInterfaceArg interfaceInfo) . vToP . unLazy
first3 f (a,b,c) = (f a, b, c)
-- update our state with the unification resolutions
resolveUnis :: [(Name, Type)] -> State -> Maybe (State, [(Type, Type)])
resolveUnis [] state = Just (state, [])
resolveUnis ((name, term@(P Bound name2 _)) : xs)
state | isJust findArgs = do
((ty1, ix1), (ty2, ix2)) <- findArgs
(state'', queue) <- resolveUnis xs state'
let transScore = fromMaybe 0 (abs <$> ((-) <$> ix1 <*> ix2))
return (inScore (\s -> s { transposition = transposition s + transScore }) state'', (ty1, ty2) : queue)
where
unresolved = argsAndInterfaces state
inScore f stat = stat { score = f (score stat) }
findArgs = ((,) <$> findName name (left unresolved) <*> findName name2 (right unresolved)) <|>
((,) <$> findName name2 (left unresolved) <*> findName name (right unresolved))
matchnames = [name, name2]
deleteArgs = deleteName name . deleteName name2
state' = state { holes = filter (not . (`elem` matchnames) . fst) (holes state)
, argsAndInterfaces = both (modifyTypes (subst name term) . deleteArgs) unresolved}
resolveUnis ((name, term) : xs)
state@(State hs unresolved _ _) = case both (findName name) unresolved of
Sided Nothing Nothing -> Nothing
Sided (Just _) (Just _) -> error "Idris internal error: TypeSearch.resolveUnis"
oneOfEach -> first (addScore (both scoreFor oneOfEach)) <$> nextStep
where
scoreFor (Just _) = mempty { argApp = 1 }
scoreFor Nothing = mempty { argApp = otherApplied }
-- find variables which are determined uniquely by the type
-- due to injectivity
matchedVarMap = usedVars term
bothT f (x, y) = (f x, f y)
(injUsedVars, notInjUsedVars) = bothT M.keys . M.partition id . M.filterWithKey (\k _-> k `elem` map fst hs) $ M.map snd matchedVarMap
varsInTy = injUsedVars ++ notInjUsedVars
toDelete = name : varsInTy
deleteMany = foldr (.) id (map deleteName toDelete)
otherApplied = length notInjUsedVars
addScore additions theState = theState { score = let s = score theState in
s { asymMods = asymMods s `mappend` additions } }
state' = state { holes = filter (not . (`elem` toDelete) . fst) hs
, argsAndInterfaces = both (modifyTypes (subst name term) . deleteMany) (argsAndInterfaces state) }
nextStep = resolveUnis xs state'
-- | resolve a queue of unification constraints
unifyQueue :: State -> [(Type, Type)] -> Maybe State
unifyQueue state [] = return state
unifyQueue state ((ty1, ty2) : queue) = do
--trace ("go: \n" ++ show state) True `seq` return ()
res <- tcToMaybe $ match_unify ctxt [ (n, Pi Nothing ty (TType (UVar [] 0))) | (n, ty) <- holes state]
(ty1, Nothing)
(ty2, Nothing) [] (map fst $ holes state) []
(state', queueAdditions) <- resolveUnis res state
guard $ scoreCriterion (score state')
unifyQueue state' (queue ++ queueAdditions)
possInterfaceImplementations :: [Name] -> Type -> [Type]
possInterfaceImplementations usedns ty = do
interfaceName <- getInterfaceName clss
interfaceDef <- lookupCtxt interfaceName interfaceInfo
n <- interface_implementations interfaceDef
def <- lookupCtxt (fst n) (definitions ctxt)
nty <- normaliseC ctxt [] <$> (case typeFromDef def of Just x -> [x]; Nothing -> [])
let ty' = vToP (uniqueBinders usedns nty)
return ty'
where
(clss, _) = unApply ty
getInterfaceName (P (TCon _ _) interfaceName _) = [interfaceName]
getInterfaceName _ = []
-- 'Just' if the computation hasn't totally failed yet, 'Nothing' if it has
-- 'Left' if we haven't found a terminal state, 'Right' if we have
nextStepsQueue :: Q.PQueue Score State -> Maybe (Either (Q.PQueue Score State) Score)
nextStepsQueue queue = do
((nextScore, next), rest) <- Q.minViewWithKey queue
Just $ if isFinal next
then Right nextScore
else let additions = if scoreCriterion nextScore
then Q.fromList [ (score state, state) | state <- nextSteps next ]
else Q.empty in
Left (Q.union rest additions)
where
isFinal (State [] (Sided ([], []) ([], [])) _ _) = True
isFinal _ = False
-- | Find all possible matches starting from a given state.
-- We go in stages rather than concatenating all three results in hopes of narrowing
-- the search tree. Once we advance in a phase, there should be no going back.
nextSteps :: State -> [State]
-- Stage 3 - match interfaces
nextSteps (State [] unresolved@(Sided ([], c1) ([], c2)) scoreAcc usedns) =
if null results3 then results4 else results3
where
-- try to match an interface argument from the left with an interface argument from the right
results3 =
catMaybes [ unifyQueue (State []
(Sided ([], deleteFromArgList n1 c1)
([], map (second subst2for1) (deleteFromArgList n2 c2)))
scoreAcc usedns) [(ty1, ty2)]
| (n1, ty1) <- c1, (n2, ty2) <- c2, let subst2for1 = psubst n2 (P Bound n1 ty1)]
-- try to hunt match an interface constraint by replacing it with an implementation
results4 = [ State [] (both (\(cs, _, _) -> ([], cs)) sds)
(scoreAcc `mappend` Score 0 0 (both (\(_, amods, _) -> amods) sds))
(usedns ++ sided (++) (both (\(_, _, hs) -> hs) sds))
| sds <- allMods ]
where
allMods = parallel defMod mods
mods :: Sided [( Interfaces, AsymMods, [Name] )]
mods = both (implementationMods . snd) unresolved
defMod :: Sided (Interfaces, AsymMods, [Name])
defMod = both (\(_, cs) -> (cs, mempty , [])) unresolved
parallel :: Sided a -> Sided [a] -> [Sided a]
parallel (Sided l r) (Sided ls rs) = map (flip Sided r) ls ++ map (Sided l) rs
implementationMods :: Interfaces -> [( Interfaces , AsymMods, [Name] )]
implementationMods interfaces = [ ( newInterfaceArgs, mempty { interfaceApp = 1 }, newHoles )
| (_, ty) <- interfaces
, impl <- possInterfaceImplementations usedns ty
, newInterfaceArgs <- maybeToList $ interfaceUnify interfaceInfo ctxt ty impl
, let newHoles = map fst newInterfaceArgs ]
-- Stage 1 - match arguments
nextSteps (State hs (Sided (dagL, c1) (dagR, c2)) scoreAcc usedns) = results where
results = concatMap takeSomeInterfaces results1
-- we only try to match arguments whose names don't appear in the types
-- of any other arguments
canBeFirst :: ArgsDAG -> [(Name, Type)]
canBeFirst = map fst . filter (S.null . snd . snd)
-- try to match an argument from the left with an argument from the right
results1 = catMaybes [ unifyQueue (State (filter (not . (`elem` [n1,n2]) . fst) hs)
(Sided (deleteFromDag n1 dagL, c1)
(inArgTys subst2for1 $ deleteFromDag n2 dagR, map (second subst2for1) c2))
scoreAcc usedns) [(ty1, ty2)]
| (n1, ty1) <- canBeFirst dagL, (n2, ty2) <- canBeFirst dagR
, let subst2for1 = psubst n2 (P Bound n1 ty1)]
-- Stage 2 - simply introduce a subset of the interfaces
-- we've finished, so take some interfaces
takeSomeInterfaces (State [] unresolved@(Sided ([], _) ([], _)) scoreAcc usedns) =
map statesFromMods . prod $ both (interfaceMods . snd) unresolved
where
swap (Sided l r) = Sided r l
statesFromMods :: Sided (Interfaces, AsymMods) -> State
statesFromMods sides = let interfaces = both (\(c, _) -> ([], c)) sides
mods = swap (both snd sides) in
State [] interfaces (scoreAcc `mappend` (mempty { asymMods = mods })) usedns
interfaceMods :: Interfaces -> [(Interfaces, AsymMods)]
interfaceMods cs = let lcs = length cs in
[ (cs', mempty { interfaceIntro = lcs - length cs' }) | cs' <- subsets cs ]
prod :: Sided [a] -> [Sided a]
prod (Sided ls rs) = [Sided l r | l <- ls, r <- rs]
-- still have arguments to match, so just be the identity
takeSomeInterfaces s = [s]
|
enolan/Idris-dev
|
src/Idris/TypeSearch.hs
|
bsd-3-clause
| 23,691
| 0
| 20
| 5,780
| 8,540
| 4,589
| 3,951
| 411
| 22
|
import Test.HUnit
import System.IO
import Ch3
let exampleList = Cons (-1) (Cons 2 (Cons (-6) Empty))
let addOne x = x + 1
let square x = x * x
mapIntList addOne exampleList
mapIntList square exampleList
keepOnlyEven exampleList
filterList even lst1
|
wangwangwar/cis194
|
test/Ch3Spec.hs
|
bsd-3-clause
| 257
| 1
| 12
| 49
| 102
| 53
| 49
| -1
| -1
|
{-# language CPP #-}
-- | = Name
--
-- VK_NV_shading_rate_image - device extension
--
-- == VK_NV_shading_rate_image
--
-- [__Name String__]
-- @VK_NV_shading_rate_image@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 165
--
-- [__Revision__]
-- 3
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Contact__]
--
-- - Pat Brown
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_NV_shading_rate_image] @nvpbrown%0A<<Here describe the issue or question you have about the VK_NV_shading_rate_image extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2019-07-18
--
-- [__Interactions and External Dependencies__]
--
-- - This extension requires
-- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_shading_rate.html SPV_NV_shading_rate>
--
-- - This extension provides API support for
-- <https://github.com/KhronosGroup/GLSL/blob/master/extensions/nv/GLSL_NV_shading_rate_image.txt GL_NV_shading_rate_image>
--
-- [__Contributors__]
--
-- - Pat Brown, NVIDIA
--
-- - Carsten Rohde, NVIDIA
--
-- - Jeff Bolz, NVIDIA
--
-- - Daniel Koch, NVIDIA
--
-- - Mathias Schott, NVIDIA
--
-- - Matthew Netsch, Qualcomm Technologies, Inc.
--
-- == Description
--
-- This extension allows applications to use a variable shading rate when
-- processing fragments of rasterized primitives. By default, Vulkan will
-- spawn one fragment shader for each pixel covered by a primitive. In this
-- extension, applications can bind a /shading rate image/ that can be used
-- to vary the number of fragment shader invocations across the
-- framebuffer. Some portions of the screen may be configured to spawn up
-- to 16 fragment shaders for each pixel, while other portions may use a
-- single fragment shader invocation for a 4x4 block of pixels. This can be
-- useful for use cases like eye tracking, where the portion of the
-- framebuffer that the user is looking at directly can be processed at
-- high frequency, while distant corners of the image can be processed at
-- lower frequency. Each texel in the shading rate image represents a
-- fixed-size rectangle in the framebuffer, covering 16x16 pixels in the
-- initial implementation of this extension. When rasterizing a primitive
-- covering one of these rectangles, the Vulkan implementation reads a
-- texel in the bound shading rate image and looks up the fetched value in
-- a palette to determine a base shading rate.
--
-- In addition to the API support controlling rasterization, this extension
-- also adds Vulkan support for the
-- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_shading_rate.html SPV_NV_shading_rate>
-- extension to SPIR-V. That extension provides two fragment shader
-- variable decorations that allow fragment shaders to determine the
-- shading rate used for processing the fragment:
--
-- - @FragmentSizeNV@, which indicates the width and height of the set of
-- pixels processed by the fragment shader.
--
-- - @InvocationsPerPixel@, which indicates the maximum number of
-- fragment shader invocations that could be spawned for the pixel(s)
-- covered by the fragment.
--
-- When using SPIR-V in conjunction with the OpenGL Shading Language
-- (GLSL), the fragment shader capabilities are provided by the
-- @GL_NV_shading_rate_image@ language extension and correspond to the
-- built-in variables @gl_FragmentSizeNV@ and @gl_InvocationsPerPixelNV@,
-- respectively.
--
-- == New Commands
--
-- - 'cmdBindShadingRateImageNV'
--
-- - 'cmdSetCoarseSampleOrderNV'
--
-- - 'cmdSetViewportShadingRatePaletteNV'
--
-- == New Structures
--
-- - 'CoarseSampleLocationNV'
--
-- - 'CoarseSampleOrderCustomNV'
--
-- - 'ShadingRatePaletteNV'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2',
-- 'Vulkan.Core10.Device.DeviceCreateInfo':
--
-- - 'PhysicalDeviceShadingRateImageFeaturesNV'
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceShadingRateImagePropertiesNV'
--
-- - Extending 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo':
--
-- - 'PipelineViewportCoarseSampleOrderStateCreateInfoNV'
--
-- - 'PipelineViewportShadingRateImageStateCreateInfoNV'
--
-- == New Enums
--
-- - 'CoarseSampleOrderTypeNV'
--
-- - 'ShadingRatePaletteEntryNV'
--
-- == New Enum Constants
--
-- - 'NV_SHADING_RATE_IMAGE_EXTENSION_NAME'
--
-- - 'NV_SHADING_RATE_IMAGE_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.AccessFlagBits.AccessFlagBits':
--
-- - 'ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV'
--
-- - Extending 'Vulkan.Core10.Enums.DynamicState.DynamicState':
--
-- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV'
--
-- - 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV'
--
-- - Extending 'Vulkan.Core10.Enums.ImageLayout.ImageLayout':
--
-- - 'IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV'
--
-- - Extending
-- 'Vulkan.Core10.Enums.ImageUsageFlagBits.ImageUsageFlagBits':
--
-- - 'IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV'
--
-- - Extending
-- 'Vulkan.Core10.Enums.PipelineStageFlagBits.PipelineStageFlagBits':
--
-- - 'PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV'
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV'
--
-- == Issues
--
-- (1) When using shading rates specifying “coarse” fragments covering
-- multiple pixels, we will generate a combined coverage mask that combines
-- the coverage masks of all pixels covered by the fragment. By default,
-- these masks are combined in an implementation-dependent order. Should we
-- provide a mechanism allowing applications to query or specify an exact
-- order?
--
-- __RESOLVED__: Yes, this feature is useful for cases where most of the
-- fragment shader can be evaluated once for an entire coarse fragment, but
-- where some per-pixel computations are also required. For example, a
-- per-pixel alpha test may want to kill all the samples for some pixels in
-- a coarse fragment. This sort of test can be implemented using an output
-- sample mask, but such a shader would need to know which bit in the mask
-- corresponds to each sample in the coarse fragment. We are including a
-- mechanism to allow aplications to specify the orders of coverage samples
-- for each shading rate and sample count, either as static pipeline state
-- or dynamically via a command buffer. This portion of the extension has
-- its own feature bit.
--
-- We will not be providing a query to determine the
-- implementation-dependent default ordering. The thinking here is that if
-- an application cares enough about the coarse fragment sample ordering to
-- perform such a query, it could instead just set its own order, also
-- using custom per-pixel sample locations if required.
--
-- (2) For the pipeline stage 'PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV',
-- should we specify a precise location in the pipeline the shading rate
-- image is accessed (after geometry shading, but before the early fragment
-- tests) or leave it under-specified in case there are other
-- implementations that access the image in a different pipeline location?
--
-- __RESOLVED__ We are specifying the pipeline stage to be between the
-- final
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#pipeline-graphics-subsets-pre-rasterization pre-rasterization shader stage>
-- ('Vulkan.Core10.Enums.PipelineStageFlagBits.PIPELINE_STAGE_GEOMETRY_SHADER_BIT')
-- and before the first stage used for fragment processing
-- ('Vulkan.Core10.Enums.PipelineStageFlagBits.PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT'),
-- which seems to be the natural place to access the shading rate image.
--
-- (3) How do centroid-sampled variables work with fragments larger than
-- one pixel?
--
-- __RESOLVED__ For single-pixel fragments, fragment shader inputs
-- decorated with @Centroid@ are sampled at an implementation-dependent
-- location in the intersection of the area of the primitive being
-- rasterized and the area of the pixel that corresponds to the fragment.
-- With multi-pixel fragments, we follow a similar pattern, using the
-- intersection of the primitive and the __set__ of pixels corresponding to
-- the fragment.
--
-- One important thing to keep in mind when using such “coarse” shading
-- rates is that fragment attributes are sampled at the center of the
-- fragment by default, regardless of the set of pixels\/samples covered by
-- the fragment. For fragments with a size of 4x4 pixels, this center
-- location will be more than two pixels (1.5 * sqrt(2)) away from the
-- center of the pixels at the corners of the fragment. When rendering a
-- primitive that covers only a small part of a coarse fragment, sampling a
-- color outside the primitive can produce overly bright or dark color
-- values if the color values have a large gradient. To deal with this, an
-- application can use centroid sampling on attributes where
-- “extrapolation” artifacts can lead to overly bright or dark pixels. Note
-- that this same problem also exists for multisampling with single-pixel
-- fragments, but is less severe because it only affects certain samples of
-- a pixel and such bright\/dark samples may be averaged with other samples
-- that do not have a similar problem.
--
-- == Version History
--
-- - Revision 3, 2019-07-18 (Mathias Schott)
--
-- - Fully list extension interfaces in this appendix.
--
-- - Revision 2, 2018-09-13 (Pat Brown)
--
-- - Miscellaneous edits preparing the specification for publication.
--
-- - Revision 1, 2018-08-08 (Pat Brown)
--
-- - Internal revisions
--
-- == See Also
--
-- 'CoarseSampleLocationNV', 'CoarseSampleOrderCustomNV',
-- 'CoarseSampleOrderTypeNV', 'PhysicalDeviceShadingRateImageFeaturesNV',
-- 'PhysicalDeviceShadingRateImagePropertiesNV',
-- 'PipelineViewportCoarseSampleOrderStateCreateInfoNV',
-- 'PipelineViewportShadingRateImageStateCreateInfoNV',
-- 'ShadingRatePaletteEntryNV', 'ShadingRatePaletteNV',
-- 'cmdBindShadingRateImageNV', 'cmdSetCoarseSampleOrderNV',
-- 'cmdSetViewportShadingRatePaletteNV'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_NV_shading_rate_image Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_NV_shading_rate_image ( cmdBindShadingRateImageNV
, cmdSetViewportShadingRatePaletteNV
, cmdSetCoarseSampleOrderNV
, pattern IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV
, pattern ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV
, pattern IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV
, pattern PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV
, ShadingRatePaletteNV(..)
, PipelineViewportShadingRateImageStateCreateInfoNV(..)
, PhysicalDeviceShadingRateImageFeaturesNV(..)
, PhysicalDeviceShadingRateImagePropertiesNV(..)
, CoarseSampleLocationNV(..)
, CoarseSampleOrderCustomNV(..)
, PipelineViewportCoarseSampleOrderStateCreateInfoNV(..)
, ShadingRatePaletteEntryNV( SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV
, SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV
, SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV
, SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV
, SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV
, SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV
, ..
)
, CoarseSampleOrderTypeNV( COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV
, COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV
, COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV
, COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV
, ..
)
, NV_SHADING_RATE_IMAGE_SPEC_VERSION
, pattern NV_SHADING_RATE_IMAGE_SPEC_VERSION
, NV_SHADING_RATE_IMAGE_EXTENSION_NAME
, pattern NV_SHADING_RATE_IMAGE_EXTENSION_NAME
) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import GHC.Show (showsPrec)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero)
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Data.Int (Int32)
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Data.Word (Word32)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.NamedType ((:::))
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Handles (CommandBuffer)
import Vulkan.Core10.Handles (CommandBuffer(..))
import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer))
import Vulkan.Core10.Handles (CommandBuffer_T)
import Vulkan.Dynamic (DeviceCmds(pVkCmdBindShadingRateImageNV))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetCoarseSampleOrderNV))
import Vulkan.Dynamic (DeviceCmds(pVkCmdSetViewportShadingRatePaletteNV))
import Vulkan.Core10.FundamentalTypes (Extent2D)
import Vulkan.Core10.Enums.ImageLayout (ImageLayout)
import Vulkan.Core10.Enums.ImageLayout (ImageLayout(..))
import Vulkan.Core10.Handles (ImageView)
import Vulkan.Core10.Handles (ImageView(..))
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.AccessFlagBits (AccessFlags)
import Vulkan.Core10.Enums.AccessFlagBits (AccessFlagBits(ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR))
import Vulkan.Core10.Enums.ImageLayout (ImageLayout(IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR))
import Vulkan.Core10.Enums.ImageUsageFlagBits (ImageUsageFlags)
import Vulkan.Core10.Enums.ImageUsageFlagBits (ImageUsageFlagBits(IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR))
import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlags)
import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlagBits(PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV))
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdBindShadingRateImageNV
:: FunPtr (Ptr CommandBuffer_T -> ImageView -> ImageLayout -> IO ()) -> Ptr CommandBuffer_T -> ImageView -> ImageLayout -> IO ()
-- | vkCmdBindShadingRateImageNV - Bind a shading rate image on a command
-- buffer
--
-- == Valid Usage
--
-- - #VUID-vkCmdBindShadingRateImageNV-None-02058# The
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-shadingRateImage shading rate image>
-- feature /must/ be enabled
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageView-02059# If @imageView@ is
-- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ be a valid
-- 'Vulkan.Core10.Handles.ImageView' handle of type
-- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D' or
-- 'Vulkan.Core10.Enums.ImageViewType.IMAGE_VIEW_TYPE_2D_ARRAY'
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageView-02060# If @imageView@ is
-- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ have a
-- format of 'Vulkan.Core10.Enums.Format.FORMAT_R8_UINT'
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageView-02061# If @imageView@ is
-- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', it /must/ have been
-- created with a @usage@ value including
-- 'IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV'
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageView-02062# If @imageView@ is
-- not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @imageLayout@ /must/
-- match the actual 'Vulkan.Core10.Enums.ImageLayout.ImageLayout' of
-- each subresource accessible from @imageView@ at the time the
-- subresource is accessed
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageLayout-02063# If @imageView@
-- is not 'Vulkan.Core10.APIConstants.NULL_HANDLE', @imageLayout@
-- /must/ be 'IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV' or
-- 'Vulkan.Core10.Enums.ImageLayout.IMAGE_LAYOUT_GENERAL'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdBindShadingRateImageNV-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
-- 'Vulkan.Core10.Handles.CommandBuffer' handle
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageView-parameter# If
-- @imageView@ is not 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- @imageView@ /must/ be a valid 'Vulkan.Core10.Handles.ImageView'
-- handle
--
-- - #VUID-vkCmdBindShadingRateImageNV-imageLayout-parameter#
-- @imageLayout@ /must/ be a valid
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout' value
--
-- - #VUID-vkCmdBindShadingRateImageNV-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdBindShadingRateImageNV-commandBuffer-cmdpool# The
-- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was
-- allocated from /must/ support graphics operations
--
-- - #VUID-vkCmdBindShadingRateImageNV-commonparent# Both of
-- @commandBuffer@, and @imageView@ that are valid handles of
-- non-ignored parameters /must/ have been created, allocated, or
-- retrieved from the same 'Vulkan.Core10.Handles.Device'
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
-- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
-- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> |
-- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+
-- | Primary | Both | Graphics |
-- | Secondary | | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'Vulkan.Core10.Handles.CommandBuffer',
-- 'Vulkan.Core10.Enums.ImageLayout.ImageLayout',
-- 'Vulkan.Core10.Handles.ImageView'
cmdBindShadingRateImageNV :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer into which the command will be
-- recorded.
CommandBuffer
-> -- | @imageView@ is an image view handle specifying the shading rate image.
-- @imageView@ /may/ be set to 'Vulkan.Core10.APIConstants.NULL_HANDLE',
-- which is equivalent to specifying a view of an image filled with zero
-- values.
ImageView
-> -- | @imageLayout@ is the layout that the image subresources accessible from
-- @imageView@ will be in when the shading rate image is accessed.
ImageLayout
-> io ()
cmdBindShadingRateImageNV commandBuffer imageView imageLayout = liftIO $ do
let vkCmdBindShadingRateImageNVPtr = pVkCmdBindShadingRateImageNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
unless (vkCmdBindShadingRateImageNVPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdBindShadingRateImageNV is null" Nothing Nothing
let vkCmdBindShadingRateImageNV' = mkVkCmdBindShadingRateImageNV vkCmdBindShadingRateImageNVPtr
traceAroundEvent "vkCmdBindShadingRateImageNV" (vkCmdBindShadingRateImageNV' (commandBufferHandle (commandBuffer)) (imageView) (imageLayout))
pure $ ()
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetViewportShadingRatePaletteNV
:: FunPtr (Ptr CommandBuffer_T -> Word32 -> Word32 -> Ptr ShadingRatePaletteNV -> IO ()) -> Ptr CommandBuffer_T -> Word32 -> Word32 -> Ptr ShadingRatePaletteNV -> IO ()
-- | vkCmdSetViewportShadingRatePaletteNV - Set shading rate image palettes
-- dynamically for a command buffer
--
-- = Description
--
-- This command sets the per-viewport shading rate image palettes for
-- subsequent drawing commands when the graphics pipeline is created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV'
-- set in
-- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@.
-- Otherwise, this state is specified by the
-- 'PipelineViewportShadingRateImageStateCreateInfoNV'::@pShadingRatePalettes@
-- values used to create the currently active pipeline.
--
-- == Valid Usage
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-None-02064# The
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-shadingRateImage shading rate image>
-- feature /must/ be enabled
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02067# The
-- sum of @firstViewport@ and @viewportCount@ /must/ be between @1@ and
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxViewports@,
-- inclusive
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-firstViewport-02068# If
-- the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @firstViewport@ /must/ be @0@
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-viewportCount-02069# If
-- the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @viewportCount@ /must/ be @1@
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
-- 'Vulkan.Core10.Handles.CommandBuffer' handle
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-pShadingRatePalettes-parameter#
-- @pShadingRatePalettes@ /must/ be a valid pointer to an array of
-- @viewportCount@ valid 'ShadingRatePaletteNV' structures
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-cmdpool#
-- The 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was
-- allocated from /must/ support graphics operations
--
-- - #VUID-vkCmdSetViewportShadingRatePaletteNV-viewportCount-arraylength#
-- @viewportCount@ /must/ be greater than @0@
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
-- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
-- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> |
-- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+
-- | Primary | Both | Graphics |
-- | Secondary | | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'Vulkan.Core10.Handles.CommandBuffer', 'ShadingRatePaletteNV'
cmdSetViewportShadingRatePaletteNV :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer into which the command will be
-- recorded.
CommandBuffer
-> -- | @firstViewport@ is the index of the first viewport whose shading rate
-- palette is updated by the command.
("firstViewport" ::: Word32)
-> -- | @pShadingRatePalettes@ is a pointer to an array of
-- 'ShadingRatePaletteNV' structures defining the palette for each
-- viewport.
("shadingRatePalettes" ::: Vector ShadingRatePaletteNV)
-> io ()
cmdSetViewportShadingRatePaletteNV commandBuffer firstViewport shadingRatePalettes = liftIO . evalContT $ do
let vkCmdSetViewportShadingRatePaletteNVPtr = pVkCmdSetViewportShadingRatePaletteNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetViewportShadingRatePaletteNVPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetViewportShadingRatePaletteNV is null" Nothing Nothing
let vkCmdSetViewportShadingRatePaletteNV' = mkVkCmdSetViewportShadingRatePaletteNV vkCmdSetViewportShadingRatePaletteNVPtr
pPShadingRatePalettes <- ContT $ allocaBytes @ShadingRatePaletteNV ((Data.Vector.length (shadingRatePalettes)) * 16)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPShadingRatePalettes `plusPtr` (16 * (i)) :: Ptr ShadingRatePaletteNV) (e) . ($ ())) (shadingRatePalettes)
lift $ traceAroundEvent "vkCmdSetViewportShadingRatePaletteNV" (vkCmdSetViewportShadingRatePaletteNV' (commandBufferHandle (commandBuffer)) (firstViewport) ((fromIntegral (Data.Vector.length $ (shadingRatePalettes)) :: Word32)) (pPShadingRatePalettes))
pure $ ()
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkCmdSetCoarseSampleOrderNV
:: FunPtr (Ptr CommandBuffer_T -> CoarseSampleOrderTypeNV -> Word32 -> Ptr CoarseSampleOrderCustomNV -> IO ()) -> Ptr CommandBuffer_T -> CoarseSampleOrderTypeNV -> Word32 -> Ptr CoarseSampleOrderCustomNV -> IO ()
-- | vkCmdSetCoarseSampleOrderNV - Set order of coverage samples for coarse
-- fragments dynamically for a command buffer
--
-- = Description
--
-- If @sampleOrderType@ is 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV', the
-- coverage sample order used for any combination of fragment area and
-- coverage sample count not enumerated in @pCustomSampleOrders@ will be
-- identical to that used for 'COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV'.
--
-- This command sets the order of coverage samples for subsequent drawing
-- commands when the graphics pipeline is created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV'
-- set in
-- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'::@pDynamicStates@.
-- Otherwise, this state is specified by the
-- 'PipelineViewportCoarseSampleOrderStateCreateInfoNV' values used to
-- create the currently active pipeline.
--
-- == Valid Usage
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-sampleOrderType-02081# If
-- @sampleOrderType@ is not 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV',
-- @customSamplerOrderCount@ /must/ be @0@
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-pCustomSampleOrders-02235# The
-- array @pCustomSampleOrders@ /must/ not contain two structures with
-- matching values for both the @shadingRate@ and @sampleCount@ members
--
-- == Valid Usage (Implicit)
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-commandBuffer-parameter#
-- @commandBuffer@ /must/ be a valid
-- 'Vulkan.Core10.Handles.CommandBuffer' handle
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-sampleOrderType-parameter#
-- @sampleOrderType@ /must/ be a valid 'CoarseSampleOrderTypeNV' value
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-pCustomSampleOrders-parameter# If
-- @customSampleOrderCount@ is not @0@, @pCustomSampleOrders@ /must/ be
-- a valid pointer to an array of @customSampleOrderCount@ valid
-- 'CoarseSampleOrderCustomNV' structures
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-commandBuffer-recording#
-- @commandBuffer@ /must/ be in the
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#commandbuffers-lifecycle recording state>
--
-- - #VUID-vkCmdSetCoarseSampleOrderNV-commandBuffer-cmdpool# The
-- 'Vulkan.Core10.Handles.CommandPool' that @commandBuffer@ was
-- allocated from /must/ support graphics operations
--
-- == Host Synchronization
--
-- - Host access to @commandBuffer@ /must/ be externally synchronized
--
-- - Host access to the 'Vulkan.Core10.Handles.CommandPool' that
-- @commandBuffer@ was allocated from /must/ be externally synchronized
--
-- == Command Properties
--
-- \'
--
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
-- | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope> | <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types> |
-- +============================================================================================================================+========================================================================================================================+=======================================================================================================================+
-- | Primary | Both | Graphics |
-- | Secondary | | |
-- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'CoarseSampleOrderCustomNV', 'CoarseSampleOrderTypeNV',
-- 'Vulkan.Core10.Handles.CommandBuffer'
cmdSetCoarseSampleOrderNV :: forall io
. (MonadIO io)
=> -- | @commandBuffer@ is the command buffer into which the command will be
-- recorded.
CommandBuffer
-> -- | @sampleOrderType@ specifies the mechanism used to order coverage samples
-- in fragments larger than one pixel.
CoarseSampleOrderTypeNV
-> -- | @pCustomSampleOrders@ is a pointer to an array of
-- 'CoarseSampleOrderCustomNV' structures, each structure specifying the
-- coverage sample order for a single combination of fragment area and
-- coverage sample count.
("customSampleOrders" ::: Vector CoarseSampleOrderCustomNV)
-> io ()
cmdSetCoarseSampleOrderNV commandBuffer sampleOrderType customSampleOrders = liftIO . evalContT $ do
let vkCmdSetCoarseSampleOrderNVPtr = pVkCmdSetCoarseSampleOrderNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds)
lift $ unless (vkCmdSetCoarseSampleOrderNVPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetCoarseSampleOrderNV is null" Nothing Nothing
let vkCmdSetCoarseSampleOrderNV' = mkVkCmdSetCoarseSampleOrderNV vkCmdSetCoarseSampleOrderNVPtr
pPCustomSampleOrders <- ContT $ allocaBytes @CoarseSampleOrderCustomNV ((Data.Vector.length (customSampleOrders)) * 24)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPCustomSampleOrders `plusPtr` (24 * (i)) :: Ptr CoarseSampleOrderCustomNV) (e) . ($ ())) (customSampleOrders)
lift $ traceAroundEvent "vkCmdSetCoarseSampleOrderNV" (vkCmdSetCoarseSampleOrderNV' (commandBufferHandle (commandBuffer)) (sampleOrderType) ((fromIntegral (Data.Vector.length $ (customSampleOrders)) :: Word32)) (pPCustomSampleOrders))
pure $ ()
-- No documentation found for TopLevel "VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV"
pattern IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV = IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR
-- No documentation found for TopLevel "VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV"
pattern ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV = ACCESS_FRAGMENT_SHADING_RATE_ATTACHMENT_READ_BIT_KHR
-- No documentation found for TopLevel "VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV"
pattern IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV = IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR
-- No documentation found for TopLevel "VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV"
pattern PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV = PIPELINE_STAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR
-- | VkShadingRatePaletteNV - Structure specifying a single shading rate
-- palette
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'PipelineViewportShadingRateImageStateCreateInfoNV',
-- 'ShadingRatePaletteEntryNV', 'cmdSetViewportShadingRatePaletteNV'
data ShadingRatePaletteNV = ShadingRatePaletteNV
{ -- | @pShadingRatePaletteEntries@ is a pointer to an array of
-- 'ShadingRatePaletteEntryNV' enums defining the shading rate for each
-- palette entry.
--
-- #VUID-VkShadingRatePaletteNV-pShadingRatePaletteEntries-parameter#
-- @pShadingRatePaletteEntries@ /must/ be a valid pointer to an array of
-- @shadingRatePaletteEntryCount@ valid 'ShadingRatePaletteEntryNV' values
shadingRatePaletteEntries :: Vector ShadingRatePaletteEntryNV }
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ShadingRatePaletteNV)
#endif
deriving instance Show ShadingRatePaletteNV
instance ToCStruct ShadingRatePaletteNV where
withCStruct x f = allocaBytes 16 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ShadingRatePaletteNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (shadingRatePaletteEntries)) :: Word32))
pPShadingRatePaletteEntries' <- ContT $ allocaBytes @ShadingRatePaletteEntryNV ((Data.Vector.length (shadingRatePaletteEntries)) * 4)
lift $ Data.Vector.imapM_ (\i e -> poke (pPShadingRatePaletteEntries' `plusPtr` (4 * (i)) :: Ptr ShadingRatePaletteEntryNV) (e)) (shadingRatePaletteEntries)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ShadingRatePaletteEntryNV))) (pPShadingRatePaletteEntries')
lift $ f
cStructSize = 16
cStructAlignment = 8
pokeZeroCStruct _ f = f
instance FromCStruct ShadingRatePaletteNV where
peekCStruct p = do
shadingRatePaletteEntryCount <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
pShadingRatePaletteEntries <- peek @(Ptr ShadingRatePaletteEntryNV) ((p `plusPtr` 8 :: Ptr (Ptr ShadingRatePaletteEntryNV)))
pShadingRatePaletteEntries' <- generateM (fromIntegral shadingRatePaletteEntryCount) (\i -> peek @ShadingRatePaletteEntryNV ((pShadingRatePaletteEntries `advancePtrBytes` (4 * (i)) :: Ptr ShadingRatePaletteEntryNV)))
pure $ ShadingRatePaletteNV
pShadingRatePaletteEntries'
instance Zero ShadingRatePaletteNV where
zero = ShadingRatePaletteNV
mempty
-- | VkPipelineViewportShadingRateImageStateCreateInfoNV - Structure
-- specifying parameters controlling shading rate image usage
--
-- = Description
--
-- If this structure is not present, @shadingRateImageEnable@ is considered
-- to be 'Vulkan.Core10.FundamentalTypes.FALSE', and the shading rate image
-- and palettes are not used.
--
-- == Valid Usage
--
-- - #VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-viewportCount-02054#
-- If the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-multiViewport multiple viewports>
-- feature is not enabled, @viewportCount@ /must/ be @0@ or @1@
--
-- - #VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-viewportCount-02055#
-- @viewportCount@ /must/ be less than or equal to
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@maxViewports@
--
-- - #VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-shadingRateImageEnable-02056#
-- If @shadingRateImageEnable@ is
-- 'Vulkan.Core10.FundamentalTypes.TRUE', @viewportCount@ /must/ be
-- greater or equal to the @viewportCount@ member of
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPipelineViewportShadingRateImageStateCreateInfoNV-sType-sType#
-- @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV'
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32', 'ShadingRatePaletteNV',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PipelineViewportShadingRateImageStateCreateInfoNV = PipelineViewportShadingRateImageStateCreateInfoNV
{ -- | @shadingRateImageEnable@ specifies whether shading rate image and
-- palettes are used during rasterization.
shadingRateImageEnable :: Bool
, -- | @pShadingRatePalettes@ is a pointer to an array of
-- 'ShadingRatePaletteNV' structures defining the palette for each
-- viewport. If the shading rate palette state is dynamic, this member is
-- ignored.
shadingRatePalettes :: Vector ShadingRatePaletteNV
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineViewportShadingRateImageStateCreateInfoNV)
#endif
deriving instance Show PipelineViewportShadingRateImageStateCreateInfoNV
instance ToCStruct PipelineViewportShadingRateImageStateCreateInfoNV where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineViewportShadingRateImageStateCreateInfoNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (shadingRateImageEnable))
lift $ poke ((p `plusPtr` 20 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (shadingRatePalettes)) :: Word32))
pPShadingRatePalettes' <- ContT $ allocaBytes @ShadingRatePaletteNV ((Data.Vector.length (shadingRatePalettes)) * 16)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPShadingRatePalettes' `plusPtr` (16 * (i)) :: Ptr ShadingRatePaletteNV) (e) . ($ ())) (shadingRatePalettes)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr ShadingRatePaletteNV))) (pPShadingRatePalettes')
lift $ f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_SHADING_RATE_IMAGE_STATE_CREATE_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PipelineViewportShadingRateImageStateCreateInfoNV where
peekCStruct p = do
shadingRateImageEnable <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
viewportCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32))
pShadingRatePalettes <- peek @(Ptr ShadingRatePaletteNV) ((p `plusPtr` 24 :: Ptr (Ptr ShadingRatePaletteNV)))
pShadingRatePalettes' <- generateM (fromIntegral viewportCount) (\i -> peekCStruct @ShadingRatePaletteNV ((pShadingRatePalettes `advancePtrBytes` (16 * (i)) :: Ptr ShadingRatePaletteNV)))
pure $ PipelineViewportShadingRateImageStateCreateInfoNV
(bool32ToBool shadingRateImageEnable) pShadingRatePalettes'
instance Zero PipelineViewportShadingRateImageStateCreateInfoNV where
zero = PipelineViewportShadingRateImageStateCreateInfoNV
zero
mempty
-- | VkPhysicalDeviceShadingRateImageFeaturesNV - Structure describing
-- shading rate image features that can be supported by an implementation
--
-- = Members
--
-- This structure describes the following features:
--
-- = Description
--
-- See
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-shading-rate-image Shading Rate Image>
-- for more information.
--
-- If the 'PhysicalDeviceShadingRateImageFeaturesNV' structure is included
-- in the @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2',
-- it is filled in to indicate whether each corresponding feature is
-- supported. 'PhysicalDeviceShadingRateImageFeaturesNV' /can/ also be used
-- in the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to
-- selectively enable these features.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceShadingRateImageFeaturesNV = PhysicalDeviceShadingRateImageFeaturesNV
{ -- | #features-shadingRateImage# @shadingRateImage@ indicates that the
-- implementation supports the use of a shading rate image to derive an
-- effective shading rate for fragment processing. It also indicates that
-- the implementation supports the @ShadingRateNV@ SPIR-V execution mode.
shadingRateImage :: Bool
, -- | #features-shadingRateCoarseSampleOrder# @shadingRateCoarseSampleOrder@
-- indicates that the implementation supports a user-configurable ordering
-- of coverage samples in fragments larger than one pixel.
shadingRateCoarseSampleOrder :: Bool
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceShadingRateImageFeaturesNV)
#endif
deriving instance Show PhysicalDeviceShadingRateImageFeaturesNV
instance ToCStruct PhysicalDeviceShadingRateImageFeaturesNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceShadingRateImageFeaturesNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (shadingRateImage))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (shadingRateCoarseSampleOrder))
f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_FEATURES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
f
instance FromCStruct PhysicalDeviceShadingRateImageFeaturesNV where
peekCStruct p = do
shadingRateImage <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
shadingRateCoarseSampleOrder <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
pure $ PhysicalDeviceShadingRateImageFeaturesNV
(bool32ToBool shadingRateImage) (bool32ToBool shadingRateCoarseSampleOrder)
instance Storable PhysicalDeviceShadingRateImageFeaturesNV where
sizeOf ~_ = 24
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceShadingRateImageFeaturesNV where
zero = PhysicalDeviceShadingRateImageFeaturesNV
zero
zero
-- | VkPhysicalDeviceShadingRateImagePropertiesNV - Structure describing
-- shading rate image limits that can be supported by an implementation
--
-- = Description
--
-- If the 'PhysicalDeviceShadingRateImagePropertiesNV' structure is
-- included in the @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2',
-- it is filled in with each corresponding implementation-dependent
-- property.
--
-- These properties are related to the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-shading-rate-image shading rate image>
-- feature.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'Vulkan.Core10.FundamentalTypes.Extent2D',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceShadingRateImagePropertiesNV = PhysicalDeviceShadingRateImagePropertiesNV
{ -- | #limits-shadingRateTexelSize# @shadingRateTexelSize@ indicates the width
-- and height of the portion of the framebuffer corresponding to each texel
-- in the shading rate image.
shadingRateTexelSize :: Extent2D
, -- | #limits-shadingRatePaletteSize# @shadingRatePaletteSize@ indicates the
-- maximum number of palette entries supported for the shading rate image.
shadingRatePaletteSize :: Word32
, -- | #limits-shadingRateMaxCoarseSamples# @shadingRateMaxCoarseSamples@
-- specifies the maximum number of coverage samples supported in a single
-- fragment. If the product of the fragment size derived from the base
-- shading rate and the number of coverage samples per pixel exceeds this
-- limit, the final shading rate will be adjusted so that its product does
-- not exceed the limit.
shadingRateMaxCoarseSamples :: Word32
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceShadingRateImagePropertiesNV)
#endif
deriving instance Show PhysicalDeviceShadingRateImagePropertiesNV
instance ToCStruct PhysicalDeviceShadingRateImagePropertiesNV where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceShadingRateImagePropertiesNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Extent2D)) (shadingRateTexelSize)
poke ((p `plusPtr` 24 :: Ptr Word32)) (shadingRatePaletteSize)
poke ((p `plusPtr` 28 :: Ptr Word32)) (shadingRateMaxCoarseSamples)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Extent2D)) (zero)
poke ((p `plusPtr` 24 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 28 :: Ptr Word32)) (zero)
f
instance FromCStruct PhysicalDeviceShadingRateImagePropertiesNV where
peekCStruct p = do
shadingRateTexelSize <- peekCStruct @Extent2D ((p `plusPtr` 16 :: Ptr Extent2D))
shadingRatePaletteSize <- peek @Word32 ((p `plusPtr` 24 :: Ptr Word32))
shadingRateMaxCoarseSamples <- peek @Word32 ((p `plusPtr` 28 :: Ptr Word32))
pure $ PhysicalDeviceShadingRateImagePropertiesNV
shadingRateTexelSize shadingRatePaletteSize shadingRateMaxCoarseSamples
instance Storable PhysicalDeviceShadingRateImagePropertiesNV where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceShadingRateImagePropertiesNV where
zero = PhysicalDeviceShadingRateImagePropertiesNV
zero
zero
zero
-- | VkCoarseSampleLocationNV - Structure specifying parameters controlling
-- shading rate image usage
--
-- == Valid Usage
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'CoarseSampleOrderCustomNV'
data CoarseSampleLocationNV = CoarseSampleLocationNV
{ -- | @pixelX@ is added to the x coordinate of the upper-leftmost pixel of
-- each fragment to identify the pixel containing the coverage sample.
--
-- #VUID-VkCoarseSampleLocationNV-pixelX-02078# @pixelX@ /must/ be less
-- than the width (in pixels) of the fragment
pixelX :: Word32
, -- | @pixelY@ is added to the y coordinate of the upper-leftmost pixel of
-- each fragment to identify the pixel containing the coverage sample.
--
-- #VUID-VkCoarseSampleLocationNV-pixelY-02079# @pixelY@ /must/ be less
-- than the height (in pixels) of the fragment
pixelY :: Word32
, -- | @sample@ is the number of the coverage sample in the pixel identified by
-- @pixelX@ and @pixelY@.
--
-- #VUID-VkCoarseSampleLocationNV-sample-02080# @sample@ /must/ be less
-- than the number of coverage samples in each pixel belonging to the
-- fragment
sample :: Word32
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (CoarseSampleLocationNV)
#endif
deriving instance Show CoarseSampleLocationNV
instance ToCStruct CoarseSampleLocationNV where
withCStruct x f = allocaBytes 12 $ \p -> pokeCStruct p x (f p)
pokeCStruct p CoarseSampleLocationNV{..} f = do
poke ((p `plusPtr` 0 :: Ptr Word32)) (pixelX)
poke ((p `plusPtr` 4 :: Ptr Word32)) (pixelY)
poke ((p `plusPtr` 8 :: Ptr Word32)) (sample)
f
cStructSize = 12
cStructAlignment = 4
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 4 :: Ptr Word32)) (zero)
poke ((p `plusPtr` 8 :: Ptr Word32)) (zero)
f
instance FromCStruct CoarseSampleLocationNV where
peekCStruct p = do
pixelX <- peek @Word32 ((p `plusPtr` 0 :: Ptr Word32))
pixelY <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32))
sample <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32))
pure $ CoarseSampleLocationNV
pixelX pixelY sample
instance Storable CoarseSampleLocationNV where
sizeOf ~_ = 12
alignment ~_ = 4
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero CoarseSampleLocationNV where
zero = CoarseSampleLocationNV
zero
zero
zero
-- | VkCoarseSampleOrderCustomNV - Structure specifying parameters
-- controlling shading rate image usage
--
-- = Description
--
-- The 'CoarseSampleOrderCustomNV' structure is used with a coverage sample
-- ordering type of 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV' to specify the
-- order of coverage samples for one combination of fragment width,
-- fragment height, and coverage sample count.
--
-- When using a custom sample ordering, element /j/ in @pSampleLocations@
-- specifies a specific pixel location and
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-multisampling-coverage-mask sample index>
-- that corresponds to
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-multisampling-coverage-mask coverage index>
-- /j/ in the multi-pixel fragment.
--
-- == Valid Usage
--
-- - #VUID-VkCoarseSampleOrderCustomNV-shadingRate-02073# @shadingRate@
-- /must/ be a shading rate that generates fragments with more than one
-- pixel
--
-- - #VUID-VkCoarseSampleOrderCustomNV-sampleCount-02074# @sampleCount@
-- /must/ correspond to a sample count enumerated in
-- 'Vulkan.Core10.Enums.SampleCountFlagBits.SampleCountFlags' whose
-- corresponding bit is set in
-- 'Vulkan.Core10.DeviceInitialization.PhysicalDeviceLimits'::@framebufferNoAttachmentsSampleCounts@
--
-- - #VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02075#
-- @sampleLocationCount@ /must/ be equal to the product of
-- @sampleCount@, the fragment width for @shadingRate@, and the
-- fragment height for @shadingRate@
--
-- - #VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-02076#
-- @sampleLocationCount@ /must/ be less than or equal to the value of
-- 'PhysicalDeviceShadingRateImagePropertiesNV'::@shadingRateMaxCoarseSamples@
--
-- - #VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-02077# The array
-- @pSampleLocations@ /must/ contain exactly one entry for every
-- combination of valid values for @pixelX@, @pixelY@, and @sample@ in
-- the structure 'CoarseSampleOrderCustomNV'
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkCoarseSampleOrderCustomNV-shadingRate-parameter#
-- @shadingRate@ /must/ be a valid 'ShadingRatePaletteEntryNV' value
--
-- - #VUID-VkCoarseSampleOrderCustomNV-pSampleLocations-parameter#
-- @pSampleLocations@ /must/ be a valid pointer to an array of
-- @sampleLocationCount@ 'CoarseSampleLocationNV' structures
--
-- - #VUID-VkCoarseSampleOrderCustomNV-sampleLocationCount-arraylength#
-- @sampleLocationCount@ /must/ be greater than @0@
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'CoarseSampleLocationNV',
-- 'PipelineViewportCoarseSampleOrderStateCreateInfoNV',
-- 'ShadingRatePaletteEntryNV', 'cmdSetCoarseSampleOrderNV'
data CoarseSampleOrderCustomNV = CoarseSampleOrderCustomNV
{ -- | @shadingRate@ is a shading rate palette entry that identifies the
-- fragment width and height for the combination of fragment area and
-- per-pixel coverage sample count to control.
shadingRate :: ShadingRatePaletteEntryNV
, -- | @sampleCount@ identifies the per-pixel coverage sample count for the
-- combination of fragment area and coverage sample count to control.
sampleCount :: Word32
, -- | @pSampleLocations@ is a pointer to an array of 'CoarseSampleLocationNV'
-- structures specifying the location of each sample in the custom
-- ordering.
sampleLocations :: Vector CoarseSampleLocationNV
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (CoarseSampleOrderCustomNV)
#endif
deriving instance Show CoarseSampleOrderCustomNV
instance ToCStruct CoarseSampleOrderCustomNV where
withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p)
pokeCStruct p CoarseSampleOrderCustomNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr ShadingRatePaletteEntryNV)) (shadingRate)
lift $ poke ((p `plusPtr` 4 :: Ptr Word32)) (sampleCount)
lift $ poke ((p `plusPtr` 8 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (sampleLocations)) :: Word32))
pPSampleLocations' <- ContT $ allocaBytes @CoarseSampleLocationNV ((Data.Vector.length (sampleLocations)) * 12)
lift $ Data.Vector.imapM_ (\i e -> poke (pPSampleLocations' `plusPtr` (12 * (i)) :: Ptr CoarseSampleLocationNV) (e)) (sampleLocations)
lift $ poke ((p `plusPtr` 16 :: Ptr (Ptr CoarseSampleLocationNV))) (pPSampleLocations')
lift $ f
cStructSize = 24
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr ShadingRatePaletteEntryNV)) (zero)
poke ((p `plusPtr` 4 :: Ptr Word32)) (zero)
f
instance FromCStruct CoarseSampleOrderCustomNV where
peekCStruct p = do
shadingRate <- peek @ShadingRatePaletteEntryNV ((p `plusPtr` 0 :: Ptr ShadingRatePaletteEntryNV))
sampleCount <- peek @Word32 ((p `plusPtr` 4 :: Ptr Word32))
sampleLocationCount <- peek @Word32 ((p `plusPtr` 8 :: Ptr Word32))
pSampleLocations <- peek @(Ptr CoarseSampleLocationNV) ((p `plusPtr` 16 :: Ptr (Ptr CoarseSampleLocationNV)))
pSampleLocations' <- generateM (fromIntegral sampleLocationCount) (\i -> peekCStruct @CoarseSampleLocationNV ((pSampleLocations `advancePtrBytes` (12 * (i)) :: Ptr CoarseSampleLocationNV)))
pure $ CoarseSampleOrderCustomNV
shadingRate sampleCount pSampleLocations'
instance Zero CoarseSampleOrderCustomNV where
zero = CoarseSampleOrderCustomNV
zero
zero
mempty
-- | VkPipelineViewportCoarseSampleOrderStateCreateInfoNV - Structure
-- specifying parameters controlling sample order in coarse fragments
--
-- = Description
--
-- If this structure is not present, @sampleOrderType@ is considered to be
-- 'COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV'.
--
-- If @sampleOrderType@ is 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV', the
-- coverage sample order used for any combination of fragment area and
-- coverage sample count not enumerated in @pCustomSampleOrders@ will be
-- identical to that used for 'COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV'.
--
-- If the pipeline was created with
-- 'Vulkan.Core10.Enums.DynamicState.DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV',
-- the contents of this structure (if present) are ignored, and the
-- coverage sample order is instead specified by
-- 'cmdSetCoarseSampleOrderNV'.
--
-- == Valid Usage
--
-- - #VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-sampleOrderType-02072#
-- If @sampleOrderType@ is not 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV',
-- @customSamplerOrderCount@ /must/ be @0@
--
-- - #VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-pCustomSampleOrders-02234#
-- The array @pCustomSampleOrders@ /must/ not contain two structures
-- with matching values for both the @shadingRate@ and @sampleCount@
-- members
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-sType-sType#
-- @sType@ /must/ be
-- 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV'
--
-- - #VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-sampleOrderType-parameter#
-- @sampleOrderType@ /must/ be a valid 'CoarseSampleOrderTypeNV' value
--
-- - #VUID-VkPipelineViewportCoarseSampleOrderStateCreateInfoNV-pCustomSampleOrders-parameter#
-- If @customSampleOrderCount@ is not @0@, @pCustomSampleOrders@ /must/
-- be a valid pointer to an array of @customSampleOrderCount@ valid
-- 'CoarseSampleOrderCustomNV' structures
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'CoarseSampleOrderCustomNV', 'CoarseSampleOrderTypeNV',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PipelineViewportCoarseSampleOrderStateCreateInfoNV = PipelineViewportCoarseSampleOrderStateCreateInfoNV
{ -- | @sampleOrderType@ specifies the mechanism used to order coverage samples
-- in fragments larger than one pixel.
sampleOrderType :: CoarseSampleOrderTypeNV
, -- | @pCustomSampleOrders@ is a pointer to an array of
-- @customSampleOrderCount@ 'CoarseSampleOrderCustomNV' structures, each
-- structure specifying the coverage sample order for a single combination
-- of fragment area and coverage sample count.
customSampleOrders :: Vector CoarseSampleOrderCustomNV
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PipelineViewportCoarseSampleOrderStateCreateInfoNV)
#endif
deriving instance Show PipelineViewportCoarseSampleOrderStateCreateInfoNV
instance ToCStruct PipelineViewportCoarseSampleOrderStateCreateInfoNV where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PipelineViewportCoarseSampleOrderStateCreateInfoNV{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
lift $ poke ((p `plusPtr` 16 :: Ptr CoarseSampleOrderTypeNV)) (sampleOrderType)
lift $ poke ((p `plusPtr` 20 :: Ptr Word32)) ((fromIntegral (Data.Vector.length $ (customSampleOrders)) :: Word32))
pPCustomSampleOrders' <- ContT $ allocaBytes @CoarseSampleOrderCustomNV ((Data.Vector.length (customSampleOrders)) * 24)
Data.Vector.imapM_ (\i e -> ContT $ pokeCStruct (pPCustomSampleOrders' `plusPtr` (24 * (i)) :: Ptr CoarseSampleOrderCustomNV) (e) . ($ ())) (customSampleOrders)
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr CoarseSampleOrderCustomNV))) (pPCustomSampleOrders')
lift $ f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr CoarseSampleOrderTypeNV)) (zero)
f
instance FromCStruct PipelineViewportCoarseSampleOrderStateCreateInfoNV where
peekCStruct p = do
sampleOrderType <- peek @CoarseSampleOrderTypeNV ((p `plusPtr` 16 :: Ptr CoarseSampleOrderTypeNV))
customSampleOrderCount <- peek @Word32 ((p `plusPtr` 20 :: Ptr Word32))
pCustomSampleOrders <- peek @(Ptr CoarseSampleOrderCustomNV) ((p `plusPtr` 24 :: Ptr (Ptr CoarseSampleOrderCustomNV)))
pCustomSampleOrders' <- generateM (fromIntegral customSampleOrderCount) (\i -> peekCStruct @CoarseSampleOrderCustomNV ((pCustomSampleOrders `advancePtrBytes` (24 * (i)) :: Ptr CoarseSampleOrderCustomNV)))
pure $ PipelineViewportCoarseSampleOrderStateCreateInfoNV
sampleOrderType pCustomSampleOrders'
instance Zero PipelineViewportCoarseSampleOrderStateCreateInfoNV where
zero = PipelineViewportCoarseSampleOrderStateCreateInfoNV
zero
mempty
-- | VkShadingRatePaletteEntryNV - Shading rate image palette entry types
--
-- = Description
--
-- The following table indicates the width and height (in pixels) of each
-- fragment generated using the indicated shading rate, as well as the
-- maximum number of fragment shader invocations launched for each
-- fragment. When processing regions of a primitive that have a shading
-- rate of 'SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV', no fragments
-- will be generated in that region.
--
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | Shading Rate | Width | Height | Invocations |
-- +=============================================================+=================+=================+=================+
-- | 'SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV' | 0 | 0 | 0 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV' | 1 | 1 | 16 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV' | 1 | 1 | 8 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV' | 1 | 1 | 4 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV' | 1 | 1 | 2 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV' | 1 | 1 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV' | 2 | 1 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV' | 1 | 2 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV' | 2 | 2 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV' | 4 | 2 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV' | 2 | 4 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
-- | 'SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV' | 4 | 4 | 1 |
-- +-------------------------------------------------------------+-----------------+-----------------+-----------------+
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'CoarseSampleOrderCustomNV', 'ShadingRatePaletteNV'
newtype ShadingRatePaletteEntryNV = ShadingRatePaletteEntryNV Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV = ShadingRatePaletteEntryNV 0
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV"
pattern SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV = ShadingRatePaletteEntryNV 1
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV"
pattern SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV = ShadingRatePaletteEntryNV 2
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV"
pattern SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV = ShadingRatePaletteEntryNV 3
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV"
pattern SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV = ShadingRatePaletteEntryNV 4
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV = ShadingRatePaletteEntryNV 5
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV = ShadingRatePaletteEntryNV 6
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV = ShadingRatePaletteEntryNV 7
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV = ShadingRatePaletteEntryNV 8
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV = ShadingRatePaletteEntryNV 9
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV = ShadingRatePaletteEntryNV 10
-- No documentation found for Nested "VkShadingRatePaletteEntryNV" "VK_SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV"
pattern SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV = ShadingRatePaletteEntryNV 11
{-# complete SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV,
SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV,
SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV,
SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV,
SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV,
SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV :: ShadingRatePaletteEntryNV #-}
conNameShadingRatePaletteEntryNV :: String
conNameShadingRatePaletteEntryNV = "ShadingRatePaletteEntryNV"
enumPrefixShadingRatePaletteEntryNV :: String
enumPrefixShadingRatePaletteEntryNV = "SHADING_RATE_PALETTE_ENTRY_"
showTableShadingRatePaletteEntryNV :: [(ShadingRatePaletteEntryNV, String)]
showTableShadingRatePaletteEntryNV =
[ (SHADING_RATE_PALETTE_ENTRY_NO_INVOCATIONS_NV , "NO_INVOCATIONS_NV")
, (SHADING_RATE_PALETTE_ENTRY_16_INVOCATIONS_PER_PIXEL_NV , "16_INVOCATIONS_PER_PIXEL_NV")
, (SHADING_RATE_PALETTE_ENTRY_8_INVOCATIONS_PER_PIXEL_NV , "8_INVOCATIONS_PER_PIXEL_NV")
, (SHADING_RATE_PALETTE_ENTRY_4_INVOCATIONS_PER_PIXEL_NV , "4_INVOCATIONS_PER_PIXEL_NV")
, (SHADING_RATE_PALETTE_ENTRY_2_INVOCATIONS_PER_PIXEL_NV , "2_INVOCATIONS_PER_PIXEL_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_PIXEL_NV , "1_INVOCATION_PER_PIXEL_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X1_PIXELS_NV, "1_INVOCATION_PER_2X1_PIXELS_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_1X2_PIXELS_NV, "1_INVOCATION_PER_1X2_PIXELS_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X2_PIXELS_NV, "1_INVOCATION_PER_2X2_PIXELS_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X2_PIXELS_NV, "1_INVOCATION_PER_4X2_PIXELS_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_2X4_PIXELS_NV, "1_INVOCATION_PER_2X4_PIXELS_NV")
, (SHADING_RATE_PALETTE_ENTRY_1_INVOCATION_PER_4X4_PIXELS_NV, "1_INVOCATION_PER_4X4_PIXELS_NV")
]
instance Show ShadingRatePaletteEntryNV where
showsPrec = enumShowsPrec enumPrefixShadingRatePaletteEntryNV
showTableShadingRatePaletteEntryNV
conNameShadingRatePaletteEntryNV
(\(ShadingRatePaletteEntryNV x) -> x)
(showsPrec 11)
instance Read ShadingRatePaletteEntryNV where
readPrec = enumReadPrec enumPrefixShadingRatePaletteEntryNV
showTableShadingRatePaletteEntryNV
conNameShadingRatePaletteEntryNV
ShadingRatePaletteEntryNV
-- | VkCoarseSampleOrderTypeNV - Shading rate image sample ordering types
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_shading_rate_image VK_NV_shading_rate_image>,
-- 'PipelineViewportCoarseSampleOrderStateCreateInfoNV',
-- 'cmdSetCoarseSampleOrderNV'
newtype CoarseSampleOrderTypeNV = CoarseSampleOrderTypeNV Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV' specifies that coverage samples
-- will be ordered in an implementation-dependent manner.
pattern COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV = CoarseSampleOrderTypeNV 0
-- | 'COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV' specifies that coverage samples
-- will be ordered according to the array of custom orderings provided in
-- either the @pCustomSampleOrders@ member of
-- 'PipelineViewportCoarseSampleOrderStateCreateInfoNV' or the
-- @pCustomSampleOrders@ member of 'cmdSetCoarseSampleOrderNV'.
pattern COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV = CoarseSampleOrderTypeNV 1
-- | 'COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV' specifies that coverage
-- samples will be ordered sequentially, sorted first by pixel coordinate
-- (in row-major order) and then by
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-multisampling-coverage-mask sample index>.
pattern COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV = CoarseSampleOrderTypeNV 2
-- | 'COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV' specifies that coverage
-- samples will be ordered sequentially, sorted first by
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#primsrast-multisampling-coverage-mask sample index>
-- and then by pixel coordinate (in row-major order).
pattern COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV = CoarseSampleOrderTypeNV 3
{-# complete COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV,
COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV,
COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV,
COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV :: CoarseSampleOrderTypeNV #-}
conNameCoarseSampleOrderTypeNV :: String
conNameCoarseSampleOrderTypeNV = "CoarseSampleOrderTypeNV"
enumPrefixCoarseSampleOrderTypeNV :: String
enumPrefixCoarseSampleOrderTypeNV = "COARSE_SAMPLE_ORDER_TYPE_"
showTableCoarseSampleOrderTypeNV :: [(CoarseSampleOrderTypeNV, String)]
showTableCoarseSampleOrderTypeNV =
[ (COARSE_SAMPLE_ORDER_TYPE_DEFAULT_NV , "DEFAULT_NV")
, (COARSE_SAMPLE_ORDER_TYPE_CUSTOM_NV , "CUSTOM_NV")
, (COARSE_SAMPLE_ORDER_TYPE_PIXEL_MAJOR_NV , "PIXEL_MAJOR_NV")
, (COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV, "SAMPLE_MAJOR_NV")
]
instance Show CoarseSampleOrderTypeNV where
showsPrec = enumShowsPrec enumPrefixCoarseSampleOrderTypeNV
showTableCoarseSampleOrderTypeNV
conNameCoarseSampleOrderTypeNV
(\(CoarseSampleOrderTypeNV x) -> x)
(showsPrec 11)
instance Read CoarseSampleOrderTypeNV where
readPrec = enumReadPrec enumPrefixCoarseSampleOrderTypeNV
showTableCoarseSampleOrderTypeNV
conNameCoarseSampleOrderTypeNV
CoarseSampleOrderTypeNV
type NV_SHADING_RATE_IMAGE_SPEC_VERSION = 3
-- No documentation found for TopLevel "VK_NV_SHADING_RATE_IMAGE_SPEC_VERSION"
pattern NV_SHADING_RATE_IMAGE_SPEC_VERSION :: forall a . Integral a => a
pattern NV_SHADING_RATE_IMAGE_SPEC_VERSION = 3
type NV_SHADING_RATE_IMAGE_EXTENSION_NAME = "VK_NV_shading_rate_image"
-- No documentation found for TopLevel "VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME"
pattern NV_SHADING_RATE_IMAGE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern NV_SHADING_RATE_IMAGE_EXTENSION_NAME = "VK_NV_shading_rate_image"
|
expipiplus1/vulkan
|
src/Vulkan/Extensions/VK_NV_shading_rate_image.hs
|
bsd-3-clause
| 84,841
| 2
| 19
| 16,152
| 8,214
| 4,910
| 3,304
| -1
| -1
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[HsLit]{Abstract syntax: source-language literals}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
module HsLit where
#include "HsVersions.h"
import {-# SOURCE #-} HsExpr( SyntaxExpr, pprExpr )
import BasicTypes ( FractionalLit(..),SourceText )
import Type ( Type )
import Outputable
import FastString
import PlaceHolder ( PostTc,PostRn,DataId )
import Data.ByteString (ByteString)
import Data.Data hiding ( Fixity )
{-
************************************************************************
* *
\subsection[HsLit]{Literals}
* *
************************************************************************
-}
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data HsLit
= HsChar SourceText Char -- Character
| HsCharPrim SourceText Char -- Unboxed character
| HsString SourceText FastString -- String
| HsStringPrim SourceText ByteString -- Packed bytes
| HsInt SourceText Integer -- Genuinely an Int; arises from
-- TcGenDeriv, and from TRANSLATION
| HsIntPrim SourceText Integer -- literal Int#
| HsWordPrim SourceText Integer -- literal Word#
| HsInt64Prim SourceText Integer -- literal Int64#
| HsWord64Prim SourceText Integer -- literal Word64#
| HsInteger SourceText Integer Type -- Genuinely an integer; arises only
-- from TRANSLATION (overloaded
-- literals are done with HsOverLit)
| HsRat FractionalLit Type -- Genuinely a rational; arises only from
-- TRANSLATION (overloaded literals are
-- done with HsOverLit)
| HsFloatPrim FractionalLit -- Unboxed Float
| HsDoublePrim FractionalLit -- Unboxed Double
deriving (Data, Typeable)
instance Eq HsLit where
(HsChar _ x1) == (HsChar _ x2) = x1==x2
(HsCharPrim _ x1) == (HsCharPrim _ x2) = x1==x2
(HsString _ x1) == (HsString _ x2) = x1==x2
(HsStringPrim _ x1) == (HsStringPrim _ x2) = x1==x2
(HsInt _ x1) == (HsInt _ x2) = x1==x2
(HsIntPrim _ x1) == (HsIntPrim _ x2) = x1==x2
(HsWordPrim _ x1) == (HsWordPrim _ x2) = x1==x2
(HsInt64Prim _ x1) == (HsInt64Prim _ x2) = x1==x2
(HsWord64Prim _ x1) == (HsWord64Prim _ x2) = x1==x2
(HsInteger _ x1 _) == (HsInteger _ x2 _) = x1==x2
(HsRat x1 _) == (HsRat x2 _) = x1==x2
(HsFloatPrim x1) == (HsFloatPrim x2) = x1==x2
(HsDoublePrim x1) == (HsDoublePrim x2) = x1==x2
_ == _ = False
data HsOverLit id -- An overloaded literal
= OverLit {
ol_val :: OverLitVal,
ol_rebindable :: PostRn id Bool, -- Note [ol_rebindable]
ol_witness :: SyntaxExpr id, -- Note [Overloaded literal witnesses]
ol_type :: PostTc id Type }
deriving (Typeable)
deriving instance (DataId id) => Data (HsOverLit id)
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data OverLitVal
= HsIntegral !SourceText !Integer -- Integer-looking literals;
| HsFractional !FractionalLit -- Frac-looking literals
| HsIsString !SourceText !FastString -- String-looking literals
deriving (Data, Typeable)
overLitType :: HsOverLit a -> PostTc a Type
overLitType = ol_type
{-
Note [ol_rebindable]
~~~~~~~~~~~~~~~~~~~~
The ol_rebindable field is True if this literal is actually
using rebindable syntax. Specifically:
False iff ol_witness is the standard one
True iff ol_witness is non-standard
Equivalently it's True if
a) RebindableSyntax is on
b) the witness for fromInteger/fromRational/fromString
that happens to be in scope isn't the standard one
Note [Overloaded literal witnesses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Before* type checking, the SyntaxExpr in an HsOverLit is the
name of the coercion function, 'fromInteger' or 'fromRational'.
*After* type checking, it is a witness for the literal, such as
(fromInteger 3) or lit_78
This witness should replace the literal.
This dual role is unusual, because we're replacing 'fromInteger' with
a call to fromInteger. Reason: it allows commoning up of the fromInteger
calls, which wouldn't be possible if the desguarar made the application.
The PostTcType in each branch records the type the overload literal is
found to have.
-}
-- Comparison operations are needed when grouping literals
-- for compiling pattern-matching (module MatchLit)
instance Eq (HsOverLit id) where
(OverLit {ol_val = val1}) == (OverLit {ol_val=val2}) = val1 == val2
instance Eq OverLitVal where
(HsIntegral _ i1) == (HsIntegral _ i2) = i1 == i2
(HsFractional f1) == (HsFractional f2) = f1 == f2
(HsIsString _ s1) == (HsIsString _ s2) = s1 == s2
_ == _ = False
instance Ord (HsOverLit id) where
compare (OverLit {ol_val=val1}) (OverLit {ol_val=val2}) = val1 `compare` val2
instance Ord OverLitVal where
compare (HsIntegral _ i1) (HsIntegral _ i2) = i1 `compare` i2
compare (HsIntegral _ _) (HsFractional _) = LT
compare (HsIntegral _ _) (HsIsString _ _) = LT
compare (HsFractional f1) (HsFractional f2) = f1 `compare` f2
compare (HsFractional _) (HsIntegral _ _) = GT
compare (HsFractional _) (HsIsString _ _) = LT
compare (HsIsString _ s1) (HsIsString _ s2) = s1 `compare` s2
compare (HsIsString _ _) (HsIntegral _ _) = GT
compare (HsIsString _ _) (HsFractional _) = GT
instance Outputable HsLit where
ppr (HsChar _ c) = pprHsChar c
ppr (HsCharPrim _ c) = pprPrimChar c
ppr (HsString _ s) = pprHsString s
ppr (HsStringPrim _ s) = pprHsBytes s
ppr (HsInt _ i) = integer i
ppr (HsInteger _ i _) = integer i
ppr (HsRat f _) = ppr f
ppr (HsFloatPrim f) = ppr f <> primFloatSuffix
ppr (HsDoublePrim d) = ppr d <> primDoubleSuffix
ppr (HsIntPrim _ i) = pprPrimInt i
ppr (HsWordPrim _ w) = pprPrimWord w
ppr (HsInt64Prim _ i) = pprPrimInt64 i
ppr (HsWord64Prim _ w) = pprPrimWord64 w
-- in debug mode, print the expression that it's resolved to, too
instance OutputableBndr id => Outputable (HsOverLit id) where
ppr (OverLit {ol_val=val, ol_witness=witness})
= ppr val <+> (ifPprDebug (parens (pprExpr witness)))
instance Outputable OverLitVal where
ppr (HsIntegral _ i) = integer i
ppr (HsFractional f) = ppr f
ppr (HsIsString _ s) = pprHsString s
-- | pmPprHsLit pretty prints literals and is used when pretty printing pattern
-- match warnings. All are printed the same (i.e., without hashes if they are
-- primitive and not wrapped in constructors if they are boxed). This happens
-- mainly for too reasons:
-- * We do not want to expose their internal representation
-- * The warnings become too messy
pmPprHsLit :: HsLit -> SDoc
pmPprHsLit (HsChar _ c) = pprHsChar c
pmPprHsLit (HsCharPrim _ c) = pprHsChar c
pmPprHsLit (HsString _ s) = pprHsString s
pmPprHsLit (HsStringPrim _ s) = pprHsBytes s
pmPprHsLit (HsInt _ i) = integer i
pmPprHsLit (HsIntPrim _ i) = integer i
pmPprHsLit (HsWordPrim _ w) = integer w
pmPprHsLit (HsInt64Prim _ i) = integer i
pmPprHsLit (HsWord64Prim _ w) = integer w
pmPprHsLit (HsInteger _ i _) = integer i
pmPprHsLit (HsRat f _) = ppr f
pmPprHsLit (HsFloatPrim f) = ppr f
pmPprHsLit (HsDoublePrim d) = ppr d
|
gridaphobe/ghc
|
compiler/hsSyn/HsLit.hs
|
bsd-3-clause
| 8,140
| 0
| 12
| 2,178
| 1,903
| 985
| 918
| 125
| 1
|
module Exercises96 where
-- 1.
-- recursively break up the string and build up the list
-- recursion stops when the input is empty. empty string returns empty list
myWords :: String -> [String]
myWords "" = []
myWords input = beg : end
where
notSpace = \x -> x /= ' '
isSpace = \x -> x == ' '
beg = takeWhile notSpace input
end = myWords . dropWhile isSpace . dropWhile notSpace $ input
-- 2, 3.
-- module PoemLines
|
pdmurray/haskell-book-ex
|
src/ch9/Exercises9.6.hs
|
bsd-3-clause
| 455
| 0
| 10
| 122
| 106
| 59
| 47
| 8
| 1
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.CopyTexture
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All raw functions from the EXT_copy_texture extension, see
-- <http://www.opengl.org/registry/specs/EXT/copy_texture.txt>.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.CopyTexture (
-- * Functions
glCopyTexImage1D,
glCopyTexImage2D,
glCopyTexSubImage1D,
glCopyTexSubImage2D,
glCopyTexSubImage3D,
) where
import Graphics.Rendering.OpenGL.Raw.Core32
|
mfpi/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/EXT/CopyTexture.hs
|
bsd-3-clause
| 771
| 0
| 4
| 102
| 51
| 41
| 10
| 7
| 0
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE UndecidableInstances #-}
#if defined(TRUSTWORTHY) && !defined(SAFE)
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Classes
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : provisional
-- Portability : Rank2Types
--
----------------------------------------------------------------------------
module Control.Lens.Classes
(
-- * Getters
Gettable(..)
, noEffect
-- * Actions
, Effective(..)
-- * Setters
, Settable(..)
-- * Prisms
, Prismatic(..)
-- * Indexable
, Indexable(..)
) where
import Control.Applicative
import Control.Applicative.Backwards (Backwards(..))
import Control.Monad (liftM)
import Data.Functor.Compose (Compose(..))
import Data.Functor.Identity (Identity(..))
import Data.Monoid (Dual(..))
import Data.Profunctor
#ifndef SAFE
import Unsafe.Coerce (unsafeCoerce)
#endif
#ifndef SAFE
#define UNSAFELY(x) unsafeCoerce
#else
#define UNSAFELY(f) (\g -> g `seq` \x -> (f) (g x))
#endif
-------------------------------------------------------------------------------
-- Gettables & Accessors
-------------------------------------------------------------------------------
-- | Generalizing 'Const' so we can apply simple 'Applicative'
-- transformations to it and so we can get nicer error messages
--
-- A 'Gettable' 'Functor' ignores its argument, which it carries solely as a
-- phantom type parameter.
--
-- To ensure this, an instance of 'Gettable' is required to satisfy:
--
-- @'id' = 'fmap' f = 'coerce'@
--
-- Which is equivalent to making a @'Gettable' f@ an \"anyvariant\" functor.
--
class Functor f => Gettable f where
-- | Replace the phantom type argument.
coerce :: f a -> f b
instance Gettable (Const r) where
coerce (Const m) = Const m
instance Gettable f => Gettable (Backwards f) where
coerce = Backwards . coerce . forwards
instance (Functor f, Gettable g) => Gettable (Compose f g) where
coerce = Compose . fmap coerce . getCompose
-- | The 'mempty' equivalent for a 'Gettable' 'Applicative' 'Functor'.
noEffect :: (Applicative f, Gettable f) => f a
noEffect = coerce $ pure ()
{-# INLINE noEffect #-}
-------------------------------------------------------------------------------
-- Programming with Effects
-------------------------------------------------------------------------------
-- | An 'Effective' 'Functor' ignores its argument and is isomorphic to a 'Monad' wrapped around a value.
--
-- That said, the 'Monad' is possibly rather unrelated to any 'Applicative' structure.
class (Monad m, Gettable f) => Effective m r f | f -> m r where
effective :: m r -> f a
ineffective :: f a -> m r
instance Effective m r f => Effective m (Dual r) (Backwards f) where
effective = Backwards . effective . liftM getDual
ineffective = liftM Dual . ineffective . forwards
-----------------------------------------------------------------------------
-- Settable
-----------------------------------------------------------------------------
-- | Anything 'Settable' must be isomorphic to the 'Identity' 'Functor'.
class Applicative f => Settable f where
untainted :: f a -> a
untaintedDot :: (a -> f b) -> a -> b
untaintedDot g = g `seq` \x -> untainted (g x)
taintedDot :: (a -> b) -> a -> f b
taintedDot g = g `seq` \x -> pure (g x)
-- | so you can pass our a 'Control.Lens.Setter.Setter' into combinators from other lens libraries
instance Settable Identity where
untainted = runIdentity
{-# INLINE untainted #-}
untaintedDot = UNSAFELY(runIdentity)
{-# INLINE untaintedDot #-}
taintedDot = UNSAFELY(Identity)
{-# INLINE taintedDot #-}
-- | 'Control.Lens.Fold.backwards'
instance Settable f => Settable (Backwards f) where
untainted = untaintedDot forwards
{-# INLINE untainted #-}
instance (Settable f, Settable g) => Settable (Compose f g) where
untainted = untaintedDot (untaintedDot getCompose)
{-# INLINE untainted #-}
-----------------------------------------------------------------------------
-- Prism Internals
-----------------------------------------------------------------------------
class Profunctor p => Prismatic p where
prismatic :: Applicative f => (s -> Either t a) -> p a (f t) -> p s (f t)
instance Prismatic (->) where
prismatic seta aft = either pure aft . seta
{-# INLINE prismatic #-}
-----------------------------------------------------------------------------
-- Indexed Internals
-----------------------------------------------------------------------------
-- | This class permits overloading of function application for things that
-- also admit a notion of a key or index.
class Profunctor p => Indexable i p where
-- | Build a function from an 'Indexed' function
indexed :: p a b -> i -> a -> b
instance Indexable i (->) where
indexed = const
{-# INLINE indexed #-}
|
np/lens
|
src/Control/Lens/Classes.hs
|
bsd-3-clause
| 5,144
| 0
| 12
| 816
| 921
| 521
| 400
| 68
| 1
|
x = y where
y = 10
|
itchyny/vim-haskell-indent
|
test/where/no_newline_where.out.hs
|
mit
| 27
| 1
| 5
| 15
| 16
| 7
| 9
| 2
| 1
|
{- DATX02-17-26, automated assessment of imperative programs.
- Copyright, 2017, see AUTHORS.md.
-
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-}
-- | Test for eliminating redundant blocks and statements
module Norm.ForIndexCLTE (
allTests
) where
import Norm.NormTestUtil
import Norm.ForIndexConstLessThanEq
normalizers :: NormalizerCU
normalizers = [ normForIndexCLTE ]
allTests :: TestTree
allTests = normTestsDir "Norm.ForIndexCLTE" "ForIndexCLTE" [normalizers]
|
DATX02-17-26/DATX02-17-26
|
Test/Norm/ForIndexCLTE.hs
|
gpl-2.0
| 1,154
| 0
| 6
| 204
| 56
| 34
| 22
| 8
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EFS.Waiters
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.EFS.Waiters where
import Network.AWS.EFS.Types
import Network.AWS.Prelude
import Network.AWS.Waiter
|
fmapfmapfmap/amazonka
|
amazonka-efs/gen/Network/AWS/EFS/Waiters.hs
|
mpl-2.0
| 612
| 0
| 4
| 122
| 39
| 31
| 8
| 7
| 0
|
{-
Copyright 2012 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Plush.Job.History (
History,
HistoryFile,
initHistory,
startHistory,
writeHistory,
writeOutput,
endHistory,
getAllHistory,
getHistoryOutput,
) where
import qualified Control.Exception as Exception
import Data.Aeson (encode, FromJSON, fromJSON, Result(..), ToJSON)
import Data.Maybe (mapMaybe)
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.Encoding as LT
import Data.Time.Clock
import Data.Time.Format
import qualified Data.Traversable as TR
import System.FilePath ((</>), splitExtension)
import System.Locale
import System.Posix
import Plush.Job.Output
import Plush.Job.Types
import Plush.Run
import Plush.Run.Posix (getDirectoryContents, write)
import Plush.Run.Posix.Utilities (createPath)
import Plush.Run.ShellExec (getVar)
data History = History { histDir :: Maybe FilePath }
data HistoryFile = HistoryFile { hfCmd :: Maybe Fd, hfOut :: Maybe Fd }
initHistory :: Runner -> IO History
initHistory runner = do
(home, _) <- run (getVar "HOME") runner
hdir <- TR.mapM mkHistDir home `catchAllAs` Nothing
return $ History hdir
-- TODO: should return latest time stamp in directory
where
mkHistDir h = do
let hdir = h </> ".plush/history"
createPath hdir ownerModes
return hdir
startHistory :: CommandRequest -> History -> IO (History, HistoryFile)
startHistory (CommandRequest _ True (CommandItem _cmd))
h@(History (Just hdir)) = do
prefix <- prefixString
next <- findFree prefix ".cmd" (0 :: Int)
cmdFd <- openFd (next ++ ".cmd") ReadWrite (Just ownerRWMode) defaultFileFlags
outFd <- openFd (next ++ ".out") ReadWrite (Just ownerRWMode) defaultFileFlags
return (h, HistoryFile (Just cmdFd) (Just outFd))
where
findFree prefix suffix n = do
let name = hdir </> prefix ++ show n
let probe = name ++ suffix
exists <- (getFileStatus probe >> return True) `catchAllAs` False
-- TODO: should check prefixes
if exists
then findFree prefix suffix (n + 1)
else return name -- TODO: add on command text
ownerRWMode = ownerReadMode `unionFileModes` ownerWriteMode
startHistory _ h = return (h, HistoryFile Nothing Nothing)
prefixString :: IO String
prefixString = do
t <- getCurrentTime
return $ formatTime defaultTimeLocale "%Y%m%d.%H%M" t ++ "."
writeHistory :: HistoryFile -> HistoryItem -> IO ()
writeHistory = writeJson . hfCmd
writeOutput :: HistoryFile -> OutputItem -> IO ()
writeOutput = writeJson . hfOut
writeJson :: (ToJSON a) => Maybe Fd -> a -> IO ()
writeJson mfd s = maybe (return ()) writeJson' mfd
where
writeJson' fd = write fd (encode s) >> write fd nl
nl = LT.encodeUtf8 $ LT.pack "\n"
endHistory :: HistoryFile -> IO ()
endHistory hf = close (hfCmd hf) >> close (hfOut hf)
where
close (Just fd) = closeFd fd `catchAllAs` ()
close Nothing = return ()
-- | Return all of history. For now... uhm, yeah, simplest thing that could
-- possibly work.
getAllHistory :: History -> IO [ReportOne HistoryItem]
getAllHistory h = case (histDir h) of
Nothing -> return []
Just hdir -> do
histFiles <- mapMaybe cmdFileName `fmap` getDirectoryContents hdir
concat `fmap` mapM (readJsonFile hdir ".cmd") histFiles
where
cmdFileName f = let (j,e) = splitExtension f in
if e == ".cmd" then Just j else Nothing
-- | Return the output for selected history jobs
getHistoryOutput :: [ JobName ] -> History -> IO [ ReportOne HistoryItem ]
getHistoryOutput jobs h = case (histDir h) of
Nothing -> return []
Just hdir -> concat `fmap` mapM (readHistoryOutput hdir) jobs
where
readHistoryOutput hdir j = do
os <- readJsonFile hdir ".out" j
return $ os ++ [ReportOne j HiEndOfOutput]
readJsonFile :: (FromJSON a) =>
FilePath -> FilePath -> String -> IO [ReportOne a]
readJsonFile hdir ext j = (`catchAllAs` []) $ do
fd <- openFd (hdir </> j ++ ext) ReadOnly Nothing defaultFileFlags
jsons <- outputStreamJson fd >>= getAvailable
closeFd fd
return $ map (ReportOne j) . successes . map fromJSON $ jsons
where
successes [] = []
successes (Success a : ps) = a : successes ps
successes (Error _ : ps) = successes ps
catchAllAs :: IO a -> a -> IO a
catchAllAs act def = act `Exception.catch` ignore def
where
-- TODO: catch something more specific
ignore :: a -> Exception.SomeException -> IO a
ignore = const . return
|
kustomzone/plush
|
src/Plush/Job/History.hs
|
apache-2.0
| 5,098
| 0
| 14
| 1,119
| 1,489
| 774
| 715
| 100
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import GitHub.Data.Id (Id (..))
import qualified GitHub.Data.DeployKeys as DK
import qualified GitHub.Endpoints.Repos.DeployKeys as DK
import qualified GitHub.Auth as Auth
main :: IO ()
main = do
let auth = Auth.OAuth "auth_token"
eDeployKey <- DK.deployKeyFor' auth "your_owner" "your_repo" (Id 18528451)
case eDeployKey of
(Left err) -> putStrLn $ "Error: " ++ (show err)
(Right deployKey) -> putStrLn $ formatRepoDeployKey deployKey
formatRepoDeployKey :: DK.RepoDeployKey -> String
formatRepoDeployKey = show
|
jwiegley/github
|
samples/Repos/DeployKeys/ShowDeployKey.hs
|
bsd-3-clause
| 592
| 0
| 12
| 94
| 173
| 97
| 76
| 15
| 2
|
-- | A library to do stuff.
module Lib
(
ourAdd
) where
-- | Add two 'Int' values.
ourAdd :: Int -- ^ left
-> Int -- ^ right
-> Int -- ^ sum
ourAdd x y = x + y
|
FranklinChen/stack-template-demo
|
src/Lib.hs
|
bsd-3-clause
| 192
| 0
| 6
| 74
| 41
| 25
| 16
| 7
| 1
|
-- |
-- Module : Crypto.PubKey.Ed448
-- License : BSD-style
-- Maintainer : Olivier Chéron <olivier.cheron@gmail.com>
-- Stability : experimental
-- Portability : unknown
--
-- Ed448 support
--
-- Internally uses Decaf point compression to omit the cofactor
-- and implementation by Mike Hamburg. Externally API and
-- data types are compatible with the encoding specified in RFC 8032.
--
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Crypto.PubKey.Ed448
( SecretKey
, PublicKey
, Signature
-- * Size constants
, publicKeySize
, secretKeySize
, signatureSize
-- * Smart constructors
, signature
, publicKey
, secretKey
-- * Methods
, toPublic
, sign
, verify
, generateSecretKey
) where
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Crypto.Error
import Crypto.Internal.ByteArray (ByteArrayAccess, Bytes,
ScrubbedBytes, withByteArray)
import qualified Crypto.Internal.ByteArray as B
import Crypto.Internal.Compat
import Crypto.Internal.Imports
import Crypto.Random
-- | An Ed448 Secret key
newtype SecretKey = SecretKey ScrubbedBytes
deriving (Show,Eq,ByteArrayAccess,NFData)
-- | An Ed448 public key
newtype PublicKey = PublicKey Bytes
deriving (Show,Eq,ByteArrayAccess,NFData)
-- | An Ed448 signature
newtype Signature = Signature Bytes
deriving (Show,Eq,ByteArrayAccess,NFData)
-- | Try to build a public key from a bytearray
publicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKey
publicKey bs
| B.length bs == publicKeySize =
CryptoPassed $ PublicKey $ B.copyAndFreeze bs (\_ -> return ())
| otherwise =
CryptoFailed $ CryptoError_PublicKeySizeInvalid
-- | Try to build a secret key from a bytearray
secretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKey
secretKey bs
| B.length bs == secretKeySize = unsafeDoIO $ withByteArray bs initialize
| otherwise = CryptoFailed CryptoError_SecretKeyStructureInvalid
where
initialize inp = do
valid <- isValidPtr inp
if valid
then (CryptoPassed . SecretKey) <$> B.copy bs (\_ -> return ())
else return $ CryptoFailed CryptoError_SecretKeyStructureInvalid
isValidPtr _ =
return True
{-# NOINLINE secretKey #-}
-- | Try to build a signature from a bytearray
signature :: ByteArrayAccess ba => ba -> CryptoFailable Signature
signature bs
| B.length bs == signatureSize =
CryptoPassed $ Signature $ B.copyAndFreeze bs (\_ -> return ())
| otherwise =
CryptoFailed CryptoError_SecretKeyStructureInvalid
-- | Create a public key from a secret key
toPublic :: SecretKey -> PublicKey
toPublic (SecretKey sec) = PublicKey <$>
B.allocAndFreeze publicKeySize $ \result ->
withByteArray sec $ \psec ->
decaf_ed448_derive_public_key result psec
{-# NOINLINE toPublic #-}
-- | Sign a message using the key pair
sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signature
sign secret public message =
Signature $ B.allocAndFreeze signatureSize $ \sig ->
withByteArray secret $ \sec ->
withByteArray public $ \pub ->
withByteArray message $ \msg ->
decaf_ed448_sign sig sec pub msg (fromIntegral msgLen) 0 no_context 0
where
!msgLen = B.length message
-- | Verify a message
verify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Bool
verify public message signatureVal = unsafeDoIO $
withByteArray signatureVal $ \sig ->
withByteArray public $ \pub ->
withByteArray message $ \msg -> do
r <- decaf_ed448_verify sig pub msg (fromIntegral msgLen) 0 no_context 0
return (r /= 0)
where
!msgLen = B.length message
-- | Generate a secret key
generateSecretKey :: MonadRandom m => m SecretKey
generateSecretKey = SecretKey <$> getRandomBytes secretKeySize
-- | A public key is 57 bytes
publicKeySize :: Int
publicKeySize = 57
-- | A secret key is 57 bytes
secretKeySize :: Int
secretKeySize = 57
-- | A signature is 114 bytes
signatureSize :: Int
signatureSize = 114
no_context :: Ptr Word8
no_context = nullPtr -- not supported yet
foreign import ccall "cryptonite_decaf_ed448_derive_public_key"
decaf_ed448_derive_public_key :: Ptr PublicKey -- public key
-> Ptr SecretKey -- secret key
-> IO ()
foreign import ccall "cryptonite_decaf_ed448_sign"
decaf_ed448_sign :: Ptr Signature -- signature
-> Ptr SecretKey -- secret
-> Ptr PublicKey -- public
-> Ptr Word8 -- message
-> CSize -- message len
-> Word8 -- prehashed
-> Ptr Word8 -- context
-> Word8 -- context len
-> IO ()
foreign import ccall "cryptonite_decaf_ed448_verify"
decaf_ed448_verify :: Ptr Signature -- signature
-> Ptr PublicKey -- public
-> Ptr Word8 -- message
-> CSize -- message len
-> Word8 -- prehashed
-> Ptr Word8 -- context
-> Word8 -- context len
-> IO CInt
|
vincenthz/cryptonite
|
Crypto/PubKey/Ed448.hs
|
bsd-3-clause
| 5,558
| 0
| 16
| 1,679
| 1,091
| 579
| 512
| 111
| 2
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>Access Control Testing | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/accessControl/src/main/javahelp/org/zaproxy/zap/extension/accessControl/resources/help_ro_RO/helpset_ro_RO.hs
|
apache-2.0
| 776
| 63
| 53
| 120
| 337
| 170
| 167
| -1
| -1
|
module RegAlloc.Linear.Stats (
binSpillReasons,
countRegRegMovesNat,
pprStats
)
where
import RegAlloc.Linear.Base
import RegAlloc.Liveness
import Instruction
import UniqFM
import Outputable
import Data.List
import State
-- | Build a map of how many times each reg was alloced, clobbered, loaded etc.
binSpillReasons
:: [SpillReason] -> UniqFM [Int]
binSpillReasons reasons
= addListToUFM_C
(zipWith (+))
emptyUFM
(map (\reason -> case reason of
SpillAlloc r -> (r, [1, 0, 0, 0, 0])
SpillClobber r -> (r, [0, 1, 0, 0, 0])
SpillLoad r -> (r, [0, 0, 1, 0, 0])
SpillJoinRR r -> (r, [0, 0, 0, 1, 0])
SpillJoinRM r -> (r, [0, 0, 0, 0, 1])) reasons)
-- | Count reg-reg moves remaining in this code.
countRegRegMovesNat
:: Instruction instr
=> NatCmmDecl statics instr -> Int
countRegRegMovesNat cmm
= execState (mapGenBlockTopM countBlock cmm) 0
where
countBlock b@(BasicBlock _ instrs)
= do mapM_ countInstr instrs
return b
countInstr instr
| Just _ <- takeRegRegMoveInstr instr
= do modify (+ 1)
return instr
| otherwise
= return instr
-- | Pretty print some RegAllocStats
pprStats
:: Instruction instr
=> [NatCmmDecl statics instr] -> [RegAllocStats] -> SDoc
pprStats code statss
= let -- sum up all the instrs inserted by the spiller
spills = foldl' (plusUFM_C (zipWith (+)))
emptyUFM
$ map ra_spillInstrs statss
spillTotals = foldl' (zipWith (+))
[0, 0, 0, 0, 0]
$ eltsUFM spills
-- count how many reg-reg-moves remain in the code
moves = sum $ map countRegRegMovesNat code
pprSpill (reg, spills)
= parens $ (hcat $ punctuate (text ", ") (doubleQuotes (ppr reg) : map ppr spills))
in ( text "-- spills-added-total"
$$ text "-- (allocs, clobbers, loads, joinRR, joinRM, reg_reg_moves_remaining)"
$$ (parens $ (hcat $ punctuate (text ", ") (map ppr spillTotals ++ [ppr moves])))
$$ text ""
$$ text "-- spills-added"
$$ text "-- (reg_name, allocs, clobbers, loads, joinRR, joinRM)"
$$ (vcat $ map pprSpill
$ ufmToList spills)
$$ text "")
|
tjakway/ghcjvm
|
compiler/nativeGen/RegAlloc/Linear/Stats.hs
|
bsd-3-clause
| 2,640
| 0
| 22
| 1,017
| 691
| 367
| 324
| 60
| 5
|
module Main where
import Control.Applicative
import System.Environment
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Read
import Data.List.Split
main = do
args <- getArgs
case args of
[x] -> profRead "ghcjs.prof" (read x)
[file,x] -> profRead file (read x)
_ -> putStrLn "usage: readProf [file] minimum"
profRead :: FilePath -> Double -> IO ()
profRead file m = do
lines <- T.lines <$> T.readFile file
mapM_ T.putStrLn (filter (isEnough m) lines)
isEnough :: Double -> T.Text -> Bool
isEnough m line
| [fun,mod,no,entries,itime,ialloc,htime,halloc] <- words (T.unpack line)
, Just ht <- readMaybe htime, Just ha <- readMaybe halloc = ht >= m || ha >= m
| otherwise = True
|
beni55/ghcjs
|
utils/profRead.hs
|
mit
| 792
| 0
| 12
| 200
| 302
| 157
| 145
| 22
| 3
|
{-# LANGUAGE CPP #-}
-- This should fail to compile with "ghc -Wcpp-undef -Werror ...".
#if this_cpp_identifier_does_not_exist
message :: String
message = "This is wrong!"
#endif
main :: IO ()
main = putStrLn "Hello"
|
olsner/ghc
|
testsuite/tests/driver/should_fail/T12752.hs
|
bsd-3-clause
| 219
| 0
| 6
| 36
| 33
| 19
| 14
| 3
| 1
|
module T6031a where
data Empty
|
urbanslug/ghc
|
testsuite/tests/deriving/should_compile/T6031a.hs
|
bsd-3-clause
| 35
| 0
| 3
| 9
| 7
| 5
| 2
| -1
| -1
|
module Axis where
data Axis
= PositiveX
| PositiveY
| PositiveZ
| NegativeX
| NegativeY
| NegativeZ
data AxisName
= AxisX
| AxisY
| AxisZ
axisName :: Axis -> AxisName
axisName PositiveX = AxisX
axisName NegativeX = AxisX
axisName PositiveY = AxisY
axisName NegativeY = AxisY
axisName PositiveZ = AxisZ
axisName NegativeZ = AxisZ
data AxisSystem = AxisSystem {
axis_right :: Axis,
axis_up :: Axis,
axis_forward :: Axis
}
axisValid :: (Axis, Axis, Axis) -> Bool
axisValid (right, up, forward) =
case (axisName right, axisName up, axisName forward) of
(AxisX, AxisY, AxisZ) -> True
(AxisZ, AxisX, AxisY) -> True
(AxisY, AxisZ, AxisX) -> True
_ -> False
data WindingOrder
= WindingOrderClockwise
| WindingOrderCounterClockwise
data CoordinateSystem = CoordinateSystem {
coords_axes :: AxisSystem,
coords_order :: WindingOrder
}
|
io7m/smf
|
com.io7m.smfj.specification/src/main/resources/com/io7m/smfj/specification/axis.hs
|
isc
| 908
| 0
| 8
| 209
| 262
| 152
| 110
| 36
| 4
|
module Chat.Room where
import Chat.Packet
import Chat.Types
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import qualified Data.Map as Map
modifyTMVar :: TMVar a -> (a -> a) -> STM ()
modifyTMVar tmvar action = do
var <- takeTMVar tmvar
putTMVar tmvar (action var)
{-
splitRoom :: (ChatSession -> Bool) -> ChatRoom -> IO (ChatRoom, ChatRoom)
splitRoom cond room = do
-- Extract the sessions, partition them on the predicate, and replace the
-- left half.
sess <- atomically $ takeTMVar (sessions room)
let (lsess, rsess) = Map.partition cond sess
atomically $ putTMVar (sessions room) lsess
-- Construct a new ChatRoom for the right half and notify the threads.
newChan <- newTChanIO
newSessions <- newTMVarIO rsess
let newRoom = ChatRoom newChan newSessions
forM_ (Map.elems rsess) $ \sess -> do
atomically . flip writeTVar newChan . chan $ sess
throwTo (tid sess) ChannelChanged
-- Return the old and new chat room.
return (room, newRoom)
-}
newChatRoom :: String -> IO ChatRoom
newChatRoom name = do
chan <- newTChanIO
sess <- newTMVarIO Map.empty
return $ ChatRoom name chan sess
addSession :: ChatRoom -> ChatSession -> IO ()
addSession room sess = do
let alias = userStateAlias sess
putStrLn ("Adding " ++ alias ++ " to chatroom " ++ name room)
atomically $ modifyTMVar (sessions room) (Map.insert alias sess)
atomically $ writeTChan (channel room) (ServerAddUser (getUser sess))
removeSession :: ChatRoom -> ChatSession -> IO ()
removeSession room sess = do
let alias = userStateAlias sess
putStrLn ("Removing " ++ alias ++ " from chatroom " ++ name room)
atomically $ writeTChan (channel room) (ServerRemoveUser (getUser sess))
atomically $ modifyTMVar (sessions room) (Map.delete alias)
|
thchittenden/GeoChat
|
src/Chat/Room.hs
|
mit
| 1,851
| 0
| 12
| 392
| 398
| 193
| 205
| 28
| 1
|
module Hadis.Commands.Sets
( sadd
, scard
, sismember
, smembers
) where
---
import Hadis.Util
import Hadis.Util.Commands
import Hadis.Ext.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
---
toSet = maybe Set.empty valToSet
onSet :: (Set String -> ReplyVal) -> Key -> CommandReply
onSet = on isSetVal toSet
---
sadd :: Key -> String -> CommandReply
sadd k v = onSet (replyBool . Set.notMember v) k
>>= preserveModify (Map.alter (Just . ValueSet . Set.insert v . toSet) k)
scard :: Key -> CommandReply
scard = onSet $ ReplyInt . Set.size
sismember :: Key -> String -> CommandReply
sismember k v = flip onSet k $ replyBool . Set.member v
smembers :: Key -> CommandReply
smembers = onSet $ ReplyList . map (ReplyStr . Just) . Set.elems
|
goshakkk/hadis
|
src/Hadis/Commands/Sets.hs
|
mit
| 877
| 0
| 13
| 210
| 302
| 166
| 136
| 24
| 1
|
-- A Cell has an X and Y coordinate.
type Cell = (Int, Int)
--A State is a list of cells.
type State = [Cell]
--Maze is described below.
--Bounds is the total size of the maze in (X,Y)
bounds :: (Int, Int)
bounds = (5,5)
--Walls are the cells within the maze that cannot be passed.
walls :: [Cell]
walls = [(1,4), (4,2), (2,2), (3,3)]
--These commented out walls create an unsolveable Maze
--walls = [(1,4), (4,2), (2,2), (3,3), (2,4)]
--Goal is the goal cell in the maze.
goal :: Cell
goal = (4,4)
-- The initial state is usually at the origin, and must be a non-wall and non-goal to make the maze interesting.
initial :: State
initial = [(0, 0)]
loser :: State
loser = []
goalTest :: State -> Bool
goalTest (x:xs) = x == goal
next :: State -> [Cell]
next (c:cs) = [(x,y)| (x,y) <-[(fst c + 1, snd c), (fst c - 1, snd c), (fst c, snd c + 1), (fst c, snd c - 1)],
notElem (x, y) walls && (x >= 0 && y >= 0) && (x < fst bounds && y < snd bounds)]
operator:: State -> [State]
operator (xs) = [(n:xs) | n <- next xs, notElem n xs]
search :: State
search = treeSearch [initial] operator
treeSearch :: [State] -> (State -> [State]) -> State
treeSearch [] op = loser
treeSearch (x:xs) op
| goalTest x = x
| otherwise = treeSearch (newstates ++ xs) op
where newstates = op x
|
fultonms/artificial-intelligence
|
a1/Maze.hs
|
mit
| 1,302
| 0
| 12
| 289
| 528
| 298
| 230
| 27
| 1
|
module GHCJS.DOM.SpeechSynthesisUtterance (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SpeechSynthesisUtterance.hs
|
mit
| 54
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
module Control.Applicative.Extended (
replicateA
, module Control.Applicative
) where
import Control.Applicative
replicateA :: Applicative f => Int -> f a -> f [a]
replicateA n = sequenceA . replicate n
|
jtobin/deanie
|
lib/Control/Applicative/Extended.hs
|
mit
| 216
| 0
| 9
| 43
| 67
| 36
| 31
| 6
| 1
|
import Data.List
fillEggnog = filter (\xs -> sum xs == 150) . subsequences
part1 :: [Int] -> Int
part1 = length . fillEggnog
part2 xs = length $ filter (\x-> length x == minLength) subs
where
subs = fillEggnog xs
minLength = minimum $ map length subs
main = do
containers <- (map read . lines) <$> readFile "inputDay17.txt"
print $ part1 containers
print $ part2 containers
|
bruno-cadorette/AdventOfCode
|
Day 17/Day17.hs
|
mit
| 408
| 0
| 11
| 101
| 159
| 79
| 80
| 11
| 1
|
module Util.Graph (
Graph,
components,
nodes,
children,
reachable,
) where
import Control.Monad (when)
import Control.Monad.State (State, modify, gets, evalState)
import Data.Maybe (fromMaybe)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
type Graph a = Map a [a]
nodes :: Graph a -> [a]
nodes = Map.keys
children :: (Ord a) => Graph a -> a -> [a]
children graph node =
fromMaybe [] (Map.lookup node graph)
reachable :: (Ord a) => a -> Graph a -> Set a
reachable node graph = findReachable (children graph node) (Set.singleton node)
where findReachable [] seen = seen
findReachable (c:cs) seen =
if Set.member c seen
then findReachable cs seen
else findReachable (children graph c ++ cs) (Set.insert c seen)
-- This finds strongly-connected components of the graph,
-- and returns them in a topological ordering.
-- This assumes that every node is mentioned as a key in the graph.
-- https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
components :: (Ord a) => Graph a -> [[a]]
components graph = evalState runConnect startingSCCState
where startingSCCState = SCCState
{ sccIndex = 0
, sccLowlinks = Map.empty
, sccIndexes = Map.empty
, sccComponents = []
, sccStack = []
, sccInStack = Set.empty }
runConnect = connect (nodes graph) graph
data SCCState a
= SCCState
{ sccIndex :: Int
, sccLowlinks :: Map a Int
, sccIndexes :: Map a Int
, sccComponents :: [[a]]
, sccStack :: [a]
, sccInStack :: Set a
}
connect :: (Ord a) => [a] -> Graph a -> State (SCCState a) [[a]]
connect [] _ =
gets sccComponents
connect (n:ns) graph = do
exists <- isIndexed n
if exists
then connect ns graph
else do
strongConnect n graph
connect ns graph
strongConnect :: (Ord a) => a -> Graph a -> State (SCCState a) ()
strongConnect node graph = do
idx <- gets sccIndex
modify $ setIndex node idx
modify $ setLowlink node idx
modify incIndex
modify $ pushStack node
connectChildren (children graph node) node graph
gatherComponent node
connectChildren :: (Ord a) => [a] -> a -> Graph a -> State (SCCState a) ()
connectChildren [] _ _ = return ()
connectChildren (c:cs) node graph = do
exists <- isIndexed c
isOnStack <- gets (Set.member c . sccInStack)
if not exists
then do
strongConnect c graph
vll <- gets (getLowlink node)
cll <- gets (getLowlink c)
modify $ setLowlink node (min vll cll)
else when isOnStack $ do
vll <- gets (getLowlink node)
cidx <- gets (getIndex c)
modify $ setLowlink node (min vll cidx)
connectChildren cs node graph
gatherComponent :: (Ord a) => a -> State (SCCState a) ()
gatherComponent node = do
index <- gets (Map.lookup node . sccIndexes)
lowlink <- gets (Map.lookup node . sccLowlinks)
when (lowlink == index) $ do
component <- popComponent node
modify $ \sccs -> sccs { sccComponents = component : sccComponents sccs }
popComponent :: (Ord a) => a -> State (SCCState a) [a]
popComponent node = do
w <- popStack
if w == node
then return [w]
else do
rest <- popComponent node
return $ w : rest
type SCCStateTX a = SCCState a -> SCCState a
isIndexed :: (Ord a) => a -> State (SCCState a) Bool
isIndexed node = do
indexes <- gets sccIndexes
return $ Map.member node indexes
pushStack :: (Ord a) => a -> SCCStateTX a
pushStack node sccs =
sccs { sccStack = node : sccStack sccs
, sccInStack = Set.insert node (sccInStack sccs) }
popStack :: (Ord a) => State (SCCState a) a
popStack = do
stack <- gets sccStack
let item = head stack
modify $ \scss ->
scss { sccStack = tail stack
, sccInStack = Set.delete item (sccInStack scss) }
return item
incIndex :: SCCStateTX a
incIndex sccs = sccs { sccIndex = 1 + sccIndex sccs }
setIndex :: (Ord a) => a -> Int -> SCCStateTX a
setIndex node index sccs =
sccs { sccIndexes = Map.insert node index (sccIndexes sccs) }
setLowlink :: (Ord a) => a -> Int -> SCCStateTX a
setLowlink node lowlink sccs =
sccs { sccLowlinks = Map.insert node lowlink (sccLowlinks sccs) }
getIndex :: (Ord a) => a -> SCCState a -> Int
getIndex node sccs = fromJust $ Map.lookup node $ sccIndexes sccs
getLowlink :: (Ord a) => a -> SCCState a -> Int
getLowlink node sccs = fromJust $ Map.lookup node $ sccLowlinks sccs
fromJust :: Maybe a -> a
fromJust (Just a) = a
fromJust Nothing = error "unexpected Nothing"
|
jmikkola/Athena
|
src/Util/Graph.hs
|
mit
| 4,732
| 0
| 15
| 1,246
| 1,770
| 898
| 872
| 126
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Data.BlockChain.Block.BlockInfo where
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe (fromJust)
import Data.Time.Clock.POSIX
-- below imports available via cabal install
import Data.Aeson
import Network.HTTP.Conduit (simpleHttp)
-- below imports available from 1HaskellADay git repository
import Data.BlockChain.Block.Types
import Data.BlockChain.Block.Utils
{--
So, last week you created a webservice that showed block information for the
latest block, then refined that to show block information for some requested
block.
The problem here is that: do you know a block hash off the top of your head?
No, you don't.
So it's best to survey block information by some criteria, such as by address,
or by day, or by pool, or by height.
Let's survey blocks by day today.
A sample set of block (meta-)information returned from a block at a specified
time (the POSIX-integer representation of time) is located at this directory:
blocks.json
or at this URL:
https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M10/D10/blocks.json
Create a structure that accepts these data, then, you know: read it in.
--}
data BlockInfo = BlockInfo { height :: Integer, hashId :: Hash, time :: Integer }
deriving Show
instance Sheesh BlockInfo where
hash = hashId
instance FromJSON BlockInfo where
parseJSON (Object o) =
BlockInfo <$> o .: "height" <*> o .: "hash" <*> o .: "time"
data Blocks = Blocks { blocks :: [BlockInfo] }
deriving Show
instance FromJSON Blocks where
parseJSON (Object o) = Blocks <$> o .: "blocks"
scanBlocks :: ByteString -> Maybe Blocks
scanBlocks = decode
{--
*Y2016.M10.D10.Solution> fmap scanBlocks $ BL.readFile "Y2016/M10/D10/blocks.json"
Just (Blocks {blocks = [BlockInfo {height = 166107, hash = "0000...fe0a", time = 1328830483},
BlockInfo {height = 166104, hash = "0000...7995", time = 1328828041}]})
I know I have an Int to time converter here somewhere. Time to make an Utils
module!
... yup, it's in Data.BlockChain.Block.Graphs ... moving it
--}
-- now read in the block info for some time from the blockchain.info api
blocksTodayURL :: FilePath
blocksTodayURL = "https://blockchain.info/blocks?format=json"
{--
bleh: bad url? obe url? idk
readBlockInfo :: POSIXTime -> IO Blocks
readBlockInfo = fmap (fromJust . scanBlocks) . simpleHttp . blocksAtTimeURL . floor
--}
-- now read in the block info for today/the current POSIX time
readTodaysBlockInfo :: IO Blocks
readTodaysBlockInfo = fmap (fromJust . scanBlocks) $ simpleHttp blocksTodayURL
-- *Y2016.M10.D10.Solution> readTodaysBlockInfo ~> blks ~> length (blocks blks) ~> 88
|
geophf/1HaskellADay
|
exercises/HAD/Data/BlockChain/Block/BlockInfo.hs
|
mit
| 2,759
| 0
| 11
| 458
| 283
| 169
| 114
| 27
| 1
|
module NetHack.Control.LevelTransition
(applyTransition)
where
import NetHack.Monad.NHAction
import NetHack.Data.LevelTransition
import NetHack.Data.Level
import Control.Monad.IO.Class
applyTransition :: NHAction ()
applyTransition = do
id <- nextRunningIDM
oldLev <- getLevelM
let (lev, _) = newLevel id
putLevelM lev
transitionMaybe <- getLevelTransitionM
let Just transition = transitionMaybe
modifiedOldLev = linkLevels transition oldLev lev
putLevelM modifiedOldLev
putCurrentLevelM lev
resetLevelTransitionM
|
Noeda/Megaman
|
src/NetHack/Control/LevelTransition.hs
|
mit
| 546
| 0
| 10
| 84
| 138
| 69
| 69
| 18
| 1
|
-- Self composition of an unary function. Primitive Recursion.
module SelfComposition where
selfCompose :: Integer -> (a -> a) -> (a -> a)
selfCompose 0 _ = id
selfCompose times function
= function . selfCompose (times - 1) function
{- GHCi>
( selfCompose 0 (+ 1) ) 1
( selfCompose 1 (+ 1) ) 1
( selfCompose 2 (+ 1) ) 1
-}
-- 1
-- 2
-- 3
|
pascal-knodel/haskell-craft
|
Examples/· Recursion/· Primitive Recursion/Higher Order Functions/SelfComposition.hs
|
mit
| 364
| 0
| 8
| 95
| 72
| 41
| 31
| 5
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-
Copyright (C) 2012-2015 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Options
Copyright : Copyright (C) 2012-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Data structures and functions for representing parser and writer
options.
-}
module Text.Pandoc.Options ( Extension(..)
, pandocExtensions
, strictExtensions
, phpMarkdownExtraExtensions
, githubMarkdownExtensions
, multimarkdownExtensions
, ReaderOptions(..)
, HTMLMathMethod (..)
, CiteMethod (..)
, ObfuscationMethod (..)
, HTMLSlideVariant (..)
, EPUBVersion (..)
, WriterOptions (..)
, TrackChanges (..)
, def
, isEnabled
) where
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Default
import Text.Pandoc.Highlighting (Style, pygments)
import Text.Pandoc.MediaBag (MediaBag)
import Data.Monoid
import Data.Data (Data)
import Data.Typeable (Typeable)
-- | Individually selectable syntax extensions.
data Extension =
Ext_footnotes -- ^ Pandoc/PHP/MMD style footnotes
| Ext_inline_notes -- ^ Pandoc-style inline notes
| Ext_pandoc_title_block -- ^ Pandoc title block
| Ext_yaml_metadata_block -- ^ YAML metadata block
| Ext_mmd_title_block -- ^ Multimarkdown metadata block
| Ext_table_captions -- ^ Pandoc-style table captions
| Ext_implicit_figures -- ^ A paragraph with just an image is a figure
| Ext_simple_tables -- ^ Pandoc-style simple tables
| Ext_multiline_tables -- ^ Pandoc-style multiline tables
| Ext_grid_tables -- ^ Grid tables (pandoc, reST)
| Ext_pipe_tables -- ^ Pipe tables (as in PHP markdown extra)
| Ext_citations -- ^ Pandoc/citeproc citations
| Ext_raw_tex -- ^ Allow raw TeX (other than math)
| Ext_raw_html -- ^ Allow raw HTML
| Ext_tex_math_dollars -- ^ TeX math between $..$ or $$..$$
| Ext_tex_math_single_backslash -- ^ TeX math btw \(..\) \[..\]
| Ext_tex_math_double_backslash -- ^ TeX math btw \\(..\\) \\[..\\]
| Ext_latex_macros -- ^ Parse LaTeX macro definitions (for math only)
| Ext_fenced_code_blocks -- ^ Parse fenced code blocks
| Ext_fenced_code_attributes -- ^ Allow attributes on fenced code blocks
| Ext_backtick_code_blocks -- ^ GitHub style ``` code blocks
| Ext_inline_code_attributes -- ^ Allow attributes on inline code
| Ext_markdown_in_html_blocks -- ^ Interpret as markdown inside HTML blocks
| Ext_native_divs -- ^ Use Div blocks for contents of <div> tags
| Ext_native_spans -- ^ Use Span inlines for contents of <span>
| Ext_markdown_attribute -- ^ Interpret text inside HTML as markdown
-- iff container has attribute 'markdown'
| Ext_escaped_line_breaks -- ^ Treat a backslash at EOL as linebreak
| Ext_link_attributes -- ^ MMD style reference link attributes
| Ext_autolink_bare_uris -- ^ Make all absolute URIs into links
| Ext_fancy_lists -- ^ Enable fancy list numbers and delimiters
| Ext_lists_without_preceding_blankline -- ^ Allow lists without preceding blank
| Ext_startnum -- ^ Make start number of ordered list significant
| Ext_definition_lists -- ^ Definition lists as in pandoc, mmd, php
| Ext_compact_definition_lists -- ^ Definition lists without
-- space between items, and disallow laziness
| Ext_example_lists -- ^ Markdown-style numbered examples
| Ext_all_symbols_escapable -- ^ Make all non-alphanumerics escapable
| Ext_intraword_underscores -- ^ Treat underscore inside word as literal
| Ext_blank_before_blockquote -- ^ Require blank line before a blockquote
| Ext_blank_before_header -- ^ Require blank line before a header
| Ext_strikeout -- ^ Strikeout using ~~this~~ syntax
| Ext_superscript -- ^ Superscript using ^this^ syntax
| Ext_subscript -- ^ Subscript using ~this~ syntax
| Ext_hard_line_breaks -- ^ All newlines become hard line breaks
| Ext_ignore_line_breaks -- ^ Newlines in paragraphs are ignored
| Ext_literate_haskell -- ^ Enable literate Haskell conventions
| Ext_abbreviations -- ^ PHP markdown extra abbreviation definitions
| Ext_auto_identifiers -- ^ Automatic identifiers for headers
| Ext_ascii_identifiers -- ^ ascii-only identifiers for headers
| Ext_header_attributes -- ^ Explicit header attributes {#id .class k=v}
| Ext_mmd_header_identifiers -- ^ Multimarkdown style header identifiers [myid]
| Ext_implicit_header_references -- ^ Implicit reference links for headers
| Ext_line_blocks -- ^ RST style line blocks
| Ext_epub_html_exts -- ^ Recognise the EPUB extended version of HTML
| Ext_shortcut_reference_links -- ^ Shortcut reference links
deriving (Show, Read, Enum, Eq, Ord, Bounded, Data, Typeable)
pandocExtensions :: Set Extension
pandocExtensions = Set.fromList
[ Ext_footnotes
, Ext_inline_notes
, Ext_pandoc_title_block
, Ext_yaml_metadata_block
, Ext_table_captions
, Ext_implicit_figures
, Ext_simple_tables
, Ext_multiline_tables
, Ext_grid_tables
, Ext_pipe_tables
, Ext_citations
, Ext_raw_tex
, Ext_raw_html
, Ext_tex_math_dollars
, Ext_latex_macros
, Ext_fenced_code_blocks
, Ext_fenced_code_attributes
, Ext_backtick_code_blocks
, Ext_inline_code_attributes
, Ext_markdown_in_html_blocks
, Ext_native_divs
, Ext_native_spans
, Ext_escaped_line_breaks
, Ext_fancy_lists
, Ext_startnum
, Ext_definition_lists
, Ext_example_lists
, Ext_all_symbols_escapable
, Ext_intraword_underscores
, Ext_blank_before_blockquote
, Ext_blank_before_header
, Ext_strikeout
, Ext_superscript
, Ext_subscript
, Ext_auto_identifiers
, Ext_header_attributes
, Ext_implicit_header_references
, Ext_line_blocks
, Ext_shortcut_reference_links
]
phpMarkdownExtraExtensions :: Set Extension
phpMarkdownExtraExtensions = Set.fromList
[ Ext_footnotes
, Ext_pipe_tables
, Ext_raw_html
, Ext_markdown_attribute
, Ext_fenced_code_blocks
, Ext_definition_lists
, Ext_intraword_underscores
, Ext_header_attributes
, Ext_abbreviations
, Ext_shortcut_reference_links
]
githubMarkdownExtensions :: Set Extension
githubMarkdownExtensions = Set.fromList
[ Ext_pipe_tables
, Ext_raw_html
, Ext_tex_math_single_backslash
, Ext_fenced_code_blocks
, Ext_auto_identifiers
, Ext_ascii_identifiers
, Ext_backtick_code_blocks
, Ext_autolink_bare_uris
, Ext_intraword_underscores
, Ext_strikeout
, Ext_hard_line_breaks
, Ext_lists_without_preceding_blankline
, Ext_shortcut_reference_links
]
multimarkdownExtensions :: Set Extension
multimarkdownExtensions = Set.fromList
[ Ext_pipe_tables
, Ext_raw_html
, Ext_markdown_attribute
, Ext_link_attributes
, Ext_raw_tex
, Ext_tex_math_double_backslash
, Ext_intraword_underscores
, Ext_mmd_title_block
, Ext_footnotes
, Ext_definition_lists
, Ext_all_symbols_escapable
, Ext_implicit_header_references
, Ext_auto_identifiers
, Ext_mmd_header_identifiers
]
strictExtensions :: Set Extension
strictExtensions = Set.fromList
[ Ext_raw_html
, Ext_shortcut_reference_links
]
data ReaderOptions = ReaderOptions{
readerExtensions :: Set Extension -- ^ Syntax extensions
, readerSmart :: Bool -- ^ Smart punctuation
, readerStandalone :: Bool -- ^ Standalone document with header
, readerParseRaw :: Bool -- ^ Parse raw HTML, LaTeX
, readerColumns :: Int -- ^ Number of columns in terminal
, readerTabStop :: Int -- ^ Tab stop
, readerOldDashes :: Bool -- ^ Use pandoc <= 1.8.2.1 behavior
-- in parsing dashes; -- is em-dash;
-- - before numerial is en-dash
, readerApplyMacros :: Bool -- ^ Apply macros to TeX math
, readerIndentedCodeClasses :: [String] -- ^ Default classes for
-- indented code blocks
, readerDefaultImageExtension :: String -- ^ Default extension for images
, readerTrace :: Bool -- ^ Print debugging info
, readerTrackChanges :: TrackChanges
} deriving (Show, Read, Data, Typeable)
instance Default ReaderOptions
where def = ReaderOptions{
readerExtensions = pandocExtensions
, readerSmart = False
, readerStandalone = False
, readerParseRaw = False
, readerColumns = 80
, readerTabStop = 4
, readerOldDashes = False
, readerApplyMacros = True
, readerIndentedCodeClasses = []
, readerDefaultImageExtension = ""
, readerTrace = False
, readerTrackChanges = AcceptChanges
}
--
-- Writer options
--
data EPUBVersion = EPUB2 | EPUB3 deriving (Eq, Show, Read, Data, Typeable)
data HTMLMathMethod = PlainMath
| LaTeXMathML (Maybe String) -- url of LaTeXMathML.js
| JsMath (Maybe String) -- url of jsMath load script
| GladTeX
| WebTeX String -- url of TeX->image script.
| MathML (Maybe String) -- url of MathMLinHTML.js
| MathJax String -- url of MathJax.js
| KaTeX String String -- url of stylesheet and katex.js
deriving (Show, Read, Eq, Data, Typeable)
data CiteMethod = Citeproc -- use citeproc to render them
| Natbib -- output natbib cite commands
| Biblatex -- output biblatex cite commands
deriving (Show, Read, Eq, Data, Typeable)
-- | Methods for obfuscating email addresses in HTML.
data ObfuscationMethod = NoObfuscation
| ReferenceObfuscation
| JavascriptObfuscation
deriving (Show, Read, Eq, Data, Typeable)
-- | Varieties of HTML slide shows.
data HTMLSlideVariant = S5Slides
| SlidySlides
| SlideousSlides
| DZSlides
| RevealJsSlides
| NoSlides
deriving (Show, Read, Eq, Data, Typeable)
-- | Options for accepting or rejecting MS Word track-changes.
data TrackChanges = AcceptChanges
| RejectChanges
| AllChanges
deriving (Show, Read, Eq, Data, Typeable)
-- | Options for writers
data WriterOptions = WriterOptions
{ writerStandalone :: Bool -- ^ Include header and footer
, writerTemplate :: String -- ^ Template to use in standalone mode
, writerVariables :: [(String, String)] -- ^ Variables to set in template
, writerTabStop :: Int -- ^ Tabstop for conversion btw spaces and tabs
, writerTableOfContents :: Bool -- ^ Include table of contents
, writerSlideVariant :: HTMLSlideVariant -- ^ Are we writing S5, Slidy or Slideous?
, writerIncremental :: Bool -- ^ True if lists should be incremental
, writerHTMLMathMethod :: HTMLMathMethod -- ^ How to print math in HTML
, writerIgnoreNotes :: Bool -- ^ Ignore footnotes (used in making toc)
, writerNumberSections :: Bool -- ^ Number sections in LaTeX
, writerNumberOffset :: [Int] -- ^ Starting number for section, subsection, ...
, writerSectionDivs :: Bool -- ^ Put sections in div tags in HTML
, writerExtensions :: Set Extension -- ^ Markdown extensions that can be used
, writerReferenceLinks :: Bool -- ^ Use reference links in writing markdown, rst
, writerWrapText :: Bool -- ^ Wrap text to line length
, writerColumns :: Int -- ^ Characters in a line (for text wrapping)
, writerEmailObfuscation :: ObfuscationMethod -- ^ How to obfuscate emails
, writerIdentifierPrefix :: String -- ^ Prefix for section & note ids in HTML
-- and for footnote marks in markdown
, writerSourceURL :: Maybe String -- ^ Absolute URL + directory of 1st source file
, writerUserDataDir :: Maybe FilePath -- ^ Path of user data directory
, writerCiteMethod :: CiteMethod -- ^ How to print cites
, writerHtml5 :: Bool -- ^ Produce HTML5
, writerHtmlQTags :: Bool -- ^ Use @<q>@ tags for quotes in HTML
, writerBeamer :: Bool -- ^ Produce beamer LaTeX slide show
, writerSlideLevel :: Maybe Int -- ^ Force header level of slides
, writerChapters :: Bool -- ^ Use "chapter" for top-level sects
, writerListings :: Bool -- ^ Use listings package for code
, writerHighlight :: Bool -- ^ Highlight source code
, writerHighlightStyle :: Style -- ^ Style to use for highlighting
, writerSetextHeaders :: Bool -- ^ Use setext headers for levels 1-2 in markdown
, writerTeXLigatures :: Bool -- ^ Use tex ligatures quotes, dashes in latex
, writerEpubVersion :: Maybe EPUBVersion -- ^ Nothing or EPUB version
, writerEpubMetadata :: String -- ^ Metadata to include in EPUB
, writerEpubStylesheet :: Maybe String -- ^ EPUB stylesheet specified at command line
, writerEpubFonts :: [FilePath] -- ^ Paths to fonts to embed
, writerEpubChapterLevel :: Int -- ^ Header level for chapters (separate files)
, writerTOCDepth :: Int -- ^ Number of levels to include in TOC
, writerReferenceODT :: Maybe FilePath -- ^ Path to reference ODT if specified
, writerReferenceDocx :: Maybe FilePath -- ^ Path to reference DOCX if specified
, writerMediaBag :: MediaBag -- ^ Media collected by docx or epub reader
, writerVerbose :: Bool -- ^ Verbose debugging output
, writerLaTeXArgs :: [String] -- ^ Flags to pass to latex-engine
} deriving (Show, Data, Typeable)
instance Default WriterOptions where
def = WriterOptions { writerStandalone = False
, writerTemplate = ""
, writerVariables = []
, writerTabStop = 4
, writerTableOfContents = False
, writerSlideVariant = NoSlides
, writerIncremental = False
, writerHTMLMathMethod = PlainMath
, writerIgnoreNotes = False
, writerNumberSections = False
, writerNumberOffset = [0,0,0,0,0,0]
, writerSectionDivs = False
, writerExtensions = pandocExtensions
, writerReferenceLinks = False
, writerWrapText = True
, writerColumns = 72
, writerEmailObfuscation = JavascriptObfuscation
, writerIdentifierPrefix = ""
, writerSourceURL = Nothing
, writerUserDataDir = Nothing
, writerCiteMethod = Citeproc
, writerHtml5 = False
, writerHtmlQTags = False
, writerBeamer = False
, writerSlideLevel = Nothing
, writerChapters = False
, writerListings = False
, writerHighlight = False
, writerHighlightStyle = pygments
, writerSetextHeaders = True
, writerTeXLigatures = True
, writerEpubVersion = Nothing
, writerEpubMetadata = ""
, writerEpubStylesheet = Nothing
, writerEpubFonts = []
, writerEpubChapterLevel = 1
, writerTOCDepth = 3
, writerReferenceODT = Nothing
, writerReferenceDocx = Nothing
, writerMediaBag = mempty
, writerVerbose = False
, writerLaTeXArgs = []
}
-- | Returns True if the given extension is enabled.
isEnabled :: Extension -> WriterOptions -> Bool
isEnabled ext opts = ext `Set.member` (writerExtensions opts)
|
csrhodes/pandoc
|
src/Text/Pandoc/Options.hs
|
gpl-2.0
| 18,245
| 0
| 10
| 6,021
| 1,935
| 1,259
| 676
| 315
| 1
|
{-# language TemplateHaskell, DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Graph.Weighted.Data where
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Set
import Autolib.Hash
import Data.Typeable
import GHC.Generics
data ( Ord v ) => Kante v w =
Kante { von :: v, nach :: v, gewicht :: w }
deriving ( Typeable )
instance ( Ord v, Hash v, Hash w ) => Hashable ( Kante v w ) where
hashWithSalt s k = hashWithSalt s (von k, nach k)
-- | das Gewicht wird beim Vergleich der Kanten ignoriert.
-- Das ist eventuell keine gute Idee.
-- Damit kann man z. B. keine Automaten darstellen,
-- dort kann es mehrere Kanten mit verschiedenem Gewicht (Labels)
-- zwischen zwei Knoten geben.
-- außerdem versteckt sich hier die Entscheidung,
-- ob Kanten gerichtet oder ungerichtet sind.
instance Ord v => Eq ( Kante v w ) where
k == l = von k == von l && nach k == nach l
instance Ord v => Ord ( Kante v w ) where
compare k l = compare ( von k, nach k ) ( von l, nach l )
data ( Ord v ) => Graph v w =
Graph { knoten :: Set v
, kanten :: Set ( Kante v w )
}
deriving ( Typeable, Eq )
instance (Ord v, Hash v, Hash w) => Hashable ( Graph v w ) where
hashWithSalt s g = hashWithSalt s (knoten g, kanten g)
$(derives [makeReader, makeToDoc] [''Kante, ''Graph])
instance (Ord v, ToDoc v, ToDoc w) => Show (Graph v w) where show = render . toDoc
|
marcellussiegburg/autotool
|
collection/src/Graph/Weighted/Data.hs
|
gpl-2.0
| 1,428
| 0
| 11
| 343
| 470
| 251
| 219
| 26
| 0
|
-- |
-- Module : Doublefunge.Parser
-- Copyright : Joe Jevnik 2013
--
-- License : GPL-2
-- Maintainer : joejev@gmail.org
-- Stability : stable
-- Portability : GHC
--
-- Parsing functions for the doublefunge interpreter.
module Befunge.Doublefunge.Parser where
import Befunge.Doublefunge.Data
import Befunge.Doublefunge.Operations
import Control.Applicative ((<$>))
import Control.Arrow (second)
import Control.Monad ((<=<))
import Data.Array.IO (IOUArray,newArray,writeArray)
-- | Reads a new state from a string.
stateFromSource :: String -> IO State
stateFromSource cs = newArray ((0,0),(24,79)) 32
>>= \arr -> iter arr 0 0
(concatMap (extend 80) $ take 25 $ lines cs)
>>= newStateFromArr
where
extend n cs = take n $ cs ++ repeat ' '
iter arr _ _ [] = return arr
iter arr 80 y cs = iter arr 0 (y + 1) cs
iter arr x y (c:cs) = writeArray arr (y,x) (charToWord c)
>> iter arr (x + 1) y cs
-- | Reads a new 'State' from a file.
stateFromFile :: FilePath -> IO State
stateFromFile = stateFromSource <=< readFile
|
llllllllll/befunge
|
Befunge/Doublefunge/Parser.hs
|
gpl-2.0
| 1,194
| 0
| 14
| 349
| 329
| 183
| 146
| 19
| 3
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS -Wall -Werror #-}
module HMumps.Types where
-- import Text.Regex
import Data.MValue
type Routine = String -> Maybe Subroutine
type Line = [Command]
type File = [(Tag, Line)]
type OldFile = [(Tag, Int, Line)]
type Subroutine = ([Name],[Line]) -- Arguments and commands
type Tag = Maybe (Name, [Name]) -- Label and arguments
instance Show Routine where
show _ = "[Routine]"
{- Definition of lexical tokens follows:
routinehead -> name eol
name -> startname [alphanumeric]
startname -> % | ['A'..'Z']++['a'..'z']
digit -> ['0'..'9']
control -> 127:[0..31]
graphic -> [x | x<-[0..255], not (elem x control)]
eol -> '\n'
-}
-- Where we put this may change, but I'm going to just include the pre
-- processing here so that we can know where we stand. The fundamental
-- assumptions that can go into the true parsing is that
-- 1. There are no comments
-- 2. There are no trailing whitespaces
-- 3. There are no newlines
-- Leaving in stupid version until I can think of a good way to fuse the traversals.
-- AST data structures
-- These structures are what MUMPS will look like AFTER parsing,
-- but these structures do NOT describe the execution environment.
--
-- EXCEPTION: The MValue data type is both used as literals in
-- the AST structures, and in the run-time environment.
--
-- These data structures, taken together, should be trvially
-- isomorphic to unparsed MUMPS
--
-- It's intended that the execution environment will execute these
-- structures - so that it's a step removed from parsing and line
-- reading, even if the base execution environment still has a
-- concept of "line"
-- I feel like this is going to turn into an explosion of type contructors
--
-- | These commands make up the initial sub-set of commands I'd like
-- to implement. I'm not sure if the ASTs described here will make
-- up the optimizable representation, but they will make up what's
-- executed by my first stab at a run-time environment.
data Command = Break (Maybe Condition)
| Do (Maybe Condition) [DoArg]
| Else
| For Vn ForArg
| ForInf
| Goto (Maybe Condition) [GotoArg]
| Halt (Maybe Condition)
| Hang (Maybe Condition) Expression
| If [Condition]
| Kill (Maybe Condition) [KillArg]
| Merge (Maybe Condition) [MergeArg]
| New (Maybe Condition) [NewArg]
| Quit (Maybe Condition) (Maybe Expression)
| Read (Maybe Condition) [WriteArg] Vn
| Set (Maybe Condition) [SetArg]
| Write (Maybe Condition) [WriteArg]
| Xecute (Maybe Condition) Expression
-- The following commands will not have parsers written for them
| Nop
| Block (Maybe Condition) Routine [[Command]]
deriving (Show)
data DoArg = DoArg (Maybe Condition) EntryRef [FunArg]
| DoArgIndirect Expression
| DoArgList [DoArg] -- not parsed, only used during run-time
deriving (Show)
data ForArg = ForArg1 Expression
| ForArg2 Expression Expression
| ForArg3 Expression Expression Expression
deriving (Show)
data GotoArg = GotoArg (Maybe Condition) EntryRef
| GotoArgIndirect Expression
deriving (Show)
-- | "EntryRef" is a thing that can be pointed to by a DO or a GOTO,
-- it may be specify a subroutine or a routine. This datatype should
-- be equivalent to the "entryref" of the MUMPS spec.
data EntryRef = Routine Routineref
| Subroutine Label (Maybe Integer) (Maybe Routineref)
deriving (Show)
-- | The DLabel is tag pointed to by an enytryref, if the entryref
-- specifies a label.
data Label = Label Name
| LabelInt Integer -- ^Labels can be given as integers
| LabelIndirect Expression
deriving (Show)
-- | The Routineref specifies a routine and an optional
-- environment. May be indirect.
data Routineref = Routineref Name
| RoutinerefIndirect Expression
deriving (Show)
type Condition = Expression
type Subscript = Expression
-- | Each argument to KILL may be
-- 1) A variable name
-- 2) A list containing the names of variables
-- not to kill (the remainder are killed)
-- 3) An expression, evaluating to a list of
-- valid kill arguments
-- See 8.2.11
data KillArg = KillSelective Vn
| KillExclusive [Name]
| KillIndirect Expression
| KillArgList [KillArg] -- not parsed, only used internally
deriving (Show)
-- |An argument to merge specifies a source and a target.
-- See 8.2.13
data MergeArg = MergeArg Vn Vn | MergeArgIndirect Expression
deriving (Show)
-- | The arguments to NEW are pretty much the same as the arguments
-- to KILL.
-- See 8.2.14
data NewArg = NewSelective Name
| NewExclusive [Name]
| NewIndirect Expression
| NewArgList [NewArg] -- not parsed. Internal only.
deriving (Show)
data WriteArg = WriteExpression Expression
| WriteFormat [WriteFormatCode]
| WriteIndirect Expression
deriving (Show)
data WriteFormatCode = Formfeed
| Newline
| Tab Int
deriving (Show)
-- |Vn describes the name of a variable, which may be local, global,
-- or indirect. Each form may optionally indicate a Subscript.
-- See 7.1.2
data Vn = Lvn Name [Subscript] -- these two will only ever
| Gvn Name [Subscript] -- be direct names. Maybe.
| IndirectVn Expression [Subscript]
deriving (Show)
-- | A funarg can be an expression, or the name of a local to pass
-- in by reference.
data FunArg = FunArgExp Expression
| FunArgName Name
deriving (Show)
type Name = String
-- | An expression is something which evaluates to an MValue.
data Expression
-- |An expression may be a literal MValue
= ExpLit MValue
-- |or a variable to be fetched
| ExpVn Vn
-- |Any expression may be precedded by one of the
-- unary operators
| ExpUnop UnaryOp Expression
-- |Binary operators may be used to combine expressions.
| ExpBinop BinOp Expression Expression
-- |MUMPS provides many builtin functions, some of which
-- are of arity zero (so are more like builtin constants)
| ExpBifCall BifCall
-- |You can even call your own functions! Locally defined
-- functions need not specify the parent routine.
| FunCall String String [FunArg]
-- |A pattern match is similar to a regular expression match.
-- This binary operator returns either 0 or 1.
-- | Pattern Expression Regex
deriving (Show)
type PatCode = ()
{-
instance Show Regex where
show _ = "<Regex>"
-}
data UnaryOp = UNot | UPlus | UMinus
deriving (Show)
data BinOp = Concat | Add | Sub | Mult | Div | Rem | Quot | Pow | And | Or
| Equal | LessThan | GreaterThan | Follows | Contains | SortsAfter
deriving (Show)
data BifCall
= BifChar [Expression]
| BifX
| BifY
| BifTest
| BifOrder Vn (Maybe Expression)
| BifReplace Expression Expression Expression
deriving Show
-- I don't know why I hadn't defined this earlier.
-- I'm glad I hadn't - it liekly would've been
-- more complicated.
-- |A set argument consists of list of variable names that are to be
-- set to the supplied expression. Even though the SetArg as a whole
-- may not be indirect, the Vn or Expression may allow for indirection.
type SetArg=([Vn],Expression)
|
aslatter/hmumps
|
HMumps/Types.hs
|
gpl-3.0
| 7,558
| 0
| 8
| 1,931
| 1,072
| 662
| 410
| 106
| 0
|
module Main where
multiplicacaoEtiope :: Int->Int->Int-> Int
multiplicacaoEtiope m n r
| m == 1 = r+n
| m `rem` 2 == 0 = multiplicacaoEtiope (m `div` 2) (n * 2) r
| otherwise = multiplicacaoEtiope (m `div` 2) (n * 2) (r+n)
main :: IO()
main = do
print(multiplicacaoEtiope 14 12 0)
|
llscm0202/BIGDATA2017
|
ATIVIDADE1/exerciciosFuncoes/ex3.hs
|
gpl-3.0
| 298
| 0
| 9
| 70
| 159
| 83
| 76
| 9
| 1
|
{-|
Read hledger data from various data formats, and related utilities.
-}
module Hledger.Read (
tests_Hledger_Read,
readJournalFile,
readJournal,
journalFromPathAndString,
ledgeraccountname,
myJournalPath,
myJournal,
someamount,
journalenvvar,
journaldefaultfilename,
requireJournalFile,
ensureJournalFile,
)
where
import Control.Monad.Error
import Data.Either (partitionEithers)
import Data.List
import Safe (headDef)
import System.Directory (doesFileExist, getHomeDirectory)
import System.Environment (getEnv)
import System.Exit (exitFailure)
import System.FilePath ((</>))
import System.IO (IOMode(..), withFile, stderr)
import Test.HUnit
import Text.Printf
import Hledger.Data.Dates (getCurrentDay)
import Hledger.Data.Types (Journal(..), Reader(..))
import Hledger.Data.Journal (nullctx)
import Hledger.Read.JournalReader as JournalReader
import Hledger.Read.TimelogReader as TimelogReader
import Hledger.Utils
import Prelude hiding (getContents, writeFile)
import Hledger.Utils.UTF8 (getContents, hGetContents, writeFile)
journalenvvar = "LEDGER_FILE"
journalenvvar2 = "LEDGER"
journaldefaultfilename = ".hledger.journal"
-- Here are the available readers. The first is the default, used for unknown data formats.
readers :: [Reader]
readers = [
JournalReader.reader
,TimelogReader.reader
]
formats = map rFormat readers
readerForFormat :: String -> Maybe Reader
readerForFormat s | null rs = Nothing
| otherwise = Just $ head rs
where
rs = filter ((s==).rFormat) readers :: [Reader]
-- | Read a Journal from this string (and file path), auto-detecting the
-- data format, or give a useful error string. Tries to parse each known
-- data format in turn. If none succeed, gives the error message specific
-- to the intended data format, which if not specified is guessed from the
-- file suffix and possibly the data.
journalFromPathAndString :: Maybe String -> FilePath -> String -> IO (Either String Journal)
journalFromPathAndString format fp s = do
let readers' = case format of Just f -> case readerForFormat f of Just r -> [r]
Nothing -> []
Nothing -> readers
(errors, journals) <- partitionEithers `fmap` mapM tryReader readers'
case journals of j:_ -> return $ Right j
_ -> return $ Left $ errMsg errors
where
tryReader r = (runErrorT . (rParser r) fp) s
errMsg [] = unknownFormatMsg
errMsg es = printf "could not parse %s data in %s\n%s" (rFormat r) fp e
where (r,e) = headDef (head readers, head es) $ filter detects $ zip readers es
detects (r,_) = (rDetector r) fp s
unknownFormatMsg = printf "could not parse %sdata in %s" (fmt formats) fp
where fmt [] = ""
fmt [f] = f ++ " "
fmt fs = intercalate ", " (init fs) ++ " or " ++ last fs ++ " "
-- | Read a journal from this file, using the specified data format or
-- trying all known formats, or give an error string; also create the file
-- if it doesn't exist.
readJournalFile :: Maybe String -> FilePath -> IO (Either String Journal)
readJournalFile format "-" = getContents >>= journalFromPathAndString format "(stdin)"
readJournalFile format f = do
requireJournalFile f
withFile f ReadMode $ \h -> hGetContents h >>= journalFromPathAndString format f
-- | If the specified journal file does not exist, give a helpful error and quit.
requireJournalFile :: FilePath -> IO ()
requireJournalFile f = do
exists <- doesFileExist f
when (not exists) $ do
hPrintf stderr "The hledger journal file \"%s\" was not found.\n" f
hPrintf stderr "Please create it first, eg with hledger add, hledger web, or a text editor.\n"
hPrintf stderr "Or, specify an existing journal file with -f or LEDGER_FILE.\n"
exitFailure
-- | Ensure there is a journal file at the given path, creating an empty one if needed.
ensureJournalFile :: FilePath -> IO ()
ensureJournalFile f = do
exists <- doesFileExist f
when (not exists) $ do
hPrintf stderr "Creating hledger journal file \"%s\".\n" f
-- note Hledger.Utils.UTF8.* do no line ending conversion on windows,
-- we currently require unix line endings on all platforms.
newJournalContent >>= writeFile f
-- | Give the content for a new auto-created journal file.
newJournalContent :: IO String
newJournalContent = do
d <- getCurrentDay
return $ printf "; journal created %s by hledger\n" (show d)
-- | Read a Journal from this string, using the specified data format or
-- trying all known formats, or give an error string.
readJournal :: Maybe String -> String -> IO (Either String Journal)
readJournal format s = journalFromPathAndString format "(string)" s
-- | Get the user's journal file path. Like ledger, we look first for the
-- LEDGER_FILE environment variable, and if that does not exist, for the
-- legacy LEDGER environment variable. If neither is set, or the value is
-- blank, return the default journal file path, which is
-- ".hledger.journal" in the users's home directory, or if we cannot
-- determine that, in the current directory.
myJournalPath :: IO String
myJournalPath = do
s <- envJournalPath
if null s then defaultJournalPath else return s
where
envJournalPath = getEnv journalenvvar `catch` (\_ -> getEnv journalenvvar2 `catch` (\_ -> return ""))
defaultJournalPath = do
home <- getHomeDirectory `catch` (\_ -> return "")
return $ home </> journaldefaultfilename
-- | Read the user's default journal file, or give an error.
myJournal :: IO Journal
myJournal = myJournalPath >>= readJournalFile Nothing >>= either error' return
tests_Hledger_Read = TestList
[
tests_Hledger_Read_JournalReader,
tests_Hledger_Read_TimelogReader,
"journalFile" ~: do
assertBool "journalFile should parse an empty file" (isRight $ parseWithCtx nullctx JournalReader.journalFile "")
jE <- readJournal Nothing "" -- don't know how to get it from journalFile
either error' (assertBool "journalFile parsing an empty file should give an empty journal" . null . jtxns) jE
]
|
Lainepress/hledger
|
hledger-lib/Hledger/Read.hs
|
gpl-3.0
| 6,281
| 0
| 16
| 1,380
| 1,311
| 691
| 620
| 104
| 7
|
{-# LANGUAGE RankNTypes #-}
module Main (
main
) where
import System.Environment
(getArgs)
import Text.CSV
(CSV(..), parseCSVFromFile, parseCSV)
import Prelude hiding (getContents)
import Pipes
import qualified Pipes.Prelude as P
import Control.Monad
(liftM, unless)
import Data.List
(intersperse)
import qualified System.IO as IO
fromHandle :: (MonadIO m) => IO.Handle -> Producer' String m ()
fromHandle h = go
where
go = do
eof <- liftIO $ IO.hIsEOF h
unless eof $ do
str <- liftIO $ IO.hGetContents h
yield str
go
stdin :: (MonadIO m) => Producer' String m ()
stdin = fromHandle IO.stdin
collect :: (Monad m) => Producer a m () -> m (Maybe [a])
collect p = do
x <- next p
return $ case x of
(Left _) -> Nothing
(Right (a, _)) -> Just $ [a]
readStdin :: IO String
readStdin = do
r <- runEffect $ collect stdin
case r of
Nothing -> return ""
(Just s) -> do
return $ concat s
transformResult lr =
case lr of
(Left _) -> Nothing
(Right v) -> Just v
parseArg :: String -> IO (Maybe CSV)
parseArg arg = do
case arg of
"-" -> do
v <- readStdin
return $ transformResult $ parseCSV arg v
_ -> do
r <- parseCSVFromFile arg
return $ transformResult $ r
parse :: String -> IO ()
parse file = do
result <- parseArg file
case result of
Nothing -> putStrLn "Error"
(Just v) -> do
putStrLn $ show $ length v
-- putStrLn $ show v
usage :: String
usage = "usage: ./csv <file.csv>"
main :: IO ()
main = do
argv <- getArgs
case argv of
(file:[]) -> parse file
_ -> putStrLn $ usage
|
adarqui/ToyBox
|
haskell/bos/text/Text.CSV/src/parse.hs
|
gpl-3.0
| 1,563
| 0
| 15
| 374
| 659
| 333
| 326
| 66
| 2
|
{-# LANGUAGE DisambiguateRecordFields, TypeFamilies,
StandaloneDeriving, DeriveFunctor, DeriveFoldable, GeneralizedNewtypeDeriving #-}
-------------------------------------------------------------------------------------
-- |
-- Copyright : (c) Hans Hoglund 2012
-- License : BSD-style
-- Maintainer : hans@hanshoglund.se
-- Stability : experimental
-- Portability : GHC
--
-- Manglers for various kinds of identifiers.
--
-------------------------------------------------------------------------------------
module Language.Modulo.Util.Mangle (
mixedCase,
capitalCase,
sepCase
) where
import Data.Semigroup
import Data.Semigroup
import Language.Modulo.Util
-- |
-- Mangle an indentifier in mixed case, i.e. @[foo, bar]@ becomes @fooBar@.
mixedCase :: [String] -> String
mixedCase [] = []
mixedCase (x:xs) = mconcat $ toLowerString x : fmap toCapitalString xs
-- |
-- Mangle an indentifier in capital case, i.e. @[foo, bar]@ becomes @FooBar@.
capitalCase :: [String] -> String
capitalCase = mconcat . fmap toCapitalString
-- |
-- Mangle an indentifier using the underscore as separator, i.e. @[foo, bar]@ becomes @foo_bar@.
sepCase :: [String] -> String
sepCase = concatSep "_"
|
hanshoglund/modulo
|
src/Language/Modulo/Util/Mangle.hs
|
gpl-3.0
| 1,225
| 0
| 7
| 190
| 152
| 93
| 59
| 16
| 1
|
module Text.Inflections.Tokenizer (
CaseStyle,
camelCase,
snakeCase,
rubyCase,
canTokenize,
tokenize) where
import Data.Char (toLower, isDigit, isLower)
import Data.Either (isRight)
import Text.Inflections
import Text.Inflections.Parse.Types
import Text.Parsec.Error (ParseError)
import Control.Fallible
type CaseStyle = String -> Either Text.Parsec.Error.ParseError [Text.Inflections.Parse.Types.Word]
camelCase :: CaseStyle
camelCase = parseCamelCase [] . filter (not.isDigit)
snakeCase :: CaseStyle
snakeCase = parseSnakeCase []
rubyCase :: CaseStyle
rubyCase word@(i:_) | i == '_' = snakeCase . unprivatize $ baseWord
| isLower i = snakeCase baseWord
| otherwise = camelCase baseWord
where
baseWord = filter (`notElem` "!?+-=[]<>|&*/") word
unprivatize = unprivatizeRight . unprivatizeLeft
unprivatizeLeft ('_':'_':xs) = xs
unprivatizeLeft ('_':xs) = xs
unprivatizeLeft xs = xs
unprivatizeRight = reverse . unprivatizeLeft . reverse
canTokenize :: CaseStyle -> String -> Bool
canTokenize style = isRight . style
tokenize :: CaseStyle -> String -> [String]
tokenize style s | Just words <- (wordsOrNothing . style) s = concatMap toToken words
| otherwise = []
where toToken = return . map toLower
wordsOrNothing = fmap (concatMap c) . orNothing
where c (Word w) = [w]
c _ = []
|
mumuki/mulang
|
src/Text/Inflections/Tokenizer.hs
|
gpl-3.0
| 1,621
| 0
| 11
| 513
| 451
| 243
| 208
| 37
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Monad (unless, when)
import Data.Aeson ((.=), encode, object, ToJSON(..))
import qualified Data.Text as T
import qualified Data.ByteString.Lazy.Char8 as BS8
import System.Environment (getArgs)
import System.Directory (doesFileExist)
import Music.LilyLexer
-- JSON output utilities
instance ToJSON Token where
toJSON (Token _ EOF _) = object ["type" .= EOF]
toJSON (Token pos typ mstr) = object alist
where
alist = ["type" .= typ, "position" .= pos] ++ (
case mstr of
Nothing -> []
Just str -> ["text" .= str])
instance ToJSON TokenType where
toJSON = toJSON . T.pack . show
instance ToJSON AlexPosn where
toJSON (AlexPn pos line col) = object [
"bytes" .= pos, "line" .= line, "column" .= col]
-- The main routine
-- | Read a file and scan it. If successful, the list of tokens are converted to JSON and printed on
-- stdout.
main :: IO ()
main = do
fileList <- getArgs
let filename = head fileList
fileExists <- doesFileExist filename
unless fileExists (error ("The following file does not exist: " ++ filename))
s <- readFile filename
case scanner s of
Left msg -> error msg
Right toks -> (BS8.putStrLn . encode) toks
|
ods94065/lylex
|
src/Main.hs
|
gpl-3.0
| 1,271
| 0
| 14
| 271
| 399
| 214
| 185
| 31
| 2
|
module Parser(Expr(Arg,Quote,Let,CarFn,CdrFn,ConsFn,If,Call),parse) where
import qualified Data.Map as Map
import qualified Data.Set as Set
import Reader(Value(Cons,Nil),foldValue)
data Expr = Arg
| Quote Value
| Let (Map.Map Value Expr) Expr
| CarFn Expr
| CdrFn Expr
| ConsFn Expr Expr
| If Expr Expr Expr
| Call Value Expr
deriving Show
parse :: Value -> Expr
parse value = parseInScope value Set.empty
parseInScope :: Value -> Set.Set Value -> Expr
parseInScope Nil _ = Arg
parseInScope value@(Cons fn arg) scope
| Set.member fn scope = Call fn (parseInScope arg scope)
| otherwise = parseIntrinsic value scope
parseIntrinsic :: Value -> Set.Set Value -> Expr
parseIntrinsic Nil _ = Arg
parseIntrinsic (Cons Nil value) _ = Quote value
parseIntrinsic (Cons (Cons Nil Nil) (Cons bindings body)) scope =
let newScope = foldValue addBoundName scope bindings
addBoundName set Nil = set
addBoundName set (Cons name _) = Set.insert name set
parsedBindings = foldValue addBinding Map.empty bindings
addBinding bindings Nil = bindings
addBinding bindings (Cons name body) =
Map.insert name (parseInScope body newScope) bindings
in Let parsedBindings (parseInScope body newScope)
parseIntrinsic (Cons (Cons (Cons Nil Nil) Nil) arg) scope =
CarFn (parseInScope arg scope)
parseIntrinsic (Cons (Cons Nil (Cons Nil Nil)) arg) scope =
CdrFn (parseInScope arg scope)
parseIntrinsic (Cons (Cons (Cons Nil Nil) (Cons Nil Nil)) Nil) scope =
Quote Nil
parseIntrinsic (Cons (Cons (Cons Nil Nil) (Cons Nil Nil)) (Cons head tail))
scope =
ConsFn (parseInScope head scope) (parseInScope tail scope)
parseIntrinsic (Cons (Cons Nil (Cons Nil (Cons Nil Nil))) Nil) scope =
Quote Nil
parseIntrinsic (Cons (Cons Nil (Cons Nil (Cons Nil Nil))) (Cons _ Nil))
scope =
Quote Nil
parseIntrinsic (Cons (Cons Nil (Cons Nil (Cons Nil Nil)))
(Cons cond (Cons ifTrue ifFalse)))
scope =
If (parseInScope cond scope)
(parseInScope ifTrue scope)
(parseInScope ifFalse scope)
parseIntrinsic _ _ = error "parse"
|
qpliu/esolang
|
ph/hs/compiler/Parser.hs
|
gpl-3.0
| 2,226
| 0
| 13
| 553
| 855
| 440
| 415
| 55
| 3
|
module Codewars.Arrays where
import Data.List
uniqueSum :: [Int] -> Int
uniqueSum = sum . nub
|
ice1000/OI-codes
|
codewars/101-200/unique-sum.hs
|
agpl-3.0
| 96
| 0
| 6
| 17
| 32
| 19
| 13
| 4
| 1
|
-- | Backend specific glue for memories and buffers
module ViperVM.Platform.Peer.MemoryPeer (
MemoryPeer(..), memoryPeerApply,
memoryName, memorySize,
BufferPeer(..), bufferPeerApply,
bufferSize, bufferAllocate, bufferRelease,
hostBuffer, clBuffer
) where
import ViperVM.Backends.Common.Buffer
import qualified ViperVM.Backends.Host.Memory as Host
import qualified ViperVM.Backends.OpenCL.Memory as CL
import qualified ViperVM.Backends.OpenCL.Buffer as CL
import qualified ViperVM.Backends.Host.Buffer as Host
import Data.Word
import Control.Applicative ( (<$>) )
-- | Backend memory
data MemoryPeer = HostMemory Host.Memory
| CLMemory CL.Memory
deriving (Eq,Ord,Show)
data BufferPeer = HostBuffer Host.Buffer
| CLBuffer CL.Buffer
-- | Apply the appropriate given function to the peer memory
memoryPeerApply :: (Host.Memory -> a) -> (CL.Memory -> a) -> MemoryPeer -> a
memoryPeerApply fHost fCL m = case m of
HostMemory peer -> fHost peer
CLMemory peer -> fCL peer
-- | Retrieve memory name
memoryName :: MemoryPeer -> String
memoryName = memoryPeerApply Host.memoryName CL.memoryName
-- | Retrieve memory size
memorySize :: MemoryPeer -> Word64
memorySize = memoryPeerApply Host.memorySize CL.memorySize
-- | Apply the appropriate given function to the peer buffer
bufferPeerApply :: (Host.Buffer -> a) -> (CL.Buffer -> a) -> BufferPeer -> a
bufferPeerApply fHost fCL b = case b of
HostBuffer peer -> fHost peer
CLBuffer peer -> fCL peer
-- | Return the size of the allocated buffer
bufferSize :: BufferPeer -> Word64
bufferSize = bufferPeerApply Host.bufferSize CL.bufferSize
-- | Try to allocate a buffer in a memory
bufferAllocate :: Word64 -> MemoryPeer -> IO (AllocResult BufferPeer)
bufferAllocate sz m = memoryPeerApply
(\m' -> fmap HostBuffer <$> Host.bufferAllocate sz m')
(\m' -> fmap CLBuffer <$> CL.bufferAllocate sz m')
m
-- | Release a buffer
bufferRelease :: BufferPeer -> IO ()
bufferRelease = bufferPeerApply Host.bufferRelease CL.bufferRelease
hostBuffer :: BufferPeer -> Host.Buffer
hostBuffer (HostBuffer b) = b
hostBuffer _ = error "Invalid buffer type"
clBuffer :: BufferPeer -> CL.Buffer
clBuffer (CLBuffer b) = b
clBuffer _ = error "Invalid buffer type"
|
hsyl20/HViperVM
|
lib/ViperVM/Platform/Peer/MemoryPeer.hs
|
lgpl-3.0
| 2,294
| 0
| 10
| 415
| 577
| 321
| 256
| 45
| 2
|
module ProjectM36.FunctionalDependency where
import ProjectM36.Base
import qualified Data.Set as S
data FunctionalDependency = FunctionalDependency AttributeNames AttributeNames RelationalExpr
--(s{city} group ({city} as x) : {z:=count(@x)}) {z}
-- as defined in Relational Algebra and All That Jazz page 21
inclusionDependenciesForFunctionalDependency :: FunctionalDependency -> (InclusionDependency, InclusionDependency)
inclusionDependenciesForFunctionalDependency (FunctionalDependency attrNamesSource attrNamesDependent relExpr) = (
InclusionDependency countSource countDep,
InclusionDependency countDep countSource)
where
countDep = relExprCount relExpr (UnionAttributeNames attrNamesSource attrNamesDependent)
countSource = relExprCount relExpr attrNamesSource
projectZName = Project (AttributeNames (S.singleton "z"))
zCount = FunctionAtomExpr "count" [AttributeAtomExpr "x"] ()
extendZName = Extend (AttributeExtendTupleExpr "z" zCount)
relExprCount expr projectionAttrNames = projectZName (extendZName
(Group projectionAttrNames "x" (Project projectionAttrNames expr)))
|
agentm/project-m36
|
src/lib/ProjectM36/FunctionalDependency.hs
|
unlicense
| 1,131
| 0
| 13
| 151
| 208
| 110
| 98
| 15
| 1
|
module Types.Agent.Omni where
import Types.World
-- |A mind that always does the same thing and which stores all visual/local
-- information about the world (i.e. stench/breeze).
data OmniMind = OmniMind {
-- |The action which the mind will always perform.
_omniMindAction :: Action,
-- |The agent's message store.
_omniMindMessageSpace :: [Message]
}
|
jtapolczai/wumpus
|
Types/Agent/Omni.hs
|
apache-2.0
| 370
| 0
| 9
| 70
| 40
| 27
| 13
| 5
| 0
|
-- Copyright (C) 2009-2012 John Millikin <john@john-millikin.com>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module DBus.Internal.Message
( Message(..)
, UnknownMessage(..)
, MethodCall(..)
, MethodReturn(..)
, MethodError(..)
, methodErrorMessage
, Signal(..)
, ReceivedMessage(..)
-- for use in Wire
, HeaderField(..)
, setMethodCallFlags
) where
import Data.Bits ((.|.), (.&.))
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Word (Word8, Word32)
import DBus.Internal.Types
class Message a where
messageTypeCode :: a -> Word8
messageHeaderFields :: a -> [HeaderField]
messageBody :: a -> [Variant]
messageFlags :: a -> Word8
messageFlags _ = 0
maybe' :: (a -> b) -> Maybe a -> [b]
maybe' f = maybe [] (\x' -> [f x'])
data UnknownMessage = UnknownMessage
{ unknownMessageType :: Word8
, unknownMessageSender :: Maybe BusName
, unknownMessageBody :: [Variant]
}
deriving (Show, Eq)
data HeaderField
= HeaderPath ObjectPath
| HeaderInterface InterfaceName
| HeaderMember MemberName
| HeaderErrorName ErrorName
| HeaderReplySerial Serial
| HeaderDestination BusName
| HeaderSender BusName
| HeaderSignature Signature
| HeaderUnixFds Word32
deriving (Show, Eq)
-- | A method call is a request to run some procedure exported by the
-- remote process. Procedures are identified by an (object_path,
-- interface_name, method_name) tuple.
data MethodCall = MethodCall
{
-- | The object path of the method call. Conceptually, object paths
-- act like a procedural language's pointers. Each object referenced
-- by a path is a collection of procedures.
methodCallPath :: ObjectPath
-- | The interface of the method call. Each object may implement any
-- number of interfaces. Each method is part of at least one
-- interface.
--
-- In certain cases, this may be @Nothing@, but most users should set
-- it to a value.
, methodCallInterface :: Maybe InterfaceName
-- | The method name of the method call. Method names are unique within
-- an interface, but might not be unique within an object.
, methodCallMember :: MemberName
-- | The name of the application that sent this call.
--
-- Most users will just leave this empty, because the bus overwrites
-- the sender for security reasons. Setting the sender manually is
-- used for peer-peer connections.
--
-- Defaults to @Nothing@.
, methodCallSender :: Maybe BusName
-- | The name of the application to send the call to.
--
-- Most users should set this. If a message with no destination is
-- sent to the bus, the bus will behave as if the destination was
-- set to @org.freedesktop.DBus@. For peer-peer connections, the
-- destination can be empty because there is only one peer.
--
-- Defaults to @Nothing@.
, methodCallDestination :: Maybe BusName
-- | Set whether a reply is expected. This can save network and cpu
-- resources by inhibiting unnecessary replies.
--
-- Defaults to @True@.
, methodCallReplyExpected :: Bool
-- | Set whether the bus should auto-start the remote
--
-- Defaults to @True@.
, methodCallAutoStart :: Bool
-- | The arguments to the method call. See 'toVariant'.
--
-- Defaults to @[]@.
, methodCallBody :: [Variant]
}
deriving (Eq, Show)
setMethodCallFlags :: MethodCall -> Word8 -> MethodCall
setMethodCallFlags c w = c
{ methodCallReplyExpected = w .&. 0x1 == 0
, methodCallAutoStart = w .&. 0x2 == 0
}
instance Message MethodCall where
messageTypeCode _ = 1
messageFlags c = foldr (.|.) 0
[ if methodCallReplyExpected c then 0 else 0x1
, if methodCallAutoStart c then 0 else 0x2
]
messageBody = methodCallBody
messageHeaderFields m = concat
[ [ HeaderPath (methodCallPath m)
, HeaderMember (methodCallMember m)
]
, maybe' HeaderInterface (methodCallInterface m)
, maybe' HeaderSender (methodCallSender m)
, maybe' HeaderDestination (methodCallDestination m)
]
-- | A method return is a reply to a method call, indicating that the call
-- succeeded.
data MethodReturn = MethodReturn
{
-- | The serial of the original method call. This lets the original
-- caller match up this reply to the pending call.
methodReturnSerial :: Serial
-- | The name of the application that is returning from a call.
--
-- Most users will just leave this empty, because the bus overwrites
-- the sender for security reasons. Setting the sender manually is
-- used for peer-peer connections.
--
-- Defaults to @Nothing@.
, methodReturnSender :: Maybe BusName
-- | The name of the application that initiated the call.
--
-- Most users should set this. If a message with no destination is
-- sent to the bus, the bus will behave as if the destination was
-- set to @org.freedesktop.DBus@. For peer-peer connections, the
-- destination can be empty because there is only one peer.
--
-- Defaults to @Nothing@.
, methodReturnDestination :: Maybe BusName
-- | Values returned from the method call. See 'toVariant'.
--
-- Defaults to @[]@.
, methodReturnBody :: [Variant]
}
deriving (Show, Eq)
instance Message MethodReturn where
messageTypeCode _ = 2
messageBody = methodReturnBody
messageHeaderFields m = concat
[ [ HeaderReplySerial (methodReturnSerial m)
]
, maybe' HeaderSender (methodReturnSender m)
, maybe' HeaderDestination (methodReturnDestination m)
]
-- | A method error is a reply to a method call, indicating that the call
-- received an error and did not succeed.
data MethodError = MethodError
{
-- | The name of the error type. Names are used so clients can
-- handle certain classes of error differently from others.
methodErrorName :: ErrorName
-- | The serial of the original method call. This lets the original
-- caller match up this reply to the pending call.
, methodErrorSerial :: Serial
-- | The name of the application that is returning from a call.
--
-- Most users will just leave this empty, because the bus overwrites
-- the sender for security reasons. Setting the sender manually is
-- used for peer-peer connections.
--
-- Defaults to @Nothing@.
, methodErrorSender :: Maybe BusName
-- | The name of the application that initiated the call.
--
-- Most users should set this. If a message with no destination is
-- sent to the bus, the bus will behave as if the destination was
-- set to @org.freedesktop.DBus@. For peer-peer connections, the
-- destination can be empty because there is only one peer.
--
-- Defaults to @Nothing@.
, methodErrorDestination :: Maybe BusName
-- | Additional information about the error. By convention, if
-- the error body contains any items, the first item should be a
-- string describing the error.
, methodErrorBody :: [Variant]
}
deriving (Show, Eq)
instance Message MethodError where
messageTypeCode _ = 3
messageBody = methodErrorBody
messageHeaderFields m = concat
[ [ HeaderErrorName (methodErrorName m)
, HeaderReplySerial (methodErrorSerial m)
]
, maybe' HeaderSender (methodErrorSender m)
, maybe' HeaderDestination (methodErrorDestination m)
]
-- | Get a human-readable description of the error, by returning the first
-- item in the error body if it's a string.
methodErrorMessage :: MethodError -> String
methodErrorMessage err = fromMaybe "(no error message)" $ do
field <- listToMaybe (methodErrorBody err)
msg <- fromVariant field
if null msg
then Nothing
else return msg
-- | Signals are broadcast by applications to notify other clients of some
-- event.
data Signal = Signal
{
-- | The path of the object that emitted this signal.
signalPath :: ObjectPath
-- | The interface that this signal belongs to.
, signalInterface :: InterfaceName
-- | The name of this signal.
, signalMember :: MemberName
-- | The name of the application that emitted this signal.
--
-- Most users will just leave this empty, because the bus overwrites
-- the sender for security reasons. Setting the sender manually is
-- used for peer-peer connections.
--
-- Defaults to @Nothing@.
, signalSender :: Maybe BusName
-- | The name of the application to emit the signal to. If @Nothing@,
-- the signal is sent to any application that has registered an
-- appropriate match rule.
--
-- Defaults to @Nothing@.
, signalDestination :: Maybe BusName
-- | Additional information about the signal, such as the new value
-- or the time.
--
-- Defaults to @[]@.
, signalBody :: [Variant]
}
deriving (Show, Eq)
instance Message Signal where
messageTypeCode _ = 4
messageBody = signalBody
messageHeaderFields m = concat
[ [ HeaderPath (signalPath m)
, HeaderMember (signalMember m)
, HeaderInterface (signalInterface m)
]
, maybe' HeaderSender (signalSender m)
, maybe' HeaderDestination (signalDestination m)
]
-- | Not an actual message type, but a wrapper around messages received from
-- the bus. Each value contains the message's 'Serial'.
--
-- If casing against these constructors, always include a default case to
-- handle messages of an unknown type. New message types may be added to the
-- D-Bus specification, and applications should handle them gracefully by
-- either ignoring or logging them.
data ReceivedMessage
= ReceivedMethodCall Serial MethodCall
| ReceivedMethodReturn Serial MethodReturn
| ReceivedMethodError Serial MethodError
| ReceivedSignal Serial Signal
| ReceivedUnknown Serial UnknownMessage
deriving (Show, Eq)
|
rblaze/haskell-dbus
|
lib/DBus/Internal/Message.hs
|
apache-2.0
| 10,785
| 0
| 11
| 2,697
| 1,302
| 783
| 519
| 124
| 2
|
module Text.HandsomeSoup (openUrl, fromUrl, parseHtml, (!), css) where
import Text.XML.HXT.Core
import Network.HTTP
import Network.URI
import Data.Tree.NTree.TypeDefs
import Control.Monad.Trans.Maybe
import Control.Monad.Trans
import Data.Maybe
import Text.Parsec
import qualified Data.Map as M
import Data.Monoid (mconcat)
import qualified Data.Functor.Identity as I
import qualified Debug.Trace as D
import Data.List
import Control.Monad
import Text.CSS.Parser hiding (css)
import Text.XML.HXT.Arrow.ReadDocument
import Text.XML.HXT.HTTP
-- | Helper function for getting page content. Example:
--
-- > contents <- runMaybeT $ openUrl "http://foo.com"
openUrl :: String -> MaybeT IO String
openUrl url = case parseURI url of
Nothing -> fail "couldn't parse url"
Just u -> liftIO (getResponseBody =<< simpleHTTP (mkRequest GET u))
-- | Given a url, returns a document. Example:
--
-- > doc = fromUrl "http://foo.com"
-- > doc = fromUrl "tests/test.html"
fromUrl :: String -> IOSArrow b (NTree XNode)
fromUrl url = readDocument [withValidate no,
withInputEncoding utf8,
withParseByMimeType yes,
withHTTP [],
withWarnings no] url
-- | Given a string, parses it and returns a document. Example:
--
-- > doc = parseHtml "<h1>hello!</h1>"
parseHtml :: String -> IOSArrow b (NTree XNode)
parseHtml = readString [withParseHTML yes, withWarnings no]
-- | Shortcut for getting attributes. Example:
--
-- > doc >>> css "a" ! "href"
(!) :: ArrowXml cat => cat a XmlTree -> String -> cat a String
(!) a str = a >>> getAttrValue str
-- | A css selector for getting elements from a document. Example:
--
-- > doc >>> css "#menu li"
css :: ArrowXml a => [Char] -> a (NTree XNode) (NTree XNode)
css tag = case (parse selector "" tag) of
Left err -> D.trace (show err) this
Right x -> fromSelectors x
-- | Used internally. works on a selector (i.e a list of simple selectors)
fromSelectors sel@(s:selectors) = foldl (\acc selector -> acc <+> _fromSelectors selector) (_fromSelectors s) selectors
-- | Used internally. works on simple selectors and their combinators
_fromSelectors (s:selectors) = foldl (\acc selector -> make acc selector) (make this s) selectors
where
make acc sel@(Selector name attrs pseudo)
| name == "*" = acc >>> ((multi this >>> makeAttrs attrs) >>. makePseudos pseudo)
| otherwise = acc >>> ((multi $ hasName name >>> makeAttrs attrs) >>. makePseudos pseudo)
make acc Space = acc >>> getChildren
make acc ChildOf = acc >>> getChildren >>> processChildren none
makeAttrs (a:attrs) = foldl (\acc attr -> acc >>> makeAttr attr) (makeAttr a) attrs
makeAttrs [] = this
makeAttr (name, "") = hasAttr name
makeAttr (name, '~':value) = hasAttrValue name (elem value . words)
makeAttr (name, '|':value) = hasAttrValue name (headMatch value)
makeAttr (name, value) = hasAttrValue name (==value)
makePseudos (p:pseudos) = foldl (\acc pseudo -> acc >>> makePseudo pseudo) (makePseudo p) pseudos
makePseudos [] = id
makePseudo selector
| selector == "first-child" = take 1
| nthSelector selector = take 1 . drop (n - 1)
where nthSelector selector = take 10 selector == "nth-child("
getN selector = read $ (takeWhile (/= ')') . drop 10) selector :: Int
n = getN selector
-- | Used internally to match attribute selectors like @ [att|=val] @.
-- From: http://www.w3.org/TR/CSS2/selector.html
-- "Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by '-'".
headMatch value attrValue = value == attrValue || value `isPrefixOf` attrValue
where first = head . words $ attrValue
|
egonSchiele/HandsomeSoup
|
src/Text/HandsomeSoup.hs
|
bsd-3-clause
| 3,911
| 0
| 14
| 916
| 1,074
| 571
| 503
| 59
| 8
|
{-# LANGUAGE DoAndIfThenElse #-}
module Main where
import LJRSS.ConcurrentAgregate
import LJRSS.LJConfig
import LJRSS.LJFeed
import LJRSS.Email
import System.Console.GetOpt
import qualified Data.Map as DM
import qualified Data.Set as DS
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Control.Monad.Error (runErrorT, liftIO)
import Control.Monad (liftM)
import Control.Applicative ((<$>))
import System.Environment (getArgs)
import System.IO
data CMDOptions = Init | Update | Snapshot | Threads Int | UpdateUser String deriving (Show)
options :: [OptDescr CMDOptions]
options = [ Option ['i'] ["init"] (NoArg Init) "Initialize settings",
Option ['r'] ["refresh"] (NoArg Update) "Update all friends",
Option ['s'] ["snapshot"] (NoArg Snapshot) "Take snapshot of last post dates - no mail",
Option ['t'] ["threads"] (ReqArg (Threads . read) "5") "Number of threads",
Option ['u'] ["update"] (OptArg (UpdateUser . fromMaybe "") "USERNAME") "Update (or add) single journal"
]
main = do
parsedOption <- validate =<< liftM (getOpt Permute options) getArgs
go parsedOption
where
validate ([],_,_) = failWithError ["No options provided"]
validate (opts,_,[]) = return opts
validate (_,_,errs) = failWithError $ "Parse error " : errs
failWithError errs = fail $ concat errs ++ usageInfo "Usage: ljrss [OPTION]" options
go [Init] = do
putStrLn "Please provide LiveJournal username"
username <- getLine
password <- readPassword
skipList <- ignored
putStrLn "Please provide target email address to be used for sending notifications"
recipient <- getLine
putStrLn "Please provide sender email address to use in From: field of notifications"
sender <- getLine
putStrLn "Do the following settings look ok?"
putStrLn $ formatTextL "Username" 12 ++ username
putStrLn $ formatTextL "From" 12 ++ sender
putStrLn $ formatTextL "To" 12 ++ recipient
putStrLn $ formatTextL "Ignored" 12 ++ (show $ DS.toList skipList)
putStrLn "[Y]es or [N]o?"
yesNo <- getLine
if "Y" /= yesNo && "y" /= yesNo
then do
go [Init]
else do
writeConfig $ LJConfig username password recipient sender skipList 10 5 DM.empty True
putStrLn "Configuration created, now use 'ljrss -r' to read friend feed"
where
formatTextL src len = T.unpack . T.justifyLeft len ' ' $ T.pack src
ignored = do
putStrLn "Do you want to setup ignored users (Y/N)?"
answer <- getLine
if answer /= "Y" && answer /= "y"
then do
return DS.empty
else do
putStrLn "Provide usernames line by line, empty line completes list"
readIgnored
readIgnored = do
username <- getLine
if null username
then
return DS.empty
else
(DS.insert username ) <$> readIgnored
readPassword = do
hSetEcho stdout False
putStrLn "Please provide LiveJournal password"
password <- getLine
putStrLn "Please confirm LiveJournal password"
confirmPassword <- getLine
hSetEcho stdout True
if (password /= confirmPassword)
then do
putStrLn "\nPasswords mismatch, please try again \n"
readPassword
else
return password
go [Update, (Threads numThreads)] = do
currentCfg <- readConfig
newConfig <- aggregateEntriesDefaultExclude numThreads currentCfg
writeConfig $ newConfig { noEntries = False }
go [Snapshot, (Threads numThreads)] = do
currentCfg <- readConfig
newConfig <- aggregateEntriesDefaultExclude numThreads $ currentCfg { noEntries = True }
writeConfig $ newConfig { noEntries = False }
go _ = putStrLn $ usageInfo "Usage: ljrss [OPTION]" options
|
jdevelop/lj2rss
|
Main.hs
|
bsd-3-clause
| 3,728
| 0
| 13
| 845
| 1,008
| 510
| 498
| 88
| 5
|
module Sharc.Instruments.ViolaMuted (violaMuted) where
import Sharc.Types
violaMuted :: Instr
violaMuted = Instr
"viola_muted_vibrato"
"Viola (muted)"
(Legend "McGill" "1" "7")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 130.81 36 "c3"))
(Pitch 130.81 36 "c3")
(Amplitude 8110.4 (HarmonicFreq 62 (Pitch 130.813 36 "c3")) 0.16))
(InstrRange
(HarmonicFreq 61 (Pitch 10053.65 40 "e3"))
(Pitch 1174.66 74 "d6")
(Amplitude 440.0 (HarmonicFreq 1 (Pitch 440.0 57 "a4")) 10430.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35
,note36
,note37
,note38]
note0 :: Note
note0 = Note
(Pitch 130.813 36 "c3")
1
(Range
(NoteRange
(NoteRangeAmplitude 8110.4 62 0.16)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 654.06 5 3382.0)
(NoteRangeHarmonicFreq 76 9941.78)))
[Harmonic 1 (-0.712) 162.48
,Harmonic 2 (-1.584) 409.73
,Harmonic 3 (-0.213) 456.09
,Harmonic 4 2.39 1893.23
,Harmonic 5 1.459 3382.0
,Harmonic 6 1.496 119.74
,Harmonic 7 (-0.407) 491.58
,Harmonic 8 1.967 235.04
,Harmonic 9 (-0.525) 789.45
,Harmonic 10 2.864 170.39
,Harmonic 11 (-0.678) 141.02
,Harmonic 12 2.675 195.14
,Harmonic 13 1.299 252.49
,Harmonic 14 0.835 92.9
,Harmonic 15 (-0.771) 69.01
,Harmonic 16 1.13 179.88
,Harmonic 17 1.336 173.65
,Harmonic 18 0.472 41.45
,Harmonic 19 0.945 38.48
,Harmonic 20 (-1.768) 29.89
,Harmonic 21 (-0.708) 28.69
,Harmonic 22 2.812 42.56
,Harmonic 23 (-0.837) 46.42
,Harmonic 24 1.386 53.12
,Harmonic 25 (-0.203) 20.17
,Harmonic 26 2.458 6.81
,Harmonic 27 0.658 14.73
,Harmonic 28 2.689 41.28
,Harmonic 29 2.424 72.22
,Harmonic 30 3.109 20.23
,Harmonic 31 0.29 6.17
,Harmonic 32 0.168 10.38
,Harmonic 33 (-0.865) 18.13
,Harmonic 34 (-0.836) 8.98
,Harmonic 35 3.117 7.24
,Harmonic 36 (-2.649) 17.5
,Harmonic 37 (-1.073) 2.75
,Harmonic 38 0.644 8.93
,Harmonic 39 1.129 10.66
,Harmonic 40 1.403 10.16
,Harmonic 41 1.542 1.9
,Harmonic 42 (-2.659) 0.78
,Harmonic 43 1.732 2.48
,Harmonic 44 (-2.273) 5.42
,Harmonic 45 (-2.444) 6.48
,Harmonic 46 (-1.247) 4.11
,Harmonic 47 (-1.705) 4.13
,Harmonic 48 0.745 1.2
,Harmonic 49 (-2.411) 2.83
,Harmonic 50 3.08 2.07
,Harmonic 51 (-2.845) 0.44
,Harmonic 52 (-9.4e-2) 1.73
,Harmonic 53 0.44 0.76
,Harmonic 54 2.241 1.87
,Harmonic 55 2.81 1.05
,Harmonic 56 (-2.12) 2.97
,Harmonic 57 (-2.007) 3.93
,Harmonic 58 (-1.828) 1.27
,Harmonic 59 1.89 1.38
,Harmonic 60 1.364 1.23
,Harmonic 61 2.122 0.57
,Harmonic 62 (-2.658) 0.16
,Harmonic 63 2.64 1.17
,Harmonic 64 3.0 0.98
,Harmonic 65 2.82 1.85
,Harmonic 66 (-2.554) 1.85
,Harmonic 67 (-2.244) 1.66
,Harmonic 68 (-1.246) 0.99
,Harmonic 69 0.119 1.27
,Harmonic 70 1.143 1.21
,Harmonic 71 1.903 1.42
,Harmonic 72 2.737 2.19
,Harmonic 73 (-3.059) 2.84
,Harmonic 74 (-2.766) 5.63
,Harmonic 75 (-2.915) 3.62
,Harmonic 76 (-2.646) 1.87]
note1 :: Note
note1 = Note
(Pitch 138.591 37 "c#3")
2
(Range
(NoteRange
(NoteRangeAmplitude 6652.36 48 0.53)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 277.18 2 5901.0)
(NoteRangeHarmonicFreq 72 9978.55)))
[Harmonic 1 (-1.814) 177.54
,Harmonic 2 1.296 5901.0
,Harmonic 3 (-2.998) 1255.77
,Harmonic 4 2.481 1106.98
,Harmonic 5 (-1.691) 1331.89
,Harmonic 6 (-5.6e-2) 472.25
,Harmonic 7 0.736 109.52
,Harmonic 8 1.574 112.13
,Harmonic 9 0.798 1125.12
,Harmonic 10 2.188 139.88
,Harmonic 11 0.203 209.2
,Harmonic 12 1.874 461.27
,Harmonic 13 (-2.002) 291.82
,Harmonic 14 (-2.51) 66.8
,Harmonic 15 (-1.269) 276.56
,Harmonic 16 (-1.905) 221.61
,Harmonic 17 1.72 56.64
,Harmonic 18 (-2.068) 72.25
,Harmonic 19 1.127 134.02
,Harmonic 20 0.482 129.22
,Harmonic 21 0.985 70.39
,Harmonic 22 1.268 50.9
,Harmonic 23 (-7.8e-2) 89.03
,Harmonic 24 (-0.606) 17.86
,Harmonic 25 (-1.988) 10.19
,Harmonic 26 2.252 50.83
,Harmonic 27 1.209 68.31
,Harmonic 28 (-2.801) 26.85
,Harmonic 29 2.621 56.4
,Harmonic 30 2.076 27.22
,Harmonic 31 2.036 9.54
,Harmonic 32 2.515 11.64
,Harmonic 33 2.642 16.46
,Harmonic 34 1.915 14.34
,Harmonic 35 (-0.867) 13.12
,Harmonic 36 (-2.105) 3.89
,Harmonic 37 0.178 5.0
,Harmonic 38 (-0.543) 16.78
,Harmonic 39 (-0.589) 7.45
,Harmonic 40 4.9e-2 0.79
,Harmonic 41 1.552 2.07
,Harmonic 42 (-2.154) 4.43
,Harmonic 43 (-2.04) 3.69
,Harmonic 44 (-2.729) 5.94
,Harmonic 45 (-1.498) 3.02
,Harmonic 46 (-1.693) 3.85
,Harmonic 47 (-2.518) 0.79
,Harmonic 48 2.147 0.53
,Harmonic 49 2.724 2.94
,Harmonic 50 (-2.027) 6.01
,Harmonic 51 2.329 1.27
,Harmonic 52 0.14 1.41
,Harmonic 53 0.977 1.86
,Harmonic 54 1.017 3.01
,Harmonic 55 1.447 3.47
,Harmonic 56 1.962 1.29
,Harmonic 57 (-3.051) 2.56
,Harmonic 58 (-2.075) 3.92
,Harmonic 59 (-1.79) 7.22
,Harmonic 60 (-1.463) 6.67
,Harmonic 61 (-0.587) 3.95
,Harmonic 62 (-5.9e-2) 2.95
,Harmonic 63 1.311 1.68
,Harmonic 64 1.963 3.13
,Harmonic 65 2.473 2.86
,Harmonic 66 (-2.989) 3.02
,Harmonic 67 (-2.073) 1.17
,Harmonic 68 0.574 2.55
,Harmonic 69 0.8 2.31
,Harmonic 70 1.834 0.73
,Harmonic 71 1.947 1.58
,Harmonic 72 1.808 2.35]
note2 :: Note
note2 = Note
(Pitch 146.832 38 "d3")
3
(Range
(NoteRange
(NoteRangeAmplitude 6607.44 45 0.34)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 293.66 2 4885.0)
(NoteRangeHarmonicFreq 68 9984.57)))
[Harmonic 1 (-3.4e-2) 208.12
,Harmonic 2 2.296 4885.0
,Harmonic 3 (-1.575) 3791.23
,Harmonic 4 (-7.9e-2) 2379.89
,Harmonic 5 (-1.137) 3788.04
,Harmonic 6 (-2.47) 189.04
,Harmonic 7 (-2.655) 1485.38
,Harmonic 8 1.518 70.6
,Harmonic 9 (-0.793) 665.69
,Harmonic 10 1.529 499.53
,Harmonic 11 2.675 337.18
,Harmonic 12 (-1.583) 413.95
,Harmonic 13 (-1.963) 188.74
,Harmonic 14 1.009 228.8
,Harmonic 15 1.401 172.93
,Harmonic 16 1.559 184.03
,Harmonic 17 (-1.356) 160.46
,Harmonic 18 (-2.745) 50.63
,Harmonic 19 (-1.676) 149.76
,Harmonic 20 (-0.746) 87.07
,Harmonic 21 0.461 46.24
,Harmonic 22 2.051 95.34
,Harmonic 23 (-2.436) 33.48
,Harmonic 24 0.304 31.07
,Harmonic 25 2.407 29.85
,Harmonic 26 (-2.653) 52.66
,Harmonic 27 (-0.499) 77.42
,Harmonic 28 0.545 57.74
,Harmonic 29 (-1.039) 11.69
,Harmonic 30 (-3.088) 6.28
,Harmonic 31 (-1.0) 10.35
,Harmonic 32 1.462 21.06
,Harmonic 33 0.856 21.54
,Harmonic 34 0.479 4.49
,Harmonic 35 2.325 4.69
,Harmonic 36 (-2.372) 15.94
,Harmonic 37 (-1.737) 10.67
,Harmonic 38 0.222 3.3
,Harmonic 39 1.679 6.56
,Harmonic 40 3.048 6.41
,Harmonic 41 (-0.391) 3.27
,Harmonic 42 2.791 5.21
,Harmonic 43 (-8.4e-2) 3.2
,Harmonic 44 0.985 5.09
,Harmonic 45 (-0.83) 0.34
,Harmonic 46 1.458 4.56
,Harmonic 47 1.103 3.72
,Harmonic 48 1.213 4.53
,Harmonic 49 2.006 1.52
,Harmonic 50 (-2.063) 6.41
,Harmonic 51 (-0.117) 9.4
,Harmonic 52 1.985 7.62
,Harmonic 53 (-1.274) 4.14
,Harmonic 54 0.359 1.31
,Harmonic 55 (-1.152) 3.82
,Harmonic 56 2.214 1.12
,Harmonic 57 (-0.313) 1.61
,Harmonic 58 (-1.033) 0.68
,Harmonic 59 0.317 2.32
,Harmonic 60 2.498 2.55
,Harmonic 61 (-0.838) 1.79
,Harmonic 62 1.502 1.59
,Harmonic 63 (-1.411) 0.86
,Harmonic 64 (-1.532) 4.13
,Harmonic 65 0.865 4.52
,Harmonic 66 (-3.082) 8.08
,Harmonic 67 (-0.693) 8.61
,Harmonic 68 1.011 3.07]
note3 :: Note
note3 = Note
(Pitch 155.563 39 "d#3")
4
(Range
(NoteRange
(NoteRangeAmplitude 9489.34 61 0.62)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 622.25 4 2818.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 (-1.465) 240.24
,Harmonic 2 0.295 2073.08
,Harmonic 3 (-2.695) 2165.61
,Harmonic 4 (-1.775) 2818.0
,Harmonic 5 2.99 610.21
,Harmonic 6 (-1.155) 597.5
,Harmonic 7 1.056 692.36
,Harmonic 8 (-0.462) 525.6
,Harmonic 9 (-1.048) 286.81
,Harmonic 10 (-0.495) 181.4
,Harmonic 11 (-2.01) 188.43
,Harmonic 12 0.721 58.02
,Harmonic 13 2.606 218.84
,Harmonic 14 1.23 199.35
,Harmonic 15 (-9.8e-2) 167.78
,Harmonic 16 2.031 46.69
,Harmonic 17 (-1.141) 103.18
,Harmonic 18 3.085 93.3
,Harmonic 19 2.278 31.65
,Harmonic 20 2.587 87.37
,Harmonic 21 1.258 106.89
,Harmonic 22 0.98 16.33
,Harmonic 23 9.3e-2 18.42
,Harmonic 24 (-2.911) 70.7
,Harmonic 25 (-2.375) 52.65
,Harmonic 26 (-2.483) 67.77
,Harmonic 27 3.122 15.95
,Harmonic 28 (-2.826) 14.04
,Harmonic 29 (-2.062) 9.36
,Harmonic 30 (-2.255) 8.41
,Harmonic 31 (-1.81) 0.8
,Harmonic 32 (-0.118) 4.96
,Harmonic 33 (-0.168) 18.27
,Harmonic 34 (-0.83) 18.47
,Harmonic 35 (-1.34) 7.35
,Harmonic 36 (-0.832) 2.25
,Harmonic 37 2.0 4.36
,Harmonic 38 2.543 10.57
,Harmonic 39 2.237 6.55
,Harmonic 40 (-0.757) 4.17
,Harmonic 41 0.651 6.17
,Harmonic 42 0.692 4.53
,Harmonic 43 2.564 2.13
,Harmonic 44 1.885 4.7
,Harmonic 45 1.436 5.03
,Harmonic 46 1.009 1.91
,Harmonic 47 (-1.932) 3.11
,Harmonic 48 (-1.575) 2.8
,Harmonic 49 (-0.198) 3.75
,Harmonic 50 (-0.768) 1.74
,Harmonic 51 1.652 1.62
,Harmonic 52 2.058 3.68
,Harmonic 53 2.621 4.01
,Harmonic 54 3.05 4.03
,Harmonic 55 (-3.09) 2.81
,Harmonic 56 2.964 3.36
,Harmonic 57 (-2.662) 2.02
,Harmonic 58 (-0.847) 2.93
,Harmonic 59 (-0.289) 3.48
,Harmonic 60 0.804 1.54
,Harmonic 61 0.284 0.62
,Harmonic 62 (-0.104) 1.13
,Harmonic 63 0.661 2.15
,Harmonic 64 1.022 1.51]
note4 :: Note
note4 = Note
(Pitch 164.814 40 "e3")
5
(Range
(NoteRange
(NoteRangeAmplitude 8735.14 53 0.3)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 659.25 4 3773.0)
(NoteRangeHarmonicFreq 61 10053.65)))
[Harmonic 1 1.407 459.27
,Harmonic 2 8.0e-2 3470.12
,Harmonic 3 (-2.014) 366.89
,Harmonic 4 2.256 3773.0
,Harmonic 5 2.98 322.08
,Harmonic 6 2.535 549.39
,Harmonic 7 1.58 983.93
,Harmonic 8 (-0.971) 653.02
,Harmonic 9 3.092 508.13
,Harmonic 10 1.265 176.35
,Harmonic 11 2.154 67.73
,Harmonic 12 2.927 149.85
,Harmonic 13 (-0.474) 495.71
,Harmonic 14 0.643 460.63
,Harmonic 15 (-1.639) 95.2
,Harmonic 16 (-2.394) 74.67
,Harmonic 17 (-0.429) 167.18
,Harmonic 18 0.763 122.52
,Harmonic 19 (-1.096) 72.97
,Harmonic 20 (-1.392) 83.99
,Harmonic 21 1.49 48.54
,Harmonic 22 2.563 54.35
,Harmonic 23 1.904 91.47
,Harmonic 24 (-1.67) 10.98
,Harmonic 25 2.287 52.49
,Harmonic 26 (-2.302) 39.82
,Harmonic 27 9.8e-2 23.57
,Harmonic 28 3.077 19.11
,Harmonic 29 0.639 21.85
,Harmonic 30 (-2.922) 14.38
,Harmonic 31 1.076 7.69
,Harmonic 32 (-2.939) 11.29
,Harmonic 33 8.2e-2 3.56
,Harmonic 34 1.47 3.69
,Harmonic 35 (-2.122) 10.74
,Harmonic 36 (-1.727) 9.68
,Harmonic 37 0.771 13.03
,Harmonic 38 (-2.871) 7.32
,Harmonic 39 1.677 3.22
,Harmonic 40 (-1.785) 2.85
,Harmonic 41 (-1.285) 6.39
,Harmonic 42 1.384 2.66
,Harmonic 43 (-2.077) 3.88
,Harmonic 44 2.311 2.45
,Harmonic 45 2.818 4.31
,Harmonic 46 1.391 3.74
,Harmonic 47 (-2.076) 8.33
,Harmonic 48 (-0.234) 4.98
,Harmonic 49 2.225 4.25
,Harmonic 50 (-2.094) 2.91
,Harmonic 51 0.488 4.28
,Harmonic 52 (-3.053) 2.98
,Harmonic 53 (-0.554) 0.3
,Harmonic 54 0.563 1.3
,Harmonic 55 (-2.527) 1.95
,Harmonic 56 0.429 1.57
,Harmonic 57 1.951 1.2
,Harmonic 58 (-4.1e-2) 3.0
,Harmonic 59 1.97 3.53
,Harmonic 60 2.983 1.69
,Harmonic 61 2.084 0.39]
note5 :: Note
note5 = Note
(Pitch 174.614 41 "f3")
6
(Range
(NoteRange
(NoteRangeAmplitude 9254.54 53 0.84)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 698.45 4 3108.0)
(NoteRangeHarmonicFreq 57 9952.99)))
[Harmonic 1 (-1.786) 1391.14
,Harmonic 2 (-0.833) 2495.33
,Harmonic 3 (-0.472) 2413.48
,Harmonic 4 (-2.511) 3108.0
,Harmonic 5 (-2.901) 823.9
,Harmonic 6 (-1.716) 824.53
,Harmonic 7 0.791 1131.21
,Harmonic 8 0.849 113.2
,Harmonic 9 0.302 84.07
,Harmonic 10 (-1.814) 578.86
,Harmonic 11 2.63 568.7
,Harmonic 12 2.597 283.44
,Harmonic 13 1.2 513.19
,Harmonic 14 (-2.975) 136.21
,Harmonic 15 (-0.223) 373.25
,Harmonic 16 (-2.479) 299.73
,Harmonic 17 2.575 112.63
,Harmonic 18 (-3.134) 93.29
,Harmonic 19 (-2.249) 16.42
,Harmonic 20 1.403 125.54
,Harmonic 21 (-1.468) 113.54
,Harmonic 22 (-2.234) 21.9
,Harmonic 23 (-1.475) 142.86
,Harmonic 24 (-1.551) 35.33
,Harmonic 25 (-2.03) 28.37
,Harmonic 26 (-1.466) 18.09
,Harmonic 27 (-2.52) 46.15
,Harmonic 28 1.127 24.97
,Harmonic 29 (-0.324) 14.31
,Harmonic 30 0.626 14.93
,Harmonic 31 0.66 23.67
,Harmonic 32 (-2.799) 7.17
,Harmonic 33 (-2.96) 15.69
,Harmonic 34 2.961 14.98
,Harmonic 35 (-2.81) 5.11
,Harmonic 36 (-1.599) 2.18
,Harmonic 37 (-2.946) 6.85
,Harmonic 38 (-1.992) 3.95
,Harmonic 39 2.418 6.32
,Harmonic 40 2.939 4.54
,Harmonic 41 2.583 1.5
,Harmonic 42 0.852 14.71
,Harmonic 43 1.185 13.72
,Harmonic 44 1.102 2.45
,Harmonic 45 (-1.368) 6.18
,Harmonic 46 (-1.692) 8.66
,Harmonic 47 (-2.682) 3.96
,Harmonic 48 0.848 4.07
,Harmonic 49 1.097 2.67
,Harmonic 50 0.349 1.53
,Harmonic 51 2.559 2.44
,Harmonic 52 2.192 3.24
,Harmonic 53 (-1.91) 0.84
,Harmonic 54 2.231 4.77
,Harmonic 55 2.612 8.85
,Harmonic 56 (-2.621) 1.19
,Harmonic 57 1.401 3.28]
note6 :: Note
note6 = Note
(Pitch 184.997 42 "f#3")
7
(Range
(NoteRange
(NoteRangeAmplitude 6659.89 36 1.68)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 369.99 2 4468.0)
(NoteRangeHarmonicFreq 53 9804.84)))
[Harmonic 1 (-2.475) 2264.59
,Harmonic 2 (-0.759) 4468.0
,Harmonic 3 1.318 2056.46
,Harmonic 4 2.213 3576.37
,Harmonic 5 (-1.368) 1762.42
,Harmonic 6 0.282 151.49
,Harmonic 7 0.441 1190.96
,Harmonic 8 2.011 648.17
,Harmonic 9 (-1.143) 362.97
,Harmonic 10 (-1.455) 724.93
,Harmonic 11 1.853 550.31
,Harmonic 12 0.824 565.4
,Harmonic 13 2.576 315.37
,Harmonic 14 (-2.362) 181.77
,Harmonic 15 1.914 360.1
,Harmonic 16 0.902 240.2
,Harmonic 17 1.22 211.02
,Harmonic 18 1.436 58.38
,Harmonic 19 (-2.809) 193.33
,Harmonic 20 (-0.311) 90.91
,Harmonic 21 1.983 42.58
,Harmonic 22 1.836 361.07
,Harmonic 23 0.0 114.35
,Harmonic 24 0.949 23.2
,Harmonic 25 2.089 48.48
,Harmonic 26 2.407 77.09
,Harmonic 27 2.811 71.18
,Harmonic 28 1.709 41.7
,Harmonic 29 2.556 14.39
,Harmonic 30 (-0.749) 34.05
,Harmonic 31 0.181 78.96
,Harmonic 32 (-0.554) 72.37
,Harmonic 33 (-0.845) 30.24
,Harmonic 34 2.8e-2 9.33
,Harmonic 35 0.421 14.59
,Harmonic 36 (-2.744) 1.68
,Harmonic 37 (-2.741) 16.92
,Harmonic 38 0.349 2.41
,Harmonic 39 1.826 13.64
,Harmonic 40 1.456 29.69
,Harmonic 41 0.335 7.61
,Harmonic 42 (-0.517) 9.97
,Harmonic 43 (-0.263) 9.76
,Harmonic 44 0.347 3.68
,Harmonic 45 (-0.329) 5.97
,Harmonic 46 (-0.172) 2.02
,Harmonic 47 (-2.9e-2) 3.34
,Harmonic 48 1.388 3.43
,Harmonic 49 1.944 4.52
,Harmonic 50 2.472 7.17
,Harmonic 51 2.73 12.47
,Harmonic 52 2.683 11.62
,Harmonic 53 2.666 10.68]
note7 :: Note
note7 = Note
(Pitch 195.998 43 "g3")
8
(Range
(NoteRange
(NoteRangeAmplitude 8819.91 45 0.94)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 587.99 3 2969.0)
(NoteRangeHarmonicFreq 51 9995.89)))
[Harmonic 1 (-2.915) 2214.0
,Harmonic 2 (-2.707) 1751.43
,Harmonic 3 (-0.502) 2969.0
,Harmonic 4 (-2.27) 453.6
,Harmonic 5 (-2.053) 1331.89
,Harmonic 6 0.908 323.48
,Harmonic 7 (-1.32) 1019.88
,Harmonic 8 0.485 506.47
,Harmonic 9 (-0.937) 317.98
,Harmonic 10 0.868 580.37
,Harmonic 11 (-6.7e-2) 722.76
,Harmonic 12 0.373 190.8
,Harmonic 13 (-2.224) 204.22
,Harmonic 14 1.79 292.08
,Harmonic 15 1.416 415.89
,Harmonic 16 0.539 234.84
,Harmonic 17 1.708 90.51
,Harmonic 18 (-3.087) 26.46
,Harmonic 19 (-1.293) 247.65
,Harmonic 20 (-0.646) 141.21
,Harmonic 21 (-1.111) 121.53
,Harmonic 22 (-2.214) 81.62
,Harmonic 23 (-1.657) 23.68
,Harmonic 24 (-0.405) 91.0
,Harmonic 25 (-0.91) 36.68
,Harmonic 26 0.272 43.89
,Harmonic 27 (-0.626) 47.72
,Harmonic 28 (-1.442) 10.24
,Harmonic 29 (-1.481) 4.06
,Harmonic 30 (-2.301) 11.68
,Harmonic 31 (-0.918) 22.95
,Harmonic 32 (-0.523) 21.07
,Harmonic 33 (-1.671) 11.69
,Harmonic 34 0.261 18.04
,Harmonic 35 (-0.532) 9.04
,Harmonic 36 (-3.051) 13.16
,Harmonic 37 1.499 6.03
,Harmonic 38 (-1.565) 15.52
,Harmonic 39 (-0.738) 3.71
,Harmonic 40 (-1.127) 6.62
,Harmonic 41 (-1.471) 3.39
,Harmonic 42 (-0.228) 3.82
,Harmonic 43 1.138 2.04
,Harmonic 44 2.451 6.23
,Harmonic 45 (-1.03) 0.94
,Harmonic 46 (-0.443) 2.86
,Harmonic 47 0.2 13.05
,Harmonic 48 0.62 6.21
,Harmonic 49 1.286 8.49
,Harmonic 50 0.564 11.58
,Harmonic 51 3.7e-2 4.51]
note8 :: Note
note8 = Note
(Pitch 207.652 44 "g#3")
9
(Range
(NoteRange
(NoteRangeAmplitude 7890.77 38 4.55)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 207.65 1 4061.0)
(NoteRangeHarmonicFreq 47 9759.64)))
[Harmonic 1 0.971 4061.0
,Harmonic 2 2.424 3564.92
,Harmonic 3 1.95 3576.51
,Harmonic 4 (-0.386) 585.59
,Harmonic 5 0.852 1614.08
,Harmonic 6 0.293 1211.74
,Harmonic 7 (-1.473) 89.07
,Harmonic 8 (-0.617) 950.64
,Harmonic 9 2.754 477.08
,Harmonic 10 1.645 661.83
,Harmonic 11 (-2.931) 1059.74
,Harmonic 12 0.288 366.36
,Harmonic 13 (-0.607) 442.37
,Harmonic 14 (-3.091) 64.59
,Harmonic 15 (-0.631) 210.94
,Harmonic 16 3.131 224.6
,Harmonic 17 (-0.331) 283.09
,Harmonic 18 1.108 145.94
,Harmonic 19 (-2.555) 79.93
,Harmonic 20 1.167 149.38
,Harmonic 21 0.333 32.0
,Harmonic 22 1.733 16.79
,Harmonic 23 (-2.4) 78.94
,Harmonic 24 1.638 130.08
,Harmonic 25 (-1.242) 62.07
,Harmonic 26 3.082 20.1
,Harmonic 27 (-0.325) 46.46
,Harmonic 28 (-1.768) 30.58
,Harmonic 29 1.929 63.35
,Harmonic 30 (-2.716) 21.39
,Harmonic 31 (-0.338) 29.3
,Harmonic 32 2.806 31.27
,Harmonic 33 (-2.082) 9.73
,Harmonic 34 1.656 10.44
,Harmonic 35 1.107 7.83
,Harmonic 36 (-0.478) 17.47
,Harmonic 37 (-1.09) 14.2
,Harmonic 38 2.531 4.55
,Harmonic 39 0.635 9.1
,Harmonic 40 2.205 9.12
,Harmonic 41 (-6.2e-2) 10.22
,Harmonic 42 (-2.966) 12.51
,Harmonic 43 (-1.921) 9.6
,Harmonic 44 1.603 10.27
,Harmonic 45 (-1.42) 10.31
,Harmonic 46 1.683 15.59
,Harmonic 47 (-1.178) 9.7]
note9 :: Note
note9 = Note
(Pitch 220.0 45 "a3")
10
(Range
(NoteRange
(NoteRangeAmplitude 9020.0 41 1.7)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 220.0 1 6065.0)
(NoteRangeHarmonicFreq 45 9900.0)))
[Harmonic 1 (-0.94) 6065.0
,Harmonic 2 (-2.545) 4766.12
,Harmonic 3 (-1.776) 2527.4
,Harmonic 4 2.328 204.58
,Harmonic 5 0.327 866.03
,Harmonic 6 1.627 480.8
,Harmonic 7 (-2.535) 132.44
,Harmonic 8 1.75 505.2
,Harmonic 9 (-1.912) 108.88
,Harmonic 10 (-1.811) 752.15
,Harmonic 11 (-0.269) 167.33
,Harmonic 12 (-1.886) 29.71
,Harmonic 13 2.404 115.59
,Harmonic 14 0.162 104.44
,Harmonic 15 (-0.967) 226.91
,Harmonic 16 1.554 37.08
,Harmonic 17 (-1.296) 147.63
,Harmonic 18 1.497 42.17
,Harmonic 19 (-1.755) 136.97
,Harmonic 20 (-1.888) 49.97
,Harmonic 21 1.939 96.92
,Harmonic 22 (-1.727) 87.44
,Harmonic 23 0.459 28.61
,Harmonic 24 (-2.399) 17.17
,Harmonic 25 (-0.826) 16.9
,Harmonic 26 3.042 13.45
,Harmonic 27 1.205 36.86
,Harmonic 28 2.861 34.61
,Harmonic 29 (-0.651) 19.6
,Harmonic 30 (-0.87) 2.55
,Harmonic 31 (-0.533) 6.03
,Harmonic 32 (-2.393) 8.2
,Harmonic 33 (-0.206) 10.72
,Harmonic 34 (-1.733) 18.32
,Harmonic 35 1.202 13.76
,Harmonic 36 (-2.297) 4.82
,Harmonic 37 (-0.408) 4.0
,Harmonic 38 2.317 13.83
,Harmonic 39 (-0.742) 2.68
,Harmonic 40 2.593 4.57
,Harmonic 41 0.979 1.7
,Harmonic 42 2.868 5.48
,Harmonic 43 (-0.837) 4.01
,Harmonic 44 1.33 2.53
,Harmonic 45 (-2.18) 4.0]
note10 :: Note
note10 = Note
(Pitch 233.082 46 "a#3")
11
(Range
(NoteRange
(NoteRangeAmplitude 10022.52 43 1.28)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 233.08 1 7559.0)
(NoteRangeHarmonicFreq 43 10022.52)))
[Harmonic 1 (-1.669) 7559.0
,Harmonic 2 (-2.273) 2400.94
,Harmonic 3 0.557 1269.34
,Harmonic 4 (-0.766) 907.58
,Harmonic 5 (-1.23) 435.71
,Harmonic 6 0.498 87.49
,Harmonic 7 3.069 479.88
,Harmonic 8 0.769 229.7
,Harmonic 9 (-2.326) 681.14
,Harmonic 10 (-0.172) 395.87
,Harmonic 11 0.996 198.07
,Harmonic 12 2.091 137.76
,Harmonic 13 (-1.736) 78.28
,Harmonic 14 (-7.3e-2) 231.92
,Harmonic 15 (-4.7e-2) 56.44
,Harmonic 16 (-0.574) 124.9
,Harmonic 17 (-2.383) 57.67
,Harmonic 18 0.343 78.88
,Harmonic 19 1.754 5.42
,Harmonic 20 0.831 35.83
,Harmonic 21 (-2.496) 34.37
,Harmonic 22 0.874 10.09
,Harmonic 23 2.911 21.16
,Harmonic 24 (-2.617) 40.97
,Harmonic 25 1.059 17.14
,Harmonic 26 (-2.773) 11.85
,Harmonic 27 (-2.644) 4.96
,Harmonic 28 2.925 12.13
,Harmonic 29 1.388 6.1
,Harmonic 30 0.312 12.55
,Harmonic 31 (-2.976) 2.97
,Harmonic 32 (-1.856) 9.19
,Harmonic 33 1.333 12.63
,Harmonic 34 (-1.99) 7.82
,Harmonic 35 1.548 2.41
,Harmonic 36 (-3.002) 2.06
,Harmonic 37 1.817 2.6
,Harmonic 38 1.133 4.61
,Harmonic 39 (-1.382) 6.36
,Harmonic 40 0.813 5.7
,Harmonic 41 (-2.759) 2.43
,Harmonic 42 1.137 4.2
,Harmonic 43 (-1.737) 1.28]
note11 :: Note
note11 = Note
(Pitch 246.942 47 "b3")
12
(Range
(NoteRange
(NoteRangeAmplitude 8149.08 33 0.27)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 246.94 1 4203.0)
(NoteRangeHarmonicFreq 40 9877.68)))
[Harmonic 1 (-1.486) 4203.0
,Harmonic 2 (-0.181) 455.6
,Harmonic 3 1.379 653.06
,Harmonic 4 1.939 987.32
,Harmonic 5 1.423 933.14
,Harmonic 6 0.875 161.04
,Harmonic 7 1.821 192.86
,Harmonic 8 2.107 143.32
,Harmonic 9 (-0.789) 556.53
,Harmonic 10 2.993 458.8
,Harmonic 11 2.601 265.6
,Harmonic 12 4.4e-2 39.67
,Harmonic 13 2.072 105.11
,Harmonic 14 8.0e-2 161.01
,Harmonic 15 (-2.738) 110.02
,Harmonic 16 2.331 48.58
,Harmonic 17 (-0.738) 60.29
,Harmonic 18 (-0.902) 5.01
,Harmonic 19 1.458 43.76
,Harmonic 20 (-0.206) 54.03
,Harmonic 21 0.287 32.45
,Harmonic 22 1.784 2.45
,Harmonic 23 (-2.027) 10.7
,Harmonic 24 0.669 10.34
,Harmonic 25 (-0.704) 3.33
,Harmonic 26 0.546 15.43
,Harmonic 27 (-2.132) 5.89
,Harmonic 28 (-6.5e-2) 11.41
,Harmonic 29 (-0.904) 9.56
,Harmonic 30 0.847 9.73
,Harmonic 31 (-2.268) 9.93
,Harmonic 32 (-0.714) 1.6
,Harmonic 33 (-0.737) 0.27
,Harmonic 34 0.664 1.19
,Harmonic 35 1.054 6.24
,Harmonic 36 2.496 3.36
,Harmonic 37 (-1.742) 4.31
,Harmonic 38 2.092 1.44
,Harmonic 39 2.891 3.31
,Harmonic 40 3.125 11.97]
note12 :: Note
note12 = Note
(Pitch 261.626 48 "c4")
13
(Range
(NoteRange
(NoteRangeAmplitude 7848.77 30 2.98)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 523.25 2 2298.0)
(NoteRangeHarmonicFreq 38 9941.78)))
[Harmonic 1 (-3.012) 1101.49
,Harmonic 2 (-0.481) 2298.0
,Harmonic 3 (-2.032) 655.74
,Harmonic 4 (-1.169) 870.47
,Harmonic 5 2.43 893.47
,Harmonic 6 1.463 45.34
,Harmonic 7 2.992 197.36
,Harmonic 8 3.01 292.26
,Harmonic 9 2.483 184.13
,Harmonic 10 (-0.285) 537.31
,Harmonic 11 (-1.137) 336.83
,Harmonic 12 2.614 164.78
,Harmonic 13 (-2.742) 39.29
,Harmonic 14 (-2.961) 149.87
,Harmonic 15 (-1.765) 56.14
,Harmonic 16 (-2.679) 110.01
,Harmonic 17 (-1.332) 19.18
,Harmonic 18 3.133 45.74
,Harmonic 19 (-1.684) 39.62
,Harmonic 20 (-1.255) 36.49
,Harmonic 21 3.114 62.89
,Harmonic 22 1.95 52.29
,Harmonic 23 2.173 40.25
,Harmonic 24 1.343 31.8
,Harmonic 25 1.765 10.6
,Harmonic 26 (-0.383) 8.77
,Harmonic 27 0.165 10.76
,Harmonic 28 (-0.927) 17.11
,Harmonic 29 (-1.897) 23.57
,Harmonic 30 (-2.365) 2.98
,Harmonic 31 0.213 11.07
,Harmonic 32 (-0.967) 6.41
,Harmonic 33 (-2.607) 8.19
,Harmonic 34 2.303 4.09
,Harmonic 35 0.232 10.77
,Harmonic 36 0.318 8.09
,Harmonic 37 3.8e-2 9.72
,Harmonic 38 0.315 6.15]
note13 :: Note
note13 = Note
(Pitch 277.183 49 "c#4")
14
(Range
(NoteRange
(NoteRangeAmplitude 9147.03 33 1.09)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 277.18 1 4270.0)
(NoteRangeHarmonicFreq 35 9701.4)))
[Harmonic 1 (-1.222) 4270.0
,Harmonic 2 (-3.043) 1380.01
,Harmonic 3 (-2.74) 459.88
,Harmonic 4 (-0.148) 185.24
,Harmonic 5 0.536 53.57
,Harmonic 6 (-0.779) 284.63
,Harmonic 7 (-0.655) 148.74
,Harmonic 8 2.756 738.2
,Harmonic 9 (-0.613) 324.03
,Harmonic 10 0.272 139.4
,Harmonic 11 2.919 122.7
,Harmonic 12 2.853 57.38
,Harmonic 13 (-0.352) 114.15
,Harmonic 14 (-1.707) 44.81
,Harmonic 15 2.387 47.54
,Harmonic 16 7.3e-2 51.06
,Harmonic 17 (-1.485) 25.91
,Harmonic 18 2.311 16.53
,Harmonic 19 (-1.092) 10.3
,Harmonic 20 3.066 5.69
,Harmonic 21 (-1.049) 8.33
,Harmonic 22 0.166 8.81
,Harmonic 23 (-1.028) 12.18
,Harmonic 24 (-0.332) 10.6
,Harmonic 25 (-0.88) 2.0
,Harmonic 26 2.786 7.17
,Harmonic 27 0.968 13.42
,Harmonic 28 (-1.951) 8.14
,Harmonic 29 0.843 1.83
,Harmonic 30 (-0.226) 2.9
,Harmonic 31 (-3.071) 2.92
,Harmonic 32 (-1.313) 4.08
,Harmonic 33 1.542 1.09
,Harmonic 34 (-1.651) 2.56
,Harmonic 35 (-1.605) 3.57]
note14 :: Note
note14 = Note
(Pitch 293.665 50 "d4")
15
(Range
(NoteRange
(NoteRangeAmplitude 6754.29 23 7.28)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 293.66 1 5803.0)
(NoteRangeHarmonicFreq 34 9984.61)))
[Harmonic 1 (-5.2e-2) 5803.0
,Harmonic 2 (-0.303) 1984.57
,Harmonic 3 0.302 941.87
,Harmonic 4 6.9e-2 528.13
,Harmonic 5 (-3.033) 4533.88
,Harmonic 6 (-2.208) 4330.5
,Harmonic 7 2.346 1580.03
,Harmonic 8 1.744 1299.68
,Harmonic 9 (-1.426) 681.86
,Harmonic 10 (-3.132) 1466.14
,Harmonic 11 1.58 1280.36
,Harmonic 12 (-1.099) 275.32
,Harmonic 13 7.3e-2 532.05
,Harmonic 14 1.253 532.09
,Harmonic 15 2.974 49.92
,Harmonic 16 2.737 76.96
,Harmonic 17 2.334 73.48
,Harmonic 18 1.487 129.06
,Harmonic 19 (-2.426) 54.23
,Harmonic 20 (-1.952) 135.75
,Harmonic 21 1.948 40.7
,Harmonic 22 (-1.853) 54.89
,Harmonic 23 (-2.821) 7.28
,Harmonic 24 (-2.45) 47.16
,Harmonic 25 (-1.848) 24.79
,Harmonic 26 1.121 57.06
,Harmonic 27 (-2.424) 17.26
,Harmonic 28 (-1.495) 20.19
,Harmonic 29 2.696 25.98
,Harmonic 30 (-2.842) 26.61
,Harmonic 31 1.663 20.36
,Harmonic 32 1.254 15.6
,Harmonic 33 1.831 30.69
,Harmonic 34 (-2.713) 8.98]
note15 :: Note
note15 = Note
(Pitch 311.127 51 "d#4")
16
(Range
(NoteRange
(NoteRangeAmplitude 9022.68 29 4.59)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 311.12 1 4086.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 (-1.833) 4086.0
,Harmonic 2 0.126 2770.0
,Harmonic 3 (-2.333) 733.04
,Harmonic 4 2.483 1456.91
,Harmonic 5 (-2.314) 51.9
,Harmonic 6 (-2.625) 244.49
,Harmonic 7 (-1.341) 965.59
,Harmonic 8 0.809 595.12
,Harmonic 9 (-2.488) 152.71
,Harmonic 10 (-1.946) 396.97
,Harmonic 11 (-2.692) 364.14
,Harmonic 12 (-2.918) 33.57
,Harmonic 13 1.838 351.72
,Harmonic 14 0.886 80.65
,Harmonic 15 (-1.731) 79.87
,Harmonic 16 1.823 75.2
,Harmonic 17 (-1.806) 47.36
,Harmonic 18 (-2.069) 75.53
,Harmonic 19 (-2.466) 68.94
,Harmonic 20 2.006 20.02
,Harmonic 21 (-0.922) 28.08
,Harmonic 22 0.21 10.85
,Harmonic 23 (-1.672) 18.83
,Harmonic 24 (-1.295) 75.36
,Harmonic 25 1.183 13.06
,Harmonic 26 (-0.379) 17.5
,Harmonic 27 2.779 26.14
,Harmonic 28 1.763 23.34
,Harmonic 29 1.798 4.59
,Harmonic 30 (-0.488) 9.26
,Harmonic 31 0.155 21.03
,Harmonic 32 (-2.02) 15.3]
note16 :: Note
note16 = Note
(Pitch 329.628 52 "e4")
17
(Range
(NoteRange
(NoteRangeAmplitude 9888.84 30 1.77)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 329.62 1 4927.0)
(NoteRangeHarmonicFreq 30 9888.84)))
[Harmonic 1 (-2.031) 4927.0
,Harmonic 2 (-1.41) 3582.75
,Harmonic 3 1.839 272.98
,Harmonic 4 (-0.742) 982.88
,Harmonic 5 (-0.452) 377.11
,Harmonic 6 (-0.176) 498.8
,Harmonic 7 0.818 430.64
,Harmonic 8 2.634 684.32
,Harmonic 9 (-2.305) 301.45
,Harmonic 10 (-2.778) 209.03
,Harmonic 11 (-1.588) 270.33
,Harmonic 12 2.024 314.95
,Harmonic 13 (-0.981) 95.31
,Harmonic 14 2.898 42.15
,Harmonic 15 1.015 145.59
,Harmonic 16 (-2.302) 125.76
,Harmonic 17 (-0.273) 158.99
,Harmonic 18 2.691 90.04
,Harmonic 19 2.031 25.11
,Harmonic 20 2.233 20.94
,Harmonic 21 2.447 44.9
,Harmonic 22 (-0.675) 65.45
,Harmonic 23 (-2.914) 7.07
,Harmonic 24 (-0.721) 11.31
,Harmonic 25 1.618 4.89
,Harmonic 26 (-0.282) 18.85
,Harmonic 27 (-0.664) 30.85
,Harmonic 28 (-2.005) 25.74
,Harmonic 29 1.117 15.62
,Harmonic 30 (-0.337) 1.77]
note17 :: Note
note17 = Note
(Pitch 349.228 53 "f4")
18
(Range
(NoteRange
(NoteRangeAmplitude 6635.33 19 3.72)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 2959.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 0.112 2959.0
,Harmonic 2 2.873 2577.73
,Harmonic 3 (-1.611) 1149.15
,Harmonic 4 0.719 454.08
,Harmonic 5 2.803 222.66
,Harmonic 6 1.98 760.94
,Harmonic 7 1.647 189.22
,Harmonic 8 1.206 142.24
,Harmonic 9 (-2.9e-2) 452.48
,Harmonic 10 (-2.202) 547.13
,Harmonic 11 0.59 210.36
,Harmonic 12 1.451 191.22
,Harmonic 13 2.09 99.4
,Harmonic 14 2.487 106.68
,Harmonic 15 1.519 141.14
,Harmonic 16 2.979 91.4
,Harmonic 17 (-0.458) 124.86
,Harmonic 18 (-1.2e-2) 30.14
,Harmonic 19 (-0.48) 3.72
,Harmonic 20 (-0.987) 54.43
,Harmonic 21 (-0.557) 135.45
,Harmonic 22 0.712 12.79
,Harmonic 23 (-2.668) 19.52
,Harmonic 24 2.978 23.21
,Harmonic 25 (-0.369) 11.4
,Harmonic 26 1.087 29.86
,Harmonic 27 1.632 25.37
,Harmonic 28 (-1.874) 21.81]
note18 :: Note
note18 = Note
(Pitch 369.994 54 "f#4")
19
(Range
(NoteRange
(NoteRangeAmplitude 8509.86 23 10.53)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 369.99 1 3993.0)
(NoteRangeHarmonicFreq 26 9619.84)))
[Harmonic 1 1.152 3993.0
,Harmonic 2 (-2.388) 2444.7
,Harmonic 3 1.192 506.03
,Harmonic 4 3.135 834.7
,Harmonic 5 1.455 625.92
,Harmonic 6 0.481 1844.27
,Harmonic 7 2.2 77.11
,Harmonic 8 (-1.635) 163.32
,Harmonic 9 (-2.879) 395.11
,Harmonic 10 0.673 453.02
,Harmonic 11 (-2.784) 288.33
,Harmonic 12 0.233 191.76
,Harmonic 13 3.5e-2 50.0
,Harmonic 14 (-2.888) 104.92
,Harmonic 15 (-0.249) 95.21
,Harmonic 16 (-1.673) 176.97
,Harmonic 17 1.268 31.44
,Harmonic 18 0.461 13.35
,Harmonic 19 2.377 33.68
,Harmonic 20 (-0.107) 122.4
,Harmonic 21 2.689 31.41
,Harmonic 22 (-1.243) 17.11
,Harmonic 23 2.642 10.53
,Harmonic 24 0.669 12.09
,Harmonic 25 (-1.313) 20.4
,Harmonic 26 6.2e-2 30.22]
note19 :: Note
note19 = Note
(Pitch 391.995 55 "g4")
20
(Range
(NoteRange
(NoteRangeAmplitude 6271.92 16 19.82)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 2743.96 7 1985.0)
(NoteRangeHarmonicFreq 25 9799.87)))
[Harmonic 1 0.808 703.0
,Harmonic 2 1.56 1939.86
,Harmonic 3 2.121 241.34
,Harmonic 4 (-2.709) 510.38
,Harmonic 5 1.891 935.65
,Harmonic 6 0.371 937.94
,Harmonic 7 0.813 1985.0
,Harmonic 8 0.662 153.29
,Harmonic 9 0.126 875.05
,Harmonic 10 1.616 119.63
,Harmonic 11 1.723 441.63
,Harmonic 12 0.916 306.36
,Harmonic 13 0.406 350.86
,Harmonic 14 1.403 64.31
,Harmonic 15 1.53 84.57
,Harmonic 16 (-2.142) 19.82
,Harmonic 17 2.589 119.68
,Harmonic 18 3.032 101.69
,Harmonic 19 2.432 74.34
,Harmonic 20 (-2.37) 50.88
,Harmonic 21 2.585 51.46
,Harmonic 22 3.05 42.28
,Harmonic 23 (-0.717) 74.54
,Harmonic 24 (-0.34) 32.81
,Harmonic 25 0.176 37.12]
note20 :: Note
note20 = Note
(Pitch 415.305 56 "g#4")
21
(Range
(NoteRange
(NoteRangeAmplitude 7890.79 19 8.78)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 415.3 1 3112.0)
(NoteRangeHarmonicFreq 23 9552.01)))
[Harmonic 1 (-1.668) 3112.0
,Harmonic 2 (-9.7e-2) 531.4
,Harmonic 3 1.86 755.7
,Harmonic 4 (-1.601) 813.19
,Harmonic 5 (-2.874) 791.73
,Harmonic 6 (-3.137) 195.94
,Harmonic 7 (-1.726) 211.23
,Harmonic 8 0.799 90.03
,Harmonic 9 0.295 786.81
,Harmonic 10 (-2.74) 486.51
,Harmonic 11 (-0.699) 63.87
,Harmonic 12 2.743 40.62
,Harmonic 13 (-0.594) 52.37
,Harmonic 14 (-1.64) 28.86
,Harmonic 15 (-1.534) 48.72
,Harmonic 16 2.873 21.65
,Harmonic 17 (-0.69) 54.08
,Harmonic 18 (-1.063) 29.23
,Harmonic 19 (-2.8e-2) 8.78
,Harmonic 20 0.388 39.09
,Harmonic 21 (-2.799) 31.76
,Harmonic 22 (-2.851) 33.08
,Harmonic 23 2.031 14.83]
note21 :: Note
note21 = Note
(Pitch 440.0 57 "a4")
22
(Range
(NoteRange
(NoteRangeAmplitude 9240.0 21 2.06)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 10430.0)
(NoteRangeHarmonicFreq 22 9680.0)))
[Harmonic 1 1.499 10430.0
,Harmonic 2 (-2.925) 321.79
,Harmonic 3 2.408 652.07
,Harmonic 4 (-1.247) 1392.4
,Harmonic 5 (-1.367) 641.15
,Harmonic 6 1.452 531.64
,Harmonic 7 1.773 1071.23
,Harmonic 8 1.335 327.41
,Harmonic 9 (-1.816) 395.4
,Harmonic 10 (-0.295) 177.11
,Harmonic 11 (-2.539) 202.94
,Harmonic 12 3.048 74.32
,Harmonic 13 0.264 71.52
,Harmonic 14 (-2.187) 76.74
,Harmonic 15 0.359 70.66
,Harmonic 16 0.773 79.19
,Harmonic 17 1.026 134.11
,Harmonic 18 (-0.675) 121.22
,Harmonic 19 (-2.476) 66.76
,Harmonic 20 (-1.544) 25.81
,Harmonic 21 (-1.444) 2.06
,Harmonic 22 (-1.0) 16.55]
note22 :: Note
note22 = Note
(Pitch 466.164 58 "a#4")
23
(Range
(NoteRange
(NoteRangeAmplitude 6060.13 13 18.17)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 2811.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 (-1.872) 2811.0
,Harmonic 2 (-0.727) 119.93
,Harmonic 3 (-1.446) 304.42
,Harmonic 4 (-1.101) 847.28
,Harmonic 5 (-1.983) 400.03
,Harmonic 6 (-2.683) 478.85
,Harmonic 7 2.424 306.31
,Harmonic 8 2.796 338.35
,Harmonic 9 (-0.691) 632.62
,Harmonic 10 (-0.562) 67.17
,Harmonic 11 (-0.142) 71.57
,Harmonic 12 (-1.375) 238.38
,Harmonic 13 (-0.408) 18.17
,Harmonic 14 2.517 256.13
,Harmonic 15 2.974 79.75
,Harmonic 16 0.624 220.24
,Harmonic 17 0.761 162.65
,Harmonic 18 (-1.203) 100.74
,Harmonic 19 (-0.121) 38.33
,Harmonic 20 1.961 38.32
,Harmonic 21 (-1.11) 23.1]
note23 :: Note
note23 = Note
(Pitch 493.883 59 "b4")
24
(Range
(NoteRange
(NoteRangeAmplitude 9877.66 20 71.75)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 2963.29 6 2721.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 (-2.137) 1702.51
,Harmonic 2 (-1.429) 1606.32
,Harmonic 3 (-1.844) 536.45
,Harmonic 4 (-3.051) 1264.19
,Harmonic 5 (-2.6) 1495.03
,Harmonic 6 (-0.674) 2721.0
,Harmonic 7 2.567 871.25
,Harmonic 8 (-2.267) 1118.75
,Harmonic 9 (-0.985) 1028.76
,Harmonic 10 1.998 204.06
,Harmonic 11 3.058 287.75
,Harmonic 12 (-0.562) 323.42
,Harmonic 13 (-2.506) 273.28
,Harmonic 14 2.821 134.89
,Harmonic 15 (-0.86) 98.45
,Harmonic 16 0.197 273.96
,Harmonic 17 (-2.464) 117.85
,Harmonic 18 (-1.577) 170.86
,Harmonic 19 1.781 123.08
,Harmonic 20 0.232 71.75]
note24 :: Note
note24 = Note
(Pitch 523.251 60 "c5")
25
(Range
(NoteRange
(NoteRangeAmplitude 9941.76 19 37.9)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 523.25 1 1767.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 (-2.345) 1767.0
,Harmonic 2 (-0.729) 649.18
,Harmonic 3 (-2.101) 315.32
,Harmonic 4 1.134 790.78
,Harmonic 5 0.603 1355.99
,Harmonic 6 (-1.142) 427.02
,Harmonic 7 (-0.245) 148.65
,Harmonic 8 0.964 886.76
,Harmonic 9 (-1.008) 190.04
,Harmonic 10 2.231 336.34
,Harmonic 11 1.983 306.49
,Harmonic 12 (-2.157) 378.49
,Harmonic 13 0.888 135.32
,Harmonic 14 1.727 77.59
,Harmonic 15 2.249 147.37
,Harmonic 16 (-2.15) 52.64
,Harmonic 17 2.299 71.61
,Harmonic 18 (-2.239) 43.45
,Harmonic 19 0.13 37.9]
note25 :: Note
note25 = Note
(Pitch 554.365 61 "c#5")
26
(Range
(NoteRange
(NoteRangeAmplitude 8869.84 16 28.36)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 2217.46 4 2334.0)
(NoteRangeHarmonicFreq 17 9424.2)))
[Harmonic 1 (-0.766) 2288.26
,Harmonic 2 2.111 1659.16
,Harmonic 3 (-2.604) 1813.81
,Harmonic 4 (-1.752) 2334.0
,Harmonic 5 (-2.938) 370.28
,Harmonic 6 (-2.611) 486.38
,Harmonic 7 1.965 1017.73
,Harmonic 8 (-0.889) 1023.98
,Harmonic 9 0.924 332.35
,Harmonic 10 (-1.933) 292.44
,Harmonic 11 (-0.313) 230.23
,Harmonic 12 (-0.753) 210.97
,Harmonic 13 (-1.299) 274.3
,Harmonic 14 1.467 418.87
,Harmonic 15 (-3.105) 113.67
,Harmonic 16 2.517 28.36
,Harmonic 17 3.086 195.62]
note26 :: Note
note26 = Note
(Pitch 587.33 62 "d5")
27
(Range
(NoteRange
(NoteRangeAmplitude 8809.95 15 5.75)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 2936.65 5 2755.3)
(NoteRangeHarmonicFreq 16 9397.28)))
[Harmonic 1 (-2.302) 1644.81
,Harmonic 2 (-2.494) 1812.85
,Harmonic 3 (-0.45) 1219.49
,Harmonic 4 (-0.343) 1232.77
,Harmonic 5 2.056 2755.3
,Harmonic 6 2.8 577.34
,Harmonic 7 (-2.499) 335.78
,Harmonic 8 (-2.833) 266.77
,Harmonic 9 1.694 219.56
,Harmonic 10 (-0.981) 101.69
,Harmonic 11 (-1.337) 33.06
,Harmonic 12 (-2.202) 20.12
,Harmonic 13 (-1.038) 9.63
,Harmonic 14 1.893 7.97
,Harmonic 15 1.546 5.75
,Harmonic 16 2.072 9.34]
note27 :: Note
note27 = Note
(Pitch 622.254 63 "d#5")
28
(Range
(NoteRange
(NoteRangeAmplitude 7467.04 12 27.47)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 622.25 1 5495.0)
(NoteRangeHarmonicFreq 15 9333.81)))
[Harmonic 1 (-0.971) 5495.0
,Harmonic 2 (-2.506) 4071.11
,Harmonic 3 2.408 2175.04
,Harmonic 4 1.191 1322.79
,Harmonic 5 (-0.377) 2912.35
,Harmonic 6 (-2.559) 1388.04
,Harmonic 7 (-2.382) 742.69
,Harmonic 8 1.734 773.56
,Harmonic 9 (-2.456) 834.04
,Harmonic 10 (-1.592) 528.53
,Harmonic 11 1.325 221.53
,Harmonic 12 (-2.365) 27.47
,Harmonic 13 (-3.12) 117.46
,Harmonic 14 1.094 55.92
,Harmonic 15 1.679 261.84]
note28 :: Note
note28 = Note
(Pitch 659.255 64 "e5")
29
(Range
(NoteRange
(NoteRangeAmplitude 9229.57 14 42.51)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 659.25 1 3396.0)
(NoteRangeHarmonicFreq 14 9229.57)))
[Harmonic 1 1.109 3396.0
,Harmonic 2 (-2.867) 439.21
,Harmonic 3 2.715 561.54
,Harmonic 4 (-3.067) 760.71
,Harmonic 5 (-0.418) 417.14
,Harmonic 6 0.819 1042.11
,Harmonic 7 2.285 254.31
,Harmonic 8 0.183 223.52
,Harmonic 9 (-1.439) 225.09
,Harmonic 10 (-1.224) 51.68
,Harmonic 11 (-1.845) 194.92
,Harmonic 12 0.271 134.39
,Harmonic 13 (-2.621) 53.92
,Harmonic 14 (-1.206) 42.51]
note29 :: Note
note29 = Note
(Pitch 698.456 65 "f5")
30
(Range
(NoteRange
(NoteRangeAmplitude 9778.38 14 29.36)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 698.45 1 2140.0)
(NoteRangeHarmonicFreq 14 9778.38)))
[Harmonic 1 0.703 2140.0
,Harmonic 2 (-1.319) 685.67
,Harmonic 3 2.784 903.66
,Harmonic 4 1.738 621.41
,Harmonic 5 1.013 499.82
,Harmonic 6 0.258 619.89
,Harmonic 7 0.628 226.31
,Harmonic 8 1.267 116.2
,Harmonic 9 2.76 281.82
,Harmonic 10 2.83 115.42
,Harmonic 11 0.381 152.6
,Harmonic 12 0.826 49.7
,Harmonic 13 2.463 36.3
,Harmonic 14 7.8e-2 29.36]
note30 :: Note
note30 = Note
(Pitch 739.989 66 "f#5")
31
(Range
(NoteRange
(NoteRangeAmplitude 8879.86 12 53.26)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 739.98 1 2168.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 (-1.362) 2168.0
,Harmonic 2 (-2.911) 629.99
,Harmonic 3 (-2.3e-2) 921.03
,Harmonic 4 (-2.147) 2039.57
,Harmonic 5 (-1.614) 554.35
,Harmonic 6 2.43 306.4
,Harmonic 7 (-1.019) 269.73
,Harmonic 8 (-2.873) 88.66
,Harmonic 9 (-2.218) 96.75
,Harmonic 10 2.612 126.03
,Harmonic 11 1.115 71.01
,Harmonic 12 (-0.798) 53.26
,Harmonic 13 2.779 121.5]
note31 :: Note
note31 = Note
(Pitch 783.991 67 "g5")
32
(Range
(NoteRange
(NoteRangeAmplitude 6271.92 8 86.8)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 2351.97 3 2272.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 1.787 2194.1
,Harmonic 2 0.646 469.69
,Harmonic 3 (-7.1e-2) 2272.0
,Harmonic 4 2.803 1176.48
,Harmonic 5 1.209 1819.44
,Harmonic 6 2.278 887.87
,Harmonic 7 (-1.628) 574.63
,Harmonic 8 2.261 86.8
,Harmonic 9 2.255 194.82
,Harmonic 10 0.841 290.28
,Harmonic 11 (-0.687) 90.75
,Harmonic 12 1.661 128.19]
note32 :: Note
note32 = Note
(Pitch 830.609 68 "g#5")
33
(Range
(NoteRange
(NoteRangeAmplitude 9136.69 11 16.09)
(NoteRangeHarmonicFreq 1 830.6))
(NoteRange
(NoteRangeAmplitude 830.6 1 2610.0)
(NoteRangeHarmonicFreq 11 9136.69)))
[Harmonic 1 (-1.593) 2610.0
,Harmonic 2 1.094 763.59
,Harmonic 3 1.071 559.41
,Harmonic 4 (-0.514) 473.82
,Harmonic 5 (-0.758) 215.48
,Harmonic 6 0.643 91.23
,Harmonic 7 0.127 90.29
,Harmonic 8 0.513 96.08
,Harmonic 9 (-0.921) 58.48
,Harmonic 10 0.174 41.23
,Harmonic 11 (-0.565) 16.09]
note33 :: Note
note33 = Note
(Pitch 880.0 69 "a5")
34
(Range
(NoteRange
(NoteRangeAmplitude 9680.0 11 41.34)
(NoteRangeHarmonicFreq 1 880.0))
(NoteRange
(NoteRangeAmplitude 2640.0 3 1710.0)
(NoteRangeHarmonicFreq 11 9680.0)))
[Harmonic 1 1.234 532.37
,Harmonic 2 1.411 1040.57
,Harmonic 3 1.367 1710.0
,Harmonic 4 (-0.393) 375.13
,Harmonic 5 (-0.604) 122.29
,Harmonic 6 2.406 196.12
,Harmonic 7 1.378 524.71
,Harmonic 8 (-0.493) 87.25
,Harmonic 9 (-1.5e-2) 184.72
,Harmonic 10 (-1.644) 65.29
,Harmonic 11 (-0.329) 41.34]
note34 :: Note
note34 = Note
(Pitch 932.328 70 "a#5")
35
(Range
(NoteRange
(NoteRangeAmplitude 8390.95 9 42.52)
(NoteRangeHarmonicFreq 1 932.32))
(NoteRange
(NoteRangeAmplitude 1864.65 2 1464.0)
(NoteRangeHarmonicFreq 10 9323.27)))
[Harmonic 1 (-1.793) 439.4
,Harmonic 2 (-2.089) 1464.0
,Harmonic 3 (-0.7) 1051.33
,Harmonic 4 1.763 732.26
,Harmonic 5 (-1.375) 213.19
,Harmonic 6 2.071 426.24
,Harmonic 7 0.276 107.0
,Harmonic 8 (-1.799) 120.14
,Harmonic 9 (-1.769) 42.52
,Harmonic 10 0.613 148.41]
note35 :: Note
note35 = Note
(Pitch 987.767 71 "b5")
36
(Range
(NoteRange
(NoteRangeAmplitude 6914.36 7 41.55)
(NoteRangeHarmonicFreq 1 987.76))
(NoteRange
(NoteRangeAmplitude 3951.06 4 2614.0)
(NoteRangeHarmonicFreq 10 9877.67)))
[Harmonic 1 (-0.27) 702.13
,Harmonic 2 8.8e-2 1210.33
,Harmonic 3 (-2.131) 2248.32
,Harmonic 4 (-1.944) 2614.0
,Harmonic 5 (-2.375) 225.83
,Harmonic 6 (-2.059) 545.8
,Harmonic 7 0.705 41.55
,Harmonic 8 2.709 274.85
,Harmonic 9 (-0.643) 548.52
,Harmonic 10 (-1.276) 119.75]
note36 :: Note
note36 = Note
(Pitch 1046.5 72 "c6")
37
(Range
(NoteRange
(NoteRangeAmplitude 7325.5 7 52.69)
(NoteRangeHarmonicFreq 1 1046.5))
(NoteRange
(NoteRangeAmplitude 1046.5 1 2526.0)
(NoteRangeHarmonicFreq 9 9418.5)))
[Harmonic 1 2.384 2526.0
,Harmonic 2 (-1.87) 2277.06
,Harmonic 3 (-0.754) 2021.46
,Harmonic 4 0.42 797.6
,Harmonic 5 (-7.3e-2) 536.99
,Harmonic 6 (-1.001) 179.14
,Harmonic 7 (-0.606) 52.69
,Harmonic 8 (-0.601) 73.53
,Harmonic 9 0.931 259.02]
note37 :: Note
note37 = Note
(Pitch 1108.73 73 "c#6")
38
(Range
(NoteRange
(NoteRangeAmplitude 7761.11 7 30.83)
(NoteRangeHarmonicFreq 1 1108.73))
(NoteRange
(NoteRangeAmplitude 2217.46 2 2085.0)
(NoteRangeHarmonicFreq 9 9978.57)))
[Harmonic 1 (-5.1e-2) 1353.85
,Harmonic 2 1.964 2085.0
,Harmonic 3 2.396 861.52
,Harmonic 4 3.034 188.22
,Harmonic 5 (-3.001) 1186.08
,Harmonic 6 2.603 478.89
,Harmonic 7 (-0.407) 30.83
,Harmonic 8 (-0.785) 72.89
,Harmonic 9 0.222 46.65]
note38 :: Note
note38 = Note
(Pitch 1174.66 74 "d6")
39
(Range
(NoteRange
(NoteRangeAmplitude 8222.62 7 33.55)
(NoteRangeHarmonicFreq 1 1174.66))
(NoteRange
(NoteRangeAmplitude 2349.32 2 1289.0)
(NoteRangeHarmonicFreq 8 9397.28)))
[Harmonic 1 (-2.003) 581.56
,Harmonic 2 (-1.395) 1289.0
,Harmonic 3 (-3.054) 331.86
,Harmonic 4 1.845 289.5
,Harmonic 5 2.146 390.96
,Harmonic 6 (-1.351) 215.38
,Harmonic 7 (-0.771) 33.55
,Harmonic 8 2.397 61.86]
|
anton-k/sharc-timbre
|
src/Sharc/Instruments/ViolaMuted.hs
|
bsd-3-clause
| 49,347
| 0
| 15
| 14,047
| 18,771
| 9,728
| 9,043
| 1,683
| 1
|
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
-- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
module Decls where
import Common
import Core
import Env
import Reduce
import PP
-- Declaration processing ---------------------------------------------------------------------
{-
? Check acyclic tsym deps
? Generate future subtype instances
? Generate future class instances
-}
-- Extend kind environment
-- Initialize empty class witness graph
-- Extract selector and constructor type schemes
-- Construct class member type schemes and bindings
-- Replace subtyping in type declarations with explicit selectors/constructors
-- Initialize subtyping graph with reflexivity witnesses
-- Close subtyping graph under transitivity (report cyclic and ambiguity errors)
-- Return extended environment, transformed decls and added witness bindings
typeDecls env ps (Types ke ds) = do (ds,pe1,eq1) <- desub env0 ds
(env',bs) <- instancePreds env0 (pe1 ++ ps)
let tds = Types ke ds
return (addTEnv0 (tenvSelsCons tds) env', tds, catBinds (Binds False pe1 eq1) bs)
where env0 = addClasses cs (addKEnv0 ke env)
cs = [ c | (c, DRec True _ _ _) <- ds ]
impDecls env (Types ke ds) = env1
where
env1 = addClasses cs (addKEnv0 ke env)
cs = [ c | (c, DRec True _ _ _) <- ds ]
-- Close the top-level instance delcarations
-- Return the extended environment and the added witness bindings
instancePreds env pe = do (env',qe,eq) <- closePreds0 env pe
let bss = preferParams env' pe qe eq
return (env', concatBinds bss)
impPreds env pe = addPreds (addPEnv0 pe env) pe
-- Computes the stand-alone type schemes associated with selectors and constructors
-- Note: these constants have no corresponding definition (i.e., no rhs)
tenvSelsCons (Types ke ds) = concatMap (tenvSelCon ke) ds
tenvSelCon ke0 (c,DRec _ vs _ ss) = map (f t ke) ss
where (t,ke) = mkHead ke0 c vs
f t ke (l, Scheme rh ps ke') = (l, Scheme rh (scheme t : ps) (ke++ke'))
tenvSelCon ke0 (c,DData vs _ cs) = map (f t ke) cs
where (t,ke) = mkHead ke0 c vs
f t ke (k, Constr ts ps ke') = (k, Scheme (tFun' ts t) ps (ke++ke'))
tenvSelCon ke0 _ = []
tenvCon ke0 (c,DData vs _ cs) = map (f t ke) cs
where (t,ke) = mkHead ke0 c vs
f t ke (k, Constr ts ps ke') = (k, Scheme (tFun' ts t) ps (ke++ke'))
tenvCon ke0 _ = []
mkHead ke0 i vs = (tAp' i vs, vs `zip` kArgs (findKind0 ke0 i))
-- Decomposition of type declarations ---------------------------------------------------------
desub env ds = do (ds',pes,eqs) <- fmap unzip3 (mapM desub' ds)
return (ds', concat pes, concat eqs)
where
desub' (i, DData vs bs cs) = do (pe,eq,cs') <- fmap unzip3 (mapM (con (fromMod i) i (mkHead ke0 i vs)) bs)
return ((i, DData vs [] (cs'++cs)), pe, eq)
desub' (i, DRec isC vs bs ss) = do (pe,eq,ss') <- fmap unzip3 (mapM (sel (fromMod i) i (mkHead ke0 i vs)) bs)
return ((i, DRec isC vs [] (ss'++ss)), pe, eq)
desub' (i, DType vs t) = return ((i, DType vs t), [], [])
ke0 = kindEnv0 env
con m i (t0,ke0) (Scheme (R t) [] ke) =
do w <- newNameModPub m (public (annot i)) coercionSym
k <- newNameModPub m (public (annot i)) (coerceConstr t t0)
x <- newName paramSym
let p = (w, Scheme (R (t `sub` t0)) [] (ke0++ke))
eq = (w, ELam [(x,scheme t)] (EAp (ECon k) [EVar x]))
c = (k, Constr [scheme t] [] ke)
return (p, eq, c)
sel m i (t0,ke0) (Scheme (R t) [] ke) =
do w <- newNameModPub m (public (annot i)) coercionSym
l <- newNameModPub m (public (annot i)) (coerceLabel t0 t)
x <- newName paramSym
let p = (w, Scheme (R (t0 `sub` t)) [] (ke0++ke))
eq = (w, ELam [(x,scheme t0)] (ESel (EVar x) l))
s = (l, Scheme (R t) [] ke)
return (p, eq, s)
coerceConstr t t0 = coerceConstrSym ++ "_" ++ render (prId3 (tId(tHead t))) ++ "_" ++ render (prId3 (tId (tHead t0)))
coerceLabel t0 t = coerceLabelSym ++ "_" ++ render (prId3 (tId(tHead t0))) ++ "_" ++ render (prId3 (tId (tHead t)))
{-
*data Exists m = All a . Pack (All b . D m b a) (All b . C m b a -> m b a)
Pack :: All m,a . (All b . D m b a) -> (All b . C m b a -> m b a) -> Exists m
f1 :: All a,b . (All b . D m b a) -> D m' b a
f1 :: All a . (All b . D m b a) -> (All b . D m' b a)
f2 :: All a,b . (All b . D m b a) -> (All b . C m b a -> m b a) -> C m' b a -> m' b a
f2 :: All a . (All b . D m b a) -> (All b . C m b a -> m b a) -> (All b . C m' b a -> m' b a)
case x of
Pack -> \d::(All b . D m b a) -> \r::(All b . C m b a -> m b a) -> Pack (f1 d) (f2 d r)
*data Exists m = All a . (All b . D m b a) => Pack (All b . C m b a -> m b a)
Pack :: All m,a . (All b . D m b a) => (All b . C m b a -> m b a) -> Exists m
f1 :: All a,b . (All b . D m b a) -> D m' b a
f1 :: All a . (All b . D m b a) -> (All b . D m' b a)
f2 :: All a,b . (All b . D m b a) -> (All b . C m b a -> m b a) -> C m' b a -> m' b a
f2 :: All a . (All b . D m b a) -> (All b . C m b a -> m b a) -> (All b . C m' b a -> m' b a)
case x of
Pack -> \d::(All b . D m b a) => \r::(All b . C m b a -> m b a) -> Pack (f1 d) (f2 d r)
*data Exists m = Pack (D m b a \\ b) (C m b a -> m b a \\ b) \\ a
Pack :: (D m b a \\ b) -> (C m b a -> m b a \\ b) -> Exists m \\ m, a
f1 :: (D m b a \\ b) -> D m' b a \\ a, b
f1 :: (D m b a \\ b) -> (D m' b a \\ b) \\ a
f2 :: (D m b a \\ b) -> (C m b a -> m b a \\ b) -> C m' b a -> m' b a \\ a, b
f2 :: (D m b a \\ b) -> (C m b a -> m b a \\ b) -> (C m' b a -> m' b a \\ b) \\ a
case x of
Pack -> \d::(D m b a \\ b) -> \r::(C m b a -> m b a \\ b) -> Pack (f1 d) (f2 d r)
*data Exists m = Pack (m b a \\ b, C m b a) \\ a, (D m b a \\ b)
Pack :: (m b a \\ b, C m b a) -> Exists m \\ m, a, (D m b a \\ b)
f1 :: (D m b a \\ b) -> D m' b a \\ a,b
f1 :: (D m b a \\ b) -> (D m' b a \\ b) \\ a
f2 :: (m b a \\ b, C m b a) -> m' b a \\ a, b, C m' b a, (D m b a \\ b)
f2 :: (m b a \\ b, C m b a) -> (m' b a \\ b, C m' b a) \\ a, (D m b a \\ b)
case x of
Pack -> \d::(D m b a \\ b) => \r::(m b a \\ b, C m b a) -> Pack (f1 d) (f2 d r)
*record T a =
x :: b -> a -> b \\ b, b < a
x :: T a -> b -> a -> b \\ b, b < a
f :: (b -> a -> b \\ b, b < a) -> b -> a' -> b \\ b, b < a'
f :: (b -> a -> b \\ b, b < a) -> (b -> a' -> b \\ b, b < a')
{ x = f r.x }
*record T a =
x :: (b<a) -> b -> a -> b \\ b
x :: T a -> (b<a) -> b -> a -> b \\ b
f :: ((b<a) -> b -> a -> b \\ b) -> (b<a') -> b -> a' -> b \\ b
f :: ((b<a) -> b -> a -> b \\ b) -> ((b<a') -> b -> a' -> b \\ b)
{ x = f r.x }
-}
|
mattias-lundell/timber-llvm
|
src/Decls.hs
|
bsd-3-clause
| 9,677
| 0
| 17
| 3,703
| 1,782
| 938
| 844
| 58
| 3
|
module Doukaku.Anagram (solve) where
solve :: String -> String
solve = show . maximum . map anagramLen' . allTails
where
anagramLen' ([], _) = 0
anagramLen' (y:ys, xs) = max (anagramLen (y:ys) xs) (anagramLen ys xs + 1)
anagramLen :: String -> String -> Int
anagramLen [] _ = 0
anagramLen (x:xs) ys = max result (anagramLen xs ys)
where
(_, ys2') = break (== x) ys
result = if null ys2' then 0 else 2 + anagramLen xs (tail ys2')
allTails :: String -> [(String, String)]
allTails = allTails' []
where
allTails' ys [] = (ys, []):[]
allTails' ys (x:xs) = (ys, x:xs) : allTails' (x:ys) xs
|
hiratara/doukaku-past-questions-advent-2013
|
src/Doukaku/Anagram.hs
|
bsd-3-clause
| 618
| 0
| 11
| 141
| 316
| 169
| 147
| 14
| 2
|
{-# LANGUAGE EmptyDataDecls #-}
-- | Introducing type constants
--
-- We wish to outlaw terms such as bad_sentence in CFG2EN.hs,
-- even though there may be an interpretation that accepts
-- these bad terms.
-- We really wish our terms represent all and only
-- valid CFG derivations. We accomplish this goal here.
-- Our approach is reminiscent of LCF.
module Lambda.CFG3EN where
data S -- clause
data NP -- noun phrase
data VP -- verb phrase
data TV -- transitive verb
-- | Parameterized types: cf notation:
--
-- > <string,features> in
--
-- the Minimalist Grammar
--
data EN a = EN { unEN :: String }
-- | One may think of the above data declaration as defining an
-- isomorphism between EN values and Strings. The functions
-- EN and unEN (what is their type?) witness the isomorphism.
-- It helps to look at their composition.
--
--
john, mary :: EN NP
like :: EN TV
r2 :: EN TV -> EN NP -> EN VP
r1 :: EN NP -> EN VP -> EN S
john = EN "John"
mary = EN "Mary"
like = EN "likes"
r2 (EN f) (EN x) = EN (f ++ " " ++ x)
r1 (EN x) (EN f) = EN (x ++ " " ++ f)
instance Show (EN a) where
show = unEN
sentence :: EN S
sentence = r1 john (r2 like mary)
-- Now the bad_sentence is rejected already in
-- the EN interpretation, in contrast to CFG2EN.hs.
-- The type error message clearly describes the error,
-- in the CFG terms.
-- bad_sentence = r2 (r2 like mary) john
|
suhailshergill/liboleg
|
Lambda/CFG3EN.hs
|
bsd-3-clause
| 1,564
| 0
| 8
| 475
| 267
| 153
| 114
| -1
| -1
|
type RGB = (Int, Int, Int)
data Suit = Spade | Heart | Diamond | Club deriving Show
data Color = Black | Red
rgb :: Suit -> RGB
rgb = toRGB . color
color :: Suit -> Color
color Spade = Black
color Heart = Red
color Diamond = Red
color Club = Black
toRGB :: Color -> RGB
toRGB Black = (0, 0, 0)
toRGB Red = (0xff, 0, 0)
|
YoshikuniJujo/funpaala
|
samples/21_adt/cards1.hs
|
bsd-3-clause
| 324
| 0
| 5
| 77
| 147
| 84
| 63
| 13
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module Valkyrie.Graphics.Mesh.Types where
import Control.Lens.TH
import qualified Data.Map as M
import Data.Typeable
import qualified Graphics.Rendering.OpenGL.Raw as GL
data Mesh = Mesh {
_meshVertexCount :: GL.GLsizei,
_meshVBO :: GL.GLuint,
_meshParts :: M.Map String (Int, GL.GLuint)
} deriving (Show, Typeable)
makeLenses ''Mesh
|
Feeniks/valkyrie
|
src/Valkyrie/Graphics/Mesh/Types.hs
|
bsd-3-clause
| 384
| 0
| 11
| 61
| 103
| 64
| 39
| 12
| 0
|
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Int
-- Copyright : (c) The University of Glasgow 1997-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The sized integral datatypes, 'Int8', 'Int16', 'Int32', and 'Int64'.
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
-- #hide
module GHC.Int (
Int8(..), Int16(..), Int32(..), Int64(..))
where
import Data.Bits
import {-# SOURCE #-} GHC.Err
import GHC.Base
import GHC.Enum
import GHC.Num
import GHC.Real
import GHC.Read
import GHC.Arr
import GHC.Word
import GHC.Show
------------------------------------------------------------------------
-- type Int8
------------------------------------------------------------------------
-- Int8 is represented in the same way as Int. Operations may assume
-- and must ensure that it holds only values from its logical range.
data Int8 = I8# Int# deriving (Eq, Ord)
-- ^ 8-bit signed integer type
instance Show Int8 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int8 where
(I8# x#) + (I8# y#) = I8# (narrow8Int# (x# +# y#))
(I8# x#) - (I8# y#) = I8# (narrow8Int# (x# -# y#))
(I8# x#) * (I8# y#) = I8# (narrow8Int# (x# *# y#))
negate (I8# x#) = I8# (narrow8Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I8# (narrow8Int# i#)
fromInteger (J# s# d#) = I8# (narrow8Int# (integer2Int# s# d#))
instance Real Int8 where
toRational x = toInteger x % 1
instance Enum Int8 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int8"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int8"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int8) && i <= fromIntegral (maxBound::Int8)
= I8# i#
| otherwise = toEnumError "Int8" i (minBound::Int8, maxBound::Int8)
fromEnum (I8# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int8 where
quot x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I8# x#) y@(I8# y#)
| y /= 0 = I8# (narrow8Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `quotInt#` y#)),
I8# (narrow8Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I8# x#) y@(I8# y#)
| y /= 0 = (I8# (narrow8Int# (x# `divInt#` y#)),
I8# (narrow8Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I8# x#) = S# x#
instance Bounded Int8 where
minBound = -0x80
maxBound = 0x7F
instance Ix Int8 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
instance Read Int8 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int8 where
(I8# x#) .&. (I8# y#) = I8# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I8# x#) .|. (I8# y#) = I8# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I8# x#) `xor` (I8# y#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I8# x#) = I8# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I8# x#) `shift` (I# i#)
| i# >=# 0# = I8# (narrow8Int# (x# `iShiftL#` i#))
| otherwise = I8# (x# `iShiftRA#` negateInt# i#)
(I8# x#) `rotate` (I# i#)
| i'# ==# 0#
= I8# x#
| otherwise
= I8# (narrow8Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (8# -# i'#)))))
where
x'# = narrow8Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 7#)
bitSize _ = 8
isSigned _ = True
{-# RULES
"fromIntegral/Int8->Int8" fromIntegral = id :: Int8 -> Int8
"fromIntegral/a->Int8" fromIntegral = \x -> case fromIntegral x of I# x# -> I8# (narrow8Int# x#)
"fromIntegral/Int8->a" fromIntegral = \(I8# x#) -> fromIntegral (I# x#)
#-}
------------------------------------------------------------------------
-- type Int16
------------------------------------------------------------------------
-- Int16 is represented in the same way as Int. Operations may assume
-- and must ensure that it holds only values from its logical range.
data Int16 = I16# Int# deriving (Eq, Ord)
-- ^ 16-bit signed integer type
instance Show Int16 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int16 where
(I16# x#) + (I16# y#) = I16# (narrow16Int# (x# +# y#))
(I16# x#) - (I16# y#) = I16# (narrow16Int# (x# -# y#))
(I16# x#) * (I16# y#) = I16# (narrow16Int# (x# *# y#))
negate (I16# x#) = I16# (narrow16Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I16# (narrow16Int# i#)
fromInteger (J# s# d#) = I16# (narrow16Int# (integer2Int# s# d#))
instance Real Int16 where
toRational x = toInteger x % 1
instance Enum Int16 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int16"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int16"
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int16) && i <= fromIntegral (maxBound::Int16)
= I16# i#
| otherwise = toEnumError "Int16" i (minBound::Int16, maxBound::Int16)
fromEnum (I16# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int16 where
quot x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I16# x#) y@(I16# y#)
| y /= 0 = I16# (narrow16Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `quotInt#` y#)),
I16# (narrow16Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I16# x#) y@(I16# y#)
| y /= 0 = (I16# (narrow16Int# (x# `divInt#` y#)),
I16# (narrow16Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I16# x#) = S# x#
instance Bounded Int16 where
minBound = -0x8000
maxBound = 0x7FFF
instance Ix Int16 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
instance Read Int16 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int16 where
(I16# x#) .&. (I16# y#) = I16# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I16# x#) .|. (I16# y#) = I16# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I16# x#) `xor` (I16# y#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I16# x#) = I16# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I16# x#) `shift` (I# i#)
| i# >=# 0# = I16# (narrow16Int# (x# `iShiftL#` i#))
| otherwise = I16# (x# `iShiftRA#` negateInt# i#)
(I16# x#) `rotate` (I# i#)
| i'# ==# 0#
= I16# x#
| otherwise
= I16# (narrow16Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (16# -# i'#)))))
where
x'# = narrow16Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 15#)
bitSize _ = 16
isSigned _ = True
{-# RULES
"fromIntegral/Word8->Int16" fromIntegral = \(W8# x#) -> I16# (word2Int# x#)
"fromIntegral/Int8->Int16" fromIntegral = \(I8# x#) -> I16# x#
"fromIntegral/Int16->Int16" fromIntegral = id :: Int16 -> Int16
"fromIntegral/a->Int16" fromIntegral = \x -> case fromIntegral x of I# x# -> I16# (narrow16Int# x#)
"fromIntegral/Int16->a" fromIntegral = \(I16# x#) -> fromIntegral (I# x#)
#-}
------------------------------------------------------------------------
-- type Int32
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 32
data Int32 = I32# Int32#
-- ^ 32-bit signed integer type
instance Eq Int32 where
(I32# x#) == (I32# y#) = x# `eqInt32#` y#
(I32# x#) /= (I32# y#) = x# `neInt32#` y#
instance Ord Int32 where
(I32# x#) < (I32# y#) = x# `ltInt32#` y#
(I32# x#) <= (I32# y#) = x# `leInt32#` y#
(I32# x#) > (I32# y#) = x# `gtInt32#` y#
(I32# x#) >= (I32# y#) = x# `geInt32#` y#
instance Show Int32 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (x# `plusInt32#` y#)
(I32# x#) - (I32# y#) = I32# (x# `minusInt32#` y#)
(I32# x#) * (I32# y#) = I32# (x# `timesInt32#` y#)
negate (I32# x#) = I32# (negateInt32# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (intToInt32# i#)
fromInteger (J# s# d#) = I32# (integerToInt32# s# d#)
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
toEnum (I# i#) = I32# (intToInt32# i#)
fromEnum x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int32ToInt# x#)
| otherwise = fromEnumError "Int32" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `quotInt32#` y#)
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `remInt32#` y#)
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `divInt32#` y#)
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (x# `modInt32#` y#)
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `quotInt32#` y#), I32# (x# `remInt32#` y#))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (x# `divInt32#` y#), I32# (x# `modInt32#` y#))
| otherwise = divZeroError
toInteger x@(I32# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int32ToInt# x#)
| otherwise = case int32ToInteger# x# of (# s, d #) -> J# s d
divInt32#, modInt32# :: Int32# -> Int32# -> Int32#
x# `divInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `minusInt32#` intToInt32# 1#) `quotInt32#` y#
| (x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= ((x# `minusInt32#` y#) `plusInt32#` intToInt32# 1#) `quotInt32#` y#
| otherwise = x# `quotInt32#` y#
x# `modInt32#` y#
| (x# `gtInt32#` intToInt32# 0#) && (y# `ltInt32#` intToInt32# 0#) ||
(x# `ltInt32#` intToInt32# 0#) && (y# `gtInt32#` intToInt32# 0#)
= if r# `neInt32#` intToInt32# 0# then r# `plusInt32#` y# else intToInt32# 0#
| otherwise = r#
where
r# = x# `remInt32#` y#
instance Read Int32 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `and32#` int32ToWord32# y#))
(I32# x#) .|. (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `or32#` int32ToWord32# y#))
(I32# x#) `xor` (I32# y#) = I32# (word32ToInt32# (int32ToWord32# x# `xor32#` int32ToWord32# y#))
complement (I32# x#) = I32# (word32ToInt32# (not32# (int32ToWord32# x#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (x# `iShiftL32#` i#)
| otherwise = I32# (x# `iShiftRA32#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (word32ToInt32# ((x'# `shiftL32#` i'#) `or32#`
(x'# `shiftRL32#` (32# -# i'#))))
where
x'# = int32ToWord32# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
foreign import "stg_eqInt32" unsafe eqInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_neInt32" unsafe neInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_ltInt32" unsafe ltInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_leInt32" unsafe leInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_gtInt32" unsafe gtInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_geInt32" unsafe geInt32# :: Int32# -> Int32# -> Bool
foreign import "stg_plusInt32" unsafe plusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_minusInt32" unsafe minusInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_timesInt32" unsafe timesInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_negateInt32" unsafe negateInt32# :: Int32# -> Int32#
foreign import "stg_quotInt32" unsafe quotInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_remInt32" unsafe remInt32# :: Int32# -> Int32# -> Int32#
foreign import "stg_intToInt32" unsafe intToInt32# :: Int# -> Int32#
foreign import "stg_int32ToInt" unsafe int32ToInt# :: Int32# -> Int#
foreign import "stg_wordToWord32" unsafe wordToWord32# :: Word# -> Word32#
foreign import "stg_int32ToWord32" unsafe int32ToWord32# :: Int32# -> Word32#
foreign import "stg_word32ToInt32" unsafe word32ToInt32# :: Word32# -> Int32#
foreign import "stg_and32" unsafe and32# :: Word32# -> Word32# -> Word32#
foreign import "stg_or32" unsafe or32# :: Word32# -> Word32# -> Word32#
foreign import "stg_xor32" unsafe xor32# :: Word32# -> Word32# -> Word32#
foreign import "stg_not32" unsafe not32# :: Word32# -> Word32#
foreign import "stg_iShiftL32" unsafe iShiftL32# :: Int32# -> Int# -> Int32#
foreign import "stg_iShiftRA32" unsafe iShiftRA32# :: Int32# -> Int# -> Int32#
foreign import "stg_shiftL32" unsafe shiftL32# :: Word32# -> Int# -> Word32#
foreign import "stg_shiftRL32" unsafe shiftRL32# :: Word32# -> Int# -> Word32#
{-# RULES
"fromIntegral/Int->Int32" fromIntegral = \(I# x#) -> I32# (intToInt32# x#)
"fromIntegral/Word->Int32" fromIntegral = \(W# x#) -> I32# (word32ToInt32# (wordToWord32# x#))
"fromIntegral/Word32->Int32" fromIntegral = \(W32# x#) -> I32# (word32ToInt32# x#)
"fromIntegral/Int32->Int" fromIntegral = \(I32# x#) -> I# (int32ToInt# x#)
"fromIntegral/Int32->Word" fromIntegral = \(I32# x#) -> W# (int2Word# (int32ToInt# x#))
"fromIntegral/Int32->Word32" fromIntegral = \(I32# x#) -> W32# (int32ToWord32# x#)
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
#-}
#else
-- Int32 is represented in the same way as Int.
#if WORD_SIZE_IN_BITS > 32
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
#endif
data Int32 = I32# Int# deriving (Eq, Ord)
-- ^ 32-bit signed integer type
instance Show Int32 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int32 where
(I32# x#) + (I32# y#) = I32# (narrow32Int# (x# +# y#))
(I32# x#) - (I32# y#) = I32# (narrow32Int# (x# -# y#))
(I32# x#) * (I32# y#) = I32# (narrow32Int# (x# *# y#))
negate (I32# x#) = I32# (narrow32Int# (negateInt# x#))
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I32# (narrow32Int# i#)
fromInteger (J# s# d#) = I32# (narrow32Int# (integer2Int# s# d#))
instance Enum Int32 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int32"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int32"
#if WORD_SIZE_IN_BITS == 32
toEnum (I# i#) = I32# i#
#else
toEnum i@(I# i#)
| i >= fromIntegral (minBound::Int32) && i <= fromIntegral (maxBound::Int32)
= I32# i#
| otherwise = toEnumError "Int32" i (minBound::Int32, maxBound::Int32)
#endif
fromEnum (I32# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int32 where
quot x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `quotInt#` y#))
| otherwise = divZeroError
rem x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `remInt#` y#))
| otherwise = divZeroError
div x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `divInt#` y#))
| otherwise = divZeroError
mod x@(I32# x#) y@(I32# y#)
| y /= 0 = I32# (narrow32Int# (x# `modInt#` y#))
| otherwise = divZeroError
quotRem x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `quotInt#` y#)),
I32# (narrow32Int# (x# `remInt#` y#)))
| otherwise = divZeroError
divMod x@(I32# x#) y@(I32# y#)
| y /= 0 = (I32# (narrow32Int# (x# `divInt#` y#)),
I32# (narrow32Int# (x# `modInt#` y#)))
| otherwise = divZeroError
toInteger (I32# x#) = S# x#
instance Read Int32 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int32 where
(I32# x#) .&. (I32# y#) = I32# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I32# x#) .|. (I32# y#) = I32# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I32# x#) `xor` (I32# y#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I32# x#) = I32# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I32# x#) `shift` (I# i#)
| i# >=# 0# = I32# (narrow32Int# (x# `iShiftL#` i#))
| otherwise = I32# (x# `iShiftRA#` negateInt# i#)
(I32# x#) `rotate` (I# i#)
| i'# ==# 0#
= I32# x#
| otherwise
= I32# (narrow32Int# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (32# -# i'#)))))
where
x'# = narrow32Word# (int2Word# x#)
i'# = word2Int# (int2Word# i# `and#` int2Word# 31#)
bitSize _ = 32
isSigned _ = True
{-# RULES
"fromIntegral/Word8->Int32" fromIntegral = \(W8# x#) -> I32# (word2Int# x#)
"fromIntegral/Word16->Int32" fromIntegral = \(W16# x#) -> I32# (word2Int# x#)
"fromIntegral/Int8->Int32" fromIntegral = \(I8# x#) -> I32# x#
"fromIntegral/Int16->Int32" fromIntegral = \(I16# x#) -> I32# x#
"fromIntegral/Int32->Int32" fromIntegral = id :: Int32 -> Int32
"fromIntegral/a->Int32" fromIntegral = \x -> case fromIntegral x of I# x# -> I32# (narrow32Int# x#)
"fromIntegral/Int32->a" fromIntegral = \(I32# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int32 where
toRational x = toInteger x % 1
instance Bounded Int32 where
minBound = -0x80000000
maxBound = 0x7FFFFFFF
instance Ix Int32 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
------------------------------------------------------------------------
-- type Int64
------------------------------------------------------------------------
#if WORD_SIZE_IN_BITS < 64
data Int64 = I64# Int64#
-- ^ 64-bit signed integer type
instance Eq Int64 where
(I64# x#) == (I64# y#) = x# `eqInt64#` y#
(I64# x#) /= (I64# y#) = x# `neInt64#` y#
instance Ord Int64 where
(I64# x#) < (I64# y#) = x# `ltInt64#` y#
(I64# x#) <= (I64# y#) = x# `leInt64#` y#
(I64# x#) > (I64# y#) = x# `gtInt64#` y#
(I64# x#) >= (I64# y#) = x# `geInt64#` y#
instance Show Int64 where
showsPrec p x = showsPrec p (toInteger x)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# `plusInt64#` y#)
(I64# x#) - (I64# y#) = I64# (x# `minusInt64#` y#)
(I64# x#) * (I64# y#) = I64# (x# `timesInt64#` y#)
negate (I64# x#) = I64# (negateInt64# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# (intToInt64# i#)
fromInteger (J# s# d#) = I64# (integerToInt64# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# (intToInt64# i#)
fromEnum x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= I# (int64ToInt# x#)
| otherwise = fromEnumError "Int64" x
enumFrom = integralEnumFrom
enumFromThen = integralEnumFromThen
enumFromTo = integralEnumFromTo
enumFromThenTo = integralEnumFromThenTo
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt64#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt64#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt64#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt64#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt64#` y#), I64# (x# `remInt64#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt64#` y#), I64# (x# `modInt64#` y#))
| otherwise = divZeroError
toInteger x@(I64# x#)
| x >= fromIntegral (minBound::Int) && x <= fromIntegral (maxBound::Int)
= S# (int64ToInt# x#)
| otherwise = case int64ToInteger# x# of (# s, d #) -> J# s d
divInt64#, modInt64# :: Int64# -> Int64# -> Int64#
x# `divInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `minusInt64#` intToInt64# 1#) `quotInt64#` y#
| (x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= ((x# `minusInt64#` y#) `plusInt64#` intToInt64# 1#) `quotInt64#` y#
| otherwise = x# `quotInt64#` y#
x# `modInt64#` y#
| (x# `gtInt64#` intToInt64# 0#) && (y# `ltInt64#` intToInt64# 0#) ||
(x# `ltInt64#` intToInt64# 0#) && (y# `gtInt64#` intToInt64# 0#)
= if r# `neInt64#` intToInt64# 0# then r# `plusInt64#` y# else intToInt64# 0#
| otherwise = r#
where
r# = x# `remInt64#` y#
instance Read Int64 where
readsPrec p s = [(fromInteger x, r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `and64#` int64ToWord64# y#))
(I64# x#) .|. (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `or64#` int64ToWord64# y#))
(I64# x#) `xor` (I64# y#) = I64# (word64ToInt64# (int64ToWord64# x# `xor64#` int64ToWord64# y#))
complement (I64# x#) = I64# (word64ToInt64# (not64# (int64ToWord64# x#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL64#` i#)
| otherwise = I64# (x# `iShiftRA64#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word64ToInt64# ((x'# `uncheckedShiftL64#` i'#) `or64#`
(x'# `uncheckedShiftRL64#` (64# -# i'#))))
where
x'# = int64ToWord64# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
-- give the 64-bit shift operations the same treatment as the 32-bit
-- ones (see GHC.Base), namely we wrap them in tests to catch the
-- cases when we're shifting more than 64 bits to avoid unspecified
-- behaviour in the C shift operations.
iShiftL64#, iShiftRA64# :: Int64# -> Int# -> Int64#
a `iShiftL64#` b | b >=# 64# = intToInt64# 0#
| otherwise = a `uncheckedIShiftL64#` b
a `iShiftRA64#` b | b >=# 64# = if a `ltInt64#` (intToInt64# 0#)
then intToInt64# (-1#)
else intToInt64# 0#
| otherwise = a `uncheckedIShiftRA64#` b
foreign import ccall unsafe "stg_eqInt64" eqInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_neInt64" neInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_ltInt64" ltInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_leInt64" leInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_gtInt64" gtInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_geInt64" geInt64# :: Int64# -> Int64# -> Bool
foreign import ccall unsafe "stg_plusInt64" plusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_minusInt64" minusInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_timesInt64" timesInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_negateInt64" negateInt64# :: Int64# -> Int64#
foreign import ccall unsafe "stg_quotInt64" quotInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_remInt64" remInt64# :: Int64# -> Int64# -> Int64#
foreign import ccall unsafe "stg_intToInt64" intToInt64# :: Int# -> Int64#
foreign import ccall unsafe "stg_int64ToInt" int64ToInt# :: Int64# -> Int#
foreign import ccall unsafe "stg_wordToWord64" wordToWord64# :: Word# -> Word64#
foreign import ccall unsafe "stg_int64ToWord64" int64ToWord64# :: Int64# -> Word64#
foreign import ccall unsafe "stg_word64ToInt64" word64ToInt64# :: Word64# -> Int64#
foreign import ccall unsafe "stg_and64" and64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_or64" or64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_xor64" xor64# :: Word64# -> Word64# -> Word64#
foreign import ccall unsafe "stg_not64" not64# :: Word64# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftL64" uncheckedShiftL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedShiftRL64" uncheckedShiftRL64# :: Word64# -> Int# -> Word64#
foreign import ccall unsafe "stg_uncheckedIShiftL64" uncheckedIShiftL64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_uncheckedIShiftRA64" uncheckedIShiftRA64# :: Int64# -> Int# -> Int64#
foreign import ccall unsafe "stg_integerToInt64" integerToInt64# :: Int# -> ByteArray# -> Int64#
{-# RULES
"fromIntegral/Int->Int64" fromIntegral = \(I# x#) -> I64# (intToInt64# x#)
"fromIntegral/Word->Int64" fromIntegral = \(W# x#) -> I64# (word64ToInt64# (wordToWord64# x#))
"fromIntegral/Word64->Int64" fromIntegral = \(W64# x#) -> I64# (word64ToInt64# x#)
"fromIntegral/Int64->Int" fromIntegral = \(I64# x#) -> I# (int64ToInt# x#)
"fromIntegral/Int64->Word" fromIntegral = \(I64# x#) -> W# (int2Word# (int64ToInt# x#))
"fromIntegral/Int64->Word64" fromIntegral = \(I64# x#) -> W64# (int64ToWord64# x#)
"fromIntegral/Int64->Int64" fromIntegral = id :: Int64 -> Int64
#-}
#else
-- Int64 is represented in the same way as Int.
-- Operations may assume and must ensure that it holds only values
-- from its logical range.
data Int64 = I64# Int# deriving (Eq, Ord)
-- ^ 64-bit signed integer type
instance Show Int64 where
showsPrec p x = showsPrec p (fromIntegral x :: Int)
instance Num Int64 where
(I64# x#) + (I64# y#) = I64# (x# +# y#)
(I64# x#) - (I64# y#) = I64# (x# -# y#)
(I64# x#) * (I64# y#) = I64# (x# *# y#)
negate (I64# x#) = I64# (negateInt# x#)
abs x | x >= 0 = x
| otherwise = negate x
signum x | x > 0 = 1
signum 0 = 0
signum _ = -1
fromInteger (S# i#) = I64# i#
fromInteger (J# s# d#) = I64# (integer2Int# s# d#)
instance Enum Int64 where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Int64"
pred x
| x /= minBound = x - 1
| otherwise = predError "Int64"
toEnum (I# i#) = I64# i#
fromEnum (I64# x#) = I# x#
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Integral Int64 where
quot x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `quotInt#` y#)
| otherwise = divZeroError
rem x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `remInt#` y#)
| otherwise = divZeroError
div x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `divInt#` y#)
| otherwise = divZeroError
mod x@(I64# x#) y@(I64# y#)
| y /= 0 = I64# (x# `modInt#` y#)
| otherwise = divZeroError
quotRem x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `quotInt#` y#), I64# (x# `remInt#` y#))
| otherwise = divZeroError
divMod x@(I64# x#) y@(I64# y#)
| y /= 0 = (I64# (x# `divInt#` y#), I64# (x# `modInt#` y#))
| otherwise = divZeroError
toInteger (I64# x#) = S# x#
instance Read Int64 where
readsPrec p s = [(fromIntegral (x::Int), r) | (x, r) <- readsPrec p s]
instance Bits Int64 where
(I64# x#) .&. (I64# y#) = I64# (word2Int# (int2Word# x# `and#` int2Word# y#))
(I64# x#) .|. (I64# y#) = I64# (word2Int# (int2Word# x# `or#` int2Word# y#))
(I64# x#) `xor` (I64# y#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# y#))
complement (I64# x#) = I64# (word2Int# (int2Word# x# `xor#` int2Word# (-1#)))
(I64# x#) `shift` (I# i#)
| i# >=# 0# = I64# (x# `iShiftL#` i#)
| otherwise = I64# (x# `iShiftRA#` negateInt# i#)
(I64# x#) `rotate` (I# i#)
| i'# ==# 0#
= I64# x#
| otherwise
= I64# (word2Int# ((x'# `shiftL#` i'#) `or#`
(x'# `shiftRL#` (64# -# i'#))))
where
x'# = int2Word# x#
i'# = word2Int# (int2Word# i# `and#` int2Word# 63#)
bitSize _ = 64
isSigned _ = True
{-# RULES
"fromIntegral/a->Int64" fromIntegral = \x -> case fromIntegral x of I# x# -> I64# x#
"fromIntegral/Int64->a" fromIntegral = \(I64# x#) -> fromIntegral (I# x#)
#-}
#endif
instance Real Int64 where
toRational x = toInteger x % 1
instance Bounded Int64 where
minBound = -0x8000000000000000
maxBound = 0x7FFFFFFFFFFFFFFF
instance Ix Int64 where
range (m,n) = [m..n]
unsafeIndex b@(m,_) i = fromIntegral i - fromIntegral m
inRange (m,n) i = m <= i && i <= n
|
alekar/hugs
|
packages/base/GHC/Int.hs
|
bsd-3-clause
| 33,811
| 545
| 17
| 10,679
| 9,663
| 5,029
| 4,634
| -1
| -1
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.SpirvExtensions
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.SpirvExtensions (
-- * Extension Support
glGetARBSpirvExtensions,
gl_ARB_spirv_extensions,
-- * Enums
pattern GL_NUM_SPIR_V_EXTENSIONS,
pattern GL_SPIR_V_EXTENSIONS
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/SpirvExtensions.hs
|
bsd-3-clause
| 695
| 0
| 5
| 95
| 52
| 39
| 13
| 8
| 0
|
module Main (main) where
import Control.Monad (void)
import Text.Megaparsec
import Text.Megaparsec.Expr
import Text.Megaparsec.String -- input stream is of the type ‘String’
import qualified Text.Megaparsec.Lexer as L
data BExpr
= BoolConst Bool
| Not BExpr
| BBinary BBinOp BExpr BExpr
| RBinary RBinOp AExpr AExpr
deriving (Show)
data BBinOp
= And
| Or
deriving (Show)
data RBinOp
= Greater
| Less
deriving (Show)
data AExpr
= Var String
| IntConst Integer
| Neg AExpr
| ABinary ABinOp AExpr AExpr
deriving (Show)
data ABinOp
= Add
| Subtract
| Multiply
| Divide
deriving (Show)
data Stmt
= Seq [Stmt]
| Assign String AExpr
| If BExpr Stmt Stmt
| While BExpr Stmt
| Skip
deriving (Show)
sc :: Parser ()
sc = L.space (void spaceChar) lineCmnt blockCmnt
where lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: String -> Parser String
symbol = L.symbol sc
-- | 'parens' parses something between parenthesis.
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
-- | 'integer' parses an integer.
integer :: Parser Integer
integer = lexeme L.integer
-- | 'semi' parses a semicolon.
semi :: Parser String
semi = symbol ";"
rword :: String -> Parser ()
rword w = string w *> notFollowedBy alphaNumChar *> sc
rws :: [String] -- list of reserved words
rws = ["if","then","else","while","do","skip","true","false","not","and","or"]
identifier :: Parser String
identifier = (lexeme . try) (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x = if x `elem` rws
then fail $ "keyword " ++ show x ++ " cannot be an identifier"
else return x
whileParser :: Parser Stmt
whileParser = between sc eof stmt
stmt :: Parser Stmt
stmt = parens stmt <|> stmtSeq
stmtSeq :: Parser Stmt
stmtSeq = f <$> sepBy1 stmt' semi
-- if there's only one stmt return it without using ‘Seq’
where f l = if length l == 1 then head l else Seq l
stmt' :: Parser Stmt
stmt' = ifStmt <|> whileStmt <|> skipStmt <|> assignStmt
ifStmt :: Parser Stmt
ifStmt = do
rword "if"
cond <- bExpr
rword "then"
stmt1 <- stmt
rword "else"
stmt2 <- stmt
return (If cond stmt1 stmt2)
whileStmt :: Parser Stmt
whileStmt = do
rword "while"
cond <- bExpr
rword "do"
stmt1 <- stmt
return (While cond stmt1)
assignStmt :: Parser Stmt
assignStmt = do
var <- identifier
void (symbol ":=")
expr <- aExpr
return (Assign var expr)
skipStmt :: Parser Stmt
skipStmt = Skip <$ rword "skip"
aExpr :: Parser AExpr
aExpr = makeExprParser aTerm aOperators
bExpr :: Parser BExpr
bExpr = makeExprParser bTerm bOperators
aOperators :: [[Operator Parser AExpr]]
aOperators =
[ [Prefix (Neg <$ symbol "-") ]
, [ InfixL (ABinary Multiply <$ symbol "*")
, InfixL (ABinary Divide <$ symbol "/") ]
, [ InfixL (ABinary Add <$ symbol "+")
, InfixL (ABinary Subtract <$ symbol "-") ]
]
bOperators :: [[Operator Parser BExpr]]
bOperators =
[ [Prefix (Not <$ rword "not") ]
, [InfixL (BBinary And <$ rword "and")
, InfixL (BBinary Or <$ rword "or") ]
]
aTerm :: Parser AExpr
aTerm = parens aExpr
<|> Var <$> identifier
<|> IntConst <$> integer
bTerm :: Parser BExpr
bTerm = parens bExpr
<|> (rword "true" *> pure (BoolConst True))
<|> (rword "false" *> pure (BoolConst False))
<|> rExpr
rExpr :: Parser BExpr
rExpr = do
a1 <- aExpr
op <- relation
a2 <- aExpr
return (RBinary op a1 a2)
relation :: Parser RBinOp
relation = (symbol ">" *> pure Greater)
<|> (symbol "<" *> pure Less)
main :: IO ()
main = return ()
|
mrkkrp/megaparsec-site
|
tutorial-code/ParsingWhile.hs
|
bsd-3-clause
| 3,707
| 0
| 12
| 853
| 1,333
| 687
| 646
| 132
| 2
|
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Monitors.Disk
-- Copyright : (c) 2010, 2011, 2012 Jose A Ortega Ruiz
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A Ortega Ruiz <jao@gnu.org>
-- Stability : unstable
-- Portability : unportable
--
-- Disk usage and throughput monitors for Xmobar
--
-----------------------------------------------------------------------------
module Plugins.Monitors.Disk (diskUConfig, runDiskU, startDiskIO) where
import Plugins.Monitors.Common
import StatFS
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Control.Exception (SomeException, handle)
import Control.Monad (zipWithM)
import qualified Data.ByteString.Lazy.Char8 as B
import Data.List (isPrefixOf, find)
import System.Directory (canonicalizePath)
diskIOConfig :: IO MConfig
diskIOConfig = mkMConfig "" ["total", "read", "write",
"totalbar", "readbar", "writebar"]
diskUConfig :: IO MConfig
diskUConfig = mkMConfig ""
["size", "free", "used", "freep", "usedp", "freebar", "usedbar"]
type DevName = String
type Path = String
type DevDataRef = IORef [(DevName, [Float])]
mountedDevices :: [String] -> IO [(DevName, Path)]
mountedDevices req = do
s <- B.readFile "/etc/mtab"
parse `fmap` mapM canon (devs s)
where
canon (d, p) = do {d' <- canonicalizePath d; return (d', p)}
devs = filter isDev . map (firstTwo . B.words) . B.lines
parse = map undev . filter isReq
firstTwo (a:b:_) = (B.unpack a, B.unpack b)
firstTwo _ = ("", "")
isDev (d, _) = "/dev/" `isPrefixOf` d
isReq (d, p) = p `elem` req || drop 5 d `elem` req
undev (d, f) = (drop 5 d, f)
diskData :: IO [(DevName, [Float])]
diskData = do
s <- B.readFile "/proc/diskstats"
let extract ws = (head ws, map read (tail ws))
return $ map (extract . map B.unpack . drop 2 . B.words) (B.lines s)
mountedData :: DevDataRef -> [DevName] -> IO [(DevName, [Float])]
mountedData dref devs = do
dt <- readIORef dref
dt' <- diskData
writeIORef dref dt'
return $ map (parseDev (zipWith diff dt' dt)) devs
where diff (dev, xs) (_, ys) = (dev, zipWith (-) xs ys)
parseDev :: [(DevName, [Float])] -> DevName -> (DevName, [Float])
parseDev dat dev =
case find ((==dev) . fst) dat of
Nothing -> (dev, [0, 0, 0])
Just (_, xs) ->
let rSp = speed (xs !! 2) (xs !! 3)
wSp = speed (xs !! 6) (xs !! 7)
sp = speed (xs !! 2 + xs !! 6) (xs !! 3 + xs !! 7)
speed x t = if t == 0 then 0 else 500 * x / t
dat' = if length xs > 6 then [sp, rSp, wSp] else [0, 0, 0]
in (dev, dat')
speedToStr :: Float -> String
speedToStr = showWithUnits 2 1
sizeToStr :: Integer -> String
sizeToStr = showWithUnits 3 0 . fromIntegral
findTempl :: DevName -> Path -> [(String, String)] -> String
findTempl dev path disks =
case find devOrPath disks of
Just (_, t) -> t
Nothing -> ""
where devOrPath (d, _) = d == dev || d == path
devTemplates :: [(String, String)]
-> [(DevName, Path)]
-> [(DevName, [Float])]
-> [(String, [Float])]
devTemplates disks mounted dat =
map (\(d, p) -> (findTempl d p disks, findData d)) mounted
where findData dev = case find ((==dev) . fst) dat of
Nothing -> [0, 0, 0]
Just (_, xs) -> xs
runDiskIO' :: (String, [Float]) -> Monitor String
runDiskIO' (tmp, xs) = do
s <- mapM (showWithColors speedToStr) xs
b <- mapM (showLogBar 0.8) xs
setConfigValue tmp template
parseTemplate $ s ++ b
runDiskIO :: DevDataRef -> [(String, String)] -> [String] -> Monitor String
runDiskIO dref disks _ = do
mounted <- io $ mountedDevices (map fst disks)
dat <- io $ mountedData dref (map fst mounted)
strs <- mapM runDiskIO' $ devTemplates disks mounted dat
return $ unwords strs
startDiskIO :: [(String, String)] ->
[String] -> Int -> (String -> IO ()) -> IO ()
startDiskIO disks args rate cb = do
mounted <- mountedDevices (map fst disks)
dref <- newIORef (map (\d -> (fst d, repeat 0)) mounted)
_ <- mountedData dref (map fst mounted)
runM args diskIOConfig (runDiskIO dref disks) rate cb
fsStats :: String -> IO [Integer]
fsStats path = do
stats <- getFileSystemStats path
case stats of
Nothing -> return [0, 0, 0]
Just f -> let tot = fsStatByteCount f
free = fsStatBytesAvailable f
used = fsStatBytesUsed f
in return [tot, free, used]
runDiskU' :: String -> String -> Monitor String
runDiskU' tmp path = do
setConfigValue tmp template
[total, free, diff] <- io (handle ign $ fsStats path)
let strs = map sizeToStr [total, free, diff]
freep = if total > 0 then free * 100 `div` total else 0
fr = fromIntegral freep / 100
s <- zipWithM showWithColors' strs [100, freep, 100 - freep]
sp <- showPercentsWithColors [fr, 1 - fr]
fb <- showPercentBar (fromIntegral freep) fr
ub <- showPercentBar (fromIntegral $ 100 - freep) (1 - fr)
parseTemplate $ s ++ sp ++ [fb, ub]
where ign = const (return [0, 0, 0]) :: SomeException -> IO [Integer]
runDiskU :: [(String, String)] -> [String] -> Monitor String
runDiskU disks _ = do
devs <- io $ mountedDevices (map fst disks)
strs <- mapM (\(d, p) -> runDiskU' (findTempl d p disks) p) devs
return $ unwords strs
|
raboof/xmobar
|
src/Plugins/Monitors/Disk.hs
|
bsd-3-clause
| 5,411
| 0
| 16
| 1,297
| 2,196
| 1,173
| 1,023
| 118
| 4
|
{-# LANGUAGE TemplateHaskell #-}
module Sodium.Chloride.Program.Scalar
( module Sodium.Chloride.Program.Scalar
, module Sodium.Chloride.Program
) where
import Control.Lens (prism', Simple, Prism)
import Control.Lens.TH
import qualified Data.Map as M
import Sodium.Chloride.Program
data Program
= Program
{ _programFuncs :: [Func]
} deriving (Show)
data Func
= Func
{ _funcSig :: FuncSig
, _funcBody :: Body
, _funcResults :: [Expression]
} deriving (Show)
data Body
= Body
{ _bodyVars :: Vars
, _bodyStatements :: [Statement]
} deriving (Show)
data Statement
= Assign Name Expression
| SideCall Name Operator [Expression]
| Execute (Maybe Name) Operator [Expression]
| ForStatement ForCycle
| MultiIfStatement MultiIfBranch
| BodyStatement Body
deriving (Show)
data ForCycle
= ForCycle
{ _forName :: Name
, _forRange :: Expression
, _forBody :: Body
} deriving (Show)
data MultiIfBranch
= MultiIfBranch
{ _multiIfLeafs :: [(Expression, Body)]
, _multiIfElse :: Body
} deriving (Show)
data Expression
= Access Name
| Call Operator [Expression]
| Primary Literal
deriving (Show)
bodyEmpty :: Body
bodyEmpty = Body M.empty []
bodySingleton :: Simple Prism Body Statement
bodySingleton
= prism' (\s -> Body M.empty [s])
$ \case
Body vars [statement] | M.null vars -> Just statement
_ -> Nothing
makeLenses ''Func
makeLenses ''Body
makeLenses ''ForCycle
makeLenses ''MultiIfBranch
makeLenses ''Program
makePrisms ''Statement
|
kirbyfan64/sodium
|
src/Sodium/Chloride/Program/Scalar.hs
|
bsd-3-clause
| 1,475
| 44
| 13
| 253
| 509
| 286
| 223
| -1
| -1
|
{-# LANGUAGE TupleSections #-}
module Jerimum.PostgreSQL.Helper
( fetchAll
, fetchColsData
, fetchColsName
) where
import Control.Monad
import qualified Data.ByteString as B
import qualified Database.PostgreSQL.LibPQ as PQ
fetchColsData :: PQ.Result -> PQ.Row -> [PQ.Column] -> IO (Maybe [B.ByteString])
fetchColsData reply row ncols = sequence <$> mapM (PQ.getvalue' reply row) ncols
fetchColsName :: PQ.Result -> IO (Maybe [(PQ.Column, B.ByteString)])
fetchColsName reply = do
ncols <- pred <$> PQ.nfields reply
mcolnames <- sequence <$> mapM (PQ.fname reply) [0 .. ncols]
pure (zip [0 .. ncols] <$> mcolnames)
fetchAll :: PQ.Result -> IO (Maybe ([B.ByteString], [[B.ByteString]]))
fetchAll reply = do
nrows <- pred <$> PQ.ntuples reply
mcols <- fetchColsName reply
status <- PQ.resultStatus reply
case (status, mcols) of
(PQ.TuplesOk, Just cols) -> do
mrows <-
sequence <$>
forM [0 .. nrows] (\row -> fetchColsData reply row (map fst cols))
pure $ (map snd cols, ) <$> mrows
_ -> pure Nothing
|
dgvncsz0f/nws
|
src/Jerimum/PostgreSQL/Helper.hs
|
bsd-3-clause
| 1,079
| 0
| 19
| 230
| 410
| 215
| 195
| 27
| 2
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Renaming of patterns
Basically dependency analysis.
Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
general, all of these functions return a renamed thing, and a set of
free variables.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
module GHC.Rename.Pat (-- main entry points
rnPat, rnPats, rnBindPat, rnPatAndThen,
NameMaker, applyNameMaker, -- a utility for making names:
localRecNameMaker, topRecNameMaker, -- sometimes we want to make local names,
-- sometimes we want to make top (qualified) names.
isTopRecNameMaker,
rnHsRecFields, HsRecFieldContext(..),
rnHsRecUpdFields,
-- CpsRn monad
CpsRn, liftCps,
-- Literals
rnLit, rnOverLit,
-- Pattern Error messages that are also used elsewhere
checkTupSize, patSigErr
) where
-- ENH: thin imports to only what is necessary for patterns
import GhcPrelude
import {-# SOURCE #-} GHC.Rename.Expr ( rnLExpr )
import {-# SOURCE #-} GHC.Rename.Splice ( rnSplicePat )
#include "HsVersions.h"
import GHC.Hs
import TcRnMonad
import TcHsSyn ( hsOverLitName )
import GHC.Rename.Env
import GHC.Rename.Fixity
import GHC.Rename.Utils ( HsDocContext(..), newLocalBndrRn, bindLocalNames
, warnUnusedMatches, newLocalBndrRn
, checkUnusedRecordWildcard
, checkDupNames, checkDupAndShadowedNames
, checkTupSize , unknownSubordinateErr )
import GHC.Rename.Types
import PrelNames
import Name
import NameSet
import RdrName
import BasicTypes
import Util
import ListSetOps ( removeDups )
import Outputable
import SrcLoc
import Literal ( inCharRange )
import TysWiredIn ( nilDataCon )
import DataCon
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad ( when, ap, guard )
import qualified Data.List.NonEmpty as NE
import Data.Ratio
{-
*********************************************************
* *
The CpsRn Monad
* *
*********************************************************
Note [CpsRn monad]
~~~~~~~~~~~~~~~~~~
The CpsRn monad uses continuation-passing style to support this
style of programming:
do { ...
; ns <- bindNames rs
; ...blah... }
where rs::[RdrName], ns::[Name]
The idea is that '...blah...'
a) sees the bindings of ns
b) returns the free variables it mentions
so that bindNames can report unused ones
In particular,
mapM rnPatAndThen [p1, p2, p3]
has a *left-to-right* scoping: it makes the binders in
p1 scope over p2,p3.
-}
newtype CpsRn b = CpsRn { unCpsRn :: forall r. (b -> RnM (r, FreeVars))
-> RnM (r, FreeVars) }
deriving (Functor)
-- See Note [CpsRn monad]
instance Applicative CpsRn where
pure x = CpsRn (\k -> k x)
(<*>) = ap
instance Monad CpsRn where
(CpsRn m) >>= mk = CpsRn (\k -> m (\v -> unCpsRn (mk v) k))
runCps :: CpsRn a -> RnM (a, FreeVars)
runCps (CpsRn m) = m (\r -> return (r, emptyFVs))
liftCps :: RnM a -> CpsRn a
liftCps rn_thing = CpsRn (\k -> rn_thing >>= k)
liftCpsFV :: RnM (a, FreeVars) -> CpsRn a
liftCpsFV rn_thing = CpsRn (\k -> do { (v,fvs1) <- rn_thing
; (r,fvs2) <- k v
; return (r, fvs1 `plusFV` fvs2) })
wrapSrcSpanCps :: (a -> CpsRn b) -> Located a -> CpsRn (Located b)
-- Set the location, and also wrap it around the value returned
wrapSrcSpanCps fn (L loc a)
= CpsRn (\k -> setSrcSpan loc $
unCpsRn (fn a) $ \v ->
k (L loc v))
lookupConCps :: Located RdrName -> CpsRn (Located Name)
lookupConCps con_rdr
= CpsRn (\k -> do { con_name <- lookupLocatedOccRn con_rdr
; (r, fvs) <- k con_name
; return (r, addOneFV fvs (unLoc con_name)) })
-- We add the constructor name to the free vars
-- See Note [Patterns are uses]
{-
Note [Patterns are uses]
~~~~~~~~~~~~~~~~~~~~~~~~
Consider
module Foo( f, g ) where
data T = T1 | T2
f T1 = True
f T2 = False
g _ = T1
Arguably we should report T2 as unused, even though it appears in a
pattern, because it never occurs in a constructed position. See
#7336.
However, implementing this in the face of pattern synonyms would be
less straightforward, since given two pattern synonyms
pattern P1 <- P2
pattern P2 <- ()
we need to observe the dependency between P1 and P2 so that type
checking can be done in the correct order (just like for value
bindings). Dependencies between bindings is analyzed in the renamer,
where we don't know yet whether P2 is a constructor or a pattern
synonym. So for now, we do report conid occurrences in patterns as
uses.
*********************************************************
* *
Name makers
* *
*********************************************************
Externally abstract type of name makers,
which is how you go from a RdrName to a Name
-}
data NameMaker
= LamMk -- Lambdas
Bool -- True <=> report unused bindings
-- (even if True, the warning only comes out
-- if -Wunused-matches is on)
| LetMk -- Let bindings, incl top level
-- Do *not* check for unused bindings
TopLevelFlag
MiniFixityEnv
topRecNameMaker :: MiniFixityEnv -> NameMaker
topRecNameMaker fix_env = LetMk TopLevel fix_env
isTopRecNameMaker :: NameMaker -> Bool
isTopRecNameMaker (LetMk TopLevel _) = True
isTopRecNameMaker _ = False
localRecNameMaker :: MiniFixityEnv -> NameMaker
localRecNameMaker fix_env = LetMk NotTopLevel fix_env
matchNameMaker :: HsMatchContext a -> NameMaker
matchNameMaker ctxt = LamMk report_unused
where
-- Do not report unused names in interactive contexts
-- i.e. when you type 'x <- e' at the GHCi prompt
report_unused = case ctxt of
StmtCtxt GhciStmtCtxt -> False
-- also, don't warn in pattern quotes, as there
-- is no RHS where the variables can be used!
ThPatQuote -> False
_ -> True
rnHsSigCps :: LHsSigWcType GhcPs -> CpsRn (LHsSigWcType GhcRn)
rnHsSigCps sig = CpsRn (rnHsSigWcTypeScoped AlwaysBind PatCtx sig)
newPatLName :: NameMaker -> Located RdrName -> CpsRn (Located Name)
newPatLName name_maker rdr_name@(L loc _)
= do { name <- newPatName name_maker rdr_name
; return (L loc name) }
newPatName :: NameMaker -> Located RdrName -> CpsRn Name
newPatName (LamMk report_unused) rdr_name
= CpsRn (\ thing_inside ->
do { name <- newLocalBndrRn rdr_name
; (res, fvs) <- bindLocalNames [name] (thing_inside name)
; when report_unused $ warnUnusedMatches [name] fvs
; return (res, name `delFV` fvs) })
newPatName (LetMk is_top fix_env) rdr_name
= CpsRn (\ thing_inside ->
do { name <- case is_top of
NotTopLevel -> newLocalBndrRn rdr_name
TopLevel -> newTopSrcBinder rdr_name
; bindLocalNames [name] $ -- Do *not* use bindLocalNameFV here
-- See Note [View pattern usage]
addLocalFixities fix_env [name] $
thing_inside name })
-- Note: the bindLocalNames is somewhat suspicious
-- because it binds a top-level name as a local name.
-- however, this binding seems to work, and it only exists for
-- the duration of the patterns and the continuation;
-- then the top-level name is added to the global env
-- before going on to the RHSes (see GHC.Rename.Source).
{-
Note [View pattern usage]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
let (r, (r -> x)) = x in ...
Here the pattern binds 'r', and then uses it *only* in the view pattern.
We want to "see" this use, and in let-bindings we collect all uses and
report unused variables at the binding level. So we must use bindLocalNames
here, *not* bindLocalNameFV. #3943.
Note [Don't report shadowing for pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is one special context where a pattern doesn't introduce any new binders -
pattern synonym declarations. Therefore we don't check to see if pattern
variables shadow existing identifiers as they are never bound to anything
and have no scope.
Without this check, there would be quite a cryptic warning that the `x`
in the RHS of the pattern synonym declaration shadowed the top level `x`.
```
x :: ()
x = ()
pattern P x = Just x
```
See #12615 for some more examples.
*********************************************************
* *
External entry points
* *
*********************************************************
There are various entry points to renaming patterns, depending on
(1) whether the names created should be top-level names or local names
(2) whether the scope of the names is entirely given in a continuation
(e.g., in a case or lambda, but not in a let or at the top-level,
because of the way mutually recursive bindings are handled)
(3) whether the a type signature in the pattern can bind
lexically-scoped type variables (for unpacking existential
type vars in data constructors)
(4) whether we do duplicate and unused variable checking
(5) whether there are fixity declarations associated with the names
bound by the patterns that need to be brought into scope with them.
Rather than burdening the clients of this module with all of these choices,
we export the three points in this design space that we actually need:
-}
-- ----------- Entry point 1: rnPats -------------------
-- Binds local names; the scope of the bindings is entirely in the thing_inside
-- * allows type sigs to bind type vars
-- * local namemaker
-- * unused and duplicate checking
-- * no fixities
rnPats :: HsMatchContext Name -- for error messages
-> [LPat GhcPs]
-> ([LPat GhcRn] -> RnM (a, FreeVars))
-> RnM (a, FreeVars)
rnPats ctxt pats thing_inside
= do { envs_before <- getRdrEnvs
-- (1) rename the patterns, bringing into scope all of the term variables
-- (2) then do the thing inside.
; unCpsRn (rnLPatsAndThen (matchNameMaker ctxt) pats) $ \ pats' -> do
{ -- Check for duplicated and shadowed names
-- Must do this *after* renaming the patterns
-- See Note [Collect binders only after renaming] in GHC.Hs.Utils
-- Because we don't bind the vars all at once, we can't
-- check incrementally for duplicates;
-- Nor can we check incrementally for shadowing, else we'll
-- complain *twice* about duplicates e.g. f (x,x) = ...
--
-- See note [Don't report shadowing for pattern synonyms]
; let bndrs = collectPatsBinders pats'
; addErrCtxt doc_pat $
if isPatSynCtxt ctxt
then checkDupNames bndrs
else checkDupAndShadowedNames envs_before bndrs
; thing_inside pats' } }
where
doc_pat = text "In" <+> pprMatchContext ctxt
rnPat :: HsMatchContext Name -- for error messages
-> LPat GhcPs
-> (LPat GhcRn -> RnM (a, FreeVars))
-> RnM (a, FreeVars) -- Variables bound by pattern do not
-- appear in the result FreeVars
rnPat ctxt pat thing_inside
= rnPats ctxt [pat] (\pats' -> let [pat'] = pats' in thing_inside pat')
applyNameMaker :: NameMaker -> Located RdrName -> RnM (Located Name)
applyNameMaker mk rdr = do { (n, _fvs) <- runCps (newPatLName mk rdr)
; return n }
-- ----------- Entry point 2: rnBindPat -------------------
-- Binds local names; in a recursive scope that involves other bound vars
-- e.g let { (x, Just y) = e1; ... } in ...
-- * does NOT allows type sig to bind type vars
-- * local namemaker
-- * no unused and duplicate checking
-- * fixities might be coming in
rnBindPat :: NameMaker
-> LPat GhcPs
-> RnM (LPat GhcRn, FreeVars)
-- Returned FreeVars are the free variables of the pattern,
-- of course excluding variables bound by this pattern
rnBindPat name_maker pat = runCps (rnLPatAndThen name_maker pat)
{-
*********************************************************
* *
The main event
* *
*********************************************************
-}
-- ----------- Entry point 3: rnLPatAndThen -------------------
-- General version: parametrized by how you make new names
rnLPatsAndThen :: NameMaker -> [LPat GhcPs] -> CpsRn [LPat GhcRn]
rnLPatsAndThen mk = mapM (rnLPatAndThen mk)
-- Despite the map, the monad ensures that each pattern binds
-- variables that may be mentioned in subsequent patterns in the list
--------------------
-- The workhorse
rnLPatAndThen :: NameMaker -> LPat GhcPs -> CpsRn (LPat GhcRn)
rnLPatAndThen nm lpat = wrapSrcSpanCps (rnPatAndThen nm) lpat
rnPatAndThen :: NameMaker -> Pat GhcPs -> CpsRn (Pat GhcRn)
rnPatAndThen _ (WildPat _) = return (WildPat noExtField)
rnPatAndThen mk (ParPat x pat) = do { pat' <- rnLPatAndThen mk pat
; return (ParPat x pat') }
rnPatAndThen mk (LazyPat x pat) = do { pat' <- rnLPatAndThen mk pat
; return (LazyPat x pat') }
rnPatAndThen mk (BangPat x pat) = do { pat' <- rnLPatAndThen mk pat
; return (BangPat x pat') }
rnPatAndThen mk (VarPat x (L l rdr))
= do { loc <- liftCps getSrcSpanM
; name <- newPatName mk (L loc rdr)
; return (VarPat x (L l name)) }
-- we need to bind pattern variables for view pattern expressions
-- (e.g. in the pattern (x, x -> y) x needs to be bound in the rhs of the tuple)
rnPatAndThen mk (SigPat x pat sig)
-- When renaming a pattern type signature (e.g. f (a :: T) = ...), it is
-- important to rename its type signature _before_ renaming the rest of the
-- pattern, so that type variables are first bound by the _outermost_ pattern
-- type signature they occur in. This keeps the type checker happy when
-- pattern type signatures happen to be nested (#7827)
--
-- f ((Just (x :: a) :: Maybe a)
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~^ `a' is first bound here
-- ~~~~~~~~~~~~~~~^ the same `a' then used here
= do { sig' <- rnHsSigCps sig
; pat' <- rnLPatAndThen mk pat
; return (SigPat x pat' sig' ) }
rnPatAndThen mk (LitPat x lit)
| HsString src s <- lit
= do { ovlStr <- liftCps (xoptM LangExt.OverloadedStrings)
; if ovlStr
then rnPatAndThen mk
(mkNPat (noLoc (mkHsIsString src s))
Nothing)
else normal_lit }
| otherwise = normal_lit
where
normal_lit = do { liftCps (rnLit lit); return (LitPat x (convertLit lit)) }
rnPatAndThen _ (NPat x (L l lit) mb_neg _eq)
= do { (lit', mb_neg') <- liftCpsFV $ rnOverLit lit
; mb_neg' -- See Note [Negative zero]
<- let negative = do { (neg, fvs) <- lookupSyntaxName negateName
; return (Just neg, fvs) }
positive = return (Nothing, emptyFVs)
in liftCpsFV $ case (mb_neg , mb_neg') of
(Nothing, Just _ ) -> negative
(Just _ , Nothing) -> negative
(Nothing, Nothing) -> positive
(Just _ , Just _ ) -> positive
; eq' <- liftCpsFV $ lookupSyntaxName eqName
; return (NPat x (L l lit') mb_neg' eq') }
rnPatAndThen mk (NPlusKPat x rdr (L l lit) _ _ _ )
= do { new_name <- newPatName mk rdr
; (lit', _) <- liftCpsFV $ rnOverLit lit -- See Note [Negative zero]
-- We skip negateName as
-- negative zero doesn't make
-- sense in n + k patterns
; minus <- liftCpsFV $ lookupSyntaxName minusName
; ge <- liftCpsFV $ lookupSyntaxName geName
; return (NPlusKPat x (L (nameSrcSpan new_name) new_name)
(L l lit') lit' ge minus) }
-- The Report says that n+k patterns must be in Integral
rnPatAndThen mk (AsPat x rdr pat)
= do { new_name <- newPatLName mk rdr
; pat' <- rnLPatAndThen mk pat
; return (AsPat x new_name pat') }
rnPatAndThen mk p@(ViewPat x expr pat)
= do { liftCps $ do { vp_flag <- xoptM LangExt.ViewPatterns
; checkErr vp_flag (badViewPat p) }
-- Because of the way we're arranging the recursive calls,
-- this will be in the right context
; expr' <- liftCpsFV $ rnLExpr expr
; pat' <- rnLPatAndThen mk pat
-- Note: at this point the PreTcType in ty can only be a placeHolder
-- ; return (ViewPat expr' pat' ty) }
; return (ViewPat x expr' pat') }
rnPatAndThen mk (ConPatIn con stuff)
-- rnConPatAndThen takes care of reconstructing the pattern
-- The pattern for the empty list needs to be replaced by an empty explicit list pattern when overloaded lists is turned on.
= case unLoc con == nameRdrName (dataConName nilDataCon) of
True -> do { ol_flag <- liftCps $ xoptM LangExt.OverloadedLists
; if ol_flag then rnPatAndThen mk (ListPat noExtField [])
else rnConPatAndThen mk con stuff}
False -> rnConPatAndThen mk con stuff
rnPatAndThen mk (ListPat _ pats)
= do { opt_OverloadedLists <- liftCps $ xoptM LangExt.OverloadedLists
; pats' <- rnLPatsAndThen mk pats
; case opt_OverloadedLists of
True -> do { (to_list_name,_) <- liftCps $ lookupSyntaxName toListName
; return (ListPat (Just to_list_name) pats')}
False -> return (ListPat Nothing pats') }
rnPatAndThen mk (TuplePat x pats boxed)
= do { liftCps $ checkTupSize (length pats)
; pats' <- rnLPatsAndThen mk pats
; return (TuplePat x pats' boxed) }
rnPatAndThen mk (SumPat x pat alt arity)
= do { pat <- rnLPatAndThen mk pat
; return (SumPat x pat alt arity)
}
-- If a splice has been run already, just rename the result.
rnPatAndThen mk (SplicePat x (HsSpliced x2 mfs (HsSplicedPat pat)))
= SplicePat x . HsSpliced x2 mfs . HsSplicedPat <$> rnPatAndThen mk pat
rnPatAndThen mk (SplicePat _ splice)
= do { eith <- liftCpsFV $ rnSplicePat splice
; case eith of -- See Note [rnSplicePat] in GHC.Rename.Splice
Left not_yet_renamed -> rnPatAndThen mk not_yet_renamed
Right already_renamed -> return already_renamed }
rnPatAndThen _ pat = pprPanic "rnLPatAndThen" (ppr pat)
--------------------
rnConPatAndThen :: NameMaker
-> Located RdrName -- the constructor
-> HsConPatDetails GhcPs
-> CpsRn (Pat GhcRn)
rnConPatAndThen mk con (PrefixCon pats)
= do { con' <- lookupConCps con
; pats' <- rnLPatsAndThen mk pats
; return (ConPatIn con' (PrefixCon pats')) }
rnConPatAndThen mk con (InfixCon pat1 pat2)
= do { con' <- lookupConCps con
; pat1' <- rnLPatAndThen mk pat1
; pat2' <- rnLPatAndThen mk pat2
; fixity <- liftCps $ lookupFixityRn (unLoc con')
; liftCps $ mkConOpPatRn con' fixity pat1' pat2' }
rnConPatAndThen mk con (RecCon rpats)
= do { con' <- lookupConCps con
; rpats' <- rnHsRecPatsAndThen mk con' rpats
; return (ConPatIn con' (RecCon rpats')) }
checkUnusedRecordWildcardCps :: SrcSpan -> Maybe [Name] -> CpsRn ()
checkUnusedRecordWildcardCps loc dotdot_names =
CpsRn (\thing -> do
(r, fvs) <- thing ()
checkUnusedRecordWildcard loc fvs dotdot_names
return (r, fvs) )
--------------------
rnHsRecPatsAndThen :: NameMaker
-> Located Name -- Constructor
-> HsRecFields GhcPs (LPat GhcPs)
-> CpsRn (HsRecFields GhcRn (LPat GhcRn))
rnHsRecPatsAndThen mk (L _ con)
hs_rec_fields@(HsRecFields { rec_dotdot = dd })
= do { flds <- liftCpsFV $ rnHsRecFields (HsRecFieldPat con) mkVarPat
hs_rec_fields
; flds' <- mapM rn_field (flds `zip` [1..])
; check_unused_wildcard (implicit_binders flds' <$> dd)
; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }) }
where
mkVarPat l n = VarPat noExtField (L l n)
rn_field (L l fld, n') =
do { arg' <- rnLPatAndThen (nested_mk dd mk n') (hsRecFieldArg fld)
; return (L l (fld { hsRecFieldArg = arg' })) }
loc = maybe noSrcSpan getLoc dd
-- Get the arguments of the implicit binders
implicit_binders fs (unLoc -> n) = collectPatsBinders implicit_pats
where
implicit_pats = map (hsRecFieldArg . unLoc) (drop n fs)
-- Don't warn for let P{..} = ... in ...
check_unused_wildcard = case mk of
LetMk{} -> const (return ())
LamMk{} -> checkUnusedRecordWildcardCps loc
-- Suppress unused-match reporting for fields introduced by ".."
nested_mk Nothing mk _ = mk
nested_mk (Just _) mk@(LetMk {}) _ = mk
nested_mk (Just (unLoc -> n)) (LamMk report_unused) n'
= LamMk (report_unused && (n' <= n))
{-
************************************************************************
* *
Record fields
* *
************************************************************************
-}
data HsRecFieldContext
= HsRecFieldCon Name
| HsRecFieldPat Name
| HsRecFieldUpd
rnHsRecFields
:: forall arg.
HsRecFieldContext
-> (SrcSpan -> RdrName -> arg)
-- When punning, use this to build a new field
-> HsRecFields GhcPs (Located arg)
-> RnM ([LHsRecField GhcRn (Located arg)], FreeVars)
-- This surprisingly complicated pass
-- a) looks up the field name (possibly using disambiguation)
-- b) fills in puns and dot-dot stuff
-- When we've finished, we've renamed the LHS, but not the RHS,
-- of each x=e binding
--
-- This is used for record construction and pattern-matching, but not updates.
rnHsRecFields ctxt mk_arg (HsRecFields { rec_flds = flds, rec_dotdot = dotdot })
= do { pun_ok <- xoptM LangExt.RecordPuns
; disambig_ok <- xoptM LangExt.DisambiguateRecordFields
; let parent = guard disambig_ok >> mb_con
; flds1 <- mapM (rn_fld pun_ok parent) flds
; mapM_ (addErr . dupFieldErr ctxt) dup_flds
; dotdot_flds <- rn_dotdot dotdot mb_con flds1
; let all_flds | null dotdot_flds = flds1
| otherwise = flds1 ++ dotdot_flds
; return (all_flds, mkFVs (getFieldIds all_flds)) }
where
mb_con = case ctxt of
HsRecFieldCon con -> Just con
HsRecFieldPat con -> Just con
_ {- update -} -> Nothing
rn_fld :: Bool -> Maybe Name -> LHsRecField GhcPs (Located arg)
-> RnM (LHsRecField GhcRn (Located arg))
rn_fld pun_ok parent (L l
(HsRecField
{ hsRecFieldLbl =
(L loc (FieldOcc _ (L ll lbl)))
, hsRecFieldArg = arg
, hsRecPun = pun }))
= do { sel <- setSrcSpan loc $ lookupRecFieldOcc parent lbl
; arg' <- if pun
then do { checkErr pun_ok (badPun (L loc lbl))
-- Discard any module qualifier (#11662)
; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl)
; return (L loc (mk_arg loc arg_rdr)) }
else return arg
; return (L l (HsRecField
{ hsRecFieldLbl = (L loc (FieldOcc
sel (L ll lbl)))
, hsRecFieldArg = arg'
, hsRecPun = pun })) }
rn_fld _ _ (L _ (HsRecField (L _ (XFieldOcc _)) _ _))
= panic "rnHsRecFields"
rn_dotdot :: Maybe (Located Int) -- See Note [DotDot fields] in GHC.Hs.Pat
-> Maybe Name -- The constructor (Nothing for an
-- out of scope constructor)
-> [LHsRecField GhcRn (Located arg)] -- Explicit fields
-> RnM ([LHsRecField GhcRn (Located arg)]) -- Field Labels we need to fill in
rn_dotdot (Just (L loc n)) (Just con) flds -- ".." on record construction / pat match
| not (isUnboundName con) -- This test is because if the constructor
-- isn't in scope the constructor lookup will add
-- an error but still return an unbound name. We
-- don't want that to screw up the dot-dot fill-in stuff.
= ASSERT( flds `lengthIs` n )
do { dd_flag <- xoptM LangExt.RecordWildCards
; checkErr dd_flag (needFlagDotDot ctxt)
; (rdr_env, lcl_env) <- getRdrEnvs
; con_fields <- lookupConstructorFields con
; when (null con_fields) (addErr (badDotDotCon con))
; let present_flds = mkOccSet $ map rdrNameOcc (getFieldLbls flds)
-- For constructor uses (but not patterns)
-- the arg should be in scope locally;
-- i.e. not top level or imported
-- Eg. data R = R { x,y :: Int }
-- f x = R { .. } -- Should expand to R {x=x}, not R{x=x,y=y}
arg_in_scope lbl = mkRdrUnqual lbl `elemLocalRdrEnv` lcl_env
(dot_dot_fields, dot_dot_gres)
= unzip [ (fl, gre)
| fl <- con_fields
, let lbl = mkVarOccFS (flLabel fl)
, not (lbl `elemOccSet` present_flds)
, Just gre <- [lookupGRE_FieldLabel rdr_env fl]
-- Check selector is in scope
, case ctxt of
HsRecFieldCon {} -> arg_in_scope lbl
_other -> True ]
; addUsedGREs dot_dot_gres
; return [ L loc (HsRecField
{ hsRecFieldLbl = L loc (FieldOcc sel (L loc arg_rdr))
, hsRecFieldArg = L loc (mk_arg loc arg_rdr)
, hsRecPun = False })
| fl <- dot_dot_fields
, let sel = flSelector fl
, let arg_rdr = mkVarUnqual (flLabel fl) ] }
rn_dotdot _dotdot _mb_con _flds
= return []
-- _dotdot = Nothing => No ".." at all
-- _mb_con = Nothing => Record update
-- _mb_con = Just unbound => Out of scope data constructor
dup_flds :: [NE.NonEmpty RdrName]
-- Each list represents a RdrName that occurred more than once
-- (the list contains all occurrences)
-- Each list in dup_fields is non-empty
(_, dup_flds) = removeDups compare (getFieldLbls flds)
-- NB: Consider this:
-- module Foo where { data R = R { fld :: Int } }
-- module Odd where { import Foo; fld x = x { fld = 3 } }
-- Arguably this should work, because the reference to 'fld' is
-- unambiguous because there is only one field id 'fld' in scope.
-- But currently it's rejected.
rnHsRecUpdFields
:: [LHsRecUpdField GhcPs]
-> RnM ([LHsRecUpdField GhcRn], FreeVars)
rnHsRecUpdFields flds
= do { pun_ok <- xoptM LangExt.RecordPuns
; overload_ok <- xoptM LangExt.DuplicateRecordFields
; (flds1, fvss) <- mapAndUnzipM (rn_fld pun_ok overload_ok) flds
; mapM_ (addErr . dupFieldErr HsRecFieldUpd) dup_flds
-- Check for an empty record update e {}
-- NB: don't complain about e { .. }, because rn_dotdot has done that already
; when (null flds) $ addErr emptyUpdateErr
; return (flds1, plusFVs fvss) }
where
doc = text "constructor field name"
rn_fld :: Bool -> Bool -> LHsRecUpdField GhcPs
-> RnM (LHsRecUpdField GhcRn, FreeVars)
rn_fld pun_ok overload_ok (L l (HsRecField { hsRecFieldLbl = L loc f
, hsRecFieldArg = arg
, hsRecPun = pun }))
= do { let lbl = rdrNameAmbiguousFieldOcc f
; sel <- setSrcSpan loc $
-- Defer renaming of overloaded fields to the typechecker
-- See Note [Disambiguating record fields] in TcExpr
if overload_ok
then do { mb <- lookupGlobalOccRn_overloaded
overload_ok lbl
; case mb of
Nothing ->
do { addErr
(unknownSubordinateErr doc lbl)
; return (Right []) }
Just r -> return r }
else fmap Left $ lookupGlobalOccRn lbl
; arg' <- if pun
then do { checkErr pun_ok (badPun (L loc lbl))
-- Discard any module qualifier (#11662)
; let arg_rdr = mkRdrUnqual (rdrNameOcc lbl)
; return (L loc (HsVar noExtField (L loc arg_rdr))) }
else return arg
; (arg'', fvs) <- rnLExpr arg'
; let fvs' = case sel of
Left sel_name -> fvs `addOneFV` sel_name
Right [sel_name] -> fvs `addOneFV` sel_name
Right _ -> fvs
lbl' = case sel of
Left sel_name ->
L loc (Unambiguous sel_name (L loc lbl))
Right [sel_name] ->
L loc (Unambiguous sel_name (L loc lbl))
Right _ -> L loc (Ambiguous noExtField (L loc lbl))
; return (L l (HsRecField { hsRecFieldLbl = lbl'
, hsRecFieldArg = arg''
, hsRecPun = pun }), fvs') }
dup_flds :: [NE.NonEmpty RdrName]
-- Each list represents a RdrName that occurred more than once
-- (the list contains all occurrences)
-- Each list in dup_fields is non-empty
(_, dup_flds) = removeDups compare (getFieldUpdLbls flds)
getFieldIds :: [LHsRecField GhcRn arg] -> [Name]
getFieldIds flds = map (unLoc . hsRecFieldSel . unLoc) flds
getFieldLbls :: [LHsRecField id arg] -> [RdrName]
getFieldLbls flds
= map (unLoc . rdrNameFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds
getFieldUpdLbls :: [LHsRecUpdField GhcPs] -> [RdrName]
getFieldUpdLbls flds = map (rdrNameAmbiguousFieldOcc . unLoc . hsRecFieldLbl . unLoc) flds
needFlagDotDot :: HsRecFieldContext -> SDoc
needFlagDotDot ctxt = vcat [text "Illegal `..' in record" <+> pprRFC ctxt,
text "Use RecordWildCards to permit this"]
badDotDotCon :: Name -> SDoc
badDotDotCon con
= vcat [ text "Illegal `..' notation for constructor" <+> quotes (ppr con)
, nest 2 (text "The constructor has no labelled fields") ]
emptyUpdateErr :: SDoc
emptyUpdateErr = text "Empty record update"
badPun :: Located RdrName -> SDoc
badPun fld = vcat [text "Illegal use of punning for field" <+> quotes (ppr fld),
text "Use NamedFieldPuns to permit this"]
dupFieldErr :: HsRecFieldContext -> NE.NonEmpty RdrName -> SDoc
dupFieldErr ctxt dups
= hsep [text "duplicate field name",
quotes (ppr (NE.head dups)),
text "in record", pprRFC ctxt]
pprRFC :: HsRecFieldContext -> SDoc
pprRFC (HsRecFieldCon {}) = text "construction"
pprRFC (HsRecFieldPat {}) = text "pattern"
pprRFC (HsRecFieldUpd {}) = text "update"
{-
************************************************************************
* *
\subsubsection{Literals}
* *
************************************************************************
When literals occur we have to make sure
that the types and classes they involve
are made available.
-}
rnLit :: HsLit p -> RnM ()
rnLit (HsChar _ c) = checkErr (inCharRange c) (bogusCharError c)
rnLit _ = return ()
-- Turn a Fractional-looking literal which happens to be an integer into an
-- Integer-looking literal.
generalizeOverLitVal :: OverLitVal -> OverLitVal
generalizeOverLitVal (HsFractional (FL {fl_text=src,fl_neg=neg,fl_value=val}))
| denominator val == 1 = HsIntegral (IL { il_text=src
, il_neg=neg
, il_value=numerator val})
generalizeOverLitVal lit = lit
isNegativeZeroOverLit :: HsOverLit t -> Bool
isNegativeZeroOverLit lit
= case ol_val lit of
HsIntegral i -> 0 == il_value i && il_neg i
HsFractional f -> 0 == fl_value f && fl_neg f
_ -> False
{-
Note [Negative zero]
~~~~~~~~~~~~~~~~~~~~~~~~~
There were problems with negative zero in conjunction with Negative Literals
extension. Numeric literal value is contained in Integer and Rational types
inside IntegralLit and FractionalLit. These types cannot represent negative
zero value. So we had to add explicit field 'neg' which would hold information
about literal sign. Here in rnOverLit we use it to detect negative zeroes and
in this case return not only literal itself but also negateName so that users
can apply it explicitly. In this case it stays negative zero. #13211
-}
rnOverLit :: HsOverLit t ->
RnM ((HsOverLit GhcRn, Maybe (HsExpr GhcRn)), FreeVars)
rnOverLit origLit
= do { opt_NumDecimals <- xoptM LangExt.NumDecimals
; let { lit@(OverLit {ol_val=val})
| opt_NumDecimals = origLit {ol_val = generalizeOverLitVal (ol_val origLit)}
| otherwise = origLit
}
; let std_name = hsOverLitName val
; (SyntaxExpr { syn_expr = from_thing_name }, fvs1)
<- lookupSyntaxName std_name
; let rebindable = case from_thing_name of
HsVar _ lv -> (unLoc lv) /= std_name
_ -> panic "rnOverLit"
; let lit' = lit { ol_witness = from_thing_name
, ol_ext = rebindable }
; if isNegativeZeroOverLit lit'
then do { (SyntaxExpr { syn_expr = negate_name }, fvs2)
<- lookupSyntaxName negateName
; return ((lit' { ol_val = negateOverLitVal val }, Just negate_name)
, fvs1 `plusFV` fvs2) }
else return ((lit', Nothing), fvs1) }
{-
************************************************************************
* *
\subsubsection{Errors}
* *
************************************************************************
-}
patSigErr :: Outputable a => a -> SDoc
patSigErr ty
= (text "Illegal signature in pattern:" <+> ppr ty)
$$ nest 4 (text "Use ScopedTypeVariables to permit it")
bogusCharError :: Char -> SDoc
bogusCharError c
= text "character literal out of range: '\\" <> char c <> char '\''
badViewPat :: Pat GhcPs -> SDoc
badViewPat pat = vcat [text "Illegal view pattern: " <+> ppr pat,
text "Use ViewPatterns to enable view patterns"]
|
sdiehl/ghc
|
compiler/GHC/Rename/Pat.hs
|
bsd-3-clause
| 37,146
| 10
| 24
| 12,281
| 7,230
| 3,757
| 3,473
| -1
| -1
|
module Main where
import Control.Monad (void)
import Test.HUnit ((~?=), runTestTT, Test(TestList))
import Jdex.Parse
main :: IO ()
main = void . runTestTT $ TestList
[ jdFileToFQCN "org/graphstream/ui/swingViewer/LayerRenderer.html" ~?= "org.graphstream.ui.swingViewer.LayerRenderer"
, jdFileToFQCN "com/google/gwt/user/datepicker/client/CellGridImpl.Cell.html" ~?= "com.google.gwt.user.datepicker.client.CellGridImpl.Cell"
, jdFileToSCN "org/graphstream/ui/swingViewer/LayerRenderer.html" ~?= "LayerRenderer"
, jdFileToSCN "com/google/gwt/user/datepicker/client/CellGridImpl.Cell.html" ~?= "CellGridImpl.Cell"
, fqcnToJdFile "java.lang.String" ~?= "java/lang/String.html"
, fqcnToJdFile "com.google.gwt.user.datepicker.client.CellGridImpl.Cell" ~?= "com/google/gwt/user/datepicker/client/CellGridImpl.Cell.html"
, fqcnToJdFile "org.graphstream.ui.swingViewer.LayerRenderer" ~?= "org/graphstream/ui/swingViewer/LayerRenderer.html"
]
|
jhrcek/jdex
|
test/Tests.hs
|
bsd-3-clause
| 971
| 0
| 9
| 98
| 137
| 75
| 62
| 13
| 1
|
module Guesswork.Math.Statistics where
import qualified Data.Vector.Unboxed as VU
import Guesswork.Types
kh xs = sqrt . (/n) . sum . map (\x->(x-avg')**2) $ xs
where avg' = avg xs
n = fromIntegral . length $ xs
avg [] = error "Empty list!"
avg xs = sum xs / (fromIntegral . length $ xs)
euclidianNorm :: FeatureVector -> FeatureVector -> Double
euclidianNorm u v = VU.sum $ VU.zipWith (\a b -> (a - b)**2) u v
-- |Scales lists (truths, predictions) between [0,1] using
-- scales from truths.
-- NOTE: this means that all predictions aren't necessarily
-- between [0,1].
scaleLists truths preds =
let minT = minimum truths
maxT = maximum truths
scale = map ((/ maxT) . subtract minT)
in (scale truths, scale preds)
-- |Calculate population variance.
popVariance :: [Double] -> Double
popVariance xs =
let n = fromIntegral . length $ xs
ax = avg xs
in (*(1/n)) . sum . map ((**2) . subtract ax) $ xs
-- |Pearson's sample correlation. Correlation is in range
-- [-1,1] and is 1.0 if lists are identical.
-- List aren't checked to be of same length.
sampleCorrelation :: [Double] -> [Double] -> Double
sampleCorrelation xs ys
| length xs < 2 || length ys < 2 = error "Correlation: too short lists."
| otherwise = if xs == ys then 1.0 else corr
where
avgX = avg xs
avgY = avg ys
nxs = map (subtract avgX) xs
nys = map (subtract avgY) ys
upper = sum $ zipWith (*) nxs nys
lowerX = sum $ map (**2) nxs
lowerY = sum $ map (**2) nys
lower = sqrt $ lowerX * lowerY
corr = upper / lower
-- |Calculate root mean square error from given list of
-- truths and predictions.
rmse :: [Double] -> [Double] -> Double
rmse truths preds =
let errors = sum . map (**2) $ zipWith (-) truths preds
n = fromIntegral . length $ truths
in sqrt $ errors / n
|
deggis/guesswork
|
src/Guesswork/Math/Statistics.hs
|
bsd-3-clause
| 1,892
| 0
| 12
| 490
| 643
| 343
| 300
| 38
| 2
|
----------------------
-- CONSTELM --
----------------------
module Constelm where
import Auxiliary
import LPPE
import Simplify
import Data.List
import Usage
import DataSpec
-- This function takes a specification, detects which parameters are constant,
-- substitutes the initial values for these parameters wherever they are used,
-- and finally removes the parameters from the LPPE.
constelm :: PSpecification -> PSpecification
constelm (lppe, initial, dataspec) = removeParametersFromLPPE (lppeReduced, initial, dataspec) (map fst constants)
where
parNames = map fst (getLPPEPars lppe)
parTypes = map snd (getLPPEPars lppe)
allVariables = [(p,parNames!!p,i) | (p, i) <- (zip [0..length initial - 1] initial)]
singletons = [(p,parNames!!p,i) | (p, i) <- (zip [0..length initial - 1] initial), length (getValues dataspec (parTypes!!p)) == 1, (getValues dataspec (parTypes!!p)) /= ["empty"], parTypes!!p /= TypeName "Nat"]
constants = [(p,i) | (p,s,i) <- (allVariables \\ ((getNonConstants lppe allVariables) \\ singletons))]
lppeReduced = substituteInLPPE lppe constants
-- This function takes an LPPE, a list of all parameters of that LPPE in the form (parNr, parName, initValue)
-- and the initial state. It provides a list of parameters of the same form, indicating that
-- those are changed.
getNonConstants :: LPPE -> [(Int, String, String)] -> [(Int, String, String)]
getNonConstants lppe stillConstant | nonConstants == [] = []
| otherwise = nonConstants ++ getNonConstants lppe (stillConstant \\ nonConstants)
where
nonConstants = getNonConstants2 lppe stillConstant stillConstant
-- Given an LPPE, a list of parameters (parNr, parName, initValue) that have not been detected to have been changed yet,
-- an a list of all parameters, this function provides a new list of parameters that are not constant.
getNonConstants2 :: LPPE -> [(Int, String, String)] -> [(Int, String, String)] -> [(Int, String, String)]
getNonConstants2 lppe stillConstant [] = []
getNonConstants2 lppe stillConstant ((parNr, name, initialValue):pairs) | isNotConstant = (parNr, name, initialValue):(getNonConstants2 lppe stillConstant pairs)
| otherwise = getNonConstants2 lppe stillConstant pairs
where
isNotConstant = or [isNotConstantInSummand lppe stillConstant initialValue summandNr parNr | summandNr <- getPSummandNrs lppe]
-- The function computes whether a parameter isn't constant. This is the case when it is changed, and moreover
-- its next value is not equal to its initial value. Finally, it is also still considered constant when it is
-- to obtain the value of another parameter, that is still considered constant, and has the same initial value
isNotConstantInSummand :: LPPE -> [(Int, String, String)] -> String -> Int -> Int -> Bool
isNotConstantInSummand lppe stillConstant initialValue summandNr parNr = changed && nextState /= Variable initialValue && not(changedToSameConstant) && enabled
where
changed = isChangedInSummand lppe summandNr parNr
nextState = simplifyExpression ([],[],[]) (getNextState summand parNr)
enabled = simplifyExpression ([],[],[]) (getCondition summand) /= Variable "F"
summand = getPSummand lppe summandNr
probChoices = getProbChoices summand
params = getLocalPars summand
changedToSameConstant = [ p | (p, s, i) <- stillConstant, nextState == Variable s, i == initialValue, not(elem s (map fst params)), not(elem s (map fst3 probChoices))] /= []
|
utwente-fmt/scoop
|
src/Constelm.hs
|
bsd-3-clause
| 3,676
| 0
| 15
| 768
| 922
| 503
| 419
| 33
| 1
|
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- | This module provides a file browser widget that allows users to
-- navigate directory trees, search for files and directories, and
-- select entries of interest. For a complete working demonstration of
-- this module, see @programs/FileBrowserDemo.hs@.
--
-- To use this module:
--
-- * Embed a 'FileBrowser' in your application state.
-- * Dispatch events to it in your event handler with
-- 'handleFileBrowserEvent'.
-- * Get the entry under the browser's cursor with 'fileBrowserCursor'
-- and get the entries selected by the user with 'Enter' or 'Space'
-- using 'fileBrowserSelection'.
-- * Inspect 'fileBrowserException' to determine whether the
-- file browser encountered an error when reading a directory in
-- 'setWorkingDirectory' or when changing directories in the event
-- handler.
--
-- File browsers have a built-in user-configurable function to limit the
-- entries displayed that defaults to showing all files. For example,
-- an application might want to limit the browser to just directories
-- and XML files. That is accomplished by setting the filter with
-- 'setFileBrowserEntryFilter' and some examples are provided in this
-- module: 'fileTypeMatch' and 'fileExtensionMatch'.
--
-- File browsers are styled using the provided collection of attribute
-- names, so add those to your attribute map to get the appearance you
-- want. File browsers also make use of a 'List' internally, so the
-- 'List' attributes will affect how the list appears.
--
-- File browsers catch 'IOException's when changing directories. If a
-- call to 'setWorkingDirectory' triggers an 'IOException' while reading
-- the working directory, the resulting 'IOException' is stored in the
-- file browser and is accessible with 'fileBrowserException'. The
-- 'setWorkingDirectory' function clears the exception field if the
-- working directory is read successfully. The caller is responsible for
-- deciding when and whether to display the exception to the user. In
-- the event that an 'IOException' is raised as described here, the file
-- browser will always present @..@ as a navigation option to allow the
-- user to continue navigating up the directory tree. It does this even
-- if the current or parent directory does not exist or cannot be read,
-- so it is always safe to present a file browser for any working
-- directory. Bear in mind that the @..@ entry is always subjected to
-- filtering and searching.
module Brick.Widgets.FileBrowser
( -- * Types
FileBrowser
, FileInfo(..)
, FileStatus(..)
, FileType(..)
-- * Making a new file browser
, newFileBrowser
, selectNonDirectories
, selectDirectories
-- * Manipulating a file browser's state
, setWorkingDirectory
, getWorkingDirectory
, updateFileBrowserSearch
, setFileBrowserEntryFilter
-- * Actions
, actionFileBrowserBeginSearch
, actionFileBrowserSelectEnter
, actionFileBrowserSelectCurrent
, actionFileBrowserListPageUp
, actionFileBrowserListPageDown
, actionFileBrowserListHalfPageUp
, actionFileBrowserListHalfPageDown
, actionFileBrowserListTop
, actionFileBrowserListBottom
, actionFileBrowserListNext
, actionFileBrowserListPrev
-- * Handling events
, handleFileBrowserEvent
, maybeSelectCurrentEntry
-- * Rendering
, renderFileBrowser
-- * Getting information
, fileBrowserCursor
, fileBrowserIsSearching
, fileBrowserSelection
, fileBrowserException
, fileBrowserSelectable
, fileInfoFileType
-- * Attributes
, fileBrowserAttr
, fileBrowserCurrentDirectoryAttr
, fileBrowserSelectionInfoAttr
, fileBrowserSelectedAttr
, fileBrowserDirectoryAttr
, fileBrowserBlockDeviceAttr
, fileBrowserRegularFileAttr
, fileBrowserCharacterDeviceAttr
, fileBrowserNamedPipeAttr
, fileBrowserSymbolicLinkAttr
, fileBrowserUnixSocketAttr
-- * Example browser entry filters
, fileTypeMatch
, fileExtensionMatch
-- * Lenses
, fileBrowserEntryFilterL
, fileBrowserSelectableL
, fileInfoFilenameL
, fileInfoSanitizedFilenameL
, fileInfoFilePathL
, fileInfoFileStatusL
, fileInfoLinkTargetTypeL
, fileStatusSizeL
, fileStatusFileTypeL
-- * Miscellaneous
, prettyFileSize
-- * Utilities
, entriesForDirectory
, getFileInfo
)
where
import qualified Control.Exception as E
import Control.Monad (forM)
import Control.Monad.IO.Class (liftIO)
import Data.Char (toLower, isPrint)
import Data.Maybe (fromMaybe, isJust, fromJust)
import qualified Data.Foldable as F
import qualified Data.Text as T
#if !(MIN_VERSION_base(4,11,0))
import Data.Monoid
#endif
import Data.Int (Int64)
import Data.List (sortBy, isSuffixOf)
import qualified Data.Set as Set
import qualified Data.Vector as V
import Lens.Micro
import qualified Graphics.Vty as Vty
import qualified System.Directory as D
import qualified System.Posix.Files as U
import qualified System.Posix.Types as U
import qualified System.FilePath as FP
import Text.Printf (printf)
import Brick.Types
import Brick.AttrMap (AttrName)
import Brick.Widgets.Core
import Brick.Widgets.List
-- | A file browser's state. Embed this in your application state and
-- transform it with 'handleFileBrowserEvent' and the functions included
-- in this module.
data FileBrowser n =
FileBrowser { fileBrowserWorkingDirectory :: FilePath
, fileBrowserEntries :: List n FileInfo
, fileBrowserLatestResults :: [FileInfo]
, fileBrowserSelectedFiles :: Set.Set String
, fileBrowserName :: n
, fileBrowserEntryFilter :: Maybe (FileInfo -> Bool)
, fileBrowserSearchString :: Maybe T.Text
, fileBrowserException :: Maybe E.IOException
-- ^ The exception status of the latest directory
-- change. If 'Nothing', the latest directory change
-- was successful and all entries were read. Otherwise,
-- this contains the exception raised by the latest
-- directory change in case the calling application
-- needs to inspect or present the error to the user.
, fileBrowserSelectable :: FileInfo -> Bool
-- ^ The function that determines what kinds of entries
-- are selectable with in the event handler. Note that
-- if this returns 'True' for an entry, an @Enter@ or
-- @Space@ keypress selects that entry rather than doing
-- anything else; directory changes can only occur if
-- this returns 'False' for directories.
--
-- Note that this is a record field so it can be used to
-- change the selection function.
}
-- | File status information.
data FileStatus =
FileStatus { fileStatusSize :: Int64
-- ^ The size, in bytes, of this entry's file.
, fileStatusFileType :: Maybe FileType
-- ^ The type of this entry's file, if it could be
-- determined.
}
deriving (Show, Eq)
-- | Information about a file entry in the browser.
data FileInfo =
FileInfo { fileInfoFilename :: String
-- ^ The filename of this entry, without its path.
-- This is not for display purposes; for that, use
-- 'fileInfoSanitizedFilename'.
, fileInfoSanitizedFilename :: String
-- ^ The filename of this entry with out its path,
-- sanitized of non-printable characters (replaced with
-- '?'). This is for display purposes only.
, fileInfoFilePath :: FilePath
-- ^ The full path to this entry's file.
, fileInfoFileStatus :: Either E.IOException FileStatus
-- ^ The file status if it could be obtained, or the
-- exception that was caught when attempting to read the
-- file's status.
, fileInfoLinkTargetType :: Maybe FileType
-- ^ If this entry is a symlink, this indicates the type of
-- file the symlink points to, if it could be obtained.
}
deriving (Show, Eq)
-- | The type of file entries in the browser.
data FileType =
RegularFile
-- ^ A regular disk file.
| BlockDevice
-- ^ A block device.
| CharacterDevice
-- ^ A character device.
| NamedPipe
-- ^ A named pipe.
| Directory
-- ^ A directory.
| SymbolicLink
-- ^ A symbolic link.
| UnixSocket
-- ^ A Unix socket.
deriving (Read, Show, Eq)
suffixLenses ''FileBrowser
suffixLenses ''FileInfo
suffixLenses ''FileStatus
-- | Make a new file browser state. The provided resource name will be
-- used to render the 'List' viewport of the browser.
--
-- By default, the browser will show all files and directories
-- in its working directory. To change that behavior, see
-- 'setFileBrowserEntryFilter'.
newFileBrowser :: (FileInfo -> Bool)
-- ^ The function used to determine what kinds of entries
-- can be selected (see 'handleFileBrowserEvent'). A
-- good default is 'selectNonDirectories'. This can be
-- changed at 'any time with 'fileBrowserSelectable' or
-- its 'corresponding lens.
-> n
-- ^ The resource name associated with the browser's
-- entry listing.
-> Maybe FilePath
-- ^ The initial working directory that the browser
-- displays. If not provided, this defaults to the
-- executable's current working directory.
-> IO (FileBrowser n)
newFileBrowser selPredicate name mCwd = do
initialCwd <- case mCwd of
Just path -> return path
Nothing -> D.getCurrentDirectory
let b = FileBrowser { fileBrowserWorkingDirectory = initialCwd
, fileBrowserEntries = list name mempty 1
, fileBrowserLatestResults = mempty
, fileBrowserSelectedFiles = mempty
, fileBrowserName = name
, fileBrowserEntryFilter = Nothing
, fileBrowserSearchString = Nothing
, fileBrowserException = Nothing
, fileBrowserSelectable = selPredicate
}
setWorkingDirectory initialCwd b
-- | A file entry selector that permits selection of all file entries
-- except directories. Use this if you want users to be able to navigate
-- directories in the browser. If you want users to be able to select
-- only directories, use 'selectDirectories'.
selectNonDirectories :: FileInfo -> Bool
selectNonDirectories i =
case fileInfoFileType i of
Just Directory -> False
Just SymbolicLink ->
case fileInfoLinkTargetType i of
Just Directory -> False
_ -> True
_ -> True
-- | A file entry selector that permits selection of directories
-- only. This prevents directory navigation and only supports directory
-- selection.
selectDirectories :: FileInfo -> Bool
selectDirectories i =
case fileInfoFileType i of
Just Directory -> True
Just SymbolicLink ->
case fileInfoLinkTargetType i of
Just Directory -> True
_ -> False
_ -> False
-- | Set the filtering function used to determine which entries in
-- the browser's current directory appear in the browser. 'Nothing'
-- indicates no filtering, meaning all entries will be shown. 'Just'
-- indicates a function that should return 'True' for entries that
-- should be permitted to appear.
setFileBrowserEntryFilter :: Maybe (FileInfo -> Bool) -> FileBrowser n -> FileBrowser n
setFileBrowserEntryFilter f b =
applyFilterAndSearch $ b & fileBrowserEntryFilterL .~ f
-- | Set the working directory of the file browser. This scans the new
-- directory and repopulates the browser while maintaining any active
-- search string and/or entry filtering.
--
-- If the directory scan raises an 'IOException', the exception is
-- stored in the browser and is accessible with 'fileBrowserException'. If
-- no exception is raised, the exception field is cleared. Regardless of
-- whether an exception is raised, @..@ is always presented as a valid
-- option in the browser.
setWorkingDirectory :: FilePath -> FileBrowser n -> IO (FileBrowser n)
setWorkingDirectory path b = do
entriesResult <- E.try $ entriesForDirectory path
let (entries, exc) = case entriesResult of
Left (e::E.IOException) -> ([], Just e)
Right es -> (es, Nothing)
allEntries <- if path == "/" then return entries else do
parentResult <- E.try $ parentOf path
return $ case parentResult of
Left (_::E.IOException) -> entries
Right parent -> parent : entries
let b' = setEntries allEntries b
return $ b' & fileBrowserWorkingDirectoryL .~ path
& fileBrowserExceptionL .~ exc
& fileBrowserSelectedFilesL .~ mempty
parentOf :: FilePath -> IO FileInfo
parentOf path = getFileInfo ".." $ FP.takeDirectory path
-- | Build a 'FileInfo' for the specified file and path. If an
-- 'IOException' is raised while attempting to get the file information,
-- the 'fileInfoFileStatus' field is populated with the exception.
-- Otherwise it is populated with the 'FileStatus' for the file.
getFileInfo :: String
-- ^ The name of the file to inspect. This filename is only
-- used to set the 'fileInfoFilename' and sanitized filename
-- fields; the actual file to be inspected is referred
-- to by the second argument. This is decomposed so that
-- 'FileInfo's can be used to represent information about
-- entries like @..@, whose display names differ from their
-- physical paths.
-> FilePath
-- ^ The actual full path to the file or directory to
-- inspect.
-> IO FileInfo
getFileInfo name = go []
where
go history fullPath = do
filePath <- D.makeAbsolute fullPath
statusResult <- E.try $ U.getSymbolicLinkStatus filePath
let stat = do
status <- statusResult
let U.COff sz = U.fileSize status
return FileStatus { fileStatusFileType = fileTypeFromStatus status
, fileStatusSize = sz
}
targetTy <- case fileStatusFileType <$> stat of
Right (Just SymbolicLink) -> do
targetPathResult <- E.try $ U.readSymbolicLink filePath
case targetPathResult of
Left (_::E.SomeException) -> return Nothing
Right targetPath ->
-- Watch out for recursive symlink chains:
-- if history starts repeating, abort the
-- symlink following process.
--
-- Examples:
-- $ ln -s foo foo
--
-- $ ln -s foo bar
-- $ ln -s bar foo
if targetPath `elem` history
then return Nothing
else do
targetInfo <- liftIO $ go (fullPath : history) targetPath
case fileInfoFileStatus targetInfo of
Right (FileStatus _ targetTy) -> return targetTy
_ -> return Nothing
_ -> return Nothing
return FileInfo { fileInfoFilename = name
, fileInfoFilePath = filePath
, fileInfoSanitizedFilename = sanitizeFilename name
, fileInfoFileStatus = stat
, fileInfoLinkTargetType = targetTy
}
-- | Get the file type for this file info entry. If the file type could
-- not be obtained due to an 'IOException', return 'Nothing'.
fileInfoFileType :: FileInfo -> Maybe FileType
fileInfoFileType i =
case fileInfoFileStatus i of
Left _ -> Nothing
Right stat -> fileStatusFileType stat
-- | Get the working directory of the file browser.
getWorkingDirectory :: FileBrowser n -> FilePath
getWorkingDirectory = fileBrowserWorkingDirectory
setEntries :: [FileInfo] -> FileBrowser n -> FileBrowser n
setEntries es b =
applyFilterAndSearch $ b & fileBrowserLatestResultsL .~ es
-- | Returns whether the file browser is in search mode, i.e., the mode
-- in which user input affects the browser's active search string and
-- displayed entries. This is used to aid in event dispatching in the
-- calling program.
fileBrowserIsSearching :: FileBrowser n -> Bool
fileBrowserIsSearching b = isJust $ b^.fileBrowserSearchStringL
-- | Get the entries chosen by the user, if any. Entries are chosen by
-- an 'Enter' or 'Space' keypress; if you want the entry under the
-- cursor, use 'fileBrowserCursor'.
fileBrowserSelection :: FileBrowser n -> [FileInfo]
fileBrowserSelection b =
let getEntry filename = fromJust $ F.find ((== filename) . fileInfoFilename) $ b^.fileBrowserLatestResultsL
in fmap getEntry $ F.toList $ b^.fileBrowserSelectedFilesL
-- | Modify the file browser's active search string. This causes the
-- browser's displayed entries to change to those in its current
-- directory that match the search string, if any. If a search string
-- is provided, it is matched case-insensitively anywhere in file or
-- directory names.
updateFileBrowserSearch :: (Maybe T.Text -> Maybe T.Text)
-- ^ The search transformation. 'Nothing'
-- indicates that search mode should be off;
-- 'Just' indicates that it should be on and
-- that the provided search string should be
-- used.
-> FileBrowser n
-- ^ The browser to modify.
-> FileBrowser n
updateFileBrowserSearch f b =
let old = b^.fileBrowserSearchStringL
new = f $ b^.fileBrowserSearchStringL
oldLen = maybe 0 T.length old
newLen = maybe 0 T.length new
in if old == new
then b
else if oldLen == newLen
-- This case avoids a list rebuild and cursor position reset
-- when the search state isn't *really* changing.
then b & fileBrowserSearchStringL .~ new
else applyFilterAndSearch $ b & fileBrowserSearchStringL .~ new
applyFilterAndSearch :: FileBrowser n -> FileBrowser n
applyFilterAndSearch b =
let filterMatch = fromMaybe (const True) (b^.fileBrowserEntryFilterL)
searchMatch = maybe (const True)
(\search i -> (T.toLower search `T.isInfixOf` (T.pack $ toLower <$> fileInfoSanitizedFilename i)))
(b^.fileBrowserSearchStringL)
match i = filterMatch i && searchMatch i
matching = filter match $ b^.fileBrowserLatestResultsL
in b { fileBrowserEntries = list (b^.fileBrowserNameL) (V.fromList matching) 1 }
-- | Generate a textual abbreviation of a file size, e.g. "10.2M" or "12
-- bytes".
prettyFileSize :: Int64
-- ^ A file size in bytes.
-> T.Text
prettyFileSize i
| i >= 2 ^ (40::Int64) = T.pack $ format (i `divBy` (2 ** 40)) <> "T"
| i >= 2 ^ (30::Int64) = T.pack $ format (i `divBy` (2 ** 30)) <> "G"
| i >= 2 ^ (20::Int64) = T.pack $ format (i `divBy` (2 ** 20)) <> "M"
| i >= 2 ^ (10::Int64) = T.pack $ format (i `divBy` (2 ** 10)) <> "K"
| otherwise = T.pack $ show i <> " bytes"
where
format = printf "%0.1f"
divBy :: Int64 -> Double -> Double
divBy a b = ((fromIntegral a) :: Double) / b
-- | Build a list of file info entries for the specified directory. This
-- function does not catch any exceptions raised by calling
-- 'makeAbsolute' or 'listDirectory', but it does catch exceptions on
-- a per-file basis. Any exceptions caught when inspecting individual
-- files are stored in the 'fileInfoFileStatus' field of each
-- 'FileInfo'.
--
-- The entries returned are all entries in the specified directory
-- except for @.@ and @..@. Directories are always given first. Entries
-- are sorted in case-insensitive lexicographic order.
--
-- This function is exported for those who want to implement their own
-- file browser using the types in this module.
entriesForDirectory :: FilePath -> IO [FileInfo]
entriesForDirectory rawPath = do
path <- D.makeAbsolute rawPath
-- Get all entries except "." and "..", then sort them
dirContents <- D.listDirectory path
infos <- forM dirContents $ \f -> do
getFileInfo f (path FP.</> f)
let dirsFirst a b = if fileInfoFileType a == Just Directory &&
fileInfoFileType b == Just Directory
then compare (toLower <$> fileInfoFilename a)
(toLower <$> fileInfoFilename b)
else if fileInfoFileType a == Just Directory &&
fileInfoFileType b /= Just Directory
then LT
else if fileInfoFileType b == Just Directory &&
fileInfoFileType a /= Just Directory
then GT
else compare (toLower <$> fileInfoFilename a)
(toLower <$> fileInfoFilename b)
allEntries = sortBy dirsFirst infos
return allEntries
fileTypeFromStatus :: U.FileStatus -> Maybe FileType
fileTypeFromStatus s =
if | U.isBlockDevice s -> Just BlockDevice
| U.isCharacterDevice s -> Just CharacterDevice
| U.isNamedPipe s -> Just NamedPipe
| U.isRegularFile s -> Just RegularFile
| U.isDirectory s -> Just Directory
| U.isSocket s -> Just UnixSocket
| U.isSymbolicLink s -> Just SymbolicLink
| otherwise -> Nothing
-- | Get the file information for the file under the cursor, if any.
fileBrowserCursor :: FileBrowser n -> Maybe FileInfo
fileBrowserCursor b = snd <$> listSelectedElement (b^.fileBrowserEntriesL)
-- | Handle a Vty input event. Note that event handling can
-- cause a directory change so the caller should be aware that
-- 'fileBrowserException' may need to be checked after handling an
-- event in case an exception was triggered while scanning the working
-- directory.
--
-- Events handled regardless of mode:
--
-- * @Ctrl-b@: 'actionFileBrowserListPageUp'
-- * @Ctrl-f@: 'actionFileBrowserListPageDown'
-- * @Ctrl-d@: 'actionFileBrowserListHalfPageDown'
-- * @Ctrl-u@: 'actionFileBrowserListHalfPageUp'
-- * @g@: 'actionFileBrowserListTop'
-- * @G@: 'actionFileBrowserListBottom'
-- * @j@: 'actionFileBrowserListNext'
-- * @k@: 'actionFileBrowserListPrev'
-- * @Ctrl-n@: 'actionFileBrowserListNext'
-- * @Ctrl-p@: 'actionFileBrowserListPrev'
--
-- Events handled only in normal mode:
--
-- * @/@: 'actionFileBrowserBeginSearch'
-- * @Enter@: 'actionFileBrowserSelectEnter'
-- * @Space@: 'actionFileBrowserSelectCurrent'
--
-- Events handled only in search mode:
--
-- * @Esc@, @Ctrl-C@: cancel search mode
-- * Text input: update search string
actionFileBrowserBeginSearch :: FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserBeginSearch b =
return $ updateFileBrowserSearch (const $ Just "") b
actionFileBrowserSelectEnter :: FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserSelectEnter b =
maybeSelectCurrentEntry b
actionFileBrowserSelectCurrent :: FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserSelectCurrent b =
selectCurrentEntry b
actionFileBrowserListPageUp :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListPageUp b = do
let old = b ^. fileBrowserEntriesL
new <- listMovePageUp old
return $ b & fileBrowserEntriesL .~ new
actionFileBrowserListPageDown :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListPageDown b = do
let old = b ^. fileBrowserEntriesL
new <- listMovePageDown old
return $ b & fileBrowserEntriesL .~ new
actionFileBrowserListHalfPageUp :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListHalfPageUp b = do
let old = b ^. fileBrowserEntriesL
new <- listMoveByPages (-0.5::Double) old
return $ b & fileBrowserEntriesL .~ new
actionFileBrowserListHalfPageDown :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListHalfPageDown b = do
let old = b ^. fileBrowserEntriesL
new <- listMoveByPages (0.5::Double) old
return $ b & fileBrowserEntriesL .~ new
actionFileBrowserListTop :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListTop b =
return $ b & fileBrowserEntriesL %~ listMoveTo 0
actionFileBrowserListBottom :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListBottom b = do
let sz = length (listElements $ b^.fileBrowserEntriesL)
return $ b & fileBrowserEntriesL %~ listMoveTo (sz - 1)
actionFileBrowserListNext :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListNext b =
return $ b & fileBrowserEntriesL %~ listMoveBy 1
actionFileBrowserListPrev :: Ord n => FileBrowser n -> EventM n (FileBrowser n)
actionFileBrowserListPrev b =
return $ b & fileBrowserEntriesL %~ listMoveBy (-1)
handleFileBrowserEvent :: (Ord n) => Vty.Event -> FileBrowser n -> EventM n (FileBrowser n)
handleFileBrowserEvent e b =
if fileBrowserIsSearching b
then handleFileBrowserEventSearching e b
else handleFileBrowserEventNormal e b
safeInit :: T.Text -> T.Text
safeInit t | T.length t == 0 = t
| otherwise = T.init t
handleFileBrowserEventSearching :: (Ord n) => Vty.Event -> FileBrowser n -> EventM n (FileBrowser n)
handleFileBrowserEventSearching e b =
case e of
Vty.EvKey (Vty.KChar 'c') [Vty.MCtrl] ->
return $ updateFileBrowserSearch (const Nothing) b
Vty.EvKey Vty.KEsc [] ->
return $ updateFileBrowserSearch (const Nothing) b
Vty.EvKey Vty.KBS [] ->
return $ updateFileBrowserSearch (fmap safeInit) b
Vty.EvKey Vty.KEnter [] ->
updateFileBrowserSearch (const Nothing) <$>
maybeSelectCurrentEntry b
Vty.EvKey (Vty.KChar c) [] ->
return $ updateFileBrowserSearch (fmap (flip T.snoc c)) b
_ ->
handleFileBrowserEventCommon e b
handleFileBrowserEventNormal :: (Ord n) => Vty.Event -> FileBrowser n -> EventM n (FileBrowser n)
handleFileBrowserEventNormal e b =
case e of
Vty.EvKey (Vty.KChar '/') [] ->
-- Begin file search
actionFileBrowserBeginSearch b
Vty.EvKey Vty.KEnter [] ->
-- Select file or enter directory
actionFileBrowserSelectEnter b
Vty.EvKey (Vty.KChar ' ') [] ->
-- Select entry
actionFileBrowserSelectCurrent b
_ ->
handleFileBrowserEventCommon e b
handleFileBrowserEventCommon :: (Ord n) => Vty.Event -> FileBrowser n -> EventM n (FileBrowser n)
handleFileBrowserEventCommon e b =
case e of
Vty.EvKey (Vty.KChar 'b') [Vty.MCtrl] ->
actionFileBrowserListPageUp b
Vty.EvKey (Vty.KChar 'f') [Vty.MCtrl] ->
actionFileBrowserListPageDown b
Vty.EvKey (Vty.KChar 'd') [Vty.MCtrl] ->
actionFileBrowserListHalfPageDown b
Vty.EvKey (Vty.KChar 'u') [Vty.MCtrl] ->
actionFileBrowserListHalfPageUp b
Vty.EvKey (Vty.KChar 'g') [] ->
actionFileBrowserListTop b
Vty.EvKey (Vty.KChar 'G') [] ->
actionFileBrowserListBottom b
Vty.EvKey (Vty.KChar 'j') [] ->
actionFileBrowserListNext b
Vty.EvKey (Vty.KChar 'k') [] ->
actionFileBrowserListPrev b
Vty.EvKey (Vty.KChar 'n') [Vty.MCtrl] ->
actionFileBrowserListNext b
Vty.EvKey (Vty.KChar 'p') [Vty.MCtrl] ->
actionFileBrowserListPrev b
_ ->
handleEventLensed b fileBrowserEntriesL handleListEvent e
-- | If the browser's current entry is selectable according to
-- @fileBrowserSelectable@, add it to the selection set and return.
-- If not, and if the entry is a directory or a symlink targeting a
-- directory, set the browser's current path to the selected directory.
--
-- Otherwise, return the browser state unchanged.
maybeSelectCurrentEntry :: FileBrowser n -> EventM n (FileBrowser n)
maybeSelectCurrentEntry b =
case fileBrowserCursor b of
Nothing -> return b
Just entry ->
if fileBrowserSelectable b entry
then return $ b & fileBrowserSelectedFilesL %~ Set.insert (fileInfoFilename entry)
else case fileInfoFileType entry of
Just Directory ->
liftIO $ setWorkingDirectory (fileInfoFilePath entry) b
Just SymbolicLink ->
case fileInfoLinkTargetType entry of
Just Directory -> do
liftIO $ setWorkingDirectory (fileInfoFilePath entry) b
_ ->
return b
_ ->
return b
selectCurrentEntry :: FileBrowser n -> EventM n (FileBrowser n)
selectCurrentEntry b =
case fileBrowserCursor b of
Nothing -> return b
Just e -> return $ b & fileBrowserSelectedFilesL %~ Set.insert (fileInfoFilename e)
-- | Render a file browser. This renders a list of entries in the
-- working directory, a cursor to select from among the entries, a
-- header displaying the working directory, and a footer displaying
-- information about the selected entry.
--
-- Note that if the most recent file browser operation produced an
-- exception in 'fileBrowserException', that exception is not rendered
-- by this function. That exception needs to be rendered (if at all) by
-- the calling application.
--
-- The file browser is greedy in both dimensions.
renderFileBrowser :: (Show n, Ord n)
=> Bool
-- ^ Whether the file browser has input focus.
-> FileBrowser n
-- ^ The browser to render.
-> Widget n
renderFileBrowser foc b =
let maxFilenameLength = maximum $ (length . fileInfoFilename) <$> (b^.fileBrowserEntriesL)
cwdHeader = padRight Max $
str $ sanitizeFilename $ fileBrowserWorkingDirectory b
selInfo = case listSelectedElement (b^.fileBrowserEntriesL) of
Nothing -> vLimit 1 $ fill ' '
Just (_, i) -> padRight Max $ selInfoFor i
fileTypeLabel Nothing = "unknown"
fileTypeLabel (Just t) =
case t of
RegularFile -> "file"
BlockDevice -> "block device"
CharacterDevice -> "character device"
NamedPipe -> "pipe"
Directory -> "directory"
SymbolicLink -> "symbolic link"
UnixSocket -> "socket"
selInfoFor i =
let label = case fileInfoFileStatus i of
Left _ -> "unknown"
Right stat ->
let maybeSize = if fileStatusFileType stat == Just RegularFile
then ", " <> prettyFileSize (fileStatusSize stat)
else ""
in fileTypeLabel (fileStatusFileType stat) <> maybeSize
in txt $ (T.pack $ fileInfoSanitizedFilename i) <> ": " <> label
maybeSearchInfo = case b^.fileBrowserSearchStringL of
Nothing -> emptyWidget
Just s -> padRight Max $
txt "Search: " <+>
showCursor (b^.fileBrowserNameL) (Location (T.length s, 0)) (txt s)
in withDefAttr fileBrowserAttr $
vBox [ withDefAttr fileBrowserCurrentDirectoryAttr cwdHeader
, renderList (renderFileInfo foc maxFilenameLength (b^.fileBrowserSelectedFilesL) (b^.fileBrowserNameL))
foc (b^.fileBrowserEntriesL)
, maybeSearchInfo
, withDefAttr fileBrowserSelectionInfoAttr selInfo
]
renderFileInfo :: Bool -> Int -> Set.Set String -> n -> Bool -> FileInfo -> Widget n
renderFileInfo foc maxLen selFiles n listSel info =
(if foc
then (if listSel then forceAttr listSelectedFocusedAttr
else if sel then forceAttr fileBrowserSelectedAttr else id)
else (if listSel then forceAttr listSelectedAttr
else if sel then forceAttr fileBrowserSelectedAttr else id)) $
padRight Max body
where
sel = fileInfoFilename info `Set.member` selFiles
addAttr = maybe id (withDefAttr . attrForFileType) (fileInfoFileType info)
body = addAttr (hLimit (maxLen + 1) $
padRight Max $
(if foc && listSel then putCursor n (Location (0,0)) else id) $
str $ fileInfoSanitizedFilename info <> suffix)
suffix = (if fileInfoFileType info == Just Directory then "/" else "") <>
(if sel then "*" else "")
-- | Sanitize a filename for terminal display, replacing non-printable
-- characters with '?'.
sanitizeFilename :: String -> String
sanitizeFilename = fmap toPrint
where
toPrint c | isPrint c = c
| otherwise = '?'
attrForFileType :: FileType -> AttrName
attrForFileType RegularFile = fileBrowserRegularFileAttr
attrForFileType BlockDevice = fileBrowserBlockDeviceAttr
attrForFileType CharacterDevice = fileBrowserCharacterDeviceAttr
attrForFileType NamedPipe = fileBrowserNamedPipeAttr
attrForFileType Directory = fileBrowserDirectoryAttr
attrForFileType SymbolicLink = fileBrowserSymbolicLinkAttr
attrForFileType UnixSocket = fileBrowserUnixSocketAttr
-- | The base attribute for all file browser attributes.
fileBrowserAttr :: AttrName
fileBrowserAttr = "fileBrowser"
-- | The attribute used for the current directory displayed at the top
-- of the browser.
fileBrowserCurrentDirectoryAttr :: AttrName
fileBrowserCurrentDirectoryAttr = fileBrowserAttr <> "currentDirectory"
-- | The attribute used for the entry information displayed at the
-- bottom of the browser.
fileBrowserSelectionInfoAttr :: AttrName
fileBrowserSelectionInfoAttr = fileBrowserAttr <> "selectionInfo"
-- | The attribute used to render directory entries.
fileBrowserDirectoryAttr :: AttrName
fileBrowserDirectoryAttr = fileBrowserAttr <> "directory"
-- | The attribute used to render block device entries.
fileBrowserBlockDeviceAttr :: AttrName
fileBrowserBlockDeviceAttr = fileBrowserAttr <> "block"
-- | The attribute used to render regular file entries.
fileBrowserRegularFileAttr :: AttrName
fileBrowserRegularFileAttr = fileBrowserAttr <> "regular"
-- | The attribute used to render character device entries.
fileBrowserCharacterDeviceAttr :: AttrName
fileBrowserCharacterDeviceAttr = fileBrowserAttr <> "char"
-- | The attribute used to render named pipe entries.
fileBrowserNamedPipeAttr :: AttrName
fileBrowserNamedPipeAttr = fileBrowserAttr <> "pipe"
-- | The attribute used to render symbolic link entries.
fileBrowserSymbolicLinkAttr :: AttrName
fileBrowserSymbolicLinkAttr = fileBrowserAttr <> "symlink"
-- | The attribute used to render Unix socket entries.
fileBrowserUnixSocketAttr :: AttrName
fileBrowserUnixSocketAttr = fileBrowserAttr <> "unixSocket"
-- | The attribute used for selected entries in the file browser.
fileBrowserSelectedAttr :: AttrName
fileBrowserSelectedAttr = fileBrowserAttr <> "selected"
-- | A file type filter for use with 'setFileBrowserEntryFilter'. This
-- filter permits entries whose file types are in the specified list.
fileTypeMatch :: [FileType] -> FileInfo -> Bool
fileTypeMatch tys i = maybe False (`elem` tys) $ fileInfoFileType i
-- | A filter that matches any directory regardless of name, or any
-- regular file with the specified extension. For example, an extension
-- argument of @"xml"@ would match regular files @test.xml@ and
-- @TEST.XML@ and it will match directories regardless of name.
--
-- This matcher also matches symlinks if and only if their targets are
-- directories. This is intended to make it possible to use this matcher
-- to find files with certain extensions, but also support directory
-- traversal via symlinks.
fileExtensionMatch :: String -> FileInfo -> Bool
fileExtensionMatch ext i = case fileInfoFileType i of
Just Directory -> True
Just RegularFile -> ('.' : (toLower <$> ext)) `isSuffixOf` (toLower <$> fileInfoFilename i)
Just SymbolicLink -> case fileInfoLinkTargetType i of
Just Directory -> True
_ -> False
_ -> False
|
sjakobi/brick
|
src/Brick/Widgets/FileBrowser.hs
|
bsd-3-clause
| 37,439
| 0
| 26
| 10,181
| 6,200
| 3,274
| 2,926
| 513
| 12
|
module Util (
doctestTestCase
, Util.cases
, errors
, failures
) where
import System.Directory (getCurrentDirectory, setCurrentDirectory)
import System.Exit (ExitCode(ExitSuccess))
import System.Process (readProcessWithExitCode)
import qualified Test.HUnit as HU
import Test.HUnit (assertEqual, Counts(..), Test(TestCase), Assertion,
showCounts)
import Data.Char (isSpace)
cases :: Int -> Counts
cases n = Counts {
HU.cases = n
, tried = n
, errors = 0
, failures = 0
}
-- | Construct a doctest specific 'TestCase'.
doctestTestCase :: FilePath -- ^ absolute path to `doctest` binary
-> FilePath -- ^ current directory of forked `doctest` process
-> [String] -- ^ args, given to doctest
-> Counts -- ^ expected test result
-> Test
doctestTestCase doctest dir args counts = TestCase $ doctestAssert doctest dir args counts
-- | Construct a doctest specific 'Assertion'.
doctestAssert :: FilePath -- ^ absolute path to `doctest` binary
-> FilePath -- ^ current directory of forked `doctest` process
-> [String] -- ^ args, given to `doctest`
-> Counts -- ^ expected test result
-> Assertion
doctestAssert doctest workingDir args counts = do
out <- runDoctest doctest workingDir args
assertEqual label (showCounts counts) (last . lines $ out)
where
label = workingDir ++ " " ++ show args
-- | Fork and run a `doctest` process.
runDoctest :: FilePath -- ^ absolute path to `doctest` binary
-> FilePath -- ^ current directory of forked `doctest` process
-> [String] -- ^ args, given to `doctest`
-> IO String -- ^ final result, as printed by `doctest`
runDoctest doctest workingDir args = do
cwd <- getCurrentDirectory
setCurrentDirectory workingDir
(exit, out, err) <- readProcessWithExitCode doctest args ""
setCurrentDirectory cwd
case exit of
ExitSuccess -> return $ lastLine err
_ ->
error $ mayCat "STDERR:" (strip err) ++ mayCat "STDOUT:" (strip out)
where
mayCat x y = if null y then "" else unlines ["", x, y]
where
lastLine = reverse . takeWhile (/= '\r') . reverse
-- | Remove leading and trailing whitespace from given string.
--
-- Example:
--
-- >>> strip " \tfoo\nbar \t\n "
-- "foo\nbar"
strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse
|
beni55/doctest-haskell
|
tests/integration/Util.hs
|
mit
| 2,497
| 0
| 14
| 658
| 541
| 300
| 241
| 50
| 3
|
module Pos.Core.Common.ChainDifficulty
( ChainDifficulty (..)
, HasDifficulty (..)
, isMoreDifficult
) where
import Universum
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Data.SafeCopy (base, deriveSafeCopySimple)
import Pos.Binary.Class (Cons (..), Field (..), deriveSimpleBi)
import Pos.Core.Common.BlockCount
import Pos.Util.Some (Some, liftLensSome)
-- | Chain difficulty represents necessary effort to generate a
-- chain. In the simplest case it can be number of blocks in chain.
newtype ChainDifficulty = ChainDifficulty
{ getChainDifficulty :: BlockCount
} deriving (Show, Eq, Ord, Num, Enum, Real, Integral, Generic, Buildable, Typeable, NFData)
class HasDifficulty a where
difficultyL :: Lens' a ChainDifficulty
instance HasDifficulty (Some HasDifficulty) where
difficultyL = liftLensSome difficultyL
isMoreDifficult :: HasDifficulty a => a -> a -> Bool
a `isMoreDifficult` b = a ^. difficultyL > b ^. difficultyL
deriveJSON defaultOptions ''ChainDifficulty
deriveSimpleBi ''ChainDifficulty [
Cons 'ChainDifficulty [
Field [| getChainDifficulty :: BlockCount |]
]]
deriveSafeCopySimple 0 'base ''ChainDifficulty
|
input-output-hk/pos-haskell-prototype
|
core/src/Pos/Core/Common/ChainDifficulty.hs
|
mit
| 1,265
| 0
| 9
| 270
| 302
| 172
| 130
| -1
| -1
|
module AllBaseModules where
import Control.Exception ()
import Data.Char ()
import Data.Data ()
import Data.Defined ()
import Data.Either ()
import Data.Function ()
import Data.List ()
import Data.LocalStorage ()
import Data.Maybe ()
import Data.MutMap ()
import Data.MutMap.Internal ()
import Data.Mutex ()
import Data.Nullable ()
import Data.Ord ()
import Data.Ratio ()
import Data.Text ()
import Data.Time ()
import Data.Var ()
import Debug.Trace ()
import FFI
import Fay.Unsafe ()
import Prelude
import Unsafe.Coerce ()
main :: Fay ()
main = putStrLn "ok"
|
beni55/fay
|
tests/AllBaseModules.hs
|
bsd-3-clause
| 562
| 0
| 6
| 80
| 197
| 122
| 75
| 26
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Module : ProcessRegistry
-- Copyright : (C) 2017, Jacob Stanley; 2018, Stevan Andjelkovic
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Stevan Andjelkovic <stevan.andjelkovic@strath.ac.uk>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
--
-- This module contains the process registry example that is commonly
-- used in the papers on Erlang QuickCheck, e.g. "Finding Race
-- Conditions in Erlang with QuickCheck and PULSE". Parts of the code
-- are stolen from an example in Hedgehog.
--
-----------------------------------------------------------------------------
module ProcessRegistry
( prop_processRegistry
, printLabelledExamples
)
where
import Control.Exception
(catch)
import Control.Monad
(when)
import Control.Monad.IO.Class
(MonadIO(..))
import Data.Foldable
(traverse_)
import Data.Functor.Classes
(Ord1)
import Data.Hashable
(Hashable)
import qualified Data.HashTable.IO as HashTable
import Data.IORef
(IORef)
import qualified Data.IORef as IORef
import Data.Kind
(Type)
import Data.List
((\\))
import Data.Map
(Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
(isJust, isNothing)
import Data.Set
(Set)
import qualified Data.Set as Set
import Data.Tuple
(swap)
import GHC.Generics
(Generic, Generic1)
import Prelude
import System.IO.Error
(ioeGetErrorString)
import System.IO.Unsafe
(unsafePerformIO)
import System.Random
(randomRIO)
import Test.QuickCheck
(Arbitrary, Gen, Property, arbitrary, elements,
tabulate, (.&&.), (===))
import Test.QuickCheck.Monadic
(monadicIO)
import Test.StateMachine
import Test.StateMachine.Labelling
import qualified Test.StateMachine.Types.Rank2 as Rank2
------------------------------------------------------------------------
-- Implementation
--
-- The following code is stolen from an Hedgehog example:
--
-- Fake Process Registry
--
-- /These are global to simulate some kind of external system we're
-- testing./
--
newtype Name = Name String
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (ToExpr)
newtype Pid = Pid Int
deriving newtype (Num)
deriving stock (Eq, Ord, Generic, Show)
deriving anyclass (ToExpr)
type ProcessTable = HashTable.CuckooHashTable String Int
pidRef :: IORef Pid
pidRef =
unsafePerformIO $ IORef.newIORef 0
{-# NOINLINE pidRef #-}
procTable :: ProcessTable
procTable =
unsafePerformIO $ HashTable.new
{-# NOINLINE procTable #-}
killedPidsRef :: IORef [Pid]
killedPidsRef =
unsafePerformIO $ IORef.newIORef []
{-# NOINLINE killedPidsRef #-}
ioReset :: IO ()
ioReset = do
IORef.writeIORef pidRef 0
ks <- fmap fst <$> HashTable.toList procTable
traverse_ (HashTable.delete procTable) ks
IORef.writeIORef killedPidsRef []
ioSpawn :: IO Pid
ioSpawn = do
pid <- IORef.readIORef pidRef
IORef.writeIORef pidRef (pid + 1)
die <- randomRIO (1, 6) :: IO Int
if die == -1
then error "ioSpawn"
else pure pid
ioKill :: Pid -> IO ()
ioKill pid =
IORef.modifyIORef killedPidsRef (pid :)
reverseLookup :: (Eq k, Eq v, Hashable k, Hashable v)
=> HashTable.CuckooHashTable k v -> v -> IO (Maybe k)
reverseLookup tbl val = do
lbt <- swapTable tbl
HashTable.lookup lbt val
where
-- Swap the keys and values in a hashtable.
swapTable :: (Eq k, Eq v, Hashable k, Hashable v)
=> HashTable.CuckooHashTable k v -> IO (HashTable.CuckooHashTable v k)
swapTable t = HashTable.fromList =<< fmap (map swap) (HashTable.toList t)
ioRegister :: Name -> Pid -> IO ()
ioRegister (Name name) pid'@(Pid pid) = do
mpid <- HashTable.lookup procTable name
when (isJust mpid) $
fail "ioRegister: name already registered"
mname <- reverseLookup procTable pid
when (isJust mname) $
fail "ioRegister: pid already registered"
killedPids <- IORef.readIORef killedPidsRef
when (pid' `elem` killedPids) $
fail "ioRegister: pid is dead"
HashTable.insert procTable name pid
ioUnregister :: Name -> IO ()
ioUnregister (Name name) = do
m <- HashTable.lookup procTable name
when (isNothing m) $
fail "ioUnregister: not registered"
HashTable.delete procTable name
-- Here we extend the Hedgehog example with a looking up names in the
-- registry.
ioWhereIs :: Name -> IO Pid
ioWhereIs (Name name) = do
mpid <- HashTable.lookup procTable name
case mpid of
Nothing -> fail "ioWhereIs: not registered"
Just pid -> return (Pid pid)
------------------------------------------------------------------------
-- Specification
data Action (r :: Type -> Type)
= Spawn
| Kill (Reference Pid r)
| Register Name (Reference Pid r)
| BadRegister Name (Reference Pid r)
| Unregister Name
| BadUnregister Name
| WhereIs Name
| Exit
deriving stock (Show, Generic1)
deriving anyclass (Rank2.Functor, Rank2.Foldable, Rank2.Traversable, CommandNames)
data Action_
= Spawn_
| Kill_
| Register_
| BadRegister_
| Unregister_
| BadUnregister_
| WhereIs_
| Exit_
deriving stock (Show, Eq, Ord, Generic)
constructor :: Action r -> Action_
constructor act = case act of
Spawn {} -> Spawn_
Kill {} -> Kill_
Register {} -> Register_
BadRegister {} -> BadRegister_
Unregister {} -> Unregister_
BadUnregister {} -> BadUnregister_
WhereIs {} -> WhereIs_
Exit {} -> Exit_
newtype Response (r :: Type -> Type) = Response
{ _getResponse :: Either Error (Success r) }
deriving stock (Show, Generic1)
deriving anyclass Rank2.Foldable
data Success (r :: Type -> Type)
= Spawned (Reference Pid r)
| Killed
| Registered
| Unregistered
| HereIs (Reference Pid r)
| Exited
deriving stock (Show, Generic1)
deriving anyclass (Rank2.Foldable)
data Error
= NameAlreadyRegisteredError
| PidAlreadyRegisteredError
| PidDeadRegisterError
| NameNotRegisteredError
| UnknownError
deriving stock Show
success :: Success r -> Response r
success = Response . Right
failure :: Error -> Response r
failure = Response . Left
data Model (r :: Type -> Type) = Model
{ pids :: [Reference Pid r]
, registry :: Map Name (Reference Pid r)
, killed :: [Reference Pid r]
, stop :: Bool
}
deriving stock (Show, Generic)
instance ToExpr (Model Concrete)
initModel :: Model r
initModel = Model [] Map.empty [] False
transition :: Model r -> Action r -> Response r -> Model r
transition m act (Response (Left _err)) = case act of
BadRegister {} -> m
BadUnregister {} -> m
_otherwise -> error "transition: good command throws error"
transition Model {..} act (Response (Right resp)) = case (act, resp) of
(Spawn, Spawned pid) ->
Model { pids = pids ++ [pid], .. }
(Kill pid, Killed) ->
Model { killed = killed ++ [pid], .. }
(Register name pid, Registered) ->
Model { registry = Map.insert name pid registry, .. }
(BadRegister _name _pid, _) -> error "transition: BadRegister"
(Unregister name, Unregistered) ->
Model { registry = Map.delete name registry, .. }
(BadUnregister _name, _) -> error "transition: BadUnregister"
(WhereIs _name, HereIs _pid) ->
Model {..}
(Exit, Exited) ->
Model { stop = True, .. }
(_, _) -> error "transition"
precondition :: Model Symbolic -> Action Symbolic -> Logic
precondition Model {..} act = case act of
Spawn -> Top
Kill pid -> pid `member` pids
Register name pid -> pid `member` pids
.&& name `notMember` Map.keys registry
.&& pid `notMember` Map.elems registry
BadRegister name pid -> pid `member` killed
.|| name `member` Map.keys registry
.|| pid `member` Map.elems registry
Unregister name -> name `member` Map.keys registry
BadUnregister name -> name `notMember` Map.keys registry
WhereIs name -> name `member` Map.keys registry
Exit -> Top
postcondition :: Model Concrete -> Action Concrete -> Response Concrete -> Logic
postcondition Model {..} act (Response (Left err)) = case act of
BadRegister _name _pid -> Top
BadUnregister _name -> Top
_ -> Bot .// show err
postcondition Model {..} act (Response (Right resp)) = case (act, resp) of
(Spawn, Spawned _pid) -> Top
(Kill _pid, Killed) -> Top
(Register _name _pid, Registered) -> Top
(Unregister _name, Unregistered) -> Top
(WhereIs name, HereIs pid) -> registry Map.! name .== pid
(Exit, Exited) -> Top
(_, _) -> Bot
semantics' :: Action Concrete -> IO (Success Concrete)
semantics' Spawn = Spawned . reference <$> ioSpawn
semantics' (Kill pid) = Killed <$ ioKill (concrete pid)
semantics' (Register name pid) = Registered <$ ioRegister name (concrete pid)
semantics' (BadRegister name pid) = Registered <$ ioRegister name (concrete pid)
semantics' (Unregister name) = Unregistered <$ ioUnregister name
semantics' (BadUnregister name) = Unregistered <$ ioUnregister name
semantics' (WhereIs name) = HereIs . reference <$> ioWhereIs name
semantics' Exit = return Exited
semantics :: Action Concrete -> IO (Response Concrete)
semantics act = fmap success (semantics' act)
`catch`
(return . failure . handler)
where
handler :: IOError -> Error
handler err = case ioeGetErrorString err of
"ioRegister: name already registered" -> NameAlreadyRegisteredError
"ioRegister: pid already registered" -> PidAlreadyRegisteredError
"ioRegister: pid is dead" -> PidDeadRegisterError
"ioUnregister: not registered" -> NameNotRegisteredError
_ -> UnknownError
data Fin2
= Zero
| One
| Two
deriving stock (Enum, Bounded, Show, Eq, Read, Ord)
data State = Fin2 :*: Fin2 | Stop
deriving stock (Show, Eq, Ord, Generic)
partition :: Model r -> State
partition Model {..}
| stop = Stop
| otherwise = ( toEnum (length pids - length killed)
:*: toEnum (length (Map.keys registry))
)
sinkState :: State -> Bool
sinkState = (== Stop)
_initState :: State
_initState = Zero :*: Zero
allNames :: [Name]
allNames = map Name ["A", "B", "C"]
instance Arbitrary Name where
arbitrary = elements allNames
genSpawn, genKill, genRegister, genBadRegister, genUnregister, genBadUnregister,
genWhereIs, genExit :: Model Symbolic -> Gen (Action Symbolic)
genSpawn _model = return Spawn
genKill model = Kill <$> elements (pids model)
genRegister model = Register <$> arbitrary <*> elements (pids model \\ killed model)
genBadRegister model = BadRegister <$> arbitrary <*> elements (pids model ++ killed model)
genUnregister model = Unregister <$> elements (Map.keys (registry model))
genBadUnregister model = BadUnregister <$> elements (allNames \\ Map.keys (registry model))
genWhereIs model = WhereIs <$> elements (Map.keys (registry model))
genExit _model = return Exit
gens :: Map Action_ (Model Symbolic -> Gen (Action Symbolic))
gens = Map.fromList
[ (Spawn_, genSpawn)
, (Kill_, genKill)
, (Register_, genRegister)
, (BadRegister_, genBadRegister)
, (Unregister_, genUnregister)
, (BadUnregister_, genBadUnregister)
, (WhereIs_, genWhereIs)
, (Exit_, genExit)
]
generator :: Model Symbolic -> Maybe (Gen (Action Symbolic))
generator = markovGenerator markov gens partition sinkState
shrinker :: Model Symbolic -> Action Symbolic -> [Action Symbolic]
shrinker _model _act = []
mock :: Model Symbolic -> Action Symbolic -> GenSym (Response Symbolic)
mock m act = case act of
Spawn -> success . Spawned <$> genSym
Kill _pid -> pure (success Killed)
Register _name _pid -> pure (success Registered)
BadRegister name pid
| name `elem` Map.keys (registry m) -> pure (failure NameAlreadyRegisteredError)
| pid `elem` Map.elems (registry m) -> pure (failure PidAlreadyRegisteredError)
| pid `elem` killed m -> pure (failure PidDeadRegisterError)
| otherwise -> error "mock: BadRegister"
Unregister _name -> pure (success Unregistered)
BadUnregister _name -> pure (failure NameNotRegisteredError)
WhereIs _name -> success . HereIs <$> genSym
Exit -> pure (success Exited)
sm :: StateMachine Model Action IO Response
sm = StateMachine initModel transition precondition postcondition
Nothing generator shrinker semantics mock noCleanup
markov :: Markov State Action_ Double
markov = makeMarkov
[ Zero :*: Zero -< [ Spawn_ /- One :*: Zero ]
, One :*: Zero -< [ Spawn_ /- Two :*: Zero
, Register_ /- One :*: One
, (BadRegister_, 10) >- One :*: Zero
, (Kill_, 20) >- Zero :*: Zero
]
, One :*: One -< [ (Spawn_, 40) >- Two :*: One
, BadRegister_ /- One :*: One
, (Unregister_, 20) >- One :*: Zero
, BadUnregister_ /- One :*: One
, (WhereIs_, 20) >- One :*: One
]
, Two :*: Zero -< [ (Register_, 80) >- Two :*: One
, (Kill_, 20) >- One :*: Zero
]
, Two :*: One -< [ (Register_, 30) >- Two :*: Two
, (Kill_, 10) >- One :*: One
, (Unregister_, 20) >- Two :*: Zero
, (BadUnregister_, 10) >- Two :*: One
, (WhereIs_, 20) >- Two :*: One
, (Exit_, 10) >- Stop
]
, Two :*: Two -< [ (Exit_, 30) >- Stop
, (Unregister_, 20) >- Two :*: One
, (WhereIs_, 50) >- Two :*: Two
]
]
------------------------------------------------------------------------
-- Requirements from the paper "How well are your requirements tested?"
-- (2016) by Arts and Hughes.
data Req
= RegisterNewNameAndPid_REG001
| RegisterExistingName_REG002
| RegisterExistingPid_REG003
| RegisterDeadPid_REG004
| UnregisterRegisteredName_UNR001
| UnregisterNotRegisteredName_UNR002
| WHE001
| WHE002
| DIE001
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (ToExpr)
type EventPred r = Predicate (Event Model Action Response r) Req
-- Convenience combinator for creating classifiers for successful commands.
successful :: (Event Model Action Response r -> Success r -> Either Req (EventPred r))
-> EventPred r
successful f = predicate $ \ev ->
case eventResp ev of
Response (Left _ ) -> Right $ successful f
Response (Right ok) -> f ev ok
tag :: forall r. Ord1 r => [Event Model Action Response r] -> [Req]
tag = classify
[ tagRegisterNewNameAndPid
, tagRegisterExistingName Set.empty
, tagRegisterExistingPid Set.empty
, tagRegisterDeadPid Set.empty
, tagUnregisterRegisteredName Set.empty
, tagUnregisterNotRegisteredName Set.empty
]
where
tagRegisterNewNameAndPid :: EventPred r
tagRegisterNewNameAndPid = successful $ \ev _ -> case eventCmd ev of
Register _ _ -> Left RegisterNewNameAndPid_REG001
_otherwise -> Right tagRegisterNewNameAndPid
tagRegisterExistingName :: Set Name -> EventPred r
tagRegisterExistingName existingNames = predicate $ \ev ->
case (eventCmd ev, eventResp ev) of
(Register name _pid, Response (Right Registered)) ->
Right (tagRegisterExistingName (Set.insert name existingNames))
(BadRegister name _pid, Response (Left NameAlreadyRegisteredError))
| name `Set.member` existingNames -> Left RegisterExistingName_REG002
_otherwise
-> Right (tagRegisterExistingName existingNames)
tagRegisterExistingPid :: Set (Reference Pid r) -> EventPred r
tagRegisterExistingPid existingPids = predicate $ \ev ->
case (eventCmd ev, eventResp ev) of
(Register _name pid, Response (Right Registered)) ->
Right (tagRegisterExistingPid (Set.insert pid existingPids))
(BadRegister _name pid, Response (Left PidAlreadyRegisteredError))
| pid `Set.member` existingPids -> Left RegisterExistingPid_REG003
_otherwise
-> Right (tagRegisterExistingPid existingPids)
tagRegisterDeadPid :: Set (Reference Pid r) -> EventPred r
tagRegisterDeadPid killedPids = predicate $ \ev ->
case (eventCmd ev, eventResp ev) of
(Kill pid, Response (Right Killed)) ->
Right (tagRegisterDeadPid (Set.insert pid killedPids))
(BadRegister _name pid, Response (Left PidDeadRegisterError))
| pid `Set.member` killedPids -> Left RegisterDeadPid_REG004
_otherwise
-> Right (tagRegisterDeadPid killedPids)
tagUnregisterRegisteredName :: Set Name -> EventPred r
tagUnregisterRegisteredName registeredNames = successful $ \ev resp ->
case (eventCmd ev, resp) of
(Register name _pid, Registered) ->
Right (tagUnregisterRegisteredName (Set.insert name registeredNames))
(Unregister name, Unregistered)
| name `Set.member` registeredNames -> Left UnregisterRegisteredName_UNR001
_otherwise
-> Right (tagUnregisterRegisteredName registeredNames)
tagUnregisterNotRegisteredName :: Set Name -> EventPred r
tagUnregisterNotRegisteredName registeredNames = predicate $ \ev ->
case (eventCmd ev, eventResp ev) of
(Register name _pid, Response (Right Registered)) ->
Right (tagUnregisterNotRegisteredName (Set.insert name registeredNames))
(BadUnregister name, Response (Left NameNotRegisteredError))
| name `Set.notMember` registeredNames -> Left UnregisterNotRegisteredName_UNR002
_otherwise
-> Right (tagUnregisterNotRegisteredName registeredNames)
printLabelledExamples :: IO ()
printLabelledExamples = showLabelledExamples sm tag
------------------------------------------------------------------------
prop_processRegistry :: StatsDb IO -> Property
prop_processRegistry sdb = forAllCommands sm (Just 100000) $ \cmds -> monadicIO $ do
liftIO ioReset
(hist, _model, res) <- runCommands sm cmds
let observed = historyObservations sm markov partition constructor hist
reqs = tag (execCmds sm cmds)
persistStats sdb observed
prettyCommands' sm tag cmds hist
$ tabulate "_Requirements" (map show reqs)
$ coverMarkov markov
$ tabulateMarkov sm partition constructor cmds
$ printReliability sdb (transitionMatrix markov) observed
$ res === Ok .&&. reqs === tag (execHistory sm hist)
|
advancedtelematic/quickcheck-state-machine-model
|
test/ProcessRegistry.hs
|
bsd-3-clause
| 20,100
| 0
| 20
| 5,478
| 5,621
| 2,941
| 2,680
| 437
| 12
|
{-# LANGUAGE TemplateHaskell #-} -- for HscInterpreted
module Info () where
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
|
cabrera/ghc-mod
|
test/data/Info.hs
|
bsd-3-clause
| 150
| 0
| 8
| 38
| 66
| 36
| 30
| 6
| 1
|
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | This module provides a scrollable list type and functions for
-- manipulating and rendering it.
module Brick.Widgets.List
( List(listElements, listSelected, listName, listItemHeight)
-- * Consructing a list
, list
-- * Rendering a list
, renderList
-- * Lenses
, listElementsL
, listSelectedL
, listNameL
, listItemHeightL
-- * Manipulating a list
, listMoveBy
, listMoveTo
, listMoveUp
, listMoveDown
, listInsert
, listRemove
, listReplace
, listSelectedElement
-- * Attributes
, listAttr
, listSelectedAttr
)
where
import Control.Applicative ((<$>))
import Control.Lens ((^.), (&), (.~), _2)
import Data.Monoid ((<>))
import Data.Maybe (fromMaybe)
import qualified Data.Algorithm.Diff as D
import Graphics.Vty (Event(..), Key(..))
import qualified Data.Vector as V
import Brick.Types
import Brick.Main (lookupViewport)
import Brick.Widgets.Core
import Brick.Util (clamp)
import Brick.AttrMap
-- | List state. Lists have an element type 'e' that is the data stored
-- by the list. Lists handle the following events by default:
--
-- * Up/down arrow keys: move cursor of selected item
-- * Page up / page down keys: move cursor of selected item by one page
-- at a time (based on the number of items shown)
-- * Home/end keys: move cursor of selected item to beginning or end of
-- list
data List e =
List { listElements :: !(V.Vector e)
, listSelected :: !(Maybe Int)
, listName :: Name
, listItemHeight :: Int
}
suffixLenses ''List
instance HandleEvent (List e) where
handleEvent e theList = f
where
f = case e of
EvKey KUp [] -> return $ listMoveUp theList
EvKey KDown [] -> return $ listMoveDown theList
EvKey KHome [] -> return $ listMoveTo 0 theList
EvKey KEnd [] -> return $ listMoveTo (V.length $ listElements theList) theList
EvKey KPageDown [] -> do
v <- lookupViewport (theList^.listNameL)
case v of
Nothing -> return theList
Just vp -> return $ listMoveBy (vp^.vpSize._2 `div` theList^.listItemHeightL) theList
EvKey KPageUp [] -> do
v <- lookupViewport (theList^.listNameL)
case v of
Nothing -> return theList
Just vp -> return $ listMoveBy (negate $ vp^.vpSize._2 `div` theList^.listItemHeightL) theList
_ -> return theList
-- | The top-level attribute used for the entire list.
listAttr :: AttrName
listAttr = "list"
-- | The attribute used only for the currently-selected list item.
-- Extends 'listAttr'.
listSelectedAttr :: AttrName
listSelectedAttr = listAttr <> "selected"
-- | Construct a list in terms of an element type 'e'.
list :: Name
-- ^ The list name (must be unique)
-> V.Vector e
-- ^ The initial list contents
-> Int
-- ^ The list item height in rows (all list item widgets must be
-- this high)
-> List e
list name es h =
let selIndex = if V.null es then Nothing else Just 0
in List es selIndex name h
-- | Turn a list state value into a widget given an item drawing
-- function.
renderList :: List e -> (Bool -> e -> Widget) -> Widget
renderList l drawElem =
withDefAttr listAttr $
drawListElements l drawElem
drawListElements :: List e -> (Bool -> e -> Widget) -> Widget
drawListElements l drawElem =
Widget Greedy Greedy $ do
c <- getContext
let es = V.slice start num (l^.listElementsL)
idx = case l^.listSelectedL of
Nothing -> 0
Just i -> i
start = max 0 $ idx - numPerHeight + 1
num = min (numPerHeight * 2) (V.length (l^.listElementsL) - start)
numPerHeight = (c^.availHeightL) `div` (l^.listItemHeightL)
off = start * (l^.listItemHeightL)
drawnElements = (flip V.imap) es $ \i e ->
let isSelected = Just (i + start) == l^.listSelectedL
elemWidget = drawElem isSelected e
makeVisible = if isSelected
then (visible . withDefAttr listSelectedAttr)
else id
in makeVisible elemWidget
render $ viewport (l^.listNameL) Vertical $
translateBy (Location (0, off)) $
vBox $ V.toList drawnElements
-- | Insert an item into a list at the specified position.
listInsert :: Int
-- ^ The position at which to insert (0 <= i <= size)
-> e
-- ^ The element to insert
-> List e
-> List e
listInsert pos e l =
let safePos = clamp 0 (V.length es) pos
es = l^.listElementsL
newSel = case l^.listSelectedL of
Nothing -> 0
Just s -> if safePos < s
then s + 1
else s
(front, back) = V.splitAt safePos es
in l & listSelectedL .~ Just newSel
& listElementsL .~ (front V.++ (e `V.cons` back))
-- | Remove an element from a list at the specified position.
listRemove :: Int
-- ^ The position at which to remove an element (0 <= i < size)
-> List e
-> List e
listRemove pos l | V.null (l^.listElementsL) = l
| pos /= clamp 0 (V.length (l^.listElementsL) - 1) pos = l
| otherwise =
let newSel = case l^.listSelectedL of
Nothing -> 0
Just s -> if pos == 0
then 0
else if pos == s
then pos - 1
else if pos < s
then s - 1
else s
(front, back) = V.splitAt pos es
es' = front V.++ V.tail back
es = l^.listElementsL
in l & listSelectedL .~ (if V.null es' then Nothing else Just newSel)
& listElementsL .~ es'
-- | Replace the contents of a list with a new set of elements but
-- preserve the currently selected index.
listReplace :: Eq e => V.Vector e -> List e -> List e
listReplace es' l | es' == l^.listElementsL = l
| otherwise =
let sel = fromMaybe 0 (l^.listSelectedL)
getNewSel es = case (V.null es, V.null es') of
(_, True) -> Nothing
(True, False) -> Just 0
(False, False) -> Just (maintainSel (V.toList es) (V.toList es') sel)
newSel = getNewSel (l^.listElementsL)
in l & listSelectedL .~ newSel
& listElementsL .~ es'
-- | Move the list selected index up by one. (Moves the cursor up,
-- subtracts one from the index.)
listMoveUp :: List e -> List e
listMoveUp = listMoveBy (-1)
-- | Move the list selected index down by one. (Moves the cursor down,
-- adds one to the index.)
listMoveDown :: List e -> List e
listMoveDown = listMoveBy 1
-- | Move the list selected index by the specified amount, subject to
-- validation.
listMoveBy :: Int -> List e -> List e
listMoveBy amt l =
let newSel = clamp 0 (V.length (l^.listElementsL) - 1) <$> (amt +) <$> (l^.listSelectedL)
in l & listSelectedL .~ newSel
-- | Set the selected index for a list to the specified index, subject
-- to validation.
listMoveTo :: Int -> List e -> List e
listMoveTo pos l =
let len = V.length (l^.listElementsL)
newSel = clamp 0 (len - 1) $ if pos < 0 then (len - pos) else pos
in l & listSelectedL .~ if len > 0
then Just newSel
else Nothing
-- | Return a list's selected element, if any.
listSelectedElement :: List e -> Maybe (Int, e)
listSelectedElement l = do
sel <- l^.listSelectedL
return (sel, (l^.listElementsL) V.! sel)
-- Assuming `xs` is an existing list that we want to update to match the
-- state of `ys`. Given a selected index in `xs`, the goal is to compute
-- the corresponding index in `ys`.
maintainSel :: (Eq e) => [e] -> [e] -> Int -> Int
maintainSel xs ys sel = let hunks = D.getDiff xs ys
in merge 0 sel hunks
merge :: (Eq e) => Int -> Int -> [D.Diff e] -> Int
merge _ sel [] = sel
merge idx sel (h:hs) | idx > sel = sel
| otherwise = case h of
D.Both _ _ -> merge sel (idx + 1) hs
-- element removed in new list
D.First _ -> let newSel = if idx < sel
then sel - 1
else sel
in merge newSel idx hs
-- element added in new list
D.Second _ -> let newSel = if idx <= sel
then sel + 1
else sel
in merge newSel (idx + 1) hs
|
ktvoelker/brick
|
src/Brick/Widgets/List.hs
|
bsd-3-clause
| 8,917
| 0
| 22
| 2,999
| 2,355
| 1,242
| 1,113
| -1
| -1
|
{-# LANGUAGE CPP #-}
module Network.Bluetooth.Device (
#if defined(mingw32_HOST_OS)
module Network.Bluetooth.Windows.Device
#elif defined(darwin_HOST_OS)
module Network.Bluetooth.OSX.Device
#elif defined(linux_HOST_OS)
module Network.Bluetooth.Linux.Device
#elif defined(freebsd_HOST_OS)
module Network.Bluetooth.FreeBSD.Device
#endif
) where
#if defined(mingw32_HOST_OS)
import Network.Bluetooth.Windows.Device
#elif defined(darwin_HOST_OS)
import Network.Bluetooth.OSX.Device
#elif defined(linux_HOST_OS)
import Network.Bluetooth.Linux.Device
#elif defined(freebsd_HOST_OS)
import Network.Bluetooth.FreeBSD.Device
#endif
|
bneijt/bluetooth
|
src/Network/Bluetooth/Device.hs
|
bsd-3-clause
| 655
| 0
| 5
| 75
| 30
| 23
| 7
| 2
| 0
|
{-# LANGUAGE RecordWildCards, DeriveDataTypeable #-}
-- | Nix configuration
module Stack.Config.Nix
(nixOptsFromMonoid
,StackNixException(..)
) where
import Control.Monad (when)
import Data.Text (pack)
import Data.Maybe
import Data.Typeable
import Stack.Types
import Control.Exception.Lifted
import Control.Monad.Catch (throwM,MonadCatch)
-- | Interprets NixOptsMonoid options.
nixOptsFromMonoid
:: (Monad m, MonadCatch m)
=> Maybe Project
-> Maybe AbstractResolver
-> NixOptsMonoid
-> m NixOpts
nixOptsFromMonoid mproject maresolver NixOptsMonoid{..} = do
let nixEnable = fromMaybe nixMonoidDefaultEnable nixMonoidEnable
mresolver = case maresolver of
Just (ARResolver resolver) -> Just resolver
Just _ -> Nothing
Nothing -> fmap projectResolver mproject
nixPackages = case mproject of
Nothing -> nixMonoidPackages
Just _ -> nixMonoidPackages ++ [case mresolver of
Just (ResolverSnapshot (LTS x y)) ->
pack ("haskell.packages.lts-" ++ show x ++ "_" ++ show y ++ ".ghc")
_ -> pack "ghc"]
nixInitFile = nixMonoidInitFile
nixShellOptions = nixMonoidShellOptions
when (not (null nixMonoidPackages) && isJust nixInitFile) $
throwM NixCannotUseShellFileAndPackagesException
return NixOpts{..}
-- Exceptions thown specifically by Stack.Nix
data StackNixException
= NixCannotUseShellFileAndPackagesException
-- ^ Nix can't be given packages and a shell file at the same time
deriving (Typeable)
instance Exception StackNixException
instance Show StackNixException where
show NixCannotUseShellFileAndPackagesException =
"You cannot have packages and a shell-file filled at the same time in your nix-shell configuration."
|
rubik/stack
|
src/Stack/Config/Nix.hs
|
bsd-3-clause
| 1,824
| 0
| 24
| 406
| 384
| 199
| 185
| 41
| 5
|
{-# LANGUAGE CPP, BangPatterns #-}
{-# OPTIONS_HADDOCK prune #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Module : Data.ByteString.Lazy.Char8
-- Copyright : (c) Don Stewart 2006-2008
-- (c) Duncan Coutts 2006-2011
-- License : BSD-style
--
-- Maintainer : dons00@gmail.com, duncan@community.haskell.org
-- Stability : stable
-- Portability : portable
--
-- Manipulate /lazy/ 'ByteString's using 'Char' operations. All Chars will
-- be truncated to 8 bits. It can be expected that these functions will
-- run at identical speeds to their 'Data.Word.Word8' equivalents in
-- "Data.ByteString.Lazy".
--
-- This module is intended to be imported @qualified@, to avoid name
-- clashes with "Prelude" functions. eg.
--
-- > import qualified Data.ByteString.Lazy.Char8 as C
--
-- The Char8 interface to bytestrings provides an instance of IsString
-- for the ByteString type, enabling you to use string literals, and
-- have them implicitly packed to ByteStrings.
-- Use @{-\# LANGUAGE OverloadedStrings \#-}@ to enable this.
--
module Data.ByteString.Lazy.Char8 (
-- * The @ByteString@ type
ByteString, -- instances: Eq, Ord, Show, Read, Data, Typeable
-- * Introducing and eliminating 'ByteString's
empty, -- :: ByteString
singleton, -- :: Char -> ByteString
pack, -- :: String -> ByteString
unpack, -- :: ByteString -> String
fromChunks, -- :: [Strict.ByteString] -> ByteString
toChunks, -- :: ByteString -> [Strict.ByteString]
fromStrict, -- :: Strict.ByteString -> ByteString
toStrict, -- :: ByteString -> Strict.ByteString
-- * Basic interface
cons, -- :: Char -> ByteString -> ByteString
cons', -- :: Char -> ByteString -> ByteString
snoc, -- :: ByteString -> Char -> ByteString
append, -- :: ByteString -> ByteString -> ByteString
head, -- :: ByteString -> Char
uncons, -- :: ByteString -> Maybe (Char, ByteString)
last, -- :: ByteString -> Char
tail, -- :: ByteString -> ByteString
unsnoc, -- :: ByteString -> Maybe (ByteString, Char)
init, -- :: ByteString -> ByteString
null, -- :: ByteString -> Bool
length, -- :: ByteString -> Int64
-- * Transforming ByteStrings
map, -- :: (Char -> Char) -> ByteString -> ByteString
reverse, -- :: ByteString -> ByteString
intersperse, -- :: Char -> ByteString -> ByteString
intercalate, -- :: ByteString -> [ByteString] -> ByteString
transpose, -- :: [ByteString] -> [ByteString]
-- * Reducing 'ByteString's (folds)
foldl, -- :: (a -> Char -> a) -> a -> ByteString -> a
foldl', -- :: (a -> Char -> a) -> a -> ByteString -> a
foldl1, -- :: (Char -> Char -> Char) -> ByteString -> Char
foldl1', -- :: (Char -> Char -> Char) -> ByteString -> Char
foldr, -- :: (Char -> a -> a) -> a -> ByteString -> a
foldr1, -- :: (Char -> Char -> Char) -> ByteString -> Char
-- ** Special folds
concat, -- :: [ByteString] -> ByteString
concatMap, -- :: (Char -> ByteString) -> ByteString -> ByteString
any, -- :: (Char -> Bool) -> ByteString -> Bool
all, -- :: (Char -> Bool) -> ByteString -> Bool
maximum, -- :: ByteString -> Char
minimum, -- :: ByteString -> Char
-- * Building ByteStrings
-- ** Scans
scanl, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
-- scanl1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString
-- scanr, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
-- scanr1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString
-- ** Accumulating maps
mapAccumL, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
-- ** Infinite ByteStrings
repeat, -- :: Char -> ByteString
replicate, -- :: Int64 -> Char -> ByteString
cycle, -- :: ByteString -> ByteString
iterate, -- :: (Char -> Char) -> Char -> ByteString
-- ** Unfolding ByteStrings
unfoldr, -- :: (a -> Maybe (Char, a)) -> a -> ByteString
-- * Substrings
-- ** Breaking strings
take, -- :: Int64 -> ByteString -> ByteString
drop, -- :: Int64 -> ByteString -> ByteString
splitAt, -- :: Int64 -> ByteString -> (ByteString, ByteString)
takeWhile, -- :: (Char -> Bool) -> ByteString -> ByteString
dropWhile, -- :: (Char -> Bool) -> ByteString -> ByteString
span, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
break, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
group, -- :: ByteString -> [ByteString]
groupBy, -- :: (Char -> Char -> Bool) -> ByteString -> [ByteString]
inits, -- :: ByteString -> [ByteString]
tails, -- :: ByteString -> [ByteString]
stripPrefix, -- :: ByteString -> ByteString -> Maybe ByteString
stripSuffix, -- :: ByteString -> ByteString -> Maybe ByteString
-- ** Breaking into many substrings
split, -- :: Char -> ByteString -> [ByteString]
splitWith, -- :: (Char -> Bool) -> ByteString -> [ByteString]
-- ** Breaking into lines and words
lines, -- :: ByteString -> [ByteString]
words, -- :: ByteString -> [ByteString]
unlines, -- :: [ByteString] -> ByteString
unwords, -- :: ByteString -> [ByteString]
-- * Predicates
isPrefixOf, -- :: ByteString -> ByteString -> Bool
isSuffixOf, -- :: ByteString -> ByteString -> Bool
-- * Searching ByteStrings
-- ** Searching by equality
elem, -- :: Char -> ByteString -> Bool
notElem, -- :: Char -> ByteString -> Bool
-- ** Searching with a predicate
find, -- :: (Char -> Bool) -> ByteString -> Maybe Char
filter, -- :: (Char -> Bool) -> ByteString -> ByteString
-- partition -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
-- * Indexing ByteStrings
index, -- :: ByteString -> Int64 -> Char
elemIndex, -- :: Char -> ByteString -> Maybe Int64
elemIndices, -- :: Char -> ByteString -> [Int64]
findIndex, -- :: (Char -> Bool) -> ByteString -> Maybe Int64
findIndices, -- :: (Char -> Bool) -> ByteString -> [Int64]
count, -- :: Char -> ByteString -> Int64
-- * Zipping and unzipping ByteStrings
zip, -- :: ByteString -> ByteString -> [(Char,Char)]
zipWith, -- :: (Char -> Char -> c) -> ByteString -> ByteString -> [c]
-- unzip, -- :: [(Char,Char)] -> (ByteString,ByteString)
-- * Ordered ByteStrings
-- sort, -- :: ByteString -> ByteString
-- * Low level conversions
-- ** Copying ByteStrings
copy, -- :: ByteString -> ByteString
-- * Reading from ByteStrings
readInt,
readInteger,
-- * I\/O with 'ByteString's
-- | ByteString I/O uses binary mode, without any character decoding
-- or newline conversion. The fact that it does not respect the Handle
-- newline mode is considered a flaw and may be changed in a future version.
-- ** Standard input and output
getContents, -- :: IO ByteString
putStr, -- :: ByteString -> IO ()
putStrLn, -- :: ByteString -> IO ()
interact, -- :: (ByteString -> ByteString) -> IO ()
-- ** Files
readFile, -- :: FilePath -> IO ByteString
writeFile, -- :: FilePath -> ByteString -> IO ()
appendFile, -- :: FilePath -> ByteString -> IO ()
-- ** I\/O with Handles
hGetContents, -- :: Handle -> IO ByteString
hGet, -- :: Handle -> Int64 -> IO ByteString
hGetNonBlocking, -- :: Handle -> Int64 -> IO ByteString
hPut, -- :: Handle -> ByteString -> IO ()
hPutNonBlocking, -- :: Handle -> ByteString -> IO ByteString
hPutStr, -- :: Handle -> ByteString -> IO ()
hPutStrLn, -- :: Handle -> ByteString -> IO ()
) where
-- Functions transparently exported
import Data.ByteString.Lazy
(fromChunks, toChunks, fromStrict, toStrict
,empty,null,length,tail,init,append,reverse,transpose,cycle
,concat,take,drop,splitAt,intercalate
,isPrefixOf,isSuffixOf,group,inits,tails,copy
,stripPrefix,stripSuffix
,hGetContents, hGet, hPut, getContents
,hGetNonBlocking, hPutNonBlocking
,putStr, hPutStr, interact
,readFile,writeFile,appendFile)
-- Functions we need to wrap.
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as S (ByteString) -- typename only
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import Data.ByteString.Lazy.Internal
import Data.ByteString.Internal (w2c, c2w, isSpaceWord8)
import Data.Int (Int64)
import qualified Data.List as List
import Prelude hiding
(reverse,head,tail,last,init,null,length,map,lines,foldl,foldr,unlines
,concat,any,take,drop,splitAt,takeWhile,dropWhile,span,break,elem,filter
,unwords,words,maximum,minimum,all,concatMap,scanl,scanl1,foldl1,foldr1
,readFile,writeFile,appendFile,replicate,getContents,getLine,putStr,putStrLn
,zip,zipWith,unzip,notElem,repeat,iterate,interact,cycle)
import System.IO (Handle, stdout)
------------------------------------------------------------------------
-- | /O(1)/ Convert a 'Char' into a 'ByteString'
singleton :: Char -> ByteString
singleton = L.singleton . c2w
{-# INLINE singleton #-}
-- | /O(n)/ Convert a 'String' into a 'ByteString'.
pack :: [Char] -> ByteString
pack = packChars
-- | /O(n)/ Converts a 'ByteString' to a 'String'.
unpack :: ByteString -> [Char]
unpack = unpackChars
infixr 5 `cons`, `cons'` --same as list (:)
infixl 5 `snoc`
-- | /O(1)/ 'cons' is analogous to '(:)' for lists.
cons :: Char -> ByteString -> ByteString
cons = L.cons . c2w
{-# INLINE cons #-}
-- | /O(1)/ Unlike 'cons', 'cons'' is
-- strict in the ByteString that we are consing onto. More precisely, it forces
-- the head and the first chunk. It does this because, for space efficiency, it
-- may coalesce the new byte onto the first \'chunk\' rather than starting a
-- new \'chunk\'.
--
-- So that means you can't use a lazy recursive contruction like this:
--
-- > let xs = cons' c xs in xs
--
-- You can however use 'cons', as well as 'repeat' and 'cycle', to build
-- infinite lazy ByteStrings.
--
cons' :: Char -> ByteString -> ByteString
cons' = L.cons' . c2w
{-# INLINE cons' #-}
-- | /O(n)/ Append a Char to the end of a 'ByteString'. Similar to
-- 'cons', this function performs a memcpy.
snoc :: ByteString -> Char -> ByteString
snoc p = L.snoc p . c2w
{-# INLINE snoc #-}
-- | /O(1)/ Extract the first element of a ByteString, which must be non-empty.
head :: ByteString -> Char
head = w2c . L.head
{-# INLINE head #-}
-- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing
-- if it is empty.
uncons :: ByteString -> Maybe (Char, ByteString)
uncons bs = case L.uncons bs of
Nothing -> Nothing
Just (w, bs') -> Just (w2c w, bs')
{-# INLINE uncons #-}
-- | /O(n\/c)/ Extract the 'init' and 'last' of a ByteString, returning Nothing
-- if it is empty.
unsnoc :: ByteString -> Maybe (ByteString, Char)
unsnoc bs = case L.unsnoc bs of
Nothing -> Nothing
Just (bs', w) -> Just (bs', w2c w)
{-# INLINE unsnoc #-}
-- | /O(1)/ Extract the last element of a packed string, which must be non-empty.
last :: ByteString -> Char
last = w2c . L.last
{-# INLINE last #-}
-- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each element of @xs@
map :: (Char -> Char) -> ByteString -> ByteString
map f = L.map (c2w . f . w2c)
{-# INLINE map #-}
-- | /O(n)/ The 'intersperse' function takes a Char and a 'ByteString'
-- and \`intersperses\' that Char between the elements of the
-- 'ByteString'. It is analogous to the intersperse function on Lists.
intersperse :: Char -> ByteString -> ByteString
intersperse = L.intersperse . c2w
{-# INLINE intersperse #-}
-- | 'foldl', applied to a binary operator, a starting value (typically
-- the left-identity of the operator), and a ByteString, reduces the
-- ByteString using the binary operator, from left to right.
foldl :: (a -> Char -> a) -> a -> ByteString -> a
foldl f = L.foldl (\a c -> f a (w2c c))
{-# INLINE foldl #-}
-- | 'foldl'' is like foldl, but strict in the accumulator.
foldl' :: (a -> Char -> a) -> a -> ByteString -> a
foldl' f = L.foldl' (\a c -> f a (w2c c))
{-# INLINE foldl' #-}
-- | 'foldr', applied to a binary operator, a starting value
-- (typically the right-identity of the operator), and a packed string,
-- reduces the packed string using the binary operator, from right to left.
foldr :: (Char -> a -> a) -> a -> ByteString -> a
foldr f = L.foldr (\c a -> f (w2c c) a)
{-# INLINE foldr #-}
-- | 'foldl1' is a variant of 'foldl' that has no starting value
-- argument, and thus must be applied to non-empty 'ByteStrings'.
foldl1 :: (Char -> Char -> Char) -> ByteString -> Char
foldl1 f ps = w2c (L.foldl1 (\x y -> c2w (f (w2c x) (w2c y))) ps)
{-# INLINE foldl1 #-}
-- | 'foldl1'' is like 'foldl1', but strict in the accumulator.
foldl1' :: (Char -> Char -> Char) -> ByteString -> Char
foldl1' f ps = w2c (L.foldl1' (\x y -> c2w (f (w2c x) (w2c y))) ps)
-- | 'foldr1' is a variant of 'foldr' that has no starting value argument,
-- and thus must be applied to non-empty 'ByteString's
foldr1 :: (Char -> Char -> Char) -> ByteString -> Char
foldr1 f ps = w2c (L.foldr1 (\x y -> c2w (f (w2c x) (w2c y))) ps)
{-# INLINE foldr1 #-}
-- | Map a function over a 'ByteString' and concatenate the results
concatMap :: (Char -> ByteString) -> ByteString -> ByteString
concatMap f = L.concatMap (f . w2c)
{-# INLINE concatMap #-}
-- | Applied to a predicate and a ByteString, 'any' determines if
-- any element of the 'ByteString' satisfies the predicate.
any :: (Char -> Bool) -> ByteString -> Bool
any f = L.any (f . w2c)
{-# INLINE any #-}
-- | Applied to a predicate and a 'ByteString', 'all' determines if
-- all elements of the 'ByteString' satisfy the predicate.
all :: (Char -> Bool) -> ByteString -> Bool
all f = L.all (f . w2c)
{-# INLINE all #-}
-- | 'maximum' returns the maximum value from a 'ByteString'
maximum :: ByteString -> Char
maximum = w2c . L.maximum
{-# INLINE maximum #-}
-- | 'minimum' returns the minimum value from a 'ByteString'
minimum :: ByteString -> Char
minimum = w2c . L.minimum
{-# INLINE minimum #-}
-- ---------------------------------------------------------------------
-- Building ByteStrings
-- | 'scanl' is similar to 'foldl', but returns a list of successive
-- reduced values from the left. This function will fuse.
--
-- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--
-- Note that
--
-- > last (scanl f z xs) == foldl f z xs.
scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString
scanl f z = L.scanl (\a b -> c2w (f (w2c a) (w2c b))) (c2w z)
-- | The 'mapAccumL' function behaves like a combination of 'map' and
-- 'foldl'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from left to right, and returning a
-- final value of this accumulator together with the new ByteString.
mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
mapAccumL f = L.mapAccumL (\a w -> case f a (w2c w) of (a',c) -> (a', c2w c))
-- | The 'mapAccumR' function behaves like a combination of 'map' and
-- 'foldr'; it applies a function to each element of a ByteString,
-- passing an accumulating parameter from right to left, and returning a
-- final value of this accumulator together with the new ByteString.
mapAccumR :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString)
mapAccumR f = L.mapAccumR (\acc w -> case f acc (w2c w) of (acc', c) -> (acc', c2w c))
------------------------------------------------------------------------
-- Generating and unfolding ByteStrings
-- | @'iterate' f x@ returns an infinite ByteString of repeated applications
-- of @f@ to @x@:
--
-- > iterate f x == [x, f x, f (f x), ...]
--
iterate :: (Char -> Char) -> Char -> ByteString
iterate f = L.iterate (c2w . f . w2c) . c2w
-- | @'repeat' x@ is an infinite ByteString, with @x@ the value of every
-- element.
--
repeat :: Char -> ByteString
repeat = L.repeat . c2w
-- | /O(n)/ @'replicate' n x@ is a ByteString of length @n@ with @x@
-- the value of every element.
--
replicate :: Int64 -> Char -> ByteString
replicate w c = L.replicate w (c2w c)
-- | /O(n)/ The 'unfoldr' function is analogous to the List \'unfoldr\'.
-- 'unfoldr' builds a ByteString from a seed value. The function takes
-- the element and returns 'Nothing' if it is done producing the
-- ByteString or returns 'Just' @(a,b)@, in which case, @a@ is a
-- prepending to the ByteString and @b@ is used as the next element in a
-- recursive call.
unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString
unfoldr f = L.unfoldr $ \a -> case f a of
Nothing -> Nothing
Just (c, a') -> Just (c2w c, a')
------------------------------------------------------------------------
-- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@,
-- returns the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@.
takeWhile :: (Char -> Bool) -> ByteString -> ByteString
takeWhile f = L.takeWhile (f . w2c)
{-# INLINE takeWhile #-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
dropWhile :: (Char -> Bool) -> ByteString -> ByteString
dropWhile f = L.dropWhile (f . w2c)
{-# INLINE dropWhile #-}
-- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
break f = L.break (f . w2c)
{-# INLINE break #-}
-- | 'span' @p xs@ breaks the ByteString into two segments. It is
-- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString)
span f = L.span (f . w2c)
{-# INLINE span #-}
{-
-- | 'breakChar' breaks its ByteString argument at the first occurence
-- of the specified Char. It is more efficient than 'break' as it is
-- implemented with @memchr(3)@. I.e.
--
-- > break (=='c') "abcd" == breakChar 'c' "abcd"
--
breakChar :: Char -> ByteString -> (ByteString, ByteString)
breakChar = L.breakByte . c2w
{-# INLINE breakChar #-}
-- | 'spanChar' breaks its ByteString argument at the first
-- occurence of a Char other than its argument. It is more efficient
-- than 'span (==)'
--
-- > span (=='c') "abcd" == spanByte 'c' "abcd"
--
spanChar :: Char -> ByteString -> (ByteString, ByteString)
spanChar = L.spanByte . c2w
{-# INLINE spanChar #-}
-}
--
-- TODO, more rules for breakChar*
--
-- | /O(n)/ Break a 'ByteString' into pieces separated by the byte
-- argument, consuming the delimiter. I.e.
--
-- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
-- > split 'a' "aXaXaXa" == ["","X","X","X"]
-- > split 'x' "x" == ["",""]
--
-- and
--
-- > intercalate [c] . split c == id
-- > split == splitWith . (==)
--
-- As for all splitting functions in this library, this function does
-- not copy the substrings, it just constructs new 'ByteStrings' that
-- are slices of the original.
--
split :: Char -> ByteString -> [ByteString]
split = L.split . c2w
{-# INLINE split #-}
-- | /O(n)/ Splits a 'ByteString' into components delimited by
-- separators, where the predicate returns True for a separator element.
-- The resulting components do not contain the separators. Two adjacent
-- separators result in an empty component in the output. eg.
--
-- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
--
splitWith :: (Char -> Bool) -> ByteString -> [ByteString]
splitWith f = L.splitWith (f . w2c)
{-# INLINE splitWith #-}
-- | The 'groupBy' function is the non-overloaded version of 'group'.
groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString]
groupBy k = L.groupBy (\a b -> k (w2c a) (w2c b))
-- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0.
index :: ByteString -> Int64 -> Char
index = (w2c .) . L.index
{-# INLINE index #-}
-- | /O(n)/ The 'elemIndex' function returns the index of the first
-- element in the given 'ByteString' which is equal (by memchr) to the
-- query element, or 'Nothing' if there is no such element.
elemIndex :: Char -> ByteString -> Maybe Int64
elemIndex = L.elemIndex . c2w
{-# INLINE elemIndex #-}
-- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning
-- the indices of all elements equal to the query element, in ascending order.
elemIndices :: Char -> ByteString -> [Int64]
elemIndices = L.elemIndices . c2w
{-# INLINE elemIndices #-}
-- | The 'findIndex' function takes a predicate and a 'ByteString' and
-- returns the index of the first element in the ByteString satisfying the predicate.
findIndex :: (Char -> Bool) -> ByteString -> Maybe Int64
findIndex f = L.findIndex (f . w2c)
{-# INLINE findIndex #-}
-- | The 'findIndices' function extends 'findIndex', by returning the
-- indices of all elements satisfying the predicate, in ascending order.
findIndices :: (Char -> Bool) -> ByteString -> [Int64]
findIndices f = L.findIndices (f . w2c)
-- | count returns the number of times its argument appears in the ByteString
--
-- > count == length . elemIndices
-- > count '\n' == length . lines
--
-- But more efficiently than using length on the intermediate list.
count :: Char -> ByteString -> Int64
count c = L.count (c2w c)
-- | /O(n)/ 'elem' is the 'ByteString' membership predicate. This
-- implementation uses @memchr(3)@.
elem :: Char -> ByteString -> Bool
elem c = L.elem (c2w c)
{-# INLINE elem #-}
-- | /O(n)/ 'notElem' is the inverse of 'elem'
notElem :: Char -> ByteString -> Bool
notElem c = L.notElem (c2w c)
{-# INLINE notElem #-}
-- | /O(n)/ 'filter', applied to a predicate and a ByteString,
-- returns a ByteString containing those characters that satisfy the
-- predicate.
filter :: (Char -> Bool) -> ByteString -> ByteString
filter f = L.filter (f . w2c)
{-# INLINE filter #-}
{-
-- | /O(n)/ and /O(n\/c) space/ A first order equivalent of /filter .
-- (==)/, for the common case of filtering a single Char. It is more
-- efficient to use /filterChar/ in this case.
--
-- > filterChar == filter . (==)
--
-- filterChar is around 10x faster, and uses much less space, than its
-- filter equivalent
--
filterChar :: Char -> ByteString -> ByteString
filterChar c ps = replicate (count c ps) c
{-# INLINE filterChar #-}
{-# RULES
"ByteString specialise filter (== x)" forall x.
filter ((==) x) = filterChar x
#-}
{-# RULES
"ByteString specialise filter (== x)" forall x.
filter (== x) = filterChar x
#-}
-}
-- | /O(n)/ The 'find' function takes a predicate and a ByteString,
-- and returns the first element in matching the predicate, or 'Nothing'
-- if there is no such element.
find :: (Char -> Bool) -> ByteString -> Maybe Char
find f ps = w2c `fmap` L.find (f . w2c) ps
{-# INLINE find #-}
{-
-- | /O(n)/ A first order equivalent of /filter . (==)/, for the common
-- case of filtering a single Char. It is more efficient to use
-- filterChar in this case.
--
-- > filterChar == filter . (==)
--
-- filterChar is around 10x faster, and uses much less space, than its
-- filter equivalent
--
filterChar :: Char -> ByteString -> ByteString
filterChar c = L.filterByte (c2w c)
{-# INLINE filterChar #-}
-- | /O(n)/ A first order equivalent of /filter . (\/=)/, for the common
-- case of filtering a single Char out of a list. It is more efficient
-- to use /filterNotChar/ in this case.
--
-- > filterNotChar == filter . (/=)
--
-- filterNotChar is around 3x faster, and uses much less space, than its
-- filter equivalent
--
filterNotChar :: Char -> ByteString -> ByteString
filterNotChar c = L.filterNotByte (c2w c)
{-# INLINE filterNotChar #-}
-}
-- | /O(n)/ 'zip' takes two ByteStrings and returns a list of
-- corresponding pairs of Chars. If one input ByteString is short,
-- excess elements of the longer ByteString are discarded. This is
-- equivalent to a pair of 'unpack' operations, and so space
-- usage may be large for multi-megabyte ByteStrings
zip :: ByteString -> ByteString -> [(Char,Char)]
zip ps qs
| L.null ps || L.null qs = []
| otherwise = (head ps, head qs) : zip (L.tail ps) (L.tail qs)
-- | 'zipWith' generalises 'zip' by zipping with the function given as
-- the first argument, instead of a tupling function. For example,
-- @'zipWith' (+)@ is applied to two ByteStrings to produce the list
-- of corresponding sums.
zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a]
zipWith f = L.zipWith ((. w2c) . f . w2c)
-- | 'lines' breaks a ByteString up into a list of ByteStrings at
-- newline Chars. The resulting strings do not contain newlines.
--
-- As of bytestring 0.9.0.3, this function is stricter than its
-- list cousin.
--
lines :: ByteString -> [ByteString]
lines Empty = []
lines (Chunk c0 cs0) = loop0 c0 cs0
where
-- this is a really performance sensitive function but the
-- chunked representation makes the general case a bit expensive
-- however assuming a large chunk size and normalish line lengths
-- we will find line endings much more frequently than chunk
-- endings so it makes sense to optimise for that common case.
-- So we partition into two special cases depending on whether we
-- are keeping back a list of chunks that will eventually be output
-- once we get to the end of the current line.
-- the common special case where we have no existing chunks of
-- the current line
loop0 :: S.ByteString -> ByteString -> [ByteString]
loop0 c cs =
case B.elemIndex (c2w '\n') c of
Nothing -> case cs of
Empty | B.null c -> []
| otherwise -> Chunk c Empty : []
(Chunk c' cs')
| B.null c -> loop0 c' cs'
| otherwise -> loop c' [c] cs'
Just n | n /= 0 -> Chunk (B.unsafeTake n c) Empty
: loop0 (B.unsafeDrop (n+1) c) cs
| otherwise -> Empty
: loop0 (B.unsafeTail c) cs
-- the general case when we are building a list of chunks that are
-- part of the same line
loop :: S.ByteString -> [S.ByteString] -> ByteString -> [ByteString]
loop c line cs =
case B.elemIndex (c2w '\n') c of
Nothing ->
case cs of
Empty -> let c' = revChunks (c : line)
in c' `seq` (c' : [])
(Chunk c' cs') -> loop c' (c : line) cs'
Just n ->
let c' = revChunks (B.unsafeTake n c : line)
in c' `seq` (c' : loop0 (B.unsafeDrop (n+1) c) cs)
{-
This function is too strict! Consider,
> prop_lazy =
(L.unpack . head . lazylines $ L.append (L.pack "a\nb\n") (error "failed"))
==
"a"
fails. Here's a properly lazy version of 'lines' for lazy bytestrings
lazylines :: L.ByteString -> [L.ByteString]
lazylines s
| L.null s = []
| otherwise =
let (l,s') = L.break ((==) '\n') s
in l : if L.null s' then []
else lazylines (L.tail s')
we need a similarly lazy, but efficient version.
-}
-- | 'unlines' is an inverse operation to 'lines'. It joins lines,
-- after appending a terminating newline to each.
unlines :: [ByteString] -> ByteString
unlines [] = empty
unlines ss = concat (List.intersperse nl ss) `append` nl -- half as much space
where nl = singleton '\n'
-- | 'words' breaks a ByteString up into a list of words, which
-- were delimited by Chars representing white space. And
--
-- > tokens isSpace = words
--
words :: ByteString -> [ByteString]
words = List.filter (not . L.null) . L.splitWith isSpaceWord8
{-# INLINE words #-}
-- | The 'unwords' function is analogous to the 'unlines' function, on words.
unwords :: [ByteString] -> ByteString
unwords = intercalate (singleton ' ')
{-# INLINE unwords #-}
-- | readInt reads an Int from the beginning of the ByteString. If
-- there is no integer at the beginning of the string, it returns
-- Nothing, otherwise it just returns the int read, and the rest of the
-- string.
--
-- Note: This function will overflow the Int for large integers.
readInt :: ByteString -> Maybe (Int, ByteString)
{-# INLINE readInt #-}
readInt Empty = Nothing
readInt (Chunk x xs) = case w2c (B.unsafeHead x) of
'-' -> loop True 0 0 (B.unsafeTail x) xs
'+' -> loop False 0 0 (B.unsafeTail x) xs
_ -> loop False 0 0 x xs
where loop :: Bool -> Int -> Int
-> S.ByteString -> ByteString -> Maybe (Int, ByteString)
loop neg !i !n !c cs
| B.null c = case cs of
Empty -> end neg i n c cs
(Chunk c' cs') -> loop neg i n c' cs'
| otherwise =
case B.unsafeHead c of
w | w >= 0x30
&& w <= 0x39 -> loop neg (i+1)
(n * 10 + (fromIntegral w - 0x30))
(B.unsafeTail c) cs
| otherwise -> end neg i n c cs
{-# INLINE end #-}
end _ 0 _ _ _ = Nothing
end neg _ n c cs = e
where n' = if neg then negate n else n
c' = chunk c cs
e = n' `seq` c' `seq` Just (n',c')
-- in n' `seq` c' `seq` JustS n' c'
-- | readInteger reads an Integer from the beginning of the ByteString. If
-- there is no integer at the beginning of the string, it returns Nothing,
-- otherwise it just returns the int read, and the rest of the string.
readInteger :: ByteString -> Maybe (Integer, ByteString)
readInteger Empty = Nothing
readInteger (Chunk c0 cs0) =
case w2c (B.unsafeHead c0) of
'-' -> first (B.unsafeTail c0) cs0 >>= \(n, cs') -> return (-n, cs')
'+' -> first (B.unsafeTail c0) cs0
_ -> first c0 cs0
where first c cs
| B.null c = case cs of
Empty -> Nothing
(Chunk c' cs') -> first' c' cs'
| otherwise = first' c cs
first' c cs = case B.unsafeHead c of
w | w >= 0x30 && w <= 0x39 -> Just $
loop 1 (fromIntegral w - 0x30) [] (B.unsafeTail c) cs
| otherwise -> Nothing
loop :: Int -> Int -> [Integer]
-> S.ByteString -> ByteString -> (Integer, ByteString)
loop !d !acc ns !c cs
| B.null c = case cs of
Empty -> combine d acc ns c cs
(Chunk c' cs') -> loop d acc ns c' cs'
| otherwise =
case B.unsafeHead c of
w | w >= 0x30 && w <= 0x39 ->
if d < 9 then loop (d+1)
(10*acc + (fromIntegral w - 0x30))
ns (B.unsafeTail c) cs
else loop 1 (fromIntegral w - 0x30)
(fromIntegral acc : ns)
(B.unsafeTail c) cs
| otherwise -> combine d acc ns c cs
combine _ acc [] c cs = end (fromIntegral acc) c cs
combine d acc ns c cs =
end (10^d * combine1 1000000000 ns + fromIntegral acc) c cs
combine1 _ [n] = n
combine1 b ns = combine1 (b*b) $ combine2 b ns
combine2 b (n:m:ns) = let t = n+m*b in t `seq` (t : combine2 b ns)
combine2 _ ns = ns
end n c cs = let c' = chunk c cs
in c' `seq` (n, c')
-- | Write a ByteString to a handle, appending a newline byte
--
hPutStrLn :: Handle -> ByteString -> IO ()
hPutStrLn h ps = hPut h ps >> hPut h (L.singleton 0x0a)
-- | Write a ByteString to stdout, appending a newline byte
--
putStrLn :: ByteString -> IO ()
putStrLn = hPutStrLn stdout
-- ---------------------------------------------------------------------
-- Internal utilities
-- reverse a list of possibly-empty chunks into a lazy ByteString
revChunks :: [S.ByteString] -> ByteString
revChunks cs = List.foldl' (flip chunk) Empty cs
|
CloudI/CloudI
|
src/api/haskell/external/bytestring-0.10.10.0/Data/ByteString/Lazy/Char8.hs
|
mit
| 34,496
| 0
| 19
| 10,098
| 5,288
| 3,011
| 2,277
| 376
| 9
|
module Settings.Builders.RunTest (runTestBuilderArgs, runTestGhcFlags) where
import Hadrian.Utilities
import System.Environment
import CommandLine
import Flavour
import Oracles.Setting (setting)
import Oracles.TestSettings
import Packages
import Settings.Builders.Common
getTestSetting :: TestSetting -> Expr String
getTestSetting key = expr $ testSetting key
-- | Parse the value of a Boolean test setting or report an error.
getBooleanSetting :: TestSetting -> Expr Bool
getBooleanSetting key = fromMaybe (error msg) <$> parseYesNo <$> getTestSetting key
where
msg = "Cannot parse test setting " ++ quote (show key)
-- | Extra flags to send to the Haskell compiler to run tests.
runTestGhcFlags :: Action String
runTestGhcFlags = do
unregisterised <- flag GhcUnregisterised
let ifMinGhcVer ver opt = do v <- ghcCanonVersion
if ver <= v then pure opt
else pure ""
-- Read extra argument for test from command line, like `-fvectorize`.
ghcOpts <- fromMaybe "" <$> (liftIO $ lookupEnv "EXTRA_HC_OPTS")
-- See: https://github.com/ghc/ghc/blob/master/testsuite/mk/test.mk#L28
let ghcExtraFlags = if unregisterised
then "-optc-fno-builtin"
else ""
-- Take flags to send to the Haskell compiler from test.mk.
-- See: https://github.com/ghc/ghc/blob/master/testsuite/mk/test.mk#L37
unwords <$> sequence
[ pure " -dcore-lint -dcmm-lint -no-user-package-db -rtsopts"
, pure ghcOpts
, pure ghcExtraFlags
, ifMinGhcVer "711" "-fno-warn-missed-specialisations"
, ifMinGhcVer "711" "-fshow-warning-groups"
, ifMinGhcVer "801" "-fdiagnostics-color=never"
, ifMinGhcVer "801" "-fno-diagnostics-show-caret"
, pure "-dno-debug-output"
]
-- Command line arguments for invoking the @runtest.py@ script. A lot of this
-- mirrors @testsuite/mk/test.mk@.
runTestBuilderArgs :: Args
runTestBuilderArgs = builder RunTest ? do
pkgs <- expr $ stagePackages Stage1
libTests <- expr $ filterM doesDirectoryExist $ concat
[ [ pkgPath pkg -/- "tests", pkgPath pkg -/- "tests-ghc" ]
| pkg <- pkgs, isLibrary pkg, pkg /= rts, pkg /= libffi ]
flav <- expr flavour
rtsWays <- expr testRTSSettings
libWays <- libraryWays flav
let hasRtsWay w = elem w rtsWays
hasLibWay w = elem w libWays
debugged = ghcDebugged flav
hasDynamic <- getBooleanSetting TestGhcDynamic
hasDynamicByDefault <- getBooleanSetting TestGhcDynamicByDefault
withNativeCodeGen <- getBooleanSetting TestGhcWithNativeCodeGen
withInterpreter <- getBooleanSetting TestGhcWithInterpreter
unregisterised <- getBooleanSetting TestGhcUnregisterised
withSMP <- getBooleanSetting TestGhcWithSMP
windows <- expr windowsHost
darwin <- expr osxHost
threads <- shakeThreads <$> expr getShakeOptions
os <- getTestSetting TestHostOS
arch <- getTestSetting TestTargetARCH_CPP
platform <- getTestSetting TestTARGETPLATFORM
wordsize <- getTestSetting TestWORDSIZE
top <- expr $ topDirectory
ghcFlags <- expr runTestGhcFlags
timeoutProg <- expr buildRoot <&> (-/- timeoutPath)
let asZeroOne s b = s ++ zeroOne b
-- TODO: set CABAL_MINIMAL_BUILD/CABAL_PLUGIN_BUILD
mconcat [ arg $ "testsuite/driver/runtests.py"
, arg $ "--rootdir=" ++ ("testsuite" -/- "tests")
, pure ["--rootdir=" ++ test | test <- libTests]
, arg "-e", arg $ "windows=" ++ show windows
, arg "-e", arg $ "darwin=" ++ show darwin
, arg "-e", arg $ "config.local=True"
, arg "-e", arg $ "config.cleanup=False" -- Don't clean up.
, arg "-e", arg $ "config.compiler_debugged=" ++ quote (yesNo debugged)
, arg "-e", arg $ "ghc_debugged=" ++ quote (yesNo debugged)
, arg "-e", arg $ asZeroOne "ghc_with_native_codegen=" withNativeCodeGen
, arg "-e", arg $ "config.have_interp=" ++ show withInterpreter
, arg "-e", arg $ "config.unregisterised=" ++ show unregisterised
, arg "-e", arg $ "ghc_compiler_always_flags=" ++ quote ghcFlags
, arg "-e", arg $ asZeroOne "ghc_with_dynamic_rts=" (hasRtsWay "dyn")
, arg "-e", arg $ asZeroOne "ghc_with_threaded_rts=" (hasRtsWay "thr")
, arg "-e", arg $ asZeroOne "config.have_vanilla=" (hasLibWay vanilla)
, arg "-e", arg $ asZeroOne "config.have_dynamic=" (hasLibWay dynamic)
, arg "-e", arg $ asZeroOne "config.have_profiling=" (hasLibWay profiling)
, arg "-e", arg $ asZeroOne "ghc_with_smp=" withSMP
, arg "-e", arg $ "ghc_with_llvm=0" -- TODO: support LLVM
, arg "-e", arg $ "config.ghc_dynamic_by_default=" ++ show hasDynamicByDefault
, arg "-e", arg $ "config.ghc_dynamic=" ++ show hasDynamic
-- Use default value, see:
-- https://github.com/ghc/ghc/blob/master/testsuite/mk/boilerplate.mk
, arg "-e", arg $ "config.in_tree_compiler=True"
, arg "-e", arg $ "config.top=" ++ show (top -/- "testsuite")
, arg "-e", arg $ "config.wordsize=" ++ show wordsize
, arg "-e", arg $ "config.os=" ++ show os
, arg "-e", arg $ "config.arch=" ++ show arch
, arg "-e", arg $ "config.platform=" ++ show platform
, arg "--config", arg $ "gs=gs" -- Use the default value as in test.mk
, arg "--config", arg $ "timeout_prog=" ++ show (top -/- timeoutProg)
, arg $ "--threads=" ++ show threads
, getTestArgs -- User-provided arguments from command line.
]
-- | Command line arguments for running GHC's test script.
getTestArgs :: Args
getTestArgs = do
args <- expr $ userSetting defaultTestArgs
bindir <- expr $ setBinaryDirectory (testCompiler args)
compiler <- expr $ setCompiler (testCompiler args)
globalVerbosity <- shakeVerbosity <$> expr getShakeOptions
let configFileArg= ["--config-file=" ++ (testConfigFile args)]
testOnlyArg = case testOnly args of
Just cases -> map ("--only=" ++) (words cases)
Nothing -> []
onlyPerfArg = if testOnlyPerf args
then Just "--only-perf-tests"
else Nothing
skipPerfArg = if testSkipPerf args
then Just "--skip-perf-tests"
else Nothing
speedArg = ["-e", "config.speed=" ++ setTestSpeed (testSpeed args)]
summaryArg = case testSummary args of
Just filepath -> Just $ "--summary-file" ++ quote filepath
Nothing -> Just $ "--summary-file=testsuite_summary.txt"
junitArg = case testJUnit args of
Just filepath -> Just $ "--junit " ++ quote filepath
Nothing -> Nothing
configArgs = concat [["-e", configArg] | configArg <- testConfigs args]
verbosityArg = case testVerbosity args of
Nothing -> Just $ "--verbose=" ++ show (fromEnum globalVerbosity)
Just verbosity -> Just $ "--verbose=" ++ verbosity
wayArgs = map ("--way=" ++) (testWays args)
compilerArg = ["--config", "compiler=" ++ show (compiler)]
ghcPkgArg = ["--config", "ghc_pkg=" ++ show (bindir -/- "ghc-pkg")]
haddockArg = ["--config", "haddock=" ++ show (bindir -/- "haddock")]
hp2psArg = ["--config", "hp2ps=" ++ show (bindir -/- "hp2ps")]
hpcArg = ["--config", "hpc=" ++ show (bindir -/- "hpc")]
pure $ configFileArg ++ testOnlyArg ++ speedArg
++ catMaybes [ onlyPerfArg, skipPerfArg, summaryArg
, junitArg, verbosityArg ]
++ configArgs ++ wayArgs ++ compilerArg ++ ghcPkgArg
++ haddockArg ++ hp2psArg ++ hpcArg
-- TODO: Switch to 'Stage' as the first argument instead of 'String'.
-- | Directory to look for Binaries
-- | We assume that required programs are present in the same binary directory
-- | in which ghc is stored and that they have their conventional name.
-- | QUESTION : packages can be named different from their conventional names.
-- | For example, ghc-pkg can be named as ghc-pkg-version. In such cases, it will
-- | be impossible to search the binary. Only possible way will be to take user
-- | inputs for these directory also. boilerplate soes not account for this
-- | problem, but simply returns an error. How should we handle such cases?
setBinaryDirectory :: String -> Action FilePath
setBinaryDirectory "stage0" = takeDirectory <$> setting SystemGhc
setBinaryDirectory "stage1" = liftM2 (-/-) topDirectory (stageBinPath Stage0)
setBinaryDirectory "stage2" = liftM2 (-/-) topDirectory (stageBinPath Stage1)
setBinaryDirectory compiler = pure $ parentPath compiler
-- TODO: Switch to 'Stage' as the first argument instead of 'String'.
-- | Set Test Compiler.
setCompiler :: String -> Action FilePath
setCompiler "stage0" = setting SystemGhc
setCompiler "stage1" = liftM2 (-/-) topDirectory (fullPath Stage0 ghc)
setCompiler "stage2" = liftM2 (-/-) topDirectory (fullPath Stage1 ghc)
setCompiler compiler = pure compiler
-- | Set speed for test
setTestSpeed :: TestSpeed -> String
setTestSpeed Slow = "0"
setTestSpeed Average = "1"
setTestSpeed Fast = "2"
-- | Returns parent path of test compiler
-- | TODO: Is there a simpler way to find parent directory?
parentPath :: String -> String
parentPath path = intercalate "/" $ init $ splitOn "/" path
-- | TODO: Move to Hadrian utilities.
fullPath :: Stage -> Package -> Action FilePath
fullPath stage pkg = programPath =<< programContext stage pkg
|
snowleopard/hadrian
|
src/Settings/Builders/RunTest.hs
|
mit
| 10,054
| 0
| 17
| 2,734
| 2,174
| 1,093
| 1,081
| 150
| 7
|
-- | This provides what is needed for the output of 'hprotoc' to
-- compile. This and the Prelude will both be imported qualified as
-- P', the prime ensuring no name conflicts are possible.
module Text.ProtocolBuffers.Header
( append, emptyBS
, pack, fromMaybe, ap
, fromDistinctAscList, member
, throwError,catchError
, choice, sepEndBy, spaces, try
, module Data.Generics
, module Text.ProtocolBuffers.Basic
, module Text.ProtocolBuffers.Extensions
, module Text.ProtocolBuffers.Identifiers
, module Text.ProtocolBuffers.Reflections
, module Text.ProtocolBuffers.TextMessage
, module Text.ProtocolBuffers.Unknown
, module Text.ProtocolBuffers.WireMessage
) where
import Control.Monad(ap)
import Control.Monad.Error.Class(throwError,catchError)
import Data.ByteString.Lazy(empty)
import Data.ByteString.Lazy.Char8(pack)
import Data.Generics(Data(..))
import Data.Maybe(fromMaybe)
import Data.Sequence((|>)) -- for append, see below
import Data.Set(fromDistinctAscList,member)
import Text.Parsec(choice, sepEndBy, spaces, try)
import Text.ProtocolBuffers.Basic -- all
import Text.ProtocolBuffers.Extensions
( wireSizeExtField,wirePutExtField,loadExtension,notExtension
, wireGetKeyToUnPacked, wireGetKeyToPacked
, GPB,Key(..),ExtField,ExtendMessage(..),MessageAPI(..),ExtKey(wireGetKey),PackedSeq )
import Text.ProtocolBuffers.Identifiers(FIName(..),MName(..),FName(..))
import Text.ProtocolBuffers.Reflections
( ReflectDescriptor(..),ReflectEnum(..),EnumInfo(..),ProtoName(..)
, GetMessageInfo(GetMessageInfo),DescriptorInfo(extRanges),makePNF )
import Text.ProtocolBuffers.TextMessage -- all
import Text.ProtocolBuffers.Unknown
( UnknownField,UnknownMessage(..),wireSizeUnknownField,wirePutUnknownField,catch'Unknown )
import Text.ProtocolBuffers.WireMessage
( Wire(..)
, prependMessageSize,putSize,splitWireTag
, wireSizeReq,wireSizeOpt,wireSizeRep
, wirePutReq,wirePutOpt,wirePutRep
, wirePutPacked,wireSizePacked
, getMessageWith,getBareMessageWith,wireGetEnum,wireGetPackedEnum
, wireSizeErr,wirePutErr,wireGetErr
, unknown,unknownField
, fieldIdOf)
{-# INLINE append #-}
append :: Seq a -> a -> Seq a
append = (|>)
{-# INLINE emptyBS #-}
emptyBS :: ByteString
emptyBS = Data.ByteString.Lazy.empty
|
timjb/protocol-buffers
|
Text/ProtocolBuffers/Header.hs
|
apache-2.0
| 2,296
| 0
| 7
| 275
| 529
| 354
| 175
| 51
| 1
|
{-# Language ViewPatterns, TypeOperators, KindSignatures, PolyKinds,
TypeInType, StandaloneDeriving, GADTs, RebindableSyntax,
RankNTypes, LambdaCase, PatternSynonyms, TypeApplications #-}
module T12698 where
import GHC.Types
import Prelude hiding ( fromInteger )
import Data.Type.Equality
import Data.Kind
import qualified Prelude
class Ty (a :: k) where ty :: T a
instance Ty Int where ty = TI
instance Ty Bool where ty = TB
instance Ty a => Ty [a] where ty = TA TL ty
instance Ty [] where ty = TL
instance Ty (,) where ty = TP
data AppResult (t :: k) where
App :: T a -> T b -> AppResult (a b)
data T :: forall k. k -> Type where
TI :: T Int
TB :: T Bool
TL :: T []
TP :: T (,)
TA :: T f -> T x -> T (f x)
deriving instance Show (T a)
splitApp :: T a -> Maybe (AppResult a)
splitApp = \case
TI -> Nothing
TB -> Nothing
TL -> Nothing
TP -> Nothing
TA f x -> Just (App f x)
data (a :: k1) :~~: (b :: k2) where
HRefl :: a :~~: a
eqT :: T a -> T b -> Maybe (a :~~: b)
eqT a b =
case (a, b) of
(TI, TI) -> Just HRefl
(TB, TB) -> Just HRefl
(TL, TL) -> Just HRefl
(TP, TP) -> Just HRefl
pattern List :: () => [] ~~ b => T b
pattern List <- (eqT (ty @(Type -> Type) @[]) -> Just HRefl)
where List = ty
pattern Int :: () => Int ~~ b => T b
pattern Int <- (eqT (ty @Type @Int) -> Just HRefl)
where Int = ty
pattern (:<->:) :: () => fx ~ f x => T f -> T x -> T fx
pattern f :<->: x <- (splitApp -> Just (App f x))
where f :<->: x = TA f x
pattern Foo <- List :<->: Int
|
olsner/ghc
|
testsuite/tests/patsyn/should_compile/T12698.hs
|
bsd-3-clause
| 1,547
| 0
| 13
| 407
| 721
| 381
| 340
| -1
| -1
|
-- | Build instance tycons for the PData and PDatas type families.
--
-- TODO: the PData and PDatas cases are very similar.
-- We should be able to factor out the common parts.
module Vectorise.Generic.PData
( buildPDataTyCon
, buildPDatasTyCon )
where
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Utils
import Vectorise.Env( GlobalEnv( global_fam_inst_env ) )
import BasicTypes
import BuildTyCl
import DataCon
import TyCon
import Type
import FamInst
import FamInstEnv
import TcMType
import Name
import Util
import MonadUtils
import Control.Monad
-- buildPDataTyCon ------------------------------------------------------------
-- | Build the PData instance tycon for a given type constructor.
buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDataTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDataTyConOcc orig_name
rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr
pdata <- builtin pdataTyCon
buildDataFamInst name' pdata vect_tc rhs
where
orig_name = tyConName orig_tc
buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst
buildDataFamInst name' fam_tc vect_tc rhs
= do { axiom_name <- mkDerivedName mkInstTyCoOcc name'
; (_, tyvars') <- liftDs $ tcInstSigTyVarsLoc (getSrcSpan name') tyvars
; let ax = mkSingleCoAxiom Representational axiom_name tyvars' fam_tc pat_tys rep_ty
tys' = mkTyVarTys tyvars'
rep_ty = mkTyConApp rep_tc tys'
pat_tys = [mkTyConApp vect_tc tys']
rep_tc = buildAlgTyCon name'
tyvars'
(map (const Nominal) tyvars')
Nothing
[] -- no stupid theta
rhs
rec_flag -- FIXME: is this ok?
False -- Not promotable
False -- not GADT syntax
(DataFamInstTyCon ax fam_tc pat_tys)
; liftDs $ newFamInst (DataFamilyInst rep_tc) ax }
where
tyvars = tyConTyVars vect_tc
rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDataTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDataDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDataDataConOcc orig_name
comp_tys <- mkSumTys repr_sel_ty mkPDataType repr
fam_envs <- readGEnv global_fam_inst_env
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
NotPromoted -- not promotable
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- buildPDatasTyCon -----------------------------------------------------------
-- | Build the PDatas instance tycon for a given type constructor.
buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDatasTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDatasTyConOcc orig_name
rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr
pdatas <- builtin pdatasTyCon
buildDataFamInst name' pdatas vect_tc rhs
where
orig_name = tyConName orig_tc
buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDatasTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDatasDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name
comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr
fam_envs <- readGEnv global_fam_inst_env
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
NotPromoted -- not promotable
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- Utils ----------------------------------------------------------------------
-- | Flatten a SumRepr into a list of data constructor types.
mkSumTys
:: (SumRepr -> Type)
-> (Type -> VM Type)
-> SumRepr
-> VM [Type]
mkSumTys repr_selX_ty mkTc repr
= sum_tys repr
where
sum_tys EmptySum = return []
sum_tys (UnarySum r) = con_tys r
sum_tys d@(Sum { repr_cons = cons })
= liftM (repr_selX_ty d :) (concatMapM con_tys cons)
con_tys (ConRepr _ r) = prod_tys r
prod_tys EmptyProd = return []
prod_tys (UnaryProd r) = liftM singleton (comp_ty r)
prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps
comp_ty r = mkTc (compOrigType r)
{-
mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
mk_fam_inst fam_tc arg_tc
= (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
-}
|
AlexanderPankiv/ghc
|
compiler/vectorise/Vectorise/Generic/PData.hs
|
bsd-3-clause
| 6,590
| 0
| 14
| 2,256
| 1,336
| 677
| 659
| 123
| 5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.