code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Test suite for "Stack.Solver"
module Stack.SolverSpec where
import Data.Text (unpack)
import Stack.Prelude
import Stack.Types.FlagName
import Stack.Types.PackageName
import Stack.Types.Version
import Test.Hspec
import qualified Data.Map as Map
import Stack.Solver
spec :: Spec
spec =
describe "Stack.Solver" $ do
successfulExample
"text-1.2.1.1 (latest: 1.2.2.0) -integer-simple (via: parsec-3.1.9) (new package)"
$(mkPackageName "text")
$(mkVersion "1.2.1.1")
[ ($(mkFlagName "integer-simple"), False)
]
successfulExample
"hspec-snap-1.0.0.0 *test (via: servant-snap-0.5) (new package)"
$(mkPackageName "hspec-snap")
$(mkVersion "1.0.0.0")
[]
successfulExample
"time-locale-compat-0.1.1.1 -old-locale (via: http-api-data-0.2.2) (new package)"
$(mkPackageName "time-locale-compat")
$(mkVersion "0.1.1.1")
[ ($(mkFlagName "old-locale"), False)
]
successfulExample
"flowdock-rest-0.2.0.0 -aeson-compat *test (via: haxl-fxtra-0.0.0.0) (new package)"
$(mkPackageName "flowdock-rest")
$(mkVersion "0.2.0.0")
[ ($(mkFlagName "aeson-compat"), False)
]
where
successfulExample input pkgName pkgVersion flags =
it ("parses " ++ unpack input) $
parseCabalOutputLine input `shouldBe` Right (pkgName, (pkgVersion, Map.fromList flags))
|
MichielDerhaeg/stack
|
src/test/Stack/SolverSpec.hs
|
Haskell
|
bsd-3-clause
| 1,546
|
module Case3 where
data T = C2 Int
caseIt x
= case x of
42 -> 1 + (f ((error
"C1 no longer defined for T at line: 3")
1
2))
where f x = 9
|
kmate/HaRe
|
old/testing/removeCon/Case3AST.hs
|
Haskell
|
bsd-3-clause
| 280
|
module AddOneParameter.C2 where
import AddOneParameter.D2
sumSquares1 (x:xs) = (sq sq_f) x + sumSquares1 xs
sumSquares1 [] = 0
sq_f_1 = 0
|
RefactoringTools/HaRe
|
test/testdata/AddOneParameter/C2.expected.hs
|
Haskell
|
bsd-3-clause
| 145
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, MagicHash, NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Event.IntMap
-- Copyright : (c) Daan Leijen 2002
-- (c) Andriy Palamarchuk 2008
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- An efficient implementation of maps from integer keys to values.
--
-- Since many function names (but not the type name) clash with
-- "Prelude" names, this module is usually imported @qualified@, e.g.
--
-- > import Data.IntMap (IntMap)
-- > import qualified Data.IntMap as IntMap
--
-- The implementation is based on /big-endian patricia trees/. This data
-- structure performs especially well on binary operations like 'union'
-- and 'intersection'. However, my benchmarks show that it is also
-- (much) faster on insertions and deletions when compared to a generic
-- size-balanced map implementation (see "Data.Map").
--
-- * Chris Okasaki and Andy Gill, \"/Fast Mergeable Integer Maps/\",
-- Workshop on ML, September 1998, pages 77-86,
-- <http://citeseer.ist.psu.edu/okasaki98fast.html>
--
-- * D.R. Morrison, \"/PATRICIA -- Practical Algorithm To Retrieve
-- Information Coded In Alphanumeric/\", Journal of the ACM, 15(4),
-- October 1968, pages 514-534.
--
-- Operation comments contain the operation time complexity in
-- the Big-O notation <http://en.wikipedia.org/wiki/Big_O_notation>.
-- Many operations have a worst-case complexity of /O(min(n,W))/.
-- This means that the operation can become linear in the number of
-- elements with a maximum of /W/ -- the number of bits in an 'Int'
-- (32 or 64).
--
-----------------------------------------------------------------------------
module GHC.Event.IntMap
(
-- * Map type
IntMap
, Key
-- * Query
, lookup
, member
-- * Construction
, empty
-- * Insertion
, insertWith
-- * Delete\/Update
, delete
, updateWith
-- * Traversal
-- ** Fold
, foldWithKey
-- * Conversion
, keys
) where
import Data.Bits
import Data.Maybe (Maybe(..))
import GHC.Base hiding (foldr)
import GHC.Num (Num(..))
import GHC.Real (fromIntegral)
import GHC.Show (Show(showsPrec), showParen, shows, showString)
#if __GLASGOW_HASKELL__
import GHC.Word (Word(..))
#else
import Data.Word
#endif
-- | A @Nat@ is a natural machine word (an unsigned Int)
type Nat = Word
natFromInt :: Key -> Nat
natFromInt i = fromIntegral i
intFromNat :: Nat -> Key
intFromNat w = fromIntegral w
shiftRL :: Nat -> Key -> Nat
#if __GLASGOW_HASKELL__
-- GHC: use unboxing to get @shiftRL@ inlined.
shiftRL (W# x) (I# i) = W# (shiftRL# x i)
#else
shiftRL x i = shiftR x i
#endif
------------------------------------------------------------------------
-- Types
-- | A map of integers to values @a@.
data IntMap a = Nil
| Tip {-# UNPACK #-} !Key !a
| Bin {-# UNPACK #-} !Prefix
{-# UNPACK #-} !Mask
!(IntMap a)
!(IntMap a)
type Prefix = Int
type Mask = Int
type Key = Int
------------------------------------------------------------------------
-- Query
-- | /O(min(n,W))/ Lookup the value at a key in the map. See also
-- 'Data.Map.lookup'.
lookup :: Key -> IntMap a -> Maybe a
lookup k t = let nk = natFromInt k in seq nk (lookupN nk t)
lookupN :: Nat -> IntMap a -> Maybe a
lookupN k t
= case t of
Bin _ m l r
| zeroN k (natFromInt m) -> lookupN k l
| otherwise -> lookupN k r
Tip kx x
| (k == natFromInt kx) -> Just x
| otherwise -> Nothing
Nil -> Nothing
-- | /O(min(n,W))/. Is the key a member of the map?
--
-- > member 5 (fromList [(5,'a'), (3,'b')]) == True
-- > member 1 (fromList [(5,'a'), (3,'b')]) == False
member :: Key -> IntMap a -> Bool
member k m
= case lookup k m of
Nothing -> False
Just _ -> True
------------------------------------------------------------------------
-- Construction
-- | /O(1)/ The empty map.
--
-- > empty == fromList []
-- > size empty == 0
empty :: IntMap a
empty = Nil
------------------------------------------------------------------------
-- Insert
-- | /O(min(n,W))/ Insert with a function, combining new value and old
-- value. @insertWith f key value mp@ will insert the pair (key,
-- value) into @mp@ if key does not exist in the map. If the key does
-- exist, the function will insert the pair (key, f new_value
-- old_value). The result is a pair where the first element is the
-- old value, if one was present, and the second is the modified map.
insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)
insertWith f k x t = case t of
Bin p m l r
| nomatch k p m -> (Nothing, join k (Tip k x) p t)
| zero k m -> let (found, l') = insertWith f k x l
in (found, Bin p m l' r)
| otherwise -> let (found, r') = insertWith f k x r
in (found, Bin p m l r')
Tip ky y
| k == ky -> (Just y, Tip k (f x y))
| otherwise -> (Nothing, join k (Tip k x) ky t)
Nil -> (Nothing, Tip k x)
------------------------------------------------------------------------
-- Delete/Update
-- | /O(min(n,W))/. Delete a key and its value from the map. When the
-- key is not a member of the map, the original map is returned. The
-- result is a pair where the first element is the value associated
-- with the deleted key, if one existed, and the second element is the
-- modified map.
delete :: Key -> IntMap a -> (Maybe a, IntMap a)
delete k t = case t of
Bin p m l r
| nomatch k p m -> (Nothing, t)
| zero k m -> let (found, l') = delete k l
in (found, bin p m l' r)
| otherwise -> let (found, r') = delete k r
in (found, bin p m l r')
Tip ky y
| k == ky -> (Just y, Nil)
| otherwise -> (Nothing, t)
Nil -> (Nothing, Nil)
updateWith :: (a -> Maybe a) -> Key -> IntMap a -> (Maybe a, IntMap a)
updateWith f k t = case t of
Bin p m l r
| nomatch k p m -> (Nothing, t)
| zero k m -> let (found, l') = updateWith f k l
in (found, bin p m l' r)
| otherwise -> let (found, r') = updateWith f k r
in (found, bin p m l r')
Tip ky y
| k == ky -> case (f y) of
Just y' -> (Just y, Tip ky y')
Nothing -> (Just y, Nil)
| otherwise -> (Nothing, t)
Nil -> (Nothing, Nil)
-- | /O(n)/. Fold the keys and values in the map, such that
-- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
-- For example,
--
-- > keys map = foldWithKey (\k x ks -> k:ks) [] map
--
-- > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
-- > foldWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
foldWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldWithKey f z t
= foldr f z t
-- | /O(n)/. Convert the map to a list of key\/value pairs.
--
-- > toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
-- > toList empty == []
toList :: IntMap a -> [(Key,a)]
toList t
= foldWithKey (\k x xs -> (k,x):xs) [] t
foldr :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldr f z t
= case t of
Bin 0 m l r | m < 0 -> foldr' f (foldr' f z l) r -- put negative numbers before.
Bin _ _ _ _ -> foldr' f z t
Tip k x -> f k x z
Nil -> z
foldr' :: (Key -> a -> b -> b) -> b -> IntMap a -> b
foldr' f z t
= case t of
Bin _ _ l r -> foldr' f (foldr' f z r) l
Tip k x -> f k x z
Nil -> z
-- | /O(n)/. Return all keys of the map in ascending order.
--
-- > keys (fromList [(5,"a"), (3,"b")]) == [3,5]
-- > keys empty == []
keys :: IntMap a -> [Key]
keys m
= foldWithKey (\k _ ks -> k:ks) [] m
------------------------------------------------------------------------
-- Eq
instance Eq a => Eq (IntMap a) where
t1 == t2 = equal t1 t2
t1 /= t2 = nequal t1 t2
equal :: Eq a => IntMap a -> IntMap a -> Bool
equal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
= (m1 == m2) && (p1 == p2) && (equal l1 l2) && (equal r1 r2)
equal (Tip kx x) (Tip ky y)
= (kx == ky) && (x==y)
equal Nil Nil = True
equal _ _ = False
nequal :: Eq a => IntMap a -> IntMap a -> Bool
nequal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
= (m1 /= m2) || (p1 /= p2) || (nequal l1 l2) || (nequal r1 r2)
nequal (Tip kx x) (Tip ky y)
= (kx /= ky) || (x/=y)
nequal Nil Nil = False
nequal _ _ = True
instance Show a => Show (IntMap a) where
showsPrec d m = showParen (d > 10) $
showString "fromList " . shows (toList m)
------------------------------------------------------------------------
-- Utility functions
join :: Prefix -> IntMap a -> Prefix -> IntMap a -> IntMap a
join p1 t1 p2 t2
| zero p1 m = Bin p m t1 t2
| otherwise = Bin p m t2 t1
where
m = branchMask p1 p2
p = mask p1 m
-- | @bin@ assures that we never have empty trees within a tree.
bin :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
bin _ _ l Nil = l
bin _ _ Nil r = r
bin p m l r = Bin p m l r
------------------------------------------------------------------------
-- Endian independent bit twiddling
zero :: Key -> Mask -> Bool
zero i m = (natFromInt i) .&. (natFromInt m) == 0
nomatch :: Key -> Prefix -> Mask -> Bool
nomatch i p m = (mask i m) /= p
mask :: Key -> Mask -> Prefix
mask i m = maskW (natFromInt i) (natFromInt m)
zeroN :: Nat -> Nat -> Bool
zeroN i m = (i .&. m) == 0
------------------------------------------------------------------------
-- Big endian operations
maskW :: Nat -> Nat -> Prefix
maskW i m = intFromNat (i .&. (complement (m-1) `xor` m))
branchMask :: Prefix -> Prefix -> Mask
branchMask p1 p2
= intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
{-
Finding the highest bit mask in a word [x] can be done efficiently in
three ways:
* convert to a floating point value and the mantissa tells us the
[log2(x)] that corresponds with the highest bit position. The mantissa
is retrieved either via the standard C function [frexp] or by some bit
twiddling on IEEE compatible numbers (float). Note that one needs to
use at least [double] precision for an accurate mantissa of 32 bit
numbers.
* use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
* use processor specific assembler instruction (asm).
The most portable way would be [bit], but is it efficient enough?
I have measured the cycle counts of the different methods on an AMD
Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
highestBitMask: method cycles
--------------
frexp 200
float 33
bit 11
asm 12
Wow, the bit twiddling is on today's RISC like machines even faster
than a single CISC instruction (BSR)!
-}
-- | @highestBitMask@ returns a word where only the highest bit is
-- set. It is found by first setting all bits in lower positions than
-- the highest bit and than taking an exclusive or with the original
-- value. Allthough the function may look expensive, GHC compiles
-- this into excellent C code that subsequently compiled into highly
-- efficient machine code. The algorithm is derived from Jorg Arndt's
-- FXT library.
highestBitMask :: Nat -> Nat
highestBitMask x0
= case (x0 .|. shiftRL x0 1) of
x1 -> case (x1 .|. shiftRL x1 2) of
x2 -> case (x2 .|. shiftRL x2 4) of
x3 -> case (x3 .|. shiftRL x3 8) of
x4 -> case (x4 .|. shiftRL x4 16) of
x5 -> case (x5 .|. shiftRL x5 32) of -- for 64 bit platforms
x6 -> (x6 `xor` (shiftRL x6 1))
|
mightymoose/liquidhaskell
|
benchmarks/ghc-7.4.1/Event/IntMap.hs
|
Haskell
|
bsd-3-clause
| 12,045
|
f :: Int -> Int -> Int
f x y = x + y
g :: (Int, Int) -> Int
g (x,y) = x + y
main = do
print $ curry g 3 4
print $ uncurry f (3,4)
|
manyoo/ghcjs
|
test/fay/curry.hs
|
Haskell
|
mit
| 137
|
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses, FlexibleInstances #-}
module T13526 where
class C a where
op :: a -> a
instance {-# OVERLAPPING #-} C [Char] where
op x = x
instance C a => C [a] where
op (x:xs) = [op x]
instance C a => C (Maybe a) where
op x = error "urk"
-- We should get no complaint
foo :: C [a] => a -> [a]
foo x = op [x]
bar :: C (Maybe a) => a -> Maybe a
bar x = op (Just x)
|
ezyang/ghc
|
testsuite/tests/typecheck/should_compile/T13526.hs
|
Haskell
|
bsd-3-clause
| 418
|
----------------------------------------------------------------------------
-- demo_cqm_recipient.hs demonstrator code how to use CMQ.
-- Copyright : (c) 2012 Joerg Fritsch
--
-- License : BSD-style
-- Maintainer : J.Fritsch@cs.cardiff.ac.uk
-- Stability : experimental
-- Portability : GHC
--
-- Receives and prints UDP messages.
-- Messages can be shown on the screen w e.g. grep -v Nothing
-----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import CMQ
import Network.Socket hiding (send, sendTo, recv, recvFrom)
import Control.Monad
import Data.Maybe
main = withSocketsDo $ do
qs <- socket AF_INET Datagram defaultProtocol
hostAddr <- inet_addr "192.168.35.85"
bindSocket qs (SockAddrInet 4711 hostAddr)
(token) <- newRq qs 512 200
forever $ do
msg <- cwPop token
print msg
|
viloocity/CMQ
|
examples/0.0.1/demo_cmq_recipient.hs
|
Haskell
|
mit
| 893
|
{-# LANGUAGE DeriveGeneric, ViewPatterns, RecordWildCards, OverloadedStrings, CPP #-}
module ReportTypes where
import qualified Data.Map as M
import Data.Aeson
import Data.Aeson.Types
import GHC.Generics
import Text.Printf
import Data.List
import Data.Char
import Paths
import ReadResult
import qualified BenchmarkSettings as S
data ClientSettings = ClientSettings
{ title :: String
, revisionInfo :: String
, diffLink :: Maybe String
}
deriving (Generic)
instance ToJSON ClientSettings
data GlobalReport = GlobalReport
{ settings :: Maybe ClientSettings
, benchmarks :: Maybe (M.Map BenchName ())
, revisions :: Maybe (M.Map Hash RevReport)
, benchGroups :: Maybe [BenchGroup]
, branches :: Maybe (M.Map BranchName BranchReport)
}
instance ToJSON GlobalReport where
toJSON (GlobalReport {..}) = object $
( "settings" .=? settings ) ++
( "benchmarks" .=? benchmarks ) ++
( "revisions" .=? revisions ) ++
( "benchGroups" .=? benchGroups ) ++
( "branches" .=? branches )
where
k .=? Just v = [ k .= toJSON v ]
_ .=? Nothing = []
emptyGlobalReport :: GlobalReport
emptyGlobalReport = GlobalReport Nothing Nothing Nothing Nothing Nothing
data SummaryStats = SummaryStats
{ totalCount :: Int
, improvementCount :: Int
, regressionCount :: Int
, summaryDesc :: String
}
deriving (Show, Generic)
instance ToJSON SummaryStats
instance FromJSON SummaryStats
{-
sumStats :: [SummaryStats] -> SummaryStats
sumStats = foldl' go (SummaryStats 0 0 0)
where go (SummaryStats a b c) (SummaryStats a' b' c') =
SummaryStats (a + a') (b + b') (c + c')
-}
data Status = Built | Failed | Waiting
deriving (Show, Generic)
instance ToJSON Status
instance FromJSON Status
data Summary = Summary
{ hash :: Hash
, gitDate :: Integer
, gitSubject :: String
, stats :: SummaryStats
, parents :: [Hash]
-- , status :: Status
}
deriving (Generic)
instance ToJSON Summary
instance FromJSON Summary
data RevReport = RevReport
{ summary :: Summary
, gitLog :: String
, benchResults :: M.Map BenchName BenchResult
}
deriving (Generic)
instance ToJSON RevReport
instance FromJSON RevReport
data BranchReport = BranchReport
{ branchHash :: Hash
, mergeBaseHash :: Hash
, branchStats :: SummaryStats
, commitCount :: Int
}
deriving (Generic)
instance ToJSON BranchReport
instance FromJSON BranchReport
data ChangeType = Improvement | Boring | Regression
deriving (Eq, Generic)
instance ToJSON ChangeType
instance FromJSON ChangeType
data BenchGroup = BenchGroup
{ groupName :: String
, groupMembers :: [BenchName]
, groupUnitFull :: Maybe String
}
deriving (Generic)
instance ToJSON BenchGroup
instance FromJSON BenchGroup
data BenchResult = BenchResult
{ name :: String
, value :: BenchValue
, unit :: String
, important :: Bool
}
deriving (Generic)
instance ToJSON BenchResult where
toJSON = genericToJSON defaultOptions
#if MIN_VERSION_aeson(0,10,0)
toEncoding = genericToEncoding defaultOptions
#endif
instance FromJSON BenchResult where
parseJSON = genericParseJSON defaultOptions
data BenchComparison = BenchComparison
{ changeName :: String
, change :: String
, changeType :: ChangeType
, changeImportant :: Bool
}
-- A smaller BenchResult
-- (This is a hack: BenchResult no longer carries a changeType. But it is convenient to
-- have that in the graph report, for the tallying for the graph summary. But all not very
-- satisfactory.)
data GraphPoint = GraphPoint
{ gpValue :: BenchValue
, gpChangeType :: ChangeType
}
deriving (Generic)
instance ToJSON GraphPoint where
toJSON = genericToJSON graphPointOptions
#if MIN_VERSION_aeson(0,10,0)
toEncoding = genericToEncoding graphPointOptions
#endif
instance FromJSON GraphPoint where
parseJSON = genericParseJSON graphPointOptions
graphPointOptions = defaultOptions { fieldLabelModifier = fixup }
where fixup ('g':'p':c:cs) = toLower c : cs
invertChangeType :: ChangeType -> ChangeType
invertChangeType Improvement = Regression
invertChangeType Boring = Boring
invertChangeType Regression = Improvement
type Explanation = (String, ChangeType)
noExplanation :: Explanation
noExplanation = ("", Boring)
equalExplanation :: Explanation
equalExplanation = ("=", Boring)
explainSmallInt :: S.BenchSettings -> Integer -> Integer -> Explanation
explainSmallInt _ i1 i2
| i2 == i1 = equalExplanation
| i2 > i1 = ("+ " ++ show (i2 - i1), Improvement)
| i2 < i1 = ("- " ++ show (i1 - i2), Regression)
explainInt :: S.BenchSettings -> Integer -> Integer -> Explanation
explainInt s i1 i2 = explainFloat s (fromIntegral i1) (fromIntegral i2)
explainFloat :: S.BenchSettings -> Double -> Double -> Explanation
explainFloat _ 0 0 = equalExplanation
explainFloat _ 0 _ = ("+ ∞", Improvement)
explainFloat s f1 f2 = (change, typ)
where
change | abs perc < 0.01 = "="
| perc >= 0 = printf "+ %.2f%%" perc
| perc < 0 = printf "- %.2f%%" (-perc)
typ | perc >= 0, perc < th_up = Boring
| perc < 0, -perc < th_down = Boring
| perc >= 0 = Improvement
| perc < 0 = Regression
perc = 100 * ((f2 - f1) / f1)
th_up = S.threshold s
-- Adjusted threshold, to make sure that the inverse change is flagged
-- equivalently
th_down = (1-(1/(1+S.threshold s/100)))*100
toFloat :: BenchValue -> Double
toFloat (I i) = fromIntegral i
toFloat (F f) = f
explain :: S.BenchSettings -> BenchValue -> BenchValue -> (String, ChangeType)
explain s@(S.numberType -> S.SmallIntegralNT) (I i1) (I i2) = explainSmallInt s i1 i2
explain s@(S.numberType -> S.IntegralNT) (I i1) (I i2) = explainInt s i1 i2
-- Treat everything else as Floats, so that we do something sensible
-- even if the user did not set the numberType correctly:
explain s v1 v2 = explainFloat s (toFloat v1) (toFloat v2)
toResult :: S.BenchSettings -> String -> BenchValue -> BenchResult
toResult s name value = BenchResult
{ name = name
, value = value
, unit = S.unit s
, important = S.important s
}
makeComparison :: S.BenchSettings -> String -> BenchValue -> Maybe BenchValue -> BenchComparison
makeComparison s name value prev = BenchComparison
{ changeName = name
, change = change
, changeType = changeType
, changeImportant = S.important s
}
where
(change, changeType') =
case prev of
Just p -> explain s p value
Nothing -> noExplanation
changeType | S.smallerIsBetter s = invertChangeType changeType'
| otherwise = changeType'
toSummaryStats :: [BenchComparison] -> SummaryStats
toSummaryStats comps = SummaryStats
{ totalCount = length comps
, improvementCount = length
[ () | comp <- importantComps , changeType comp == Improvement ]
, regressionCount = length
[ () | comp <- importantComps , changeType comp == Regression ]
, summaryDesc = andMore "No significant changes" 5
[ changeName comp ++ ": " ++ change comp
| comp <- importantComps
, changeType comp `elem` [Improvement, Regression]
]
}
where importantComps = filter changeImportant comps
andMore :: String -> Int -> [String] -> String
andMore def _ [] = def
andMore _ n xs = intercalate "\n" (take n xs) ++ rest
where rest | length xs > n = "\nand " ++ show (length xs - n) ++ " more"
| otherwise = ""
{-
toGroup :: String -> [BenchResult] -> BenchGroup
toGroup n res = BenchGroup
{ groupName = n
, benchResults = res
, groupStats = SummaryStats
{ totalCount = length res
, improvementCount = length [ () | BenchResult { changeType = Improvement } <- res ]
, regressionCount = length [ () | BenchResult { changeType = Regression } <- res ]
}
}
-}
createBranchReport ::
S.Settings -> Hash -> Hash ->
ResultMap -> ResultMap ->
Int ->
BranchReport
createBranchReport settings this other thisM otherM commitCount = BranchReport
{ branchHash = this
, mergeBaseHash = other
, branchStats = toSummaryStats comparisons
, commitCount = commitCount
}
where
comparisons =
[ makeComparison s name value (M.lookup name otherM)
| (name, value) <- M.toAscList thisM
, let s = S.benchSettings settings name
]
createReport ::
S.Settings -> Hash -> [Hash] ->
ResultMap -> ResultMap ->
String -> String -> Integer ->
RevReport
createReport settings this parents thisM parentM log subject date = RevReport
{ summary = Summary
{ hash = this
, parents = parents
, stats = toSummaryStats comparisons
, gitSubject = subject
, gitDate = date
}
--, benchGroups = benchGroups
, benchResults = results
, gitLog = log
}
where
results = M.fromList
[ (name, toResult s name value)
| (name, value) <- M.toAscList thisM
, let s = S.benchSettings settings name
]
comparisons =
[ makeComparison s name value (M.lookup name parentM)
| (name, value) <- M.toAscList thisM
, let s = S.benchSettings settings name
]
summarize :: RevReport -> Summary
summarize (RevReport {..}) = summary
|
nomeata/gipeda
|
src/ReportTypes.hs
|
Haskell
|
mit
| 9,495
|
-- if we want to map an IO function
-- through a list we might make:
-- map print [1, 2, 3] will make [print 1, print 2, print 3]
-- we need to make instead:
-- sequence (map print [1, 2, 3, 4, 5])
-- or better yet:
main = mapM print [1, 2, 3]
|
fabriceleal/learn-you-a-haskell
|
09/mapMs.hs
|
Haskell
|
mit
| 255
|
{-# htermination addListToFM_C :: Ord a => (b -> b -> b) -> FiniteMap a b -> [(a,b)] -> FiniteMap a b #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addListToFM_C_1.hs
|
Haskell
|
mit
| 123
|
{-# LANGUAGE ViewPatterns #-}
module Core.LambdaLift.Abstract.Naive
( abstract
) where
import Common
import Core.AST
import Core.AnnotAST
import qualified Data.Set as S
abstract :: AnnotProgram (S.Set Name) Name -> Program Name
abstract = Program . map abstractSC . getProgramF
where abstractSC (SupercombF name args body) = Supercomb name args (abstractExpr body)
abstractExpr :: AnnotExpr (S.Set Name) Name -> Expr Name
abstractExpr (Annot (S.toList -> fv, e)) = case e of
EVarF v -> EVar v
ENumF n -> ENum n
EConstrF tag arity -> EConstr tag arity
EApF e1 e2 -> EAp (abstractExpr e1) (abstractExpr e2)
ELetF rec defs body -> ELet rec defs' body'
where defs' = [(x, abstractExpr e) | (x, e) <- defs]
body' = abstractExpr body
ECaseF e alts -> ECase (abstractExpr e) (map abstractAlter alts)
EAbsF args body -> foldl EAp e' (map EVar fv)
where e' = ELet False [(anonym, EAbs (fv ++ args) body')] (EVar anonym)
body' = abstractExpr body
abstractAlter :: AnnotAlter (S.Set Name) Name -> Alter Name
abstractAlter (AlterF tag xs body) = Alter tag xs (abstractExpr body)
|
meimisaki/Rin
|
src/Core/LambdaLift/Abstract/Naive.hs
|
Haskell
|
mit
| 1,117
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.DOMNamedFlowCollection
(js_item, item, js_namedItem, namedItem, js_getLength, getLength,
DOMNamedFlowCollection, castToDOMNamedFlowCollection,
gTypeDOMNamedFlowCollection)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"item\"]($2)" js_item ::
JSRef DOMNamedFlowCollection -> Word -> IO (JSRef WebKitNamedFlow)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitNamedFlowCollection.item Mozilla WebKitNamedFlowCollection.item documentation>
item ::
(MonadIO m) =>
DOMNamedFlowCollection -> Word -> m (Maybe WebKitNamedFlow)
item self index
= liftIO
((js_item (unDOMNamedFlowCollection self) index) >>= fromJSRef)
foreign import javascript unsafe "$1[\"namedItem\"]($2)"
js_namedItem ::
JSRef DOMNamedFlowCollection ->
JSString -> IO (JSRef WebKitNamedFlow)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitNamedFlowCollection.namedItem Mozilla WebKitNamedFlowCollection.namedItem documentation>
namedItem ::
(MonadIO m, ToJSString name) =>
DOMNamedFlowCollection -> name -> m (Maybe WebKitNamedFlow)
namedItem self name
= liftIO
((js_namedItem (unDOMNamedFlowCollection self) (toJSString name))
>>= fromJSRef)
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
JSRef DOMNamedFlowCollection -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitNamedFlowCollection.length Mozilla WebKitNamedFlowCollection.length documentation>
getLength :: (MonadIO m) => DOMNamedFlowCollection -> m Word
getLength self
= liftIO (js_getLength (unDOMNamedFlowCollection self))
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/DOMNamedFlowCollection.hs
|
Haskell
|
mit
| 2,503
|
module Compiler.Rum.StackMachine.Translator where
import Control.Monad.Extra (concatMapM)
import qualified Data.HashMap.Strict as HM
import Compiler.Rum.Internal.AST
import Compiler.Rum.Internal.Rumlude
import Compiler.Rum.Internal.Util
import Compiler.Rum.StackMachine.Structure
import Compiler.Rum.StackMachine.Util
translateP :: Program -> Instructions
translateP pr = let (funs, rest) = span isFun pr in
translate funs >>= \f -> translate rest >>= \r -> pure $ f ++ [Label "start"] ++ r
where
isFun Fun{} = True
isFun _ = False
translate :: Program -> Instructions
translate = concatMapM translateStmt
translateStmt :: Statement -> Instructions
translateStmt Skip = pure [Nop]
translateStmt AssignmentVar{..} = translateExpr value >>= \x -> pure $ x ++ [Store var]
translateStmt AssignmentArr{..} = translateExpr value >>= \x ->
concatMapM translateExpr (index arrC) >>= \inds ->
pure $ x ++ inds ++ [StoreArr (arr arrC) (length $ index arrC) ]
translateStmt IfElse{..} = do
lblTrue <- newLabel
lblFalse <- newLabel
ifC <- translateExpr ifCond
fAct <- translate falseAct
tAct <- translate trueAct
pure $ ifC ++ [JumpIfTrue lblTrue]
++ fAct ++ [Jump lblFalse, Label lblTrue]
++ tAct ++ [Label lblFalse]
translateStmt RepeatUntil{..} = do
lblRepeat <- newLabel
action <- translate act
repC <- translateExpr repCond
pure $ Label lblRepeat:action ++ repC ++ [JumpIfFalse lblRepeat]
translateStmt WhileDo{..} = do
lblWhile <- newLabel
lblEnd <- newLabel
whileC <- translateExpr whileCond
action <- translate act
pure $ Label lblWhile:whileC ++ [JumpIfFalse lblEnd]
++ action ++ [Jump lblWhile, Label lblEnd]
translateStmt For{..} = do
lblFor <- newLabel
lblEnd <- newLabel
st <- translate start
forExp <- translateExpr expr
bodyF <- translate body
up <- translate update
pure $ st ++ Label lblFor:forExp ++ [JumpIfFalse lblEnd]
++ bodyF ++ up ++ [Jump lblFor, Label lblEnd]
translateStmt Return{..} = translateExpr retExp >>= \ret -> pure $ ret ++ [SReturn]
translateStmt Fun {..} = translate funBody >>= \f ->
pure $ (Label $ LabelId $ varName funName) : map Store (reverse params) ++ f
translateStmt (FunCallStmt f@FunCall{fName = "strset", args = [var@(Var v), i, c]}) = do
str <- translateExpr var
ind <- translateExpr i
ch <- translateExpr c
pure $ str ++ ind ++ ch ++ [SRumludeCall Strset, Store v]
translateStmt (FunCallStmt f) = translateFunCall f
--translateStmt e = error $ "Not supported operation for stack: " ++ show e
translateExpr :: Expression -> Instructions
translateExpr (Const x) = pure [Push x]
translateExpr (Var v) = if isUp v then pure [LoadRef v] else pure [Load v]
translateExpr (ArrC ArrCell{..}) = concatMapM translateExpr index >>= \indexes ->
pure $ indexes ++ [LoadArr arr $ length indexes]
translateExpr (ArrLit exps) = concatMapM translateExpr exps >>= \ins -> pure $ ins ++ [PushNArr $ length exps]
translateExpr BinOper{..} = translateExpr l >>= \x -> translateExpr r >>= \y -> pure $ x ++ y ++ [SBinOp bop]
translateExpr CompOper{..} = translateExpr l >>= \x -> translateExpr r >>= \y -> pure $ x ++ y ++ [SCompOp cop]
translateExpr LogicOper{..} = translateExpr l >>= \x -> translateExpr r >>= \y -> pure $ x ++ y ++ [SLogicOp lop]
translateExpr (Neg e) = translateExpr e >>= \x -> pure $ Push (Number 0) : x ++ [SBinOp Sub]
translateExpr (FunCallExp f) = translateFunCall f
--translateExpr e = error $ "Not supported operation for stack: " ++ show e
-- f :: a -> m b
-- l :: [a]
-- mapM f l :: m [b]
-- almostResult = mapM translateExpr (args call) :: m [[Instruction]]
-- result = concat <$> almostResult
-- result = concatMapM translateExpr (args call) :: m [Instruction]
translateFunCall :: FunCall -> Instructions
translateFunCall FunCall{..} = let funName = varName fName in
concatMapM translateExpr args >>= \res -> pure $ res ++
case HM.lookup funName rumludeFunNames of
Nothing -> [SFunCall (LabelId funName) (length args)]
Just x -> [SRumludeCall x]
|
vrom911/Compiler
|
src/Compiler/Rum/StackMachine/Translator.hs
|
Haskell
|
mit
| 4,171
|
module Main where
-------------
-- Imports --
import Distribution.Simple
----------
-- Code --
main :: IO ()
main = defaultMain
|
crockeo/ballgame
|
src/Setup.hs
|
Haskell
|
mit
| 130
|
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.Pretty.JS
-- Copyright : (c) Phil Freeman 2013
-- License : MIT
--
-- Maintainer : Phil Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
-- Pretty printer for the Javascript AST
--
-----------------------------------------------------------------------------
module Language.PureScript.Pretty.JS (
prettyPrintJS
) where
import Prelude ()
import Prelude.Compat
import Data.List hiding (concat, concatMap)
import Data.Maybe (fromMaybe)
import Control.Arrow ((<+>))
import Control.Monad.State hiding (sequence)
import Control.PatternArrows
import qualified Control.Arrow as A
import Language.PureScript.Crash
import Language.PureScript.CodeGen.JS.AST
import Language.PureScript.CodeGen.JS.Common
import Language.PureScript.Pretty.Common
import Language.PureScript.Comments
import Numeric
literals :: Pattern PrinterState JS String
literals = mkPattern' match
where
match :: JS -> StateT PrinterState Maybe String
match (JSNumericLiteral n) = return $ either show show n
match (JSStringLiteral s) = return $ string s
match (JSBooleanLiteral True) = return "true"
match (JSBooleanLiteral False) = return "false"
match (JSArrayLiteral xs) = concat <$> sequence
[ return "[ "
, intercalate ", " <$> forM xs prettyPrintJS'
, return " ]"
]
match (JSObjectLiteral []) = return "{}"
match (JSObjectLiteral ps) = concat <$> sequence
[ return "{\n"
, withIndent $ do
jss <- forM ps $ \(key, value) -> fmap ((objectPropertyToString key ++ ": ") ++) . prettyPrintJS' $ value
indentString <- currentIndent
return $ intercalate ", \n" $ map (indentString ++) jss
, return "\n"
, currentIndent
, return "}"
]
where
objectPropertyToString :: String -> String
objectPropertyToString s | identNeedsEscaping s = show s
| otherwise = s
match (JSBlock sts) = concat <$> sequence
[ return "{\n"
, withIndent $ prettyStatements sts
, return "\n"
, currentIndent
, return "}"
]
match (JSVar ident) = return ident
match (JSVariableIntroduction ident value) = concat <$> sequence
[ return "var "
, return ident
, maybe (return "") (fmap (" = " ++) . prettyPrintJS') value
]
match (JSAssignment target value) = concat <$> sequence
[ prettyPrintJS' target
, return " = "
, prettyPrintJS' value
]
match (JSWhile cond sts) = concat <$> sequence
[ return "while ("
, prettyPrintJS' cond
, return ") "
, prettyPrintJS' sts
]
match (JSFor ident start end sts) = concat <$> sequence
[ return $ "for (var " ++ ident ++ " = "
, prettyPrintJS' start
, return $ "; " ++ ident ++ " < "
, prettyPrintJS' end
, return $ "; " ++ ident ++ "++) "
, prettyPrintJS' sts
]
match (JSForIn ident obj sts) = concat <$> sequence
[ return $ "for (var " ++ ident ++ " in "
, prettyPrintJS' obj
, return ") "
, prettyPrintJS' sts
]
match (JSIfElse cond thens elses) = concat <$> sequence
[ return "if ("
, prettyPrintJS' cond
, return ") "
, prettyPrintJS' thens
, maybe (return "") (fmap (" else " ++) . prettyPrintJS') elses
]
match (JSReturn value) = concat <$> sequence
[ return "return "
, prettyPrintJS' value
]
match (JSThrow value) = concat <$> sequence
[ return "throw "
, prettyPrintJS' value
]
match (JSBreak lbl) = return $ "break " ++ lbl
match (JSContinue lbl) = return $ "continue " ++ lbl
match (JSLabel lbl js) = concat <$> sequence
[ return $ lbl ++ ": "
, prettyPrintJS' js
]
match (JSComment com js) = fmap concat $ sequence $
[ return "\n"
, currentIndent
, return "/**\n"
] ++
map asLine (concatMap commentLines com) ++
[ currentIndent
, return " */\n"
, currentIndent
, prettyPrintJS' js
]
where
commentLines :: Comment -> [String]
commentLines (LineComment s) = [s]
commentLines (BlockComment s) = lines s
asLine :: String -> StateT PrinterState Maybe String
asLine s = do
i <- currentIndent
return $ i ++ " * " ++ removeComments s ++ "\n"
removeComments :: String -> String
removeComments ('*' : '/' : s) = removeComments s
removeComments (c : s) = c : removeComments s
removeComments [] = []
match (JSRaw js) = return js
match _ = mzero
string :: String -> String
string s = '"' : concatMap encodeChar s ++ "\""
where
encodeChar :: Char -> String
encodeChar '\b' = "\\b"
encodeChar '\t' = "\\t"
encodeChar '\n' = "\\n"
encodeChar '\v' = "\\v"
encodeChar '\f' = "\\f"
encodeChar '\r' = "\\r"
encodeChar '"' = "\\\""
encodeChar '\\' = "\\\\"
encodeChar c | fromEnum c > 0xFFFF = "\\u" ++ showHex highSurrogate "" ++ "\\u" ++ showHex lowSurrogate ""
where
(h, l) = divMod (fromEnum c - 0x10000) 0x400
highSurrogate = h + 0xD800
lowSurrogate = l + 0xDC00
encodeChar c | fromEnum c > 0xFFF = "\\u" ++ showHex (fromEnum c) ""
encodeChar c | fromEnum c > 0xFF = "\\u0" ++ showHex (fromEnum c) ""
encodeChar c | fromEnum c < 0x10 = "\\x0" ++ showHex (fromEnum c) ""
encodeChar c | fromEnum c > 0x7E || fromEnum c < 0x20 = "\\x" ++ showHex (fromEnum c) ""
encodeChar c = [c]
conditional :: Pattern PrinterState JS ((JS, JS), JS)
conditional = mkPattern match
where
match (JSConditional cond th el) = Just ((th, el), cond)
match _ = Nothing
accessor :: Pattern PrinterState JS (String, JS)
accessor = mkPattern match
where
match (JSAccessor prop val) = Just (prop, val)
match _ = Nothing
indexer :: Pattern PrinterState JS (String, JS)
indexer = mkPattern' match
where
match (JSIndexer index val) = (,) <$> prettyPrintJS' index <*> pure val
match _ = mzero
lam :: Pattern PrinterState JS ((Maybe String, [String]), JS)
lam = mkPattern match
where
match (JSFunction name args ret) = Just ((name, args), ret)
match _ = Nothing
app :: Pattern PrinterState JS (String, JS)
app = mkPattern' match
where
match (JSApp val args) = do
jss <- traverse prettyPrintJS' args
return (intercalate ", " jss, val)
match _ = mzero
typeOf :: Pattern PrinterState JS ((), JS)
typeOf = mkPattern match
where
match (JSTypeOf val) = Just ((), val)
match _ = Nothing
instanceOf :: Pattern PrinterState JS (JS, JS)
instanceOf = mkPattern match
where
match (JSInstanceOf val ty) = Just (val, ty)
match _ = Nothing
unary' :: UnaryOperator -> (JS -> String) -> Operator PrinterState JS String
unary' op mkStr = Wrap match (++)
where
match :: Pattern PrinterState JS (String, JS)
match = mkPattern match'
where
match' (JSUnary op' val) | op' == op = Just (mkStr val, val)
match' _ = Nothing
unary :: UnaryOperator -> String -> Operator PrinterState JS String
unary op str = unary' op (const str)
negateOperator :: Operator PrinterState JS String
negateOperator = unary' Negate (\v -> if isNegate v then "- " else "-")
where
isNegate (JSUnary Negate _) = True
isNegate _ = False
binary :: BinaryOperator -> String -> Operator PrinterState JS String
binary op str = AssocL match (\v1 v2 -> v1 ++ " " ++ str ++ " " ++ v2)
where
match :: Pattern PrinterState JS (JS, JS)
match = mkPattern match'
where
match' (JSBinary op' v1 v2) | op' == op = Just (v1, v2)
match' _ = Nothing
prettyStatements :: [JS] -> StateT PrinterState Maybe String
prettyStatements sts = do
jss <- forM sts prettyPrintJS'
indentString <- currentIndent
return $ intercalate "\n" $ map ((++ ";") . (indentString ++)) jss
-- |
-- Generate a pretty-printed string representing a Javascript expression
--
prettyPrintJS1 :: JS -> String
prettyPrintJS1 = fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyPrintJS'
-- |
-- Generate a pretty-printed string representing a collection of Javascript expressions at the same indentation level
--
prettyPrintJS :: [JS] -> String
prettyPrintJS = fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements
-- |
-- Generate an indented, pretty-printed string representing a Javascript expression
--
prettyPrintJS' :: JS -> StateT PrinterState Maybe String
prettyPrintJS' = A.runKleisli $ runPattern matchValue
where
matchValue :: Pattern PrinterState JS String
matchValue = buildPrettyPrinter operators (literals <+> fmap parens matchValue)
operators :: OperatorTable PrinterState JS String
operators =
OperatorTable [ [ Wrap accessor $ \prop val -> val ++ "." ++ prop ]
, [ Wrap indexer $ \index val -> val ++ "[" ++ index ++ "]" ]
, [ Wrap app $ \args val -> val ++ "(" ++ args ++ ")" ]
, [ unary JSNew "new " ]
, [ Wrap lam $ \(name, args) ret -> "function "
++ fromMaybe "" name
++ "(" ++ intercalate ", " args ++ ") "
++ ret ]
, [ Wrap typeOf $ \_ s -> "typeof " ++ s ]
, [ unary Not "!"
, unary BitwiseNot "~"
, unary Positive "+"
, negateOperator ]
, [ binary Multiply "*"
, binary Divide "/"
, binary Modulus "%" ]
, [ binary Add "+"
, binary Subtract "-" ]
, [ binary ShiftLeft "<<"
, binary ShiftRight ">>"
, binary ZeroFillShiftRight ">>>" ]
, [ binary LessThan "<"
, binary LessThanOrEqualTo "<="
, binary GreaterThan ">"
, binary GreaterThanOrEqualTo ">="
, AssocR instanceOf $ \v1 v2 -> v1 ++ " instanceof " ++ v2 ]
, [ binary EqualTo "==="
, binary NotEqualTo "!==" ]
, [ binary BitwiseAnd "&" ]
, [ binary BitwiseXor "^" ]
, [ binary BitwiseOr "|" ]
, [ binary And "&&" ]
, [ binary Or "||" ]
, [ Wrap conditional $ \(th, el) cond -> cond ++ " ? " ++ prettyPrintJS1 th ++ " : " ++ prettyPrintJS1 el ]
]
|
michaelficarra/purescript
|
src/Language/PureScript/Pretty/JS.hs
|
Haskell
|
mit
| 10,688
|
{-# LANGUAGE DeriveDataTypeable #-}
module ReprTree (reprTree, reprTreeString) where
import Data.Tree
import Data.Generics
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
-- | A data representation in form of a formatted multiline string, such as
-- the following:
--
-- @
-- :
-- - A
-- | - :
-- | | - a
-- | | - b
-- | | - c
-- | - 9
-- - C
-- | - 3
-- - B
-- - D
-- - :
-- - :
-- | - asdf
-- | - 123
-- | - ldskfjkl
-- - :
-- - f
-- @
--
-- Which is a result of running the following code:
--
-- > import Data.Generics (Data, Typeable)
-- >
-- > data SomeType =
-- > A [String] Int |
-- > B |
-- > C Int |
-- > D [[String]]
-- > deriving (Typeable, Data)
-- >
-- > xxx = A ["a", "b", "c"] 9
-- > : C 3
-- > : B
-- > : D [["asdf", "123", "ldskfjkl"], ["f"]]
-- > : []
-- >
-- > main = putStrLn $ reprTreeString xxx
--
reprTreeString :: (Data a) => a -> String
reprTreeString = unlines . treeLines . reprTree where
treeLines (Node x ts) = x : subTreesLines ts
subTreesLines [] = []
subTreesLines [t] = shift "- " " " (treeLines t)
subTreesLines (t:ts) = shift "- " "| " (treeLines t) ++ subTreesLines ts
shift first other = zipWith (++) (first : repeat other)
-- | Get a representation tree of a generic data structure using SYB. Can be
-- used to implement a custom converter to textual representation.
reprTree :: Data a => a -> Tree String
reprTree = adtReprTree
`ext2Q` mapReprTree
`ext2Q` pairReprTree
`ext1Q` listReprTree
`ext1Q` setReprTree
`extQ` textReprTree
`extQ` stringReprTree
textReprTree :: Text -> Tree String
textReprTree x = Node (Text.unpack x) []
stringReprTree :: String -> Tree String
stringReprTree x = Node x []
adtReprTree :: Data a => a -> Tree String
adtReprTree a = Node (stripBraces $ showConstr $ toConstr a) (gmapQ reprTree a)
where
stripBraces :: String -> String
stripBraces s =
fromMaybe s $
stripPrefix "(" s >>= fmap reverse . stripPrefix ")" . reverse
mapReprTree :: (Data a, Data k) => Map k a -> Tree String
mapReprTree = Node "Map" . map pairReprTree . Map.toList
pairReprTree :: (Data a, Data b) => (a, b) -> Tree String
pairReprTree (a, b) = Node "," [reprTree a, reprTree b]
listReprTree :: (Data a) => [a] -> Tree String
listReprTree = Node ":" . map reprTree
setReprTree :: (Data a) => Set a -> Tree String
setReprTree = Node "Set" . map reprTree . Set.toList
|
nikita-volkov/repr-tree-syb
|
src/ReprTree.hs
|
Haskell
|
mit
| 2,597
|
module Development.Duplo where
import Control.Exception (throw)
import Control.Lens hiding (Action)
import Control.Monad (unless, void, when)
import Control.Monad.Trans.Maybe (runMaybeT)
import qualified Development.Duplo.Component as CM
import Development.Duplo.Git as Git
import Development.Duplo.Markups as Markups
import Development.Duplo.Scripts as Scripts
import Development.Duplo.Static as Static
import Development.Duplo.Styles as Styles
import qualified Development.Duplo.Types.AppInfo as AI
import qualified Development.Duplo.Types.Builder as BD
import qualified Development.Duplo.Types.Config as TC
import qualified Development.Duplo.Types.Options as OP
import Development.Duplo.Utilities (createIntermediaryDirectories,
createStdEnv,
headerPrintSetter, logStatus,
successPrintSetter)
import Development.Shake
import qualified Development.Shake as DS
import Development.Shake.FilePath ((</>))
import System.Console.GetOpt (ArgDescr (..), OptDescr (..))
import System.IO (readFile)
shakeOpts = shakeOptions { shakeThreads = 4 }
build :: String -> [String] -> TC.BuildConfig -> OP.Options -> IO ()
build cmdName cmdArgs config options = shake shakeOpts $ do
let headerPrinter = liftIO . logStatus headerPrintSetter
let successPrinter = liftIO . logStatus successPrintSetter
let port = config ^. TC.port
let cwd = config ^. TC.cwd
let utilPath = config ^. TC.utilPath
let miscPath = config ^. TC.miscPath
let targetPath = config ^. TC.targetPath
let bumpLevel = config ^. TC.bumpLevel
let appName = config ^. TC.appName
let appVersion = config ^. TC.appVersion
let appId = config ^. TC.appId
let duploPath = config ^. TC.duploPath
-- What to build and each action's related action
let targetScript = targetPath </> "index.js"
let targetStyle = targetPath </> "index.css"
let targetMarkup = targetPath </> "index.html"
targetScript *> (void . runMaybeT . Scripts.build config)
targetStyle *> (void . runMaybeT . Styles.build config)
targetMarkup *> (void . runMaybeT . Markups.build config)
-- Manually bootstrap Shake
action $ do
-- Keep a list of commands so we can check before we call Shake,
-- which doesn't allow us to change the error message when an action
-- isn't found.
let actions = [ "static"
, "clean"
, "build"
, "test"
, "bump"
, "init"
, "version"
]
-- Default to help
let cmdName' = if cmdName `elem` actions then cmdName else "help"
-- Call command
need [cmdName']
-- Trailing space
putNormal ""
-- Handling static assets
Static.qualify config &?> Static.build config
"static" ~> Static.deps config
-- Install dependencies.
"deps" ~> do
liftIO $ logStatus headerPrintSetter "Installing dependencies"
envOpt <- createStdEnv config
command_ [envOpt] (utilPath </> "install-deps.sh") []
"clean" ~> do
-- Clean only when the target is there.
needCleaning <- doesDirectoryExist targetPath
when needCleaning $ liftIO $ removeFiles targetPath ["//*"]
successPrinter "Clean completed"
"build" ~> do
-- Make sure all static files and dependencies are there.
need ["static", "deps"]
-- Then compile, in parallel.
need [targetScript, targetStyle, targetMarkup]
successPrinter "Build completed"
"test" ~> do
envOpt <- createStdEnv config
let appPath = config ^. TC.appPath
let targetPath = config ^. TC.targetPath </> "tests"
let utilPath = config ^. TC.utilPath
let testPath = config ^. TC.testPath
let testCompiler = utilPath </> "scripts-test.sh"
let find path pttrn = command [Cwd path] (utilPath </> "find.sh") [".", pttrn]
-- There must be a test directory.
testsExist <- doesDirectoryExist testPath
unless testsExist $ throw BD.MissingTestDirectory
-- Do a semi-full build
need ["static", "deps"]
need [targetScript, targetStyle]
let prepareFile path =
do
let absPath = targetPath </> path
-- Create intermediary directories
createIntermediaryDirectories absPath
-- Inject into each app file dependencies, AMD, etc in
-- preparation for testing.
Stdout compiled <- command [envOpt] testCompiler [path]
-- Then write to the respective path in the output directory.
writeFileChanged absPath compiled
-- Each path is relative to the application root (most likely
-- `app/`).
Stdout codePaths' <- find testPath "*.js"
mapM_ prepareFile $ lines codePaths'
-- Build the markup once we have the script files in target.
need [targetMarkup]
-- Run the test suite
command_ [envOpt] (utilPath </> "run-test.sh") []
-- Copy over
successPrinter "Tests completed"
"bump" ~> do
(oldVersion, newVersion) <- Git.commit config bumpLevel
successPrinter $ "Bumped version from " ++ oldVersion ++ " to " ++ newVersion
"init" ~> do
let user = cmdArgs ^. element 0
let repo = cmdArgs ^. element 1
let name = user ++ "/" ++ repo
let src = miscPath </> "boilerplate/"
let dest = cwd ++ "/"
-- Check prerequisites
when (null user) $ throw BD.MissingGithubUserException
when (null repo) $ throw BD.MissingGithubRepoException
headerPrinter $ "Creating new duplo project " ++ name
-- Initialize with boilerplate
command_ [] (utilPath </> "init-boilerplate.sh") [src, dest]
-- Update fields
appInfo <- liftIO CM.readManifest
let newAppInfo = appInfo { AI.name = repo
, AI.repo = name
}
-- Commit app info
liftIO $ CM.writeManifest newAppInfo
-- Initalize git
command_ [] (utilPath </> "init-git.sh") [name]
successPrinter $ "Project created at " ++ dest
-- Version should have already been displayed if requested
"version" ~> return ()
"help" ~> liftIO (readFile (miscPath </> "help.txt") >>= putStr)
|
pixbi/duplo
|
src/Development/Duplo.hs
|
Haskell
|
mit
| 6,815
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Graphics.Renderer(
Renderer
, rendererContext
, rendererSetNumViewports
, rendererSetViewport
, rendererGetTextureQuality
, rendererSetTextureQuality
, rendererGetMaterialQuality
, rendererSetMaterialQuality
, rendererGetSpecularLighting
, rendererSetSpecularLighting
, rendererGetDrawShadows
, rendererSetDrawShadows
, rendererGetShadowMapSize
, rendererSetShadowMapSize
, rendererGetShadowQuality
, rendererSetShadowQuality
, rendererGetMaxOccluderTriangles
, rendererSetMaxOccluderTriangles
, rendererGetDynamicInstancing
, rendererSetDynamicInstancing
, rendererDrawDebugGeometry
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Graphics.Urho3D.Graphics.Internal.Renderer
import Graphics.Urho3D.Graphics.Viewport
import Graphics.Urho3D.Graphics.Defs
import Graphics.Urho3D.Core.Object
import Graphics.Urho3D.Monad
import Graphics.Urho3D.Parent
import Data.Monoid
import Foreign
C.context (C.cppCtx <> rendererCntx <> objectContext <> viewportContext)
C.include "<Urho3D/Graphics/Renderer.h>"
C.using "namespace Urho3D"
rendererContext :: C.Context
rendererContext = objectContext <> rendererCntx
deriveParent ''Object ''Renderer
instance Subsystem Renderer where
getSubsystemImpl ptr = [C.exp| Renderer* { $(Object* ptr)->GetSubsystem<Renderer>() } |]
-- | Set number of backbuffer viewports to render.
rendererSetNumViewports :: (Parent Renderer a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to renderer
-> Word -- ^ Count of backbuffers
-> m ()
rendererSetNumViewports p w = liftIO $ do
let ptr = parentPointer p
wi = fromIntegral w
[C.exp| void { $(Renderer* ptr)->SetNumViewports($(unsigned int wi)) } |]
-- | Set a backbuffer viewport.
rendererSetViewport :: (Parent Renderer a, Pointer p a, Parent Viewport b, Pointer pv b, MonadIO m)
=> p -- ^ Pointer to renderer
-> Word -- ^ Index of backbuffer
-> pv -- ^ Pointer to viewport
-> m ()
rendererSetViewport p w pv = liftIO $ do
let ptr = parentPointer p
wi = fromIntegral w
vptr = parentPointer pv
[C.exp| void { $(Renderer* ptr)->SetViewport($(unsigned int wi), $(Viewport* vptr)) } |]
-- | Return texture quality level.
rendererGetTextureQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m MaterialQuality
rendererGetTextureQuality p = liftIO $ do
let ptr = parentPointer p
toEnum . fromIntegral <$> [C.exp| int { $(Renderer* ptr)->GetTextureQuality() } |]
-- | Sets texture quality level
rendererSetTextureQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> MaterialQuality -- ^ Quality level
-> m ()
rendererSetTextureQuality p q = liftIO $ do
let ptr = parentPointer p
e = fromIntegral $ fromEnum q
[C.exp| void {$(Renderer* ptr)->SetTextureQuality((MaterialQuality)$(int e))} |]
-- | Return material quality level.
rendererGetMaterialQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m MaterialQuality
rendererGetMaterialQuality p = liftIO $ do
let ptr = parentPointer p
toEnum . fromIntegral <$> [C.exp| int { (int)$(Renderer* ptr)->GetMaterialQuality() } |]
-- | Sets texture quality level
rendererSetMaterialQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> MaterialQuality -- ^ Quality level
-> m ()
rendererSetMaterialQuality p q = liftIO $ do
let ptr = parentPointer p
e = fromIntegral $ fromEnum q
[C.exp| void {$(Renderer* ptr)->SetMaterialQuality((MaterialQuality)$(int e))} |]
-- | Is specular lighting on?
rendererGetSpecularLighting :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m Bool
rendererGetSpecularLighting p = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {$(Renderer* ptr)->GetSpecularLighting()}|]
-- | Switches on/off specular lighting
rendererSetSpecularLighting :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> Bool -- ^ Flag
-> m ()
rendererSetSpecularLighting p flag = liftIO $ do
let ptr = parentPointer p
flag' = if flag then 1 else 0
[C.exp| void {$(Renderer* ptr)->SetSpecularLighting($(int flag') != 0)}|]
-- | Is shadows on?
rendererGetDrawShadows :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m Bool
rendererGetDrawShadows p = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {$(Renderer* ptr)->GetDrawShadows()}|]
-- | Switches on/off shadows
rendererSetDrawShadows :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> Bool -- ^ Flag
-> m ()
rendererSetDrawShadows p flag = liftIO $ do
let ptr = parentPointer p
flag' = if flag then 1 else 0
[C.exp| void {$(Renderer* ptr)->SetDrawShadows($(int flag') != 0)}|]
-- | Returns length of side of shadow texture
rendererGetShadowMapSize :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m Int
rendererGetShadowMapSize p = liftIO $ do
let ptr = parentPointer p
fromIntegral <$> [C.exp| int {$(Renderer* ptr)->GetShadowMapSize()}|]
-- | Sets length of side of shadow texture
rendererSetShadowMapSize :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> Int -- ^ Size, usually power of 2
-> m ()
rendererSetShadowMapSize p s = liftIO $ do
let ptr = parentPointer p
s' = fromIntegral s
[C.exp| void {$(Renderer* ptr)->SetShadowMapSize($(int s'))} |]
-- | Return shadow quality level.
rendererGetShadowQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m ShadowQuality
rendererGetShadowQuality p = liftIO $ do
let ptr = parentPointer p
toEnum . fromIntegral <$> [C.exp| int { $(Renderer* ptr)->GetShadowQuality() } |]
-- | Sets shadow quality level
rendererSetShadowQuality :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> ShadowQuality -- ^ Quality level
-> m ()
rendererSetShadowQuality p q = liftIO $ do
let ptr = parentPointer p
e = fromIntegral $ fromEnum q
[C.exp| void {$(Renderer* ptr)->SetShadowQuality((ShadowQuality) $(int e))} |]
-- | Returns maximum number of triangles that occluder lefts on scene
rendererGetMaxOccluderTriangles :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m Int
rendererGetMaxOccluderTriangles p = liftIO $ do
let ptr = parentPointer p
fromIntegral <$> [C.exp| int {$(Renderer* ptr)->GetMaxOccluderTriangles()}|]
-- | Sets maximum number of triangles that occluder lefts on scene
rendererSetMaxOccluderTriangles :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> Int -- ^ Size, usually power of 2
-> m ()
rendererSetMaxOccluderTriangles p s = liftIO $ do
let ptr = parentPointer p
s' = fromIntegral s
[C.exp| void {$(Renderer* ptr)->SetMaxOccluderTriangles($(int s'))} |]
-- | Is dynamic instancing on?
rendererGetDynamicInstancing :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> m Bool
rendererGetDynamicInstancing p = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {$(Renderer* ptr)->GetDynamicInstancing()}|]
-- | Switches on/off dynamic instancing
rendererSetDynamicInstancing :: (Parent Renderer a, Pointer p a, MonadIO m) => p -- ^ Pointer to renderer or child
-> Bool -- ^ Flag
-> m ()
rendererSetDynamicInstancing p flag = liftIO $ do
let ptr = parentPointer p
flag' = fromBool flag
[C.exp| void {$(Renderer* ptr)->SetDynamicInstancing($(int flag') != 0)}|]
-- | Add debug geometry to the debug renderer.
rendererDrawDebugGeometry :: (Parent Renderer a, Pointer p a, MonadIO m)
=> p -- ^ Pointer to renderer or ascentoer
-> Bool -- ^ Flag
-> m ()
rendererDrawDebugGeometry p depthTest = liftIO $ do
let ptr = parentPointer p
depthTest' = fromBool depthTest
[C.exp| void {$(Renderer* ptr)->DrawDebugGeometry($(int depthTest') != 0)}|]
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Graphics/Renderer.hs
|
Haskell
|
mit
| 8,188
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.Node
(js_insertBefore, insertBefore, js_replaceChild, replaceChild,
js_removeChild, removeChild, js_appendChild, appendChild,
js_hasChildNodes, hasChildNodes, js_cloneNode, cloneNode,
js_normalize, normalize, js_isSupported, isSupported,
js_isSameNode, isSameNode, js_isEqualNode, isEqualNode,
js_lookupPrefix, lookupPrefix, js_isDefaultNamespace,
isDefaultNamespace, js_lookupNamespaceURI, lookupNamespaceURI,
js_compareDocumentPosition, compareDocumentPosition, js_contains,
contains, pattern ELEMENT_NODE, pattern ATTRIBUTE_NODE,
pattern TEXT_NODE, pattern CDATA_SECTION_NODE,
pattern ENTITY_REFERENCE_NODE, pattern ENTITY_NODE,
pattern PROCESSING_INSTRUCTION_NODE, pattern COMMENT_NODE,
pattern DOCUMENT_NODE, pattern DOCUMENT_TYPE_NODE,
pattern DOCUMENT_FRAGMENT_NODE, pattern NOTATION_NODE,
pattern DOCUMENT_POSITION_DISCONNECTED,
pattern DOCUMENT_POSITION_PRECEDING,
pattern DOCUMENT_POSITION_FOLLOWING,
pattern DOCUMENT_POSITION_CONTAINS,
pattern DOCUMENT_POSITION_CONTAINED_BY,
pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, js_getNodeName,
getNodeName, js_setNodeValue, setNodeValue, js_getNodeValue,
getNodeValue, js_getNodeType, getNodeType, js_getParentNode,
getParentNode, js_getChildNodes, getChildNodes, js_getFirstChild,
getFirstChild, js_getLastChild, getLastChild,
js_getPreviousSibling, getPreviousSibling, js_getNextSibling,
getNextSibling, js_getOwnerDocument, getOwnerDocument,
js_getNamespaceURI, getNamespaceURI, js_setPrefix, setPrefix,
js_getPrefix, getPrefix, js_getLocalName, getLocalName,
js_getBaseURI, getBaseURI, js_setTextContent, setTextContent,
js_getTextContent, getTextContent, js_getParentElement,
getParentElement, Node, castToNode, gTypeNode, IsNode, toNode)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"insertBefore\"]($2, $3)"
js_insertBefore ::
Node -> Nullable Node -> Nullable Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore Mozilla Node.insertBefore documentation>
insertBefore ::
(MonadIO m, IsNode self, IsNode newChild, IsNode refChild) =>
self -> Maybe newChild -> Maybe refChild -> m (Maybe Node)
insertBefore self newChild refChild
= liftIO
(nullableToMaybe <$>
(js_insertBefore (toNode self)
(maybeToNullable (fmap toNode newChild))
(maybeToNullable (fmap toNode refChild))))
foreign import javascript unsafe "$1[\"replaceChild\"]($2, $3)"
js_replaceChild ::
Node -> Nullable Node -> Nullable Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild Mozilla Node.replaceChild documentation>
replaceChild ::
(MonadIO m, IsNode self, IsNode newChild, IsNode oldChild) =>
self -> Maybe newChild -> Maybe oldChild -> m (Maybe Node)
replaceChild self newChild oldChild
= liftIO
(nullableToMaybe <$>
(js_replaceChild (toNode self)
(maybeToNullable (fmap toNode newChild))
(maybeToNullable (fmap toNode oldChild))))
foreign import javascript unsafe "$1[\"removeChild\"]($2)"
js_removeChild :: Node -> Nullable Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild Mozilla Node.removeChild documentation>
removeChild ::
(MonadIO m, IsNode self, IsNode oldChild) =>
self -> Maybe oldChild -> m (Maybe Node)
removeChild self oldChild
= liftIO
(nullableToMaybe <$>
(js_removeChild (toNode self)
(maybeToNullable (fmap toNode oldChild))))
foreign import javascript unsafe "$1[\"appendChild\"]($2)"
js_appendChild :: Node -> Nullable Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild Mozilla Node.appendChild documentation>
appendChild ::
(MonadIO m, IsNode self, IsNode newChild) =>
self -> Maybe newChild -> m (Maybe Node)
appendChild self newChild
= liftIO
(nullableToMaybe <$>
(js_appendChild (toNode self)
(maybeToNullable (fmap toNode newChild))))
foreign import javascript unsafe
"($1[\"hasChildNodes\"]() ? 1 : 0)" js_hasChildNodes ::
Node -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.hasChildNodes Mozilla Node.hasChildNodes documentation>
hasChildNodes :: (MonadIO m, IsNode self) => self -> m Bool
hasChildNodes self = liftIO (js_hasChildNodes (toNode self))
foreign import javascript unsafe "$1[\"cloneNode\"]($2)"
js_cloneNode :: Node -> Bool -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode Mozilla Node.cloneNode documentation>
cloneNode ::
(MonadIO m, IsNode self) => self -> Bool -> m (Maybe Node)
cloneNode self deep
= liftIO (nullableToMaybe <$> (js_cloneNode (toNode self) deep))
foreign import javascript unsafe "$1[\"normalize\"]()" js_normalize
:: Node -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize Mozilla Node.normalize documentation>
normalize :: (MonadIO m, IsNode self) => self -> m ()
normalize self = liftIO (js_normalize (toNode self))
foreign import javascript unsafe
"($1[\"isSupported\"]($2,\n$3) ? 1 : 0)" js_isSupported ::
Node -> JSString -> Nullable JSString -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isSupported Mozilla Node.isSupported documentation>
isSupported ::
(MonadIO m, IsNode self, ToJSString feature, ToJSString version) =>
self -> feature -> Maybe version -> m Bool
isSupported self feature version
= liftIO
(js_isSupported (toNode self) (toJSString feature)
(toMaybeJSString version))
foreign import javascript unsafe "($1[\"isSameNode\"]($2) ? 1 : 0)"
js_isSameNode :: Node -> Nullable Node -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isSameNode Mozilla Node.isSameNode documentation>
isSameNode ::
(MonadIO m, IsNode self, IsNode other) =>
self -> Maybe other -> m Bool
isSameNode self other
= liftIO
(js_isSameNode (toNode self) (maybeToNullable (fmap toNode other)))
foreign import javascript unsafe
"($1[\"isEqualNode\"]($2) ? 1 : 0)" js_isEqualNode ::
Node -> Nullable Node -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isEqualNode Mozilla Node.isEqualNode documentation>
isEqualNode ::
(MonadIO m, IsNode self, IsNode other) =>
self -> Maybe other -> m Bool
isEqualNode self other
= liftIO
(js_isEqualNode (toNode self)
(maybeToNullable (fmap toNode other)))
foreign import javascript unsafe "$1[\"lookupPrefix\"]($2)"
js_lookupPrefix ::
Node -> Nullable JSString -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupPrefix Mozilla Node.lookupPrefix documentation>
lookupPrefix ::
(MonadIO m, IsNode self, ToJSString namespaceURI,
FromJSString result) =>
self -> Maybe namespaceURI -> m (Maybe result)
lookupPrefix self namespaceURI
= liftIO
(fromMaybeJSString <$>
(js_lookupPrefix (toNode self) (toMaybeJSString namespaceURI)))
foreign import javascript unsafe
"($1[\"isDefaultNamespace\"]($2) ? 1 : 0)" js_isDefaultNamespace ::
Node -> Nullable JSString -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.isDefaultNamespace Mozilla Node.isDefaultNamespace documentation>
isDefaultNamespace ::
(MonadIO m, IsNode self, ToJSString namespaceURI) =>
self -> Maybe namespaceURI -> m Bool
isDefaultNamespace self namespaceURI
= liftIO
(js_isDefaultNamespace (toNode self)
(toMaybeJSString namespaceURI))
foreign import javascript unsafe "$1[\"lookupNamespaceURI\"]($2)"
js_lookupNamespaceURI ::
Node -> Nullable JSString -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lookupNamespaceURI Mozilla Node.lookupNamespaceURI documentation>
lookupNamespaceURI ::
(MonadIO m, IsNode self, ToJSString prefix, FromJSString result) =>
self -> Maybe prefix -> m (Maybe result)
lookupNamespaceURI self prefix
= liftIO
(fromMaybeJSString <$>
(js_lookupNamespaceURI (toNode self) (toMaybeJSString prefix)))
foreign import javascript unsafe
"$1[\"compareDocumentPosition\"]($2)" js_compareDocumentPosition ::
Node -> Nullable Node -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition Mozilla Node.compareDocumentPosition documentation>
compareDocumentPosition ::
(MonadIO m, IsNode self, IsNode other) =>
self -> Maybe other -> m Word
compareDocumentPosition self other
= liftIO
(js_compareDocumentPosition (toNode self)
(maybeToNullable (fmap toNode other)))
foreign import javascript unsafe "($1[\"contains\"]($2) ? 1 : 0)"
js_contains :: Node -> Nullable Node -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.contains Mozilla Node.contains documentation>
contains ::
(MonadIO m, IsNode self, IsNode other) =>
self -> Maybe other -> m Bool
contains self other
= liftIO
(js_contains (toNode self) (maybeToNullable (fmap toNode other)))
pattern ELEMENT_NODE = 1
pattern ATTRIBUTE_NODE = 2
pattern TEXT_NODE = 3
pattern CDATA_SECTION_NODE = 4
pattern ENTITY_REFERENCE_NODE = 5
pattern ENTITY_NODE = 6
pattern PROCESSING_INSTRUCTION_NODE = 7
pattern COMMENT_NODE = 8
pattern DOCUMENT_NODE = 9
pattern DOCUMENT_TYPE_NODE = 10
pattern DOCUMENT_FRAGMENT_NODE = 11
pattern NOTATION_NODE = 12
pattern DOCUMENT_POSITION_DISCONNECTED = 1
pattern DOCUMENT_POSITION_PRECEDING = 2
pattern DOCUMENT_POSITION_FOLLOWING = 4
pattern DOCUMENT_POSITION_CONTAINS = 8
pattern DOCUMENT_POSITION_CONTAINED_BY = 16
pattern DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32
foreign import javascript unsafe "$1[\"nodeName\"]" js_getNodeName
:: Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeName Mozilla Node.nodeName documentation>
getNodeName ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getNodeName self
= liftIO (fromMaybeJSString <$> (js_getNodeName (toNode self)))
foreign import javascript unsafe "$1[\"nodeValue\"] = $2;"
js_setNodeValue :: Node -> Nullable JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation>
setNodeValue ::
(MonadIO m, IsNode self, ToJSString val) =>
self -> Maybe val -> m ()
setNodeValue self val
= liftIO (js_setNodeValue (toNode self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"nodeValue\"]"
js_getNodeValue :: Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeValue Mozilla Node.nodeValue documentation>
getNodeValue ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getNodeValue self
= liftIO (fromMaybeJSString <$> (js_getNodeValue (toNode self)))
foreign import javascript unsafe "$1[\"nodeType\"]" js_getNodeType
:: Node -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType Mozilla Node.nodeType documentation>
getNodeType :: (MonadIO m, IsNode self) => self -> m Word
getNodeType self = liftIO (js_getNodeType (toNode self))
foreign import javascript unsafe "$1[\"parentNode\"]"
js_getParentNode :: Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentNode Mozilla Node.parentNode documentation>
getParentNode :: (MonadIO m, IsNode self) => self -> m (Maybe Node)
getParentNode self
= liftIO (nullableToMaybe <$> (js_getParentNode (toNode self)))
foreign import javascript unsafe "$1[\"childNodes\"]"
js_getChildNodes :: Node -> IO (Nullable NodeList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.childNodes Mozilla Node.childNodes documentation>
getChildNodes ::
(MonadIO m, IsNode self) => self -> m (Maybe NodeList)
getChildNodes self
= liftIO (nullableToMaybe <$> (js_getChildNodes (toNode self)))
foreign import javascript unsafe "$1[\"firstChild\"]"
js_getFirstChild :: Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.firstChild Mozilla Node.firstChild documentation>
getFirstChild :: (MonadIO m, IsNode self) => self -> m (Maybe Node)
getFirstChild self
= liftIO (nullableToMaybe <$> (js_getFirstChild (toNode self)))
foreign import javascript unsafe "$1[\"lastChild\"]"
js_getLastChild :: Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.lastChild Mozilla Node.lastChild documentation>
getLastChild :: (MonadIO m, IsNode self) => self -> m (Maybe Node)
getLastChild self
= liftIO (nullableToMaybe <$> (js_getLastChild (toNode self)))
foreign import javascript unsafe "$1[\"previousSibling\"]"
js_getPreviousSibling :: Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.previousSibling Mozilla Node.previousSibling documentation>
getPreviousSibling ::
(MonadIO m, IsNode self) => self -> m (Maybe Node)
getPreviousSibling self
= liftIO
(nullableToMaybe <$> (js_getPreviousSibling (toNode self)))
foreign import javascript unsafe "$1[\"nextSibling\"]"
js_getNextSibling :: Node -> IO (Nullable Node)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.nextSibling Mozilla Node.nextSibling documentation>
getNextSibling ::
(MonadIO m, IsNode self) => self -> m (Maybe Node)
getNextSibling self
= liftIO (nullableToMaybe <$> (js_getNextSibling (toNode self)))
foreign import javascript unsafe "$1[\"ownerDocument\"]"
js_getOwnerDocument :: Node -> IO (Nullable Document)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.ownerDocument Mozilla Node.ownerDocument documentation>
getOwnerDocument ::
(MonadIO m, IsNode self) => self -> m (Maybe Document)
getOwnerDocument self
= liftIO (nullableToMaybe <$> (js_getOwnerDocument (toNode self)))
foreign import javascript unsafe "$1[\"namespaceURI\"]"
js_getNamespaceURI :: Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.namespaceURI Mozilla Node.namespaceURI documentation>
getNamespaceURI ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getNamespaceURI self
= liftIO (fromMaybeJSString <$> (js_getNamespaceURI (toNode self)))
foreign import javascript unsafe "$1[\"prefix\"] = $2;"
js_setPrefix :: Node -> Nullable JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.prefix Mozilla Node.prefix documentation>
setPrefix ::
(MonadIO m, IsNode self, ToJSString val) =>
self -> Maybe val -> m ()
setPrefix self val
= liftIO (js_setPrefix (toNode self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"prefix\"]" js_getPrefix ::
Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.prefix Mozilla Node.prefix documentation>
getPrefix ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getPrefix self
= liftIO (fromMaybeJSString <$> (js_getPrefix (toNode self)))
foreign import javascript unsafe "$1[\"localName\"]"
js_getLocalName :: Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.localName Mozilla Node.localName documentation>
getLocalName ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getLocalName self
= liftIO (fromMaybeJSString <$> (js_getLocalName (toNode self)))
foreign import javascript unsafe "$1[\"baseURI\"]" js_getBaseURI ::
Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.baseURI Mozilla Node.baseURI documentation>
getBaseURI ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getBaseURI self
= liftIO (fromMaybeJSString <$> (js_getBaseURI (toNode self)))
foreign import javascript unsafe "$1[\"textContent\"] = $2;"
js_setTextContent :: Node -> Nullable JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation>
setTextContent ::
(MonadIO m, IsNode self, ToJSString val) =>
self -> Maybe val -> m ()
setTextContent self val
= liftIO (js_setTextContent (toNode self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"textContent\"]"
js_getTextContent :: Node -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent Mozilla Node.textContent documentation>
getTextContent ::
(MonadIO m, IsNode self, FromJSString result) =>
self -> m (Maybe result)
getTextContent self
= liftIO (fromMaybeJSString <$> (js_getTextContent (toNode self)))
foreign import javascript unsafe "$1[\"parentElement\"]"
js_getParentElement :: Node -> IO (Nullable Element)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement Mozilla Node.parentElement documentation>
getParentElement ::
(MonadIO m, IsNode self) => self -> m (Maybe Element)
getParentElement self
= liftIO (nullableToMaybe <$> (js_getParentElement (toNode self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Node.hs
|
Haskell
|
mit
| 18,951
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module ACME.Yes.PreCure5.GoGo.ProfilesSpec where
import ACME.Yes.PreCure5.GoGo.Profiles
import qualified ACME.Yes.PreCure5.Profiles as Yes
import Test.Hspec
import Test.Hspec.QuickCheck (prop)
import Test.QuickCheck
import qualified Data.Set as S
import Debug.Trace
import Control.Monad
traceId :: String -> String
traceId = join trace
instance Arbitrary Yes.PreCure5 where
arbitrary = elements $ S.toList allPrecures
spec :: Spec
spec = do
describe "transformationPhraseOf" $ do
prop "is same phrase as `transformationPhraseOf PreCure5`" $
\yes ->
let gogo = PreCure5 yes in
Yes.transformationPhraseOf (S.singleton yes) == transformationPhraseOf (S.singleton gogo)
prop "is PreCure5's phrase with MilkyRose's phrase" $
\yes ->
let gogo = PreCure5 yes in
transformationPhraseOf (S.singleton $ gogo) ++ transformationPhraseOf (S.singleton MilkyRose)
== transformationPhraseOf (S.fromList [gogo, MilkyRose])
|
igrep/yes-precure5-command
|
test/ACME/Yes/PreCure5/GoGo/ProfilesSpec.hs
|
Haskell
|
mit
| 1,017
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QFontDatabase.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:14
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QFontDatabase (
QqFontDatabase(..)
,QqFontDatabase_nf(..)
,qFontDatabaseAddApplicationFont
,qFontDatabaseAddApplicationFontFromData
,qFontDatabaseApplicationFontFamilies
,Qfamilies(..)
,QisBitmapScalable(..)
,QisFixedPitch(..)
,QisScalable(..)
,QisSmoothlyScalable(..)
,QpointSizes(..)
,qFontDatabaseRemoveAllApplicationFonts
,qFontDatabaseRemoveApplicationFont
,smoothSizes
,qFontDatabaseStandardSizes
,QstyleString(..)
,styles
,qFontDatabaseWritingSystemName
,qFontDatabaseWritingSystemSample
,QwritingSystems(..)
,qFontDatabase_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QFontDatabase
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
class QqFontDatabase x1 where
qFontDatabase :: x1 -> IO (QFontDatabase ())
instance QqFontDatabase (()) where
qFontDatabase ()
= withQFontDatabaseResult $
qtc_QFontDatabase
foreign import ccall "qtc_QFontDatabase" qtc_QFontDatabase :: IO (Ptr (TQFontDatabase ()))
instance QqFontDatabase ((QFontDatabase t1)) where
qFontDatabase (x1)
= withQFontDatabaseResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFontDatabase1 cobj_x1
foreign import ccall "qtc_QFontDatabase1" qtc_QFontDatabase1 :: Ptr (TQFontDatabase t1) -> IO (Ptr (TQFontDatabase ()))
class QqFontDatabase_nf x1 where
qFontDatabase_nf :: x1 -> IO (QFontDatabase ())
instance QqFontDatabase_nf (()) where
qFontDatabase_nf ()
= withObjectRefResult $
qtc_QFontDatabase
instance QqFontDatabase_nf ((QFontDatabase t1)) where
qFontDatabase_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFontDatabase1 cobj_x1
qFontDatabaseAddApplicationFont :: ((String)) -> IO (Int)
qFontDatabaseAddApplicationFont (x1)
= withIntResult $
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_addApplicationFont cstr_x1
foreign import ccall "qtc_QFontDatabase_addApplicationFont" qtc_QFontDatabase_addApplicationFont :: CWString -> IO CInt
qFontDatabaseAddApplicationFontFromData :: ((String)) -> IO (Int)
qFontDatabaseAddApplicationFontFromData (x1)
= withIntResult $
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_addApplicationFontFromData cstr_x1
foreign import ccall "qtc_QFontDatabase_addApplicationFontFromData" qtc_QFontDatabase_addApplicationFontFromData :: CWString -> IO CInt
qFontDatabaseApplicationFontFamilies :: ((Int)) -> IO ([String])
qFontDatabaseApplicationFontFamilies (x1)
= withQListStringResult $ \arr ->
qtc_QFontDatabase_applicationFontFamilies (toCInt x1) arr
foreign import ccall "qtc_QFontDatabase_applicationFontFamilies" qtc_QFontDatabase_applicationFontFamilies :: CInt -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qbold (QFontDatabase a) ((String, String)) where
bold x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_bold cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_bold" qtc_QFontDatabase_bold :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
class Qfamilies x1 where
families :: QFontDatabase a -> x1 -> IO ([String])
instance Qfamilies (()) where
families x0 ()
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFontDatabase_families cobj_x0 arr
foreign import ccall "qtc_QFontDatabase_families" qtc_QFontDatabase_families :: Ptr (TQFontDatabase a) -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qfamilies ((WritingSystem)) where
families x0 (x1)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFontDatabase_families1 cobj_x0 (toCLong $ qEnum_toInt x1) arr
foreign import ccall "qtc_QFontDatabase_families1" qtc_QFontDatabase_families1 :: Ptr (TQFontDatabase a) -> CLong -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qfont (QFontDatabase a) ((String, String, Int)) where
font x0 (x1, x2, x3)
= withQFontResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_font cobj_x0 cstr_x1 cstr_x2 (toCInt x3)
foreign import ccall "qtc_QFontDatabase_font" qtc_QFontDatabase_font :: Ptr (TQFontDatabase a) -> CWString -> CWString -> CInt -> IO (Ptr (TQFont ()))
class QisBitmapScalable x1 where
isBitmapScalable :: QFontDatabase a -> x1 -> IO (Bool)
instance QisBitmapScalable ((String)) where
isBitmapScalable x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_isBitmapScalable cobj_x0 cstr_x1
foreign import ccall "qtc_QFontDatabase_isBitmapScalable" qtc_QFontDatabase_isBitmapScalable :: Ptr (TQFontDatabase a) -> CWString -> IO CBool
instance QisBitmapScalable ((String, String)) where
isBitmapScalable x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_isBitmapScalable1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_isBitmapScalable1" qtc_QFontDatabase_isBitmapScalable1 :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
class QisFixedPitch x1 where
isFixedPitch :: QFontDatabase a -> x1 -> IO (Bool)
instance QisFixedPitch ((String)) where
isFixedPitch x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_isFixedPitch cobj_x0 cstr_x1
foreign import ccall "qtc_QFontDatabase_isFixedPitch" qtc_QFontDatabase_isFixedPitch :: Ptr (TQFontDatabase a) -> CWString -> IO CBool
instance QisFixedPitch ((String, String)) where
isFixedPitch x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_isFixedPitch1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_isFixedPitch1" qtc_QFontDatabase_isFixedPitch1 :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
class QisScalable x1 where
isScalable :: QFontDatabase a -> x1 -> IO (Bool)
instance QisScalable ((String)) where
isScalable x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_isScalable cobj_x0 cstr_x1
foreign import ccall "qtc_QFontDatabase_isScalable" qtc_QFontDatabase_isScalable :: Ptr (TQFontDatabase a) -> CWString -> IO CBool
instance QisScalable ((String, String)) where
isScalable x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_isScalable1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_isScalable1" qtc_QFontDatabase_isScalable1 :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
class QisSmoothlyScalable x1 where
isSmoothlyScalable :: QFontDatabase a -> x1 -> IO (Bool)
instance QisSmoothlyScalable ((String)) where
isSmoothlyScalable x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_isSmoothlyScalable cobj_x0 cstr_x1
foreign import ccall "qtc_QFontDatabase_isSmoothlyScalable" qtc_QFontDatabase_isSmoothlyScalable :: Ptr (TQFontDatabase a) -> CWString -> IO CBool
instance QisSmoothlyScalable ((String, String)) where
isSmoothlyScalable x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_isSmoothlyScalable1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_isSmoothlyScalable1" qtc_QFontDatabase_isSmoothlyScalable1 :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
instance Qitalic (QFontDatabase a) ((String, String)) where
italic x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_italic cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_italic" qtc_QFontDatabase_italic :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CBool
class QpointSizes x1 where
pointSizes :: QFontDatabase a -> x1 -> IO ([Int])
instance QpointSizes ((String)) where
pointSizes x0 (x1)
= withQListIntResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_pointSizes cobj_x0 cstr_x1 arr
foreign import ccall "qtc_QFontDatabase_pointSizes" qtc_QFontDatabase_pointSizes :: Ptr (TQFontDatabase a) -> CWString -> Ptr CInt -> IO CInt
instance QpointSizes ((String, String)) where
pointSizes x0 (x1, x2)
= withQListIntResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_pointSizes1 cobj_x0 cstr_x1 cstr_x2 arr
foreign import ccall "qtc_QFontDatabase_pointSizes1" qtc_QFontDatabase_pointSizes1 :: Ptr (TQFontDatabase a) -> CWString -> CWString -> Ptr CInt -> IO CInt
qFontDatabaseRemoveAllApplicationFonts :: (()) -> IO (Bool)
qFontDatabaseRemoveAllApplicationFonts ()
= withBoolResult $
qtc_QFontDatabase_removeAllApplicationFonts
foreign import ccall "qtc_QFontDatabase_removeAllApplicationFonts" qtc_QFontDatabase_removeAllApplicationFonts :: IO CBool
qFontDatabaseRemoveApplicationFont :: ((Int)) -> IO (Bool)
qFontDatabaseRemoveApplicationFont (x1)
= withBoolResult $
qtc_QFontDatabase_removeApplicationFont (toCInt x1)
foreign import ccall "qtc_QFontDatabase_removeApplicationFont" qtc_QFontDatabase_removeApplicationFont :: CInt -> IO CBool
smoothSizes :: QFontDatabase a -> ((String, String)) -> IO ([Int])
smoothSizes x0 (x1, x2)
= withQListIntResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_smoothSizes cobj_x0 cstr_x1 cstr_x2 arr
foreign import ccall "qtc_QFontDatabase_smoothSizes" qtc_QFontDatabase_smoothSizes :: Ptr (TQFontDatabase a) -> CWString -> CWString -> Ptr CInt -> IO CInt
qFontDatabaseStandardSizes :: (()) -> IO ([Int])
qFontDatabaseStandardSizes ()
= withQListIntResult $ \arr ->
qtc_QFontDatabase_standardSizes arr
foreign import ccall "qtc_QFontDatabase_standardSizes" qtc_QFontDatabase_standardSizes :: Ptr CInt -> IO CInt
class QstyleString x1 where
styleString :: QFontDatabase a -> x1 -> IO (String)
instance QstyleString ((QFont t1)) where
styleString x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFontDatabase_styleString1 cobj_x0 cobj_x1
foreign import ccall "qtc_QFontDatabase_styleString1" qtc_QFontDatabase_styleString1 :: Ptr (TQFontDatabase a) -> Ptr (TQFont t1) -> IO (Ptr (TQString ()))
instance QstyleString ((QFontInfo t1)) where
styleString x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QFontDatabase_styleString cobj_x0 cobj_x1
foreign import ccall "qtc_QFontDatabase_styleString" qtc_QFontDatabase_styleString :: Ptr (TQFontDatabase a) -> Ptr (TQFontInfo t1) -> IO (Ptr (TQString ()))
styles :: QFontDatabase a -> ((String)) -> IO ([String])
styles x0 (x1)
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_styles cobj_x0 cstr_x1 arr
foreign import ccall "qtc_QFontDatabase_styles" qtc_QFontDatabase_styles :: Ptr (TQFontDatabase a) -> CWString -> Ptr (Ptr (TQString ())) -> IO CInt
instance Qweight (QFontDatabase a) ((String, String)) where
weight x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QFontDatabase_weight cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QFontDatabase_weight" qtc_QFontDatabase_weight :: Ptr (TQFontDatabase a) -> CWString -> CWString -> IO CInt
qFontDatabaseWritingSystemName :: ((WritingSystem)) -> IO (String)
qFontDatabaseWritingSystemName (x1)
= withStringResult $
qtc_QFontDatabase_writingSystemName (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QFontDatabase_writingSystemName" qtc_QFontDatabase_writingSystemName :: CLong -> IO (Ptr (TQString ()))
qFontDatabaseWritingSystemSample :: ((WritingSystem)) -> IO (String)
qFontDatabaseWritingSystemSample (x1)
= withStringResult $
qtc_QFontDatabase_writingSystemSample (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QFontDatabase_writingSystemSample" qtc_QFontDatabase_writingSystemSample :: CLong -> IO (Ptr (TQString ()))
class QwritingSystems x1 where
writingSystems :: QFontDatabase a -> x1 -> IO ([WritingSystem])
instance QwritingSystems (()) where
writingSystems x0 ()
= withQEnumListResult $
withQListLongResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QFontDatabase_writingSystems cobj_x0 arr
foreign import ccall "qtc_QFontDatabase_writingSystems" qtc_QFontDatabase_writingSystems :: Ptr (TQFontDatabase a) -> Ptr CLong -> IO CInt
instance QwritingSystems ((String)) where
writingSystems x0 (x1)
= withQEnumListResult $
withQListLongResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QFontDatabase_writingSystems1 cobj_x0 cstr_x1 arr
foreign import ccall "qtc_QFontDatabase_writingSystems1" qtc_QFontDatabase_writingSystems1 :: Ptr (TQFontDatabase a) -> CWString -> Ptr CLong -> IO CInt
qFontDatabase_delete :: QFontDatabase a -> IO ()
qFontDatabase_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QFontDatabase_delete cobj_x0
foreign import ccall "qtc_QFontDatabase_delete" qtc_QFontDatabase_delete :: Ptr (TQFontDatabase a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QFontDatabase.hs
|
Haskell
|
bsd-2-clause
| 14,131
|
import System.Environment
import Test.DocTest
main = doctest ["word2vec"]
|
RayRacine/hs-word2vec
|
word2vec-test.hs
|
Haskell
|
bsd-3-clause
| 75
|
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Math.Budget.Lens.ArbitraryMethodL where
class ArbitraryMethodL cat target | target -> cat where
arbitraryMethodL :: cat target String
|
tonymorris/hbudget
|
src/Math/Budget/Lens/ArbitraryMethodL.hs
|
Haskell
|
bsd-3-clause
| 208
|
{-# LANGUAGE PackageImports #-}
module System.Posix.Internals (module M) where
import "base" System.Posix.Internals as M
|
silkapp/base-noprelude
|
src/System/Posix/Internals.hs
|
Haskell
|
bsd-3-clause
| 126
|
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving #-}
module Lib.HGit.Data
( runGit
, GitConfig(..)
, GitCommand(..)
, GitReader
, createGitProcess
, spawnGitProcess
, ID
, CommitID
, BlobID
, TagID
, TreeID
, Tag
, GitObject(..)
, Person(..)
, Commitent(..)
, TreeNode(..)
, Trees(..)
, idFromGitObject
, gitObjectToString
, makeGitObject
, readGitObject
) where
import System.Command
import System.IO
import Control.Monad.Reader
import Data.Maybe
import qualified Data.Text.Lazy as T
import Data.Text.Lazy (Text)
import Data.Text.Encoding as E
import Data.List (find)
data GitConfig = GitConfig
{ gitCwd :: FilePath
, gitPath :: Maybe FilePath }
deriving (Show)
newtype GitReader a = GitReader (ReaderT GitConfig IO a)
deriving (Monad, MonadIO, MonadReader GitConfig)
runGit :: GitConfig -> GitReader t -> IO t
runGit config (GitReader a) = runReaderT a config
data GitCommand = GitCommand
{ gitCmd :: Text
, args :: [Text] }
deriving (Show)
createGitProcess :: GitCommand -> GitReader CreateProcess
createGitProcess command = do
conf <- ask
return $ createGitProcess' conf command
createGitProcess' :: GitConfig -> GitCommand -> CreateProcess
createGitProcess' GitConfig { gitCwd = gitCwd', gitPath = gitPath }
GitCommand { gitCmd = cmd, args = args'}
= (proc (fromMaybe "git" gitPath) args'')
{ cwd = Just gitCwd'
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
, close_fds = True }
where args'' = map T.unpack $ cmd : args'
spawnGitProcess :: GitCommand
-> GitReader (Handle, Handle, Handle, ProcessHandle)
spawnGitProcess command = do
proc <- createGitProcess command
(Just inh, Just outh, Just errh, pid) <- liftIO $ createProcess proc
return (inh, outh, errh, pid)
type ID = Text
type CommitID = ID
type BlobID = ID
type TreeID = ID
type TagID = ID
data GitObject = Commit CommitID
| Blob BlobID
| Tree TreeID
| Tag TagID
deriving (Show, Eq)
data Person = Person
{ personName :: Text
, personEmail :: Text
} deriving (Show)
data Commitent = Commitent
{ ceParents :: [CommitID]
, ceTree :: TreeID
, ceAuthor :: Person
, ceAuthorTime :: Text
, ceCommitter :: Person
, ceCommitterTime :: Text
, ceCommitMsg :: Text
} deriving (Show)
data TreeNode = TreeNode
{ mode :: Int
, object :: GitObject
, name :: FilePath }
deriving (Show)
data Tag = FilePath
data Trees = Trees [TreeNode]
deriving (Show)
readGitObject :: Text -> GitObject
readGitObject str = makeGitObject t id
where x = T.words str
t = head x
id = last x
idFromGitObject :: GitObject -> ID
idFromGitObject (Commit id) = id
idFromGitObject (Blob id) = id
idFromGitObject (Tag id) = id
idFromGitObject (Tree id) = id
gitObjectToString :: GitObject -> Text
gitObjectToString (Commit id) = T.unwords [T.pack "commit", id]
gitObjectToString (Blob id) = T.unwords [T.pack "blob" , id]
gitObjectToString (Tag id) = T.unwords [T.pack "tag" , id]
gitObjectToString (Tree id) = T.unwords [T.pack "tree" , id]
objReader :: [ (Text, ID -> GitObject) ]
objReader = [ (T.pack "commit" , Commit )
, (T.pack "blob" , Blob )
, (T.pack "tag" , Tag )
, (T.pack "tree" , Tree ) ]
makeGitObject :: Text -> ID -> GitObject
makeGitObject t id = c id
where c = snd $ fromJust $ find (\(x,n) -> t == x) objReader
|
MarcusWalz/hgit
|
Lib/HGit/Data.hs
|
Haskell
|
bsd-3-clause
| 3,658
|
{-# LANGUAGE QuasiQuotes #-}
module Output.Totals where
import Control.Lens
import Data.List (sortBy)
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Ord (comparing)
import Data.Ratio
import Data.Time.Calendar (Day)
import NewTTRS.Law
import Text.Hamlet (Html, shamlet)
import qualified Data.Map as Map
import DataStore
import Output.Common
import Player
tournamentColumns :: Int
tournamentColumns = 2
totalsHtml ::
Map PlayerId Player ->
Map (PlayerId, PlayerId) Int ->
Map PlayerId (Day, Law) ->
Html
totalsHtml players matches laws = [shamlet|
$doctype 5
<html>
<head>
^{metaTags}
<title>#{title}
<link rel=stylesheet type=text/css href=/static/common.css>
<link rel=stylesheet type=text/css href=/static/results.css>
<body>
^{navigationLinks}
<h1>#{title}
^{matchesMatrix players matches sortedPlayerIds}
$forall playerId <- sortedPlayerIds
$with Just player <- Map.lookup playerId players
<div .resultbox>
<span .playername>
^{playerLink playerId player}
<table .data>
<tr>
<th>Opponent
<th>W
<th>L
<th>Σ
<th>%
<th>Share
$forall opponentId <- sortedPlayerIds
$with Just opponent <- Map.lookup opponentId players
$with wins <- look playerId opponentId
$with losses <- look opponentId playerId
$if isInteresting wins losses
<tr>
<td>
^{playerLink opponentId opponent}
<td .num>#{wins}
<td .num>#{losses}
<td .num>#{plus wins losses}
<td .num>#{ratio wins losses}
<td .num>#{ratio (plus wins losses) (played opponentId)}
$else
<tr>
<td>
^{playerLink opponentId opponent}
<td>
<td>
<td>
<td>
<td>
<tr>
<th>Totals
$with totalWins <- countWins playerId
$with totalLosses <- countLosses playerId
<td .num>#{totalWins}
<td .num>#{totalLosses}
<td .num>#{plus totalWins totalLosses}
<td .num>#{ratio totalWins totalLosses}
<td>N/A
|]
where
title = "Totals"
look winner loser = view (at (winner,loser) . non 0) matches
isInteresting wins losses = wins > 0 || losses > 0
plus = (+)
sortedPlayerIds :: [PlayerId]
sortedPlayerIds
= map fst
$ sortBy (flip (comparing (lawScore . snd . snd)))
$ Map.toList laws
ratio wins losses = show (round (wins % (wins + losses) * 100) :: Integer)
played playerId = fromJust $ Map.lookup playerId playedMap
playedMap = Map.fromListWith (+)
[ (playerId, n)
| ((w,l),n) <- Map.toList matches
, playerId <- [w,l]
]
countWins p = sum [n | ((w,_),n) <- Map.toList matches, p == w]
countLosses p = sum [n | ((_,l),n) <- Map.toList matches, p == l]
matchesMatrix :: Map PlayerId Player -> Map (PlayerId, PlayerId) Int -> [PlayerId] -> Html
matchesMatrix players matches sortedPlayerIds = [shamlet|
<table .data>
$forall playerId <- sortedPlayerIds
<tr>
$with Just player <- Map.lookup playerId players
<th>^{playerLink playerId player}
$forall opponentId <- sortedPlayerIds
$if playerId == opponentId
<th>
$else
<td .num>
$maybe n <- Map.lookup (playerId, opponentId) matches
#{n}
|]
|
glguy/tt-ratings
|
Output/Totals.hs
|
Haskell
|
bsd-3-clause
| 3,726
|
import System.Environment
import System.Directory
-- | A fake version of gcc that simply echos its last argument.
-- This is to replicate the --print-file-name flag of gcc
-- which is the only functionality of gcc that GHC needs.
main :: IO ()
main = do
args <- getArgs
if null args then return () else do
let input = last args
-- In the case of .a files, which are newly needed as of 8.0.1,
-- (libmingw32.a and libmingwex.a as deps of ghc-prim)
-- we must return an absolute path as they are handled by a separate
-- part of the GHC linker than DLLs (which are passed to Windows own
-- search mechanisms, which include the current directory)
-- See https://phabricator.haskell.org/D1805#69313
putStrLn =<< case input of
"libmingw32.a" -> makeAbsolute input
"libmingwex.a" -> makeAbsolute input
other -> return other
|
lukexi/rumpus
|
util/fakeGCC.hs
|
Haskell
|
bsd-3-clause
| 936
|
#define IncludedmakeIndicesNull
makeIndicesNull :: RString -> RString -> Integer -> Integer -> Proof
{-@ makeIndicesNull
:: s:RString
-> t:RString
-> lo:INat
-> hi:{Integer | (stringLen t < 2 + stringLen s && 1 + stringLen s - stringLen t <= lo && lo <= hi)
|| (1 + stringLen s <= stringLen t)
|| (stringLen s < lo + stringLen t)
|| (stringLen s < stringLen t)}
-> {makeIndices s t lo hi == N } / [hi - lo +1] @-}
makeIndicesNull s1 t lo hi
| hi < lo
= makeIndices s1 t lo hi ==. N *** QED
| lo == hi, not (isGoodIndex s1 t lo)
= makeIndices s1 t lo hi
==. makeIndices s1 t (lo+1) lo
==. N *** QED
| not (isGoodIndex s1 t lo)
= makeIndices s1 t lo hi
==. makeIndices s1 t (lo + 1) hi
==. N ? makeIndicesNull s1 t (lo+1) hi
*** QED
|
nikivazou/verified_string_matching
|
src/Proofs/makeIndicesNull.hs
|
Haskell
|
bsd-3-clause
| 819
|
{-# LANGUAGE Rank2Types, GADTs #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
module InterfacesRules where
{-# LINE 2 "./src-ag/Interfaces.ag" #-}
import CommonTypes
import SequentialTypes
{-# LINE 11 "dist/build/InterfacesRules.hs" #-}
{-# LINE 10 "./src-ag/InterfacesRules.lag" #-}
import Interfaces
import CodeSyntax
import GrammarInfo
import qualified Data.Sequence as Seq
import Data.Sequence(Seq)
import qualified Data.Map as Map
import Data.Map(Map)
import Data.Tree(Tree(Node), Forest)
import Data.Graph(Graph, dfs, edges, buildG, transposeG)
import Data.Maybe (fromJust)
import Data.List (partition,transpose,(\\),nub,findIndex)
import Data.Array ((!),inRange,bounds,assocs)
import Data.Foldable(toList)
{-# LINE 29 "dist/build/InterfacesRules.hs" #-}
import Control.Monad.Identity (Identity)
import qualified Control.Monad.Identity
{-# LINE 53 "./src-ag/InterfacesRules.lag" #-}
type VisitSS = [Vertex]
{-# LINE 35 "dist/build/InterfacesRules.hs" #-}
{-# LINE 88 "./src-ag/InterfacesRules.lag" #-}
gather :: Info -> [Vertex] -> [[Vertex]]
gather info = eqClasses comp
where comp a b = isEqualField (ruleTable info ! a) (ruleTable info ! b)
{-# LINE 42 "dist/build/InterfacesRules.hs" #-}
{-# LINE 129 "./src-ag/InterfacesRules.lag" #-}
-- Only non-empty syn will ever be forced, because visits with empty syn are never performed
-- Right hand side synthesized attributes always have a field
cv :: (Vertex -> CRule) -> Int -> Vertex -> ([Vertex],[Vertex]) -> (Vertex,ChildVisit)
cv look n v (inh,syn) = let fld = getField (look (head syn))
rnt = fromJust (getRhsNt (look (head syn)))
d = ChildVisit fld rnt n inh syn
in (v,d)
{-# LINE 53 "dist/build/InterfacesRules.hs" #-}
{-# LINE 152 "./src-ag/InterfacesRules.lag" #-}
ed :: Vertex -> ([Vertex], [Vertex]) -> [(Vertex, Vertex)]
ed v (inh,syn) = map (\i -> (i,v)) inh ++ map (\s -> (v,s)) syn
{-# LINE 59 "dist/build/InterfacesRules.hs" #-}
{-# LINE 240 "./src-ag/InterfacesRules.lag" #-}
postorder :: Tree a -> [a]
postorder (Node a ts) = postorderF ts ++ [a]
postorderF :: Forest a -> [a]
postorderF = concatMap postorder
postOrd :: Graph -> [Vertex] -> [Vertex]
postOrd g = postorderF . dfs g
topSort' :: Graph -> [Vertex] -> [Vertex]
topSort' g = postOrd g
{-# LINE 71 "dist/build/InterfacesRules.hs" #-}
{-# LINE 323 "./src-ag/InterfacesRules.lag" #-}
type IntraVisit = [Vertex]
{-# LINE 76 "dist/build/InterfacesRules.hs" #-}
{-# LINE 345 "./src-ag/InterfacesRules.lag" #-}
swap :: (a,b) -> (b,a)
swap (a,b) = (b,a)
{-# LINE 82 "dist/build/InterfacesRules.hs" #-}
{-# LINE 420 "./src-ag/InterfacesRules.lag" #-}
ccv :: Identifier -> NontermIdent -> Int -> CInterfaceMap -> CRule
ccv name nt n table
= CChildVisit name nt n inh syn lst
where CInterface segs = Map.findWithDefault (error ("InterfacesRules::ccv::interfaces not in table for nt: " ++ show nt)) nt table
(seg:remain) = drop n segs
CSegment inh syn = seg
lst = null remain
{-# LINE 93 "dist/build/InterfacesRules.hs" #-}
-- IRoot -------------------------------------------------------
-- wrapper
data Inh_IRoot = Inh_IRoot { dpr_Inh_IRoot :: !([Edge]), info_Inh_IRoot :: !(Info), tdp_Inh_IRoot :: !(Graph) }
data Syn_IRoot = Syn_IRoot { edp_Syn_IRoot :: !([Edge]), inters_Syn_IRoot :: !(CInterfaceMap), visits_Syn_IRoot :: !(CVisitsMap) }
{-# INLINABLE wrap_IRoot #-}
wrap_IRoot :: T_IRoot -> Inh_IRoot -> (Syn_IRoot )
wrap_IRoot !(T_IRoot act) !(Inh_IRoot _lhsIdpr _lhsIinfo _lhsItdp) =
Control.Monad.Identity.runIdentity (
do !sem <- act
let arg = T_IRoot_vIn1 _lhsIdpr _lhsIinfo _lhsItdp
!(T_IRoot_vOut1 _lhsOedp _lhsOinters _lhsOvisits) <- return (inv_IRoot_s2 sem arg)
return (Syn_IRoot _lhsOedp _lhsOinters _lhsOvisits)
)
-- cata
{-# INLINE sem_IRoot #-}
sem_IRoot :: IRoot -> T_IRoot
sem_IRoot ( IRoot inters_ ) = sem_IRoot_IRoot ( sem_Interfaces inters_ )
-- semantic domain
newtype T_IRoot = T_IRoot {
attach_T_IRoot :: Identity (T_IRoot_s2 )
}
newtype T_IRoot_s2 = C_IRoot_s2 {
inv_IRoot_s2 :: (T_IRoot_v1 )
}
data T_IRoot_s3 = C_IRoot_s3
type T_IRoot_v1 = (T_IRoot_vIn1 ) -> (T_IRoot_vOut1 )
data T_IRoot_vIn1 = T_IRoot_vIn1 ([Edge]) (Info) (Graph)
data T_IRoot_vOut1 = T_IRoot_vOut1 ([Edge]) (CInterfaceMap) (CVisitsMap)
{-# NOINLINE sem_IRoot_IRoot #-}
sem_IRoot_IRoot :: T_Interfaces -> T_IRoot
sem_IRoot_IRoot arg_inters_ = T_IRoot (return st2) where
{-# NOINLINE st2 #-}
!st2 = let
v1 :: T_IRoot_v1
v1 = \ !(T_IRoot_vIn1 _lhsIdpr _lhsIinfo _lhsItdp) -> ( let
_intersX8 = Control.Monad.Identity.runIdentity (attach_T_Interfaces (arg_inters_))
(T_Interfaces_vOut7 _intersIdescr _intersIedp _intersIfirstvisitvertices _intersIinters _intersInewedges _intersIv _intersIvisits) = inv_Interfaces_s8 _intersX8 (T_Interfaces_vIn7 _intersOallInters _intersOddp _intersOinfo _intersOprev _intersOv _intersOvisitDescr _intersOvssGraph)
_newedges = rule0 _intersInewedges
_visitssGraph = rule1 _intersIv _lhsItdp _newedges
_intersOv = rule2 _lhsItdp
_intersOvisitDescr = rule3 _descr
_descr = rule4 _intersIdescr
_intersOvssGraph = rule5 _visitssGraph
_intersOprev = rule6 _intersIfirstvisitvertices _lhsIinfo
_intersOddp = rule7 _intersIv _lhsIdpr _newedges
_intersOallInters = rule8 _intersIinters
_lhsOedp :: [Edge]
_lhsOedp = rule9 _intersIedp
_lhsOinters :: CInterfaceMap
_lhsOinters = rule10 _intersIinters
_lhsOvisits :: CVisitsMap
_lhsOvisits = rule11 _intersIvisits
_intersOinfo = rule12 _lhsIinfo
!__result_ = T_IRoot_vOut1 _lhsOedp _lhsOinters _lhsOvisits
in __result_ )
in C_IRoot_s2 v1
{-# INLINE rule0 #-}
{-# LINE 66 "./src-ag/InterfacesRules.lag" #-}
rule0 = \ ((_intersInewedges) :: Seq Edge ) ->
{-# LINE 66 "./src-ag/InterfacesRules.lag" #-}
toList _intersInewedges
{-# LINE 157 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule1 #-}
{-# LINE 67 "./src-ag/InterfacesRules.lag" #-}
rule1 = \ ((_intersIv) :: Vertex) ((_lhsItdp) :: Graph) _newedges ->
{-# LINE 67 "./src-ag/InterfacesRules.lag" #-}
let graph = buildG (0,_intersIv-1) es
es = _newedges ++ edges _lhsItdp
in transposeG graph
{-# LINE 165 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule2 #-}
{-# LINE 80 "./src-ag/InterfacesRules.lag" #-}
rule2 = \ ((_lhsItdp) :: Graph) ->
{-# LINE 80 "./src-ag/InterfacesRules.lag" #-}
snd (bounds _lhsItdp) + 1
{-# LINE 171 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule3 #-}
{-# LINE 122 "./src-ag/InterfacesRules.lag" #-}
rule3 = \ _descr ->
{-# LINE 122 "./src-ag/InterfacesRules.lag" #-}
Map.fromList _descr
{-# LINE 177 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule4 #-}
{-# LINE 142 "./src-ag/InterfacesRules.lag" #-}
rule4 = \ ((_intersIdescr) :: Seq (Vertex,ChildVisit)) ->
{-# LINE 142 "./src-ag/InterfacesRules.lag" #-}
toList _intersIdescr
{-# LINE 183 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule5 #-}
{-# LINE 214 "./src-ag/InterfacesRules.lag" #-}
rule5 = \ _visitssGraph ->
{-# LINE 214 "./src-ag/InterfacesRules.lag" #-}
_visitssGraph
{-# LINE 189 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule6 #-}
{-# LINE 260 "./src-ag/InterfacesRules.lag" #-}
rule6 = \ ((_intersIfirstvisitvertices) :: [Vertex]) ((_lhsIinfo) :: Info) ->
{-# LINE 260 "./src-ag/InterfacesRules.lag" #-}
let terminals = [ v | (v,cr) <- assocs (ruleTable _lhsIinfo), not (getHasCode cr), isLocal cr ]
in _intersIfirstvisitvertices ++ terminals
{-# LINE 196 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule7 #-}
{-# LINE 343 "./src-ag/InterfacesRules.lag" #-}
rule7 = \ ((_intersIv) :: Vertex) ((_lhsIdpr) :: [Edge]) _newedges ->
{-# LINE 343 "./src-ag/InterfacesRules.lag" #-}
buildG (0,_intersIv-1) (map swap (_lhsIdpr ++ _newedges))
{-# LINE 202 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule8 #-}
{-# LINE 381 "./src-ag/InterfacesRules.lag" #-}
rule8 = \ ((_intersIinters) :: CInterfaceMap) ->
{-# LINE 381 "./src-ag/InterfacesRules.lag" #-}
_intersIinters
{-# LINE 208 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule9 #-}
{-# LINE 443 "./src-ag/InterfacesRules.lag" #-}
rule9 = \ ((_intersIedp) :: Seq Edge) ->
{-# LINE 443 "./src-ag/InterfacesRules.lag" #-}
toList _intersIedp
{-# LINE 214 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule10 #-}
rule10 = \ ((_intersIinters) :: CInterfaceMap) ->
_intersIinters
{-# INLINE rule11 #-}
rule11 = \ ((_intersIvisits) :: CVisitsMap) ->
_intersIvisits
{-# INLINE rule12 #-}
rule12 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
-- Interface ---------------------------------------------------
-- wrapper
data Inh_Interface = Inh_Interface { allInters_Inh_Interface :: !(CInterfaceMap), ddp_Inh_Interface :: !(Graph), info_Inh_Interface :: !(Info), prev_Inh_Interface :: !([Vertex]), v_Inh_Interface :: !(Vertex), visitDescr_Inh_Interface :: !(Map Vertex ChildVisit), vssGraph_Inh_Interface :: !(Graph) }
data Syn_Interface = Syn_Interface { descr_Syn_Interface :: !(Seq (Vertex,ChildVisit)), edp_Syn_Interface :: !(Seq Edge), firstvisitvertices_Syn_Interface :: !([Vertex]), inter_Syn_Interface :: !(CInterface), newedges_Syn_Interface :: !(Seq Edge ), nt_Syn_Interface :: !(NontermIdent), v_Syn_Interface :: !(Vertex), visits_Syn_Interface :: !(Map ConstructorIdent CVisits) }
{-# INLINABLE wrap_Interface #-}
wrap_Interface :: T_Interface -> Inh_Interface -> (Syn_Interface )
wrap_Interface !(T_Interface act) !(Inh_Interface _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) =
Control.Monad.Identity.runIdentity (
do !sem <- act
let arg = T_Interface_vIn4 _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph
!(T_Interface_vOut4 _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinter _lhsOnewedges _lhsOnt _lhsOv _lhsOvisits) <- return (inv_Interface_s5 sem arg)
return (Syn_Interface _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinter _lhsOnewedges _lhsOnt _lhsOv _lhsOvisits)
)
-- cata
{-# INLINE sem_Interface #-}
sem_Interface :: Interface -> T_Interface
sem_Interface ( Interface !nt_ !cons_ seg_ ) = sem_Interface_Interface nt_ cons_ ( sem_Segments seg_ )
-- semantic domain
newtype T_Interface = T_Interface {
attach_T_Interface :: Identity (T_Interface_s5 )
}
newtype T_Interface_s5 = C_Interface_s5 {
inv_Interface_s5 :: (T_Interface_v4 )
}
data T_Interface_s6 = C_Interface_s6
type T_Interface_v4 = (T_Interface_vIn4 ) -> (T_Interface_vOut4 )
data T_Interface_vIn4 = T_Interface_vIn4 (CInterfaceMap) (Graph) (Info) ([Vertex]) (Vertex) (Map Vertex ChildVisit) (Graph)
data T_Interface_vOut4 = T_Interface_vOut4 (Seq (Vertex,ChildVisit)) (Seq Edge) ([Vertex]) (CInterface) (Seq Edge ) (NontermIdent) (Vertex) (Map ConstructorIdent CVisits)
{-# NOINLINE sem_Interface_Interface #-}
sem_Interface_Interface :: (NontermIdent) -> ([ConstructorIdent]) -> T_Segments -> T_Interface
sem_Interface_Interface !arg_nt_ !arg_cons_ arg_seg_ = T_Interface (return st5) where
{-# NOINLINE st5 #-}
!st5 = let
v4 :: T_Interface_v4
v4 = \ !(T_Interface_vIn4 _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_segX14 = Control.Monad.Identity.runIdentity (attach_T_Segments (arg_seg_))
(T_Segments_vOut13 _segIcvisits _segIdescr _segIedp _segIfirstInh _segIgroups _segIhdIntravisits _segInewedges _segInewvertices _segIprev _segIsegs _segIv) = inv_Segments_s14 _segX14 (T_Segments_vIn13 _segOallInters _segOcons _segOddp _segOfromLhs _segOinfo _segOisFirst _segOn _segOprev _segOv _segOvisitDescr _segOvssGraph)
_segOv = rule13 _lhsIv
_v = rule14 _segInewvertices _segIv
_lhsOv :: Vertex
_lhsOv = rule15 _v
_firstvisitvertices = rule16 _segIv _v
_newedges = rule17 _firstvisitvertices _segInewvertices
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule18 _newedges _segInewedges
_look :: Vertex -> CRule
_look = rule19 _lhsIinfo
_descr = rule20 _firstvisitvertices _look _segIgroups
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule21 _descr _segIdescr
_segOn = rule22 ()
_segOcons = rule23 arg_cons_
_segOisFirst = rule24 ()
_segOfromLhs = rule25 _lhsIprev
_lhsOnt :: NontermIdent
_lhsOnt = rule26 arg_nt_
_lhsOinter :: CInterface
_lhsOinter = rule27 _segIsegs
_lhsOvisits :: Map ConstructorIdent CVisits
_lhsOvisits = rule28 _segIcvisits arg_cons_
_lhsOedp :: Seq Edge
_lhsOedp = rule29 _segIedp
_lhsOfirstvisitvertices :: [Vertex]
_lhsOfirstvisitvertices = rule30 _firstvisitvertices
_segOallInters = rule31 _lhsIallInters
_segOddp = rule32 _lhsIddp
_segOinfo = rule33 _lhsIinfo
_segOprev = rule34 _lhsIprev
_segOvisitDescr = rule35 _lhsIvisitDescr
_segOvssGraph = rule36 _lhsIvssGraph
!__result_ = T_Interface_vOut4 _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinter _lhsOnewedges _lhsOnt _lhsOv _lhsOvisits
in __result_ )
in C_Interface_s5 v4
{-# INLINE rule13 #-}
{-# LINE 183 "./src-ag/InterfacesRules.lag" #-}
rule13 = \ ((_lhsIv) :: Vertex) ->
{-# LINE 183 "./src-ag/InterfacesRules.lag" #-}
_lhsIv
{-# LINE 305 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule14 #-}
{-# LINE 184 "./src-ag/InterfacesRules.lag" #-}
rule14 = \ ((_segInewvertices) :: [Vertex]) ((_segIv) :: Vertex) ->
{-# LINE 184 "./src-ag/InterfacesRules.lag" #-}
_segIv + length _segInewvertices
{-# LINE 311 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule15 #-}
{-# LINE 185 "./src-ag/InterfacesRules.lag" #-}
rule15 = \ _v ->
{-# LINE 185 "./src-ag/InterfacesRules.lag" #-}
_v
{-# LINE 317 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule16 #-}
{-# LINE 186 "./src-ag/InterfacesRules.lag" #-}
rule16 = \ ((_segIv) :: Vertex) _v ->
{-# LINE 186 "./src-ag/InterfacesRules.lag" #-}
[_segIv .. _v-1]
{-# LINE 323 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule17 #-}
{-# LINE 187 "./src-ag/InterfacesRules.lag" #-}
rule17 = \ _firstvisitvertices ((_segInewvertices) :: [Vertex]) ->
{-# LINE 187 "./src-ag/InterfacesRules.lag" #-}
zip _firstvisitvertices _segInewvertices
{-# LINE 329 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule18 #-}
{-# LINE 188 "./src-ag/InterfacesRules.lag" #-}
rule18 = \ _newedges ((_segInewedges) :: Seq Edge ) ->
{-# LINE 188 "./src-ag/InterfacesRules.lag" #-}
_segInewedges Seq.>< Seq.fromList _newedges
{-# LINE 335 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule19 #-}
{-# LINE 191 "./src-ag/InterfacesRules.lag" #-}
rule19 = \ ((_lhsIinfo) :: Info) ->
{-# LINE 191 "./src-ag/InterfacesRules.lag" #-}
\a -> ruleTable _lhsIinfo ! a
{-# LINE 341 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule20 #-}
{-# LINE 192 "./src-ag/InterfacesRules.lag" #-}
rule20 = \ _firstvisitvertices ((_look) :: Vertex -> CRule) ((_segIgroups) :: [([Vertex],[Vertex])]) ->
{-# LINE 192 "./src-ag/InterfacesRules.lag" #-}
zipWith (cv _look (-1)) _firstvisitvertices _segIgroups
{-# LINE 347 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule21 #-}
{-# LINE 193 "./src-ag/InterfacesRules.lag" #-}
rule21 = \ _descr ((_segIdescr) :: Seq (Vertex,ChildVisit)) ->
{-# LINE 193 "./src-ag/InterfacesRules.lag" #-}
_segIdescr Seq.>< Seq.fromList _descr
{-# LINE 353 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule22 #-}
{-# LINE 201 "./src-ag/InterfacesRules.lag" #-}
rule22 = \ (_ :: ()) ->
{-# LINE 201 "./src-ag/InterfacesRules.lag" #-}
0
{-# LINE 359 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule23 #-}
{-# LINE 233 "./src-ag/InterfacesRules.lag" #-}
rule23 = \ cons_ ->
{-# LINE 233 "./src-ag/InterfacesRules.lag" #-}
cons_
{-# LINE 365 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule24 #-}
{-# LINE 314 "./src-ag/InterfacesRules.lag" #-}
rule24 = \ (_ :: ()) ->
{-# LINE 314 "./src-ag/InterfacesRules.lag" #-}
True
{-# LINE 371 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule25 #-}
{-# LINE 352 "./src-ag/InterfacesRules.lag" #-}
rule25 = \ ((_lhsIprev) :: [Vertex]) ->
{-# LINE 352 "./src-ag/InterfacesRules.lag" #-}
_lhsIprev
{-# LINE 377 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule26 #-}
{-# LINE 392 "./src-ag/InterfacesRules.lag" #-}
rule26 = \ nt_ ->
{-# LINE 392 "./src-ag/InterfacesRules.lag" #-}
nt_
{-# LINE 383 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule27 #-}
{-# LINE 396 "./src-ag/InterfacesRules.lag" #-}
rule27 = \ ((_segIsegs) :: CSegments) ->
{-# LINE 396 "./src-ag/InterfacesRules.lag" #-}
CInterface _segIsegs
{-# LINE 389 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule28 #-}
{-# LINE 397 "./src-ag/InterfacesRules.lag" #-}
rule28 = \ ((_segIcvisits) :: [[CVisit]]) cons_ ->
{-# LINE 397 "./src-ag/InterfacesRules.lag" #-}
Map.fromList (zip cons_ (transpose _segIcvisits))
{-# LINE 395 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule29 #-}
rule29 = \ ((_segIedp) :: Seq Edge) ->
_segIedp
{-# INLINE rule30 #-}
rule30 = \ _firstvisitvertices ->
_firstvisitvertices
{-# INLINE rule31 #-}
rule31 = \ ((_lhsIallInters) :: CInterfaceMap) ->
_lhsIallInters
{-# INLINE rule32 #-}
rule32 = \ ((_lhsIddp) :: Graph) ->
_lhsIddp
{-# INLINE rule33 #-}
rule33 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
{-# INLINE rule34 #-}
rule34 = \ ((_lhsIprev) :: [Vertex]) ->
_lhsIprev
{-# INLINE rule35 #-}
rule35 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ->
_lhsIvisitDescr
{-# INLINE rule36 #-}
rule36 = \ ((_lhsIvssGraph) :: Graph) ->
_lhsIvssGraph
-- Interfaces --------------------------------------------------
-- wrapper
data Inh_Interfaces = Inh_Interfaces { allInters_Inh_Interfaces :: !(CInterfaceMap), ddp_Inh_Interfaces :: !(Graph), info_Inh_Interfaces :: !(Info), prev_Inh_Interfaces :: !([Vertex]), v_Inh_Interfaces :: !(Vertex), visitDescr_Inh_Interfaces :: !(Map Vertex ChildVisit), vssGraph_Inh_Interfaces :: !(Graph) }
data Syn_Interfaces = Syn_Interfaces { descr_Syn_Interfaces :: !(Seq (Vertex,ChildVisit)), edp_Syn_Interfaces :: !(Seq Edge), firstvisitvertices_Syn_Interfaces :: !([Vertex]), inters_Syn_Interfaces :: !(CInterfaceMap), newedges_Syn_Interfaces :: !(Seq Edge ), v_Syn_Interfaces :: !(Vertex), visits_Syn_Interfaces :: !(CVisitsMap) }
{-# INLINABLE wrap_Interfaces #-}
wrap_Interfaces :: T_Interfaces -> Inh_Interfaces -> (Syn_Interfaces )
wrap_Interfaces !(T_Interfaces act) !(Inh_Interfaces _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) =
Control.Monad.Identity.runIdentity (
do !sem <- act
let arg = T_Interfaces_vIn7 _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph
!(T_Interfaces_vOut7 _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinters _lhsOnewedges _lhsOv _lhsOvisits) <- return (inv_Interfaces_s8 sem arg)
return (Syn_Interfaces _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinters _lhsOnewedges _lhsOv _lhsOvisits)
)
-- cata
{-# NOINLINE sem_Interfaces #-}
sem_Interfaces :: Interfaces -> T_Interfaces
sem_Interfaces list = Prelude.foldr sem_Interfaces_Cons sem_Interfaces_Nil (Prelude.map sem_Interface list)
-- semantic domain
newtype T_Interfaces = T_Interfaces {
attach_T_Interfaces :: Identity (T_Interfaces_s8 )
}
newtype T_Interfaces_s8 = C_Interfaces_s8 {
inv_Interfaces_s8 :: (T_Interfaces_v7 )
}
data T_Interfaces_s9 = C_Interfaces_s9
type T_Interfaces_v7 = (T_Interfaces_vIn7 ) -> (T_Interfaces_vOut7 )
data T_Interfaces_vIn7 = T_Interfaces_vIn7 (CInterfaceMap) (Graph) (Info) ([Vertex]) (Vertex) (Map Vertex ChildVisit) (Graph)
data T_Interfaces_vOut7 = T_Interfaces_vOut7 (Seq (Vertex,ChildVisit)) (Seq Edge) ([Vertex]) (CInterfaceMap) (Seq Edge ) (Vertex) (CVisitsMap)
{-# NOINLINE sem_Interfaces_Cons #-}
sem_Interfaces_Cons :: T_Interface -> T_Interfaces -> T_Interfaces
sem_Interfaces_Cons arg_hd_ arg_tl_ = T_Interfaces (return st8) where
{-# NOINLINE st8 #-}
!st8 = let
v7 :: T_Interfaces_v7
v7 = \ !(T_Interfaces_vIn7 _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_hdX5 = Control.Monad.Identity.runIdentity (attach_T_Interface (arg_hd_))
_tlX8 = Control.Monad.Identity.runIdentity (attach_T_Interfaces (arg_tl_))
(T_Interface_vOut4 _hdIdescr _hdIedp _hdIfirstvisitvertices _hdIinter _hdInewedges _hdInt _hdIv _hdIvisits) = inv_Interface_s5 _hdX5 (T_Interface_vIn4 _hdOallInters _hdOddp _hdOinfo _hdOprev _hdOv _hdOvisitDescr _hdOvssGraph)
(T_Interfaces_vOut7 _tlIdescr _tlIedp _tlIfirstvisitvertices _tlIinters _tlInewedges _tlIv _tlIvisits) = inv_Interfaces_s8 _tlX8 (T_Interfaces_vIn7 _tlOallInters _tlOddp _tlOinfo _tlOprev _tlOv _tlOvisitDescr _tlOvssGraph)
_lhsOinters :: CInterfaceMap
_lhsOinters = rule37 _hdIinter _hdInt _tlIinters
_lhsOvisits :: CVisitsMap
_lhsOvisits = rule38 _hdInt _hdIvisits _tlIvisits
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule39 _hdIdescr _tlIdescr
_lhsOedp :: Seq Edge
_lhsOedp = rule40 _hdIedp _tlIedp
_lhsOfirstvisitvertices :: [Vertex]
_lhsOfirstvisitvertices = rule41 _hdIfirstvisitvertices _tlIfirstvisitvertices
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule42 _hdInewedges _tlInewedges
_lhsOv :: Vertex
_lhsOv = rule43 _tlIv
_hdOallInters = rule44 _lhsIallInters
_hdOddp = rule45 _lhsIddp
_hdOinfo = rule46 _lhsIinfo
_hdOprev = rule47 _lhsIprev
_hdOv = rule48 _lhsIv
_hdOvisitDescr = rule49 _lhsIvisitDescr
_hdOvssGraph = rule50 _lhsIvssGraph
_tlOallInters = rule51 _lhsIallInters
_tlOddp = rule52 _lhsIddp
_tlOinfo = rule53 _lhsIinfo
_tlOprev = rule54 _lhsIprev
_tlOv = rule55 _hdIv
_tlOvisitDescr = rule56 _lhsIvisitDescr
_tlOvssGraph = rule57 _lhsIvssGraph
!__result_ = T_Interfaces_vOut7 _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinters _lhsOnewedges _lhsOv _lhsOvisits
in __result_ )
in C_Interfaces_s8 v7
{-# INLINE rule37 #-}
{-# LINE 386 "./src-ag/InterfacesRules.lag" #-}
rule37 = \ ((_hdIinter) :: CInterface) ((_hdInt) :: NontermIdent) ((_tlIinters) :: CInterfaceMap) ->
{-# LINE 386 "./src-ag/InterfacesRules.lag" #-}
Map.insert _hdInt _hdIinter _tlIinters
{-# LINE 498 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule38 #-}
{-# LINE 387 "./src-ag/InterfacesRules.lag" #-}
rule38 = \ ((_hdInt) :: NontermIdent) ((_hdIvisits) :: Map ConstructorIdent CVisits) ((_tlIvisits) :: CVisitsMap) ->
{-# LINE 387 "./src-ag/InterfacesRules.lag" #-}
Map.insert _hdInt _hdIvisits _tlIvisits
{-# LINE 504 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule39 #-}
rule39 = \ ((_hdIdescr) :: Seq (Vertex,ChildVisit)) ((_tlIdescr) :: Seq (Vertex,ChildVisit)) ->
_hdIdescr Seq.>< _tlIdescr
{-# INLINE rule40 #-}
rule40 = \ ((_hdIedp) :: Seq Edge) ((_tlIedp) :: Seq Edge) ->
_hdIedp Seq.>< _tlIedp
{-# INLINE rule41 #-}
rule41 = \ ((_hdIfirstvisitvertices) :: [Vertex]) ((_tlIfirstvisitvertices) :: [Vertex]) ->
_hdIfirstvisitvertices ++ _tlIfirstvisitvertices
{-# INLINE rule42 #-}
rule42 = \ ((_hdInewedges) :: Seq Edge ) ((_tlInewedges) :: Seq Edge ) ->
_hdInewedges Seq.>< _tlInewedges
{-# INLINE rule43 #-}
rule43 = \ ((_tlIv) :: Vertex) ->
_tlIv
{-# INLINE rule44 #-}
rule44 = \ ((_lhsIallInters) :: CInterfaceMap) ->
_lhsIallInters
{-# INLINE rule45 #-}
rule45 = \ ((_lhsIddp) :: Graph) ->
_lhsIddp
{-# INLINE rule46 #-}
rule46 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
{-# INLINE rule47 #-}
rule47 = \ ((_lhsIprev) :: [Vertex]) ->
_lhsIprev
{-# INLINE rule48 #-}
rule48 = \ ((_lhsIv) :: Vertex) ->
_lhsIv
{-# INLINE rule49 #-}
rule49 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ->
_lhsIvisitDescr
{-# INLINE rule50 #-}
rule50 = \ ((_lhsIvssGraph) :: Graph) ->
_lhsIvssGraph
{-# INLINE rule51 #-}
rule51 = \ ((_lhsIallInters) :: CInterfaceMap) ->
_lhsIallInters
{-# INLINE rule52 #-}
rule52 = \ ((_lhsIddp) :: Graph) ->
_lhsIddp
{-# INLINE rule53 #-}
rule53 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
{-# INLINE rule54 #-}
rule54 = \ ((_lhsIprev) :: [Vertex]) ->
_lhsIprev
{-# INLINE rule55 #-}
rule55 = \ ((_hdIv) :: Vertex) ->
_hdIv
{-# INLINE rule56 #-}
rule56 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ->
_lhsIvisitDescr
{-# INLINE rule57 #-}
rule57 = \ ((_lhsIvssGraph) :: Graph) ->
_lhsIvssGraph
{-# NOINLINE sem_Interfaces_Nil #-}
sem_Interfaces_Nil :: T_Interfaces
sem_Interfaces_Nil = T_Interfaces (return st8) where
{-# NOINLINE st8 #-}
!st8 = let
v7 :: T_Interfaces_v7
v7 = \ !(T_Interfaces_vIn7 _lhsIallInters _lhsIddp _lhsIinfo _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_lhsOinters :: CInterfaceMap
_lhsOinters = rule58 ()
_lhsOvisits :: CVisitsMap
_lhsOvisits = rule59 ()
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule60 ()
_lhsOedp :: Seq Edge
_lhsOedp = rule61 ()
_lhsOfirstvisitvertices :: [Vertex]
_lhsOfirstvisitvertices = rule62 ()
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule63 ()
_lhsOv :: Vertex
_lhsOv = rule64 _lhsIv
!__result_ = T_Interfaces_vOut7 _lhsOdescr _lhsOedp _lhsOfirstvisitvertices _lhsOinters _lhsOnewedges _lhsOv _lhsOvisits
in __result_ )
in C_Interfaces_s8 v7
{-# INLINE rule58 #-}
{-# LINE 388 "./src-ag/InterfacesRules.lag" #-}
rule58 = \ (_ :: ()) ->
{-# LINE 388 "./src-ag/InterfacesRules.lag" #-}
Map.empty
{-# LINE 591 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule59 #-}
{-# LINE 389 "./src-ag/InterfacesRules.lag" #-}
rule59 = \ (_ :: ()) ->
{-# LINE 389 "./src-ag/InterfacesRules.lag" #-}
Map.empty
{-# LINE 597 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule60 #-}
rule60 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule61 #-}
rule61 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule62 #-}
rule62 = \ (_ :: ()) ->
[]
{-# INLINE rule63 #-}
rule63 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule64 #-}
rule64 = \ ((_lhsIv) :: Vertex) ->
_lhsIv
-- Segment -----------------------------------------------------
-- wrapper
data Inh_Segment = Inh_Segment { allInters_Inh_Segment :: !(CInterfaceMap), cons_Inh_Segment :: !([ConstructorIdent]), ddp_Inh_Segment :: !(Graph), fromLhs_Inh_Segment :: !([Vertex]), info_Inh_Segment :: !(Info), isFirst_Inh_Segment :: !(Bool), n_Inh_Segment :: !(Int), nextInh_Inh_Segment :: !([Vertex]), nextIntravisits_Inh_Segment :: !([IntraVisit]), nextNewvertices_Inh_Segment :: !([Vertex]), prev_Inh_Segment :: !([Vertex]), v_Inh_Segment :: !(Vertex), visitDescr_Inh_Segment :: !(Map Vertex ChildVisit), vssGraph_Inh_Segment :: !(Graph) }
data Syn_Segment = Syn_Segment { cvisits_Syn_Segment :: !([CVisit]), descr_Syn_Segment :: !(Seq (Vertex,ChildVisit)), edp_Syn_Segment :: !(Seq Edge), groups_Syn_Segment :: !([([Vertex],[Vertex])]), inh_Syn_Segment :: !([Vertex]), intravisits_Syn_Segment :: !([IntraVisit]), newedges_Syn_Segment :: !(Seq Edge ), newvertices_Syn_Segment :: !([Vertex]), prev_Syn_Segment :: !([Vertex]), seg_Syn_Segment :: !(CSegment), v_Syn_Segment :: !(Vertex), visitss_Syn_Segment :: !([VisitSS]) }
{-# INLINABLE wrap_Segment #-}
wrap_Segment :: T_Segment -> Inh_Segment -> (Syn_Segment )
wrap_Segment !(T_Segment act) !(Inh_Segment _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsInextInh _lhsInextIntravisits _lhsInextNewvertices _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) =
Control.Monad.Identity.runIdentity (
do !sem <- act
let arg = T_Segment_vIn10 _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsInextInh _lhsInextIntravisits _lhsInextNewvertices _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph
!(T_Segment_vOut10 _lhsOcvisits _lhsOdescr _lhsOedp _lhsOgroups _lhsOinh _lhsOintravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOseg _lhsOv _lhsOvisitss) <- return (inv_Segment_s11 sem arg)
return (Syn_Segment _lhsOcvisits _lhsOdescr _lhsOedp _lhsOgroups _lhsOinh _lhsOintravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOseg _lhsOv _lhsOvisitss)
)
-- cata
{-# INLINE sem_Segment #-}
sem_Segment :: Segment -> T_Segment
sem_Segment ( Segment !inh_ !syn_ ) = sem_Segment_Segment inh_ syn_
-- semantic domain
newtype T_Segment = T_Segment {
attach_T_Segment :: Identity (T_Segment_s11 )
}
newtype T_Segment_s11 = C_Segment_s11 {
inv_Segment_s11 :: (T_Segment_v10 )
}
data T_Segment_s12 = C_Segment_s12
type T_Segment_v10 = (T_Segment_vIn10 ) -> (T_Segment_vOut10 )
data T_Segment_vIn10 = T_Segment_vIn10 (CInterfaceMap) ([ConstructorIdent]) (Graph) ([Vertex]) (Info) (Bool) (Int) ([Vertex]) ([IntraVisit]) ([Vertex]) ([Vertex]) (Vertex) (Map Vertex ChildVisit) (Graph)
data T_Segment_vOut10 = T_Segment_vOut10 ([CVisit]) (Seq (Vertex,ChildVisit)) (Seq Edge) ([([Vertex],[Vertex])]) ([Vertex]) ([IntraVisit]) (Seq Edge ) ([Vertex]) ([Vertex]) (CSegment) (Vertex) ([VisitSS])
{-# NOINLINE sem_Segment_Segment #-}
sem_Segment_Segment :: ([Vertex]) -> ([Vertex]) -> T_Segment
sem_Segment_Segment !arg_inh_ !arg_syn_ = T_Segment (return st11) where
{-# NOINLINE st11 #-}
!st11 = let
v10 :: T_Segment_v10
v10 = \ !(T_Segment_vIn10 _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsInextInh _lhsInextIntravisits _lhsInextNewvertices _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_look :: Vertex -> CRule
_look = rule65 _lhsIinfo
_occurAs :: (CRule -> Bool) -> [Vertex] -> [Vertex]
_occurAs = rule66 _lhsIinfo _look
_groups :: [([Vertex],[Vertex])]
_groups = rule67 _lhsIinfo _look _occurAs arg_inh_ arg_syn_
_v :: Int
_v = rule68 _groups _lhsIv
_newvertices = rule69 _lhsIv _v
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule70 _groups _lhsIn _look _newvertices
_attredges = rule71 _groups _newvertices
_visitedges = rule72 _lhsInextNewvertices _newvertices
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule73 _attredges _visitedges
_synOccur = rule74 _lhsIinfo _occurAs arg_syn_
_vss = rule75 _lhsIcons _lhsIinfo _lhsIvssGraph _synOccur arg_syn_
_visitss' = rule76 _lhsIprev _vss
_defined = rule77 _lhsIvisitDescr _visitss
_lhsOprev :: [Vertex]
_lhsOprev = rule78 _defined _lhsIprev
_visitss :: [[Vertex]]
_visitss = rule79 _lhsIinfo _visitss'
_fromLhs = rule80 _lhsIfromLhs _occurAs arg_inh_
_computed = rule81 _lhsIinfo _lhsIvisitDescr _visitss
_intravisits = rule82 _iv _lhsInextIntravisits _visitss
_iv = rule83 _computed _fromLhs _lhsIddp
_lhsOseg :: CSegment
_lhsOseg = rule84 _inhmap _lhsIprev _lhsIvisitDescr _lhsIvssGraph _synmap
_inhmap :: Map Identifier Type
_synmap :: Map Identifier Type
(_inhmap,_synmap) = rule85 _lhsIinfo arg_inh_ arg_syn_
_lhsOcvisits :: [CVisit]
_lhsOcvisits = rule86 _inhmap _intravisits _lhsIallInters _lhsIinfo _lhsIvisitDescr _synmap _visitss
_lhsOedp :: Seq Edge
_lhsOedp = rule87 _lhsInextInh arg_inh_ arg_syn_
_lhsOinh :: [Vertex]
_lhsOinh = rule88 arg_inh_
_lhsOgroups :: [([Vertex],[Vertex])]
_lhsOgroups = rule89 _groups
_lhsOintravisits :: [IntraVisit]
_lhsOintravisits = rule90 _intravisits
_lhsOnewvertices :: [Vertex]
_lhsOnewvertices = rule91 _newvertices
_lhsOv :: Vertex
_lhsOv = rule92 _v
_lhsOvisitss :: [VisitSS]
_lhsOvisitss = rule93 _visitss
!__result_ = T_Segment_vOut10 _lhsOcvisits _lhsOdescr _lhsOedp _lhsOgroups _lhsOinh _lhsOintravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOseg _lhsOv _lhsOvisitss
in __result_ )
in C_Segment_s11 v10
{-# INLINE rule65 #-}
{-# LINE 101 "./src-ag/InterfacesRules.lag" #-}
rule65 = \ ((_lhsIinfo) :: Info) ->
{-# LINE 101 "./src-ag/InterfacesRules.lag" #-}
\a -> ruleTable _lhsIinfo ! a
{-# LINE 707 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule66 #-}
{-# LINE 104 "./src-ag/InterfacesRules.lag" #-}
rule66 = \ ((_lhsIinfo) :: Info) ((_look) :: Vertex -> CRule) ->
{-# LINE 104 "./src-ag/InterfacesRules.lag" #-}
\p us -> [ a | u <- us
, a <- tdsToTdp _lhsIinfo ! u
, p (_look a)]
{-# LINE 715 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule67 #-}
{-# LINE 108 "./src-ag/InterfacesRules.lag" #-}
rule67 = \ ((_lhsIinfo) :: Info) ((_look) :: Vertex -> CRule) ((_occurAs) :: (CRule -> Bool) -> [Vertex] -> [Vertex]) inh_ syn_ ->
{-# LINE 108 "./src-ag/InterfacesRules.lag" #-}
let group as = gather _lhsIinfo (_occurAs isRhs as)
in map (partition (isInh . _look)) (group (inh_ ++ syn_))
{-# LINE 722 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule68 #-}
{-# LINE 111 "./src-ag/InterfacesRules.lag" #-}
rule68 = \ ((_groups) :: [([Vertex],[Vertex])]) ((_lhsIv) :: Vertex) ->
{-# LINE 111 "./src-ag/InterfacesRules.lag" #-}
_lhsIv + length _groups
{-# LINE 728 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule69 #-}
{-# LINE 112 "./src-ag/InterfacesRules.lag" #-}
rule69 = \ ((_lhsIv) :: Vertex) ((_v) :: Int) ->
{-# LINE 112 "./src-ag/InterfacesRules.lag" #-}
[_lhsIv .. _v -1]
{-# LINE 734 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule70 #-}
{-# LINE 127 "./src-ag/InterfacesRules.lag" #-}
rule70 = \ ((_groups) :: [([Vertex],[Vertex])]) ((_lhsIn) :: Int) ((_look) :: Vertex -> CRule) _newvertices ->
{-# LINE 127 "./src-ag/InterfacesRules.lag" #-}
Seq.fromList $ zipWith (cv _look _lhsIn) _newvertices _groups
{-# LINE 740 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule71 #-}
{-# LINE 150 "./src-ag/InterfacesRules.lag" #-}
rule71 = \ ((_groups) :: [([Vertex],[Vertex])]) _newvertices ->
{-# LINE 150 "./src-ag/InterfacesRules.lag" #-}
concat (zipWith ed _newvertices _groups)
{-# LINE 746 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule72 #-}
{-# LINE 170 "./src-ag/InterfacesRules.lag" #-}
rule72 = \ ((_lhsInextNewvertices) :: [Vertex]) _newvertices ->
{-# LINE 170 "./src-ag/InterfacesRules.lag" #-}
zip _newvertices _lhsInextNewvertices
{-# LINE 752 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule73 #-}
{-# LINE 171 "./src-ag/InterfacesRules.lag" #-}
rule73 = \ _attredges _visitedges ->
{-# LINE 171 "./src-ag/InterfacesRules.lag" #-}
Seq.fromList _attredges Seq.>< Seq.fromList _visitedges
{-# LINE 758 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule74 #-}
{-# LINE 225 "./src-ag/InterfacesRules.lag" #-}
rule74 = \ ((_lhsIinfo) :: Info) ((_occurAs) :: (CRule -> Bool) -> [Vertex] -> [Vertex]) syn_ ->
{-# LINE 225 "./src-ag/InterfacesRules.lag" #-}
gather _lhsIinfo (_occurAs isLhs syn_)
{-# LINE 764 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule75 #-}
{-# LINE 226 "./src-ag/InterfacesRules.lag" #-}
rule75 = \ ((_lhsIcons) :: [ConstructorIdent]) ((_lhsIinfo) :: Info) ((_lhsIvssGraph) :: Graph) _synOccur syn_ ->
{-# LINE 226 "./src-ag/InterfacesRules.lag" #-}
let hasCode' v | inRange (bounds (ruleTable _lhsIinfo)) v = getHasCode (ruleTable _lhsIinfo ! v)
| otherwise = True
in if null syn_
then replicate (length _lhsIcons) []
else map (filter hasCode' . topSort' _lhsIvssGraph) _synOccur
{-# LINE 774 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule76 #-}
{-# LINE 270 "./src-ag/InterfacesRules.lag" #-}
rule76 = \ ((_lhsIprev) :: [Vertex]) _vss ->
{-# LINE 270 "./src-ag/InterfacesRules.lag" #-}
map (\\ _lhsIprev) _vss
{-# LINE 780 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule77 #-}
{-# LINE 271 "./src-ag/InterfacesRules.lag" #-}
rule77 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ((_visitss) :: [[Vertex]]) ->
{-# LINE 271 "./src-ag/InterfacesRules.lag" #-}
let defines v = case Map.lookup v _lhsIvisitDescr of
Nothing -> [v]
Just (ChildVisit _ _ _ inh _) -> v:inh
in concatMap (concatMap defines) _visitss
{-# LINE 789 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule78 #-}
{-# LINE 275 "./src-ag/InterfacesRules.lag" #-}
rule78 = \ _defined ((_lhsIprev) :: [Vertex]) ->
{-# LINE 275 "./src-ag/InterfacesRules.lag" #-}
_lhsIprev ++ _defined
{-# LINE 795 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule79 #-}
{-# LINE 284 "./src-ag/InterfacesRules.lag" #-}
rule79 = \ ((_lhsIinfo) :: Info) _visitss' ->
{-# LINE 284 "./src-ag/InterfacesRules.lag" #-}
let rem' :: [(Identifier,Identifier,Maybe Type)] -> [Vertex] -> [Vertex]
rem' _ [] = []
rem' prev (v:vs)
| inRange (bounds table) v
= let cr = table ! v
addV = case findIndex cmp prev of
Just _ -> id
_ -> (v:)
cmp (fld,attr,tp) = getField cr == fld && getAttr cr == attr && sameNT (getType cr) tp
sameNT (Just (NT ntA _ _)) (Just (NT ntB _ _)) = ntA == ntB
sameNT _ _ = False
def = Map.elems (getDefines cr)
in addV (rem' (def ++ prev) vs)
| otherwise = v:rem' prev vs
table = ruleTable _lhsIinfo
in map (rem' []) _visitss'
{-# LINE 816 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule80 #-}
{-# LINE 357 "./src-ag/InterfacesRules.lag" #-}
rule80 = \ ((_lhsIfromLhs) :: [Vertex]) ((_occurAs) :: (CRule -> Bool) -> [Vertex] -> [Vertex]) inh_ ->
{-# LINE 357 "./src-ag/InterfacesRules.lag" #-}
_occurAs isLhs inh_ ++ _lhsIfromLhs
{-# LINE 822 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule81 #-}
{-# LINE 358 "./src-ag/InterfacesRules.lag" #-}
rule81 = \ ((_lhsIinfo) :: Info) ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ((_visitss) :: [[Vertex]]) ->
{-# LINE 358 "./src-ag/InterfacesRules.lag" #-}
let computes v = case Map.lookup v _lhsIvisitDescr of
Nothing -> Map.keys (getDefines (ruleTable _lhsIinfo ! v))
Just (ChildVisit _ _ _ _ syn) -> v:syn
in concatMap (concatMap computes) _visitss
{-# LINE 831 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule82 #-}
{-# LINE 362 "./src-ag/InterfacesRules.lag" #-}
rule82 = \ _iv ((_lhsInextIntravisits) :: [IntraVisit]) ((_visitss) :: [[Vertex]]) ->
{-# LINE 362 "./src-ag/InterfacesRules.lag" #-}
zipWith _iv _visitss _lhsInextIntravisits
{-# LINE 837 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule83 #-}
{-# LINE 363 "./src-ag/InterfacesRules.lag" #-}
rule83 = \ _computed _fromLhs ((_lhsIddp) :: Graph) ->
{-# LINE 363 "./src-ag/InterfacesRules.lag" #-}
\vs next ->
let needed = concatMap (_lhsIddp !) vs
in nub (needed ++ next) \\ (_fromLhs ++ _computed)
{-# LINE 845 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule84 #-}
{-# LINE 406 "./src-ag/InterfacesRules.lag" #-}
rule84 = \ ((_inhmap) :: Map Identifier Type) ((_lhsIprev) :: [Vertex]) ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ((_lhsIvssGraph) :: Graph) ((_synmap) :: Map Identifier Type) ->
{-# LINE 406 "./src-ag/InterfacesRules.lag" #-}
if False then undefined _lhsIvssGraph _lhsIvisitDescr _lhsIprev else CSegment _inhmap _synmap
{-# LINE 851 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule85 #-}
{-# LINE 410 "./src-ag/InterfacesRules.lag" #-}
rule85 = \ ((_lhsIinfo) :: Info) inh_ syn_ ->
{-# LINE 410 "./src-ag/InterfacesRules.lag" #-}
let makemap = Map.fromList . map findType
findType v = getNtaNameType (attrTable _lhsIinfo ! v)
in (makemap inh_,makemap syn_)
{-# LINE 859 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule86 #-}
{-# LINE 413 "./src-ag/InterfacesRules.lag" #-}
rule86 = \ ((_inhmap) :: Map Identifier Type) _intravisits ((_lhsIallInters) :: CInterfaceMap) ((_lhsIinfo) :: Info) ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ((_synmap) :: Map Identifier Type) ((_visitss) :: [[Vertex]]) ->
{-# LINE 413 "./src-ag/InterfacesRules.lag" #-}
let mkVisit vss intra = CVisit _inhmap _synmap (mkSequence vss) (mkSequence intra) True
mkSequence = map mkRule
mkRule v = case Map.lookup v _lhsIvisitDescr of
Nothing -> ruleTable _lhsIinfo ! v
Just (ChildVisit name nt n _ _) -> ccv name nt n _lhsIallInters
in zipWith mkVisit _visitss _intravisits
{-# LINE 870 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule87 #-}
{-# LINE 440 "./src-ag/InterfacesRules.lag" #-}
rule87 = \ ((_lhsInextInh) :: [Vertex]) inh_ syn_ ->
{-# LINE 440 "./src-ag/InterfacesRules.lag" #-}
Seq.fromList [(i,s) | i <- inh_, s <- syn_]
Seq.>< Seq.fromList [(s,i) | s <- syn_, i <- _lhsInextInh ]
{-# LINE 877 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule88 #-}
{-# LINE 445 "./src-ag/InterfacesRules.lag" #-}
rule88 = \ inh_ ->
{-# LINE 445 "./src-ag/InterfacesRules.lag" #-}
inh_
{-# LINE 883 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule89 #-}
rule89 = \ ((_groups) :: [([Vertex],[Vertex])]) ->
_groups
{-# INLINE rule90 #-}
rule90 = \ _intravisits ->
_intravisits
{-# INLINE rule91 #-}
rule91 = \ _newvertices ->
_newvertices
{-# INLINE rule92 #-}
rule92 = \ ((_v) :: Int) ->
_v
{-# INLINE rule93 #-}
rule93 = \ ((_visitss) :: [[Vertex]]) ->
_visitss
-- Segments ----------------------------------------------------
-- wrapper
data Inh_Segments = Inh_Segments { allInters_Inh_Segments :: !(CInterfaceMap), cons_Inh_Segments :: !([ConstructorIdent]), ddp_Inh_Segments :: !(Graph), fromLhs_Inh_Segments :: !([Vertex]), info_Inh_Segments :: !(Info), isFirst_Inh_Segments :: !(Bool), n_Inh_Segments :: !(Int), prev_Inh_Segments :: !([Vertex]), v_Inh_Segments :: !(Vertex), visitDescr_Inh_Segments :: !(Map Vertex ChildVisit), vssGraph_Inh_Segments :: !(Graph) }
data Syn_Segments = Syn_Segments { cvisits_Syn_Segments :: !([[CVisit]]), descr_Syn_Segments :: !(Seq (Vertex,ChildVisit)), edp_Syn_Segments :: !(Seq Edge), firstInh_Syn_Segments :: !([Vertex]), groups_Syn_Segments :: !([([Vertex],[Vertex])]), hdIntravisits_Syn_Segments :: !([IntraVisit]), newedges_Syn_Segments :: !(Seq Edge ), newvertices_Syn_Segments :: !([Vertex]), prev_Syn_Segments :: !([Vertex]), segs_Syn_Segments :: !(CSegments), v_Syn_Segments :: !(Vertex) }
{-# INLINABLE wrap_Segments #-}
wrap_Segments :: T_Segments -> Inh_Segments -> (Syn_Segments )
wrap_Segments !(T_Segments act) !(Inh_Segments _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) =
Control.Monad.Identity.runIdentity (
do !sem <- act
let arg = T_Segments_vIn13 _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph
!(T_Segments_vOut13 _lhsOcvisits _lhsOdescr _lhsOedp _lhsOfirstInh _lhsOgroups _lhsOhdIntravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOsegs _lhsOv) <- return (inv_Segments_s14 sem arg)
return (Syn_Segments _lhsOcvisits _lhsOdescr _lhsOedp _lhsOfirstInh _lhsOgroups _lhsOhdIntravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOsegs _lhsOv)
)
-- cata
{-# NOINLINE sem_Segments #-}
sem_Segments :: Segments -> T_Segments
sem_Segments list = Prelude.foldr sem_Segments_Cons sem_Segments_Nil (Prelude.map sem_Segment list)
-- semantic domain
newtype T_Segments = T_Segments {
attach_T_Segments :: Identity (T_Segments_s14 )
}
newtype T_Segments_s14 = C_Segments_s14 {
inv_Segments_s14 :: (T_Segments_v13 )
}
data T_Segments_s15 = C_Segments_s15
type T_Segments_v13 = (T_Segments_vIn13 ) -> (T_Segments_vOut13 )
data T_Segments_vIn13 = T_Segments_vIn13 (CInterfaceMap) ([ConstructorIdent]) (Graph) ([Vertex]) (Info) (Bool) (Int) ([Vertex]) (Vertex) (Map Vertex ChildVisit) (Graph)
data T_Segments_vOut13 = T_Segments_vOut13 ([[CVisit]]) (Seq (Vertex,ChildVisit)) (Seq Edge) ([Vertex]) ([([Vertex],[Vertex])]) ([IntraVisit]) (Seq Edge ) ([Vertex]) ([Vertex]) (CSegments) (Vertex)
{-# NOINLINE sem_Segments_Cons #-}
sem_Segments_Cons :: T_Segment -> T_Segments -> T_Segments
sem_Segments_Cons arg_hd_ arg_tl_ = T_Segments (return st14) where
{-# NOINLINE st14 #-}
!st14 = let
v13 :: T_Segments_v13
v13 = \ !(T_Segments_vIn13 _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_hdX11 = Control.Monad.Identity.runIdentity (attach_T_Segment (arg_hd_))
_tlX14 = Control.Monad.Identity.runIdentity (attach_T_Segments (arg_tl_))
(T_Segment_vOut10 _hdIcvisits _hdIdescr _hdIedp _hdIgroups _hdIinh _hdIintravisits _hdInewedges _hdInewvertices _hdIprev _hdIseg _hdIv _hdIvisitss) = inv_Segment_s11 _hdX11 (T_Segment_vIn10 _hdOallInters _hdOcons _hdOddp _hdOfromLhs _hdOinfo _hdOisFirst _hdOn _hdOnextInh _hdOnextIntravisits _hdOnextNewvertices _hdOprev _hdOv _hdOvisitDescr _hdOvssGraph)
(T_Segments_vOut13 _tlIcvisits _tlIdescr _tlIedp _tlIfirstInh _tlIgroups _tlIhdIntravisits _tlInewedges _tlInewvertices _tlIprev _tlIsegs _tlIv) = inv_Segments_s14 _tlX14 (T_Segments_vIn13 _tlOallInters _tlOcons _tlOddp _tlOfromLhs _tlOinfo _tlOisFirst _tlOn _tlOprev _tlOv _tlOvisitDescr _tlOvssGraph)
_hdOnextNewvertices = rule94 _tlInewvertices
_lhsOnewvertices :: [Vertex]
_lhsOnewvertices = rule95 _hdInewvertices
_lhsOgroups :: [([Vertex],[Vertex])]
_lhsOgroups = rule96 _hdIgroups
_tlOn = rule97 _lhsIn
_tlOisFirst = rule98 ()
_hdOnextIntravisits = rule99 _tlIhdIntravisits
_lhsOhdIntravisits :: [IntraVisit]
_lhsOhdIntravisits = rule100 _hdIintravisits
_hdOfromLhs = rule101 _lhsIfromLhs
_tlOfromLhs = rule102 ()
_lhsOsegs :: CSegments
_lhsOsegs = rule103 _hdIseg _tlIsegs
_hdOnextInh = rule104 _tlIfirstInh
_lhsOfirstInh :: [Vertex]
_lhsOfirstInh = rule105 _hdIinh
_lhsOcvisits :: [[CVisit]]
_lhsOcvisits = rule106 _hdIcvisits _tlIcvisits
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule107 _hdIdescr _tlIdescr
_lhsOedp :: Seq Edge
_lhsOedp = rule108 _hdIedp _tlIedp
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule109 _hdInewedges _tlInewedges
_lhsOprev :: [Vertex]
_lhsOprev = rule110 _tlIprev
_lhsOv :: Vertex
_lhsOv = rule111 _tlIv
_hdOallInters = rule112 _lhsIallInters
_hdOcons = rule113 _lhsIcons
_hdOddp = rule114 _lhsIddp
_hdOinfo = rule115 _lhsIinfo
_hdOisFirst = rule116 _lhsIisFirst
_hdOn = rule117 _lhsIn
_hdOprev = rule118 _lhsIprev
_hdOv = rule119 _lhsIv
_hdOvisitDescr = rule120 _lhsIvisitDescr
_hdOvssGraph = rule121 _lhsIvssGraph
_tlOallInters = rule122 _lhsIallInters
_tlOcons = rule123 _lhsIcons
_tlOddp = rule124 _lhsIddp
_tlOinfo = rule125 _lhsIinfo
_tlOprev = rule126 _hdIprev
_tlOv = rule127 _hdIv
_tlOvisitDescr = rule128 _lhsIvisitDescr
_tlOvssGraph = rule129 _lhsIvssGraph
!__result_ = T_Segments_vOut13 _lhsOcvisits _lhsOdescr _lhsOedp _lhsOfirstInh _lhsOgroups _lhsOhdIntravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOsegs _lhsOv
in __result_ )
in C_Segments_s14 v13
{-# INLINE rule94 #-}
{-# LINE 165 "./src-ag/InterfacesRules.lag" #-}
rule94 = \ ((_tlInewvertices) :: [Vertex]) ->
{-# LINE 165 "./src-ag/InterfacesRules.lag" #-}
_tlInewvertices
{-# LINE 996 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule95 #-}
{-# LINE 166 "./src-ag/InterfacesRules.lag" #-}
rule95 = \ ((_hdInewvertices) :: [Vertex]) ->
{-# LINE 166 "./src-ag/InterfacesRules.lag" #-}
_hdInewvertices
{-# LINE 1002 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule96 #-}
{-# LINE 180 "./src-ag/InterfacesRules.lag" #-}
rule96 = \ ((_hdIgroups) :: [([Vertex],[Vertex])]) ->
{-# LINE 180 "./src-ag/InterfacesRules.lag" #-}
_hdIgroups
{-# LINE 1008 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule97 #-}
{-# LINE 203 "./src-ag/InterfacesRules.lag" #-}
rule97 = \ ((_lhsIn) :: Int) ->
{-# LINE 203 "./src-ag/InterfacesRules.lag" #-}
_lhsIn + 1
{-# LINE 1014 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule98 #-}
{-# LINE 316 "./src-ag/InterfacesRules.lag" #-}
rule98 = \ (_ :: ()) ->
{-# LINE 316 "./src-ag/InterfacesRules.lag" #-}
False
{-# LINE 1020 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule99 #-}
{-# LINE 329 "./src-ag/InterfacesRules.lag" #-}
rule99 = \ ((_tlIhdIntravisits) :: [IntraVisit]) ->
{-# LINE 329 "./src-ag/InterfacesRules.lag" #-}
_tlIhdIntravisits
{-# LINE 1026 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule100 #-}
{-# LINE 330 "./src-ag/InterfacesRules.lag" #-}
rule100 = \ ((_hdIintravisits) :: [IntraVisit]) ->
{-# LINE 330 "./src-ag/InterfacesRules.lag" #-}
_hdIintravisits
{-# LINE 1032 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule101 #-}
{-# LINE 354 "./src-ag/InterfacesRules.lag" #-}
rule101 = \ ((_lhsIfromLhs) :: [Vertex]) ->
{-# LINE 354 "./src-ag/InterfacesRules.lag" #-}
_lhsIfromLhs
{-# LINE 1038 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule102 #-}
{-# LINE 355 "./src-ag/InterfacesRules.lag" #-}
rule102 = \ (_ :: ()) ->
{-# LINE 355 "./src-ag/InterfacesRules.lag" #-}
[]
{-# LINE 1044 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule103 #-}
{-# LINE 401 "./src-ag/InterfacesRules.lag" #-}
rule103 = \ ((_hdIseg) :: CSegment) ((_tlIsegs) :: CSegments) ->
{-# LINE 401 "./src-ag/InterfacesRules.lag" #-}
_hdIseg : _tlIsegs
{-# LINE 1050 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule104 #-}
{-# LINE 447 "./src-ag/InterfacesRules.lag" #-}
rule104 = \ ((_tlIfirstInh) :: [Vertex]) ->
{-# LINE 447 "./src-ag/InterfacesRules.lag" #-}
_tlIfirstInh
{-# LINE 1056 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule105 #-}
{-# LINE 448 "./src-ag/InterfacesRules.lag" #-}
rule105 = \ ((_hdIinh) :: [Vertex]) ->
{-# LINE 448 "./src-ag/InterfacesRules.lag" #-}
_hdIinh
{-# LINE 1062 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule106 #-}
rule106 = \ ((_hdIcvisits) :: [CVisit]) ((_tlIcvisits) :: [[CVisit]]) ->
_hdIcvisits : _tlIcvisits
{-# INLINE rule107 #-}
rule107 = \ ((_hdIdescr) :: Seq (Vertex,ChildVisit)) ((_tlIdescr) :: Seq (Vertex,ChildVisit)) ->
_hdIdescr Seq.>< _tlIdescr
{-# INLINE rule108 #-}
rule108 = \ ((_hdIedp) :: Seq Edge) ((_tlIedp) :: Seq Edge) ->
_hdIedp Seq.>< _tlIedp
{-# INLINE rule109 #-}
rule109 = \ ((_hdInewedges) :: Seq Edge ) ((_tlInewedges) :: Seq Edge ) ->
_hdInewedges Seq.>< _tlInewedges
{-# INLINE rule110 #-}
rule110 = \ ((_tlIprev) :: [Vertex]) ->
_tlIprev
{-# INLINE rule111 #-}
rule111 = \ ((_tlIv) :: Vertex) ->
_tlIv
{-# INLINE rule112 #-}
rule112 = \ ((_lhsIallInters) :: CInterfaceMap) ->
_lhsIallInters
{-# INLINE rule113 #-}
rule113 = \ ((_lhsIcons) :: [ConstructorIdent]) ->
_lhsIcons
{-# INLINE rule114 #-}
rule114 = \ ((_lhsIddp) :: Graph) ->
_lhsIddp
{-# INLINE rule115 #-}
rule115 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
{-# INLINE rule116 #-}
rule116 = \ ((_lhsIisFirst) :: Bool) ->
_lhsIisFirst
{-# INLINE rule117 #-}
rule117 = \ ((_lhsIn) :: Int) ->
_lhsIn
{-# INLINE rule118 #-}
rule118 = \ ((_lhsIprev) :: [Vertex]) ->
_lhsIprev
{-# INLINE rule119 #-}
rule119 = \ ((_lhsIv) :: Vertex) ->
_lhsIv
{-# INLINE rule120 #-}
rule120 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ->
_lhsIvisitDescr
{-# INLINE rule121 #-}
rule121 = \ ((_lhsIvssGraph) :: Graph) ->
_lhsIvssGraph
{-# INLINE rule122 #-}
rule122 = \ ((_lhsIallInters) :: CInterfaceMap) ->
_lhsIallInters
{-# INLINE rule123 #-}
rule123 = \ ((_lhsIcons) :: [ConstructorIdent]) ->
_lhsIcons
{-# INLINE rule124 #-}
rule124 = \ ((_lhsIddp) :: Graph) ->
_lhsIddp
{-# INLINE rule125 #-}
rule125 = \ ((_lhsIinfo) :: Info) ->
_lhsIinfo
{-# INLINE rule126 #-}
rule126 = \ ((_hdIprev) :: [Vertex]) ->
_hdIprev
{-# INLINE rule127 #-}
rule127 = \ ((_hdIv) :: Vertex) ->
_hdIv
{-# INLINE rule128 #-}
rule128 = \ ((_lhsIvisitDescr) :: Map Vertex ChildVisit) ->
_lhsIvisitDescr
{-# INLINE rule129 #-}
rule129 = \ ((_lhsIvssGraph) :: Graph) ->
_lhsIvssGraph
{-# NOINLINE sem_Segments_Nil #-}
sem_Segments_Nil :: T_Segments
sem_Segments_Nil = T_Segments (return st14) where
{-# NOINLINE st14 #-}
!st14 = let
v13 :: T_Segments_v13
v13 = \ !(T_Segments_vIn13 _lhsIallInters _lhsIcons _lhsIddp _lhsIfromLhs _lhsIinfo _lhsIisFirst _lhsIn _lhsIprev _lhsIv _lhsIvisitDescr _lhsIvssGraph) -> ( let
_lhsOnewvertices :: [Vertex]
_lhsOnewvertices = rule130 ()
_lhsOgroups :: [([Vertex],[Vertex])]
_lhsOgroups = rule131 ()
_lhsOhdIntravisits :: [IntraVisit]
_lhsOhdIntravisits = rule132 ()
_lhsOsegs :: CSegments
_lhsOsegs = rule133 ()
_lhsOfirstInh :: [Vertex]
_lhsOfirstInh = rule134 ()
_lhsOcvisits :: [[CVisit]]
_lhsOcvisits = rule135 ()
_lhsOdescr :: Seq (Vertex,ChildVisit)
_lhsOdescr = rule136 ()
_lhsOedp :: Seq Edge
_lhsOedp = rule137 ()
_lhsOnewedges :: Seq Edge
_lhsOnewedges = rule138 ()
_lhsOprev :: [Vertex]
_lhsOprev = rule139 _lhsIprev
_lhsOv :: Vertex
_lhsOv = rule140 _lhsIv
!__result_ = T_Segments_vOut13 _lhsOcvisits _lhsOdescr _lhsOedp _lhsOfirstInh _lhsOgroups _lhsOhdIntravisits _lhsOnewedges _lhsOnewvertices _lhsOprev _lhsOsegs _lhsOv
in __result_ )
in C_Segments_s14 v13
{-# INLINE rule130 #-}
{-# LINE 167 "./src-ag/InterfacesRules.lag" #-}
rule130 = \ (_ :: ()) ->
{-# LINE 167 "./src-ag/InterfacesRules.lag" #-}
[]
{-# LINE 1172 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule131 #-}
{-# LINE 181 "./src-ag/InterfacesRules.lag" #-}
rule131 = \ (_ :: ()) ->
{-# LINE 181 "./src-ag/InterfacesRules.lag" #-}
[]
{-# LINE 1178 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule132 #-}
{-# LINE 331 "./src-ag/InterfacesRules.lag" #-}
rule132 = \ (_ :: ()) ->
{-# LINE 331 "./src-ag/InterfacesRules.lag" #-}
repeat []
{-# LINE 1184 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule133 #-}
{-# LINE 402 "./src-ag/InterfacesRules.lag" #-}
rule133 = \ (_ :: ()) ->
{-# LINE 402 "./src-ag/InterfacesRules.lag" #-}
[]
{-# LINE 1190 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule134 #-}
{-# LINE 449 "./src-ag/InterfacesRules.lag" #-}
rule134 = \ (_ :: ()) ->
{-# LINE 449 "./src-ag/InterfacesRules.lag" #-}
[]
{-# LINE 1196 "dist/build/InterfacesRules.hs"#-}
{-# INLINE rule135 #-}
rule135 = \ (_ :: ()) ->
[]
{-# INLINE rule136 #-}
rule136 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule137 #-}
rule137 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule138 #-}
rule138 = \ (_ :: ()) ->
Seq.empty
{-# INLINE rule139 #-}
rule139 = \ ((_lhsIprev) :: [Vertex]) ->
_lhsIprev
{-# INLINE rule140 #-}
rule140 = \ ((_lhsIv) :: Vertex) ->
_lhsIv
|
norm2782/uuagc
|
src-generated/InterfacesRules.hs
|
Haskell
|
bsd-3-clause
| 64,297
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- ^
-- Original location https://github.com/nh2/aesonbson/blob/master/Data/AesonBson/Instances.hs
-- ^ Provides @ToJSON@ instances for BSON @Value@s and @Document@s.
module Data.AesonBson.Instances where
import Data.Aeson.Types as AESON
import Data.Bson as BSON
import Data.AesonBson
instance ToJSON BSON.Value where
toJSON = aesonifyValue
|
gabesoft/kapi
|
src/Data/AesonBson/Instances.hs
|
Haskell
|
bsd-3-clause
| 443
|
-- vim:sw=2:ts=2:expandtab:autoindent
{- |
Module : Math.SMT.Yices.Pipe
Copyright : (c) 2009 by Ki Yung Ahn
License : BSD3
Maintainer : Ahn, Ki Yung <kya@pdx.edu>
Stability : provisional
Portability : portable
Inter-process communication to Yices through pipe.
-}
module Math.SMT.Yices.Pipe (
YicesIPC, ResY(..), createYicesPipe,
runCmdsY', runCmdsY, checkY, exitY, flushY,
quickCheckY, quickCheckY'
) where
import Math.SMT.Yices.Syntax
import Math.SMT.Yices.Parser
import Data.List
import Control.Monad
import System.IO
import System.Process
-- | type abbrevation for IPC handle quadruple
type YicesIPC = (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
-- | To read in the result of the (check) command
data ResY
= Sat [ExpY]
| Unknown [ExpY]
| UnSat [Integer]
| InCon [String]
deriving Show
-- | Start yices on a given path with given options.
-- The first argumnet yPath is the path binary file of yices
-- (e.g. /home/kyagrd/yices-1.0.21/bin/yices).
-- By default -i and -e options are already present, and
-- yOpts argument appens more options
createYicesPipe :: FilePath -> [String] -> IO YicesIPC
createYicesPipe yPath yOpts = createProcess $
(proc yPath $ "-i":"-e":yOpts){std_in=CreatePipe,std_out=CreatePipe}
_BEGIN_OUTPUT = "_![<[BEGIN_OUTPUT]>]!_"
_END_OUTPUT = "_![<[END_OUTPUT]>]!_"
runCmdStringY yp s = runCmdStringY' yp s >> flushY yp
runCmdStringY' (Just hin, _, _, _) = hPutStrLn hin
-- | send yices commands and flush
runCmdsY :: YicesIPC -> [CmdY] -> IO ()
runCmdsY yp cmds = runCmdsY' yp cmds >> flushY yp
-- | send yices commands without flushing
runCmdsY' :: YicesIPC -> [CmdY] -> IO ()
runCmdsY' (Just hin, _, _, _) = mapM_ (hPutStrLn hin . show)
-- | send exit command and flush
exitY :: YicesIPC -> IO ()
exitY (Just hin, _, _, _) = hPutStrLn hin (show EXIT) >> hFlush hin
-- | flush the input pipe to yices (needed after actions like runCmdsY')
flushY :: YicesIPC -> IO ()
flushY (Just hin, _, _, _) = hFlush hin
-- | send check command and reads the result
checkY :: YicesIPC -> IO ResY
checkY yp@(_, Just hout, _, _) =
do runCmdsY yp [ECHO('\n':_BEGIN_OUTPUT), CHECK, ECHO('\n':_END_OUTPUT)]
(s:ss) <- hGetOutLines hout
-- hPutStrLn stderr s -- for debugging
return $
case s of
"sat" -> Sat (parseExpYs $ unlines ss)
"unknown"-> Unknown (parseExpYs $ unlines ss)
"unsat" -> UnSat (map read.words.tail.dropWhile (/=':').head $ ss)
_ -> InCon (s:ss)
-- | sends a bunch of commands followed by a check command and reads the resulting model.
-- This function should be the preferred option when large expressions are involved.
quickCheckY :: String -> [String] -> [CmdY] -> IO ResY
quickCheckY yPath yOpts cmds = quickCheckY' yPath yOpts (cmds ++ [CHECK])
-- | sends a bunch of commands and reads the result.
-- This function is similar to 'quickCheckY' but does not append a check command.
-- It can be useful if you intend to
quickCheckY' :: String -> [String] -> [CmdY] -> IO ResY
quickCheckY' yPath yOpts cmds = do
(code, out', err) <- readProcessWithExitCode yPath ("-e" : yOpts) (unlines $ map show cmds)
let out = filter (/= '\r') out'
when (not $ null err) $ hPutStrLn stderr err
hPutStrLn stderr out'
return $
case lines out of
"sat" : ss -> Sat (parseExpYs $ unlines $ filter f ss)
"unknown" : ss -> Unknown (parseExpYs $ unlines $ filter f ss)
"unsat" : ss -> UnSat (map read.words.tail.dropWhile (/=':').head $ ss)
other -> InCon other
where f x = not(null x ||
"unsatisfied assertion ids:" `isPrefixOf` x ||
"cost:" `isPrefixOf` x)
stripYicesPrompt line | yprompt `isPrefixOf` line = drop (length yprompt) line
| otherwise = line
where yprompt = "yices > "
{- -- for debugging echoing to stderr
hGetOutLines h = do
ll <- (hGetLinesWhile (/= _END_OUTPUT) h)
mapM_ (hPutStrLn stderr) (filter (not.null) . map stripYicesPrompt . takeWhile (/= _BEGIN_OUTPUT) $ ll)
return $ ( filter (not . null) . map stripYicesPrompt .
tail . dropWhile (/=_BEGIN_OUTPUT) )
ll
-}
hGetOutLines h = liftM ( filter (not . null) . map stripYicesPrompt .
tail . dropWhile (/=_BEGIN_OUTPUT) )
(hGetLinesWhile (/= _END_OUTPUT) h)
hGetLinesWhile p h = do line <- hGetLine h
if p line
then liftM (line:) (hGetLinesWhile p h)
else return []
{-
hGetReadyString1 h = liftM2 (:) (hGetChar h) (hGetReadyString h)
hGetReadyString h =
do ready <- hReady h
if ready then liftM2 (:) (hGetChar h) (hGetReadyString h) else return []
-}
|
pepeiborra/yices-0.0.0.12
|
Math/SMT/Yices/Pipe.hs
|
Haskell
|
bsd-3-clause
| 4,875
|
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
import Java
import Control.Applicative
import Options
import Data.Aeson
import Data.Aeson.TH
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
data User = User
{ userId :: Int
, userFirstName :: String
, userLastName :: String
} deriving (Eq, Show)
$(deriveJSON defaultOptions ''User)
type API = "users" :> Get '[JSON] [User]
startApp :: IO ()
startApp = run 8080 app
app :: Application
app = serve api server
api :: Proxy API
api = Proxy
server :: Server API
server = return users
users :: [User]
users = [ User 1 "Isaac" "Newton"
, User 2 "Albert" "Einstein"
]
data MainOptions = MainOptions
{ port :: Int
, message :: String
}
instance Options MainOptions where
defineOptions = pure MainOptions
<*> simpleOption "port" 8088
"the port for web service "
<*> simpleOption "message" "test message"
"message for testing."
foreign import java unsafe "@static eta.dl4j.Word2VecRawText.mainfun"
word2VecRawText :: String->String -> IO ()
main = startApp
main1 :: IO ()
main1 = runCommand $ \opts args -> do
word2VecRawText "/Users/zhangjun/Documents/fudan/paper/run/logfile/Cods.log.2015-01-25" "/Users/zhangjun/code/ibm/eta-example/testoutput"
print $ message opts
|
JulianZhang/eta-example
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 1,399
|
module D1Lib where
import Text.Megaparsec
import Text.Megaparsec.String
import Text.Megaparsec.Char
import Text.Megaparsec.Lexer as L
type ParseResult = Either (ParseError Char Dec) [Integer]
wrapl :: a -> [a]
wrapl = replicate 1
digit :: Parser Integer
digit = read <$> (wrapl <$> digitChar)
parser :: Parser [Integer]
parser = many digit
parseStr :: String -> ParseResult
parseStr = parse parser "NO_INPUT_FILE"
calc1 :: [Integer] -> Integer
calc1 = sum . map pairVal . pairs 1
calc2 :: [Integer] -> Integer
calc2 xs = sum . map pairVal $ pairs (length xs `div` 2) xs
pairs :: Int -> [a] -> [(a, a)]
pairs shiftDist xs = zip xs $ shift shiftDist xs
pairs _ [] = []
shift :: Int -> [a] -> [a]
shift d xs = t' ++ h'
where
(h', t') = splitAt d xs
pairVal :: (Integer, Integer) -> Integer
pairVal (x, y) = if x == y then x else 0
|
wfleming/advent-of-code-2016
|
2017/D1/src/D1Lib.hs
|
Haskell
|
bsd-3-clause
| 845
|
module Main where --Main
import CAProtoMain (caEntity_CA)
import ProtoMonad
import ProtoTypes
import ProtoActions
import VChanUtil
import TPMUtil
import Keys
import ProtoTypes(Channel)
import Prelude
import Data.ByteString.Lazy hiding (putStrLn, head, tail, map)
import qualified Data.Map as M
import System.IO
import Codec.Crypto.RSA
import System.Random
import Control.Monad.IO.Class
import Control.Monad
import Control.Concurrent
caCommInit :: Channel -> Int -> IO ProtoEnv
caCommInit attChan pId = do
-- attChan <- server_init domid
let myInfo = EntityInfo "CA" 22 attChan
attInfo = EntityInfo "Attester" 22 attChan
mList = [(0, myInfo), (1, attInfo)]
ents = M.fromList mList
myPri = snd $ generateAKeyPair
attPub = getBPubKey
pubs = M.fromList [(1,attPub)]
return $ ProtoEnv 0 myPri ents pubs 0 0 0 pId
{-
caCommInit :: Int -> IO ProtoEnv
caCommInit domid = do
attChan <- server_init domid
let myInfo = EntityInfo "CA" 22 attChan
attInfo = EntityInfo "Attester" 22 attChan
mList = [(0, myInfo), (1, attInfo)]
ents = M.fromList mList
myPri = snd $ generateAKeyPair
attPub = getBPubKey
pubs = M.fromList [(1,attPub)]
return $ ProtoEnv 0 myPri ents pubs 0 0 0 -}
--return ()
caProcess :: ProtoEnv -> Int -> IO ()
caProcess env chanId = do
-- yield
attChan <- liftIO $ server_init chanId
eitherResult <- runProto (caEntity_CA attChan) env
case eitherResult of
Left s -> putStrLn $ "Error occured: " ++ s
Right _ -> putStrLn $ "Completed successfully" -- ++ (show resp)
close attChan
--main = attCommInit [1,2]
main :: IO ()
main = do
putStrLn "Main of entity CA"
env <- caCommInit undefined undefined -- [appId, caId] --TODO: Need Channel form Paul
--TODO: choose protocol based on protoId
let vChannels :: [Int]
vChannels = [3, 5]
-- mapM (forkIO . forever . (caProcess env)) (tail vChannels)
forever$ do
caProcess env 3
--caProcess env 5
--caProcess env (head vChannels)
{-eitherResult <- runProto (caEntity_CA attChan) env
case eitherResult of
Left s -> putStrLn $ "Error occured: " ++ s
Right _ -> putStrLn $ "Completed successfully" -- ++ (show resp)
--TODO: Output to Justin's log file here -}
{-let as = [ANonce empty, ANonce empty, ACipherText empty]
asCipher = genEncrypt (fst generateAKeyPair) as
as' = genDecrypt (snd generateAKeyPair) asCipher
putStrLn $ show $ as' -}
--main
return ()
{-camain :: Channel -> Int -> IO ()
camain chan pId = do
putStrLn "Main of entity CA"
env <- caCommInit undefined undefined -- [appId, caId] --TODO: Need Channel form Paul
--TODO: choose protocol based on protoId
eitherResult <- runProto caEntity_CA env
case eitherResult of
Left s -> putStrLn $ "Error occured: " ++ s
Right _ -> putStrLn $ "Completed successfully" -- ++ (show resp)
--TODO: Output to Justin's log file here
{-let as = [ANonce empty, ANonce empty, ACipherText empty]
asCipher = genEncrypt (fst generateAKeyPair) as
as' = genDecrypt (snd generateAKeyPair) asCipher
putStrLn $ show $ as' -}
return () -}
|
armoredsoftware/protocol
|
tpm/mainline/protoMonad/CAMain.hs
|
Haskell
|
bsd-3-clause
| 3,184
|
module Test.Tup(main) where
import Development.Shake
import Development.Shake.Config
import Development.Shake.FilePath
import Development.Shake.Util
import Test.Type
import Data.Maybe
import Control.Monad
import System.Info.Extra
-- Running ar on Mac seems to break in CI - not sure why
main = testBuild (unless isMac . defaultTest) $ do
-- Example inspired by http://gittup.org/tup/ex_multiple_directories.html
usingConfigFile $ shakeRoot </> "src/Test/Tup/root.cfg"
action $ do
keys <- getConfigKeys
need [x -<.> exe | x <- keys, takeExtension x == ".exe"]
let objects dir key = do
let f x | takeExtension x == ".c" = dir </> x -<.> "o"
| takeExtension x == ".a" = takeBaseName x </> "lib" ++ x
| otherwise = error $ "Unknown extension, " ++ x
x <- fromMaybe (error $ "Missing config key, " ++ key) <$> getConfig key
pure $ map f $ words x
(\x -> x -<.> exe == x) ?> \out -> do
os <- objects "" $ takeBaseName out <.> "exe"
need os
cmd "gcc" os "-o" [out]
"//lib*.a" %> \out -> do
os <- objects (drop 3 $ takeBaseName out) $ drop 3 $ takeFileName out
need os
cmd "ar crs" [out] os
"//*.o" %> \out -> do
let src = shakeRoot </> "src/Test/Tup" </> out -<.> "c"
need [src]
cmd_ "gcc -c -MMD -MF" [out -<.> "d"] [src] "-o" [out] "-O2 -Wall" ["-I" ++ shakeRoot </> "src/Test/Tup/newmath"]
neededMakefileDependencies $ out -<.> "d"
|
ndmitchell/shake
|
src/Test/Tup.hs
|
Haskell
|
bsd-3-clause
| 1,537
|
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.K3.Runtime.Dataspace.Test (tests) where
import Control.Monad
import Control.Monad.Trans.Either
import Data.List
import Data.Maybe
import Test.HUnit hiding (Test)
import Test.Framework.Providers.API
import Test.Framework.Providers.HUnit
import Language.K3.Runtime.Common
import Language.K3.Interpreter
import Language.K3.Runtime.Dataspace
import Language.K3.Runtime.Engine
import Language.K3.Runtime.FileDataspace
import Language.K3.Interpreter.Values
import Language.K3.Interpreter.Data.Accessors
compareDataspaceToList :: (Dataspace Interpretation ds Value) => ds -> [Value] -> Interpretation Bool
compareDataspaceToList dataspace l = do
ds <- foldM findAndRemoveElement dataspace l
s <- sizeDS ds
if s == 0 then return True else throwE $ RunTimeInterpretationError $ "Dataspace had " ++ (show s) ++ " extra elements"
where
findAndRemoveElement :: (Dataspace Interpretation ds Value) => ds -> Value -> Interpretation (ds)
findAndRemoveElement ds cur_val = do
contains <- containsDS ds cur_val
if contains
then do
removed <- deleteDS cur_val ds
return $ removed
else
throwE $ RunTimeInterpretationError $ "Could not find element " ++ (show cur_val)
emptyPeek :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
emptyPeek dataspace _ = do
d <- emptyDS (Just dataspace)
result <- peekDS d
return (isNothing result)
testEmptyFold :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testEmptyFold dataspace _ = do
d <- emptyDS (Just dataspace)
counter <- foldDS innerFold 0 d
return (counter == 0 )
where
innerFold :: Int -> Value -> Interpretation Int
innerFold cnt _ = return $ cnt + 1
test_lst = [VInt 1, VInt 2, VInt 3, VInt 4, VInt 4, VInt 100]
testPeek :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testPeek dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
peekResult <- peekDS test_ds
case peekResult of
Nothing -> throwE $ RunTimeInterpretationError "Peek returned nothing!"
Just v -> containsDS test_ds v
testInsert :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testInsert dataspace _ = do
test_ds <- emptyDS (Just dataspace)
built_ds <- foldM (\ds val -> insertDS ds val) test_ds test_lst
compareDataspaceToList built_ds test_lst
testDelete :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testDelete dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
test_ds <- deleteDS (VInt 3) test_ds
test_ds <- deleteDS (VInt 4) test_ds
compareDataspaceToList test_ds [VInt 1, VInt 2, VInt 4, VInt 100]
testMissingDelete :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testMissingDelete dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
deleted <- deleteDS (VInt 5) test_ds
compareDataspaceToList deleted test_lst
testUpdate :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testUpdate dataspace _ = do
updated <- initialDS test_lst (Just dataspace) >>= updateDS (VInt 1) (VInt 4)
compareDataspaceToList updated [VInt 4, VInt 2, VInt 3, VInt 4, VInt 4, VInt 100]
testUpdateMultiple :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testUpdateMultiple dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
updated <- updateDS (VInt 4) (VInt 5) test_ds
compareDataspaceToList updated [VInt 1, VInt 2, VInt 3, VInt 5, VInt 4, VInt 100]
testUpdateMissing :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testUpdateMissing dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
updated <- updateDS (VInt 40) (VInt 5) test_ds
compareDataspaceToList updated ( test_lst ++ [VInt 5] )
testFold :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testFold dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
test_sum <- foldDS innerFold 0 test_ds
return $ test_sum == 114
where
innerFold :: Int -> Value -> Interpretation Int
innerFold acc value =
case value of
VInt v -> return $ acc + v
otherwise -> throwE $ RunTimeTypeError "Exepected Int in folding test"
vintAdd :: Int -> Value -> Value
vintAdd c val =
case val of
VInt v -> VInt (v + c)
otherwise -> VInt (-1) -- TODO throw real error
testMap :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testMap dataspace _ = do
test_ds <- initialDS test_lst (Just dataspace)
mapped_ds <- mapDS (return . (vintAdd 5)) test_ds
compareDataspaceToList mapped_ds [VInt 6, VInt 7, VInt 8, VInt 9, VInt 9, VInt 105]
testFilter :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testFilter dataspace _ = do
filtered_ds <- initialDS test_lst (Just dataspace) >>= filterDS (\(VInt v) -> return $ v > 50)
compareDataspaceToList filtered_ds [VInt 100]
testCombine :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testCombine dataspace _ = do
left' <- initialDS test_lst (Just dataspace)
right' <- initialDS test_lst (Just dataspace)
combined <- combineDS left' right'
compareDataspaceToList combined (test_lst ++ test_lst)
testCombineSelf :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testCombineSelf dataspace _ = do
self <- initialDS test_lst (Just dataspace)
combined <- combineDS self self
compareDataspaceToList combined (test_lst ++ test_lst)
sizeDS :: (Monad m, Dataspace m ds Value) => ds -> m Int
sizeDS ds = do
foldDS innerFold 0 ds
where
innerFold :: (Monad m) => Int -> Value -> m Int
innerFold cnt _ = return $ cnt + 1
-- depends on combine working
testSplit :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
testSplit dataspace _ = do
-- split doesn't do anything if one of the collections contains less than 10 elements
let long_lst = test_lst ++ test_lst
first_ds <- initialDS long_lst (Just dataspace)
(left', right') <- splitDS first_ds
leftLen <- sizeDS left'
rightLen <- sizeDS right'
--TODO should the >= be just > ?
if leftLen >= length long_lst || rightLen >= length long_lst || leftLen + rightLen > length long_lst
then
return False
else do
remainders <- foldM findAndRemoveElement (Just (left', right')) long_lst
case remainders of
Nothing -> return False
Just (l, r) -> do
lLen <- sizeDS l
rLen <- sizeDS r
if lLen == 0 && rLen == 0
then
return True
else
return False
where
findAndRemoveElement :: (Dataspace Interpretation ds Value) => Maybe (ds, ds) -> Value -> Interpretation (Maybe (ds, ds))
findAndRemoveElement maybeTuple cur_val =
case maybeTuple of
Nothing -> return Nothing
Just (left, right) -> do
leftContains <- containsDS left cur_val
if leftContains
then do
removed_left <- deleteDS cur_val left
return $ Just (removed_left, right)
else do
rightContains <- containsDS right cur_val
if rightContains
then do
removed_right <- deleteDS cur_val right
return $ Just (left, removed_right)
else
return Nothing
-- TODO These just makes sure that nothing crashes, but should probably check for correctness also
insertInsideMap :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
insertInsideMap dataspace _ = do
outer_ds <- initialDS test_lst (Just dataspace)
result_ds <- mapDS (\cur_val -> do
insertDS outer_ds (VInt 256);
return $ VInt 4
) outer_ds
return True
insertInsideMap_ :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
insertInsideMap_ dataspace _ = do
outer_ds <- initialDS test_lst (Just dataspace)
mapDS_ (\cur_val -> do
insertDS outer_ds (VInt 256)
return $ VInt 4
) outer_ds
return True
insertInsideFilter :: (Dataspace Interpretation ds Value) => ds -> () -> Interpretation Bool
insertInsideFilter dataspace _ = do
outer_ds <- initialDS test_lst (Just dataspace)
result_ds <- filterDS (\cur_val -> do
insertDS outer_ds (VInt 256);
return True
) outer_ds
return True
containsDS :: (Monad m, Dataspace m ds Value) => ds -> Value -> m Bool
containsDS ds val =
foldDS (\fnd cur -> return $ fnd || cur == val) False ds
callTest :: (() -> Interpretation Bool) -> IO ()
callTest testFunc = do
emptyEnv <- emptyStaticEnvIO
engine <- simulationEngine [] False defaultSystem (syntaxValueWD emptyEnv)
eState <- emptyStateIO
interpResult <- runInterpretation engine eState (testFunc ())
success <- either (return . Just . show) (either (return . Just . show) (\good -> if good then return Nothing else return $ Just "Dataspace test failed") . getResultVal) interpResult
case success of
Nothing -> return ()
Just msg -> assertFailure msg
makeTestGroup :: (Dataspace Interpretation dataspace Value) => String -> dataspace -> Test
makeTestGroup name ds =
testGroup name [
testCase "EmptyPeek" $ callTest $ emptyPeek ds,
testCase "Fold on Empty List Test" $ callTest $ testEmptyFold ds,
testCase "Peek Test" $ callTest $ testPeek ds,
testCase "Insert Test" $ callTest $ testInsert ds,
testCase "Delete Test" $ callTest $ testDelete ds,
testCase "Delete of missing element Test" $ callTest $ testMissingDelete ds,
testCase "Update Test" $ callTest $ testUpdate ds,
testCase "Update Multiple Test" $ callTest $ testUpdateMultiple ds,
testCase "Update missing element Test" $ callTest $ testUpdateMissing ds,
testCase "Fold Test" $ callTest $ testFold ds,
testCase "Map Test" $ callTest $ testMap ds,
testCase "Filter Test" $ callTest $ testFilter ds,
testCase "Combine Test" $ callTest $ testCombine ds,
testCase "Combine with Self Test" $ callTest $ testCombineSelf ds,
testCase "Split Test" $ callTest $ testSplit ds,
testCase "Insert inside map" $ callTest $ insertInsideMap ds,
testCase "Insert inside map_" $ callTest $ insertInsideMap_ ds,
testCase "Insert inside filter" $ callTest $ insertInsideFilter ds
]
tests :: [Test]
tests = [
makeTestGroup "List Dataspace" ([] :: (Dataspace Interpretation [Value] Value) => [Value]),
makeTestGroup "File Dataspace" (FileDataspace "tmp" :: FileDataspace Value)
]
|
DaMSL/K3
|
test/Language/K3/Runtime/Dataspace/Test.hs
|
Haskell
|
apache-2.0
| 10,707
|
{-# LANGUAGE FlexibleInstances, ExistentialQuantification, MultiParamTypeClasses #-}
-- |
-- Module : Scion.Server.ConnectionIO
-- License : BSD-style
--
-- Maintainer : marco-oweber@gmx.de
-- Stability : experimental
-- Portability : portable
--
-- Abstraction over Socket and Handle IO.
module Scion.Server.ConnectionIO (
ConnectionIO(..), mkSocketConnection
) where
import Prelude hiding (log)
import System.IO (Handle, hFlush)
import Network.Socket (Socket)
import Network.Socket.ByteString (recv, send)
import Data.IORef
import qualified System.Log.Logger as HL
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
log :: HL.Priority -> String -> IO ()
log = HL.logM "io.connection"
logError :: String -> IO ()
logError = log HL.ERROR
class ConnectionIO con where
getLine :: con -> IO L.ByteString
getN :: con -> Int -> IO L.ByteString
put :: con -> L.ByteString -> IO ()
putLine :: con -> L.ByteString -> IO ()
putLine c s = put c s >> put c (L.singleton '\n')
-- (stdin,stdout) implemenation
instance ConnectionIO (Handle, Handle) where
getLine (i, _) = do l <- S.hGetLine i; return (L.fromChunks [l])
getN (i,_) = L.hGet i
put (_,o) = L.hPut o
putLine (_,o) = \l -> do
-- ghc doesn't use the ghc api to print texts all the time. So mark
-- scion replies by a leading "scion:" see README.markdown
S.hPutStr o scionPrefix
L.hPut o l
S.hPutStr o newline
hFlush o -- don't ask me why this is needed. LineBuffering is set as well (!)
scionPrefix :: S.ByteString
scionPrefix = S.pack "scion:"
newline :: S.ByteString
newline = S.pack "\n"
data SocketConnection = SockConn Socket (IORef S.ByteString)
mkSocketConnection :: Socket -> IO SocketConnection
mkSocketConnection sock =
do r <- newIORef S.empty; return $ SockConn sock r
-- Socket.ByteString implemenation
instance ConnectionIO SocketConnection where
-- TODO: Handle client side closing of connection.
getLine (SockConn sock r) = do
buf <- readIORef r
(line_chunks, buf') <- go buf
writeIORef r buf'
return (L.fromChunks line_chunks)
where
go buf | S.null buf = do
chunk <- recv sock 1024
if S.null chunk
then return ([], S.empty)
else go chunk
go buf =
let (before, rest) = S.breakSubstring newline buf in
case () of
_ | S.null rest -> do
-- no newline found
(cs', buf') <- go rest
return (before:cs', buf')
_ | otherwise ->
return ([before], S.drop (S.length newline) rest)
getN (SockConn sock r) len = do
buf <- readIORef r
if S.length buf > len
then do let (str, buf') = S.splitAt len buf
writeIORef r buf'
return (L.fromChunks [str])
else do
str <- recv sock (len - S.length buf)
writeIORef r S.empty
return (L.fromChunks [buf, str])
put (SockConn sock _) lstr = do
go (L.toChunks lstr)
-- is there a better excption which should be thrown instead? (TODO)
-- throw $ mkIOError ResourceBusy ("put in " ++ __FILE__) Nothing Nothing
where go [] = return ()
go (str:strs) = do
let l = S.length str
sent <- send sock str
if (sent /= l) then do
logError $ (show l) ++ " bytes to be sent but could only sent : " ++ (show sent)
else go strs
|
CristhianMotoche/scion
|
server/Scion/Server/ConnectionIO.hs
|
Haskell
|
bsd-3-clause
| 3,491
|
{-# Language GADTs, NoMonomorphismRestriction #-}
module Midi.TimeSet ( normalize ) where
import Data.Set (fromAscList, toAscList, unions)
import Control.Arrow ((>>>))
normalize :: (Ord b, Ord a, Num a) => [[(a, b)]] -> [(a, b)]
normalize = map absolute >>> norm >>> relative
norm :: (Eq x, Ord x, Eq y, Ord y) => [[(x,y)]] -> [(x,y)]
norm = toAscList . unions . map fromAscList
absolute = scanl1 f where f (a,_) (b,y) = (a+b, y)
relative :: Num a => [(a,b)] -> [(a,b)]
relative [] = []
relative l@(x:xs) = x : zipWith g l xs
where
g (a,_) (c,d) = (c-a, d)
|
beni55/Midi
|
src/Midi/TimeSet.hs
|
Haskell
|
bsd-3-clause
| 569
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Lazyfoo.Lesson18 (main) where
import Prelude hiding (any, mapM_)
import Control.Applicative
import Control.Monad hiding (mapM_)
import Data.Foldable
import Data.Maybe
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.colorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.renderCopyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.AcceleratedVSyncRenderer
, SDL.rendererTargetTexture = False
})
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
pressTexture <- loadTexture renderer "examples/lazyfoo/press.bmp"
upTexture <- loadTexture renderer "examples/lazyfoo/up.bmp"
downTexture <- loadTexture renderer "examples/lazyfoo/down.bmp"
leftTexture <- loadTexture renderer "examples/lazyfoo/left.bmp"
rightTexture <- loadTexture renderer "examples/lazyfoo/right.bmp"
let
loop = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- map SDL.eventPayload <$> collectEvents
let quit = any (== SDL.QuitEvent) events
keyMap <- SDL.getKeyboardState
let texture =
if | keyMap SDL.ScancodeUp -> upTexture
| keyMap SDL.ScancodeDown -> downTexture
| keyMap SDL.ScancodeLeft -> leftTexture
| keyMap SDL.ScancodeRight -> rightTexture
| otherwise -> pressTexture
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.renderClear renderer
renderTexture renderer texture 0 Nothing Nothing Nothing Nothing
SDL.renderPresent renderer
unless quit loop
loop
SDL.destroyWindow window
SDL.quit
|
bj4rtmar/sdl2
|
examples/lazyfoo/Lesson18.hs
|
Haskell
|
bsd-3-clause
| 3,449
|
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
--
-- Assumes that the `NoPat` pass has been run.
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ViewPatterns #-}
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE RecursiveDo #-}
#else
{-# LANGUAGE DoRec, RecursiveDo #-}
#endif
{-# LANGUAGE Safe #-}
module Cryptol.TypeCheck.Infer where
import Cryptol.Parser.Position
import qualified Cryptol.Parser.AST as P
import qualified Cryptol.Parser.Names as P
import Cryptol.TypeCheck.AST
import Cryptol.TypeCheck.Monad
import Cryptol.TypeCheck.Solve
import Cryptol.TypeCheck.Kind(checkType,checkSchema,checkTySyn,
checkNewtype)
import Cryptol.TypeCheck.Instantiate
import Cryptol.TypeCheck.Depends
import Cryptol.TypeCheck.Subst (listSubst,apSubst,fvs,(@@))
import Cryptol.TypeCheck.Solver.InfNat(genLog)
import Cryptol.Utils.Panic(panic)
import Cryptol.Utils.PP
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Either(partitionEithers)
import Data.Maybe(mapMaybe,isJust)
import Data.List(partition,find)
import Data.Graph(SCC(..))
import Data.Traversable(forM)
import Control.Monad(when,zipWithM)
-- import Cryptol.Utils.Debug
inferModule :: P.Module -> InferM Module
inferModule m =
inferDs (P.mDecls m) $ \ds1 ->
do simplifyAllConstraints
ts <- getTSyns
nts <- getNewtypes
return Module { mName = thing (P.mName m)
, mExports = P.modExports m
, mImports = map thing (P.mImports m)
, mTySyns = Map.mapMaybe onlyLocal ts
, mNewtypes = Map.mapMaybe onlyLocal nts
, mDecls = ds1
}
where
onlyLocal (IsLocal, x) = Just x
onlyLocal (IsExternal, _) = Nothing
desugarLiteral :: Bool -> P.Literal -> InferM P.Expr
desugarLiteral fixDec lit =
do l <- curRange
let named (x,y) = P.NamedInst
P.Named { name = Located l (mkName x), value = P.TNum y }
demote fs = P.EAppT (P.EVar (P.mkPrim "demote")) (map named fs)
return $ case lit of
P.ECNum num info ->
demote $ [ ("val", num) ] ++ case info of
P.BinLit n -> [ ("bits", 1 * toInteger n) ]
P.OctLit n -> [ ("bits", 3 * toInteger n) ]
P.HexLit n -> [ ("bits", 4 * toInteger n) ]
P.CharLit -> [ ("bits", 8 :: Integer) ]
P.DecLit
| fixDec -> if num == 0
then [ ("bits", 0)]
else case genLog num 2 of
Just (x,_) -> [ ("bits", x + 1) ]
_ -> []
| otherwise -> [ ]
P.PolyLit _n -> [ ]
P.ECString s ->
P.ETyped (P.EList [ P.ELit (P.ECNum (fromIntegral (fromEnum c))
P.CharLit) | c <- s ])
(P.TSeq P.TWild (P.TSeq (P.TNum 8) P.TBit))
-- | Infer the type of an expression with an explicit instantiation.
appTys :: P.Expr -> [Located (Maybe QName,Type)] -> Type -> InferM Expr
appTys expr ts tGoal =
case expr of
P.EVar x ->
do res <- lookupVar x
(e',t) <- case res of
ExtVar s -> instantiateWith (EVar x) s ts
CurSCC e t -> instantiateWith e (Forall [] [] t) ts
checkHasType e' t tGoal
P.ELit l -> do e <- desugarLiteral False l
appTys e ts tGoal
P.EAppT e fs ->
do ps <- mapM inferTyParam fs
appTys e (ps ++ ts) tGoal
-- Here is an example of why this might be useful:
-- f ` { x = T } where type T = ...
P.EWhere e ds ->
inferDs ds $ \ds1 -> do e1 <- appTys e ts tGoal
return (EWhere e1 ds1)
-- XXX: Is there a scoping issue here? I think not, but check.
P.ELocated e r ->
inRange r (appTys e ts tGoal)
P.ETuple {} -> mono
P.ERecord {} -> mono
P.ESel {} -> mono
P.EList {} -> mono
P.EFromTo {} -> mono
P.EInfFrom {} -> mono
P.EComp {} -> mono
P.EApp {} -> mono
P.EIf {} -> mono
P.ETyped {} -> mono
P.ETypeVal {} -> mono
P.EFun {} -> mono
P.EParens {} -> tcPanic "appTys" [ "Unexpected EParens" ]
P.EInfix {} -> tcPanic "appTys" [ "Unexpected EInfix" ]
where mono = do e' <- checkE expr tGoal
(ie,t) <- instantiateWith e' (Forall [] [] tGoal) ts
-- XXX seems weird to need to do this, as t should be the same
-- as tGoal
checkHasType ie t tGoal
inferTyParam :: P.TypeInst -> InferM (Located (Maybe QName, Type))
inferTyParam (P.NamedInst param) =
do let loc = srcRange (P.name param)
t <- inRange loc $ checkType (P.value param) Nothing
return $ Located loc (Just (mkUnqual (thing (P.name param))), t)
inferTyParam (P.PosInst param) =
do t <- checkType param Nothing
rng <- case getLoc param of
Nothing -> curRange
Just r -> return r
return Located { srcRange = rng, thing = (Nothing, t) }
checkTypeOfKind :: P.Type -> Kind -> InferM Type
checkTypeOfKind ty k = checkType ty (Just k)
-- | We use this when we want to ensure that the expr has exactly
-- (syntactically) the given type.
inferE :: Doc -> P.Expr -> InferM (Expr, Type)
inferE desc expr =
do t <- newType desc KType
e1 <- checkE expr t
return (e1,t)
-- | Infer the type of an expression, and translate it to a fully elaborated
-- core term.
checkE :: P.Expr -> Type -> InferM Expr
checkE expr tGoal =
case expr of
P.EVar x ->
do res <- lookupVar x
(e',t) <- case res of
ExtVar s -> instantiateWith (EVar x) s []
CurSCC e t -> return (e, t)
checkHasType e' t tGoal
P.ELit l -> (`checkE` tGoal) =<< desugarLiteral False l
P.ETuple es ->
do etys <- expectTuple (length es) tGoal
es' <- zipWithM checkE es etys
return (ETuple es')
P.ERecord fs ->
do (ns,es,ts) <- unzip3 `fmap` expectRec fs tGoal
es' <- zipWithM checkE es ts
return (ERec (zip ns es'))
P.ESel e l ->
do let src = case l of
RecordSel _ _ -> text "type of record"
TupleSel _ _ -> text "type of tuple"
ListSel _ _ -> text "type of sequence"
(e',t) <- inferE src e
f <- newHasGoal l t tGoal
return (f e')
P.EList [] ->
do (len,a) <- expectSeq tGoal
expectFin 0 len
return (EList [] a)
P.EList es ->
do (len,a) <- expectSeq tGoal
expectFin (length es) len
es' <- mapM (`checkE` a) es
return (EList es' a)
P.EFromTo t1 Nothing Nothing ->
do rng <- curRange
bit <- newType (text "bit-width of enumeration sequnce") KNum
fstT <- checkTypeOfKind t1 KNum
let totLen = tNum (2::Int) .^. bit
lstT = totLen .-. tNum (1::Int)
appTys (P.EVar (P.mkPrim "fromTo"))
[ Located rng (Just (mkUnqual (mkName x)), y)
| (x,y) <- [ ("first",fstT), ("last", lstT), ("bits", bit) ]
] tGoal
P.EFromTo t1 mbt2 mbt3 ->
do l <- curRange
let (c,fs) =
case (mbt2, mbt3) of
(Nothing, Nothing) -> tcPanic "checkE"
[ "EFromTo _ Nothing Nothing" ]
(Just t2, Nothing) ->
(P.EVar (P.mkPrim "fromThen"), [ ("next", t2) ])
(Nothing, Just t3) ->
(P.EVar (P.mkPrim "fromTo"), [ ("last", t3) ])
(Just t2, Just t3) ->
(P.EVar (P.mkPrim "fromThenTo"), [ ("next",t2), ("last",t3) ])
let e' = P.EAppT c
[ P.NamedInst P.Named { name = Located l (mkName x), value = y }
| (x,y) <- ("first",t1) : fs
]
checkE e' tGoal
P.EInfFrom e1 Nothing ->
checkE (P.EApp (P.EVar (P.mkPrim "infFrom")) e1) tGoal
P.EInfFrom e1 (Just e2) ->
checkE (P.EApp (P.EApp (P.EVar (P.mkPrim "infFromThen")) e1) e2) tGoal
P.EComp e mss ->
do (mss', dss, ts) <- unzip3 `fmap` zipWithM inferCArm [ 1 .. ] mss
(len,a)<- expectSeq tGoal
newGoals CtComprehension =<< unify len =<< smallest ts
ds <- combineMaps dss
e' <- withMonoTypes ds (checkE e a)
return (EComp tGoal e' mss')
P.EAppT e fs ->
do ts <- mapM inferTyParam fs
appTys e ts tGoal
P.EApp fun@(dropLoc -> P.EApp (dropLoc -> P.EVar c) _)
arg@(dropLoc -> P.ELit l)
| c `elem` [ P.mkPrim "<<", P.mkPrim ">>", P.mkPrim "<<<", P.mkPrim ">>>"
, P.mkPrim "@", P.mkPrim "!" ] ->
do newArg <- do l1 <- desugarLiteral True l
return $ case arg of
P.ELocated _ pos -> P.ELocated l1 pos
_ -> l1
checkE (P.EApp fun newArg) tGoal
P.EApp e1 e2 ->
do t1 <- newType (text "argument to function") KType
e1' <- checkE e1 (tFun t1 tGoal)
e2' <- checkE e2 t1
return (EApp e1' e2')
P.EIf e1 e2 e3 ->
do e1' <- checkE e1 tBit
e2' <- checkE e2 tGoal
e3' <- checkE e3 tGoal
return (EIf e1' e2' e3')
P.EWhere e ds ->
inferDs ds $ \ds1 -> do e1 <- checkE e tGoal
return (EWhere e1 ds1)
P.ETyped e t ->
do tSig <- checkTypeOfKind t KType
e' <- checkE e tSig
checkHasType e' tSig tGoal
P.ETypeVal t ->
do l <- curRange
checkE (P.EAppT (P.EVar (P.mkPrim "demote"))
[P.NamedInst
P.Named { name = Located l (mkName "val"), value = t }]) tGoal
P.EFun ps e -> checkFun (text "anonymous function") ps e tGoal
P.ELocated e r -> inRange r (checkE e tGoal)
P.EInfix a op _ b -> checkE (P.EVar (thing op) `P.EApp` a `P.EApp` b) tGoal
P.EParens e -> checkE e tGoal
expectSeq :: Type -> InferM (Type,Type)
expectSeq ty =
case ty of
TUser _ _ ty' ->
expectSeq ty'
TCon (TC TCSeq) [a,b] ->
return (a,b)
TVar _ ->
do tys@(a,b) <- genTys
newGoals CtExactType =<< unify (tSeq a b) ty
return tys
_ ->
do tys@(a,b) <- genTys
recordError (TypeMismatch (tSeq a b) ty)
return tys
where
genTys =
do a <- newType (text "size of the sequence") KNum
b <- newType (text "type of sequence elements") KType
return (a,b)
expectTuple :: Int -> Type -> InferM [Type]
expectTuple n ty =
case ty of
TUser _ _ ty' ->
expectTuple n ty'
TCon (TC (TCTuple n')) tys | n == n' ->
return tys
TVar _ ->
do tys <- genTys
newGoals CtExactType =<< unify (tTuple tys) ty
return tys
_ ->
do tys <- genTys
recordError (TypeMismatch (tTuple tys) ty)
return tys
where
genTys =forM [ 0 .. n - 1 ] $ \ i ->
let desc = text "type of"
<+> ordinal i
<+> text "tuple field"
in newType desc KType
expectRec :: [P.Named a] -> Type -> InferM [(Name,a,Type)]
expectRec fs ty =
case ty of
TUser _ _ ty' ->
expectRec fs ty'
TRec ls | Just tys <- mapM checkField ls ->
return tys
_ ->
do (tys,res) <- genTys
case ty of
TVar TVFree{} -> do ps <- unify (TRec tys) ty
newGoals CtExactType ps
_ -> recordError (TypeMismatch (TRec tys) ty)
return res
where
checkField (n,t) =
do f <- find (\f -> thing (P.name f) == n) fs
return (thing (P.name f), P.value f, t)
genTys =
do res <- forM fs $ \ f ->
do let field = thing (P.name f)
t <- newType (text "type of field" <+> quotes (pp field)) KType
return (field, P.value f, t)
let (ls,_,ts) = unzip3 res
return (zip ls ts, res)
expectFin :: Int -> Type -> InferM ()
expectFin n ty =
case ty of
TUser _ _ ty' ->
expectFin n ty'
TCon (TC (TCNum n')) [] | toInteger n == n' ->
return ()
TVar TVFree{} ->
do newGoals CtExactType =<< unify (tNum n) ty
_ ->
recordError (TypeMismatch (tNum n) ty)
expectFun :: Int -> Type -> InferM ([Type],Type)
expectFun = go []
where
go tys arity ty
| arity > 0 =
case ty of
TUser _ _ ty' ->
go tys arity ty'
TCon (TC TCFun) [a,b] ->
go (a:tys) (arity - 1) b
_ ->
do args <- genArgs arity
res <- newType (text "result of function") KType
case ty of
TVar TVFree{} -> do ps <- unify (foldr tFun res args) ty
newGoals CtExactType ps
_ -> recordError (TypeMismatch (foldr tFun res args) ty)
return (reverse tys ++ args, res)
| otherwise =
return (reverse tys, ty)
genArgs arity = forM [ 1 .. arity ] $ \ ix ->
newType (text "argument" <+> ordinal ix) KType
checkHasType :: Expr -> Type -> Type -> InferM Expr
checkHasType e inferredType givenType =
do ps <- unify givenType inferredType
case ps of
[] -> return e
_ -> newGoals CtExactType ps >> return (ECast e givenType)
checkFun :: Doc -> [P.Pattern] -> P.Expr -> Type -> InferM Expr
checkFun _ [] e tGoal = checkE e tGoal
checkFun desc ps e tGoal =
inNewScope $
do let descs = [ text "type of" <+> ordinal n <+> text "argument"
<+> text "of" <+> desc | n <- [ 1 :: Int .. ] ]
(tys,tRes) <- expectFun (length ps) tGoal
largs <- sequence (zipWith3 checkP descs ps tys)
let ds = Map.fromList [ (thing x, x { thing = t }) | (x,t) <- zip largs tys ]
e1 <- withMonoTypes ds (checkE e tRes)
let args = [ (thing x, t) | (x,t) <- zip largs tys ]
return (foldr (\(x,t) b -> EAbs x t b) e1 args)
{-| The type the is the smallest of all -}
smallest :: [Type] -> InferM Type
smallest [] = newType (text "length of list comprehension") KNum
smallest [t] = return t
smallest ts = do a <- newType (text "length of list comprehension") KNum
newGoals CtComprehension [ a =#= foldr1 tMin ts ]
return a
checkP :: Doc -> P.Pattern -> Type -> InferM (Located QName)
checkP desc p tGoal =
do (x, t) <- inferP desc p
ps <- unify tGoal (thing t)
case ps of
[] -> return (Located (srcRange t) x)
_ -> tcPanic "checkP" [ "Unexpected constraints:", show ps ]
{-| Infer the type of a pattern. Assumes that the pattern will be just
a variable. -}
inferP :: Doc -> P.Pattern -> InferM (QName, Located Type)
inferP desc pat =
case pat of
P.PVar x0 ->
do a <- newType desc KType
let x = thing x0
return (mkUnqual x, x0 { thing = a })
P.PTyped p t ->
do tSig <- checkTypeOfKind t KType
ln <- checkP desc p tSig
return (thing ln, ln { thing = tSig })
_ -> tcPanic "inferP" [ "Unexpected pattern:", show pat ]
-- | Infer the type of one match in a list comprehension.
inferMatch :: P.Match -> InferM (Match, QName, Located Type, Type)
inferMatch (P.Match p e) =
do (x,t) <- inferP (text "XXX:MATCH") p
n <- newType (text "sequence length of comprehension match") KNum
e' <- checkE e (tSeq n (thing t))
return (From x (thing t) e', x, t, n)
inferMatch (P.MatchLet b)
| P.bMono b =
do a <- newType (text "`let` binding in comprehension") KType
b1 <- checkMonoB b a
return (Let b1, dName b1, Located (srcRange (P.bName b)) a, tNum (1::Int))
| otherwise = tcPanic "inferMatch"
[ "Unexpected polymorphic match let:", show b ]
-- | Infer the type of one arm of a list comprehension.
inferCArm :: Int -> [P.Match] -> InferM
( [Match]
, Map QName (Located Type)-- defined vars
, Type -- length of sequence
)
inferCArm _ [] = do n <- newType (text "lenght of empty comprehension") KNum
-- shouldn't really happen
return ([], Map.empty, n)
inferCArm _ [m] =
do (m1, x, t, n) <- inferMatch m
return ([m1], Map.singleton x t, n)
inferCArm armNum (m : ms) =
do (m1, x, t, n) <- inferMatch m
(ms', ds, n') <- withMonoType (x,t) (inferCArm armNum ms)
-- XXX: Well, this is just the lenght of this sub-sequence
let src = text "length of" <+> ordinal armNum <+>
text "arm of list comprehension"
sz <- newType src KNum
newGoals CtComprehension [ sz =#= (n .*. n') ]
return (m1 : ms', Map.insertWith (\_ old -> old) x t ds, sz)
-- | @inferBinds isTopLevel isRec binds@ performs inference for a
-- strongly-connected component of 'P.Bind's. If @isTopLevel@ is true,
-- any bindings without type signatures will be generalized. If it is
-- false, and the mono-binds flag is enabled, no bindings without type
-- signatures will be generalized, but bindings with signatures will
-- be unaffected.
inferBinds :: Bool -> Bool -> [P.Bind] -> InferM [Decl]
inferBinds isTopLevel isRec binds =
mdo let dExpr (DExpr e) = e
dExpr DPrim = panic "[TypeCheck]" [ "primitive in a recursive group" ]
exprMap = Map.fromList [ (x,inst (EVar x) (dExpr (dDefinition b)))
| b <- genBs, let x = dName b ] -- REC.
inst e (ETAbs x e1) = inst (ETApp e (TVar (tpVar x))) e1
inst e (EProofAbs _ e1) = inst (EProofApp e) e1
inst e _ = e
-- when mono-binds is enabled, and we're not checking top-level
-- declarations, mark all bindings lacking signatures as monomorphic
monoBinds <- getMonoBinds
let binds' | monoBinds && not isTopLevel = sigs ++ monos
| otherwise = binds
(sigs,noSigs) = partition (isJust . P.bSignature) binds
monos = [ b { P.bMono = True } | b <- noSigs ]
((doneBs, genCandidates), cs) <-
collectGoals $
{- Guess type is here, because while we check user supplied signatures
we may generate additional constraints. For example, `x - y` would
generate an additional constraint `x >= y`. -}
do (newEnv,todos) <- unzip `fmap` mapM (guessType exprMap) binds'
let extEnv = if isRec then withVarTypes newEnv else id
extEnv $
do let (sigsAndMonos,noSigGen) = partitionEithers todos
genCs <- sequence noSigGen
done <- sequence sigsAndMonos
simplifyAllConstraints
return (done, genCs)
genBs <- generalize genCandidates cs -- RECURSION
return (doneBs ++ genBs)
{- | Come up with a type for recursive calls to a function, and decide
how we are going to be checking the binding.
Returns: (Name, type or schema, computation to check binding)
The `exprMap` is a thunk where we can lookup the final expressions
and we should be careful not to force it.
-}
guessType :: Map QName Expr -> P.Bind ->
InferM ( (QName, VarType)
, Either (InferM Decl) -- no generalization
(InferM Decl) -- generalize these
)
guessType exprMap b@(P.Bind { .. }) =
case bSignature of
Just s ->
do s1 <- checkSchema s
return ((name, ExtVar (fst s1)), Left (checkSigB b s1))
Nothing
| bMono ->
do t <- newType (text "defintion of" <+> quotes (pp name)) KType
let schema = Forall [] [] t
return ((name, ExtVar schema), Left (checkMonoB b t))
| otherwise ->
do t <- newType (text "definition of" <+> quotes (pp name)) KType
let noWay = tcPanic "guessType" [ "Missing expression for:" ,
show name ]
expr = Map.findWithDefault noWay name exprMap
return ((name, CurSCC expr t), Right (checkMonoB b t))
where
name = thing bName
-- | Try to evaluate the inferred type in a binding.
simpBind :: Decl -> Decl
simpBind d =
case dSignature d of
Forall as qs t ->
case simpTypeMaybe t of
Nothing -> d
Just t1 -> d { dSignature = Forall as qs t1
, dDefinition = case dDefinition d of
DPrim -> DPrim
DExpr e -> DExpr (castUnder t1 e)
}
where
-- Assumes the quantifiers match
castUnder t (ETAbs a e) = ETAbs a (castUnder t e)
castUnder t (EProofAbs p e) = EProofAbs p (castUnder t e)
castUnder t e = ECast e t
-- | The inputs should be declarations with monomorphic types
-- (i.e., of the form `Forall [] [] t`).
generalize :: [Decl] -> [Goal] -> InferM [Decl]
{- This may happen because we have monomorphic bindings.
In this case we may get some goal, due to the monomorphic bindings,
but the group of components is empty. -}
generalize [] gs0 =
do addGoals gs0
return []
generalize bs0 gs0 =
do gs <- forM gs0 $ \g -> applySubst g
-- XXX: Why would these bindings have signatures??
bs1 <- forM bs0 $ \b -> do s <- applySubst (dSignature b)
return b { dSignature = s }
let bs = map simpBind bs1
let goalFVS g = Set.filter isFreeTV $ fvs $ goal g
inGoals = Set.unions $ map goalFVS gs
inSigs = Set.filter isFreeTV $ fvs $ map dSignature bs
candidates = Set.union inGoals inSigs
asmpVs <- varsWithAsmps
let gen0 = Set.difference candidates asmpVs
stays g = any (`Set.member` gen0) $ Set.toList $ goalFVS g
(here0,later) = partition stays gs
-- Figure out what might be ambigious
let (maybeAmbig, ambig) = partition ((KNum ==) . kindOf)
$ Set.toList
$ Set.difference gen0 inSigs
when (not (null ambig)) $ recordError $ AmbiguousType $ map dName bs
cfg <- getSolverConfig
(as0,here1,defSu,ws) <- io $ improveByDefaulting cfg maybeAmbig here0
mapM_ recordWarning ws
let here = map goal here1
let as = as0 ++ Set.toList (Set.difference inSigs asmpVs)
asPs = [ TParam { tpUnique = x, tpKind = k, tpName = Nothing }
| TVFree x k _ _ <- as ]
totSu <- getSubst
let
su = listSubst (zip as (map (TVar . tpVar) asPs)) @@ defSu @@ totSu
qs = map (apSubst su) here
genE e = foldr ETAbs (foldr EProofAbs (apSubst su e) qs) asPs
genB d = d { dDefinition = case dDefinition d of
DExpr e -> DExpr (genE e)
DPrim -> DPrim
, dSignature = Forall asPs qs
$ apSubst su $ sType $ dSignature d
}
addGoals later
return (map (simpBind . genB) bs)
checkMonoB :: P.Bind -> Type -> InferM Decl
checkMonoB b t =
inRangeMb (getLoc b) $
case thing (P.bDef b) of
P.DPrim ->
return Decl { dName = thing (P.bName b)
, dSignature = Forall [] [] t
, dDefinition = DPrim
, dPragmas = P.bPragmas b
, dInfix = P.bInfix b
, dFixity = P.bFixity b
, dDoc = P.bDoc b
}
P.DExpr e ->
do e1 <- checkFun (pp (thing (P.bName b))) (P.bParams b) e t
let f = thing (P.bName b)
return Decl { dName = f
, dSignature = Forall [] [] t
, dDefinition = DExpr e1
, dPragmas = P.bPragmas b
, dInfix = P.bInfix b
, dFixity = P.bFixity b
, dDoc = P.bDoc b
}
-- XXX: Do we really need to do the defaulting business in two different places?
checkSigB :: P.Bind -> (Schema,[Goal]) -> InferM Decl
checkSigB b (Forall as asmps0 t0, validSchema) = case thing (P.bDef b) of
-- XXX what should we do with validSchema in this case?
P.DPrim ->
do return Decl { dName = thing (P.bName b)
, dSignature = Forall as asmps0 t0
, dDefinition = DPrim
, dPragmas = P.bPragmas b
, dInfix = P.bInfix b
, dFixity = P.bFixity b
, dDoc = P.bDoc b
}
P.DExpr e0 ->
inRangeMb (getLoc b) $
withTParams as $
do (e1,cs0) <- collectGoals $
do e1 <- checkFun (pp (thing (P.bName b))) (P.bParams b) e0 t0
() <- simplifyAllConstraints -- XXX: using `asmps` also...
return e1
cs <- applySubst cs0
let letGo qs c = Set.null (qs `Set.intersection` fvs (goal c))
splitPreds qs n ps =
let (l,n1) = partition (letGo qs) ps
in if null n1
then (l,n)
else splitPreds (fvs (map goal n1) `Set.union` qs) (n1 ++ n) l
(later0,now) = splitPreds (Set.fromList (map tpVar as)) [] cs
asmps1 <- applySubst asmps0
defSu1 <- proveImplication (P.bName b) as asmps1 (validSchema ++ now)
let later = apSubst defSu1 later0
asmps = apSubst defSu1 asmps1
-- Now we check for any remaining variables that are not mentioned
-- in the environment. The plan is to try to default these to something
-- reasonable.
do let laterVs = fvs (map goal later)
asmpVs <- varsWithAsmps
let genVs = laterVs `Set.difference` asmpVs
(maybeAmbig,ambig) = partition ((== KNum) . kindOf)
(Set.toList genVs)
when (not (null ambig)) $ recordError
$ AmbiguousType [ thing (P.bName b) ]
cfg <- getSolverConfig
(_,_,defSu2,ws) <- io $ improveByDefaulting cfg maybeAmbig later
mapM_ recordWarning ws
extendSubst defSu2
addGoals later
su <- getSubst
let su' = defSu1 @@ su
t = apSubst su' t0
e2 = apSubst su' e1
return Decl
{ dName = thing (P.bName b)
, dSignature = Forall as asmps t
, dDefinition = DExpr (foldr ETAbs (foldr EProofAbs e2 asmps) as)
, dPragmas = P.bPragmas b
, dInfix = P.bInfix b
, dFixity = P.bFixity b
, dDoc = P.bDoc b
}
inferDs :: FromDecl d => [d] -> ([DeclGroup] -> InferM a) -> InferM a
inferDs ds continue = checkTyDecls =<< orderTyDecls (mapMaybe toTyDecl ds)
where
isTopLevel = isTopDecl (head ds)
checkTyDecls (TS t : ts) =
do t1 <- checkTySyn t
withTySyn t1 (checkTyDecls ts)
checkTyDecls (NT t : ts) =
do t1 <- checkNewtype t
withNewtype t1 (checkTyDecls ts)
-- We checked all type synonyms, now continue with value-level definitions:
checkTyDecls [] = checkBinds [] $ orderBinds $ mapMaybe toBind ds
checkBinds decls (CyclicSCC bs : more) =
do bs1 <- inferBinds isTopLevel True bs
foldr (\b m -> withVar (dName b) (dSignature b) m)
(checkBinds (Recursive bs1 : decls) more)
bs1
checkBinds decls (AcyclicSCC c : more) =
do [b] <- inferBinds isTopLevel False [c]
withVar (dName b) (dSignature b) $
checkBinds (NonRecursive b : decls) more
-- We are done with all value-level definitions.
-- Now continue with anything that's in scope of the declarations.
checkBinds decls [] = continue (reverse decls)
tcPanic :: String -> [String] -> a
tcPanic l msg = panic ("[TypeCheck] " ++ l) msg
|
beni55/cryptol
|
src/Cryptol/TypeCheck/Infer.hs
|
Haskell
|
bsd-3-clause
| 28,607
|
-- | Spectral functions
module Csound.Air.Spec(
toSpec, fromSpec, mapSpec, scaleSpec, addSpec, scalePitch,
CrossSpec(..),
crossSpecFilter, crossSpecVocoder, crossSpecFilter1, crossSpecVocoder1
) where
import Data.Default
import Csound.Typed
import Csound.Typed.Opcode
import Csound.Tab(sine)
--------------------------------------------------------------------------
-- spectral functions
-- | Converts signal to spectrum.
toSpec :: Sig -> Spec
toSpec asig = pvsanal asig 1024 256 1024 1
-- | Converts spectrum to signal.
fromSpec :: Spec -> Sig
fromSpec = pvsynth
-- | Applies a transformation to the spectrum of the signal.
mapSpec :: (Spec -> Spec) -> Sig -> Sig
mapSpec f = fromSpec . f . toSpec
-- | Scales all frequencies. Usefull for transposition.
-- For example, we can transpose a signal by the given amount of semitones:
--
-- > scaleSpec (semitone 1) asig
scaleSpec :: Sig -> Sig -> Sig
scaleSpec k = mapSpec $ \x -> pvscale x k
-- | Adds given amount of Hz to all frequencies.
--
-- > addSpec hz asig
addSpec :: Sig -> Sig -> Sig
addSpec hz = mapSpec $ \x -> pvshift x hz 0
-- | Scales frequency in semitones.
scalePitch :: Sig -> Sig -> Sig
scalePitch n = scaleSpec (semitone n)
--------------------------------------------------------------------------
at2 :: (Sig -> Sig -> Sig) -> Sig2 -> Sig2 -> Sig2
at2 f (left1, right1) (left2, right2) = (f left1 left2, f right1 right2)
-- | Settings for cross filtering algorithm.
--
-- They are the defaults for opvodes: @pvsifd@, @tradsyn@, @trcross@ and @partials@.
--
-- * Fft size degree -- it's the power of 2. The default is 12.
--
-- * Hop size degree -- it's the power of 2. The default is 9
--
-- * scale --amplitude scaling factor. default is 1
--
-- * pitch -- the pitch scaling factor. default is 1
--
-- * @maxTracks@ -- max number of tracks in resynthesis (tradsyn) and analysis (partials).
--
-- * @winType@ -- O: Hamming, 1: Hanning (default)
--
-- * @Search@ -- search interval length. The default is 1.05
--
-- * @Depth@ -- depth of the effect
--
-- * @Thresh@ -- analysis threshold. Tracks below ktresh*max_magnitude will be discarded (1 > ktresh >= 0).The default is 0.01
--
-- * @MinPoints@ -- minimum number of time points for a detected peak to make a track (1 is the minimum).
--
-- * @MaxGap@ -- maximum gap between time-points for track continuation (> 0). Tracks that have no continuation after kmaxgap will be discarded.
data CrossSpec = CrossSpec
{ crossFft :: D
, crossHopSize :: D
, crossScale :: Sig
, crossPitch :: Sig
, crossMaxTracks :: D
, crossWinType :: D
, crossSearch :: Sig
, crossDepth :: Sig
, crossThresh :: Sig
, crossMinPoints :: Sig
, crossMaxGap :: Sig
}
instance Default CrossSpec where
def = CrossSpec
{ crossFft = 12
, crossHopSize = 9
, crossScale = 1
, crossPitch = 1
, crossMaxTracks = 500
, crossWinType = 1
, crossSearch = 1.05
, crossDepth = 1
, crossThresh = 0.01
, crossMinPoints = 1
, crossMaxGap = 3
}
-- | Filters the partials of the second signal with partials of the first signal.
crossSpecFilter :: CrossSpec -> Sig2 -> Sig2 -> Sig2
crossSpecFilter spec = at2 (crossSpecFilter1 spec)
-- | Substitutes the partials of the second signal with partials of the first signal.
crossSpecVocoder :: CrossSpec -> Sig2 -> Sig2 -> Sig2
crossSpecVocoder spec = at2 (crossSpecVocoder1 spec)
-- | @crossSpecFilter@ for mono signals.
crossSpecFilter1 :: CrossSpec -> Sig -> Sig -> Sig
crossSpecFilter1 = crossSpecBy 0
-- | @crossSpecVocoder@ for mono signals.
crossSpecVocoder1 :: CrossSpec -> Sig -> Sig -> Sig
crossSpecVocoder1 = crossSpecBy 1
crossSpecBy :: D -> CrossSpec -> Sig -> Sig -> Sig
crossSpecBy imode spec ain1 ain2 =
tradsyn (trcross (getPartials ain2) (getPartials ain1) (crossSearch spec) (crossDepth spec) `withD` imode) (crossScale spec) (crossPitch spec) (sig $ crossMaxTracks spec) sine
where
getPartials asig = partials fs1 fsi2 (crossThresh spec) (crossMinPoints spec) (crossMaxGap spec) (crossMaxTracks spec)
where (fs1, fsi2) = pvsifd asig (2 ** (crossFft spec)) (2 ** (crossHopSize spec)) (crossWinType spec)
|
isomorphism/csound-expression
|
src/Csound/Air/Spec.hs
|
Haskell
|
bsd-3-clause
| 4,168
|
tick y = y:tock y
tock y = y:tick y
|
themattchan/tandoori
|
input/mutual.hs
|
Haskell
|
bsd-3-clause
| 36
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Typeable.Internal
-- Copyright : (c) The University of Glasgow, CWI 2001--2011
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- The representations of the types TyCon and TypeRep, and the
-- function mkTyCon which is used by derived instances of Typeable to
-- construct a TyCon.
--
-----------------------------------------------------------------------------
module Data.Typeable.Internal (
Proxy (..),
Fingerprint(..),
-- * Typeable class
typeOf, typeOf1, typeOf2, typeOf3, typeOf4, typeOf5, typeOf6, typeOf7,
Typeable1, Typeable2, Typeable3, Typeable4, Typeable5, Typeable6, Typeable7,
-- * Module
Module, -- Abstract
moduleName, modulePackage,
-- * TyCon
TyCon, -- Abstract
tyConPackage, tyConModule, tyConName, tyConString, tyConFingerprint,
mkTyCon3, mkTyCon3#,
rnfTyCon,
tcBool, tc'True, tc'False,
tcOrdering, tc'LT, tc'EQ, tc'GT,
tcChar, tcInt, tcWord, tcFloat, tcDouble, tcFun,
tcIO, tcSPEC, tcTyCon, tcModule,
tcCoercible, tcList, tcEq,
tcLiftedKind, tcUnliftedKind, tcOpenKind, tcBOX, tcConstraint, tcAnyK,
funTc, -- ToDo
-- * TypeRep
TypeRep(..), KindRep,
typeRep,
mkTyConApp,
mkPolyTyConApp,
mkAppTy,
typeRepTyCon,
Typeable(..),
mkFunTy,
splitTyConApp,
splitPolyTyConApp,
funResultTy,
typeRepArgs,
typeRepFingerprint,
rnfTypeRep,
showsTypeRep,
typeRepKinds,
typeSymbolTypeRep, typeNatTypeRep
) where
import GHC.Base
import GHC.Word
import GHC.Show
import Data.Proxy
import GHC.TypeLits( KnownNat, KnownSymbol, natVal', symbolVal' )
import GHC.Fingerprint.Type
import {-# SOURCE #-} GHC.Fingerprint
-- loop: GHC.Fingerprint -> Foreign.Ptr -> Data.Typeable
-- Better to break the loop here, because we want non-SOURCE imports
-- of Data.Typeable as much as possible so we can optimise the derived
-- instances.
#include "MachDeps.h"
{- *********************************************************************
* *
The TyCon type
* *
********************************************************************* -}
modulePackage :: Module -> String
modulePackage (Module p _) = trNameString p
moduleName :: Module -> String
moduleName (Module _ m) = trNameString m
tyConPackage :: TyCon -> String
tyConPackage (TyCon _ _ m _) = modulePackage m
tyConModule :: TyCon -> String
tyConModule (TyCon _ _ m _) = moduleName m
tyConName :: TyCon -> String
tyConName (TyCon _ _ _ n) = trNameString n
trNameString :: TrName -> String
trNameString (TrNameS s) = unpackCString# s
trNameString (TrNameD s) = s
-- | Observe string encoding of a type representation
{-# DEPRECATED tyConString "renamed to 'tyConName'; 'tyConModule' and 'tyConPackage' are also available." #-}
-- deprecated in 7.4
tyConString :: TyCon -> String
tyConString = tyConName
tyConFingerprint :: TyCon -> Fingerprint
tyConFingerprint (TyCon hi lo _ _)
= Fingerprint (W64# hi) (W64# lo)
mkTyCon3# :: Addr# -- ^ package name
-> Addr# -- ^ module name
-> Addr# -- ^ the name of the type constructor
-> TyCon -- ^ A unique 'TyCon' object
mkTyCon3# pkg modl name
| Fingerprint (W64# hi) (W64# lo) <- fingerprint
= TyCon hi lo (Module (TrNameS pkg) (TrNameS modl)) (TrNameS name)
where
fingerprint :: Fingerprint
fingerprint = fingerprintString (unpackCString# pkg
++ (' ': unpackCString# modl)
++ (' ' : unpackCString# name))
mkTyCon3 :: String -- ^ package name
-> String -- ^ module name
-> String -- ^ the name of the type constructor
-> TyCon -- ^ A unique 'TyCon' object
-- Used when the strings are dynamically allocated,
-- eg from binary deserialisation
mkTyCon3 pkg modl name
| Fingerprint (W64# hi) (W64# lo) <- fingerprint
= TyCon hi lo (Module (TrNameD pkg) (TrNameD modl)) (TrNameD name)
where
fingerprint :: Fingerprint
fingerprint = fingerprintString (pkg ++ (' ':modl) ++ (' ':name))
isTupleTyCon :: TyCon -> Bool
isTupleTyCon tc
| ('(':',':_) <- tyConName tc = True
| otherwise = False
-- | Helper to fully evaluate 'TyCon' for use as @NFData(rnf)@ implementation
--
-- @since 4.8.0.0
rnfModule :: Module -> ()
rnfModule (Module p m) = rnfTrName p `seq` rnfTrName m
rnfTrName :: TrName -> ()
rnfTrName (TrNameS _) = ()
rnfTrName (TrNameD n) = rnfString n
rnfTyCon :: TyCon -> ()
rnfTyCon (TyCon _ _ m n) = rnfModule m `seq` rnfTrName n
rnfString :: [Char] -> ()
rnfString [] = ()
rnfString (c:cs) = c `seq` rnfString cs
{- *********************************************************************
* *
The TypeRep type
* *
********************************************************************* -}
-- | A concrete representation of a (monomorphic) type.
-- 'TypeRep' supports reasonably efficient equality.
data TypeRep = TypeRep {-# UNPACK #-} !Fingerprint TyCon [KindRep] [TypeRep]
-- NB: For now I've made this lazy so that it's easy to
-- optimise code that constructs and deconstructs TypeReps
-- perf/should_run/T9203 is a good example
-- Also note that mkAppTy does discards the fingerprint,
-- so it's a waste to compute it
type KindRep = TypeRep
-- Compare keys for equality
instance Eq TypeRep where
TypeRep x _ _ _ == TypeRep y _ _ _ = x == y
instance Ord TypeRep where
TypeRep x _ _ _ <= TypeRep y _ _ _ = x <= y
-- | Observe the 'Fingerprint' of a type representation
--
-- @since 4.8.0.0
typeRepFingerprint :: TypeRep -> Fingerprint
typeRepFingerprint (TypeRep fpr _ _ _) = fpr
-- | Applies a kind-polymorphic type constructor to a sequence of kinds and
-- types
mkPolyTyConApp :: TyCon -> [KindRep] -> [TypeRep] -> TypeRep
{-# INLINE mkPolyTyConApp #-}
mkPolyTyConApp tc kinds types
= TypeRep (fingerprintFingerprints sub_fps) tc kinds types
where
!kt_fps = typeRepFingerprints kinds types
sub_fps = tyConFingerprint tc : kt_fps
typeRepFingerprints :: [KindRep] -> [TypeRep] -> [Fingerprint]
-- Builds no thunks
typeRepFingerprints kinds types
= go1 [] kinds
where
go1 acc [] = go2 acc types
go1 acc (k:ks) = let !fp = typeRepFingerprint k
in go1 (fp:acc) ks
go2 acc [] = acc
go2 acc (t:ts) = let !fp = typeRepFingerprint t
in go2 (fp:acc) ts
-- | Applies a kind-monomorphic type constructor to a sequence of types
mkTyConApp :: TyCon -> [TypeRep] -> TypeRep
mkTyConApp tc = mkPolyTyConApp tc []
-- | A special case of 'mkTyConApp', which applies the function
-- type constructor to a pair of types.
mkFunTy :: TypeRep -> TypeRep -> TypeRep
mkFunTy f a = mkTyConApp tcFun [f,a]
-- | Splits a type constructor application.
-- Note that if the type construcotr is polymorphic, this will
-- not return the kinds that were used.
-- See 'splitPolyTyConApp' if you need all parts.
splitTyConApp :: TypeRep -> (TyCon,[TypeRep])
splitTyConApp (TypeRep _ tc _ trs) = (tc,trs)
-- | Split a type constructor application
splitPolyTyConApp :: TypeRep -> (TyCon,[KindRep],[TypeRep])
splitPolyTyConApp (TypeRep _ tc ks trs) = (tc,ks,trs)
-- | Applies a type to a function type. Returns: @'Just' u@ if the
-- first argument represents a function of type @t -> u@ and the
-- second argument represents a function of type @t@. Otherwise,
-- returns 'Nothing'.
funResultTy :: TypeRep -> TypeRep -> Maybe TypeRep
funResultTy trFun trArg
= case splitTyConApp trFun of
(tc, [t1,t2]) | tc == tcFun && t1 == trArg -> Just t2
_ -> Nothing
-- | Adds a TypeRep argument to a TypeRep.
mkAppTy :: TypeRep -> TypeRep -> TypeRep
{-# INLINE mkAppTy #-}
mkAppTy (TypeRep _ tc ks trs) arg_tr = mkPolyTyConApp tc ks (trs ++ [arg_tr])
-- Notice that we call mkTyConApp to construct the fingerprint from tc and
-- the arg fingerprints. Simply combining the current fingerprint with
-- the new one won't give the same answer, but of course we want to
-- ensure that a TypeRep of the same shape has the same fingerprint!
-- See Trac #5962
----------------- Observation ---------------------
-- | Observe the type constructor of a type representation
typeRepTyCon :: TypeRep -> TyCon
typeRepTyCon (TypeRep _ tc _ _) = tc
-- | Observe the argument types of a type representation
typeRepArgs :: TypeRep -> [TypeRep]
typeRepArgs (TypeRep _ _ _ tys) = tys
-- | Observe the argument kinds of a type representation
typeRepKinds :: TypeRep -> [KindRep]
typeRepKinds (TypeRep _ _ ks _) = ks
{- *********************************************************************
* *
The Typeable class
* *
********************************************************************* -}
-------------------------------------------------------------
--
-- The Typeable class and friends
--
-------------------------------------------------------------
-- | The class 'Typeable' allows a concrete representation of a type to
-- be calculated.
class Typeable a where
typeRep# :: Proxy# a -> TypeRep
-- | Takes a value of type @a@ and returns a concrete representation
-- of that type.
--
-- @since 4.7.0.0
typeRep :: forall proxy a. Typeable a => proxy a -> TypeRep
typeRep _ = typeRep# (proxy# :: Proxy# a)
{-# INLINE typeRep #-}
-- Keeping backwards-compatibility
typeOf :: forall a. Typeable a => a -> TypeRep
typeOf _ = typeRep (Proxy :: Proxy a)
typeOf1 :: forall t (a :: *). Typeable t => t a -> TypeRep
typeOf1 _ = typeRep (Proxy :: Proxy t)
typeOf2 :: forall t (a :: *) (b :: *). Typeable t => t a b -> TypeRep
typeOf2 _ = typeRep (Proxy :: Proxy t)
typeOf3 :: forall t (a :: *) (b :: *) (c :: *). Typeable t
=> t a b c -> TypeRep
typeOf3 _ = typeRep (Proxy :: Proxy t)
typeOf4 :: forall t (a :: *) (b :: *) (c :: *) (d :: *). Typeable t
=> t a b c d -> TypeRep
typeOf4 _ = typeRep (Proxy :: Proxy t)
typeOf5 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *). Typeable t
=> t a b c d e -> TypeRep
typeOf5 _ = typeRep (Proxy :: Proxy t)
typeOf6 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *).
Typeable t => t a b c d e f -> TypeRep
typeOf6 _ = typeRep (Proxy :: Proxy t)
typeOf7 :: forall t (a :: *) (b :: *) (c :: *) (d :: *) (e :: *) (f :: *)
(g :: *). Typeable t => t a b c d e f g -> TypeRep
typeOf7 _ = typeRep (Proxy :: Proxy t)
type Typeable1 (a :: * -> *) = Typeable a
type Typeable2 (a :: * -> * -> *) = Typeable a
type Typeable3 (a :: * -> * -> * -> *) = Typeable a
type Typeable4 (a :: * -> * -> * -> * -> *) = Typeable a
type Typeable5 (a :: * -> * -> * -> * -> * -> *) = Typeable a
type Typeable6 (a :: * -> * -> * -> * -> * -> * -> *) = Typeable a
type Typeable7 (a :: * -> * -> * -> * -> * -> * -> * -> *) = Typeable a
{-# DEPRECATED Typeable1 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable2 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable3 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable4 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable5 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable6 "renamed to 'Typeable'" #-} -- deprecated in 7.8
{-# DEPRECATED Typeable7 "renamed to 'Typeable'" #-} -- deprecated in 7.8
----------------- Showing TypeReps --------------------
instance Show TypeRep where
showsPrec p (TypeRep _ tycon kinds tys) =
case tys of
[] -> showsPrec p tycon
[x] | tycon == tcList -> showChar '[' . shows x . showChar ']'
[a,r] | tycon == tcFun -> showParen (p > 8) $
showsPrec 9 a .
showString " -> " .
showsPrec 8 r
xs | isTupleTyCon tycon -> showTuple xs
| otherwise ->
showParen (p > 9) $
showsPrec p tycon .
showChar ' ' .
showArgs (showChar ' ') (kinds ++ tys)
showsTypeRep :: TypeRep -> ShowS
showsTypeRep = shows
-- | Helper to fully evaluate 'TypeRep' for use as @NFData(rnf)@ implementation
--
-- @since 4.8.0.0
rnfTypeRep :: TypeRep -> ()
rnfTypeRep (TypeRep _ tyc krs tyrs) = rnfTyCon tyc `seq` go krs `seq` go tyrs
where
go [] = ()
go (x:xs) = rnfTypeRep x `seq` go xs
-- Some (Show.TypeRep) helpers:
showArgs :: Show a => ShowS -> [a] -> ShowS
showArgs _ [] = id
showArgs _ [a] = showsPrec 10 a
showArgs sep (a:as) = showsPrec 10 a . sep . showArgs sep as
showTuple :: [TypeRep] -> ShowS
showTuple args = showChar '('
. showArgs (showChar ',') args
. showChar ')'
{- *********************************************************
* *
* TyCon definitions for GHC.Types *
* *
********************************************************* -}
mkGhcTypesTyCon :: Addr# -> TyCon
{-# INLINE mkGhcTypesTyCon #-}
mkGhcTypesTyCon name = mkTyCon3# "ghc-prim"# "GHC.Types"# name
tcBool, tc'True, tc'False,
tcOrdering, tc'GT, tc'EQ, tc'LT,
tcChar, tcInt, tcWord, tcFloat, tcDouble, tcFun,
tcIO, tcSPEC, tcTyCon, tcModule,
tcCoercible, tcEq, tcList :: TyCon
tcBool = mkGhcTypesTyCon "Bool"# -- Bool is promotable
tc'True = mkGhcTypesTyCon "'True"#
tc'False = mkGhcTypesTyCon "'False"#
tcOrdering = mkGhcTypesTyCon "Ordering"# -- Ordering is promotable
tc'GT = mkGhcTypesTyCon "'GT"#
tc'EQ = mkGhcTypesTyCon "'EQ"#
tc'LT = mkGhcTypesTyCon "'LT"#
-- None of the rest are promotable (see TysWiredIn)
tcChar = mkGhcTypesTyCon "Char"#
tcInt = mkGhcTypesTyCon "Int"#
tcWord = mkGhcTypesTyCon "Word"#
tcFloat = mkGhcTypesTyCon "Float"#
tcDouble = mkGhcTypesTyCon "Double"#
tcSPEC = mkGhcTypesTyCon "SPEC"#
tcIO = mkGhcTypesTyCon "IO"#
tcTyCon = mkGhcTypesTyCon "TyCon"#
tcModule = mkGhcTypesTyCon "Module"#
tcCoercible = mkGhcTypesTyCon "Coercible"#
tcFun = mkGhcTypesTyCon "->"#
tcList = mkGhcTypesTyCon "[]"# -- Type rep for the list type constructor
tcEq = mkGhcTypesTyCon "~"# -- Type rep for the (~) type constructor
tcLiftedKind, tcUnliftedKind, tcOpenKind, tcBOX, tcConstraint, tcAnyK :: TyCon
tcLiftedKind = mkGhcTypesTyCon "*"#
tcUnliftedKind = mkGhcTypesTyCon "#"#
tcOpenKind = mkGhcTypesTyCon "#"#
tcBOX = mkGhcTypesTyCon "BOX"#
tcAnyK = mkGhcTypesTyCon "AnyK"#
tcConstraint = mkGhcTypesTyCon "Constraint"#
funTc :: TyCon
funTc = tcFun -- Legacy
{- *********************************************************
* *
* TyCon/TypeRep definitions for type literals *
* (Symbol and Nat) *
* *
********************************************************* -}
mkTypeLitTyCon :: String -> TyCon
mkTypeLitTyCon name = mkTyCon3 "base" "GHC.TypeLits" name
-- | Used to make `'Typeable' instance for things of kind Nat
typeNatTypeRep :: KnownNat a => Proxy# a -> TypeRep
typeNatTypeRep p = typeLitTypeRep (show (natVal' p))
-- | Used to make `'Typeable' instance for things of kind Symbol
typeSymbolTypeRep :: KnownSymbol a => Proxy# a -> TypeRep
typeSymbolTypeRep p = typeLitTypeRep (show (symbolVal' p))
-- | An internal function, to make representations for type literals.
typeLitTypeRep :: String -> TypeRep
typeLitTypeRep nm = mkTyConApp (mkTypeLitTyCon nm) []
|
AlexanderPankiv/ghc
|
libraries/base/Data/Typeable/Internal.hs
|
Haskell
|
bsd-3-clause
| 16,598
|
import Test.Cabal.Prelude hiding (cabal)
import qualified Test.Cabal.Prelude as P
-- See #4332, dep solving output is not deterministic
main = cabalTest . recordMode DoNotRecord $ do
fails $ cabal "new-build" []
cabal "new-build" ["--allow-older"]
fails $ cabal "new-build" ["--allow-older=baz,quux"]
cabal "new-build" ["--allow-older=base", "--allow-older=baz,quux"]
cabal "new-build" ["--allow-older=bar", "--allow-older=base,baz"
,"--allow-older=quux"]
fails $ cabal "new-build" ["--enable-tests"]
cabal "new-build" ["--enable-tests", "--allow-older"]
fails $ cabal "new-build" ["--enable-benchmarks"]
cabal "new-build" ["--enable-benchmarks", "--allow-older"]
fails $ cabal "new-build" ["--enable-benchmarks", "--enable-tests"]
cabal "new-build" ["--enable-benchmarks", "--enable-tests"
,"--allow-older"]
fails $ cabal "new-build" ["--allow-older=Foo:base"]
fails $ cabal "new-build" ["--allow-older=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
cabal "new-build" ["--allow-older=AllowOlder:base"]
cabal "new-build" ["--allow-older=AllowOlder:base"
,"--allow-older=Foo:base"]
cabal "new-build" ["--allow-older=AllowOlder:base"
,"--allow-older=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
where
cabal cmd args = P.cabal cmd ("--dry-run" : args)
|
mydaum/cabal
|
cabal-testsuite/PackageTests/AllowOlder/cabal.test.hs
|
Haskell
|
bsd-3-clause
| 1,476
|
main :: IO ()
main = asdf
|
MichielDerhaeg/stack
|
test/integration/tests/1659-skip-component/files/test/Spec.hs
|
Haskell
|
bsd-3-clause
| 26
|
-- (c) 2007 Andy Gill
module HpcFlags where
import System.Console.GetOpt
import qualified Data.Set as Set
import Data.Char
import Trace.Hpc.Tix
import Trace.Hpc.Mix
import System.Exit
import System.FilePath
data Flags = Flags
{ outputFile :: String
, includeMods :: Set.Set String
, excludeMods :: Set.Set String
, hpcDirs :: [String]
, srcDirs :: [String]
, destDir :: String
, perModule :: Bool
, decList :: Bool
, xmlOutput :: Bool
, funTotals :: Bool
, altHighlight :: Bool
, combineFun :: CombineFun -- tick-wise combine
, postFun :: PostFun --
, mergeModule :: MergeFun -- module-wise merge
, verbosity :: Verbosity
}
default_flags :: Flags
default_flags = Flags
{ outputFile = "-"
, includeMods = Set.empty
, excludeMods = Set.empty
, hpcDirs = [".hpc"]
, srcDirs = []
, destDir = "."
, perModule = False
, decList = False
, xmlOutput = False
, funTotals = False
, altHighlight = False
, combineFun = ADD
, postFun = ID
, mergeModule = INTERSECTION
, verbosity = Normal
}
data Verbosity = Silent | Normal | Verbose
deriving (Eq, Ord)
verbosityFromString :: String -> Verbosity
verbosityFromString "0" = Silent
verbosityFromString "1" = Normal
verbosityFromString "2" = Verbose
verbosityFromString v = error $ "unknown verbosity: " ++ v
-- We do this after reading flags, because the defaults
-- depends on if specific flags we used.
default_final_flags :: Flags -> Flags
default_final_flags flags = flags
{ srcDirs = if null (srcDirs flags)
then ["."]
else srcDirs flags
}
type FlagOptSeq = [OptDescr (Flags -> Flags)] -> [OptDescr (Flags -> Flags)]
noArg :: String -> String -> (Flags -> Flags) -> FlagOptSeq
noArg flag detail fn = (:) $ Option [] [flag] (NoArg $ fn) detail
anArg :: String -> String -> String -> (String -> Flags -> Flags) -> FlagOptSeq
anArg flag detail argtype fn = (:) $ Option [] [flag] (ReqArg fn argtype) detail
infoArg :: String -> FlagOptSeq
infoArg info = (:) $ Option [] [] (NoArg $ id) info
excludeOpt, includeOpt, hpcDirOpt, resetHpcDirsOpt, srcDirOpt,
destDirOpt, outputOpt, verbosityOpt,
perModuleOpt, decListOpt, xmlOutputOpt, funTotalsOpt,
altHighlightOpt, combineFunOpt, combineFunOptInfo, mapFunOpt,
mapFunOptInfo, unionModuleOpt :: FlagOptSeq
excludeOpt = anArg "exclude" "exclude MODULE and/or PACKAGE" "[PACKAGE:][MODULE]"
$ \ a f -> f { excludeMods = a `Set.insert` excludeMods f }
includeOpt = anArg "include" "include MODULE and/or PACKAGE" "[PACKAGE:][MODULE]"
$ \ a f -> f { includeMods = a `Set.insert` includeMods f }
hpcDirOpt = anArg "hpcdir" "append sub-directory that contains .mix files" "DIR"
(\ a f -> f { hpcDirs = hpcDirs f ++ [a] })
. infoArg "default .hpc [rarely used]"
resetHpcDirsOpt = noArg "reset-hpcdirs" "empty the list of hpcdir's"
(\ f -> f { hpcDirs = [] })
. infoArg "[rarely used]"
srcDirOpt = anArg "srcdir" "path to source directory of .hs files" "DIR"
(\ a f -> f { srcDirs = srcDirs f ++ [a] })
. infoArg "multi-use of srcdir possible"
destDirOpt = anArg "destdir" "path to write output to" "DIR"
$ \ a f -> f { destDir = a }
outputOpt = anArg "output" "output FILE" "FILE" $ \ a f -> f { outputFile = a }
verbosityOpt = anArg "verbosity" "verbosity level, 0-2" "[0-2]"
(\ a f -> f { verbosity = verbosityFromString a })
. infoArg "default 1"
-- markup
perModuleOpt = noArg "per-module" "show module level detail" $ \ f -> f { perModule = True }
decListOpt = noArg "decl-list" "show unused decls" $ \ f -> f { decList = True }
xmlOutputOpt = noArg "xml-output" "show output in XML" $ \ f -> f { xmlOutput = True }
funTotalsOpt = noArg "fun-entry-count" "show top-level function entry counts"
$ \ f -> f { funTotals = True }
altHighlightOpt
= noArg "highlight-covered" "highlight covered code, rather that code gaps"
$ \ f -> f { altHighlight = True }
combineFunOpt = anArg "function"
"combine .tix files with join function, default = ADD" "FUNCTION"
$ \ a f -> case reads (map toUpper a) of
[(c,"")] -> f { combineFun = c }
_ -> error $ "no such combine function : " ++ a
combineFunOptInfo = infoArg
$ "FUNCTION = " ++ foldr1 (\ a b -> a ++ " | " ++ b) (map fst foldFuns)
mapFunOpt = anArg "function"
"apply function to .tix files, default = ID" "FUNCTION"
$ \ a f -> case reads (map toUpper a) of
[(c,"")] -> f { postFun = c }
_ -> error $ "no such combine function : " ++ a
mapFunOptInfo = infoArg
$ "FUNCTION = " ++ foldr1 (\ a b -> a ++ " | " ++ b) (map fst postFuns)
unionModuleOpt = noArg "union"
"use the union of the module namespace (default is intersection)"
$ \ f -> f { mergeModule = UNION }
-------------------------------------------------------------------------------
readMixWithFlags :: Flags -> Either String TixModule -> IO Mix
readMixWithFlags flags modu = readMix [ dir </> hpcDir
| dir <- srcDirs flags
, hpcDir <- hpcDirs flags
] modu
-------------------------------------------------------------------------------
command_usage :: Plugin -> IO ()
command_usage plugin =
putStrLn $
"Usage: hpc " ++ (name plugin) ++ " " ++
(usage plugin) ++
"\n" ++ summary plugin ++ "\n" ++
if null (options plugin [])
then ""
else usageInfo "\n\nOptions:\n" (options plugin [])
hpcError :: Plugin -> String -> IO a
hpcError plugin msg = do
putStrLn $ "Error: " ++ msg
command_usage plugin
exitFailure
-------------------------------------------------------------------------------
data Plugin = Plugin { name :: String
, usage :: String
, options :: FlagOptSeq
, summary :: String
, implementation :: Flags -> [String] -> IO ()
, init_flags :: Flags
, final_flags :: Flags -> Flags
}
------------------------------------------------------------------------------
-- filterModules takes a list of candidate modules,
-- and
-- * excludes the excluded modules
-- * includes the rest if there are no explicity included modules
-- * otherwise, accepts just the included modules.
allowModule :: Flags -> String -> Bool
allowModule flags full_mod
| full_mod' `Set.member` excludeMods flags = False
| pkg_name `Set.member` excludeMods flags = False
| mod_name `Set.member` excludeMods flags = False
| Set.null (includeMods flags) = True
| full_mod' `Set.member` includeMods flags = True
| pkg_name `Set.member` includeMods flags = True
| mod_name `Set.member` includeMods flags = True
| otherwise = False
where
full_mod' = pkg_name ++ mod_name
-- pkg name always ends with '/', main
(pkg_name,mod_name) =
case span (/= '/') full_mod of
(p,'/':m) -> (p ++ ":",m)
(m,[]) -> (":",m)
_ -> error "impossible case in allowModule"
filterTix :: Flags -> Tix -> Tix
filterTix flags (Tix tixs) =
Tix $ filter (allowModule flags . tixModuleName) tixs
------------------------------------------------------------------------------
-- HpcCombine specifics
data CombineFun = ADD | DIFF | SUB
deriving (Eq,Show, Read, Enum)
theCombineFun :: CombineFun -> Integer -> Integer -> Integer
theCombineFun fn = case fn of
ADD -> \ l r -> l + r
SUB -> \ l r -> max 0 (l - r)
DIFF -> \ g b -> if g > 0 then 0 else min 1 b
foldFuns :: [ (String,CombineFun) ]
foldFuns = [ (show comb,comb)
| comb <- [ADD .. SUB]
]
data PostFun = ID | INV | ZERO
deriving (Eq,Show, Read, Enum)
thePostFun :: PostFun -> Integer -> Integer
thePostFun ID x = x
thePostFun INV 0 = 1
thePostFun INV _ = 0
thePostFun ZERO _ = 0
postFuns :: [(String, PostFun)]
postFuns = [ (show pos,pos)
| pos <- [ID .. ZERO]
]
data MergeFun = INTERSECTION | UNION
deriving (Eq,Show, Read, Enum)
theMergeFun :: (Ord a) => MergeFun -> Set.Set a -> Set.Set a -> Set.Set a
theMergeFun INTERSECTION = Set.intersection
theMergeFun UNION = Set.union
mergeFuns :: [(String, MergeFun)]
mergeFuns = [ (show pos,pos)
| pos <- [INTERSECTION,UNION]
]
|
wxwxwwxxx/ghc
|
utils/hpc/HpcFlags.hs
|
Haskell
|
bsd-3-clause
| 9,605
|
module ShouldFail where
-- !!! Testing duplicate type variables
type T a a = Either a a
|
urbanslug/ghc
|
testsuite/tests/module/mod23.hs
|
Haskell
|
bsd-3-clause
| 88
|
module Hesh ( sh, cmd, (|>), (/>), (!>), (&>), (</), (/>>), (!>>), (&>>), (<//), (.=)
, passThrough
) where
import Hesh.Process
import Hesh.Shell
|
jekor/hesh
|
lib/Hesh.hs
|
Haskell
|
mit
| 171
|
module Development.Duplo.Utilities where
import Control.Applicative ((<$>))
import Control.Lens.Operators
import Control.Monad (filterM, zipWithM)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Data.List (intercalate)
import Development.Duplo.Files (File (..), fileContent,
readFile)
import qualified Development.Duplo.Types.Config as TC
import Development.Shake (CmdOption (..))
import qualified Development.Shake as DS
import Development.Shake.FilePath ((</>))
import Prelude hiding (readFile)
import System.Console.ANSI (Color (..),
ColorIntensity (..),
ConsoleLayer (..), SGR (..),
setSGR)
import System.FilePath.Posix (dropTrailingPathSeparator,
joinPath, splitPath)
type CompiledContent = MaybeT DS.Action
type FileProcessor = [File] -> CompiledContent [File]
type StringProcessor = String -> CompiledContent String
-- | Construct a file pattern by providing a base directory and an
-- extension.
makePattern :: FilePath -> String -> FilePath
makePattern base extension = base ++ "//*" ++ extension
-- | Construct and return the given base directory and extension whose base
-- directory exists.
makeValidPattern :: FilePath -> String -> DS.Action [FilePath]
makeValidPattern base extension = do
exists <- DS.doesDirectoryExist base
let ptrn = makePattern base extension
return [ ptrn | exists ]
-- | Splice a list of base directories and their corresponding extensions
-- for a list of file patterns.
makeFilePatterns :: [FilePath] -> [String] -> DS.Action [DS.FilePattern]
makeFilePatterns bases exts = do
patternList <- zipWithM makeValidPattern bases exts
let conc = foldl1 (++)
-- Avoid infinite list.
let patterns = if null patternList
then return []
else conc patternList
return patterns
-- | Given a working directory and a list of patterns, expand all the
-- paths, in order.
getDirectoryFilesInOrder :: FilePath -> String -> [DS.FilePattern] -> DS.Action [FilePath]
getDirectoryFilesInOrder base extension patterns = do
-- Make sure we have a clean base.
let base' = dropTrailingPathSeparator base
-- We need to terminate the infinite list.
let listSize = length patterns
-- Make extension a list of itself.
let exts = replicate listSize extension
-- Turn file patterns into absolute patterns.
let absPatterns = fmap (base' </>) patterns
-- Make sure we get all valid file patterns for dynamic paths.
validPatterns <- makeFilePatterns absPatterns exts
-- Remove the prefix that was needed for file pattern construction.
let relPatterns = fmap (drop (length base' + 1)) validPatterns
-- We need to turn all elements into lists for each to be run independently.
let patternLists = fmap (replicate 1) relPatterns
-- Curry the function that gets the files given a list of paths.
let getFiles = getDirectoryFiles base'
-- Map over the list monadically to get the paths in order.
allFiles <- mapM getFiles patternLists
-- Re-package the contents into the list of paths that we've wanted.
let files = concat $ filter (not . null) allFiles
-- We're all set
return files
-- | Given the path to a compiler, parameters to the compiler, a list of
-- paths of to-be-compiled files, the output file path, and a processing
-- function, do the following:
--
-- * reads all the to-be-compiled files
-- * calls the processor with the list of files to perform any
-- pre-processing
-- * concatenates all files
-- * passes the concatenated string to the compiler
-- * returns the compiled content
compile :: TC.BuildConfig
-- The path to the compilation command
-> FilePath
-- The parameters passed to the compilation command
-> [String]
-- Files to be compiled
-> [FilePath]
-- The processing lambda: it is handed with a list of files.
-> FileProcessor
-- The postpcessing lambda: it is handed with all content
-- concatenated.
-> StringProcessor
-- The compiled content
-> CompiledContent String
compile config compiler params paths preprocess postprocess = do
mapM_ (lift . DS.putNormal . ("Including " ++)) paths
let cwd = config ^. TC.cwd
-- Construct files
files <- mapM (readFile cwd) paths
-- Pass to processor for specific manipulation
processed <- preprocess files
-- We only care about the content from this point on
let contents = fmap (^. fileContent) processed
-- Trailing newline is significant in case of empty Stylus
let concatenated = intercalate "\n" contents ++ "\n"
-- Send string over to post-processor in case of any manipulation before
-- handing off to the compiler. Add trailing newline for hygiene.
postprocessed <- (++ "\n") <$> postprocess concatenated
-- Paths should be available as environment variables
envOpt <- createStdEnv config
lift $ DS.putNormal $ "Compiling with: "
++ compiler
++ " "
++ unwords params
-- Pass it through the compiler
DS.Stdout compiled <-
lift $ DS.command [DS.Stdin postprocessed, envOpt] compiler params
-- The output
return compiled
-- | Given a list of static and a list of dynamic paths, return a list of
-- all paths, resolved to absolute paths.
expandPaths :: FilePath -> String -> [FilePath] -> [FilePath] -> DS.Action [FilePath]
expandPaths cwd extension staticPaths dynamicPaths = do
let expandStatic = map (\p -> cwd </> p ++ extension)
let expandDynamic = map (cwd </>)
staticExpanded <- filterM DS.doesFileExist $ expandStatic staticPaths
dynamicExpanded <- getDirectoryFilesInOrder cwd extension dynamicPaths
return $ staticExpanded ++ expandDynamic dynamicExpanded
-- | Given a list of paths, make sure all intermediary directories are
-- there.
createPathDirectories :: [FilePath] -> DS.Action ()
createPathDirectories paths = do
let mkdir dir = DS.command_ [] "mkdir" ["-p", dir]
existing <- filterM (fmap not . DS.doesDirectoryExist) paths
mapM_ mkdir existing
-- | Create all the directories within a path if they do not exist. Note
-- that the last segment is assumed to be the file and therefore not
-- created.
createIntermediaryDirectories :: String -> DS.Action ()
createIntermediaryDirectories path =
DS.command_ [] "mkdir" ["-p", dir]
where
dir = joinPath $ init $ splitPath path
-- | Return a list of dynamic paths given a list of dependency ID and
-- a function to expand one ID into a list of paths.
expandDeps :: [String] -> (String -> [FilePath]) -> [FilePath]
expandDeps deps expander = concat $ fmap expander deps
-- | Shake hangs when the path given to `getDirectoryFiles` doesn't exist.
-- This is a safe version of that.
getDirectoryFiles :: FilePath -> [DS.FilePattern] -> DS.Action [FilePath]
getDirectoryFiles base patterns = do
exist <- DS.doesDirectoryExist base
if exist
then DS.getDirectoryFiles base patterns
else return []
-- | Error printer: white text over red background.
errorPrintSetter :: IO ()
errorPrintSetter = setSGR [ SetColor Background Vivid Red
, SetColor Foreground Vivid White
]
-- | Header printer: blue text
headerPrintSetter :: IO ()
headerPrintSetter = setSGR [ SetColor Foreground Vivid Magenta ]
-- | Success printer: white text over green background
successPrintSetter :: IO ()
successPrintSetter = setSGR [ SetColor Background Vivid Green
, SetColor Foreground Vivid White
]
-- | Log a message with a provided print configuration setter.
logStatus :: IO () -> String -> IO ()
logStatus printSetter message = do
printSetter
putStr $ "\n>> " ++ message
setSGR [Reset]
putStrLn ""
-- | Put together common (i.e. standard) environment variables.
createStdEnv :: MonadIO m => TC.BuildConfig -> m CmdOption
createStdEnv config = do
let cwd = config ^. TC.cwd
let util = config ^. TC.utilPath
let nodejs = config ^. TC.nodejsPath
let misc = config ^. TC.miscPath
let target = config ^. TC.targetPath
let duplo = config ^. TC.duploPath
let test = config ^. TC.testPath
let app = config ^. TC.appPath
let deps = config ^. TC.depsPath
let dev = config ^. TC.devPath
DS.addEnv [ ("DUPLO_UTIL", util)
, ("DUPLO_NODEJS", nodejs)
, ("DUPLO_CWD", cwd)
, ("DUPLO_MISC", misc)
, ("DUPLO_TARGET", target)
, ("DUPLO_PATH", duplo)
, ("DUPLO_TEST", test)
, ("DUPLO_APP", app)
, ("DUPLO_DEPS", deps)
, ("DUPLO_DEV", dev)
]
|
pixbi/duplo
|
src/Development/Duplo/Utilities.hs
|
Haskell
|
mit
| 9,270
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Math.Vector4(
Vector4(..)
, HasX(..)
, HasY(..)
, HasZ(..)
, HasW(..)
, vector4Context
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Control.Lens
import Data.Monoid
import Foreign
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Math.Defs
import Graphics.Urho3D.Math.Internal.Vector4
import Graphics.Urho3D.Monad
import Text.RawString.QQ
C.context (C.cppCtx <> vector4Cntx)
C.include "<Urho3D/Math/Vector4.h>"
C.using "namespace Urho3D"
vector4Context :: C.Context
vector4Context = vector4Cntx
C.verbatim [r|
template <class T>
class Traits
{
public:
struct AlignmentFinder
{
char a;
T b;
};
enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)};
};
|]
instance Storable Vector4 where
sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(Vector4) } |]
alignment _ = fromIntegral $ [C.pure| int { (int)Traits<Vector4>::AlignmentOf } |]
peek ptr = do
vx <- realToFrac <$> [C.exp| float { $(Vector4* ptr)->x_ } |]
vy <- realToFrac <$> [C.exp| float { $(Vector4* ptr)->y_ } |]
vz <- realToFrac <$> [C.exp| float { $(Vector4* ptr)->z_ } |]
vw <- realToFrac <$> [C.exp| float { $(Vector4* ptr)->w_ } |]
return $ Vector4 vx vy vz vw
poke ptr (Vector4 vx vy vz vw) = [C.block| void {
$(Vector4* ptr)->x_ = $(float vx');
$(Vector4* ptr)->y_ = $(float vy');
$(Vector4* ptr)->z_ = $(float vz');
$(Vector4* ptr)->w_ = $(float vw');
} |]
where
vx' = realToFrac vx
vy' = realToFrac vy
vz' = realToFrac vz
vw' = realToFrac vw
instance Num Vector4 where
a + b = Vector4 (a^.x + b^.x) (a^.y + b^.y) (a^.z + b^.z) (a^.w + b^.w)
a - b = Vector4 (a^.x - b^.x) (a^.y - b^.y) (a^.z - b^.z) (a^.w - b^.w)
a * b = Vector4 (a^.x * b^.x) (a^.y * b^.y) (a^.z * b^.z) (a^.w * b^.w)
abs a = Vector4 (abs $ a^.x) (abs $ a^.y) (abs $ a^.z) (abs $ a^.w)
signum a = Vector4 (signum $ a^.x) (signum $ a^.y) (signum $ a^.z) (signum $ a^.w)
fromInteger i = Vector4 (fromIntegral i) (fromIntegral i) (fromIntegral i) (fromIntegral i)
instance Fractional Vector4 where
a / b = Vector4 (a^.x / b^.x) (a^.y / b^.y) (a^.z / b^.z) (a^.w / b^.w)
fromRational v = Vector4 (fromRational v) (fromRational v) (fromRational v) (fromRational v)
instance Creatable (Ptr Vector4) where
type CreationOptions (Ptr Vector4) = Vector4
newObject = liftIO . new
deleteObject = liftIO . free
instance UrhoRandom Vector4 where
random = Vector4 <$> random <*> random <*> random <*> random
randomUp maxv = Vector4
<$> randomUp (maxv^.x)
<*> randomUp (maxv^.y)
<*> randomUp (maxv^.z)
<*> randomUp (maxv^.w)
randomRange minv maxv = Vector4
<$> randomRange (minv^.x) (maxv^.x)
<*> randomRange (minv^.y) (maxv^.y)
<*> randomRange (minv^.z) (maxv^.z)
<*> randomRange (minv^.w) (maxv^.w)
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Math/Vector4.hs
|
Haskell
|
mit
| 2,945
|
{-# LANGUAGE BangPatterns #-}
module Language.HAsm.Types (
module Data.Word,
module Data.Int,
module Language.HAsm.X86.CPU,
-- routines:
safeHead, int, toInt32,
immToW, immToB, isWord8,
HasmStatement(..), Directive(..),
ParseResult, HasmStmtWithPos, SrcPos(..)
) where
import Data.Word
import Data.Int
import Language.HAsm.X86.CPU
int :: (Integral a, Num b) => a -> b
int = fromIntegral
toInt32 :: Integral a => a -> Int32
toInt32 = fromIntegral
isWord8 :: ImmValue -> Bool
isWord8 (ImmB imm) = True
isWord8 (ImmW imm) = imm < 0x100
isWord8 (ImmL imm) = imm < 0x100
immToW :: ImmValue -> Either String ImmValue
immToW (ImmW imm) = Right (ImmW imm)
immToW (ImmB imm) = Right (ImmW (int imm))
immToW (ImmL imm) | imm < 0x10000 = Right (ImmW (int imm))
immToW imm = Left $ "Value " ++ show imm ++ " is too large for a word"
immToB :: ImmValue -> Either String ImmValue
immToB (ImmB imm) = Right (ImmB imm)
immToB (ImmW imm) | imm < 0x100 = Right (ImmB (int imm))
immToB (ImmL imm) | imm < 0x100 = Right (ImmB (int imm))
immToB imm = Left $ "Value " ++ show imm ++ " is too large for a word"
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (s:_) = Just s
data HasmStatement
= HasmStLabel String
| HasmStDirective Directive
| HasmStInstr [OpPrefix] Operation
deriving (Show, Read, Eq)
data SrcPos = SrcPos String !Int !Int deriving (Eq, Ord)
instance Show SrcPos where
show (SrcPos src line col) = src ++ ":" ++ show line ++ ":" ++ show col
type HasmStmtWithPos = (HasmStatement, SrcPos)
type ParseResult = [HasmStmtWithPos]
data Directive
-- location control directives:
= DirBAlign Int Int Int -- Align by Int bytes with pattern Int(=0) no more than Int(=INT_MAX)
| DirSection String Int String -- section with name:String and opt. subsection index Int(=0), opt. flags:String
| DirFile String -- set filename
| DirInclude String -- include file
| DirSkip Int Word8 -- skip n:Int bytes filling with value:Word8(=0); synonym: .space
| DirOrg Int
-- symbol control:
| DirEqu Symbol Int -- set value of the symbol; synonym: .set
| DirEquiv Symbol Int -- as .equ, but signal an error if Symbol is already defined
| DirEqv Symbol Int -- lazy assignment
| DirSize Symbol Int -- set symbol size
| DirType Symbol String -- set symbol type
-- symbol visibility:
| DirExtern [Symbol]
| DirGlobal [Symbol] -- .global/.globl
| DirHidden [Symbol]
| DirLocal [Symbol]
| DirWeak [Symbol]
-- data directives:
| DirBytes [Word8]
| DirShort [Word16] -- .hword/.short/.octa
| DirWord [Word32] -- .word/.long
| DirAscii [[Word8]] -- zero or more ASCII strings
| DirAsciz [[Word8]] -- zero or more ASCII strings separated by \0, synonym: .string
| DirDouble [Double] -- zero or more flonums
| DirFloat [Float] -- synonyms: .single
| DirFill Int Int Int -- repeat times:Int pattern of size:Int(=1) (if >8 than 8) of value:Int(=0)
| DirComm Symbol Int Int -- make a BSS symbol:Symbol with length:Int and alignment:Int(=1)
| DirCFI CFIInfo
-- def directives:
| DirDef Symbol -- start defining debug info for Symbol
| DirDim
| DirEndef
-- conditional assembly directives:
| DirIf Int
| DirIfdef Symbol
| DirIfblank String
| DirIfcmp String String -- .ifc/.ifeqs
| DirIfeq Int Int
| DirIfge Int Int
| DirIfgt Int Int
| DirElse
| DirElseIf
| DirEndif
-- listing directives:
| DirErr
| DirError String
| DirEnd -- marks end of the assembly file, does not process anything from this point
| DirEject -- generate page break on assembly listings
deriving (Show, Read, Eq)
{-
- Call Frame Info directives
-}
data CFIInfo
= CFISections [String]
| CFIStartproc
| CFIEndproc
| CFIPersonality
| CFILsda
| CFIDefCfa
| CFIDefCfaReg Int
| CFIDefCfaOffset Int
| CFIAdjCfaOffset Int
| CFIOffset Int Int
| CFIRelOffset
| CFIRegister Int Int
| CFIRestore Int
| CFIUndefined Int
| CFISameValue Int
| CFIRememberState
| CFIRetColumn Int
| CFISignalFrame
| CFIEscape
deriving (Show, Read, Eq)
|
EarlGray/hasm
|
src/Language/HAsm/Types.hs
|
Haskell
|
mit
| 4,072
|
-- Find the odd int
-- http://www.codewars.com/kata/54da5a58ea159efa38000836/
module Codewars.Kata.FindOdd where
import Data.List (sort, group)
findOdd :: [Int] -> Int
findOdd = head . head . filter (odd . length) . group . sort
|
gafiatulin/codewars
|
src/6 kyu/FindOdd.hs
|
Haskell
|
mit
| 232
|
{-# LANGUAGE
OverloadedStrings
#-}
{-|
Module : HSat.Problem.Instances.CNF.Parser.Internal
Description : Helper functions for parsing CNF files
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
Exports a set of internally used functions to parse parts of a 'CNF' file
-}
module HSat.Problem.Instances.CNF.Parser.Internal (
-- * Functions
parseComment, -- :: Parser ()
parseComments, -- :: Parser ()
parseNonZeroInteger, -- :: Parser Integer
parseProblemLine, -- :: Parser CNFBuildErr
parseClause, -- :: CNFBuildErr -> Parser CNFBuildErr
parseClauses -- :: CNFBuildErr -> Parser CNFBuildErr
) where
import Control.Monad (void)
import Control.Monad.Catch
import qualified Data.Attoparsec.Internal.Types as T
import Data.Attoparsec.Text as P
import HSat.Problem.Instances.CNF.Builder
instance MonadThrow (T.Parser i) where
throwM e = fail (show e)
{-|
Parser to parse many comments. No information is retained about the comments
-}
parseComments :: Parser ()
parseComments = void (skipMany (parseComment >> endOfLine)) <?> "parseComments"
{-|
Parser to parse a comment. No information is retained about the comment.
-}
parseComment :: Parser ()
parseComment =
many' space' >> option () (
char 'c' >> skipWhile (not . isEndOfLine)) <?> "parseComment"
{-|
Parser to parse a problem line in a CNF file. Builds a 'CNFBuildErr' from it
-}
parseProblemLine :: (MonadThrow m) => Parser (m CNFBuilder)
parseProblemLine = do
vars <-
skipMany space' >> char 'p' >> skipMany1 space' >>
string "cnf" >> skipMany1 space' >> P.signed P.decimal
clauses <- skipMany1 space' >> P.signed P.decimal
cnfBuilder vars clauses <$ skipMany space'
<?> "parseProblemLine"
--Parsers spaces and tabs
space' :: Parser ()
space' = void (choice [char '\t', char ' ']) <?> "space'"
--Parses strictly positive numbers
positive :: Parser Integer
positive = (
do
x <- choices "123456789"
xs <- many' $ choices "0123456789"
return . read $ (x:xs)
) <?> "positive"
--A helper function. When given a string, will parse any of the characters
choices :: String -> Parser Char
choices xs = choice (fmap char xs) <?> "choices"
{-|
Parser to parse a 'Clause', adding the 'HSat.Problem.BSP.Common.Clause' to the 'CNFBuildErr' argument
-}
parseClause :: (MonadThrow m) => m CNFBuilder -> Parser (m CNFBuilder)
parseClause b = choice [
--Parse the '0' at the end of the clause
(b >>= finishClause) <$ (many' space' >> char '0'),
--Parse a non zero integer, then continue
(many' space' >> (\i -> b >>= addLiteral i) <$> parseNonZeroInteger) >>= parseClause,
--Parse the end of the line, and any comments, then continue parsing the clause
many' space' >> endOfLine >> parseComments >> parseClause b
] <?> "parseClause"
{-|
Parser to Parse a set of 'HSat.Problem.BSP.Common.Clauses', adding them to the 'CNFBuildErr' argument
-}
parseClauses :: (MonadThrow m) => m CNFBuilder -> Parser (m CNFBuilder)
parseClauses cnf =
parseComments >> choice [
parseClause cnf >>= parseClauses,
cnf <$ parseComments
] <?> "parseClauses"
{-|
Parser to parse an 'Integer' that is non-zero
-}
parseNonZeroInteger :: Parser Integer
parseNonZeroInteger = option id (negate <$ char '-') <*> positive <?> "parseNonZeroInteger"
|
aburnett88/HSat
|
src/HSat/Problem/Instances/CNF/Parser/Internal.hs
|
Haskell
|
mit
| 3,495
|
{-# LANGUAGE LambdaCase #-}
module Main(main) where
import Parse
import Write
main :: IO ()
main =
do specHtml <- getContents
parseSpec specHtml >>= \case
Nothing -> error "Unable to extract spec from html"
Just spec -> writeSpecToFiles "SpirV" spec
|
expipiplus1/spir-v
|
generate/src/Main.hs
|
Haskell
|
mit
| 274
|
module ProjectEuler.Problem106
( problem
) where
import Control.Monad
import Data.Monoid
import Petbox
import qualified Data.List.Ordered as LOrdered
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 106 Solved result
{-
Looks like we should expect this to be a difficult one.
But I blame the problem description of not doing a good job of explaining what's going on.
We first need to figure out where do these numbers come from:
- n = 4, 1 out of 25 subsets pairs needs to be tested.
- n = 7, 70 out of 966 subset pairs needs to be tested.
- n = 12, <?> out of 261625 subset pairs needs to be tested.
Now that "261625" looks like a distinct number that we can search.
Indeed, a OEIS search on "25" "966" "261625" yields: https://oeis.org/A000392.
Quote:
> Let P(A) be the power set of an n-element set A.
> Then a(n+1) = the number of pairs of elements {x,y} of P(A)
> for which x and y are disjoint and for which x is not a subset of y
> and y is not a subset of x. Wieder calls these "disjoint strict 2-combinations".
Sounds making perfect sense in our case.
Also, no need of checking the second property suggests
that the comparison should only be performed between sum of subsets
of same # of elements.
For n = 4, assume the set is {A,B,C,D} with A < B < C < D,
the pairs are:
LHS | RHS(s)
{A} | {B,C,D} {B,C} {B,D} {C,D} {B} {C} {D} (# = 7)
{A,B} | {C,D} {C} {D} (# = 3)
{A,C} | {B,D} {B} {D} (# = 3)
{A,D} | {B,C} {B} {C} (# = 3)
{A,B,C} | {D} (# = 1)
{A,B,D} | {C} (# = 1)
{A,C,D} | {B} (# = 1)
{B} | {C,D} {C} {D} (# = 3)
{B,C} | {D} (# = 1)
{B,D} | {C} (# = 1)
{C} | {D} (# = 1)
This does sum up to 25.
So far we know:
- For any n, we only need to check for subsets of the same size,
because from property 2, we can assume this is always true.
- Subsets of size 1 can be ignored, knowing all elements are unique.
- Subset sizes can only be <= floor(n/2),
so we want to do this for subset size m=2,3,4,...,floor(n/2)
for each of those pairs, if we can prove the inequality from
sequence of elements (e.g. using A < B < C < D for n = 4),
we don't need to check it.
Taking this into account, there's only 3 pairs remaining:
- {A,B}, {C,D}: for this one, we know A+B < C+D, no need of checking
(or, in other words, this is because A < C and B < D)
- {A,C}, {B,D}: for this one, A<B, C<D, no need of checking
- {A,D}, {B,C}: looks like this is the remaining one.
Notice the pattern: if we can pair all elements (taking from two sets)
in both set using the inequation A < B < C < D, then the comparison
is not needed.
Well, we need to investigate n > 4 and see if we can find a pattern.
More precisely, let the full set contain n elements, and
let's assume we are pairing two disjoint set of the same size m,
we want to investigate the number of pairs that we cannot draw a conclusion
by simply looking at `A < B < C < ... < ...`.
Experiment:
- Given 0 .. n, create pairs of disjoint sets of the same size m
- see if we can avoid equality test by just discharging number pairs (a,b),
whenever a < b.
- print out / count remainings
So, turns out testing on 12 is fast enough to solve the problem.
-}
pickSomeInOrder :: Int -> [a] -> [[a]]
pickSomeInOrder 0 _ = [[]]
pickSomeInOrder n xs = do
(y,ys) <- pickInOrder xs
(y:) <$> pickSomeInOrder (n-1) ys
{-
generate pairs of disjoint sets,
from [1..n], with each set has m elements.
-}
disjointPairs :: Int -> Int -> [] ([Int], [Int])
disjointPairs n m = do
l <- sets
r <- sets
guard $ l < r
guard $ null (LOrdered.isect l r)
pure (l,r)
where
sets = pickSomeInOrder m [1..n]
{-
given two disjoint subset (sorted),
see if we can check for its inequality
by pairing all elements (from both sets)
using inequality.
-}
_alreadyInequal :: ([Int], [Int]) -> Bool
_alreadyInequal ([],[]) = True
_alreadyInequal (xs,ys) = or $ do
(x,xs') <- pick xs
(y,ys') <- pick ys
guard $ x < y
pure $ _alreadyInequal (xs',ys')
{-
`needEqualTest 12` also computes the final answer.
slow, as this is brute force.
-}
_needEqualTest :: Int -> Int
_needEqualTest n = sum $ do
m <- [2..quot n 2]
let count = filter (not . _alreadyInequal) $ disjointPairs n m
pure (length count)
{-
needEqualTest <$> [4..10]
> 1,2,3,6,11,23,47,106,235
oeis gives: https://oeis.org/A304011
-}
result :: Int
result = getSum $ foldMap countPairs [2..quot n 2]
where
n = 12
countPairs i = Sum $ choose n (i+i) * choose (i+i-1) (i-2)
|
Javran/Project-Euler
|
src/ProjectEuler/Problem106.hs
|
Haskell
|
mit
| 4,629
|
{-# LANGUAGE StandaloneDeriving #-}
module GestionEvents
( space
, parseEvents
, keyDown
, firing
, rebooting
) where
import Prelude hiding ((.), id, null, filter, until)
import Control.Wire hiding (empty)
import Control.Wire.Unsafe.Event as Event
import FRP.Netwire hiding (empty)
import Data.Monoid (Monoid)
import Data.Set (Set, empty, insert, delete, null, filter)
import qualified Data.List as List
import qualified Graphics.UI.SDL as SDL
import DataStructures
----------------------------------------SDL Events--------------------------------------------
space :: SDL.Keysym
space = SDL.Keysym SDL.SDLK_s [SDL.KeyModNone] ' '
--Code from ocharles
parseEvents :: Set SDL.Keysym -> IO (Set SDL.Keysym)
parseEvents keysDown = do
event <- SDL.pollEvent
case event of
SDL.NoEvent -> return keysDown
SDL.KeyDown k -> parseEvents (insert k keysDown)
SDL.KeyUp k -> parseEvents (delete k keysDown)
_ -> parseEvents keysDown
--Code from ocharles
keyDown :: SDL.SDLKey -> Set SDL.Keysym -> Bool
keyDown k = not . null . filter ((== k) . SDL.symKey)
------------------------------------Netwire 5 Events------------------------------------------
instance (Eq a) => Eq (Event a) where
(Event a) == (Event b) = a == b
(Event a) == Event.NoEvent = False
Event.NoEvent == (Event a) = False
Event.NoEvent == Event.NoEvent = True
firing :: Event SDL.Keysym
firing = Event (space)
rebooting :: Event String
rebooting = Event ("reboot!")
deriving instance Ord SDL.Keysym
|
hardkey/Netwire5-shmup-prototype
|
src/GestionEvents.hs
|
Haskell
|
mit
| 1,532
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module PostgREST.DbStructure (
getDbStructure
, accessibleTables
, doesProcExist
, doesProcReturnJWT
) where
import qualified Hasql.Decoders as HD
import qualified Hasql.Encoders as HE
import qualified Hasql.Query as H
import Control.Applicative
import Control.Monad (join, replicateM)
import Data.Functor.Contravariant (contramap)
import Data.List (elemIndex, find, sort,
subsequences, transpose)
import Data.Maybe (fromJust, fromMaybe, isJust,
listToMaybe, mapMaybe)
import Data.Monoid
import Data.Text (Text, split)
import qualified Hasql.Session as H
import PostgREST.Types
import Text.InterpolatedString.Perl6 (q)
import Data.Int (Int32)
import GHC.Exts (groupWith)
import Prelude
getDbStructure :: Schema -> H.Session DbStructure
getDbStructure schema = do
tabs <- H.query () allTables
cols <- H.query () $ allColumns tabs
syns <- H.query () $ allSynonyms cols
rels <- H.query () $ allRelations tabs cols
keys <- H.query () $ allPrimaryKeys tabs
let rels' = (addManyToManyRelations . raiseRelations schema syns . addParentRelations . addSynonymousRelations syns) rels
cols' = addForeignKeys rels' cols
keys' = synonymousPrimaryKeys syns keys
return DbStructure {
dbTables = tabs
, dbColumns = cols'
, dbRelations = rels'
, dbPrimaryKeys = keys'
}
encodeQi :: HE.Params QualifiedIdentifier
encodeQi =
contramap qiSchema (HE.value HE.text) <>
contramap qiName (HE.value HE.text)
decodeTables :: HD.Result [Table]
decodeTables =
HD.rowsList tblRow
where
tblRow = Table <$> HD.value HD.text <*> HD.value HD.text
<*> HD.value HD.bool
decodeColumns :: [Table] -> HD.Result [Column]
decodeColumns tables =
mapMaybe (columnFromRow tables) <$> HD.rowsList colRow
where
colRow =
(,,,,,,,,,,)
<$> HD.value HD.text <*> HD.value HD.text
<*> HD.value HD.text <*> HD.value HD.int4
<*> HD.value HD.bool <*> HD.value HD.text
<*> HD.value HD.bool
<*> HD.nullableValue HD.int4
<*> HD.nullableValue HD.int4
<*> HD.nullableValue HD.text
<*> HD.nullableValue HD.text
decodeRelations :: [Table] -> [Column] -> HD.Result [Relation]
decodeRelations tables cols =
mapMaybe (relationFromRow tables cols) <$> HD.rowsList relRow
where
relRow = (,,,,,)
<$> HD.value HD.text
<*> HD.value HD.text
<*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text)))
<*> HD.value HD.text
<*> HD.value HD.text
<*> HD.value (HD.array (HD.arrayDimension replicateM (HD.arrayValue HD.text)))
decodePks :: [Table] -> HD.Result [PrimaryKey]
decodePks tables =
mapMaybe (pkFromRow tables) <$> HD.rowsList pkRow
where
pkRow = (,,) <$> HD.value HD.text <*> HD.value HD.text <*> HD.value HD.text
decodeSynonyms :: [Column] -> HD.Result [(Column,Column)]
decodeSynonyms cols =
mapMaybe (synonymFromRow cols) <$> HD.rowsList synRow
where
synRow = (,,,,,)
<$> HD.value HD.text <*> HD.value HD.text
<*> HD.value HD.text <*> HD.value HD.text
<*> HD.value HD.text <*> HD.value HD.text
doesProcExist :: H.Query QualifiedIdentifier Bool
doesProcExist =
H.statement sql encodeQi (HD.singleRow (HD.value HD.bool)) True
where
sql = [q| SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p
ON pronamespace = n.oid
WHERE nspname = $1
AND proname = $2
) |]
doesProcReturnJWT :: H.Query QualifiedIdentifier Bool
doesProcReturnJWT =
H.statement sql encodeQi (HD.singleRow (HD.value HD.bool)) True
where
sql = [q| SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p
ON pronamespace = n.oid
WHERE nspname = $1
AND proname = $2
AND pg_catalog.pg_get_function_result(p.oid) like '%jwt_claims'
) |]
accessibleTables :: H.Query Schema [Table]
accessibleTables =
H.statement sql (HE.value HE.text) decodeTables True
where
sql = [q|
select
n.nspname as table_schema,
relname as table_name,
c.relkind = 'r' or (c.relkind IN ('v', 'f')) and (pg_relation_is_updatable(c.oid::regclass, false) & 8) = 8
or (exists (
select 1
from pg_trigger
where pg_trigger.tgrelid = c.oid and (pg_trigger.tgtype::integer & 69) = 69)
) as insertable
from
pg_class c
join pg_namespace n on n.oid = c.relnamespace
where
c.relkind in ('v', 'r', 'm')
and n.nspname = $1
and (
pg_has_role(c.relowner, 'USAGE'::text)
or has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text)
or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text)
)
order by relname |]
synonymousColumns :: [(Column,Column)] -> [Column] -> [[Column]]
synonymousColumns allSyns cols = synCols'
where
syns = sort $ filter ((== colTable (head cols)) . colTable . fst) allSyns
synCols = transpose $ map (\c -> map snd $ filter ((== c) . fst) syns) cols
synCols' = (filter sameTable . filter matchLength) synCols
matchLength cs = length cols == length cs
sameTable (c:cs) = all (\cc -> colTable c == colTable cc) (c:cs)
sameTable [] = False
addForeignKeys :: [Relation] -> [Column] -> [Column]
addForeignKeys rels = map addFk
where
addFk col = col { colFK = fk col }
fk col = join $ relToFk col <$> find (lookupFn col) rels
lookupFn :: Column -> Relation -> Bool
lookupFn c Relation{relColumns=cs, relType=rty} = c `elem` cs && rty==Child
-- lookupFn _ _ = False
relToFk col Relation{relColumns=cols, relFColumns=colsF} = ForeignKey <$> colF
where
pos = elemIndex col cols
colF = (colsF !!) <$> pos
addSynonymousRelations :: [(Column,Column)] -> [Relation] -> [Relation]
addSynonymousRelations _ [] = []
addSynonymousRelations syns (rel:rels) = rel : synRelsP ++ synRelsF ++ addSynonymousRelations syns rels
where
synRelsP = synRels (relColumns rel) (\t cs -> rel{relTable=t,relColumns=cs})
synRelsF = synRels (relFColumns rel) (\t cs -> rel{relFTable=t,relFColumns=cs})
synRels cols mapFn = map (\cs -> mapFn (colTable $ head cs) cs) $ synonymousColumns syns cols
addParentRelations :: [Relation] -> [Relation]
addParentRelations [] = []
addParentRelations (rel@(Relation t c ft fc _ _ _ _):rels) = Relation ft fc t c Parent Nothing Nothing Nothing : rel : addParentRelations rels
addManyToManyRelations :: [Relation] -> [Relation]
addManyToManyRelations rels = rels ++ addMirrorRelation (mapMaybe link2Relation links)
where
links = join $ map (combinations 2) $ filter (not . null) $ groupWith groupFn $ filter ( (==Child). relType) rels
groupFn :: Relation -> Text
groupFn Relation{relTable=Table{tableSchema=s, tableName=t}} = s<>"_"<>t
combinations k ns = filter ((k==).length) (subsequences ns)
addMirrorRelation [] = []
addMirrorRelation (rel@(Relation t c ft fc _ lt lc1 lc2):rels') = Relation ft fc t c Many lt lc2 lc1 : rel : addMirrorRelation rels'
link2Relation [
Relation{relTable=lt, relColumns=lc1, relFTable=t, relFColumns=c},
Relation{ relColumns=lc2, relFTable=ft, relFColumns=fc}
]
| lc1 /= lc2 && length lc1 == 1 && length lc2 == 1 = Just $ Relation t c ft fc Many (Just lt) (Just lc1) (Just lc2)
| otherwise = Nothing
link2Relation _ = Nothing
raiseRelations :: Schema -> [(Column,Column)] -> [Relation] -> [Relation]
raiseRelations schema syns = map raiseRel
where
raiseRel rel
| tableSchema table == schema = rel
| isJust newCols = rel{relFTable=fromJust newTable,relFColumns=fromJust newCols}
| otherwise = rel
where
cols = relFColumns rel
table = relFTable rel
newCols = listToMaybe $ filter ((== schema) . tableSchema . colTable . head) (synonymousColumns syns cols)
newTable = (colTable . head) <$> newCols
synonymousPrimaryKeys :: [(Column,Column)] -> [PrimaryKey] -> [PrimaryKey]
synonymousPrimaryKeys _ [] = []
synonymousPrimaryKeys syns (key:keys) = key : newKeys ++ synonymousPrimaryKeys syns keys
where
keySyns = filter ((\c -> colTable c == pkTable key && colName c == pkName key) . fst) syns
newKeys = map ((\c -> PrimaryKey{pkTable=colTable c,pkName=colName c}) . snd) keySyns
allTables :: H.Query () [Table]
allTables =
H.statement sql HE.unit decodeTables True
where
sql = [q|
SELECT
n.nspname AS table_schema,
c.relname AS table_name,
c.relkind = 'r' OR (c.relkind IN ('v','f'))
AND (pg_relation_is_updatable(c.oid::regclass, FALSE) & 8) = 8
OR (EXISTS
( SELECT 1
FROM pg_trigger
WHERE pg_trigger.tgrelid = c.oid
AND (pg_trigger.tgtype::integer & 69) = 69) ) AS insertable
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('v','r','m')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
GROUP BY table_schema, table_name, insertable
ORDER BY table_schema, table_name |]
allColumns :: [Table] -> H.Query () [Column]
allColumns tabs =
H.statement sql HE.unit (decodeColumns tabs) True
where
sql = [q|
SELECT DISTINCT
info.table_schema AS schema,
info.table_name AS table_name,
info.column_name AS name,
info.ordinal_position AS position,
info.is_nullable::boolean AS nullable,
info.data_type AS col_type,
info.is_updatable::boolean AS updatable,
info.character_maximum_length AS max_len,
info.numeric_precision AS precision,
info.column_default AS default_value,
array_to_string(enum_info.vals, ',') AS enum
FROM (
/*
-- CTE based on information_schema.columns to remove the owner filter
*/
WITH columns AS (
SELECT current_database()::information_schema.sql_identifier AS table_catalog,
nc.nspname::information_schema.sql_identifier AS table_schema,
c.relname::information_schema.sql_identifier AS table_name,
a.attname::information_schema.sql_identifier AS column_name,
a.attnum::information_schema.cardinal_number AS ordinal_position,
pg_get_expr(ad.adbin, ad.adrelid)::information_schema.character_data AS column_default,
CASE
WHEN a.attnotnull OR t.typtype = 'd'::"char" AND t.typnotnull THEN 'NO'::text
ELSE 'YES'::text
END::information_schema.yes_or_no AS is_nullable,
CASE
WHEN t.typtype = 'd'::"char" THEN
CASE
WHEN bt.typelem <> 0::oid AND bt.typlen = (-1) THEN 'ARRAY'::text
WHEN nbt.nspname = 'pg_catalog'::name THEN format_type(t.typbasetype, NULL::integer)
ELSE 'USER-DEFINED'::text
END
ELSE
CASE
WHEN t.typelem <> 0::oid AND t.typlen = (-1) THEN 'ARRAY'::text
WHEN nt.nspname = 'pg_catalog'::name THEN format_type(a.atttypid, NULL::integer)
ELSE 'USER-DEFINED'::text
END
END::information_schema.character_data AS data_type,
information_schema._pg_char_max_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_maximum_length,
information_schema._pg_char_octet_length(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS character_octet_length,
information_schema._pg_numeric_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision,
information_schema._pg_numeric_precision_radix(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_precision_radix,
information_schema._pg_numeric_scale(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS numeric_scale,
information_schema._pg_datetime_precision(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.cardinal_number AS datetime_precision,
information_schema._pg_interval_type(information_schema._pg_truetypid(a.*, t.*), information_schema._pg_truetypmod(a.*, t.*))::information_schema.character_data AS interval_type,
NULL::integer::information_schema.cardinal_number AS interval_precision,
NULL::character varying::information_schema.sql_identifier AS character_set_catalog,
NULL::character varying::information_schema.sql_identifier AS character_set_schema,
NULL::character varying::information_schema.sql_identifier AS character_set_name,
CASE
WHEN nco.nspname IS NOT NULL THEN current_database()
ELSE NULL::name
END::information_schema.sql_identifier AS collation_catalog,
nco.nspname::information_schema.sql_identifier AS collation_schema,
co.collname::information_schema.sql_identifier AS collation_name,
CASE
WHEN t.typtype = 'd'::"char" THEN current_database()
ELSE NULL::name
END::information_schema.sql_identifier AS domain_catalog,
CASE
WHEN t.typtype = 'd'::"char" THEN nt.nspname
ELSE NULL::name
END::information_schema.sql_identifier AS domain_schema,
CASE
WHEN t.typtype = 'd'::"char" THEN t.typname
ELSE NULL::name
END::information_schema.sql_identifier AS domain_name,
current_database()::information_schema.sql_identifier AS udt_catalog,
COALESCE(nbt.nspname, nt.nspname)::information_schema.sql_identifier AS udt_schema,
COALESCE(bt.typname, t.typname)::information_schema.sql_identifier AS udt_name,
NULL::character varying::information_schema.sql_identifier AS scope_catalog,
NULL::character varying::information_schema.sql_identifier AS scope_schema,
NULL::character varying::information_schema.sql_identifier AS scope_name,
NULL::integer::information_schema.cardinal_number AS maximum_cardinality,
a.attnum::information_schema.sql_identifier AS dtd_identifier,
'NO'::character varying::information_schema.yes_or_no AS is_self_referencing,
'NO'::character varying::information_schema.yes_or_no AS is_identity,
NULL::character varying::information_schema.character_data AS identity_generation,
NULL::character varying::information_schema.character_data AS identity_start,
NULL::character varying::information_schema.character_data AS identity_increment,
NULL::character varying::information_schema.character_data AS identity_maximum,
NULL::character varying::information_schema.character_data AS identity_minimum,
NULL::character varying::information_schema.yes_or_no AS identity_cycle,
'NEVER'::character varying::information_schema.character_data AS is_generated,
NULL::character varying::information_schema.character_data AS generation_expression,
CASE
WHEN c.relkind = 'r'::"char" OR (c.relkind = ANY (ARRAY['v'::"char", 'f'::"char"])) AND pg_column_is_updatable(c.oid::regclass, a.attnum, false) THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS is_updatable
FROM pg_attribute a
LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
JOIN (pg_class c
JOIN pg_namespace nc ON c.relnamespace = nc.oid) ON a.attrelid = c.oid
JOIN (pg_type t
JOIN pg_namespace nt ON t.typnamespace = nt.oid) ON a.atttypid = t.oid
LEFT JOIN (pg_type bt
JOIN pg_namespace nbt ON bt.typnamespace = nbt.oid) ON t.typtype = 'd'::"char" AND t.typbasetype = bt.oid
LEFT JOIN (pg_collation co
JOIN pg_namespace nco ON co.collnamespace = nco.oid) ON a.attcollation = co.oid AND (nco.nspname <> 'pg_catalog'::name OR co.collname <> 'default'::name)
WHERE NOT pg_is_other_temp_schema(nc.oid) AND a.attnum > 0 AND NOT a.attisdropped AND (c.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"]))
/*--AND (pg_has_role(c.relowner, 'USAGE'::text) OR has_column_privilege(c.oid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/
)
SELECT
table_schema,
table_name,
column_name,
ordinal_position,
is_nullable,
data_type,
is_updatable,
character_maximum_length,
numeric_precision,
column_default,
udt_name
/*-- FROM information_schema.columns*/
FROM columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
) AS info
LEFT OUTER JOIN (
SELECT
n.nspname AS s,
t.typname AS n,
array_agg(e.enumlabel ORDER BY e.enumsortorder) AS vals
FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
GROUP BY s,n
) AS enum_info ON (info.udt_name = enum_info.n)
ORDER BY schema, position |]
columnFromRow :: [Table] ->
(Text, Text, Text,
Int32, Bool, Text,
Bool, Maybe Int32, Maybe Int32,
Maybe Text, Maybe Text)
-> Maybe Column
columnFromRow tabs (s, t, n, pos, nul, typ, u, l, p, d, e) = buildColumn <$> table
where
buildColumn tbl = Column tbl n pos nul typ u l p d (parseEnum e) Nothing
table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs
parseEnum :: Maybe Text -> [Text]
parseEnum str = fromMaybe [] $ split (==',') <$> str
allRelations :: [Table] -> [Column] -> H.Query () [Relation]
allRelations tabs cols =
H.statement sql HE.unit (decodeRelations tabs cols) True
where
sql = [q|
SELECT ns1.nspname AS table_schema,
tab.relname AS table_name,
column_info.cols AS columns,
ns2.nspname AS foreign_table_schema,
other.relname AS foreign_table_name,
column_info.refs AS foreign_columns
FROM pg_constraint,
LATERAL (SELECT array_agg(cols.attname) AS cols,
array_agg(cols.attnum) AS nums,
array_agg(refs.attname) AS refs
FROM ( SELECT unnest(conkey) AS col, unnest(confkey) AS ref) k,
LATERAL (SELECT * FROM pg_attribute
WHERE attrelid = conrelid AND attnum = col)
AS cols,
LATERAL (SELECT * FROM pg_attribute
WHERE attrelid = confrelid AND attnum = ref)
AS refs)
AS column_info,
LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = connamespace) AS ns1,
LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = conrelid) AS tab,
LATERAL (SELECT * FROM pg_class WHERE pg_class.oid = confrelid) AS other,
LATERAL (SELECT * FROM pg_namespace WHERE pg_namespace.oid = other.relnamespace) AS ns2
WHERE confrelid != 0
ORDER BY (conrelid, column_info.nums) |]
relationFromRow :: [Table] -> [Column] -> (Text, Text, [Text], Text, Text, [Text]) -> Maybe Relation
relationFromRow allTabs allCols (rs, rt, rcs, frs, frt, frcs) =
Relation <$> table <*> cols <*> tableF <*> colsF <*> pure Child <*> pure Nothing <*> pure Nothing <*> pure Nothing
where
findTable s t = find (\tbl -> tableSchema tbl == s && tableName tbl == t) allTabs
findCol s t c = find (\col -> tableSchema (colTable col) == s && tableName (colTable col) == t && colName col == c) allCols
table = findTable rs rt
tableF = findTable frs frt
cols = mapM (findCol rs rt) rcs
colsF = mapM (findCol frs frt) frcs
allPrimaryKeys :: [Table] -> H.Query () [PrimaryKey]
allPrimaryKeys tabs =
H.statement sql HE.unit (decodePks tabs) True
where
sql = [q|
/*
-- CTE to replace information_schema.table_constraints to remove owner limit
*/
WITH tc AS (
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
nc.nspname::information_schema.sql_identifier AS constraint_schema,
c.conname::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
nr.nspname::information_schema.sql_identifier AS table_schema,
r.relname::information_schema.sql_identifier AS table_name,
CASE c.contype
WHEN 'c'::"char" THEN 'CHECK'::text
WHEN 'f'::"char" THEN 'FOREIGN KEY'::text
WHEN 'p'::"char" THEN 'PRIMARY KEY'::text
WHEN 'u'::"char" THEN 'UNIQUE'::text
ELSE NULL::text
END::information_schema.character_data AS constraint_type,
CASE
WHEN c.condeferrable THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS is_deferrable,
CASE
WHEN c.condeferred THEN 'YES'::text
ELSE 'NO'::text
END::information_schema.yes_or_no AS initially_deferred
FROM pg_namespace nc,
pg_namespace nr,
pg_constraint c,
pg_class r
WHERE nc.oid = c.connamespace AND nr.oid = r.relnamespace AND c.conrelid = r.oid AND (c.contype <> ALL (ARRAY['t'::"char", 'x'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)
/*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/
UNION ALL
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
nr.nspname::information_schema.sql_identifier AS constraint_schema,
(((((nr.oid::text || '_'::text) || r.oid::text) || '_'::text) || a.attnum::text) || '_not_null'::text)::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
nr.nspname::information_schema.sql_identifier AS table_schema,
r.relname::information_schema.sql_identifier AS table_name,
'CHECK'::character varying::information_schema.character_data AS constraint_type,
'NO'::character varying::information_schema.yes_or_no AS is_deferrable,
'NO'::character varying::information_schema.yes_or_no AS initially_deferred
FROM pg_namespace nr,
pg_class r,
pg_attribute a
WHERE nr.oid = r.relnamespace AND r.oid = a.attrelid AND a.attnotnull AND a.attnum > 0 AND NOT a.attisdropped AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)
/*--AND (pg_has_role(r.relowner, 'USAGE'::text) OR has_table_privilege(r.oid, 'INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) OR has_any_column_privilege(r.oid, 'INSERT, UPDATE, REFERENCES'::text))*/
),
/*
-- CTE to replace information_schema.key_column_usage to remove owner limit
*/
kc AS (
SELECT current_database()::information_schema.sql_identifier AS constraint_catalog,
ss.nc_nspname::information_schema.sql_identifier AS constraint_schema,
ss.conname::information_schema.sql_identifier AS constraint_name,
current_database()::information_schema.sql_identifier AS table_catalog,
ss.nr_nspname::information_schema.sql_identifier AS table_schema,
ss.relname::information_schema.sql_identifier AS table_name,
a.attname::information_schema.sql_identifier AS column_name,
(ss.x).n::information_schema.cardinal_number AS ordinal_position,
CASE
WHEN ss.contype = 'f'::"char" THEN information_schema._pg_index_position(ss.conindid, ss.confkey[(ss.x).n])
ELSE NULL::integer
END::information_schema.cardinal_number AS position_in_unique_constraint
FROM pg_attribute a,
( SELECT r.oid AS roid,
r.relname,
r.relowner,
nc.nspname AS nc_nspname,
nr.nspname AS nr_nspname,
c.oid AS coid,
c.conname,
c.contype,
c.conindid,
c.confkey,
c.confrelid,
information_schema._pg_expandarray(c.conkey) AS x
FROM pg_namespace nr,
pg_class r,
pg_namespace nc,
pg_constraint c
WHERE nr.oid = r.relnamespace AND r.oid = c.conrelid AND nc.oid = c.connamespace AND (c.contype = ANY (ARRAY['p'::"char", 'u'::"char", 'f'::"char"])) AND r.relkind = 'r'::"char" AND NOT pg_is_other_temp_schema(nr.oid)) ss
WHERE ss.roid = a.attrelid AND a.attnum = (ss.x).x AND NOT a.attisdropped
/*--AND (pg_has_role(ss.relowner, 'USAGE'::text) OR has_column_privilege(ss.roid, a.attnum, 'SELECT, INSERT, UPDATE, REFERENCES'::text))*/
)
SELECT
kc.table_schema,
kc.table_name,
kc.column_name
FROM
/*
--information_schema.table_constraints tc,
--information_schema.key_column_usage kc
*/
tc, kc
WHERE
tc.constraint_type = 'PRIMARY KEY' AND
kc.table_name = tc.table_name AND
kc.table_schema = tc.table_schema AND
kc.constraint_name = tc.constraint_name AND
kc.table_schema NOT IN ('pg_catalog', 'information_schema') |]
pkFromRow :: [Table] -> (Schema, Text, Text) -> Maybe PrimaryKey
pkFromRow tabs (s, t, n) = PrimaryKey <$> table <*> pure n
where table = find (\tbl -> tableSchema tbl == s && tableName tbl == t) tabs
allSynonyms :: [Column] -> H.Query () [(Column,Column)]
allSynonyms cols =
H.statement sql HE.unit (decodeSynonyms cols) True
where
-- query explanation at https://gist.github.com/ruslantalpa/2eab8c930a65e8043d8f
sql = [q|
WITH view_columns AS (
SELECT
c.oid AS view_oid,
a.attname::information_schema.sql_identifier AS column_name
FROM pg_attribute a
JOIN pg_class c ON a.attrelid = c.oid
JOIN pg_namespace nc ON c.relnamespace = nc.oid
WHERE
NOT pg_is_other_temp_schema(nc.oid)
AND a.attnum > 0
AND NOT a.attisdropped
AND (c.relkind = 'v'::"char")
AND nc.nspname NOT IN ('information_schema', 'pg_catalog')
),
view_column_usage AS (
SELECT DISTINCT
v.oid as view_oid,
nv.nspname::information_schema.sql_identifier AS view_schema,
v.relname::information_schema.sql_identifier AS view_name,
nt.nspname::information_schema.sql_identifier AS table_schema,
t.relname::information_schema.sql_identifier AS table_name,
a.attname::information_schema.sql_identifier AS column_name,
pg_get_viewdef(v.oid)::information_schema.character_data AS view_definition
FROM pg_namespace nv
JOIN pg_class v ON nv.oid = v.relnamespace
JOIN pg_depend dv ON v.oid = dv.refobjid
JOIN pg_depend dt ON dv.objid = dt.objid
JOIN pg_class t ON dt.refobjid = t.oid
JOIN pg_namespace nt ON t.relnamespace = nt.oid
JOIN pg_attribute a ON t.oid = a.attrelid AND dt.refobjsubid = a.attnum
WHERE
nv.nspname not in ('information_schema', 'pg_catalog')
AND v.relkind = 'v'::"char"
AND dv.refclassid = 'pg_class'::regclass::oid
AND dv.classid = 'pg_rewrite'::regclass::oid
AND dv.deptype = 'i'::"char"
AND dv.refobjid <> dt.refobjid
AND dt.classid = 'pg_rewrite'::regclass::oid
AND dt.refclassid = 'pg_class'::regclass::oid
AND (t.relkind = ANY (ARRAY['r'::"char", 'v'::"char", 'f'::"char"]))
),
candidates AS (
SELECT
vcu.*,
(
SELECT CASE WHEN match IS NOT NULL THEN coalesce(match[7], match[4]) END
FROM REGEXP_MATCHES(
CONCAT('SELECT ', SPLIT_PART(vcu.view_definition, 'SELECT', 2)),
CONCAT('SELECT.*?((',vcu.table_name,')|(\w+))\.(', vcu.column_name, ')(\sAS\s(")?([^"]+)\6)?.*?FROM.*?',vcu.table_schema,'\.(\2|',vcu.table_name,'\s+(AS\s)?\3)'),
'ns'
) match
) AS view_column_name
FROM view_column_usage AS vcu
)
SELECT
c.table_schema,
c.table_name,
c.column_name AS table_column_name,
c.view_schema,
c.view_name,
c.view_column_name
FROM view_columns AS vc, candidates AS c
WHERE
vc.view_oid = c.view_oid AND
vc.column_name = c.view_column_name
ORDER BY c.view_schema, c.view_name, c.table_name, c.view_column_name
|]
synonymFromRow :: [Column] -> (Text,Text,Text,Text,Text,Text) -> Maybe (Column,Column)
synonymFromRow allCols (s1,t1,c1,s2,t2,c2) = (,) <$> col1 <*> col2
where
col1 = findCol s1 t1 c1
col2 = findCol s2 t2 c2
findCol s t c = find (\col -> (tableSchema . colTable) col == s && (tableName . colTable) col == t && colName col == c) allCols
|
league/postgrest
|
src/PostgREST/DbStructure.hs
|
Haskell
|
mit
| 30,824
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MediaSource
(js_newMediaSource, newMediaSource, js_addSourceBuffer,
addSourceBuffer, js_removeSourceBuffer, removeSourceBuffer,
js_endOfStream, endOfStream, js_isTypeSupported, isTypeSupported,
js_getSourceBuffers, getSourceBuffers, js_getActiveSourceBuffers,
getActiveSourceBuffers, js_setDuration, setDuration,
js_getDuration, getDuration, js_getReadyState, getReadyState,
MediaSource, castToMediaSource, gTypeMediaSource)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "new window[\"MediaSource\"]()"
js_newMediaSource :: IO MediaSource
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource Mozilla MediaSource documentation>
newMediaSource :: (MonadIO m) => m MediaSource
newMediaSource = liftIO (js_newMediaSource)
foreign import javascript unsafe "$1[\"addSourceBuffer\"]($2)"
js_addSourceBuffer ::
MediaSource -> JSString -> IO (Nullable SourceBuffer)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.addSourceBuffer Mozilla MediaSource.addSourceBuffer documentation>
addSourceBuffer ::
(MonadIO m, ToJSString type') =>
MediaSource -> type' -> m (Maybe SourceBuffer)
addSourceBuffer self type'
= liftIO
(nullableToMaybe <$>
(js_addSourceBuffer (self) (toJSString type')))
foreign import javascript unsafe "$1[\"removeSourceBuffer\"]($2)"
js_removeSourceBuffer ::
MediaSource -> Nullable SourceBuffer -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.removeSourceBuffer Mozilla MediaSource.removeSourceBuffer documentation>
removeSourceBuffer ::
(MonadIO m) => MediaSource -> Maybe SourceBuffer -> m ()
removeSourceBuffer self buffer
= liftIO (js_removeSourceBuffer (self) (maybeToNullable buffer))
foreign import javascript unsafe "$1[\"endOfStream\"]($2)"
js_endOfStream :: MediaSource -> JSVal -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.endOfStream Mozilla MediaSource.endOfStream documentation>
endOfStream ::
(MonadIO m) => MediaSource -> EndOfStreamError -> m ()
endOfStream self error
= liftIO (js_endOfStream (self) (pToJSVal error))
foreign import javascript unsafe
"($1[\"isTypeSupported\"]($2) ? 1 : 0)" js_isTypeSupported ::
MediaSource -> JSString -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.isTypeSupported Mozilla MediaSource.isTypeSupported documentation>
isTypeSupported ::
(MonadIO m, ToJSString type') => MediaSource -> type' -> m Bool
isTypeSupported self type'
= liftIO (js_isTypeSupported (self) (toJSString type'))
foreign import javascript unsafe "$1[\"sourceBuffers\"]"
js_getSourceBuffers ::
MediaSource -> IO (Nullable SourceBufferList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.sourceBuffers Mozilla MediaSource.sourceBuffers documentation>
getSourceBuffers ::
(MonadIO m) => MediaSource -> m (Maybe SourceBufferList)
getSourceBuffers self
= liftIO (nullableToMaybe <$> (js_getSourceBuffers (self)))
foreign import javascript unsafe "$1[\"activeSourceBuffers\"]"
js_getActiveSourceBuffers ::
MediaSource -> IO (Nullable SourceBufferList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.activeSourceBuffers Mozilla MediaSource.activeSourceBuffers documentation>
getActiveSourceBuffers ::
(MonadIO m) => MediaSource -> m (Maybe SourceBufferList)
getActiveSourceBuffers self
= liftIO (nullableToMaybe <$> (js_getActiveSourceBuffers (self)))
foreign import javascript unsafe "$1[\"duration\"] = $2;"
js_setDuration :: MediaSource -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.duration Mozilla MediaSource.duration documentation>
setDuration :: (MonadIO m) => MediaSource -> Double -> m ()
setDuration self val = liftIO (js_setDuration (self) val)
foreign import javascript unsafe "$1[\"duration\"]" js_getDuration
:: MediaSource -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.duration Mozilla MediaSource.duration documentation>
getDuration :: (MonadIO m) => MediaSource -> m Double
getDuration self = liftIO (js_getDuration (self))
foreign import javascript unsafe "$1[\"readyState\"]"
js_getReadyState :: MediaSource -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaSource.readyState Mozilla MediaSource.readyState documentation>
getReadyState ::
(MonadIO m, FromJSString result) => MediaSource -> m result
getReadyState self
= liftIO (fromJSString <$> (js_getReadyState (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaSource.hs
|
Haskell
|
mit
| 5,611
|
{-# LANGUAGE OverloadedStrings, LambdaCase, FlexibleInstances,
OverloadedLists, TypeSynonymInstances,
FlexibleContexts #-}
module Language.Rowling.Definitions.Types where
import qualified Prelude as P
import Data.Char (isLower)
import qualified Data.HashMap.Strict as H
import Data.Text (Text, strip, head, length)
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.List as L
import Data.String (IsString(..))
import Data.Traversable
import Language.Rowling.Common hiding (head, length)
-- | The type of expressions.
data Type
-- | A record type. The optional name is a type variable for the "rest" of
-- the record, i.e., fields additional to the ones given. If `Nothing`, then
-- the type is considered exact.
= TRecord (HashMap Name Type) (Maybe Name)
-- | A type constant, such as @List@ or @Int@.
| TConst Name
-- | A type variable, which can be later unified to a specific type, or can
-- be left in for a polymorphic type.
| TVar Name
-- | Two types applied to each other. For example, @Just 1@ is the @Maybe@
-- type applied to the @Int@ type.
| TApply Type Type
deriving (Show, Eq)
instance Render Type where
render t = case t of
TConst name -> name
TVar name -> name
TApply (TApply (TConst "->") t1) t2 ->
renderParens t1 <> " -> " <> render t2
TApply (t1@(TApply _ _)) t2 -> render t1 <> " " <> renderParens t2
TApply t1 t2 -> renderParens t1 <> " " <> renderParens t2
TRecord row r -> "(" <> inside <> renderRest r <> ")" where
inside = case splitRow row of
-- Only non-numeric keys
([], named) -> commas renderPair named
-- Only numeric keys
(vals, []) -> commas render vals
-- Mixture of the two
(vals, named) -> commas render vals <> ", " <> commas renderPair named
where
renderRest r = case r of
Nothing -> ""
Just name -> " | " <> name
commas rndr = intercalate ", " . map rndr
renderPair (field, typ) = field <> ": " <> render typ
-- | Splits a row into the fields which have numeric names (0, 1, ...)
-- and the ones that have "normal" names.
splitRow :: HashMap Name Type -> ([Type], [(Name, Type)])
splitRow row = (snd <$> nums', withNames) where
(withNums, withNames) = L.partition (isNumber . fst) $ H.toList row
toNum :: (Name, Type) -> (Int, Type)
toNum (name, t) = (P.read (unpack name) :: Int, t)
nums' = L.sortBy (\(a, _) (b, _) -> compare a b) (map toNum withNums)
renderParens t@(TApply _ _) = "(" <> render t <> ")"
renderParens t = render t
instance Default Type where
def = TRecord mempty Nothing
-- | Checks if the type on the left is at least as general as the type on
-- the right. For example, a type variable is at least as general as anything,
-- a `Float` is at least as general as an `Int`, etc.
(>==) :: Type -- ^ The type which should be more general (e.g. a parameter).
-> Type -- ^ The type which can be more specific (e.g. an argument).
-> Bool -- ^ If the first type is at least as general as the second.
TRecord fields1 r1 >== TRecord fields2 r2 =
fields1 `vs` fields2 && case (r1, r2) of
(Nothing, Nothing) -> True
(Just _, _) -> True
_ -> False
where
-- | Comparing the generality of two records.
rec1 `vs` rec2 = go $ H.toList rec1 where
go [] = True
go ((field, typ):rest) = case H.lookup field rec2 of
-- If the field doesn't exist in the second record, they're not
-- compatible.
Nothing -> False
-- Otherwise, they must be compatible.
Just typ' -> typ >== typ' && go rest
TConst name1 >== TConst name2 = name1 == name2
TVar _ >== _ = True
TApply t1 t2 >== TApply t3 t4 = t1 >== t3 && t2 >== t4
_ >== _ = False
instance IsString Type where
fromString s = do
let s' = strip $ pack s
if length s' > 0 && (isLower (head s') || head s' == '$')
then TVar s'
else TConst s'
-- | Class of things which contain free variables. @freevars@ gets all of the
-- free variables out. For example, the type @a@ has free variables @{a}@,
-- while the type @a -> b@ has free variables @{a, b}@; the type @Maybe (a ->
-- Int) -> b -> c@ has free variables @{a, b, c}@, etc.
class FreeVars a where freevars :: a -> Set Name
instance FreeVars Type where
freevars = \case
TVar n -> S.singleton n
TConst _ -> mempty
TApply t1 t2 -> freevars t1 <> freevars t2
TRecord fields Nothing -> freevars fields
TRecord fields (Just r) -> S.insert r $ mconcat (fmap freevars $ toList fields)
instance FreeVars Polytype where
freevars (Polytype vars t) = freevars t \\ vars
instance FreeVars a => FreeVars (Maybe a) where
freevars Nothing = mempty
freevars (Just x) = freevars x
instance FreeVars b => FreeVars (a, b) where
freevars = freevars . snd
instance FreeVars a => FreeVars [a] where
freevars = mconcat . fmap freevars
instance FreeVars a => FreeVars (HashMap x a) where
freevars = freevars . H.elems
data Polytype = Polytype (Set Name) Type deriving (Show, Eq)
instance IsString Polytype where
fromString = polytype . fromString
-- | Stores names that we've typed.
type TypeMap = HashMap Name Polytype
instance Default TypeMap where
def = mempty
-- | Stores type aliases.
type AliasMap = HashMap Name Type
instance Default AliasMap where
def = mempty
-- | Normalizing means replacing obscurely-named type variables with letters.
-- For example, the type @(t$13 -> [t$4]) -> t$13@ would be @(a -> b) -> a@.
-- The best way to do this is with a state monad so that we can track which
-- renamings have been done. So the only method that we need is @normalizeS@
-- (@S@ for state monad). This lets us normalize across multiple types.
class Normalize t where
normalizeS :: t -> State (Text, HashMap Name Name) t
-- | Normalizes starting with `a`.
normalize :: Normalize a => a -> a
normalize = normalizeWith ("a", mempty)
-- | Normalizes given some initial starting point.
normalizeWith :: Normalize a => (Text, HashMap Name Name) -> a -> a
normalizeWith state x = evalState (normalizeS x) state
instance Normalize Type where
normalizeS type_ = case type_ of
TVar name -> TVar <$> normalizeS name
TApply a b -> TApply <$> normalizeS a <*> normalizeS b
TRecord row rest -> TRecord <$> normalizeS row <*> normalizeS rest
_ -> return type_
instance (Normalize a, Traversable f) => Normalize (f a) where
normalizeS = mapM normalizeS
instance Normalize Text where
normalizeS oldName = do
(newName, mapping) <- get
case H.lookup oldName mapping of
Just n -> return n
Nothing -> do put (next newName, H.insert oldName newName mapping)
return newName
class CanApply a where apply :: a -> a -> a
instance CanApply Type where
apply = TApply
instance CanApply Polytype where
apply (Polytype vs1 t1) (Polytype vs2 t2) =
Polytype (vs1 <> vs2) (apply t1 t2)
-- | The function type, which is actually a rank-2 type applied twice.
(==>) :: (IsString a, CanApply a) => a -> a -> a
t1 ==> t2 = apply (apply "->" t1) t2
infixr 3 ==>
-- | Creates a polytype out of a type. Somewhat hacky.
polytype :: Type -> Polytype
polytype = Polytype mempty
-- | Creates an exact (non-extensible) record type from a list of fields.
tRecord :: [(Name, Type)] -> Type
tRecord fields = TRecord (H.fromList fields) Nothing
-- | Creates an extensible record type from a list of fields.
tRecord' :: [(Name, Type)] -> Name -> Type
tRecord' fields name = TRecord (H.fromList fields) (Just name)
-- | Checks if the string is a number.
isNumber :: Text -> Bool
isNumber = T.all isDigit
-- | Generates the next name in the "fresh name sequence". This sequence is:
-- @a, b, c, ..., z, za, zb, zc, ... zz, zza, zzb, zzc...@
next :: Text -> Text
next name = case T.last name of
c | c < 'z' -> T.init name `T.snoc` succ c
| True -> name `T.snoc` 'a'
listOf :: Type -> Type
listOf = TApply "List"
|
thinkpad20/rowling
|
src/Language/Rowling/Definitions/Types.hs
|
Haskell
|
mit
| 8,002
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigatewayv2-stage-accesslogsettings.html
module Stratosphere.ResourceProperties.ApiGatewayV2StageAccessLogSettings where
import Stratosphere.ResourceImports
-- | Full data type definition for ApiGatewayV2StageAccessLogSettings. See
-- 'apiGatewayV2StageAccessLogSettings' for a more convenient constructor.
data ApiGatewayV2StageAccessLogSettings =
ApiGatewayV2StageAccessLogSettings
{ _apiGatewayV2StageAccessLogSettingsDestinationArn :: Maybe (Val Text)
, _apiGatewayV2StageAccessLogSettingsFormat :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON ApiGatewayV2StageAccessLogSettings where
toJSON ApiGatewayV2StageAccessLogSettings{..} =
object $
catMaybes
[ fmap (("DestinationArn",) . toJSON) _apiGatewayV2StageAccessLogSettingsDestinationArn
, fmap (("Format",) . toJSON) _apiGatewayV2StageAccessLogSettingsFormat
]
-- | Constructor for 'ApiGatewayV2StageAccessLogSettings' containing required
-- fields as arguments.
apiGatewayV2StageAccessLogSettings
:: ApiGatewayV2StageAccessLogSettings
apiGatewayV2StageAccessLogSettings =
ApiGatewayV2StageAccessLogSettings
{ _apiGatewayV2StageAccessLogSettingsDestinationArn = Nothing
, _apiGatewayV2StageAccessLogSettingsFormat = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigatewayv2-stage-accesslogsettings.html#cfn-apigatewayv2-stage-accesslogsettings-destinationarn
agvsalsDestinationArn :: Lens' ApiGatewayV2StageAccessLogSettings (Maybe (Val Text))
agvsalsDestinationArn = lens _apiGatewayV2StageAccessLogSettingsDestinationArn (\s a -> s { _apiGatewayV2StageAccessLogSettingsDestinationArn = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigatewayv2-stage-accesslogsettings.html#cfn-apigatewayv2-stage-accesslogsettings-format
agvsalsFormat :: Lens' ApiGatewayV2StageAccessLogSettings (Maybe (Val Text))
agvsalsFormat = lens _apiGatewayV2StageAccessLogSettingsFormat (\s a -> s { _apiGatewayV2StageAccessLogSettingsFormat = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/ApiGatewayV2StageAccessLogSettings.hs
|
Haskell
|
mit
| 2,241
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE Trustworthy #-}
-- | A container for keeping values of various types together.
module System.Hurtle.TypedStore
( Id(), Mode(..), TypedStore()
, typedStore, insert, lookup, (!), update, delete
) where
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Maybe (fromJust)
import Unsafe.Coerce (unsafeCoerce)
import Prelude hiding (lookup)
data Box f where Box :: f a -> Box f
data Mode
= Mono -- ^ Monotonic (no deletes, only inserts and updates)
| NonMono -- ^ Non-monotonic (allows deletes)
newtype Id s a = Id Int
unbox :: Box f -> f a
unbox (Box x) = unsafeCoerce x
data TypedStore s (mode :: Mode) f = TS Int (IntMap (Box f))
insert :: f a -> TypedStore s mode f -> (Id s (f a), TypedStore s mode f)
insert x (TS n st) = (Id n, TS (succ n) (IM.insert n (Box x) st))
lookup :: Id s (f a) -> TypedStore s mode f -> Maybe (f a)
lookup (Id i) (TS _ st) = fmap unbox (IM.lookup i st)
(!) :: Id s (f a) -> TypedStore s Mono f -> f a
Id i ! TS _ st = fromJust (fmap unbox (IM.lookup i st))
update :: Id s (f a) -> f a -> TypedStore s mode f -> TypedStore s mode f
update (Id i) x (TS n st) = TS n (IM.insert i (Box x) st)
delete :: Id s (f a) -> TypedStore s NonMono f -> TypedStore s NonMono f
delete (Id i) (TS n st) = TS n (IM.delete i st)
-- | Create a 'NonMono'tonic store, that is 'delete's are allowed but you can't
-- use the '!' operator and have to deal with 'Maybe's from 'lookup'.
--
-- Uses an existential phantom type for safety.
typedStore :: (forall s. TypedStore s mode f -> a) -> a
typedStore f = f (TS 0 IM.empty)
|
bens/hurtle
|
src/System/Hurtle/TypedStore.hs
|
Haskell
|
apache-2.0
| 1,816
|
{-# Hey #-}
{-# LANGUAGE OhMyGod #-}
{-# OPTIONS_GHC --omG #-}
|
rikvdkleij/intellij-haskell
|
src/test/testData/parsing-hs/Pragma.hs
|
Haskell
|
apache-2.0
| 63
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.PodSecurityContext where
import GHC.Generics
import Kubernetes.V1.SELinuxOptions
import qualified Data.Aeson
-- | PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext.
data PodSecurityContext = PodSecurityContext
{ seLinuxOptions :: Maybe SELinuxOptions -- ^ The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
, runAsUser :: Maybe Integer -- ^ The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
, runAsNonRoot :: Maybe Bool -- ^ Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
, supplementalGroups :: Maybe [Integer] -- ^ A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.
, fsGroup :: Maybe Integer -- ^ A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:\n\n1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON PodSecurityContext
instance Data.Aeson.ToJSON PodSecurityContext
|
minhdoboi/deprecated-openshift-haskell-api
|
kubernetes/lib/Kubernetes/V1/PodSecurityContext.hs
|
Haskell
|
apache-2.0
| 2,467
|
module TransCFSpec (transSpec, testConcreteSyn) where
import BackEnd
import FrontEnd (source2core)
import JavaUtils (getClassPath)
import MonadLib
import OptiUtils (Exp(Hide))
import PartialEvaluator (rewriteAndEval)
import SpecHelper
import StringPrefixes (namespace)
import StringUtils (capitalize)
import TestTerms
import Language.Java.Pretty (prettyPrint)
import System.Directory
import System.FilePath
import System.IO
import System.Process
import Test.Tasty.Hspec
testCasesPath = "testsuite/tests/shouldRun"
fetchResult :: Handle -> IO String
fetchResult outP = do
msg <- hGetLine outP
if msg == "exit" then fetchResult outP else return msg
-- java compilation + run
compileAndRun inP outP name compileF exp =
do let source = prettyPrint (fst (compileF name (rewriteAndEval exp)))
let jname = name ++ ".java"
hPutStrLn inP jname
hPutStrLn inP (source ++ "\n" ++ "//end of file")
fetchResult outP
testAbstractSyn inP outP compilation (name, filePath, ast, expectedOutput) = do
let className = capitalize $ dropExtension (takeFileName filePath)
output <- runIO (compileAndRun inP outP className compilation ast)
it ("should compile and run " ++ name ++ " and get \"" ++ expectedOutput ++ "\"") $
return output `shouldReturn` expectedOutput
testConcreteSyn inP outP compilation (name, filePath) =
do source <- runIO (readFile filePath)
case parseExpectedOutput source of
Nothing -> error (filePath ++ ": " ++
"The integration test file should start with '-->', \
\followed by the expected output")
Just expectedOutput ->
do ast <- runIO (source2core NoDump "" (filePath, source))
testAbstractSyn inP outP compilation (name, filePath, ast, expectedOutput)
abstractCases =
[ ("factorial 10", "main_1", Hide factApp, "3628800")
, ("fibonacci 10", "main_2", Hide fiboApp, "55")
, ("idF Int 10", "main_3", Hide idfNum, "10")
, ("const Int 10 20", "main_4", Hide constNum, "10")
, ("program1 Int 5", "main_5", Hide program1Num, "5")
, ("program2", "main_6", Hide program2, "5")
, ("program4", "main_7", Hide program4, "11")
]
transSpec =
do concreteCases <- runIO (discoverTestCases testCasesPath)
-- change to testing directory for module testing
curr <- runIO (getCurrentDirectory)
runIO (setCurrentDirectory $ curr </> testCasesPath)
forM_
[("BaseTransCF" , compileN)
,("ApplyTransCF", compileAO)
,("StackTransCF", compileS)]
(\(name, compilation) ->
describe name $
do cp <- runIO getClassPath
let p = (proc "java" ["-cp", cp, namespace ++ "FileServer", cp])
{std_in = CreatePipe, std_out = CreatePipe}
(Just inP, Just outP, _, proch) <- runIO $ createProcess p
runIO $ hSetBuffering inP NoBuffering
runIO $ hSetBuffering outP NoBuffering
forM_ abstractCases (testAbstractSyn inP outP compilation)
forM_ concreteCases (testConcreteSyn inP outP compilation))
runIO (setCurrentDirectory curr)
|
bixuanzju/fcore
|
testsuite/TransCFSpec.hs
|
Haskell
|
bsd-2-clause
| 3,136
|
{--
Copyright (c) 2014-2020, Clockwork Dev Studio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
--}
{-# LANGUAGE CPP #-}
module Assembler where
import Common
import Options
import System.Process
import System.Exit
import System.IO
import System.FilePath.Posix
import Data.Maybe
import Data.List
import Debug.Trace
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Identity
assemble :: CodeTransformation ()
assemble =
do config <- gets asmStateConfig
code <- gets asmStateCode
let asmFileName = configAsmFileName config
objectFileName = configObjectFileName config
inputFile = configInputFile config
outputFile = configOutputFile config
options = configOptions config
verbose = optionVerbose options
liftIO $ hPutStr outputFile (concat code)
liftIO $ hClose inputFile
liftIO $ hClose outputFile
verboseCommentary ("Assembling...\n") verbose
verboseCommentary ("(Assembler backend is '" ++ optionAssembler options ++ "')\n") verbose
case optionAssembler options of
"fasm" ->
do
#if LINUX==1 || MAC_OS==1
let fasmPath = IWL_HOME ++ "/fasm"
#elif WINDOWS==1
let fasmPath = IWL_HOME ++ "\\fasm.exe"
#endif
verboseCommentary ("fasm " ++ asmFileName ++ "\n") verbose
(exit, stdout, stderr) <- liftIO $ readProcessWithExitCode fasmPath [asmFileName] ""
case exit of
(ExitFailure n) -> do liftIO $ putStrLn (stderr ++ "\nAssembler error (fasm, code " ++ (show n) ++ ").")
liftIO $ exitFailure
_ -> return ()
"nasm" ->
do
#if LINUX==1
let nasmPath = IWL_HOME ++ "/nasm"
nasmOptions = [asmFileName, "--discard-labels","-o", objectFileName, "-f", "elf64"]
#elif MAC_OS==1
let nasmPath = IWL_HOME ++ "/nasm"
nasmOptions = [asmFileName, "-o", objectFileName, "-f", "macho64"]
#elif WINDOWS==1
let nasmPath = IWL_HOME ++ "\\nasm.exe"
nasmOptions = [asmFileName, "-o", objectFileName, "-f", "win64"]
#endif
verboseCommentary (IWL_HOME ++ "/nasm " ++ (concat (intersperse " " nasmOptions)) ++ "\n") verbose
(exit, stdout, stderr) <- liftIO $ readProcessWithExitCode nasmPath nasmOptions ""
case exit of
(ExitFailure n) -> do liftIO $ putStrLn (stderr ++ "\nAssembler error (nasm, code " ++ (show n) ++ ").")
liftIO $ exitFailure
_ -> return ()
debugInfo <- gets asmStateDebugInfo
put LinkState {linkStateDebugInfo = debugInfo,
linkStateConfig = config}
|
clockworkdevstudio/Idlewild-Lang
|
Assembler.hs
|
Haskell
|
bsd-2-clause
| 4,077
|
-- base
import Control.Concurrent (threadDelay)
import Control.Monad (forM, forM_, when)
import Data.Char (isAscii)
import Data.List (intercalate, isPrefixOf)
import Foreign.C.String (peekCString, withCString)
import Foreign.C.Types (CDouble(..))
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Array (peekArray)
import Foreign.Ptr (Ptr, nullPtr, nullFunPtr)
import Foreign.Storable (Storable(..))
-- HUnit
import Test.HUnit ((@?=), (@?), assertBool, assertFailure, assertEqual)
-- test-framework
import Test.Framework (Test, defaultMain, testGroup)
-- test-framework-hunit
import Test.Framework.Providers.HUnit (testCase)
-- bindings-GLFW
import Bindings.GLFW
--------------------------------------------------------------------------------
main :: IO ()
main = do
c'glfwInitHint c'GLFW_COCOA_CHDIR_RESOURCES c'GLFW_FALSE
_ <- c'glfwInit
p'mon <- c'glfwGetPrimaryMonitor
c'glfwWindowHint c'GLFW_VISIBLE c'GLFW_FALSE
p'win <- withCString "bindings-GLFW test" $ \p'title ->
c'glfwCreateWindow 100 100 p'title nullPtr nullPtr
c'glfwMakeContextCurrent p'win
-- Mostly check for compiling
cmcb <- mk'GLFWcharmodsfun $ \win x y ->
putStrLn $ "Got char mods callback! " ++ show (win, x, y)
_ <- c'glfwSetCharModsCallback p'win cmcb
jcb <- mk'GLFWjoystickfun $ \x y ->
putStrLn $ "Got joystick callback! " ++ show (x, y)
_ <- c'glfwSetJoystickCallback jcb
wcscb <- mk'GLFWwindowcontentscalefun $ \win x y ->
putStrLn $ "Got window content scale callback! " ++ show (win, x, y)
_ <- c'glfwSetWindowContentScaleCallback p'win wcscb
c'glfwGetError nullPtr
>>= assertEqual "Got inititialization error!" c'GLFW_NO_ERROR
defaultMain $ tests p'mon p'win
-- TODO because of how defaultMain works, this code is not reached
c'glfwDestroyWindow p'win
c'glfwTerminate
--------------------------------------------------------------------------------
versionMajor, versionMinor, versionRevision :: Int
versionMajor = 3
versionMinor = 3
versionRevision = 2
giveItTime :: IO ()
giveItTime = threadDelay 500000
joysticks :: Num a => [a]
joysticks =
[ c'GLFW_JOYSTICK_1
, c'GLFW_JOYSTICK_2
, c'GLFW_JOYSTICK_3
, c'GLFW_JOYSTICK_4
, c'GLFW_JOYSTICK_5
, c'GLFW_JOYSTICK_6
, c'GLFW_JOYSTICK_7
, c'GLFW_JOYSTICK_8
, c'GLFW_JOYSTICK_9
, c'GLFW_JOYSTICK_10
, c'GLFW_JOYSTICK_11
, c'GLFW_JOYSTICK_12
, c'GLFW_JOYSTICK_13
, c'GLFW_JOYSTICK_14
, c'GLFW_JOYSTICK_15
, c'GLFW_JOYSTICK_16
]
between :: Ord a => a -> (a,a) -> Bool
between n (l,h) = n >= l && n <= h
videoModeLooksValid :: C'GLFWvidmode -> Bool
videoModeLooksValid vm = and
[ c'GLFWvidmode'width vm `between` (0,8192)
, c'GLFWvidmode'height vm `between` (0,8192)
, c'GLFWvidmode'redBits vm `between` (0,32)
, c'GLFWvidmode'greenBits vm `between` (0,32)
, c'GLFWvidmode'blueBits vm `between` (0,32)
, c'GLFWvidmode'refreshRate vm `between` (0,240)
]
--------------------------------------------------------------------------------
glfwTest :: String -> IO () -> Test
glfwTest name test = testCase name $ do
_ <- c'glfwGetError nullPtr -- clear last error
test
alloca $ \p'errMsg -> do
errResult <- c'glfwGetError p'errMsg
errMsg <- if errResult == c'GLFW_NO_ERROR then return "" else do
msg <- peek p'errMsg >>= peekCString
return $ concat ["Test '", name, "' generated error: ", msg]
assertEqual errMsg errResult c'GLFW_NO_ERROR
tests :: Ptr C'GLFWmonitor -> Ptr C'GLFWwindow -> [Test]
tests p'mon p'win =
[ testGroup "Initialization and version information"
[ testCase "glfwGetVersion" test_glfwGetVersion
, testCase "glfwGetVersionString" test_glfwGetVersionString
, testCase "glfwGetError" test_glfwGetError
, testCase "glfwRawMouseMotionSupported" test_glfwRawMouseMotionSupported
]
, testGroup "Monitor handling"
[ glfwTest "glfwGetMonitors" test_glfwGetMonitors
, glfwTest "glfwGetPrimaryMonitor" test_glfwGetPrimaryMonitor
, glfwTest "glfwGetMonitorContentScale" $ test_glfwGetMonitorContentScale p'mon
, glfwTest "glfwGetMonitorPos" $ test_glfwGetMonitorPos p'mon
, glfwTest "glfwGetMonitorPhysicalSize" $ test_glfwGetMonitorPhysicalSize p'mon
, glfwTest "glfwGetMonitorName" $ test_glfwGetMonitorName p'mon
, glfwTest "glfwGetMonitorWorkarea" $ test_glfwGetMonitorWorkarea p'mon
, glfwTest "glfwGetVideoModes" $ test_glfwGetVideoModes p'mon
, glfwTest "glfwGetVideoMode" $ test_glfwGetVideoMode p'mon
, glfwTest "glfwGetGammaRamp" $ test_glfwGetGammaRamp p'mon
]
, testGroup "Window handling"
[ glfwTest "glfwDefaultWindowHints" test_glfwDefaultWindowHints
, glfwTest "glfwGetWindowAttrib" $ test_glfwGetWindowAttrib p'win
, glfwTest "glfwSetWindowAttrib" $ test_glfwSetWindowAttrib p'win
, glfwTest "window close flag" $ test_window_close_flag p'win
, glfwTest "glfwSetWindowTitle" $ test_glfwSetWindowTitle p'win
, glfwTest "window pos" $ test_window_pos p'win
, glfwTest "window size" $ test_window_size p'win
, glfwTest "glfwGetWindowContentSize" $ test_glfwGetWindowContentScale p'win
, glfwTest "glfwGetWindowFrameSize" $ test_glfwGetWindowFrameSize p'win
, glfwTest "glfwGetFramebufferSize" $ test_glfwGetFramebufferSize p'win
, glfwTest "iconification" $ test_iconification p'win
-- , glfwTest "show/hide" $ test_show_hide p'win
, glfwTest "glfwGetWindowMonitor" $ test_glfwGetWindowMonitor p'win p'mon
, glfwTest "glfwSetWindowMonitor" $ test_glfwSetWindowMonitor p'win p'mon
, glfwTest "glfwSetWindowIcon" $ test_glfwSetWindowIcon p'win
, glfwTest "glfwSetWindowOpacity" $ test_glfwSetWindowOpacity p'win
, glfwTest "glfwMaximizeWindow" $ test_glfwMaximizeWindow p'win
, glfwTest "glfwSetWindowSizeLimits" $ test_glfwSetWindowSizeLimits p'win
, glfwTest "glfwSetWindowAspectRatio" $ test_glfwSetWindowAspectRatio p'win
, glfwTest "glfwFocusWindow" $ test_glfwFocusWindow p'win
, glfwTest "glfwRequestWindowAttention" $ test_glfwRequestWindowAttention p'win
, glfwTest "cursor pos" $ test_cursor_pos p'win
, glfwTest "glfwPollEvents" test_glfwPollEvents
, glfwTest "glfwWaitEvents" test_glfwWaitEvents
, glfwTest "glfwWaitEventsTimeout" test_glfwWaitEventsTimeout
]
, testGroup "Input handling"
[ glfwTest "glfwJoystickPresent" test_glfwJoystickPresent
, glfwTest "glfwGetJoystickAxes" test_glfwGetJoystickAxes
, glfwTest "glfwGetJoystickButtons" test_glfwGetJoystickButtons
, glfwTest "glfwGetJoystickHats" test_glfwGetJoystickHats
, glfwTest "glfwGetJoystickName" test_glfwGetJoystickName
, glfwTest "glfwGetJoystickGUID" test_glfwGetJoystickGUID
, glfwTest "glfwGetGamepadState" test_glfwGetGamepadState
, glfwTest "glfwGetKeyName" test_glfwGetKeyName
, glfwTest "glfwGetKeyScancode" test_glfwGetKeyScancode
]
, testGroup "Time"
[ glfwTest "glfwGetTime" test_glfwGetTime
, glfwTest "glfwSetTime" test_glfwSetTime
, glfwTest "glfwGetTimerValue" test_glfwGetTimerValue
, glfwTest "glfwSetTimerFrequency" test_glfwGetTimerFrequency
]
, testGroup "Context"
[ glfwTest "glfwGetCurrentContext" $ test_glfwGetCurrentContext p'win
, glfwTest "glfwSwapBuffers" $ test_glfwSwapBuffers p'win
, glfwTest "glfwSwapInterval" test_glfwSwapInterval
, glfwTest "glfwExtensionSupported" test_glfwExtensionSupported
]
, testGroup "Clipboard"
[ glfwTest "clipboard" $ test_clipboard p'win
]
, testGroup "Vulkan"
[ glfwTest "glfwVulkanSupported" test_glfwVulkanSupported
, glfwTest "glfwGetRequiredInstanceExtensions" test_glfwGetRequiredInstanceExtensions
, glfwTest "glfwGetInstanceProcAddress" test_glfwGetInstanceProcAddress
, glfwTest "glfwGetPhysicalDevicePresentationSupport" test_glfwGetPhysicalDevicePresentationSupport
, glfwTest "glfwCreateWindowSurface" $ test_glfwCreateWindowSurface p'win
]
]
--------------------------------------------------------------------------------
test_glfwGetVersion :: IO ()
test_glfwGetVersion =
alloca $ \p'v0 ->
alloca $ \p'v1 ->
alloca $ \p'v2 -> do
c'glfwGetVersion p'v0 p'v1 p'v2
v0 <- peek p'v0
v1 <- peek p'v1
v2 <- peek p'v2
v0 @?= fromIntegral versionMajor
v1 @?= fromIntegral versionMinor
v2 @?= fromIntegral versionRevision
test_glfwGetVersionString :: IO ()
test_glfwGetVersionString = do
p'vs <- c'glfwGetVersionString
if p'vs == nullPtr
then assertFailure ""
else do
vs <- peekCString p'vs
assertBool "" $ v `isPrefixOf` vs
where
v = intercalate "." $ map show [versionMajor, versionMinor, versionRevision]
test_glfwGetError :: IO ()
test_glfwGetError =
alloca $ \p'err ->
c'glfwGetError p'err >>= assertEqual "Discovered GLFW error!" c'GLFW_NO_ERROR
test_glfwRawMouseMotionSupported :: IO ()
test_glfwRawMouseMotionSupported = c'glfwRawMouseMotionSupported >> return ()
--------------------------------------------------------------------------------
test_glfwGetMonitors :: IO ()
test_glfwGetMonitors =
alloca $ \p'n -> do
p'mons <- c'glfwGetMonitors p'n
n <- peek p'n
if p'mons == nullPtr || n <= 0
then assertFailure ""
else do
mons <- peekArray (fromIntegral n) p'mons
assertBool "" $ not $ null mons
test_glfwGetPrimaryMonitor :: IO ()
test_glfwGetPrimaryMonitor = do
p'mon <- c'glfwGetPrimaryMonitor
assertBool "" $ p'mon /= nullPtr
test_glfwGetMonitorContentScale :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetMonitorContentScale p'mon =
alloca $ \p'x ->
alloca $ \p'y -> do
c'glfwGetMonitorContentScale p'mon p'x p'y
x <- peek p'x
y <- peek p'y
assertBool "Monitor content scale x is defined" $ x > 0
assertBool "Monitor content scale y is defined" $ y > 0
test_glfwGetMonitorPos :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetMonitorPos p'mon =
alloca $ \p'x ->
alloca $ \p'y -> do
c'glfwGetMonitorPos p'mon p'x p'y
x <- peek p'x
y <- peek p'y
assertBool "" $ x >= 0
assertBool "" $ y >= 0
test_glfwGetMonitorPhysicalSize :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetMonitorPhysicalSize p'mon =
alloca $ \p'w ->
alloca $ \p'h -> do
c'glfwGetMonitorPhysicalSize p'mon p'w p'h
w <- peek p'w
h <- peek p'h
assertBool "" $ w `between` (0, 1000)
assertBool "" $ h `between` (0, 500)
test_glfwGetMonitorName :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetMonitorName p'mon = do
p'name <- c'glfwGetMonitorName p'mon
if p'name == nullPtr
then assertFailure ""
else do
name <- peekCString p'name
assertBool "" $ length name `between` (0, 20)
assertBool "" $ all isAscii name
test_glfwGetMonitorWorkarea :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetMonitorWorkarea p'mon =
alloca $ \p'xpos ->
alloca $ \p'ypos ->
alloca $ \p'w ->
alloca $ \p'h -> do
c'glfwGetMonitorWorkarea p'mon p'xpos p'ypos p'w p'h
xpos <- peek p'xpos
ypos <- peek p'ypos
w <- peek p'w
h <- peek p'h
assertBool "Workarea xpos not negative" $ xpos >= 0
assertBool "Workarea ypos not negative" $ ypos >= 0
assertBool "Workarea width is positive" $ w > 0
assertBool "Workarea height is positive" $ h > 0
test_glfwGetVideoModes :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetVideoModes p'mon =
alloca $ \p'n -> do
p'vms <- c'glfwGetVideoModes p'mon p'n
n <- fromIntegral `fmap` peek p'n
if p'vms == nullPtr || n <= 0
then assertFailure ""
else do
vms <- peekArray n p'vms
assertBool "" $ all videoModeLooksValid vms
test_glfwGetVideoMode :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetVideoMode p'mon = do
p'vm <- c'glfwGetVideoMode p'mon
if p'vm == nullPtr
then assertFailure ""
else do
vm <- peek p'vm
assertBool "" $ videoModeLooksValid vm
test_glfwGetGammaRamp :: Ptr C'GLFWmonitor -> IO ()
test_glfwGetGammaRamp p'mon = do
p'gr <- c'glfwGetGammaRamp p'mon
if p'gr == nullPtr
then assertFailure ""
else do
gr <- peek p'gr
let p'rs = c'GLFWgammaramp'red gr
p'gs = c'GLFWgammaramp'green gr
p'bs = c'GLFWgammaramp'blue gr
cn = c'GLFWgammaramp'size gr
n = fromIntegral cn
if nullPtr `elem` [p'rs, p'gs, p'bs]
then assertFailure ""
else do
rs <- peekArray n p'rs
gs <- peekArray n p'gs
bs <- peekArray n p'bs
let rsl = length rs
gsl = length gs
bsl = length bs
assertBool "" $ rsl > 0 && rsl == gsl && gsl == bsl
--------------------------------------------------------------------------------
test_glfwDefaultWindowHints :: IO ()
test_glfwDefaultWindowHints =
c'glfwDefaultWindowHints
test_window_close_flag :: Ptr C'GLFWwindow -> IO ()
test_window_close_flag p'win = do
r0 <- c'glfwWindowShouldClose p'win
r0 @?= c'GLFW_FALSE
c'glfwSetWindowShouldClose p'win c'GLFW_TRUE
r1 <- c'glfwWindowShouldClose p'win
r1 @?= c'GLFW_TRUE
c'glfwSetWindowShouldClose p'win c'GLFW_FALSE
r2 <- c'glfwWindowShouldClose p'win
r2 @?= c'GLFW_FALSE
test_glfwSetWindowTitle :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowTitle p'win =
withCString "some new title" $
c'glfwSetWindowTitle p'win
-- This is a little strange. Depending on your window manager, etc, after
-- setting the window position to (x,y), the actual new window position might
-- be (x+5,y+5) due to borders. So we just check for consistency.
test_window_pos :: Ptr C'GLFWwindow -> IO ()
test_window_pos p'win = do
let x = 17
y = 37
xoff = 53
yoff = 149
(x0, y0, dx0, dy0) <- setGet x y
(x1, y1, dx1, dy1) <- setGet (x+xoff) (y+yoff)
dx0 @?= dx1
dy0 @?= dy1
x1 - x0 @?= xoff
y1 - y0 @?= yoff
where
setGet :: Int -> Int -> IO (Int, Int, Int, Int)
setGet x0 y0 = do
c'glfwSetWindowPos p'win (fromIntegral x0) (fromIntegral y0)
c'glfwSwapBuffers p'win
giveItTime
alloca $ \p'x1 ->
alloca $ \p'y1 -> do
c'glfwGetWindowPos p'win p'x1 p'y1
x1 <- fromIntegral `fmap` peek p'x1
y1 <- fromIntegral `fmap` peek p'y1
let (dx, dy) = (x0-x1, y0-y1)
return (x1, y1, dx, dy)
test_window_size :: Ptr C'GLFWwindow -> IO ()
test_window_size p'win = do
let w = 177
h = 372
c'glfwSetWindowSize p'win w h
giveItTime
alloca $ \p'w' ->
alloca $ \p'h' -> do
c'glfwGetWindowSize p'win p'w' p'h'
w' <- fromIntegral `fmap` peek p'w'
h' <- fromIntegral `fmap` peek p'h'
w' @?= w
h' @?= h
-- Really all we can say here is that we likely have a title bar, so just check
-- that the 'frame' around the top edge is > 0.
test_glfwGetWindowFrameSize :: Ptr C'GLFWwindow -> IO ()
test_glfwGetWindowFrameSize p'win =
alloca $ \p'win_frame_top -> do
c'glfwGetWindowFrameSize p'win nullPtr p'win_frame_top nullPtr nullPtr
top <- peek p'win_frame_top
assertBool "Window has no frame width up top!" $ top > 0
test_glfwGetFramebufferSize :: Ptr C'GLFWwindow -> IO ()
test_glfwGetFramebufferSize p'win =
alloca $ \p'w ->
alloca $ \p'h ->
alloca $ \p'fw ->
alloca $ \p'fh -> do
c'glfwGetWindowSize p'win p'w p'h
c'glfwGetFramebufferSize p'win p'fw p'fh
w <- peek p'w
h <- peek p'h
fw <- peek p'fw
fh <- peek p'fh
((fw `mod` w) == 0) @? "Framebuffer width multiple of window's"
((fh `mod` h) == 0) @? "Framebuffer height multiple of window's"
test_iconification :: Ptr C'GLFWwindow -> IO ()
test_iconification p'win = do
c'glfwShowWindow p'win
r0 <- c'glfwGetWindowAttrib p'win c'GLFW_ICONIFIED
r0 @?= c'GLFW_FALSE
c'glfwIconifyWindow p'win
giveItTime
r1 <- c'glfwGetWindowAttrib p'win c'GLFW_ICONIFIED
r1 @?= c'GLFW_TRUE
c'glfwRestoreWindow p'win
c'glfwHideWindow p'win
-- test_show_hide :: Ptr C'GLFWwindow -> IO ()
-- test_show_hide p'win = do
-- v0 <- c'glfwGetWindowAttrib p'win c'GLFW_VISIBLE
-- v0 @?= c'GLFW_FALSE
-- c'glfwShowWindow p'win
-- giveItTime
-- v1 <- c'glfwGetWindowAttrib p'win c'GLFW_VISIBLE
-- v1 @?= c'GLFW_TRUE
-- c'glfwHideWindow p'win
-- giveItTime
-- v2 <- c'glfwGetWindowAttrib p'win c'GLFW_VISIBLE
-- v2 @?= c'GLFW_FALSE
test_glfwGetWindowContentScale :: Ptr C'GLFWwindow -> IO ()
test_glfwGetWindowContentScale p'win =
alloca $ \p'x ->
alloca $ \p'y -> do
c'glfwGetWindowContentScale p'win p'x p'y
x <- peek p'x
y <- peek p'y
assertBool "Window content scale x is defined" $ x > 0
assertBool "Window content scale y is defined" $ y > 0
test_glfwGetWindowMonitor :: Ptr C'GLFWwindow -> Ptr C'GLFWmonitor -> IO ()
test_glfwGetWindowMonitor p'win _ = do
p'mon <- c'glfwGetWindowMonitor p'win
p'mon @?= nullPtr
test_glfwSetWindowMonitor :: Ptr C'GLFWwindow -> Ptr C'GLFWmonitor -> IO ()
test_glfwSetWindowMonitor p'win _ = do
c'glfwSetWindowMonitor p'win nullPtr 0 0 100 100 60
test_glfwSetWindowIcon :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowIcon p'win = do
c'glfwSetWindowIcon p'win 0 nullPtr
test_glfwSetWindowOpacity :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowOpacity p'win = do
let desiredOpacity = 0.27
c'glfwSetWindowOpacity p'win desiredOpacity
newOpacity <- c'glfwGetWindowOpacity p'win
assertBool "Opacity is roughly the same." $
abs (desiredOpacity - newOpacity) < 0.01
c'glfwSetWindowOpacity p'win 1.0
test_glfwSetWindowSizeLimits :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowSizeLimits p'win = do
c'glfwSetWindowSizeLimits p'win 640 480 1024 768
test_glfwSetWindowAspectRatio :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowAspectRatio p'win = do
c'glfwSetWindowAspectRatio p'win c'GLFW_DONT_CARE c'GLFW_DONT_CARE
test_glfwFocusWindow :: Ptr C'GLFWwindow -> IO ()
test_glfwFocusWindow = c'glfwFocusWindow
test_glfwRequestWindowAttention :: Ptr C'GLFWwindow -> IO ()
test_glfwRequestWindowAttention = c'glfwRequestWindowAttention
-- NOTE: This test seems to fail in X11. This might be due to the asynchronous
-- nature of focus events in X. We may be able to fix it by waiting for the focus
-- event before setting the cursor position.
test_cursor_pos :: Ptr C'GLFWwindow -> IO ()
test_cursor_pos p'win =
alloca $ \p'w ->
alloca $ \p'h ->
alloca $ \p'cx' ->
alloca $ \p'cy' -> do
c'glfwShowWindow p'win
c'glfwGetWindowSize p'win p'w p'h
w <- peek p'w
h <- peek p'h
-- Make sure we use integral coordinates here so that we don't run into
-- platform-dependent differences.
let cx :: CDouble
cy :: CDouble
(cx, cy) = (fromIntegral $ w `div` 2, fromIntegral $ h `div` 2)
-- !HACK! Poll events seems to be necessary on OS X,
-- before /and/ after glfwSetCursorPos, otherwise, the
-- windowing system likely never receives the cursor update. This is
-- reflected in the C version of GLFW as well, we just call it here in
-- order to have a more robust test.
c'glfwPollEvents
c'glfwSetCursorPos p'win cx cy
c'glfwPollEvents -- !HACK! see comment above
c'glfwGetCursorPos p'win p'cx' p'cy'
cx' <- peek p'cx'
cy' <- peek p'cy'
cx' @?= cx
cy' @?= cy
c'glfwHideWindow p'win
test_glfwGetWindowAttrib :: Ptr C'GLFWwindow -> IO ()
test_glfwGetWindowAttrib p'win = do
let pairs =
[ ( c'GLFW_FOCUSED, c'GLFW_FALSE )
, ( c'GLFW_ICONIFIED, c'GLFW_FALSE )
, ( c'GLFW_RESIZABLE, c'GLFW_TRUE )
, ( c'GLFW_DECORATED, c'GLFW_TRUE )
, ( c'GLFW_CLIENT_API, c'GLFW_OPENGL_API )
]
rs <- mapM (c'glfwGetWindowAttrib p'win . fst) pairs
rs @?= map snd pairs
test_glfwSetWindowAttrib :: Ptr C'GLFWwindow -> IO ()
test_glfwSetWindowAttrib p'win = do
c'glfwSetWindowAttrib p'win c'GLFW_RESIZABLE c'GLFW_FALSE
norsz <- c'glfwGetWindowAttrib p'win c'GLFW_RESIZABLE
norsz @?= c'GLFW_FALSE
c'glfwSetWindowAttrib p'win c'GLFW_RESIZABLE c'GLFW_TRUE
rsz <- c'glfwGetWindowAttrib p'win c'GLFW_RESIZABLE
rsz @?= c'GLFW_TRUE
test_glfwMaximizeWindow :: Ptr C'GLFWwindow -> IO ()
test_glfwMaximizeWindow p'win = do
c'glfwShowWindow p'win
startsMaximized <- c'glfwGetWindowAttrib p'win c'GLFW_MAXIMIZED
startsMaximized @?= c'GLFW_FALSE
c'glfwMaximizeWindow p'win
giveItTime
isMaximized <- c'glfwGetWindowAttrib p'win c'GLFW_MAXIMIZED
isMaximized @?= c'GLFW_TRUE
c'glfwHideWindow p'win
test_glfwPollEvents :: IO ()
test_glfwPollEvents = c'glfwPollEvents
test_glfwWaitEvents :: IO ()
test_glfwWaitEvents = c'glfwPostEmptyEvent >> c'glfwWaitEvents
test_glfwWaitEventsTimeout :: IO ()
test_glfwWaitEventsTimeout =
-- to not slow down the test too much we set the timeout to 0.001 second :
c'glfwWaitEventsTimeout 0.001
--------------------------------------------------------------------------------
test_glfwJoystickPresent :: IO ()
test_glfwJoystickPresent = do
_ <- c'glfwJoystickPresent c'GLFW_JOYSTICK_1
r <- c'glfwJoystickPresent c'GLFW_JOYSTICK_16
r @?= c'GLFW_FALSE
test_glfwGetJoystickAxes :: IO ()
test_glfwGetJoystickAxes =
forM_ joysticks $ \js ->
alloca $ \p'n -> do
p'axes <- c'glfwGetJoystickAxes js p'n
when (p'axes /= nullPtr) $ do
n <- fromIntegral `fmap` peek p'n
if n <= 0
then assertFailure ""
else do
axes <- peekArray n p'axes
length axes @?= n
test_glfwGetJoystickButtons :: IO ()
test_glfwGetJoystickButtons =
forM_ joysticks $ \js ->
alloca $ \p'n -> do
p'buttons <- c'glfwGetJoystickButtons js p'n
when (p'buttons /= nullPtr) $ do
n <- fromIntegral `fmap` peek p'n
if n <= 0
then assertFailure ""
else do
buttons <- peekArray n p'buttons
length buttons @?= n
test_glfwGetJoystickHats :: IO ()
test_glfwGetJoystickHats =
forM_ joysticks $ \js ->
alloca $ \p'n -> do
p'hats <- c'glfwGetJoystickHats js p'n
when (p'hats /= nullPtr) $ do
n <- fromIntegral `fmap` peek p'n
if n <= 0
then assertFailure "No joystick hats??"
else do
hats <- peekArray n p'hats
length hats @?= n
forM_ hats $ assertEqual "Hat is centered" c'GLFW_HAT_CENTERED
test_glfwGetJoystickName :: IO ()
test_glfwGetJoystickName =
forM_ joysticks $ \js -> do
p'name <- c'glfwGetJoystickName js
when (p'name /= nullPtr) $ do
name <- peekCString p'name
assertBool "" $ not $ null name
test_glfwGetJoystickGUID :: IO ()
test_glfwGetJoystickGUID =
forM_ joysticks $ \js -> do
p'guid <- c'glfwGetJoystickGUID js
when (p'guid /= nullPtr) $ do
guid <- peekCString p'guid
assertBool "" $ not $ null guid
test_glfwGetGamepadState :: IO ()
test_glfwGetGamepadState =
forM_ joysticks $ \js ->
alloca $ \p'gp -> do
gotMapping <- c'glfwGetGamepadState js p'gp
when (gotMapping == c'GLFW_TRUE) $ do
assertBool "Gamepad state is valid" (p'gp /= nullPtr)
c'glfwJoystickIsGamepad js
>>= assertEqual "Is gamepad" c'GLFW_TRUE
c'glfwGetGamepadName js
>>= peekCString
>>= assertBool "Gamepad has name" . not . null
gp <- peek p'gp
forM_ (c'GLFWgamepadstate'buttons gp) $
assertEqual "Button not pressed" c'GLFW_RELEASE
test_glfwGetKeyName :: IO ()
test_glfwGetKeyName =
forM_ [c'GLFW_KEY_SLASH, c'GLFW_KEY_PERIOD] $ \k -> do
p'name <- c'glfwGetKeyName k 0
when (p'name /= nullPtr) $ do
name <- peekCString p'name
assertBool "" $ not $ null name
test_glfwGetKeyScancode :: IO ()
test_glfwGetKeyScancode = do
forM_ [c'GLFW_KEY_SLASH, c'GLFW_KEY_PERIOD] $ \k -> do
sc <- c'glfwGetKeyScancode k
assertBool (mconcat ["Key ", show k, " scancode not found."]) (sc > 0)
-- According to the docs this should work but it returns 0. This is a GLFW
-- bug (at least on OS X).
-- c'glfwGetKeyScancode c'GLFW_KEY_UNKNOWN >>= assertEqual "" (-1)
--------------------------------------------------------------------------------
test_glfwGetTime :: IO ()
test_glfwGetTime = do
t <- c'glfwGetTime
assertBool "" $ t > 0
test_glfwSetTime :: IO ()
test_glfwSetTime = do
let t = 37 :: Double
c'glfwSetTime (realToFrac t)
t' <- realToFrac `fmap` c'glfwGetTime
assertBool "" $ t' `between` (t, t+10)
test_glfwGetTimerValue :: IO ()
test_glfwGetTimerValue = do
val <- c'glfwGetTimerValue
assertBool "" $ val > 0
test_glfwGetTimerFrequency :: IO ()
test_glfwGetTimerFrequency = do
freq <- c'glfwGetTimerFrequency
assertBool "" $ freq > 0
--------------------------------------------------------------------------------
test_glfwGetCurrentContext :: Ptr C'GLFWwindow -> IO ()
test_glfwGetCurrentContext p'win = do
p'win' <- c'glfwGetCurrentContext
p'win' @?= p'win
test_glfwSwapBuffers :: Ptr C'GLFWwindow -> IO ()
test_glfwSwapBuffers =
c'glfwSwapBuffers
test_glfwSwapInterval :: IO ()
test_glfwSwapInterval =
c'glfwSwapInterval 1
test_glfwExtensionSupported :: IO ()
test_glfwExtensionSupported = do
let pairs =
[ ( "GL_ARB_multisample", c'GLFW_TRUE )
, ( "bogus", c'GLFW_FALSE )
]
rs <- forM (map fst pairs) $ \ext ->
withCString ext c'glfwExtensionSupported
rs @?= map snd pairs
--------------------------------------------------------------------------------
test_clipboard :: Ptr C'GLFWwindow -> IO ()
test_clipboard p'win = do
rs <- mapM setGet ss
rs @?= ss
where
ss =
[ "abc 123 ???"
, "xyz 456 !!!"
]
setGet s = do
withCString s $ c'glfwSetClipboardString p'win
threadDelay 100000 -- Give it a little time
p's' <- c'glfwGetClipboardString p'win
-- See if we generated a known error for the clipboard, which would
-- indicate that the format is not supported.
errResult <- c'glfwGetError nullPtr
if errResult == c'GLFW_FORMAT_UNAVAILABLE
then return s
else if errResult == c'GLFW_NO_ERROR then do
if p's' == nullPtr
then return ""
else peekCString p's'
else do
assertFailure "Unexpected error from clipboard"
--------------------------------------------------------------------------------
test_glfwVulkanSupported :: IO ()
test_glfwVulkanSupported =
-- Just test that it doesn't error. If it does, then we have a problem, but
-- some platforms (like OS X) don't actually support vulkan.
c'glfwVulkanSupported >> return ()
test_glfwGetRequiredInstanceExtensions :: IO ()
test_glfwGetRequiredInstanceExtensions = do
support <- c'glfwVulkanSupported
when (support == c'GLFW_TRUE) $
alloca $ \p'count -> do
p'exts <- c'glfwGetRequiredInstanceExtensions p'count
when (p'exts /= nullPtr) $ do
count <- peek p'count
assertBool "Got at least some extensions" $ count > 0
test_glfwGetInstanceProcAddress :: IO ()
test_glfwGetInstanceProcAddress = do
support <- c'glfwVulkanSupported
when (support == c'GLFW_TRUE) $ do
shouldBeNull <- withCString "notafunction" $
\s -> c'glfwGetInstanceProcAddress nullPtr s
shouldBeNull @?= nullFunPtr
assertBool "Function pointer is defined!" $
p'glfwGetInstanceProcAddress /= nullFunPtr
test_glfwGetPhysicalDevicePresentationSupport :: IO ()
test_glfwGetPhysicalDevicePresentationSupport = do
-- We don't really have the proper types to test this function
support <- c'glfwVulkanSupported
when (support == c'GLFW_TRUE) $ do
shouldBeFalse <-
c'glfwGetPhysicalDevicePresentationSupport nullPtr nullPtr 0
shouldBeFalse @?= c'GLFW_FALSE
-- If we pass a nullptr for the instance here then we better get a
-- GLFW_API_UNAVAILABLE error since we didn't create the instance with
-- the proper extensions...
alloca $ \p'errMsg ->
c'glfwGetError p'errMsg >>=
assertEqual "Got proper vulkan error" c'GLFW_API_UNAVAILABLE
assertBool "Function pointer is defined!" $
p'glfwGetPhysicalDevicePresentationSupport /= nullFunPtr
test_glfwCreateWindowSurface :: Ptr C'GLFWwindow -> IO ()
test_glfwCreateWindowSurface p'win = do
-- We don't really have the proper types to test this function
support <- c'glfwVulkanSupported
when (support == c'GLFW_TRUE) $ do
alloca $ \p'surface -> do
let resPtr = p'surface :: Ptr ()
shouldNotBeSuccessful <-
c'glfwCreateWindowSurface nullPtr p'win nullPtr resPtr
assertBool "c'glfwCreateSurface was successful??" $
shouldNotBeSuccessful /= 0
-- The window that we pass here was not created with GLFW_NO_API, so
-- the proper error received here seems to be GLFW_INVALID_VALUE
alloca $ \p'errMsg ->
c'glfwGetError p'errMsg >>=
assertEqual "Got proper vulkan error" c'GLFW_INVALID_VALUE
assertBool "Function pointer is defined!" $
p'glfwCreateWindowSurface /= nullFunPtr
{-# ANN module "HLint: ignore Use camelCase" #-}
|
bsl/bindings-GLFW
|
Test.hs
|
Haskell
|
bsd-2-clause
| 31,062
|
{-# LANGUAGE DataKinds, EmptyDataDecls, TypeOperators, UndecidableInstances #-}
module HaskHOL.Lib.Pair.Context
( PairType
, PairThry
, PairCtxt
, ctxtPair
) where
import HaskHOL.Core
import HaskHOL.Deductive hiding (newDefinition)
import qualified HaskHOL.Deductive as D (newDefinition)
import HaskHOL.Lib.Pair.Base
data PairThry
type instance PairThry == PairThry = 'True
instance CtxtName PairThry where
ctxtName _ = "PairCtxt"
type instance PolyTheory PairType b = PairCtxt b
type family PairCtxt a :: Constraint where
PairCtxt a = (Typeable a, DeductiveCtxt a, PairContext a ~ 'True)
type PairType = ExtThry PairThry DeductiveType
type family PairContext a :: Bool where
PairContext UnsafeThry = 'True
PairContext BaseThry = 'False
PairContext (ExtThry a b) = PairContext b || (a == PairThry)
ctxtPair :: TheoryPath PairType
ctxtPair = extendTheory ctxtDeductive $(thisModule') $
-- stage1
do defs1 <- mapM D.newDefinition
[ ("LET", [txt| LET (f:A->B) x = f x |])
, ("LET_END", [txt| LET_END (t:A) = t |])
, ("GABS", [txt| GABS (P:A->bool) = (@) P |])
, ("GEQ", [txt| GEQ a b = (a:A = b) |])
, ("mk_pair", [txt| mk_pair (x:A) (y:B) =
\ a b. (a = x) /\ (b = y) |])
]
mapM_ D.newDefinition
[ ("_SEQPATTERN", [txt| _SEQPATTERN = \ r s x. if ? y. r x y
then r x else s x |])
, ("_UNGUARDED_PATTERN", [txt| _UNGUARDED_PATTERN = \ p r. p /\ r |])
, ("_GUARDED_PATTERN",[txt| _GUARDED_PATTERN = \ p g r. p /\ g /\ r |])
, ("_MATCH", [txt| _MATCH = \ e r. if (?!) (r e)
then (@) (r e) else @ z. F |])
, ("_FUNCTION", [txt| _FUNCTION = \ r x. if (?!) (r x)
then (@) (r x) else @ z. F |])
]
-- stage2
void $ newTypeDefinition "prod" "ABS_prod" "REP_prod" thmPAIR_EXISTS
parseAsInfix (",", (14, "right"))
defs2 <- mapM D.newDefinition
[ (",", [txt| ((x:A), (y:B)) = ABS_prod(mk_pair x y) |])
, ("FST", [txt| FST (p:A#B) = @ x. ? y. p = (x, y) |])
, ("SND", [txt| SND (p:A#B) = @ y. ? x. p = (x, y) |])
]
-- stage3
extendBasicRewrites [thmFST, thmSND, thmPAIR]
defs3 <- sequence [ def_one, defI, defO, defCOND, def_FALSITY_
, defTY_EXISTS, defTY_FORALL
, defEXISTS_UNIQUE, defEXISTS, defFORALL
, defNOT, defOR, defIMP, defAND
, defFALSE, defT
]
let ths' = zip [ "LET", "LET_END", "GABS", "GEQ", "mk_pair"
, ",", "FST", "SND"
, "one", "I", "o", "COND", "_FALSITY_"
, "??", "!!", "?!", "?", "!", "~", "\\/", "==>", "/\\"
, "F", "T"
] $ defs1 ++ defs2 ++ defs3
acid <- openLocalStateHOL (Definitions mapEmpty)
updateHOL acid (AddDefinitions ths')
closeAcidStateHOL acid
mapM_ newDefinition
[ ("CURRY", [txt| CURRY(f:A#B->C) x y = f(x,y) |])
, ("UNCURRY", [txt| !f x y. UNCURRY(f:A->B->C)(x,y) = f x y |])
, ("PASSOC", [txt| !f x y z. PASSOC (f:(A#B)#C->D) (x,y,z) =
f ((x,y),z) |])
]
-- stage4
addIndDef ("prod", (1, inductPAIR, recursionPAIR))
extendBasicConvs [("convGEN_BETA",
([txt| GABS (\ a. b) c |], "HaskHOL.Lib.Pair"))]
|
ecaustin/haskhol-math
|
src/HaskHOL/Lib/Pair/Context.hs
|
Haskell
|
bsd-2-clause
| 3,729
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTableWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:26
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTableWidget (
QqTableWidget(..)
,cellWidget
,clearContents
,removeCellWidget
,selectedRanges
,setCellWidget
,setCurrentCell
,setRangeSelected
,visualColumn
,visualRow
,qTableWidget_delete
,qTableWidget_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 (QTableWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QTableWidget_userMethod" qtc_QTableWidget_userMethod :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QuserMethod (QTableWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QTableWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QTableWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTableWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QTableWidget_userMethodVariant" qtc_QTableWidget_userMethodVariant :: Ptr (TQTableWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QTableWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QTableWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqTableWidget x1 where
qTableWidget :: x1 -> IO (QTableWidget ())
instance QqTableWidget (()) where
qTableWidget ()
= withQTableWidgetResult $
qtc_QTableWidget
foreign import ccall "qtc_QTableWidget" qtc_QTableWidget :: IO (Ptr (TQTableWidget ()))
instance QqTableWidget ((QWidget t1)) where
qTableWidget (x1)
= withQTableWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget1 cobj_x1
foreign import ccall "qtc_QTableWidget1" qtc_QTableWidget1 :: Ptr (TQWidget t1) -> IO (Ptr (TQTableWidget ()))
instance QqTableWidget ((Int, Int)) where
qTableWidget (x1, x2)
= withQTableWidgetResult $
qtc_QTableWidget2 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget2" qtc_QTableWidget2 :: CInt -> CInt -> IO (Ptr (TQTableWidget ()))
instance QqTableWidget ((Int, Int, QWidget t3)) where
qTableWidget (x1, x2, x3)
= withQTableWidgetResult $
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTableWidget3 (toCInt x1) (toCInt x2) cobj_x3
foreign import ccall "qtc_QTableWidget3" qtc_QTableWidget3 :: CInt -> CInt -> Ptr (TQWidget t3) -> IO (Ptr (TQTableWidget ()))
cellWidget :: QTableWidget a -> ((Int, Int)) -> IO (QWidget ())
cellWidget x0 (x1, x2)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_cellWidget cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_cellWidget" qtc_QTableWidget_cellWidget :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQWidget ()))
instance Qclear (QTableWidget a) (()) where
clear x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_clear cobj_x0
foreign import ccall "qtc_QTableWidget_clear" qtc_QTableWidget_clear :: Ptr (TQTableWidget a) -> IO ()
clearContents :: QTableWidget a -> (()) -> IO ()
clearContents x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_clearContents cobj_x0
foreign import ccall "qtc_QTableWidget_clearContents" qtc_QTableWidget_clearContents :: Ptr (TQTableWidget a) -> IO ()
instance QclosePersistentEditor (QTableWidget a) ((QTableWidgetItem t1)) where
closePersistentEditor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closePersistentEditor cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_closePersistentEditor" qtc_QTableWidget_closePersistentEditor :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
instance Qcolumn (QTableWidget a) ((QTableWidgetItem t1)) where
column x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_column cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_column" qtc_QTableWidget_column :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO CInt
instance QcolumnCount (QTableWidget a) (()) where
columnCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnCount cobj_x0
foreign import ccall "qtc_QTableWidget_columnCount" qtc_QTableWidget_columnCount :: Ptr (TQTableWidget a) -> IO CInt
instance QcurrentColumn (QTableWidget a) (()) where
currentColumn x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_currentColumn cobj_x0
foreign import ccall "qtc_QTableWidget_currentColumn" qtc_QTableWidget_currentColumn :: Ptr (TQTableWidget a) -> IO CInt
instance QcurrentItem (QTableWidget a) (()) (IO (QTableWidgetItem ())) where
currentItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_currentItem cobj_x0
foreign import ccall "qtc_QTableWidget_currentItem" qtc_QTableWidget_currentItem :: Ptr (TQTableWidget a) -> IO (Ptr (TQTableWidgetItem ()))
instance QcurrentRow (QTableWidget a) (()) where
currentRow x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_currentRow cobj_x0
foreign import ccall "qtc_QTableWidget_currentRow" qtc_QTableWidget_currentRow :: Ptr (TQTableWidget a) -> IO CInt
instance QdropEvent (QTableWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dropEvent_h" qtc_QTableWidget_dropEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QTableWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dropEvent_h cobj_x0 cobj_x1
instance QdropMimeData (QTableWidget ()) ((Int, Int, QMimeData t3, DropAction)) where
dropMimeData x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTableWidget_dropMimeData cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
foreign import ccall "qtc_QTableWidget_dropMimeData" qtc_QTableWidget_dropMimeData :: Ptr (TQTableWidget a) -> CInt -> CInt -> Ptr (TQMimeData t3) -> CLong -> IO CBool
instance QdropMimeData (QTableWidgetSc a) ((Int, Int, QMimeData t3, DropAction)) where
dropMimeData x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTableWidget_dropMimeData cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
instance QeditItem (QTableWidget a) ((QTableWidgetItem t1)) where
editItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_editItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_editItem" qtc_QTableWidget_editItem :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
instance Qevent (QTableWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_event_h" qtc_QTableWidget_event_h :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QTableWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_event_h cobj_x0 cobj_x1
instance QfindItems (QTableWidget a) ((String, MatchFlags)) (IO ([QTableWidgetItem ()])) where
findItems x0 (x1, x2)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_findItems cobj_x0 cstr_x1 (toCLong $ qFlags_toInt x2) arr
foreign import ccall "qtc_QTableWidget_findItems" qtc_QTableWidget_findItems :: Ptr (TQTableWidget a) -> CWString -> CLong -> Ptr (Ptr (TQTableWidgetItem ())) -> IO CInt
instance QhorizontalHeaderItem (QTableWidget a) ((Int)) (IO (QTableWidgetItem ())) where
horizontalHeaderItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalHeaderItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_horizontalHeaderItem" qtc_QTableWidget_horizontalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QindexFromItem (QTableWidget ()) ((QTableWidgetItem t1)) where
indexFromItem x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexFromItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_indexFromItem" qtc_QTableWidget_indexFromItem :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO (Ptr (TQModelIndex ()))
instance QindexFromItem (QTableWidgetSc a) ((QTableWidgetItem t1)) where
indexFromItem x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexFromItem cobj_x0 cobj_x1
instance QinsertColumn (QTableWidget ()) ((Int)) (IO ()) where
insertColumn x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_insertColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_insertColumn" qtc_QTableWidget_insertColumn :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QinsertColumn (QTableWidgetSc a) ((Int)) (IO ()) where
insertColumn x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_insertColumn cobj_x0 (toCInt x1)
instance QinsertRow (QTableWidget ()) ((Int)) (IO ()) where
insertRow x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_insertRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_insertRow" qtc_QTableWidget_insertRow :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QinsertRow (QTableWidgetSc a) ((Int)) (IO ()) where
insertRow x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_insertRow cobj_x0 (toCInt x1)
instance QisItemSelected (QTableWidget a) ((QTableWidgetItem t1)) where
isItemSelected x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_isItemSelected cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_isItemSelected" qtc_QTableWidget_isItemSelected :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO CBool
instance QisSortingEnabled (QTableWidget ()) (()) where
isSortingEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_isSortingEnabled cobj_x0
foreign import ccall "qtc_QTableWidget_isSortingEnabled" qtc_QTableWidget_isSortingEnabled :: Ptr (TQTableWidget a) -> IO CBool
instance QisSortingEnabled (QTableWidgetSc a) (()) where
isSortingEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_isSortingEnabled cobj_x0
instance Qitem (QTableWidget a) ((Int, Int)) (IO (QTableWidgetItem ())) where
item x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_item cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_item" qtc_QTableWidget_item :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QitemAt (QTableWidget a) ((Int, Int)) (IO (QTableWidgetItem ())) where
itemAt x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_itemAt1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_itemAt1" qtc_QTableWidget_itemAt1 :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QitemAt (QTableWidget a) ((Point)) (IO (QTableWidgetItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_itemAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTableWidget_itemAt_qth" qtc_QTableWidget_itemAt_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QqitemAt (QTableWidget a) ((QPoint t1)) (IO (QTableWidgetItem ())) where
qitemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_itemAt cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_itemAt" qtc_QTableWidget_itemAt :: Ptr (TQTableWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQTableWidgetItem ()))
instance QitemFromIndex (QTableWidget ()) ((QModelIndex t1)) (IO (QTableWidgetItem ())) where
itemFromIndex x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_itemFromIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_itemFromIndex" qtc_QTableWidget_itemFromIndex :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQTableWidgetItem ()))
instance QitemFromIndex (QTableWidgetSc a) ((QModelIndex t1)) (IO (QTableWidgetItem ())) where
itemFromIndex x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_itemFromIndex cobj_x0 cobj_x1
instance QitemPrototype (QTableWidget a) (()) (IO (QTableWidgetItem ())) where
itemPrototype x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_itemPrototype cobj_x0
foreign import ccall "qtc_QTableWidget_itemPrototype" qtc_QTableWidget_itemPrototype :: Ptr (TQTableWidget a) -> IO (Ptr (TQTableWidgetItem ()))
instance Qitems (QTableWidget ()) ((QMimeData t1)) (IO ([QTableWidgetItem ()])) where
items x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_items cobj_x0 cobj_x1 arr
foreign import ccall "qtc_QTableWidget_items" qtc_QTableWidget_items :: Ptr (TQTableWidget a) -> Ptr (TQMimeData t1) -> Ptr (Ptr (TQTableWidgetItem ())) -> IO CInt
instance Qitems (QTableWidgetSc a) ((QMimeData t1)) (IO ([QTableWidgetItem ()])) where
items x0 (x1)
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_items cobj_x0 cobj_x1 arr
instance QopenPersistentEditor (QTableWidget a) ((QTableWidgetItem t1)) where
openPersistentEditor x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_openPersistentEditor cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_openPersistentEditor" qtc_QTableWidget_openPersistentEditor :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
removeCellWidget :: QTableWidget a -> ((Int, Int)) -> IO ()
removeCellWidget x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_removeCellWidget cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_removeCellWidget" qtc_QTableWidget_removeCellWidget :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QremoveColumn (QTableWidget a) ((Int)) (IO ()) where
removeColumn x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_removeColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_removeColumn" qtc_QTableWidget_removeColumn :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QremoveRow (QTableWidget a) ((Int)) (IO ()) where
removeRow x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_removeRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_removeRow" qtc_QTableWidget_removeRow :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance Qrow (QTableWidget a) ((QTableWidgetItem t1)) where
row x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_row cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_row" qtc_QTableWidget_row :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO CInt
instance QrowCount (QTableWidget a) (()) where
rowCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowCount cobj_x0
foreign import ccall "qtc_QTableWidget_rowCount" qtc_QTableWidget_rowCount :: Ptr (TQTableWidget a) -> IO CInt
instance QscrollToItem (QTableWidget a) ((QTableWidgetItem t1)) where
scrollToItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollToItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_scrollToItem" qtc_QTableWidget_scrollToItem :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
instance QscrollToItem (QTableWidget a) ((QTableWidgetItem t1, ScrollHint)) where
scrollToItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollToItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTableWidget_scrollToItem1" qtc_QTableWidget_scrollToItem1 :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> CLong -> IO ()
instance QselectedItems (QTableWidget a) (()) (IO ([QTableWidgetItem ()])) where
selectedItems x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectedItems cobj_x0 arr
foreign import ccall "qtc_QTableWidget_selectedItems" qtc_QTableWidget_selectedItems :: Ptr (TQTableWidget a) -> Ptr (Ptr (TQTableWidgetItem ())) -> IO CInt
selectedRanges :: QTableWidget a -> (()) -> IO ([QTableWidgetSelectionRange ()])
selectedRanges x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectedRanges cobj_x0 arr
foreign import ccall "qtc_QTableWidget_selectedRanges" qtc_QTableWidget_selectedRanges :: Ptr (TQTableWidget a) -> Ptr (Ptr (TQTableWidgetSelectionRange ())) -> IO CInt
setCellWidget :: QTableWidget a -> ((Int, Int, QWidget t3)) -> IO ()
setCellWidget x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTableWidget_setCellWidget cobj_x0 (toCInt x1) (toCInt x2) cobj_x3
foreign import ccall "qtc_QTableWidget_setCellWidget" qtc_QTableWidget_setCellWidget :: Ptr (TQTableWidget a) -> CInt -> CInt -> Ptr (TQWidget t3) -> IO ()
instance QsetColumnCount (QTableWidget a) ((Int)) where
setColumnCount x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setColumnCount cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_setColumnCount" qtc_QTableWidget_setColumnCount :: Ptr (TQTableWidget a) -> CInt -> IO ()
setCurrentCell :: QTableWidget a -> ((Int, Int)) -> IO ()
setCurrentCell x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setCurrentCell cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_setCurrentCell" qtc_QTableWidget_setCurrentCell :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QsetCurrentItem (QTableWidget a) ((QTableWidgetItem t1)) where
setCurrentItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setCurrentItem cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setCurrentItem" qtc_QTableWidget_setCurrentItem :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
instance QsetHorizontalHeaderItem (QTableWidget a) ((Int, QTableWidgetItem t2)) where
setHorizontalHeaderItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_setHorizontalHeaderItem cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QTableWidget_setHorizontalHeaderItem" qtc_QTableWidget_setHorizontalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> Ptr (TQTableWidgetItem t2) -> IO ()
instance QsetHorizontalHeaderLabels (QTableWidget a) (([String])) where
setHorizontalHeaderLabels x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QTableWidget_setHorizontalHeaderLabels cobj_x0 cqlistlen_x1 cqliststr_x1
foreign import ccall "qtc_QTableWidget_setHorizontalHeaderLabels" qtc_QTableWidget_setHorizontalHeaderLabels :: Ptr (TQTableWidget a) -> CInt -> Ptr (Ptr CWchar) -> IO ()
instance QsetItem (QTableWidget a) ((Int, Int, QTableWidgetItem t3)) where
setItem x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTableWidget_setItem cobj_x0 (toCInt x1) (toCInt x2) cobj_x3
foreign import ccall "qtc_QTableWidget_setItem" qtc_QTableWidget_setItem :: Ptr (TQTableWidget a) -> CInt -> CInt -> Ptr (TQTableWidgetItem t3) -> IO ()
instance QsetItemPrototype (QTableWidget a) ((QTableWidgetItem t1)) where
setItemPrototype x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setItemPrototype cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setItemPrototype" qtc_QTableWidget_setItemPrototype :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO ()
instance QsetItemSelected (QTableWidget a) ((QTableWidgetItem t1, Bool)) where
setItemSelected x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setItemSelected cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTableWidget_setItemSelected" qtc_QTableWidget_setItemSelected :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> CBool -> IO ()
setRangeSelected :: QTableWidget a -> ((QTableWidgetSelectionRange t1, Bool)) -> IO ()
setRangeSelected x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setRangeSelected cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTableWidget_setRangeSelected" qtc_QTableWidget_setRangeSelected :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetSelectionRange t1) -> CBool -> IO ()
instance QsetRowCount (QTableWidget a) ((Int)) where
setRowCount x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setRowCount cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_setRowCount" qtc_QTableWidget_setRowCount :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QsetSortingEnabled (QTableWidget ()) ((Bool)) where
setSortingEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setSortingEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_setSortingEnabled" qtc_QTableWidget_setSortingEnabled :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QsetSortingEnabled (QTableWidgetSc a) ((Bool)) where
setSortingEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setSortingEnabled cobj_x0 (toCBool x1)
instance QsetVerticalHeaderItem (QTableWidget a) ((Int, QTableWidgetItem t2)) where
setVerticalHeaderItem x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_setVerticalHeaderItem cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QTableWidget_setVerticalHeaderItem" qtc_QTableWidget_setVerticalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> Ptr (TQTableWidgetItem t2) -> IO ()
instance QsetVerticalHeaderLabels (QTableWidget a) (([String])) where
setVerticalHeaderLabels x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withQListString x1 $ \cqlistlen_x1 cqliststr_x1 ->
qtc_QTableWidget_setVerticalHeaderLabels cobj_x0 cqlistlen_x1 cqliststr_x1
foreign import ccall "qtc_QTableWidget_setVerticalHeaderLabels" qtc_QTableWidget_setVerticalHeaderLabels :: Ptr (TQTableWidget a) -> CInt -> Ptr (Ptr CWchar) -> IO ()
instance QsortItems (QTableWidget a) ((Int)) where
sortItems x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sortItems cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_sortItems" qtc_QTableWidget_sortItems :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QsortItems (QTableWidget a) ((Int, SortOrder)) where
sortItems x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sortItems1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTableWidget_sortItems1" qtc_QTableWidget_sortItems1 :: Ptr (TQTableWidget a) -> CInt -> CLong -> IO ()
instance QsupportedDropActions (QTableWidget ()) (()) where
supportedDropActions x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_supportedDropActions cobj_x0
foreign import ccall "qtc_QTableWidget_supportedDropActions" qtc_QTableWidget_supportedDropActions :: Ptr (TQTableWidget a) -> IO CLong
instance QsupportedDropActions (QTableWidgetSc a) (()) where
supportedDropActions x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_supportedDropActions cobj_x0
instance QtakeHorizontalHeaderItem (QTableWidget a) ((Int)) (IO (QTableWidgetItem ())) where
takeHorizontalHeaderItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_takeHorizontalHeaderItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_takeHorizontalHeaderItem" qtc_QTableWidget_takeHorizontalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QtakeItem (QTableWidget a) ((Int, Int)) (IO (QTableWidgetItem ())) where
takeItem x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_takeItem cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_takeItem" qtc_QTableWidget_takeItem :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QtakeVerticalHeaderItem (QTableWidget a) ((Int)) (IO (QTableWidgetItem ())) where
takeVerticalHeaderItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_takeVerticalHeaderItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_takeVerticalHeaderItem" qtc_QTableWidget_takeVerticalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> IO (Ptr (TQTableWidgetItem ()))
instance QverticalHeaderItem (QTableWidget a) ((Int)) (IO (QTableWidgetItem ())) where
verticalHeaderItem x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalHeaderItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_verticalHeaderItem" qtc_QTableWidget_verticalHeaderItem :: Ptr (TQTableWidget a) -> CInt -> IO (Ptr (TQTableWidgetItem ()))
visualColumn :: QTableWidget a -> ((Int)) -> IO (Int)
visualColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_visualColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_visualColumn" qtc_QTableWidget_visualColumn :: Ptr (TQTableWidget a) -> CInt -> IO CInt
instance QqvisualItemRect (QTableWidget a) ((QTableWidgetItem t1)) where
qvisualItemRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualItemRect cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_visualItemRect" qtc_QTableWidget_visualItemRect :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> IO (Ptr (TQRect ()))
instance QvisualItemRect (QTableWidget a) ((QTableWidgetItem 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_QTableWidget_visualItemRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTableWidget_visualItemRect_qth" qtc_QTableWidget_visualItemRect_qth :: Ptr (TQTableWidget a) -> Ptr (TQTableWidgetItem t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
visualRow :: QTableWidget a -> ((Int)) -> IO (Int)
visualRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_visualRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_visualRow" qtc_QTableWidget_visualRow :: Ptr (TQTableWidget a) -> CInt -> IO CInt
qTableWidget_delete :: QTableWidget a -> IO ()
qTableWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_delete cobj_x0
foreign import ccall "qtc_QTableWidget_delete" qtc_QTableWidget_delete :: Ptr (TQTableWidget a) -> IO ()
qTableWidget_deleteLater :: QTableWidget a -> IO ()
qTableWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_deleteLater cobj_x0
foreign import ccall "qtc_QTableWidget_deleteLater" qtc_QTableWidget_deleteLater :: Ptr (TQTableWidget a) -> IO ()
instance QcolumnCountChanged (QTableWidget ()) ((Int, Int)) where
columnCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnCountChanged cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_columnCountChanged" qtc_QTableWidget_columnCountChanged :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QcolumnCountChanged (QTableWidgetSc a) ((Int, Int)) where
columnCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnCountChanged cobj_x0 (toCInt x1) (toCInt x2)
instance QcolumnMoved (QTableWidget ()) ((Int, Int, Int)) where
columnMoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnMoved cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_columnMoved" qtc_QTableWidget_columnMoved :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> IO ()
instance QcolumnMoved (QTableWidgetSc a) ((Int, Int, Int)) where
columnMoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnMoved cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
instance QcolumnResized (QTableWidget ()) ((Int, Int, Int)) where
columnResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_columnResized" qtc_QTableWidget_columnResized :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> IO ()
instance QcolumnResized (QTableWidgetSc a) ((Int, Int, Int)) where
columnResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_columnResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
instance QcurrentChanged (QTableWidget ()) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_currentChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_currentChanged" qtc_QTableWidget_currentChanged :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QcurrentChanged (QTableWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
currentChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_currentChanged cobj_x0 cobj_x1 cobj_x2
instance QhorizontalOffset (QTableWidget ()) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalOffset cobj_x0
foreign import ccall "qtc_QTableWidget_horizontalOffset" qtc_QTableWidget_horizontalOffset :: Ptr (TQTableWidget a) -> IO CInt
instance QhorizontalOffset (QTableWidgetSc a) (()) where
horizontalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalOffset cobj_x0
instance QhorizontalScrollbarAction (QTableWidget ()) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_horizontalScrollbarAction" qtc_QTableWidget_horizontalScrollbarAction :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QhorizontalScrollbarAction (QTableWidgetSc a) ((Int)) where
horizontalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalScrollbarAction cobj_x0 (toCInt x1)
instance QindexAt (QTableWidget ()) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTableWidget_indexAt_qth_h" qtc_QTableWidget_indexAt_qth_h :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt (QTableWidgetSc a) ((Point)) where
indexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_indexAt_qth_h cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt (QTableWidget ()) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexAt_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_indexAt_h" qtc_QTableWidget_indexAt_h :: Ptr (TQTableWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt (QTableWidgetSc a) ((QPoint t1)) where
qindexAt x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_indexAt_h cobj_x0 cobj_x1
instance QisIndexHidden (QTableWidget ()) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_isIndexHidden cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_isIndexHidden" qtc_QTableWidget_isIndexHidden :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO CBool
instance QisIndexHidden (QTableWidgetSc a) ((QModelIndex t1)) where
isIndexHidden x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_isIndexHidden cobj_x0 cobj_x1
instance QmoveCursor (QTableWidget ()) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTableWidget_moveCursor" qtc_QTableWidget_moveCursor :: Ptr (TQTableWidget a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor (QTableWidgetSc a) ((CursorAction, KeyboardModifiers)) (IO (QModelIndex ())) where
moveCursor x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QpaintEvent (QTableWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_paintEvent_h" qtc_QTableWidget_paintEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QTableWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paintEvent_h cobj_x0 cobj_x1
instance QrowCountChanged (QTableWidget ()) ((Int, Int)) where
rowCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowCountChanged cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_rowCountChanged" qtc_QTableWidget_rowCountChanged :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QrowCountChanged (QTableWidgetSc a) ((Int, Int)) where
rowCountChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowCountChanged cobj_x0 (toCInt x1) (toCInt x2)
instance QrowMoved (QTableWidget ()) ((Int, Int, Int)) where
rowMoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowMoved cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_rowMoved" qtc_QTableWidget_rowMoved :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> IO ()
instance QrowMoved (QTableWidgetSc a) ((Int, Int, Int)) where
rowMoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowMoved cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
instance QrowResized (QTableWidget ()) ((Int, Int, Int)) where
rowResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_rowResized" qtc_QTableWidget_rowResized :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> IO ()
instance QrowResized (QTableWidgetSc a) ((Int, Int, Int)) where
rowResized x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_rowResized cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3)
instance QscrollContentsBy (QTableWidget ()) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_scrollContentsBy_h" qtc_QTableWidget_scrollContentsBy_h :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy (QTableWidgetSc a) ((Int, Int)) where
scrollContentsBy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollContentsBy_h cobj_x0 (toCInt x1) (toCInt x2)
instance QscrollTo (QTableWidget ()) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollTo_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTableWidget_scrollTo_h" qtc_QTableWidget_scrollTo_h :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo (QTableWidgetSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_scrollTo_h cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QselectedIndexes (QTableWidget ()) (()) where
selectedIndexes x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectedIndexes cobj_x0 arr
foreign import ccall "qtc_QTableWidget_selectedIndexes" qtc_QTableWidget_selectedIndexes :: Ptr (TQTableWidget a) -> Ptr (Ptr (TQModelIndex ())) -> IO CInt
instance QselectedIndexes (QTableWidgetSc a) (()) where
selectedIndexes x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectedIndexes cobj_x0 arr
instance QselectionChanged (QTableWidget ()) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_selectionChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_selectionChanged" qtc_QTableWidget_selectionChanged :: Ptr (TQTableWidget a) -> Ptr (TQItemSelection t1) -> Ptr (TQItemSelection t2) -> IO ()
instance QselectionChanged (QTableWidgetSc a) ((QItemSelection t1, QItemSelection t2)) where
selectionChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_selectionChanged cobj_x0 cobj_x1 cobj_x2
instance QsetModel (QTableWidget ()) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setModel_h" qtc_QTableWidget_setModel_h :: Ptr (TQTableWidget a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel (QTableWidgetSc a) ((QAbstractItemModel t1)) where
setModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setModel_h cobj_x0 cobj_x1
instance QsetRootIndex (QTableWidget ()) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setRootIndex_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setRootIndex_h" qtc_QTableWidget_setRootIndex_h :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex (QTableWidgetSc a) ((QModelIndex t1)) where
setRootIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setRootIndex_h cobj_x0 cobj_x1
instance QqsetSelection (QTableWidget ()) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTableWidget_setSelection" qtc_QTableWidget_setSelection :: Ptr (TQTableWidget a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection (QTableWidgetSc a) ((QRect t1, SelectionFlags)) where
qsetSelection x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection (QTableWidget ()) ((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_QTableWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTableWidget_setSelection_qth" qtc_QTableWidget_setSelection_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection (QTableWidgetSc 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_QTableWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSelectionModel (QTableWidget ()) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelectionModel_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setSelectionModel_h" qtc_QTableWidget_setSelectionModel_h :: Ptr (TQTableWidget a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel (QTableWidgetSc a) ((QItemSelectionModel t1)) where
setSelectionModel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setSelectionModel_h cobj_x0 cobj_x1
instance QsizeHintForColumn (QTableWidget ()) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHintForColumn cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_sizeHintForColumn" qtc_QTableWidget_sizeHintForColumn :: Ptr (TQTableWidget a) -> CInt -> IO CInt
instance QsizeHintForColumn (QTableWidgetSc a) ((Int)) where
sizeHintForColumn x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHintForColumn cobj_x0 (toCInt x1)
instance QsizeHintForRow (QTableWidget ()) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHintForRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_sizeHintForRow" qtc_QTableWidget_sizeHintForRow :: Ptr (TQTableWidget a) -> CInt -> IO CInt
instance QsizeHintForRow (QTableWidgetSc a) ((Int)) where
sizeHintForRow x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHintForRow cobj_x0 (toCInt x1)
instance QtimerEvent (QTableWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_timerEvent" qtc_QTableWidget_timerEvent :: Ptr (TQTableWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QTableWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_timerEvent cobj_x0 cobj_x1
instance QupdateGeometries (QTableWidget ()) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateGeometries cobj_x0
foreign import ccall "qtc_QTableWidget_updateGeometries" qtc_QTableWidget_updateGeometries :: Ptr (TQTableWidget a) -> IO ()
instance QupdateGeometries (QTableWidgetSc a) (()) where
updateGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateGeometries cobj_x0
instance QverticalOffset (QTableWidget ()) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalOffset cobj_x0
foreign import ccall "qtc_QTableWidget_verticalOffset" qtc_QTableWidget_verticalOffset :: Ptr (TQTableWidget a) -> IO CInt
instance QverticalOffset (QTableWidgetSc a) (()) where
verticalOffset x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalOffset cobj_x0
instance QverticalScrollbarAction (QTableWidget ()) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalScrollbarAction cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_verticalScrollbarAction" qtc_QTableWidget_verticalScrollbarAction :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QverticalScrollbarAction (QTableWidgetSc a) ((Int)) where
verticalScrollbarAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalScrollbarAction cobj_x0 (toCInt x1)
instance QviewOptions (QTableWidget ()) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_viewOptions cobj_x0
foreign import ccall "qtc_QTableWidget_viewOptions" qtc_QTableWidget_viewOptions :: Ptr (TQTableWidget a) -> IO (Ptr (TQStyleOptionViewItem ()))
instance QviewOptions (QTableWidgetSc a) (()) where
viewOptions x0 ()
= withQStyleOptionViewItemResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_viewOptions cobj_x0
instance QqvisualRect (QTableWidget ()) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_visualRect_h" qtc_QTableWidget_visualRect_h :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect (QTableWidgetSc a) ((QModelIndex t1)) where
qvisualRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRect_h cobj_x0 cobj_x1
instance QvisualRect (QTableWidget ()) ((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_QTableWidget_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTableWidget_visualRect_qth_h" qtc_QTableWidget_visualRect_qth_h :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect (QTableWidgetSc 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_QTableWidget_visualRect_qth_h cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QvisualRegionForSelection (QTableWidget ()) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRegionForSelection cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_visualRegionForSelection" qtc_QTableWidget_visualRegionForSelection :: Ptr (TQTableWidget a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection (QTableWidgetSc a) ((QItemSelection t1)) where
visualRegionForSelection x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_visualRegionForSelection cobj_x0 cobj_x1
instance QcloseEditor (QTableWidget ()) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTableWidget_closeEditor" qtc_QTableWidget_closeEditor :: Ptr (TQTableWidget a) -> Ptr (TQWidget t1) -> CLong -> IO ()
instance QcloseEditor (QTableWidgetSc a) ((QWidget t1, EndEditHint)) where
closeEditor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEditor cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcommitData (QTableWidget ()) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_commitData cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_commitData" qtc_QTableWidget_commitData :: Ptr (TQTableWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QcommitData (QTableWidgetSc a) ((QWidget t1)) where
commitData x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_commitData cobj_x0 cobj_x1
instance QdataChanged (QTableWidget ()) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_dataChanged" qtc_QTableWidget_dataChanged :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QdataChanged (QTableWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
dataChanged x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
instance QdirtyRegionOffset (QTableWidget ()) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QTableWidget_dirtyRegionOffset_qth" qtc_QTableWidget_dirtyRegionOffset_qth :: Ptr (TQTableWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QdirtyRegionOffset (QTableWidgetSc a) (()) where
dirtyRegionOffset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dirtyRegionOffset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
instance QqdirtyRegionOffset (QTableWidget ()) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dirtyRegionOffset cobj_x0
foreign import ccall "qtc_QTableWidget_dirtyRegionOffset" qtc_QTableWidget_dirtyRegionOffset :: Ptr (TQTableWidget a) -> IO (Ptr (TQPoint ()))
instance QqdirtyRegionOffset (QTableWidgetSc a) (()) where
qdirtyRegionOffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dirtyRegionOffset cobj_x0
instance QdoAutoScroll (QTableWidget ()) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doAutoScroll cobj_x0
foreign import ccall "qtc_QTableWidget_doAutoScroll" qtc_QTableWidget_doAutoScroll :: Ptr (TQTableWidget a) -> IO ()
instance QdoAutoScroll (QTableWidgetSc a) (()) where
doAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doAutoScroll cobj_x0
instance QdoItemsLayout (QTableWidget ()) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doItemsLayout_h cobj_x0
foreign import ccall "qtc_QTableWidget_doItemsLayout_h" qtc_QTableWidget_doItemsLayout_h :: Ptr (TQTableWidget a) -> IO ()
instance QdoItemsLayout (QTableWidgetSc a) (()) where
doItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_doItemsLayout_h cobj_x0
instance QdragEnterEvent (QTableWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragEnterEvent_h" qtc_QTableWidget_dragEnterEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QTableWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QTableWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragLeaveEvent_h" qtc_QTableWidget_dragLeaveEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QTableWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QTableWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_dragMoveEvent_h" qtc_QTableWidget_dragMoveEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QTableWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropIndicatorPosition (QTableWidget ()) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dropIndicatorPosition cobj_x0
foreign import ccall "qtc_QTableWidget_dropIndicatorPosition" qtc_QTableWidget_dropIndicatorPosition :: Ptr (TQTableWidget a) -> IO CLong
instance QdropIndicatorPosition (QTableWidgetSc a) (()) where
dropIndicatorPosition x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_dropIndicatorPosition cobj_x0
instance Qedit (QTableWidget ()) ((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_QTableWidget_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
foreign import ccall "qtc_QTableWidget_edit" qtc_QTableWidget_edit :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> CLong -> Ptr (TQEvent t3) -> IO CBool
instance Qedit (QTableWidgetSc 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_QTableWidget_edit cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) cobj_x3
instance QeditorDestroyed (QTableWidget ()) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_editorDestroyed cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_editorDestroyed" qtc_QTableWidget_editorDestroyed :: Ptr (TQTableWidget a) -> Ptr (TQObject t1) -> IO ()
instance QeditorDestroyed (QTableWidgetSc a) ((QObject t1)) where
editorDestroyed x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_editorDestroyed cobj_x0 cobj_x1
instance QexecuteDelayedItemsLayout (QTableWidget ()) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_executeDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QTableWidget_executeDelayedItemsLayout" qtc_QTableWidget_executeDelayedItemsLayout :: Ptr (TQTableWidget a) -> IO ()
instance QexecuteDelayedItemsLayout (QTableWidgetSc a) (()) where
executeDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_executeDelayedItemsLayout cobj_x0
instance QfocusInEvent (QTableWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_focusInEvent_h" qtc_QTableWidget_focusInEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QTableWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextPrevChild (QTableWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_focusNextPrevChild" qtc_QTableWidget_focusNextPrevChild :: Ptr (TQTableWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QTableWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QTableWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_focusOutEvent_h" qtc_QTableWidget_focusOutEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QTableWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QhorizontalScrollbarValueChanged (QTableWidget ()) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_horizontalScrollbarValueChanged" qtc_QTableWidget_horizontalScrollbarValueChanged :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QhorizontalScrollbarValueChanged (QTableWidgetSc a) ((Int)) where
horizontalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QhorizontalStepsPerItem (QTableWidget ()) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalStepsPerItem cobj_x0
foreign import ccall "qtc_QTableWidget_horizontalStepsPerItem" qtc_QTableWidget_horizontalStepsPerItem :: Ptr (TQTableWidget a) -> IO CInt
instance QhorizontalStepsPerItem (QTableWidgetSc a) (()) where
horizontalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_horizontalStepsPerItem cobj_x0
instance QinputMethodEvent (QTableWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_inputMethodEvent" qtc_QTableWidget_inputMethodEvent :: Ptr (TQTableWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QTableWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QTableWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTableWidget_inputMethodQuery_h" qtc_QTableWidget_inputMethodQuery_h :: Ptr (TQTableWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QTableWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent (QTableWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_keyPressEvent_h" qtc_QTableWidget_keyPressEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QTableWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyboardSearch (QTableWidget ()) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_keyboardSearch_h cobj_x0 cstr_x1
foreign import ccall "qtc_QTableWidget_keyboardSearch_h" qtc_QTableWidget_keyboardSearch_h :: Ptr (TQTableWidget a) -> CWString -> IO ()
instance QkeyboardSearch (QTableWidgetSc a) ((String)) where
keyboardSearch x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_keyboardSearch_h cobj_x0 cstr_x1
instance QmouseDoubleClickEvent (QTableWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseDoubleClickEvent_h" qtc_QTableWidget_mouseDoubleClickEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QTableWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseMoveEvent_h" qtc_QTableWidget_mouseMoveEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QTableWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mousePressEvent_h" qtc_QTableWidget_mousePressEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QTableWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QTableWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_mouseReleaseEvent_h" qtc_QTableWidget_mouseReleaseEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QTableWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qreset (QTableWidget ()) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_reset_h cobj_x0
foreign import ccall "qtc_QTableWidget_reset_h" qtc_QTableWidget_reset_h :: Ptr (TQTableWidget a) -> IO ()
instance Qreset (QTableWidgetSc a) (()) (IO ()) where
reset x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_reset_h cobj_x0
instance QresizeEvent (QTableWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_resizeEvent_h" qtc_QTableWidget_resizeEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QTableWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resizeEvent_h cobj_x0 cobj_x1
instance QrowsAboutToBeRemoved (QTableWidget ()) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_rowsAboutToBeRemoved" qtc_QTableWidget_rowsAboutToBeRemoved :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsAboutToBeRemoved (QTableWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QrowsInserted (QTableWidget ()) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTableWidget_rowsInserted" qtc_QTableWidget_rowsInserted :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsInserted (QTableWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsInserted x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QscheduleDelayedItemsLayout (QTableWidget ()) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scheduleDelayedItemsLayout cobj_x0
foreign import ccall "qtc_QTableWidget_scheduleDelayedItemsLayout" qtc_QTableWidget_scheduleDelayedItemsLayout :: Ptr (TQTableWidget a) -> IO ()
instance QscheduleDelayedItemsLayout (QTableWidgetSc a) (()) where
scheduleDelayedItemsLayout x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scheduleDelayedItemsLayout cobj_x0
instance QscrollDirtyRegion (QTableWidget ()) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_scrollDirtyRegion" qtc_QTableWidget_scrollDirtyRegion :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance QscrollDirtyRegion (QTableWidgetSc a) ((Int, Int)) where
scrollDirtyRegion x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_scrollDirtyRegion cobj_x0 (toCInt x1) (toCInt x2)
instance QselectAll (QTableWidget ()) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectAll_h cobj_x0
foreign import ccall "qtc_QTableWidget_selectAll_h" qtc_QTableWidget_selectAll_h :: Ptr (TQTableWidget a) -> IO ()
instance QselectAll (QTableWidgetSc a) (()) where
selectAll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_selectAll_h cobj_x0
instance QselectionCommand (QTableWidget ()) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_selectionCommand cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_selectionCommand" qtc_QTableWidget_selectionCommand :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> IO CLong
instance QselectionCommand (QTableWidgetSc a) ((QModelIndex t1)) where
selectionCommand x0 (x1)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_selectionCommand cobj_x0 cobj_x1
instance QselectionCommand (QTableWidget ()) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_selectionCommand1" qtc_QTableWidget_selectionCommand1 :: Ptr (TQTableWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQEvent t2) -> IO CLong
instance QselectionCommand (QTableWidgetSc a) ((QModelIndex t1, QEvent t2)) where
selectionCommand x0 (x1, x2)
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_selectionCommand1 cobj_x0 cobj_x1 cobj_x2
instance QsetDirtyRegion (QTableWidget ()) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setDirtyRegion cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setDirtyRegion" qtc_QTableWidget_setDirtyRegion :: Ptr (TQTableWidget a) -> Ptr (TQRegion t1) -> IO ()
instance QsetDirtyRegion (QTableWidgetSc a) ((QRegion t1)) where
setDirtyRegion x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setDirtyRegion cobj_x0 cobj_x1
instance QsetHorizontalStepsPerItem (QTableWidget ()) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_setHorizontalStepsPerItem" qtc_QTableWidget_setHorizontalStepsPerItem :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QsetHorizontalStepsPerItem (QTableWidgetSc a) ((Int)) where
setHorizontalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setHorizontalStepsPerItem cobj_x0 (toCInt x1)
instance QsetState (QTableWidget ()) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setState cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTableWidget_setState" qtc_QTableWidget_setState :: Ptr (TQTableWidget a) -> CLong -> IO ()
instance QsetState (QTableWidgetSc a) ((QAbstractItemViewState)) where
setState x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setState cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetVerticalStepsPerItem (QTableWidget ()) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVerticalStepsPerItem cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_setVerticalStepsPerItem" qtc_QTableWidget_setVerticalStepsPerItem :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QsetVerticalStepsPerItem (QTableWidgetSc a) ((Int)) where
setVerticalStepsPerItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVerticalStepsPerItem cobj_x0 (toCInt x1)
instance QstartAutoScroll (QTableWidget ()) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_startAutoScroll cobj_x0
foreign import ccall "qtc_QTableWidget_startAutoScroll" qtc_QTableWidget_startAutoScroll :: Ptr (TQTableWidget a) -> IO ()
instance QstartAutoScroll (QTableWidgetSc a) (()) where
startAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_startAutoScroll cobj_x0
instance QstartDrag (QTableWidget ()) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QTableWidget_startDrag" qtc_QTableWidget_startDrag :: Ptr (TQTableWidget a) -> CLong -> IO ()
instance QstartDrag (QTableWidgetSc a) ((DropActions)) where
startDrag x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_startDrag cobj_x0 (toCLong $ qFlags_toInt x1)
instance Qstate (QTableWidget ()) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_state cobj_x0
foreign import ccall "qtc_QTableWidget_state" qtc_QTableWidget_state :: Ptr (TQTableWidget a) -> IO CLong
instance Qstate (QTableWidgetSc a) (()) (IO (QAbstractItemViewState)) where
state x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_state cobj_x0
instance QstopAutoScroll (QTableWidget ()) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_stopAutoScroll cobj_x0
foreign import ccall "qtc_QTableWidget_stopAutoScroll" qtc_QTableWidget_stopAutoScroll :: Ptr (TQTableWidget a) -> IO ()
instance QstopAutoScroll (QTableWidgetSc a) (()) where
stopAutoScroll x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_stopAutoScroll cobj_x0
instance QupdateEditorData (QTableWidget ()) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateEditorData cobj_x0
foreign import ccall "qtc_QTableWidget_updateEditorData" qtc_QTableWidget_updateEditorData :: Ptr (TQTableWidget a) -> IO ()
instance QupdateEditorData (QTableWidgetSc a) (()) where
updateEditorData x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateEditorData cobj_x0
instance QupdateEditorGeometries (QTableWidget ()) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateEditorGeometries cobj_x0
foreign import ccall "qtc_QTableWidget_updateEditorGeometries" qtc_QTableWidget_updateEditorGeometries :: Ptr (TQTableWidget a) -> IO ()
instance QupdateEditorGeometries (QTableWidgetSc a) (()) where
updateEditorGeometries x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateEditorGeometries cobj_x0
instance QverticalScrollbarValueChanged (QTableWidget ()) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_verticalScrollbarValueChanged" qtc_QTableWidget_verticalScrollbarValueChanged :: Ptr (TQTableWidget a) -> CInt -> IO ()
instance QverticalScrollbarValueChanged (QTableWidgetSc a) ((Int)) where
verticalScrollbarValueChanged x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalScrollbarValueChanged cobj_x0 (toCInt x1)
instance QverticalStepsPerItem (QTableWidget ()) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalStepsPerItem cobj_x0
foreign import ccall "qtc_QTableWidget_verticalStepsPerItem" qtc_QTableWidget_verticalStepsPerItem :: Ptr (TQTableWidget a) -> IO CInt
instance QverticalStepsPerItem (QTableWidgetSc a) (()) where
verticalStepsPerItem x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_verticalStepsPerItem cobj_x0
instance QviewportEvent (QTableWidget ()) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_viewportEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_viewportEvent_h" qtc_QTableWidget_viewportEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent (QTableWidgetSc a) ((QEvent t1)) where
viewportEvent x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_viewportEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QTableWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_contextMenuEvent_h" qtc_QTableWidget_contextMenuEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QTableWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance QqminimumSizeHint (QTableWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QTableWidget_minimumSizeHint_h" qtc_QTableWidget_minimumSizeHint_h :: Ptr (TQTableWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QTableWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QTableWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTableWidget_minimumSizeHint_qth_h" qtc_QTableWidget_minimumSizeHint_qth_h :: Ptr (TQTableWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QTableWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetViewportMargins (QTableWidget ()) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTableWidget_setViewportMargins" qtc_QTableWidget_setViewportMargins :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetViewportMargins (QTableWidgetSc a) ((Int, Int, Int, Int)) where
setViewportMargins x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setViewportMargins cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QsetupViewport (QTableWidget ()) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setupViewport cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setupViewport" qtc_QTableWidget_setupViewport :: Ptr (TQTableWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QsetupViewport (QTableWidgetSc a) ((QWidget t1)) where
setupViewport x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setupViewport cobj_x0 cobj_x1
instance QqsizeHint (QTableWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QTableWidget_sizeHint_h" qtc_QTableWidget_sizeHint_h :: Ptr (TQTableWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QTableWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_h cobj_x0
instance QsizeHint (QTableWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTableWidget_sizeHint_qth_h" qtc_QTableWidget_sizeHint_qth_h :: Ptr (TQTableWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QTableWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent (QTableWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_wheelEvent_h" qtc_QTableWidget_wheelEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QTableWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_wheelEvent_h cobj_x0 cobj_x1
instance QchangeEvent (QTableWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_changeEvent_h" qtc_QTableWidget_changeEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QTableWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_changeEvent_h cobj_x0 cobj_x1
instance QdrawFrame (QTableWidget ()) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_drawFrame cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_drawFrame" qtc_QTableWidget_drawFrame :: Ptr (TQTableWidget a) -> Ptr (TQPainter t1) -> IO ()
instance QdrawFrame (QTableWidgetSc a) ((QPainter t1)) where
drawFrame x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_drawFrame cobj_x0 cobj_x1
instance QactionEvent (QTableWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_actionEvent_h" qtc_QTableWidget_actionEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QTableWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QTableWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_addAction" qtc_QTableWidget_addAction :: Ptr (TQTableWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QTableWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_addAction cobj_x0 cobj_x1
instance QcloseEvent (QTableWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_closeEvent_h" qtc_QTableWidget_closeEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QTableWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_closeEvent_h cobj_x0 cobj_x1
instance Qcreate (QTableWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_create cobj_x0
foreign import ccall "qtc_QTableWidget_create" qtc_QTableWidget_create :: Ptr (TQTableWidget a) -> IO ()
instance Qcreate (QTableWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_create cobj_x0
instance Qcreate (QTableWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_create1" qtc_QTableWidget_create1 :: Ptr (TQTableWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QTableWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QTableWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QTableWidget_create2" qtc_QTableWidget_create2 :: Ptr (TQTableWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QTableWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QTableWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QTableWidget_create3" qtc_QTableWidget_create3 :: Ptr (TQTableWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QTableWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QTableWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy cobj_x0
foreign import ccall "qtc_QTableWidget_destroy" qtc_QTableWidget_destroy :: Ptr (TQTableWidget a) -> IO ()
instance Qdestroy (QTableWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy cobj_x0
instance Qdestroy (QTableWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_destroy1" qtc_QTableWidget_destroy1 :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance Qdestroy (QTableWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QTableWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QTableWidget_destroy2" qtc_QTableWidget_destroy2 :: Ptr (TQTableWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QTableWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QTableWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_devType_h cobj_x0
foreign import ccall "qtc_QTableWidget_devType_h" qtc_QTableWidget_devType_h :: Ptr (TQTableWidget a) -> IO CInt
instance QdevType (QTableWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_devType_h cobj_x0
instance QenabledChange (QTableWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_enabledChange" qtc_QTableWidget_enabledChange :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QenabledChange (QTableWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QTableWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_enterEvent_h" qtc_QTableWidget_enterEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QTableWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QTableWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QTableWidget_focusNextChild" qtc_QTableWidget_focusNextChild :: Ptr (TQTableWidget a) -> IO CBool
instance QfocusNextChild (QTableWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusNextChild cobj_x0
instance QfocusPreviousChild (QTableWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QTableWidget_focusPreviousChild" qtc_QTableWidget_focusPreviousChild :: Ptr (TQTableWidget a) -> IO CBool
instance QfocusPreviousChild (QTableWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_focusPreviousChild cobj_x0
instance QfontChange (QTableWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_fontChange" qtc_QTableWidget_fontChange :: Ptr (TQTableWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QTableWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QTableWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTableWidget_heightForWidth_h" qtc_QTableWidget_heightForWidth_h :: Ptr (TQTableWidget a) -> CInt -> IO CInt
instance QheightForWidth (QTableWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QTableWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_hideEvent_h" qtc_QTableWidget_hideEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QTableWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_hideEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QTableWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_keyReleaseEvent_h" qtc_QTableWidget_keyReleaseEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QTableWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QTableWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_languageChange cobj_x0
foreign import ccall "qtc_QTableWidget_languageChange" qtc_QTableWidget_languageChange :: Ptr (TQTableWidget a) -> IO ()
instance QlanguageChange (QTableWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_languageChange cobj_x0
instance QleaveEvent (QTableWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_leaveEvent_h" qtc_QTableWidget_leaveEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QTableWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QTableWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTableWidget_metric" qtc_QTableWidget_metric :: Ptr (TQTableWidget a) -> CLong -> IO CInt
instance Qmetric (QTableWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance Qmove (QTableWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_move1" qtc_QTableWidget_move1 :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QTableWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QTableWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTableWidget_move_qth" qtc_QTableWidget_move_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QTableWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTableWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QTableWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_move" qtc_QTableWidget_move :: Ptr (TQTableWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QTableWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QTableWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_moveEvent_h" qtc_QTableWidget_moveEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QTableWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QTableWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QTableWidget_paintEngine_h" qtc_QTableWidget_paintEngine_h :: Ptr (TQTableWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QTableWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_paintEngine_h cobj_x0
instance QpaletteChange (QTableWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_paletteChange" qtc_QTableWidget_paletteChange :: Ptr (TQTableWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QTableWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QTableWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_repaint cobj_x0
foreign import ccall "qtc_QTableWidget_repaint" qtc_QTableWidget_repaint :: Ptr (TQTableWidget a) -> IO ()
instance Qrepaint (QTableWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_repaint cobj_x0
instance Qrepaint (QTableWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTableWidget_repaint2" qtc_QTableWidget_repaint2 :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QTableWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QTableWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_repaint1" qtc_QTableWidget_repaint1 :: Ptr (TQTableWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QTableWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QTableWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QTableWidget_resetInputContext" qtc_QTableWidget_resetInputContext :: Ptr (TQTableWidget a) -> IO ()
instance QresetInputContext (QTableWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_resetInputContext cobj_x0
instance Qresize (QTableWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTableWidget_resize1" qtc_QTableWidget_resize1 :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QTableWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QTableWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_resize" qtc_QTableWidget_resize :: Ptr (TQTableWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QTableWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_resize cobj_x0 cobj_x1
instance Qresize (QTableWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QTableWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QTableWidget_resize_qth" qtc_QTableWidget_resize_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QTableWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QTableWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QTableWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QTableWidget_setGeometry1" qtc_QTableWidget_setGeometry1 :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QTableWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QTableWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_setGeometry" qtc_QTableWidget_setGeometry :: Ptr (TQTableWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QTableWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QTableWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTableWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QTableWidget_setGeometry_qth" qtc_QTableWidget_setGeometry_qth :: Ptr (TQTableWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QTableWidgetSc 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_QTableWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QTableWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_setMouseTracking" qtc_QTableWidget_setMouseTracking :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QTableWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QTableWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_setVisible_h" qtc_QTableWidget_setVisible_h :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QsetVisible (QTableWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QTableWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_showEvent_h" qtc_QTableWidget_showEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QTableWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QTableWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_tabletEvent_h" qtc_QTableWidget_tabletEvent_h :: Ptr (TQTableWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QTableWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QTableWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QTableWidget_updateMicroFocus" qtc_QTableWidget_updateMicroFocus :: Ptr (TQTableWidget a) -> IO ()
instance QupdateMicroFocus (QTableWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_updateMicroFocus cobj_x0
instance QwindowActivationChange (QTableWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTableWidget_windowActivationChange" qtc_QTableWidget_windowActivationChange :: Ptr (TQTableWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QTableWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QTableWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_childEvent" qtc_QTableWidget_childEvent :: Ptr (TQTableWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QTableWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QTableWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTableWidget_connectNotify" qtc_QTableWidget_connectNotify :: Ptr (TQTableWidget a) -> CWString -> IO ()
instance QconnectNotify (QTableWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QTableWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTableWidget_customEvent" qtc_QTableWidget_customEvent :: Ptr (TQTableWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QTableWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTableWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QTableWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QTableWidget_disconnectNotify" qtc_QTableWidget_disconnectNotify :: Ptr (TQTableWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QTableWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QTableWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTableWidget_eventFilter_h" qtc_QTableWidget_eventFilter_h :: Ptr (TQTableWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QTableWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTableWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QTableWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QTableWidget_receivers" qtc_QTableWidget_receivers :: Ptr (TQTableWidget a) -> CWString -> IO CInt
instance Qreceivers (QTableWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTableWidget_receivers cobj_x0 cstr_x1
instance Qsender (QTableWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sender cobj_x0
foreign import ccall "qtc_QTableWidget_sender" qtc_QTableWidget_sender :: Ptr (TQTableWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QTableWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTableWidget_sender cobj_x0
|
keera-studios/hsQt
|
Qtc/Gui/QTableWidget.hs
|
Haskell
|
bsd-2-clause
| 108,770
|
module Common
( BaseGene(..)
, CoupleGene(..)
, replaceAtIndex
, boxMuller
, InBounds
, FitnessFunction(..)
, GeneFormat(..)
, StartPopulation(..)
, calcFitness
, mutateStandard
, mutateGauss
, evolve
, generate
) where
-- the (..) also exports the constructor
import System.Random
import Control.Monad.State.Lazy
import Text.Printf
--
-- Our genes
--
newtype BaseGene = BaseGene { getBaseGene :: Float } deriving Show
newtype CoupleGene = CoupleGene { getCoupleGene :: (Float, Float) } deriving Show
--
-- Some basic tools
--
replaceAtIndex :: Int -> a -> [a] -> [a]
replaceAtIndex n item ls = a ++ (item:b) where (a, (_:b)) = splitAt n ls
pick :: [a] -> StdGen -> (a, StdGen)
pick xs seed = extractInCouple xs (getPosition xs seed)
-- Helpers for the pick function
bounds :: [a] -> (Int, Int)
bounds xs = (0, length xs - 1)
getPosition :: [a] -> StdGen -> (Int, StdGen)
getPosition xs g = randomR (bounds xs) g
extractInCouple :: [a] -> (Int, StdGen) -> (a, StdGen)
extractInCouple xs (i, g) = (xs !! i, g)
--
-- Gaussian distribution
--
boxMuller :: StdGen -> (Float, StdGen)
boxMuller seed = (sqrt (-2 * log u1) * cos (2 * pi * u2), seed_2)
where (u1, seed_1) = randomR (0, 1) seed
(u2, seed_2) = randomR (0, 1) seed_1
--
-- Check if in bounds
--
class InBounds g where
inBounds :: g -> Float -> Float -> Bool
instance InBounds BaseGene where
inBounds (BaseGene g) lb ub = (lb <= g) && (g <= ub)
instance InBounds CoupleGene where
inBounds (CoupleGene (x, y)) lb ub = (lb <= x) && (x <= ub) && (lb <= y) && (y <= ub)
--
-- Fitness functions (type class)
-- In the end from Haskell point of view a gene is something
-- that has a fitness function
--
class FitnessFunction g where
fitnessFunction :: g -> Float
instance FitnessFunction BaseGene where
fitnessFunction = \(BaseGene x) -> 50 - (x^2)
instance FitnessFunction CoupleGene where
fitnessFunction = \(CoupleGene (x, y)) -> x^2 + y^2
--
-- Print formatting functions (type class)
--
class GeneFormat g where
geneFormat :: (g, Float) -> IO ()
instance GeneFormat BaseGene where
geneFormat x = do
let g = getBaseGene $ fst x
let f = snd x
putStrLn ("Gene: " ++ (printf "%12.8f" g ++ " " ++ "; Fitness: " ++ (printf "%14.8f" f)))
instance GeneFormat CoupleGene where
geneFormat x = do
let (g1, g2) = getCoupleGene $ fst x
let f = snd x
putStrLn ("Gene: (" ++ (printf "%12.8f" g1) ++ ", " ++ (printf "%12.8f" g2) ++"); Fitness: " ++ (printf "%14.8f" f))
--
-- Type class with instances that generate the starting population
--
class StartPopulation g where
startPopulation :: Int -> Float -> Float -> State StdGen [g]
instance StartPopulation BaseGene where
-- startPopulation n lb ub seed = take n $ map BaseGene (randomRs (lb, ub) seed)
startPopulation n lb ub = do
replicateM n $ fmap BaseGene $ state $ randomR (lb, ub)
instance StartPopulation CoupleGene where
-- startPopulation n lb ub seed_1 = take n $ map CoupleGene $ zip (randomRs (lb, ub) seed_1) (randomRs (lb, ub) seed_2)
-- where (_, seed_2) = random seed_1 :: (Float, StdGen)
startPopulation n lb ub = do
replicateM n $ fmap CoupleGene $ state $ randomR' (lb, ub)
-- These functions helped me to sort out wrapping/unwrapping in the State Monad
-- randomR'' :: (Float, Float) -> State StdGen BaseGene
-- randomR'' (lb, ub) = fmap BaseGene (state (randomR (lb, ub)))
-- randoms' :: Int -> Float -> Float -> State StdGen [BaseGene]
-- randoms' n lb ub = replicateM n (randomR'' (lb, ub))
-- randoms :: Int -> Float -> Float -> StdGen -> ([BaseGene], StdGen)
-- randoms n lb ub = runState (randoms' n lb ub)
-- randomState :: Float -> Float -> State StdGen CoupleGene
-- randomState lb ub = fmap CoupleGene (state (randomR' (lb, ub)))
-- This is actually used in startPopulation
randomR' :: (Float, Float) -> StdGen -> ((Float, Float), StdGen)
randomR' (lb, ub) seed = ((fst (randomR (lb, ub) seed), fst (randomR (lb, ub) seed_1)), seed_2)
where (seed_1, seed_2) = split seed
--
-- Generic function to calculate the fitness
-- g must have a fitness function i.e. must be a gene
--
calcFitness :: FitnessFunction g => [g] -> [Float]
calcFitness xs = map fitnessFunction xs
--
-- Mutation using delta mutation
--
class MutateStandard g where
mutateStandard :: g -> State StdGen g
instance MutateStandard BaseGene where
-- making an identical copy of the parent, and then probabilistically mutating it to produce the offspring.
mutateStandard (BaseGene g) = do
seed <- get
let (factor, newseed) = pick [-1.0, 1.0] seed
put newseed
return (BaseGene (g + factor))
instance MutateStandard CoupleGene where
-- making an identical copy of the parent, and then probabilistically mutating it to produce the offspring.
mutateStandard (CoupleGene (f, s)) = do
seed <- get
let (factor_1, newseed) = pick [-1.0, 1.0] seed
let (factor_2, finalseed) = pick [-1.0, 1.0] newseed
put finalseed
return (CoupleGene (f + factor_1, s + factor_2))
--
-- Type class with instances that probabilistically mutate a gene
-- using a gaussian distribution
--
class MutateGauss g where
mutateGauss :: g -> State StdGen g
instance MutateGauss BaseGene where
-- making an identical copy of the parent, and then probabilistically mutating it to produce the offspring.
mutateGauss (BaseGene g) = do
seed <- get
let (factor, newseed) = boxMuller seed
put newseed
return (BaseGene (g + factor))
instance MutateGauss CoupleGene where
-- making an identical copy of the parent, and then probabilistically mutating it to produce the offspring.
mutateGauss (CoupleGene (f, s)) = do
seed <- get
let (factor_1, newseed) = boxMuller seed
let (factor_2, finalseed) = boxMuller newseed
put finalseed
return (CoupleGene (f + factor_1, s + factor_2))
--
-- Generic function to extract a gene and mutate it using
-- a function with signature g -> g
--
extractElementAndMutate :: [g] -> Int -> (g -> State StdGen g) -> State StdGen g
extractElementAndMutate pop pos f = do
seed <- get
let elem = pop !! pos
let (offspring, newseed) = runState (f elem) seed
put newseed
return offspring
--
-- Generic function that takes a population and a mutation function
-- and returns a new population with the mutation in place if it has higher fitness
--
evolve :: (InBounds g, FitnessFunction g) => Float -> Float -> [g] -> (g -> State StdGen g) -> State StdGen [g]
evolve lb ub pop f = do
seed <- get
let (pos_1, seed_1) = randomR (bounds pop) seed
let (pos_2, seed_2) = randomR (bounds pop) seed_1
-- select a parent randomly using a uniform probability distribution over the current population.
-- Use the selected parent to produce a single offspring
let (offspring, finalseed) = runState (extractElementAndMutate pop pos_1 f) seed_2
let opponent = pop !! pos_2
let offFitness = fitnessFunction offspring
let oppFitness = fitnessFunction opponent
let winner = if offFitness > oppFitness then offspring else opponent
put finalseed
if inBounds offspring lb ub
-- randomly selecting a candidate for deletion from the current population using a uniform probability distribution;
-- and keeping either the candidate or the offspring depending on wich one has higher fitness.
then return (replaceAtIndex pos_2 winner pop)
else return pop
--
-- Core generic function that generates n generations starting fom
-- the initial population using a probabilistic mutation function
-- [g] starting population
-- (g -> State StdGen g) mutation function
-- [[g]] accumulator
-- n number of steps remaining
-- IO [[g]] full history
--
generate :: (InBounds g, FitnessFunction g) => Float -> Float -> [g] -> [[g]] -> Int -> (g -> State StdGen g) -> State StdGen [[g]]
generate lb ub xs acc n f =
if n == 0
then do
ys <- evolve lb ub xs f
return ([ys]++[xs]++acc)
else do
ys <- evolve lb ub xs f
generate lb ub ys ([xs]++acc) (n-1) f
|
mezzomondo/dejong
|
src/Common.hs
|
Haskell
|
bsd-3-clause
| 8,238
|
-- | An index function represents a mapping from an array index space
-- to a flat byte offset.
module Futhark.Representation.ExplicitMemory.IndexFunction
(
IxFun(..)
, index
, iota
, offsetIndex
, strideIndex
, permute
, reshape
, applyInd
, base
, rebase
, shape
, rank
, linearWithOffset
, rearrangeWithOffset
, isDirect
)
where
import Data.Monoid
import Prelude hiding (div, quot)
import Futhark.Transform.Substitute
import Futhark.Transform.Rename
import Futhark.Representation.AST.Syntax (DimChange(..), ShapeChange)
import Futhark.Representation.AST.Attributes.Names
import Futhark.Representation.AST.Attributes.Reshape
import Futhark.Representation.AST.Attributes.Rearrange
import Futhark.Representation.AST.Pretty ()
import Futhark.Util.IntegralExp
import Futhark.Util.Pretty
type Shape num = [num]
type Indices num = [num]
type Permutation = [Int]
data IxFun num = Direct (Shape num)
| Offset (IxFun num) num
| Permute (IxFun num) Permutation
| Index (IxFun num) (Indices num)
| Reshape (IxFun num) (ShapeChange num)
| Stride (IxFun num) num
--- XXX: this is almost just structural equality, which may be too
--- conservative - unless we normalise first, somehow.
instance (IntegralCond num, Eq num) => Eq (IxFun num) where
Direct _ == Direct _ =
True
Offset ixfun1 offset1 == Offset ixfun2 offset2 =
ixfun1 == ixfun2 && offset1 == offset2
Permute ixfun1 perm1 == Permute ixfun2 perm2 =
ixfun1 == ixfun2 && perm1 == perm2
Index ixfun1 is1 == Index ixfun2 is2 =
ixfun1 == ixfun2 && is1 == is2
Reshape ixfun1 shape1 == Reshape ixfun2 shape2 =
ixfun1 == ixfun2 && length shape1 == length shape2
_ == _ = False
instance Show num => Show (IxFun num) where
show (Direct n) = "Direct (" ++ show n ++ ")"
show (Offset fun k) = "Offset (" ++ show fun ++ ", " ++ show k ++ ")"
show (Permute fun perm) = "Permute (" ++ show fun ++ ", " ++ show perm ++ ")"
show (Index fun is) = "Index (" ++ show fun ++ ", " ++ show is ++ ")"
show (Reshape fun newshape) = "Reshape (" ++ show fun ++ ", " ++ show newshape ++ ")"
show (Stride fun stride) = "Stride (" ++ show fun ++ ", " ++ show stride ++ ")"
instance Pretty num => Pretty (IxFun num) where
ppr (Direct dims) =
text "Direct" <> parens (commasep $ map ppr dims)
ppr (Offset fun k) = ppr fun <+> text "+" <+> ppr k
ppr (Permute fun perm) = ppr fun <> ppr perm
ppr (Index fun is) = ppr fun <> brackets (commasep $ map ppr is)
ppr (Reshape fun oldshape) =
ppr fun <> text "->" <>
parens (commasep (map ppr oldshape))
ppr (Stride fun stride) =
ppr fun <> text "*" <> ppr stride
instance (Eq num, IntegralCond num, Substitute num) => Substitute (IxFun num) where
substituteNames _ (Direct n) =
Direct n
substituteNames subst (Offset fun k) =
Offset (substituteNames subst fun) (substituteNames subst k)
substituteNames subst (Permute fun perm) =
Permute (substituteNames subst fun) perm
substituteNames subst (Index fun is) =
Index
(substituteNames subst fun)
(map (substituteNames subst) is)
substituteNames subst (Reshape fun newshape) =
reshape
(substituteNames subst fun)
(map (substituteNames subst) newshape)
substituteNames subst (Stride fun stride) =
Stride
(substituteNames subst fun)
(substituteNames subst stride)
instance FreeIn num => FreeIn (IxFun num) where
freeIn (Direct dims) = freeIn dims
freeIn (Offset ixfun e) = freeIn ixfun <> freeIn e
freeIn (Stride ixfun e) = freeIn ixfun <> freeIn e
freeIn (Permute ixfun _) = freeIn ixfun
freeIn (Index ixfun is) =
freeIn ixfun <> mconcat (map freeIn is)
freeIn (Reshape ixfun dims) =
freeIn ixfun <> freeIn dims
instance (Eq num, IntegralCond num, Substitute num, Rename num) => Rename (IxFun num) where
-- Because there is no mapM-like function on sized vectors, we
-- implement renaming by retrieving the substitution map, then using
-- 'substituteNames'. This is safe as index functions do not
-- contain their own bindings.
rename ixfun = do
subst <- renamerSubstitutions
return $ substituteNames subst ixfun
index :: (Pretty num, IntegralCond num) =>
IxFun num -> Indices num -> num -> num
index (Direct dims) is element_size =
sum (zipWith (*) is slicesizes) * element_size
where slicesizes = drop 1 $ sliceSizes dims
index (Offset fun offset) (i:is) element_size =
index fun ((i + offset) : is) element_size
index (Permute fun perm) is_new element_size =
index fun is_old element_size
where is_old = rearrangeShape (rearrangeInverse perm) is_new
index (Index fun is1) is2 element_size =
index fun (is1 ++ is2) element_size
index (Reshape fun newshape) is element_size =
let new_indices = reshapeIndex (shape fun) (newDims newshape) is
in index fun new_indices element_size
index (Stride fun stride) (i:is) element_size =
index fun (i * stride:is) element_size
index ixfun [] _ =
error $ "Empty index list provided to " ++ pretty ixfun
iota :: IntegralCond num =>
Shape num -> IxFun num
iota = Direct
offsetIndex :: IntegralCond num =>
IxFun num -> num -> IxFun num
offsetIndex = Offset
strideIndex :: IntegralCond num =>
IxFun num -> num -> IxFun num
strideIndex = Stride
permute :: IntegralCond num =>
IxFun num -> Permutation -> IxFun num
permute (Permute ixfun oldperm) perm
| rearrangeInverse oldperm == perm = ixfun
permute ixfun perm = Permute ixfun perm
reshape :: (Eq num, IntegralCond num) =>
IxFun num -> ShapeChange num -> IxFun num
reshape (Direct oldshape) newshape
| length oldshape == length newshape =
Direct $ map newDim newshape
reshape (Reshape ixfun _) newshape =
reshape ixfun newshape
reshape ixfun newshape
| shape ixfun == map newDim newshape =
ixfun
| rank ixfun == length newshape,
Just _ <- shapeCoercion newshape =
case ixfun of
Permute ixfun' perm ->
let ixfun'' = reshape ixfun' $
rearrangeShape (rearrangeInverse perm) newshape
in Permute ixfun'' perm
Offset ixfun' offset ->
Offset (reshape ixfun' newshape) offset
Stride{} ->
Reshape ixfun newshape
Index ixfun' is ->
let unchanged_shape =
map DimCoercion $ take (length is) $ shape ixfun'
newshape' = unchanged_shape ++ newshape
in applyInd (reshape ixfun' newshape') is
Reshape _ _ ->
Reshape ixfun newshape
Direct _ ->
Direct $ map newDim newshape
| otherwise =
Reshape ixfun newshape
applyInd :: IntegralCond num =>
IxFun num -> Indices num -> IxFun num
applyInd (Index ixfun mis) is =
Index ixfun $ mis ++ is
applyInd ixfun [] = ixfun
applyInd ixfun is = Index ixfun is
rank :: IntegralCond num =>
IxFun num -> Int
rank (Direct dims) = length dims
rank (Offset ixfun _) = rank ixfun
rank (Permute ixfun _) = rank ixfun
rank (Index ixfun is) = rank ixfun - length is
rank (Reshape _ newshape) = length newshape
rank (Stride ixfun _) = rank ixfun
shape :: IntegralCond num =>
IxFun num -> Shape num
shape (Direct dims) =
dims
shape (Permute ixfun perm) =
rearrangeShape perm $ shape ixfun
shape (Offset ixfun _) =
shape ixfun
shape (Index ixfun indices) =
drop (length indices) $ shape ixfun
shape (Reshape _ dims) =
map newDim dims
shape (Stride ixfun _) =
shape ixfun
base :: IxFun num -> Shape num
base (Direct dims) =
dims
base (Offset ixfun _) =
base ixfun
base (Permute ixfun _) =
base ixfun
base (Index ixfun _) =
base ixfun
base (Reshape ixfun _) =
base ixfun
base (Stride ixfun _) =
base ixfun
rebase :: (Eq num, IntegralCond num) =>
IxFun num
-> IxFun num
-> IxFun num
rebase new_base (Direct _) =
new_base
rebase new_base (Offset ixfun o) =
offsetIndex (rebase new_base ixfun) o
rebase new_base (Stride ixfun stride) =
strideIndex (rebase new_base ixfun) stride
rebase new_base (Permute ixfun perm) =
permute (rebase new_base ixfun) perm
rebase new_base (Index ixfun is) =
applyInd (rebase new_base ixfun) is
rebase new_base (Reshape ixfun new_shape) =
reshape (rebase new_base ixfun) new_shape
-- This function does not cover all possible cases. It's a "best
-- effort" kind of thing.
linearWithOffset :: IntegralCond num =>
IxFun num -> num -> Maybe num
linearWithOffset (Direct _) _ =
Just 0
linearWithOffset (Offset ixfun n) element_size = do
inner_offset <- linearWithOffset ixfun element_size
case drop 1 $ sliceSizes $ shape ixfun of
[] -> Nothing
rowslice : _ ->
return $ inner_offset + (n * rowslice * element_size)
linearWithOffset (Reshape ixfun _) element_size =
linearWithOffset ixfun element_size
linearWithOffset (Index ixfun is) element_size = do
inner_offset <- linearWithOffset ixfun element_size
let slices = take m $ drop 1 $ sliceSizes $ shape ixfun
return $ inner_offset + sum (zipWith (*) slices is) * element_size
where m = length is
linearWithOffset _ _ = Nothing
rearrangeWithOffset :: IntegralCond num =>
IxFun num -> num -> Maybe (num, [(Int,num)])
rearrangeWithOffset (Reshape ixfun _) element_size =
rearrangeWithOffset ixfun element_size
rearrangeWithOffset (Permute ixfun perm) element_size = do
offset <- linearWithOffset ixfun element_size
return (offset, zip perm $ rearrangeShape perm $ shape ixfun)
rearrangeWithOffset _ _ =
Nothing
isDirect :: (Eq num, IntegralCond num) => IxFun num -> Bool
isDirect =
maybe False (==0) . flip linearWithOffset 1
|
CulpaBS/wbBach
|
src/Futhark/Representation/ExplicitMemory/IndexFunction.hs
|
Haskell
|
bsd-3-clause
| 9,785
|
{-# LANGUAGE TypeOperators, DataKinds, TypeFamilies, NoMonomorphismRestriction #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Tests.OffSystemCSU where
import Data.Metrology.Poly
import Data.Metrology.SI
import qualified Data.Dimensions.SI as D
import Test.Tasty.HUnit
import Test.HUnit.Approx
type YardPond = MkLCSU '[ (D.Length, Foot)]
type LengthYP = MkQu_DLN D.Length YardPond Double
data Foot = Foot
instance Unit Foot where
type BaseUnit Foot = Meter
conversionRatio _ = 0.3048
data Year = Year
instance Unit Year where
type BaseUnit Year = Second
conversionRatio _ = 60 * 60 * 24 * 365.242
len1 :: LengthYP
len1 = 3 % Foot
len2 :: LengthYP
len2 = 1 % Meter
x :: Double
x = (len1 |+| len2) # Meter
tests = testCase "OffSystemCSU" (x @?~ 1.9144)
|
goldfirere/units
|
units-test/Tests/OffSystemCSU.hs
|
Haskell
|
bsd-3-clause
| 783
|
{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Monad (zipWithM)
import Diagrams.Prelude
import Diagrams.TwoD.Text
import Diagrams.Backend.SVG
data LabelProps = LabelProps
{ lFontSize :: Double
, lFontSlant :: FontSlant
, lStrutWidth :: Double
, lStrutHeight :: Double
}
data CurveProps = CurveProps
{ cLabelProps :: LabelProps
, cLabelSuperscripting :: Double
, cWidth :: Double
, cHeight :: Double
}
curveLabelProps :: LabelProps
curveLabelProps = LabelProps 1 FontSlantNormal 2 1
arrowLabelProps :: LabelProps
arrowLabelProps = LabelProps 0.75 FontSlantNormal 2 1
normalCurveProps :: CurveProps
normalCurveProps = CurveProps
{ cLabelProps = curveLabelProps
, cLabelSuperscripting = 1.5
, cWidth = 6
, cHeight = 3
}
subsumedCurveProps :: CurveProps
subsumedCurveProps = CurveProps
{ cLabelProps = curveLabelProps { lFontSize = 0.75, lStrutWidth = 2 }
, cLabelSuperscripting = 1
, cWidth = 3
, cHeight = 2.5
}
label' :: LabelProps -> String -> Diagram B R2
label' p l = text l # fontSizeL (lFontSize p)
# fontSlant (lFontSlant p)
# font "sans-serif"
<> strutX (lStrutWidth p)
<> strutY (lStrutHeight p)
label :: String -> Diagram B R2
label = label' curveLabelProps
arrowLabel :: String -> Diagram B R2
arrowLabel = label' arrowLabelProps
curve :: Double -> Double -> Diagram B R2
curve x y = roundedRect x y 0.5
namedCurve' :: CurveProps -> String -> Diagram B R2
namedCurve' p l = curve (cWidth p) (cHeight p) ||| lab
where
lab = label' (cLabelProps p) l # translateY (cLabelSuperscripting p)
namedCurve :: String -> Diagram B R2
namedCurve = namedCurve' normalCurveProps
subsumedCurve :: String -> Diagram B R2
subsumedCurve = namedCurve' subsumedCurveProps
mkArrow = connectOutside' (with & arrowShaft .~ shaft)
where
shaft = arc (0 @@ turn) (1/4 @@ turn) # reverseTrail
curveDog :: Diagram B R2
curveDog = namedCurve "Dog" # named "dog"
curveTail :: Diagram B R2
curveTail = namedCurve "Tail" # named "tail"
diagramDogSubsumePuppy :: Diagram B R2
diagramDogSubsumePuppy =
curveDog `atop` (curvePuppy # translateX (-1.25))
where
curvePuppy = subsumedCurve "Puppy"
diagramDogWagTail1 :: Diagram B R2
diagramDogWagTail1 =
curves # mkArrow "dog" "tail"
where
wagLabel = arrowLabel "wag" # translateY 1.25
curves = hcat [ curveDog, wagLabel, curveTail ]
diagramDogWagTail2 :: Diagram B R2
diagramDogWagTail2 =
curves # mkArrow "dog" "tail'"
where
wagLabel = arrowLabel "wag" # translateY 1.25
curves = hcat [ curveDog, wagLabel, curveTail `atop` curveTail' ]
curveTail' = curve 5 2.5 # named "tail'"
diagramAvfPattern :: Diagram B R2
diagramAvfPattern =
curves # mkArrow "c1" "c2'"
where
wagLabel = label' aprops "property" # translateY 2.5
curves = hcat [ curveC1, wagLabel, curveC2 `atop` curveC2' ]
curveC1 = (namedCurve' cprops "Class1" # named "c1") `atop` universe
curveC2 = (namedCurve' cprops "Class2" # named "c2") `atop` universe
curveC2' = curve 4 2.5 # named "c2'"
universe = rect 9 5 # translateX 1.5
aprops = arrowLabelProps { lFontSlant = FontSlantItalic
, lStrutWidth = 5
}
cprops = normalCurveProps
{ cWidth = 5
, cLabelProps = (cLabelProps normalCurveProps) { lFontSlant = FontSlantItalic }
, cLabelSuperscripting = 2
}
diagrams :: [(Diagram B R2, String)]
diagrams =
[ (curveDog, "curve")
, (diagramDogSubsumePuppy, "subsumption")
, (diagramDogWagTail1, "simple-property")
, (diagramDogWagTail2, "avf-property")
, (diagramAvfPattern, "avf-pattern")
]
everything :: Diagram B R2
everything = vcat' (with & sep .~ 2) (map fst diagrams)
main :: IO ()
main =
mapM_ mkSvg $ (everything, "all") : diagrams
where
mkSvg (d,fp) = renderSVG ("diagram-" <> fp <> ".svg") spec d
spec = mkSizeSpec (Just 400) Nothing
|
kowey/conceptdiagram-examples
|
conceptdiagram-examples.hs
|
Haskell
|
bsd-3-clause
| 4,007
|
[(Call, Env aam, Store d aam, Time aam)]
|
davdar/quals
|
writeup-old/sections/04MonadicAAM/04Optimizations/00Widen/00BeforeSS.hs
|
Haskell
|
bsd-3-clause
| 41
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
-- |
-- Module : Data.Array.Nikola.Language.Monad
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <mainland@apeiron.net>
-- Stability : experimental
-- Portability : non-portable
module Data.Array.Nikola.Language.Monad (
emptyREnv,
defaultREnv,
REnv,
R,
H,
P,
runR,
reset,
shift,
getFlags,
gensym,
lookupExp,
extendExps,
lookupStableName,
insertStableName,
lamE,
letE,
mkLetE,
inNewScope
) where
import Control.Applicative
import Control.Monad.Cont
import Control.Monad.State
import Data.Dynamic
import qualified Data.IntMap as IntMap
import Data.List (foldl')
import qualified Data.Map as Map
import System.Mem.StableName
import Text.PrettyPrint.Mainland
import Data.Array.Nikola.Backend.Flags
import Data.Array.Nikola.Language.Check
import Data.Array.Nikola.Language.Syntax
-- import Data.Array.Nikola.Pretty
type StableNameHash = Int
data REnv = REnv
{ rUniq :: Int
, rFlags :: Flags
, rContext :: Context
, rVarTypes :: Map.Map Var Type
, rExpCache :: Map.Map Exp Exp
, rSharingCache :: IntMap.IntMap [(Dynamic, Exp)]
}
deriving (Typeable)
emptyREnv :: Flags -> REnv
emptyREnv flags = REnv
{ rUniq = 0
, rFlags = flags
, rContext = Host
, rVarTypes = Map.empty
, rExpCache = Map.empty
, rSharingCache = IntMap.empty
}
defaultREnv :: REnv
defaultREnv = emptyREnv defaultFlags
instance Show (StableName Exp) where
show _ = "StableName Exp"
newtype R r a = R { unR :: REnv -> (REnv -> a -> IO (REnv, r)) -> IO (REnv, r) }
deriving (Typeable)
runR :: R a a -> REnv -> IO (REnv, a)
runR m env = unR m env (\s x -> return (s, x))
instance Monad (R r) where
return a = R $ \s k -> k s a
m >>= f = R $ \s k -> unR m s $ \s' x -> unR (f x) s' k
m1 >> m2 = R $ \s k -> unR m1 s $ \s' _ -> unR m2 s' k
fail err = R $ \_ _ -> fail err
instance Functor (R r) where
fmap f x = x >>= return . f
instance Applicative (R r) where
pure = return
(<*>) = ap
instance MonadState REnv (R r) where
get = R $ \s k -> k s s
put s = R $ \_ k -> k s ()
instance MonadIO (R r) where
liftIO m = R $ \s k -> m >>= \x -> k s x
instance MonadCont (R r) where
-- callCC :: ((a -> R r b) -> R r a) -> R r a
callCC f = R $ \s k -> unR (f (\a -> R $ \s _ -> k s a)) s k
reset :: R a a -> R r a
reset m = R $ \s k -> do (s', x) <- unR m s $ \s' x -> return (s', x)
k s' x
shift :: ((a -> R r r) -> R r r) -> R r a
shift f = R $ \s k ->
let c = \x -> R $ \s k' -> do (s', y) <- k s x
k' s' y
in
runR (f c) s
getFlags :: R r Flags
getFlags = gets rFlags
instance MonadCheck (R r) where
getContext = gets rContext
setContext ctx = modify $ \s -> s { rContext = ctx }
lookupVarType v = do
maybe_tau <- gets $ \s -> Map.lookup v (rVarTypes s)
case maybe_tau of
Just tau -> return tau
Nothing -> faildoc $ text "Variable" <+> ppr v <+>
text "not in scope."
extendVarTypes vtaus act = do
old_vtaus <- gets rVarTypes
modify $ \s -> s { rVarTypes = foldl' insert (rVarTypes s) vtaus }
x <- act
modify $ \s -> s { rVarTypes = old_vtaus }
return x
where
insert m (k, v) = Map.insert k v m
-- | Our monad for constructing host programs
type H a = R Exp a
-- | Our monad for constructing kernels
type P a = R Exp a
gensym :: String -> R r Var
gensym v = do
u <- gets rUniq
modify $ \s -> s { rUniq = u + 1 }
return $ Var (v ++ "_" ++ show u)
lookupExp :: Exp -> R r (Maybe Exp)
lookupExp e =
gets $ \s -> Map.lookup e (rExpCache s)
extendExps :: [(Exp, Exp)] -> R r a -> R r a
extendExps es kont = do
cache <- gets rExpCache
modify $ \s -> s { rExpCache = foldl' insert (rExpCache s) es }
x <- kont
modify $ \s -> s { rExpCache = cache }
return x
where
insert m (k, v) = Map.insert k v m
lookupStableName :: Typeable a => StableName a -> R r (Maybe Exp)
lookupStableName sn = do
cache <- gets rSharingCache
case IntMap.lookup hash cache of
Just xs -> return $ Prelude.lookup (Just sn)
[(fromDynamic d,x) | (d,x) <- xs]
Nothing -> return Nothing
where
hash :: StableNameHash
hash = hashStableName sn
insertStableName :: Typeable a => StableName a -> Exp -> R r ()
insertStableName sn e =
modify $ \s ->
s { rSharingCache = IntMap.alter add (hashStableName sn)
(rSharingCache s) }
where
add :: Maybe [(Dynamic, Exp)] -> Maybe [(Dynamic, Exp)]
add Nothing = Just [(toDyn sn, e)]
add (Just xs) = Just ((toDyn sn, e) : xs)
lamE :: [(Var, Type)] -> R Exp Exp -> R Exp Exp
lamE vtaus m = do
e <- extendVarTypes vtaus $ reset $ m
case e of
LamE vtaus' e -> return $ LamE (vtaus ++ vtaus') e
_ -> return $ LamE vtaus e
letE :: Var -> Type -> Exp -> R Exp Exp
letE v tau e =
shift $ \k -> do
body <- extendVarTypes [(v, tau)] $
extendExps [(e, VarE v)] $
reset $
k (VarE v)
return $ LetE v tau Many e body
-- We never let-bind atomic expressions or monadic values.
mkLetE :: Exp -> R Exp Exp
mkLetE e | isAtomicE e =
return e
mkLetE e = do
tau <- inferExp e
if isMT tau
then return e
else do v <- if isFunT tau then gensym "f" else gensym "v"
letE v tau e
inNewScope :: Bool -> R a a -> R r a
inNewScope isLambda comp = do
expCache <- gets rExpCache
sharingCache <- gets rSharingCache
when isLambda $ do
modify $ \s -> s { rExpCache = Map.empty
, rSharingCache = IntMap.empty
}
a <- reset comp
modify $ \s -> s { rExpCache = expCache
, rSharingCache = sharingCache
}
return a
|
mainland/nikola
|
src/Data/Array/Nikola/Language/Monad.hs
|
Haskell
|
bsd-3-clause
| 6,454
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Region
( Region(..)
) where
import Data.Hashable
import GHC.Generics
import Prelude
import TextShow (TextShow)
import qualified TextShow as TS
-- | ISO 3166-1 alpha-2 Country code (includes regions and territories).
-- See https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
data Region
= AR
| AU
| BE
| BZ
| CA
| CL
| CN
| CO
| EG
| ES
| GB
| HK
| IE
| IN
| JM
| MN
| MX
| MO
| NL
| NZ
| PE
| PH
| TT
| TW
| US
| VE
| ZA
deriving (Bounded, Enum, Eq, Generic, Hashable, Ord, Read, Show)
instance TextShow Region where
showb = TS.fromString . show
|
facebookincubator/duckling
|
Duckling/Region.hs
|
Haskell
|
bsd-3-clause
| 932
|
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Either
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- The Either type, and associated operations.
--
-----------------------------------------------------------------------------
module Data.Either (
Either(..),
either -- :: (a -> c) -> (b -> c) -> Either a b -> c
) where
|
OS2World/DEV-UTIL-HUGS
|
libraries/Data/Either.hs
|
Haskell
|
bsd-3-clause
| 609
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.TextureSwizzle
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.TextureSwizzle (
-- * Extension Support
glGetEXTTextureSwizzle,
gl_EXT_texture_swizzle,
-- * Enums
pattern GL_TEXTURE_SWIZZLE_A_EXT,
pattern GL_TEXTURE_SWIZZLE_B_EXT,
pattern GL_TEXTURE_SWIZZLE_G_EXT,
pattern GL_TEXTURE_SWIZZLE_RGBA_EXT,
pattern GL_TEXTURE_SWIZZLE_R_EXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/EXT/TextureSwizzle.hs
|
Haskell
|
bsd-3-clause
| 806
|
{-# LANGUAGE TypeApplications #-}
module Database.PostgreSQL.PQTypes.JSON
( JSON(..)
, JSONB(..)
, aesonFromSQL
, aesonToSQL
) where
import Data.Aeson
import Foreign.Ptr
import qualified Control.Exception as E
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Database.PostgreSQL.PQTypes.Format
import Database.PostgreSQL.PQTypes.FromSQL
import Database.PostgreSQL.PQTypes.Internal.C.Types
import Database.PostgreSQL.PQTypes.ToSQL
-- | Wrapper for (de)serializing underlying type as 'json'.
newtype JSON json = JSON { unJSON :: json }
deriving (Eq, Functor, Ord, Show)
instance PQFormat (JSON json) where
pqFormat = BS.pack "%json"
instance FromSQL (JSON BS.ByteString) where
type PQBase (JSON BS.ByteString) = PGbytea
fromSQL = fmap JSON . fromSQL
instance FromSQL (JSON BSL.ByteString) where
type PQBase (JSON BSL.ByteString) = PGbytea
fromSQL = fmap JSON . fromSQL
instance ToSQL (JSON BS.ByteString) where
type PQDest (JSON BS.ByteString) = PGbytea
toSQL = toSQL . unJSON
instance ToSQL (JSON BSL.ByteString) where
type PQDest (JSON BSL.ByteString) = PGbytea
toSQL = toSQL . unJSON
instance FromSQL (JSON Value) where
type PQBase (JSON Value) = PGbytea
fromSQL = fmap JSON . aesonFromSQL
instance ToSQL (JSON Value) where
type PQDest (JSON Value) = PGbytea
toSQL = aesonToSQL . unJSON
----------------------------------------
-- | Wrapper for (de)serializing underlying type as 'jsonb'.
newtype JSONB jsonb = JSONB { unJSONB :: jsonb }
deriving (Eq, Functor, Ord, Show)
instance PQFormat (JSONB jsonb) where
pqFormat = BS.pack "%jsonb"
instance FromSQL (JSONB BS.ByteString) where
type PQBase (JSONB BS.ByteString) = PGbytea
fromSQL = fmap JSONB . fromSQL
instance FromSQL (JSONB BSL.ByteString) where
type PQBase (JSONB BSL.ByteString) = PGbytea
fromSQL = fmap JSONB . fromSQL
instance ToSQL (JSONB BS.ByteString) where
type PQDest (JSONB BS.ByteString) = PGbytea
toSQL = toSQL . unJSONB
instance ToSQL (JSONB BSL.ByteString) where
type PQDest (JSONB BSL.ByteString) = PGbytea
toSQL = toSQL . unJSONB
instance FromSQL (JSONB Value) where
type PQBase (JSONB Value) = PGbytea
fromSQL = fmap JSONB . aesonFromSQL
instance ToSQL (JSONB Value) where
type PQDest (JSONB Value) = PGbytea
toSQL = aesonToSQL . unJSONB
----------------------------------------
-- | Helper for defining 'FromSQL' instance for a type with 'FromJSON' instance.
--
-- @since 1.9.1.0
aesonFromSQL :: FromJSON t => Maybe PGbytea -> IO t
aesonFromSQL mbase = do
evalue <- eitherDecodeStrict' <$> fromSQL mbase
case evalue of
Left err -> E.throwIO . E.ErrorCall $ "aesonFromSQL: " ++ err
Right value -> return value
-- | Helper for defining 'ToSQL' instance for a type with 'ToJSON' instance.
--
-- @since 1.9.1.0
aesonToSQL
:: ToJSON t
=> t
-> ParamAllocator
-> (Ptr PGbytea -> IO r)
-> IO r
aesonToSQL = toSQL . BSL.toStrict . encode
|
scrive/hpqtypes
|
src/Database/PostgreSQL/PQTypes/JSON.hs
|
Haskell
|
bsd-3-clause
| 2,970
|
{-# OPTIONS_GHC -fno-warn-tabs #-}
import Common
main = putStrLn "=== Challange15 ==="
-- Challange done in library code
|
andrewcchen/matasano-cryptopals-solutions
|
set2/Challange15.hs
|
Haskell
|
bsd-3-clause
| 124
|
module Koriel.Core.LambdaLift
( lambdalift,
)
where
import Control.Lens (At (at), Lens', lens, traverseOf, traversed, use, (<>=), (?=))
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import Koriel.Core.Flat
import Koriel.Core.Syntax
import Koriel.Core.Type
import Koriel.Id
import Koriel.MonadUniq
import Koriel.Prelude
import Relude.Extra.Map (member)
data LambdaLiftState = LambdaLiftState
{ _funcs :: HashMap (Id Type) ([Id Type], Exp (Id Type)),
_knowns :: HashSet (Id Type)
}
funcs :: Lens' LambdaLiftState (HashMap (Id Type) ([Id Type], Exp (Id Type)))
funcs = lens _funcs (\l x -> l {_funcs = x})
knowns :: Lens' LambdaLiftState (HashSet (Id Type))
knowns = lens _knowns (\l x -> l {_knowns = x})
lambdalift :: MonadIO m => UniqSupply -> Program (Id Type) -> m (Program (Id Type))
lambdalift us Program {..} =
runReaderT ?? us $
evalStateT ?? LambdaLiftState {_funcs = mempty, _knowns = HashSet.fromList $ map fst _topFuncs} $ do
topFuncs <- traverse (\(f, (ps, e)) -> (f,) . (ps,) <$> llift e) _topFuncs
funcs <>= HashMap.fromList topFuncs
knowns <>= HashSet.fromList (map fst topFuncs)
LambdaLiftState {_funcs} <- get
-- TODO: lambdalift _topVars
traverseOf appProgram (pure . flat) $ Program _moduleName _topVars (HashMap.toList _funcs)
llift :: (MonadIO f, MonadState LambdaLiftState f, MonadReader UniqSupply f) => Exp (Id Type) -> f (Exp (Id Type))
llift (Call (Var f) xs) = do
ks <- use knowns
if f `member` ks then pure $ CallDirect f xs else pure $ Call (Var f) xs
llift (Let [LocalDef n (Fun xs call@Call {})] e) = do
call' <- llift call
Let [LocalDef n (Fun xs call')] <$> llift e
llift (Let [LocalDef n o@(Fun _ ExtCall {})] e) = Let [LocalDef n o] <$> llift e
llift (Let [LocalDef n o@(Fun _ CallDirect {})] e) = Let [LocalDef n o] <$> llift e
llift (Let [LocalDef n (Fun as body)] e) = do
backup <- get
ks <- use knowns
-- nがknownだと仮定してlambda liftする
knowns . at n ?= ()
body' <- llift body
funcs . at n ?= (as, body')
(e', _) <- localState $ llift e
-- (Fun as body')の自由変数がknownsを除いてなく、e'の自由変数にnが含まれないならnはknown
-- (Call n _)は(CallDirect n _)に変換されているので、nが値として使われているときのみ自由変数になる
let fvs = HashSet.difference (freevars body') (ks <> HashSet.fromList as)
if null fvs && not (n `member` freevars e')
then llift e
else do
put backup
body' <- llift body
let fvs = HashSet.difference (freevars body') (ks <> HashSet.fromList as)
newFun <- def (idToText n) (toList fvs <> as) body'
Let [LocalDef n (Fun as (CallDirect newFun $ map Var $ toList fvs <> as))] <$> llift e
llift (Let ds e) = Let ds <$> llift e
llift (Match e cs) = Match <$> llift e <*> traverseOf (traversed . appCase) llift cs
llift e = pure e
def :: (MonadIO m, MonadState LambdaLiftState m, MonadReader env m, HasUniqSupply env) => Text -> [Id Type] -> Exp (Id Type) -> m (Id Type)
def name xs e = do
f <- newInternalId ("$raw_" <> name) (map typeOf xs :-> typeOf e)
funcs . at f ?= (xs, e)
pure f
|
takoeight0821/malgo
|
src/Koriel/Core/LambdaLift.hs
|
Haskell
|
bsd-3-clause
| 3,195
|
module Day7 where
import Data.List
import qualified Data.List.Split as LS
data IP = IP { normal :: [String], hyper :: [String] }
deriving Show
parseIP :: String -> IP
parseIP s = let (normal,hyper) = foldr (\y ~(xs,ys) -> (y:ys,xs)) ([],[]) ss
ss = LS.splitOneOf "[]" s
in IP normal hyper
hasABBA :: String -> Bool
hasABBA = any match . fours
where
match [a,b,c,d] = a == d && b == c && a /= b
fours = init . init . init . init . map (take 4) . tails
hasSSL :: IP -> Bool
hasSSL ip = any hasBAB abas
where
threes = init . init . init . map (take 3) . tails
abas = filter (\[a,b,c] -> a == c) . concatMap threes . normal $ ip
hasBAB [a,b,c] = any (\[x,y,z] -> x == b && y == a && z == b) (concatMap threes . hyper $ ip)
hasTLS :: IP -> Bool
hasTLS (IP normal hyper) = any hasABBA normal && all (not . hasABBA) hyper
run :: (IP -> Bool) -> IO Int
run f = length . filter (f . parseIP) . lines <$> readFile "./input/d7.txt"
runFirst = run hasTLS
runSecond = run hasSSL
testTLSGood1 = "abba[mnop]qrst"
testTLSBad1 = "abcd[bddb]xyyx"
testTLSBad2 = "aaaa[qwer]tyui"
testTLSGood2 = "ioxxoj[asdfgh]zxcvbn"
testSSLGood1 = "aba[bab]xyz"
testSSLBad1 = "xyx[xyx]xyx"
testSSLGood2 = "aaa[kek]eke"
testSSLGood3 = "zazbz[bzb]cdb"
|
MarcelineVQ/advent2016
|
src/Day7.hs
|
Haskell
|
bsd-3-clause
| 1,280
|
module Cache
( File
, CacheSize
, CacheStatistic
, getCacheStatistic
, calculateHits
, Cache (..)
, fits
, WriteStrategy (..)
, biggerAsMax
)
where
import Prelude hiding (fail)
import Request
type File = (FileID, FileSize)
type CacheSize = Int
type CacheStatistic = (Int, Int)
data WriteStrategy = Invalidate | AddToCache deriving (Eq, Show)
class Cache a where
to :: File -> a -> a
readFromCache :: File -> a -> (Bool, a)
remove :: File -> a -> a
empty :: CacheSize -> WriteStrategy -> a
size :: a -> CacheSize
maxSize :: a -> CacheSize
writeStrategy :: a -> WriteStrategy
getCacheStatistic :: Cache a => String -> a -> IO CacheStatistic
getCacheStatistic fileName cache = (`calculateHits` ((0, 0), cache)) `forEachFileRequestIn` fileName
--getCacheStatistic fileName cache = (fst . foldl' calculateHits' ((0, 0), cache)) `forEachFileRequestIn` fileName
calculateHits :: Cache a => [FileRequest] -> (CacheStatistic, a) -> CacheStatistic
calculateHits [] (stats, _) = stats
calculateHits ((Read, fileID, fileSize) : rest) (stats, cache) =
let (readResult, updatedCache) = readFromCache (fileID, fileSize) cache
in calculateHits rest (boolToCacheStatistic readResult stats, updatedCache)
calculateHits ((Write, fileID, fileSize) : rest) (stats, cache)
| writeStrategy cache == Invalidate = calculateHits rest (stats, cacheWithoutFile)
| otherwise = calculateHits rest (stats, file `to` cacheWithoutFile)
where file = (fileID, fileSize)
cacheWithoutFile = remove file cache -- invalidate possible old version before adding it to the cache
calculateHits ((Remove, fileID, fileSize) : rest) (stats, cache) =
let file = (fileID, fileSize)
updatedCache = remove file cache
in calculateHits rest (stats, updatedCache)
calculateHits' :: Cache a => (CacheStatistic, a) -> FileRequest -> (CacheStatistic, a)
calculateHits' (stats, cache) (Read, fileID, fileSize) =
let (readResult, cache') = readFromCache (fileID, fileSize) cache
in (boolToCacheStatistic readResult stats, cache')
calculateHits' (stats, cache) (Write, fileID, fileSize)
| writeStrategy cache == Invalidate = (stats, cacheWithoutFile)
| otherwise = (stats, file `to` cacheWithoutFile)
where file = (fileID, fileSize)
cacheWithoutFile = remove file cache
calculateHits' (stats, cache) (Remove, fileID, fileSize) =
let file = (fileID, fileSize)
cache' = remove file cache
in (stats, cache')
boolToCacheStatistic :: Bool -> CacheStatistic -> CacheStatistic
boolToCacheStatistic True = hit
boolToCacheStatistic _ = fail
hit :: CacheStatistic -> CacheStatistic
hit (hits, fails) = (hits + 1, fails)
fail :: CacheStatistic -> CacheStatistic
fail (hits, fails) = (hits, fails + 1)
fits :: Cache a => File -> a -> Bool
fits (_, fileSize) cache =
let cacheSize = size cache
maxCacheSize = maxSize cache
futureSize = fileSize + cacheSize
in futureSize <= maxCacheSize
biggerAsMax :: Cache a => File -> a -> Bool
biggerAsMax (_, fileSize) cache = fileSize > maxSize cache
|
wochinge/CacheSimulator
|
src/Cache.hs
|
Haskell
|
bsd-3-clause
| 3,106
|
module Main where
import qualified Bot
main :: IO ()
main = Bot.run
|
wimdu/alonzo
|
src/Main.hs
|
Haskell
|
mit
| 70
|
<?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="zh-CN">
<title>Ruby Scripting</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>搜索</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/jruby/src/main/javahelp/org/zaproxy/zap/extension/jruby/resources/help_zh_CN/helpset_zh_CN.hs
|
Haskell
|
apache-2.0
| 960
|
module BCode
( BCode(..)
, BCodePath(..)
, encode
, decode
, search
, searchInt
, searchStr
) where
import Control.Applicative ((<$>), (<*>), (<|>), (*>), (<*))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import Data.Char (ord, isDigit, digitToInt)
import Data.Map (Map)
import qualified Data.Map as M
import Data.Word (Word8)
import Text.Parsec.ByteString (Parser)
import qualified Text.Parsec.Char as P
import qualified Text.Parsec.Error as P
import qualified Text.Parsec.Combinator as P
import qualified Text.ParserCombinators.Parsec.Prim as P
data BCode
= BInt Integer
| BStr ByteString
| BList [BCode]
| BDict (Map ByteString BCode)
deriving (Show, Read, Ord, Eq)
instance Eq P.ParseError where
_ == _ = False
toW8 :: Char -> Word8
toW8 = fromIntegral . ord
wrap :: Char -> Char -> ByteString -> ByteString
wrap a b c = B.concat [B8.pack [a], c, B8.pack [b]]
between :: Char -> Char -> Parser a -> Parser a
between a b c = P.char a *> c <* P.char b
getUInt :: (Num a) => Parser a
getUInt = fromIntegral <$> digit
where
digit = str2int <$> P.many1 (P.satisfy isDigit)
str2int = foldl (\acc x -> acc * 10 + digitToInt x) 0
getBInt :: Parser BCode
getBInt = BInt <$> between 'i' 'e' getInt
where
sign = (P.char '-' >> return negate) <|> return id
getInt = sign <*> getUInt
getBStr :: Parser BCode
getBStr = do
count <- getUInt
P.char ':'
BStr . B8.pack <$> P.count count P.anyToken
getBList :: Parser BCode
getBList = BList <$> between 'l' 'e' (P.many getBCode)
getBDict :: Parser BCode
getBDict = BDict . M.fromList <$> between 'd' 'e' (P.many getPair)
where
getPair = do
(BStr key) <- getBStr
value <- getBCode
return (key, value)
getBCode :: Parser BCode
getBCode = getBInt <|> getBStr <|> getBList <|> getBDict
decode :: ByteString -> Either P.ParseError BCode
decode input = P.parse getBCode "" input
encode :: BCode -> ByteString
encode = put
where
put (BInt i) = wrap 'i' 'e' $ int2bs i
put (BStr s) = B.concat [int2bs $ B.length s, B8.pack ":", s]
put (BList l) = wrap 'l' 'e' $ B.concat (map put l)
put (BDict d) = wrap 'd' 'e' $ B.concat (map encodePair $ M.toList d)
int2bs :: (Integral a) => a -> ByteString
int2bs = B8.pack . show . fromIntegral
encodePair :: (ByteString, BCode) -> ByteString
encodePair (k, v) = put (BStr k) `B.append` put v
data BCodePath = BCodePInt Int
| BCodePStr String
search :: [BCodePath] -> BCode -> Maybe BCode
search [] a = Just a
search (BCodePInt x:xs) (BList l)
| x < 0 || (x + 1) > length l = Nothing
| otherwise = search xs (l !! x)
search (BCodePStr x:xs) (BDict d) =
M.lookup (B8.pack x) d >>= search xs
search _ _ = Nothing
searchInt :: String -> BCode -> Maybe Integer
searchInt key bc = do
(BInt i) <- search [BCodePStr key] bc
return i
searchStr :: String -> BCode -> Maybe ByteString
searchStr key bc = do
(BStr s) <- search [BCodePStr key] bc
return s
|
artems/htorr
|
src/BCode.hs
|
Haskell
|
bsd-3-clause
| 3,114
|
{-
- Copyright (c) 2010 Mats Rauhala <mats.rauhala@gmail.com>
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the "Software"), to deal in the Software without
- restriction, including without limitation the rights to use,
- copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the
- Software is furnished to do so, subject to the following
- conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
-}
module Files where
import System.Directory (doesFileExist, getDirectoryContents)
import System.FilePath
import Control.Monad (forM)
import Control.Monad.Error
import Data.List (isPrefixOf)
batterydir :: FilePath
batterydir = "/sys/class/power_supply/"
batteryfile :: ErrorT String IO FilePath
batteryfile = do
all <- liftIO $ getDirectoryContents batterydir
case filter (("BAT" `isPrefixOf`)) all of
[] -> throwError "No batteries present"
(x:_) -> return $ batterydir </> x
full :: ErrorT String IO FilePath
full = (</> "charge_full") `fmap` batteryfile
charge :: ErrorT String IO FilePath
charge = (</> "charge_now") `fmap` batteryfile
status :: ErrorT String IO FilePath
status = (</> "status") `fmap` batteryfile
readFileM :: FilePath -> ErrorT String IO String
readFileM = liftIO . readFile
|
sjakobi/zsh-battery
|
Files.hs
|
Haskell
|
bsd-3-clause
| 1,995
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.OrgMode.Parse.Attoparsec.Section
-- Copyright : © 2015 Parnell Springmeyer
-- License : All Rights Reserved
-- Maintainer : Parnell Springmeyer <parnell@digitalmentat.com>
-- Stability : stable
--
-- Parsing combinators for org-mode sections.
----------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Data.OrgMode.Parse.Attoparsec.Section where
import Control.Applicative ((<$>), (<*>), (<|>))
import Data.Attoparsec.Text as T
import Data.Attoparsec.Types as TP
import Data.Monoid (mempty)
import Data.Text (Text, pack,
unlines)
import Prelude hiding (unlines)
import Data.OrgMode.Parse.Attoparsec.PropertyDrawer
import Data.OrgMode.Parse.Attoparsec.Time
import Data.OrgMode.Parse.Types
-- | Parse a heading section
--
-- Heading sections contain optionally a property drawer,
-- a list of clock entries, code blocks (not yet implemented),
-- plain lists (not yet implemented), and unstructured text.
parseSection :: TP.Parser Text Section
parseSection = Section
<$> (Plns <$> parsePlannings)
<*> many' parseClock
<*> option mempty parseDrawer
<*> (unlines <$> many' nonHeaderLine)
where
-- | Parse a non-heading line of a section.
nonHeaderLine :: TP.Parser Text Text
nonHeaderLine = nonHeaderLine0 <|> nonHeaderLine1
where
nonHeaderLine0 = endOfLine >> return (pack "")
nonHeaderLine1 = pack <$> do
h <- notChar '*'
t <- manyTill anyChar endOfLine
return (h:t)
|
imalsogreg/orgmode-parse
|
src/Data/OrgMode/Parse/Attoparsec/Section.hs
|
Haskell
|
bsd-3-clause
| 1,970
|
module Reflex.DynamicWriter
{-# DEPRECATED "Use 'Reflex.DynamicWriter.Class' and 'Reflex.DynamicWrite.Base' instead, or just import 'Reflex'" #-}
( module X
) where
import Reflex.DynamicWriter.Base as X
import Reflex.DynamicWriter.Class as X
|
ryantrinkle/reflex
|
src/Reflex/DynamicWriter.hs
|
Haskell
|
bsd-3-clause
| 249
|
{-# LANGUAGE TupleSections, GeneralizedNewtypeDeriving #-}
-- |A simple graph implementation backed by 'Data.HashMap'.
module Data.RDF.MGraph(MGraph, empty, mkRdf, triplesOf, uniqTriplesOf, select, query)
where
import Prelude hiding (pred)
import Control.DeepSeq (NFData)
import Data.RDF.Types
import Data.RDF.Query
import Data.RDF.Namespace
import qualified Data.Map as Map
import Data.Hashable()
import Data.HashMap.Strict(HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.HashSet(HashSet)
import qualified Data.HashSet as Set
import Data.List
-- |A map-based graph implementation.
--
-- Worst-case time complexity of the graph functions, with respect
-- to the number of triples, are:
--
-- * 'empty' : O(1)
--
-- * 'mkRdf' : O(n)
--
-- * 'triplesOf': O(n)
--
-- * 'select' : O(n)
--
-- * 'query' : O(log n)
newtype MGraph = MGraph (TMaps, Maybe BaseUrl, PrefixMappings)
deriving (NFData)
instance RDF MGraph where
baseUrl = baseUrl'
prefixMappings = prefixMappings'
addPrefixMappings = addPrefixMappings'
empty = empty'
mkRdf = mkRdf'
triplesOf = triplesOf'
uniqTriplesOf = uniqTriplesOf'
select = select'
query = query'
instance Show MGraph where
show gr = concatMap (\t -> show t ++ "\n") (triplesOf gr)
-- some convenience type alias for readability
-- An adjacency map for a subject, mapping from a predicate node to
-- to the adjacent nodes via that predicate.
type AdjacencyMap = HashMap Predicate (HashSet Node)
type Adjacencies = HashSet Node
type TMap = HashMap Node AdjacencyMap
type TMaps = (TMap, TMap)
baseUrl' :: MGraph -> Maybe BaseUrl
baseUrl' (MGraph (_, baseURL, _)) = baseURL
prefixMappings' :: MGraph -> PrefixMappings
prefixMappings' (MGraph (_, _, pms)) = pms
addPrefixMappings' :: MGraph -> PrefixMappings -> Bool -> MGraph
addPrefixMappings' (MGraph (ts, baseURL, pms)) pms' replace =
let merge = if replace then flip mergePrefixMappings else mergePrefixMappings
in MGraph (ts, baseURL, merge pms pms')
empty' :: MGraph
empty' = MGraph ((HashMap.empty, HashMap.empty), Nothing, PrefixMappings Map.empty)
mkRdf' :: Triples -> Maybe BaseUrl -> PrefixMappings -> MGraph
mkRdf' ts baseURL pms = MGraph (mergeTs (HashMap.empty, HashMap.empty) ts, baseURL, pms)
mergeTs :: TMaps -> [Triple] -> TMaps
mergeTs = foldl' mergeT
where
mergeT :: TMaps -> Triple -> TMaps
mergeT m t = mergeT' m (subjectOf t) (predicateOf t) (objectOf t)
mergeT' :: TMaps -> Subject -> Predicate -> Object -> TMaps
mergeT' (spo, ops) s p o = (mergeT'' spo s p o, mergeT'' ops o p s)
mergeT'' :: TMap -> Subject -> Predicate -> Object -> TMap
mergeT'' m s p o =
if s `HashMap.member` m then
(if p `HashMap.member` adjs then HashMap.insert s addPredObj m
else HashMap.insert s addNewPredObjMap m)
else HashMap.insert s newPredMap m
where
adjs = HashMap.lookupDefault HashMap.empty s m
newPredMap :: HashMap Predicate (HashSet Object)
newPredMap = HashMap.singleton p (Set.singleton o)
addNewPredObjMap :: HashMap Predicate (HashSet Object)
addNewPredObjMap = HashMap.insert p (Set.singleton o) adjs
addPredObj :: HashMap Predicate (HashSet Object)
addPredObj = HashMap.insert p (Set.insert o (get p adjs)) adjs
--get :: (Ord k, Hashable k) => k -> HashMap k v -> v
get = HashMap.lookupDefault Set.empty
-- 3 following functions support triplesOf
triplesOf' :: MGraph -> Triples
triplesOf' (MGraph ((spoMap, _), _, _)) = concatMap (uncurry tripsSubj) subjPredMaps
where subjPredMaps = HashMap.toList spoMap
-- naive implementation for now
uniqTriplesOf' :: MGraph -> Triples
uniqTriplesOf' = nub . expandTriples
tripsSubj :: Subject -> AdjacencyMap -> Triples
tripsSubj s adjMap = concatMap (uncurry (tfsp s)) (HashMap.toList adjMap)
where tfsp = tripsForSubjPred
tripsForSubjPred :: Subject -> Predicate -> Adjacencies -> Triples
tripsForSubjPred s p adjs = map (Triple s p) (Set.toList adjs)
-- supports select
select' :: MGraph -> NodeSelector -> NodeSelector -> NodeSelector -> Triples
select' (MGraph ((spoMap,_),_,_)) subjFn predFn objFn =
map (\(s,p,o) -> Triple s p o) $ Set.toList $ sel1 subjFn predFn objFn spoMap
sel1 :: NodeSelector -> NodeSelector -> NodeSelector -> TMap -> HashSet (Node, Node, Node)
sel1 (Just subjFn) p o spoMap =
Set.unions $ map (sel2 p o) $ filter (\(x,_) -> subjFn x) $ HashMap.toList spoMap
sel1 Nothing p o spoMap = Set.unions $ map (sel2 p o) $ HashMap.toList spoMap
sel2 :: NodeSelector -> NodeSelector -> (Node, HashMap Node (HashSet Node)) -> HashSet (Node, Node, Node)
sel2 (Just predFn) mobjFn (s, ps) =
Set.map (\(p,o) -> (s,p,o)) $
foldl' Set.union Set.empty $
map (sel3 mobjFn) poMapS :: HashSet (Node, Node, Node)
where
poMapS :: [(Node, HashSet Node)]
poMapS = filter (\(k,_) -> predFn k) $ HashMap.toList ps
sel2 Nothing mobjFn (s, ps) =
Set.map (\(p,o) -> (s,p,o)) $
foldl' Set.union Set.empty $
map (sel3 mobjFn) poMaps
where
poMaps = HashMap.toList ps
sel3 :: NodeSelector -> (Node, HashSet Node) -> HashSet (Node, Node)
sel3 (Just objFn) (p, os) = Set.map (\o -> (p, o)) $ Set.filter objFn os
sel3 Nothing (p, os) = Set.map (\o -> (p, o)) os
-- support query
query' :: MGraph -> Maybe Node -> Maybe Predicate -> Maybe Node -> Triples
query' (MGraph (m,_ , _)) subj pred obj = map f $ Set.toList $ q1 subj pred obj m
where f (s, p, o) = Triple s p o
q1 :: Maybe Node -> Maybe Node -> Maybe Node -> TMaps -> HashSet (Node, Node, Node)
q1 (Just s) p o (spoMap, _ ) = q2 p o (s, HashMap.lookupDefault HashMap.empty s spoMap)
q1 s p (Just o) (_ , opsMap) = Set.map (\(o',p',s') -> (s',p',o')) $ q2 p s (o, HashMap.lookupDefault HashMap.empty o opsMap)
q1 Nothing p o (spoMap, _ ) = Set.unions $ map (q2 p o) $ HashMap.toList spoMap
q2 :: Maybe Node -> Maybe Node -> (Node, HashMap Node (HashSet Node)) -> HashSet (Node, Node, Node)
q2 (Just p) o (s, pmap) =
maybe Set.empty (Set.map (\ (p', o') -> (s, p', o')) . q3 o . (p,)) $ HashMap.lookup p pmap
q2 Nothing o (s, pmap) = Set.map (\(x,y) -> (s,x,y)) $ Set.unions $ map (q3 o) opmaps
where opmaps ::[(Node, HashSet Node)]
opmaps = HashMap.toList pmap
q3 :: Maybe Node -> (Node, HashSet Node) -> HashSet (Node, Node)
q3 (Just o) (p, os) = if o `Set.member` os then Set.singleton (p, o) else Set.empty
q3 Nothing (p, os) = Set.map (\o -> (p, o)) os
|
ddssff/rdf4h
|
src/Data/RDF/MGraph.hs
|
Haskell
|
bsd-3-clause
| 6,482
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
-- | Construct a @Plan@ for how to build
module Stack.Build.ConstructPlan
( constructPlan
) where
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.Catch (MonadCatch)
import Control.Monad.IO.Class
import Control.Monad.Logger (MonadLogger)
import Control.Monad.RWS.Strict
import Control.Monad.Trans.Resource
import qualified Data.ByteString.Char8 as S8
import Data.Either
import Data.Function
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Distribution.Package (Dependency (..))
import Distribution.Version (anyVersion)
import Network.HTTP.Client.Conduit (HasHttpManager)
import Prelude hiding (FilePath, pi, writeFile)
import Stack.Build.Cache
import Stack.Build.Haddock
import Stack.Build.Installed
import Stack.Build.Source
import Stack.Types.Build
import Stack.BuildPlan
import Stack.Package
import Stack.PackageIndex
import Stack.Types
data PackageInfo
= PIOnlyInstalled Version InstallLocation Installed
| PIOnlySource PackageSource
| PIBoth PackageSource Installed
combineSourceInstalled :: PackageSource
-> (Version, InstallLocation, Installed)
-> PackageInfo
combineSourceInstalled ps (version, location, installed) =
assert (piiVersion ps == version) $
assert (piiLocation ps == location) $
case location of
-- Always trust something in the snapshot
Snap -> PIOnlyInstalled version location installed
Local -> PIBoth ps installed
type CombinedMap = Map PackageName PackageInfo
combineMap :: SourceMap -> InstalledMap -> CombinedMap
combineMap = Map.mergeWithKey
(\_ s i -> Just $ combineSourceInstalled s i)
(fmap PIOnlySource)
(fmap (\(v, l, i) -> PIOnlyInstalled v l i))
data AddDepRes
= ADRToInstall Task
| ADRFound InstallLocation Version Installed
deriving Show
data W = W
{ wFinals :: !(Map PackageName (Either ConstructPlanException (Task, LocalPackageTB)))
, wInstall :: !(Map Text InstallLocation)
-- ^ executable to be installed, and location where the binary is placed
, wDirty :: !(Map PackageName Text)
-- ^ why a local package is considered dirty
, wDeps :: !(Set PackageName)
-- ^ Packages which count as dependencies
}
instance Monoid W where
mempty = W mempty mempty mempty mempty
mappend (W a b c d) (W w x y z) = W (mappend a w) (mappend b x) (mappend c y) (mappend d z)
type M = RWST
Ctx
W
(Map PackageName (Either ConstructPlanException AddDepRes))
IO
data Ctx = Ctx
{ mbp :: !MiniBuildPlan
, baseConfigOpts :: !BaseConfigOpts
, loadPackage :: !(PackageName -> Version -> Map FlagName Bool -> IO Package)
, combinedMap :: !CombinedMap
, toolToPackages :: !(Dependency -> Map PackageName VersionRange)
, ctxEnvConfig :: !EnvConfig
, callStack :: ![PackageName]
, extraToBuild :: !(Set PackageName)
, latestVersions :: !(Map PackageName Version)
, wanted :: !(Set PackageName)
}
instance HasStackRoot Ctx
instance HasPlatform Ctx
instance HasGHCVariant Ctx
instance HasConfig Ctx
instance HasBuildConfig Ctx where
getBuildConfig = getBuildConfig . getEnvConfig
instance HasEnvConfig Ctx where
getEnvConfig = ctxEnvConfig
constructPlan :: forall env m.
(MonadCatch m, MonadReader env m, HasEnvConfig env, MonadIO m, MonadLogger m, MonadBaseControl IO m, HasHttpManager env)
=> MiniBuildPlan
-> BaseConfigOpts
-> [LocalPackage]
-> Set PackageName -- ^ additional packages that must be built
-> Map GhcPkgId PackageIdentifier -- ^ locally registered
-> (PackageName -> Version -> Map FlagName Bool -> IO Package) -- ^ load upstream package
-> SourceMap
-> InstalledMap
-> m Plan
constructPlan mbp0 baseConfigOpts0 locals extraToBuild0 locallyRegistered loadPackage0 sourceMap installedMap = do
menv <- getMinimalEnvOverride
caches <- getPackageCaches menv
let latest = Map.fromListWith max $ map toTuple $ Map.keys caches
econfig <- asks getEnvConfig
let onWanted lp = do
case lpExeComponents lp of
Nothing -> return ()
Just _ -> void $ addDep False $ packageName $ lpPackage lp
case lpTestBench lp of
Just tb -> addFinal lp tb
Nothing -> return ()
let inner = do
mapM_ onWanted $ filter lpWanted locals
mapM_ (addDep False) $ Set.toList extraToBuild0
((), m, W efinals installExes dirtyReason deps) <- liftIO $ runRWST inner (ctx econfig latest) M.empty
let toEither (_, Left e) = Left e
toEither (k, Right v) = Right (k, v)
(errlibs, adrs) = partitionEithers $ map toEither $ M.toList m
(errfinals, finals) = partitionEithers $ map toEither $ M.toList efinals
errs = errlibs ++ errfinals
if null errs
then do
let toTask (_, ADRFound _ _ _) = Nothing
toTask (name, ADRToInstall task) = Just (name, task)
tasks = M.fromList $ mapMaybe toTask adrs
takeSubset =
case boptsBuildSubset $ bcoBuildOpts baseConfigOpts0 of
BSAll -> id
BSOnlySnapshot -> stripLocals
BSOnlyDependencies -> stripNonDeps deps
return $ takeSubset Plan
{ planTasks = tasks
, planFinals = M.fromList finals
, planUnregisterLocal = mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap
, planInstallExes =
if boptsInstallExes $ bcoBuildOpts baseConfigOpts0
then installExes
else Map.empty
}
else throwM $ ConstructPlanExceptions errs (bcStackYaml $ getBuildConfig econfig)
where
ctx econfig latest = Ctx
{ mbp = mbp0
, baseConfigOpts = baseConfigOpts0
, loadPackage = loadPackage0
, combinedMap = combineMap sourceMap installedMap
, toolToPackages = \ (Dependency name _) ->
maybe Map.empty (Map.fromSet (\_ -> anyVersion)) $
Map.lookup (S8.pack . packageNameString . fromCabalPackageName $ name) toolMap
, ctxEnvConfig = econfig
, callStack = []
, extraToBuild = extraToBuild0
, latestVersions = latest
, wanted = wantedLocalPackages locals
}
-- TODO Currently, this will only consider and install tools from the
-- snapshot. It will not automatically install build tools from extra-deps
-- or local packages.
toolMap = getToolMap mbp0
-- | Determine which packages to unregister based on the given tasks and
-- already registered local packages
mkUnregisterLocal :: Map PackageName Task
-> Map PackageName Text
-> Map GhcPkgId PackageIdentifier
-> SourceMap
-> Map GhcPkgId (PackageIdentifier, Maybe Text)
mkUnregisterLocal tasks dirtyReason locallyRegistered sourceMap =
Map.unions $ map toUnregisterMap $ Map.toList locallyRegistered
where
toUnregisterMap (gid, ident) =
case M.lookup name tasks of
Nothing ->
case M.lookup name sourceMap of
Just (PSUpstream _ Snap _) -> Map.singleton gid
( ident
, Just "Switching to snapshot installed package"
)
_ -> Map.empty
Just _ -> Map.singleton gid
( ident
, Map.lookup name dirtyReason
)
where
name = packageIdentifierName ident
addFinal :: LocalPackage -> LocalPackageTB -> M ()
addFinal lp lptb = do
depsRes <- addPackageDeps False package
res <- case depsRes of
Left e -> return $ Left e
Right (missing, present, _minLoc) -> do
ctx <- ask
return $ Right (Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
in configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
allDeps
True -- wanted
Local
package
, taskPresent = present
, taskType = TTLocal lp
}, lptb)
tell mempty { wFinals = Map.singleton (packageName package) res }
where
package = lptbPackage lptb
addDep :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep treatAsDep' name = do
ctx <- ask
let treatAsDep = treatAsDep' || name `Set.notMember` wanted ctx
when treatAsDep $ markAsDep name
m <- get
case Map.lookup name m of
Just res -> return res
Nothing -> do
res <- addDep' treatAsDep name
modify $ Map.insert name res
return res
addDep' :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep' treatAsDep name = do
ctx <- ask
if name `elem` callStack ctx
then return $ Left $ DependencyCycleDetected $ name : callStack ctx
else local
(\ctx' -> ctx' { callStack = name : callStack ctx' }) $ do
(addDep'' treatAsDep name)
addDep'' :: Bool -- ^ is this being used by a dependency?
-> PackageName -> M (Either ConstructPlanException AddDepRes)
addDep'' treatAsDep name = do
ctx <- ask
case Map.lookup name $ combinedMap ctx of
-- TODO look up in the package index and see if there's a
-- recommendation available
Nothing -> return $ Left $ UnknownPackage name
Just (PIOnlyInstalled version loc installed) -> do
tellExecutablesUpstream name version loc Map.empty -- slightly hacky, no flags since they likely won't affect executable names
return $ Right $ ADRFound loc version installed
Just (PIOnlySource ps) -> do
tellExecutables name ps
installPackage treatAsDep name ps
Just (PIBoth ps installed) -> do
tellExecutables name ps
needInstall <- checkNeedInstall treatAsDep name ps installed (wanted ctx)
if needInstall
then installPackage treatAsDep name ps
else return $ Right $ ADRFound (piiLocation ps) (piiVersion ps) installed
tellExecutables :: PackageName -> PackageSource -> M () -- TODO merge this with addFinal above?
tellExecutables _ (PSLocal lp)
| lpWanted lp = tellExecutablesPackage Local $ lpPackage lp
| otherwise = return ()
tellExecutables name (PSUpstream version loc flags) = do
tellExecutablesUpstream name version loc flags
tellExecutablesUpstream :: PackageName -> Version -> InstallLocation -> Map FlagName Bool -> M ()
tellExecutablesUpstream name version loc flags = do
ctx <- ask
when (name `Set.member` extraToBuild ctx) $ do
p <- liftIO $ loadPackage ctx name version flags
tellExecutablesPackage loc p
tellExecutablesPackage :: InstallLocation -> Package -> M ()
tellExecutablesPackage loc p = do
cm <- asks combinedMap
-- Determine which components are enabled so we know which ones to copy
let myComps =
case Map.lookup (packageName p) cm of
Nothing -> assert False Set.empty
Just (PIOnlyInstalled _ _ _) -> Set.empty
Just (PIOnlySource ps) -> goSource ps
Just (PIBoth ps _) -> goSource ps
goSource (PSLocal lp) = fromMaybe Set.empty $ lpExeComponents lp
goSource (PSUpstream _ _ _) = Set.empty
tell mempty { wInstall = m myComps }
where
m myComps = Map.fromList $ map (, loc) $ Set.toList
$ filterComps myComps $ packageExes p
filterComps myComps x
| Set.null myComps = x
| otherwise = Set.intersection x $ Set.map toExe myComps
toExe x = fromMaybe x $ T.stripPrefix "exe:" x
-- TODO There are a lot of duplicated computations below. I've kept that for
-- simplicity right now
installPackage :: Bool -- ^ is this being used by a dependency?
-> PackageName -> PackageSource -> M (Either ConstructPlanException AddDepRes)
installPackage treatAsDep name ps = do
ctx <- ask
package <- psPackage name ps
depsRes <- addPackageDeps treatAsDep package
case depsRes of
Left e -> return $ Left e
Right (missing, present, minLoc) -> do
return $ Right $ ADRToInstall Task
{ taskProvides = PackageIdentifier
(packageName package)
(packageVersion package)
, taskConfigOpts = TaskConfigOpts missing $ \missing' ->
let allDeps = Map.union present missing'
destLoc = piiLocation ps <> minLoc
in configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
allDeps
(psWanted ps)
-- An assertion to check for a recurrence of
-- https://github.com/commercialhaskell/stack/issues/345
(assert (destLoc == piiLocation ps) destLoc)
package
, taskPresent = present
, taskType =
case ps of
PSLocal lp -> TTLocal lp
PSUpstream _ loc _ -> TTUpstream package $ loc <> minLoc
}
checkNeedInstall :: Bool
-> PackageName -> PackageSource -> Installed -> Set PackageName -> M Bool
checkNeedInstall treatAsDep name ps installed wanted = assert (piiLocation ps == Local) $ do
package <- psPackage name ps
depsRes <- addPackageDeps treatAsDep package
case depsRes of
Left _e -> return True -- installPackage will find the error again
Right (missing, present, _loc)
| Set.null missing -> checkDirtiness ps installed package present wanted
| otherwise -> do
tell mempty { wDirty = Map.singleton name $
let t = T.intercalate ", " $ map (T.pack . packageNameString . packageIdentifierName) (Set.toList missing)
in T.append "missing dependencies: " $
if T.length t < 100
then t
else T.take 97 t <> "..." }
return True
addPackageDeps :: Bool -- ^ is this being used by a dependency?
-> Package -> M (Either ConstructPlanException (Set PackageIdentifier, Map PackageIdentifier GhcPkgId, InstallLocation))
addPackageDeps treatAsDep package = do
ctx <- ask
deps' <- packageDepsWithTools package
deps <- forM (Map.toList deps') $ \(depname, range) -> do
eres <- addDep treatAsDep depname
let mlatest = Map.lookup depname $ latestVersions ctx
case eres of
Left e ->
let bd =
case e of
UnknownPackage name -> assert (name == depname) NotInBuildPlan
_ -> Couldn'tResolveItsDependencies
in return $ Left (depname, (range, mlatest, bd))
Right adr | not $ adrVersion adr `withinRange` range ->
return $ Left (depname, (range, mlatest, DependencyMismatch $ adrVersion adr))
Right (ADRToInstall task) -> return $ Right
(Set.singleton $ taskProvides task, Map.empty, taskLocation task)
Right (ADRFound loc _ (Executable _)) -> return $ Right
(Set.empty, Map.empty, loc)
Right (ADRFound loc _ (Library ident gid)) -> return $ Right
(Set.empty, Map.singleton ident gid, loc)
case partitionEithers deps of
([], pairs) -> return $ Right $ mconcat pairs
(errs, _) -> return $ Left $ DependencyPlanFailures
(PackageIdentifier
(packageName package)
(packageVersion package))
(Map.fromList errs)
where
adrVersion (ADRToInstall task) = packageIdentifierVersion $ taskProvides task
adrVersion (ADRFound _ v _) = v
checkDirtiness :: PackageSource
-> Installed
-> Package
-> Map PackageIdentifier GhcPkgId
-> Set PackageName
-> M Bool
checkDirtiness ps installed package present wanted = do
ctx <- ask
moldOpts <- tryGetFlagCache installed
let configOpts = configureOpts
(getEnvConfig ctx)
(baseConfigOpts ctx)
present
(psWanted ps)
(piiLocation ps) -- should be Local always
package
buildOpts = bcoBuildOpts (baseConfigOpts ctx)
wantConfigCache = ConfigCache
{ configCacheOpts = configOpts
, configCacheDeps = Set.fromList $ Map.elems present
, configCacheComponents =
case ps of
PSLocal lp -> Set.map renderComponent $ lpComponents lp
PSUpstream _ _ _ -> Set.empty
, configCacheHaddock =
shouldHaddockPackage buildOpts wanted (packageName package) ||
-- Disabling haddocks when old config had haddocks doesn't make dirty.
maybe False configCacheHaddock moldOpts
}
let mreason =
case moldOpts of
Nothing -> Just "old configure information not found"
Just oldOpts
| Just reason <- describeConfigDiff oldOpts wantConfigCache -> Just reason
| psDirty ps -> Just "local file changes"
| otherwise -> Nothing
case mreason of
Nothing -> return False
Just reason -> do
tell mempty { wDirty = Map.singleton (packageName package) reason }
return True
describeConfigDiff :: ConfigCache -> ConfigCache -> Maybe Text
describeConfigDiff old new
| configCacheDeps old /= configCacheDeps new = Just "dependencies changed"
| not $ Set.null newComponents =
Just $ "components added: " `T.append` T.intercalate ", "
(map (decodeUtf8With lenientDecode) (Set.toList newComponents))
| not (configCacheHaddock old) && configCacheHaddock new = Just "rebuilding with haddocks"
| oldOpts /= newOpts = Just $ T.pack $ concat
[ "flags changed from "
, show oldOpts
, " to "
, show newOpts
]
| otherwise = Nothing
where
-- options set by stack
isStackOpt t = any (`T.isPrefixOf` t)
[ "--dependency="
, "--constraint="
, "--package-db="
, "--libdir="
, "--bindir="
, "--enable-tests"
, "--enable-benchmarks"
]
userOpts = filter (not . isStackOpt)
. map T.pack
. (\(ConfigureOpts x y) -> x ++ y)
. configCacheOpts
(oldOpts, newOpts) = removeMatching (userOpts old) (userOpts new)
removeMatching (x:xs) (y:ys)
| x == y = removeMatching xs ys
removeMatching xs ys = (xs, ys)
newComponents = configCacheComponents new `Set.difference` configCacheComponents old
psDirty :: PackageSource -> Bool
psDirty (PSLocal lp) = lpDirtyFiles lp
psDirty (PSUpstream _ _ _) = False -- files never change in an upstream package
psWanted :: PackageSource -> Bool
psWanted (PSLocal lp) = lpWanted lp
psWanted (PSUpstream _ _ _) = False
psPackage :: PackageName -> PackageSource -> M Package
psPackage _ (PSLocal lp) = return $ lpPackage lp
psPackage name (PSUpstream version _ flags) = do
ctx <- ask
liftIO $ loadPackage ctx name version flags
-- | Get all of the dependencies for a given package, including guessed build
-- tool dependencies.
packageDepsWithTools :: Package -> M (Map PackageName VersionRange)
packageDepsWithTools p = do
ctx <- ask
return $ Map.unionsWith intersectVersionRanges
$ packageDeps p
: map (toolToPackages ctx) (packageTools p)
-- | Strip out anything from the @Plan@ intended for the local database
stripLocals :: Plan -> Plan
stripLocals plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planUnregisterLocal = Map.empty
, planInstallExes = Map.filter (/= Local) $ planInstallExes plan
}
where
checkTask task =
case taskType task of
TTLocal _ -> False
TTUpstream _ Local -> False
TTUpstream _ Snap -> True
stripNonDeps :: Set PackageName -> Plan -> Plan
stripNonDeps deps plan = plan
{ planTasks = Map.filter checkTask $ planTasks plan
, planFinals = Map.empty
, planInstallExes = Map.empty -- TODO maybe don't disable this?
}
where
checkTask task = packageIdentifierName (taskProvides task) `Set.member` deps
markAsDep :: PackageName -> M ()
markAsDep name = tell mempty { wDeps = Set.singleton name }
|
kairuku/stack
|
src/Stack/Build/ConstructPlan.hs
|
Haskell
|
bsd-3-clause
| 22,289
|
module PfeSocket(listenOnPFE,connectToPFE,acceptPFE,removePFE,
pfeClient,clientOps,serverOps,sResult,errorString) where
import Prelude hiding (putStr,readIO)
import Network(listenOn,accept,connectTo,PortID(..))
import IO(hPutStrLn,hPrint,hGetLine,hGetContents,hClose,hSetBuffering,BufferMode(..))
import AbstractIO
import MUtils(ifM,done)
import SIO
listenOnPFE dir = ifM (doesFileExist (pfePath dir)) tryConnect listen
where
listen = listenOn (pfePort dir)
tryConnect =
do r <- try connect
case r of
Left _ -> cleanUp>>listen
Right _ -> backoff
connect = do h <- connectToPFE dir
hPutStrLn h ""
s <- hGetContents h
seq (length s) done -- to avoid crashing the server
hClose h
backoff = fail "PFE Server is already running"
cleanUp = removePFE dir
acceptPFE s = do a@(h,_,_) <- accept s
hSetBuffering h IO.LineBuffering
return a
connectToPFE dir =
do h <- connectTo "localhost" (pfePort dir)
hSetBuffering h LineBuffering
return h
pfeClient h args =
do inBase $ hPutStrLn h (unwords args)
clientLoop
inBase $ hClose h
where
clientLoop =
do msg <- inBase $ hReadLn h
case msg of
Stdout s -> putStr s >> clientLoop
Stderr s -> ePutStr s >> clientLoop
Result r -> case r of
Left s -> fail s
Right () -> done
removePFE = removeFile . pfePath
pfePort = UnixSocket . pfePath
pfePath dir = dir++"/pfeserver"
data Msg = Stdout String | Stderr String | Result Result deriving (Read,Show)
type Result = Either String ()
serverOps h = StdIO {put=sPut h, eput=sePut h}
clientOps = StdIO {put=putStr, eput=ePutStr {-. color-}}
-- where color s = "\ESC[31m"++s++"\ESC[m"
sPut h = hPrint h . Stdout
sePut h = hPrint h . Stderr
sResult h = hPrint h . Result . either (Left . show) Right
hReadLn h = readIO =<< hGetLine h
-- Work around the ugly way GHC prints user errors...
errorString e =
if isUserError e
then dropPrefix "user error\nReason: " (ioeGetErrorString e)
else show e
dropPrefix (x:xs) (y:ys) | x==y = dropPrefix xs ys
dropPrefix _ ys = ys
|
forste/haReFork
|
tools/pfe/PfeSocket.hs
|
Haskell
|
bsd-3-clause
| 2,141
|
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveFoldable, DeriveTraversable #-}
module Distribution.Client.Dependency.Modular.PSQ where
-- Priority search queues.
--
-- I am not yet sure what exactly is needed. But we need a data structure with
-- key-based lookup that can be sorted. We're using a sequence right now with
-- (inefficiently implemented) lookup, because I think that queue-based
-- operations and sorting turn out to be more efficiency-critical in practice.
import Data.Foldable
import Data.Function
import Data.List as S hiding (foldr)
import Data.Traversable
import Prelude hiding (foldr)
newtype PSQ k v = PSQ [(k, v)]
deriving (Eq, Show, Functor, Foldable, Traversable)
keys :: PSQ k v -> [k]
keys (PSQ xs) = fmap fst xs
lookup :: Eq k => k -> PSQ k v -> Maybe v
lookup k (PSQ xs) = S.lookup k xs
map :: (v1 -> v2) -> PSQ k v1 -> PSQ k v2
map f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f v)) xs)
mapKeys :: (k1 -> k2) -> PSQ k1 v -> PSQ k2 v
mapKeys f (PSQ xs) = PSQ (fmap (\ (k, v) -> (f k, v)) xs)
mapWithKey :: (k -> a -> b) -> PSQ k a -> PSQ k b
mapWithKey f (PSQ xs) = PSQ (fmap (\ (k, v) -> (k, f k v)) xs)
mapWithKeyState :: (s -> k -> a -> (b, s)) -> PSQ k a -> s -> PSQ k b
mapWithKeyState p (PSQ xs) s0 =
PSQ (foldr (\ (k, v) r s -> case p s k v of
(w, n) -> (k, w) : (r n))
(const []) xs s0)
delete :: Eq k => k -> PSQ k a -> PSQ k a
delete k (PSQ xs) = PSQ (snd (partition ((== k) . fst) xs))
fromList :: [(k, a)] -> PSQ k a
fromList = PSQ
cons :: k -> a -> PSQ k a -> PSQ k a
cons k x (PSQ xs) = PSQ ((k, x) : xs)
snoc :: PSQ k a -> k -> a -> PSQ k a
snoc (PSQ xs) k x = PSQ (xs ++ [(k, x)])
casePSQ :: PSQ k a -> r -> (k -> a -> PSQ k a -> r) -> r
casePSQ (PSQ xs) n c =
case xs of
[] -> n
(k, v) : ys -> c k v (PSQ ys)
splits :: PSQ k a -> PSQ k (a, PSQ k a)
splits = go id
where
go f xs = casePSQ xs
(PSQ [])
(\ k v ys -> cons k (v, f ys) (go (f . cons k v) ys))
sortBy :: (a -> a -> Ordering) -> PSQ k a -> PSQ k a
sortBy cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` snd) xs)
sortByKeys :: (k -> k -> Ordering) -> PSQ k a -> PSQ k a
sortByKeys cmp (PSQ xs) = PSQ (S.sortBy (cmp `on` fst) xs)
filterKeys :: (k -> Bool) -> PSQ k a -> PSQ k a
filterKeys p (PSQ xs) = PSQ (S.filter (p . fst) xs)
filter :: (a -> Bool) -> PSQ k a -> PSQ k a
filter p (PSQ xs) = PSQ (S.filter (p . snd) xs)
length :: PSQ k a -> Int
length (PSQ xs) = S.length xs
-- | "Lazy length".
--
-- Only approximates the length, but doesn't force the list.
llength :: PSQ k a -> Int
llength (PSQ []) = 0
llength (PSQ (_:[])) = 1
llength (PSQ (_:_:[])) = 2
llength (PSQ _) = 3
null :: PSQ k a -> Bool
null (PSQ xs) = S.null xs
toList :: PSQ k a -> [(k, a)]
toList (PSQ xs) = xs
|
DavidAlphaFox/ghc
|
libraries/Cabal/cabal-install/Distribution/Client/Dependency/Modular/PSQ.hs
|
Haskell
|
bsd-3-clause
| 2,802
|
{-# OPTIONS -fno-warn-redundant-constraints #-}
-- !!! This is the example given in TcDeriv
--
module ShouldSucceed where
data T a b
= C1 (Foo a) (Bar b)
| C2 Int (T b a)
| C3 (T a a)
deriving Eq
data Foo a = MkFoo Double a deriving ()
instance (Eq a) => Eq (Foo a)
data Bar a = MkBar Int Int deriving ()
instance (Ping b) => Eq (Bar b)
class Ping a
|
urbanslug/ghc
|
testsuite/tests/deriving/should_compile/drv003.hs
|
Haskell
|
bsd-3-clause
| 365
|
-- !! check if tc type substitutions really do
-- !! clone (or if not, work around it by cloning
-- !! all binders in first pass of the simplifier).
module ShouldCompile where
f,g :: Eq a => (a,b)
f = g
g = f
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_compile/tc099.hs
|
Haskell
|
bsd-3-clause
| 210
|
{-# LANGUAGE PatternSynonyms #-}
module Main where
pattern First x <- x:_ where
First x = foo [x, x, x]
foo :: [a] -> [a]
foo xs@(First x) = replicate (length xs + 1) x
main = mapM_ print $ First ()
|
ghc-android/ghc
|
testsuite/tests/patsyn/should_run/bidir-explicit-scope.hs
|
Haskell
|
bsd-3-clause
| 204
|
to_tens :: Integer -> [Integer]
to_tens 0 = []
to_tens n = to_tens (n `div` 10) ++ [n `mod` 10]
isPrime :: Integer -> Bool
isPrime 1 = False
isPrime k
| k <= 0 = False
|otherwise = null [ x | x <- [2..(truncate $ sqrt $ fromIntegral k)], k `mod` x == 0]
from_tens xs = sum $ map (\(a,b) -> 10^a * b) $ zip [0..] $ reverse xs
truncate_left' xs 0 = xs
truncate_left' (x:[]) _ = []
truncate_left' (x:xs) 1 = xs
truncate_left' (x:xs) n = (truncate_left' (xs) (n-1))
truncate_left num n = from_tens $ truncate_left' (to_tens num) n
truncate_right num n = let xs = to_tens num
in from_tens $ reverse $ truncate_left' (reverse xs) n
is_truncatable_prime 2 = False
is_truncatable_prime 3 = False
is_truncatable_prime 5 = False
is_truncatable_prime 7 = False
is_truncatable_prime n = let
l = length $ to_tens n
in
and $ map isPrime $ map (truncate_left n) [0..(l-1)] ++ map (truncate_right n) [0..(l-1)]
-- ++ ((truncate_left n) [0..(l-1)]))
ans = filter is_truncatable_prime [x| x <- [11,13..739397], isPrime x]
|
stefan-j/ProjectEuler
|
q37.hs
|
Haskell
|
mit
| 1,093
|
-- Isomorphism
-- https://www.codewars.com/kata/5922543bf9c15705d0000020
module ISO where
import Data.Void
import Data.Tuple(swap)
import Control.Arrow ((***), (+++))
type ISO a b = (a -> b, b -> a)
substL :: ISO a b -> (a -> b)
substL = fst
substR :: ISO a b -> (b -> a)
substR = snd
isoBool :: ISO Bool Bool
isoBool = (id, id)
isoBoolNot :: ISO Bool Bool
isoBoolNot = (not, not)
refl :: ISO a a
refl = (id, id)
symm :: ISO a b -> ISO b a
symm = swap
trans :: ISO a b -> ISO b c -> ISO a c
trans (ab, ba) (bc, cb) = (bc . ab, ba . cb)
isoTuple :: ISO a b -> ISO c d -> ISO (a, c) (b, d)
isoTuple (ab, ba) (cd, dc) = (ab *** cd, ba *** dc)
isoList :: ISO a b -> ISO [a] [b]
isoList (ab, ba) = (map ab, map ba)
isoMaybe :: ISO a b -> ISO (Maybe a) (Maybe b)
isoMaybe (ab, ba) = (fmap ab, fmap ba)
isoEither :: ISO a b -> ISO c d -> ISO (Either a c) (Either b d)
isoEither (ab, ba) (cd, dc) = (ab +++ cd, ba +++ dc)
isoFunc :: ISO a b -> ISO c d -> ISO (a -> c) (b -> d)
isoFunc (ab, ba) (cd, dc) = (\f -> cd . f . ba, \f -> dc . f . ab)
isoUnMaybe :: ISO (Maybe a) (Maybe b) -> ISO a b
isoUnMaybe m@(mamb, mbma) = (get . mamb . Just, substL $ isoUnMaybe $ symm m)
where get (Just b) = b
get Nothing = getJust (mamb Nothing)
getJust (Just b) = b
getJust Nothing = undefined
isoEU :: ISO (Either [()] ()) (Either [()] Void)
isoEU = (Left . either ( (): ) (const []), ab)
where ab (Left []) = Right ()
ab (Left (_:x)) = Left x
ab (Right v) = absurd v
isoSymm :: ISO (ISO a b) (ISO b a)
isoSymm = (symm, symm)
|
gafiatulin/codewars
|
src/3 kyu/Isomorphism.hs
|
Haskell
|
mit
| 1,582
|
module S8_1 where
-- Tipo das funções utilizadas em divideAndConquer
--ind :: p -> Bool
--solve :: p -> s
--divide :: p -: [s]
--combine :: p -> [s] -> s
divideAndConquer :: ( p -> Bool) -> (p -> s) -> (p -> [p]) -> (p -> [s] -> s)
-> p -> s
divideAndConquer ind solve divide combine initPb
= dc' initPb
where dc' pb
| ind pb = solve pb
| otherwise = combine pb (map dc' (divide pb))
msort xs = divideAndConquer ind id divide combine xs
where ind xs = length xs <= 1
divide xs = let n = length xs `div` 2
in [take n xs , drop n xs]
combine _ [l1,l2] = merge l1 l2
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] b = b
merge a [] = a
merge a@(x:xs) b@(y:ys) | (x<=y) = x : (merge xs b)
| otherwise = y : (merge a ys)
qsort xs = divideAndConquer ind id divide combine xs
where ind xs = length xs <= 1
divide (x:xs) = [[ y | y<-xs, y<=x],
[ y | y<-xs, y>x] ]
combine (x:_) [l1,l2] = l1 ++ [x] ++ l2
l = [3,1,4,1,5,9,2]
{- Examples of evaluations and results
? msort l
[1, 1, 2, 3, 4, 5, 9]
? qsort l
[1, 1, 2, 3, 4, 5, 9]
-}
|
gustavoramos00/tecnicas-topdown
|
S8_1.hs
|
Haskell
|
mit
| 1,261
|
module PosNegIf where
posOrNeg x =
if x >= 0
then "Pos "
else "Neg "
-- note no returns or paren
|
HaskellForCats/HaskellForCats
|
simpcondi1.hs
|
Haskell
|
mit
| 106
|
module Nodes.Statement where
import Nodes
import Nodes.Expression (Expr)
data Stmt
= Line { expr :: Expr }
instance AstNode Stmt where
ast (Line expr) = ast expr
|
milankinen/cbhs
|
src/nodes/Statement.hs
|
Haskell
|
mit
| 169
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.