code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE 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 | mit | 2,503 | 22 | 11 | 356 | 582 | 344 | 238 | 43 | 1 |
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 | mit | 4,171 | 0 | 16 | 886 | 1,480 | 737 | 743 | -1 | -1 |
module Main where
-------------
-- Imports --
import Distribution.Simple
----------
-- Code --
main :: IO ()
main = defaultMain
| crockeo/ballgame | src/Setup.hs | mit | 130 | 0 | 6 | 22 | 28 | 18 | 10 | 4 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.Pretty.JS
-- Copyright : (c) Phil Freeman 2013
-- License : MIT
--
-- Maintainer : Phil Freeman <[email protected]>
-- 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 | mit | 10,688 | 0 | 22 | 3,160 | 3,308 | 1,701 | 1,607 | 229 | 26 |
{-# 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 | mit | 2,597 | 0 | 11 | 615 | 712 | 397 | 315 | 45 | 3 |
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 | mit | 6,815 | 0 | 19 | 2,184 | 1,491 | 765 | 726 | 114 | 2 |
{-# 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 | mit | 8,188 | 0 | 12 | 1,460 | 1,885 | 1,017 | 868 | -1 | -1 |
{-# 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 | mit | 18,951 | 242 | 13 | 3,587 | 4,288 | 2,264 | 2,024 | 321 | 1 |
{-# 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 | mit | 1,017 | 0 | 19 | 184 | 262 | 141 | 121 | 26 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{- |
Module : $Header$
Description : Morphism extension for modal signature morphisms
Copyright : DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module ExtModal.MorphismExtension where
import qualified Data.Map as Map
import qualified Data.Set as Set
import CASL.Morphism
import CASL.Sign
import CASL.MapSentence
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.Utils
import qualified Common.Lib.MapSet as MapSet
import ExtModal.ExtModalSign
import ExtModal.AS_ExtModal
import ExtModal.Print_AS ()
data MorphExtension = MorphExtension
{ mod_map :: Map.Map Id Id
, nom_map :: Map.Map Id Id
} deriving (Show, Eq, Ord)
emptyMorphExtension :: MorphExtension
emptyMorphExtension = MorphExtension Map.empty Map.empty
instance Pretty MorphExtension where
pretty me = pretty (mod_map me) $+$ pretty (nom_map me)
instance MorphismExtension EModalSign MorphExtension where
ideMorphismExtension _ = emptyMorphExtension
composeMorphismExtension fme1 fme2 = let
me1 = extended_map fme1
me2 = extended_map fme2
src = msource fme1
mSrc = extendedInfo src
in return $ MorphExtension
(composeMap (MapSet.setToMap $ modalities mSrc) (mod_map me1)
$ mod_map me2)
$ composeMap (MapSet.setToMap $ nominals mSrc) (nom_map me1)
$ nom_map me2
-- ignore inverses
isInclusionMorphismExtension me =
Map.null (mod_map me) && Map.null (nom_map me)
inducedEMsign :: InducedSign EM_FORMULA EModalSign MorphExtension EModalSign
inducedEMsign sm om pm m sig =
let ms = extendedInfo sig
mods = mod_map m
tmods = termMods ms
msm i = Map.findWithDefault i i
$ if Set.member i tmods then sm else mods
in ms
{ flexOps = inducedOpMap sm om $ flexOps ms
, flexPreds = inducedPredMap sm pm $ flexPreds ms
, modalities = Set.map msm $ modalities ms
, timeMods = Set.map msm $ timeMods ms
, termMods = Set.map (\ i -> Map.findWithDefault i i sm) tmods
, nominals = Set.map (\ i -> Map.findWithDefault i i $ nom_map m)
$ nominals ms
}
mapEMmod :: Morphism EM_FORMULA EModalSign MorphExtension -> MODALITY
-> MODALITY
mapEMmod morph tm = case tm of
SimpleMod sm -> case Map.lookup (simpleIdToId sm) $ mod_map
$ extended_map morph of
Just ni -> SimpleMod $ idToSimpleId ni
Nothing -> tm
ModOp o tm1 tm2 -> ModOp o (mapEMmod morph tm1) $ mapEMmod morph tm2
TransClos tm1 -> TransClos $ mapEMmod morph tm1
Guard frm -> Guard $ mapSen mapEMform morph frm
TermMod trm -> TermMod $ mapTerm mapEMform morph trm
mapEMprefix :: Morphism EM_FORMULA EModalSign MorphExtension -> FormPrefix
-> FormPrefix
mapEMprefix morph pf = case pf of
BoxOrDiamond choice tm leq_geq num ->
BoxOrDiamond choice (mapEMmod morph tm) leq_geq num
_ -> pf
-- Modal formula mapping via signature morphism
mapEMform :: MapSen EM_FORMULA EModalSign MorphExtension
mapEMform morph frm =
let rmapf = mapSen mapEMform morph
em = extended_map morph
in case frm of
PrefixForm p f pos -> PrefixForm (mapEMprefix morph p) (rmapf f) pos
UntilSince choice f1 f2 pos -> UntilSince choice (rmapf f1) (rmapf f2) pos
ModForm (ModDefn ti te is fs pos) -> ModForm $ ModDefn ti te
(map (fmap $ \ i -> Map.findWithDefault i i
$ if Set.member i $ sortSet $ msource morph then
sort_map morph else mod_map em) is)
(map (fmap $ mapEMframe morph) fs) pos
mapEMframe :: Morphism EM_FORMULA EModalSign MorphExtension -> FrameForm
-> FrameForm
mapEMframe morph (FrameForm vs fs r) =
FrameForm vs (map (fmap $ mapSen mapEMform morph) fs) r
| nevrenato/HetsAlloy | ExtModal/MorphismExtension.hs | gpl-2.0 | 3,848 | 0 | 22 | 887 | 1,167 | 583 | 584 | 85 | 6 |
{-
- The Lambda Shell, an interactive environment for evaluating pure untyped lambda terms.
- Copyright (C) 2005-2011, Robert Dockins
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-}
-- | This module defines parsers for lambda terms
-- and for \"let\" bound definitions.
module LambdaParser
( nameParser
, lambdaParser
, definitionFileParser
, stripComments
, Statement (..)
, statementParser
, statementsParser
, LamParseState (..)
, LamParser
)
where
import Data.List
import qualified Data.Map as Map
import Text.ParserCombinators.Parsec
import Lambda
import CPS
-- | A type representing "statements". A statement is
-- either a lambda form to reduce, a let binding,
-- a confluence test, a cps transform,
-- or the empty statement.
data Statement
= Stmt_eval (PureLambda () String)
| Stmt_decl [String]
| Stmt_let String (PureLambda () String)
| Stmt_isEq (PureLambda () String)
(PureLambda () String)
| Stmt_empty
data LamParseState
= LamParseState
{ cpsTransform :: CPS LamParser
, extendedSyntax :: Bool
}
type LamParser = GenParser Char LamParseState
-- | Parser for an identifier. An identifier is
-- a letter followed by zero or more alphanumeric characters (or underscores).
nameParser :: LamParser String
nameParser =
do a <- letter
as <- many (char '_' <|> alphaNum)
return (a:as)
-- | Parser for a lambda term. Function application is left associative.
--
-- @
-- lambda -\> name
-- lambda -\> \'(\' lambda \')\'
-- lambda -\> lambda lambda
-- lambda -\> \'\\\' {name} \'.\' lambda
-- @
lambdaParser :: Bindings () String -> LamParser (PureLambda () String)
lambdaParser b = do
st <- getState
let p = if (extendedSyntax st) then extSyntax else basicSyntax
spaces
e <- appParser p b []
spaces
return e
-- | Parser for multiple statements.
--
-- @
-- stmts -\> stmt ';' stmts
-- stmts -\>
-- @
statementsParser :: Bindings () String -> LamParser [Statement]
statementsParser b = do spaces; x <- p b; eof; return x
where p b = do x <- stmtParser b
let b' = case x of
(Stmt_let name t) -> Map.insert name (Just t) b
_ -> b
spaces
( do char ';'
spaces
xs <- p b'
return (x:xs))
<|> (return [x])
-- | Parser for a statement.
--
-- @
-- stmt -\> \'let\' name \'=\' lambda
-- stmt -\> lambda
-- @
statementParser :: Bindings () String -> LamParser Statement
statementParser b = do
spaces
x <- stmtParser b
spaces
eof
return x
stmtParser :: Bindings () String -> LamParser Statement
stmtParser b =
try (letDefParser b >>= return . uncurry Stmt_let)
<|> try (declParser b >>= return . Stmt_decl)
<|> try (compParser b >>= return . uncurry Stmt_isEq)
<|> (lambdaParser b >>= return . Stmt_eval)
<|> (return Stmt_empty)
compParser :: Bindings () String -> LamParser (PureLambda () String,PureLambda () String)
compParser b = do
x <- lambdaParser b
spaces
string "=="
spaces
y <- lambdaParser b
spaces
return (x,y)
declParser :: Bindings () String -> LamParser [String]
declParser b = do
string "decl"
many1 space
sepBy1 nameParser (many1 space)
letDefParser :: Bindings () String -> LamParser (String,PureLambda () String)
letDefParser b = do
string "let"
many1 space
n <- nameParser
spaces
char '='
e <- lambdaParser b
return (n,e)
stripComments :: String -> String
stripComments (x:xs)
| x == '#' = stripComments (dropWhile (/= '\n') xs)
| otherwise = x : stripComments xs
stripComments [] = []
-- | Parser a file of definitions. Each definition takes the form
--
-- @
-- def -\> \'let\' name \'=\' lambda \';\'
-- @
definitionFileParser :: Bindings () String -> LamParser (Bindings () String)
definitionFileParser b =
(do spaces
(n,t) <- definitionParser b
spaces
let b' = Map.insert n (Just t) b
definitionFileParser b'
)
<|> (eof >> return b)
definitionParser :: Bindings () String -> LamParser (String,PureLambda () String)
definitionParser b =
do n <- nameParser
spaces
char '='
e <- lambdaParser b
char ';'
return (n,e)
type P = Bindings () String -> [String] -> LamParser (PureLambda () String)
cpsParser :: P -> P
cpsParser p b l = do
string "[["
spaces
x <- (appParser p) b l
spaces
string "]]"
st <- getState
cpsTransform st b x
parensParser :: P -> P
parensParser p b l = do
char '('
spaces
e <- (appParser p) b l
spaces
char ')'
return e
varParser :: P
varParser b labels = do
var <- nameParser
let i = elemIndex var labels
case i of
Just i -> return (Var () i)
Nothing -> if Map.member var b
then return (Binding () var)
else fail ("variable '"++var++"' not in scope")
absParser :: P -> P
absParser p b labels = do
char '\\'
spaces
vars <- sepEndBy1 nameParser spaces
char '.'
spaces
let labels' = foldr (:) labels (reverse vars)
exp <- (appParser p) b labels'
let expr = foldr (Lam ()) exp vars
return expr
appParser :: P -> P
appParser p b l = do
exprs <- sepEndBy1 (p b l) (many1 space)
return (foldl1 (App ()) exprs)
basicSyntax :: P
basicSyntax b l =
parensParser basicSyntax b l <|>
absParser basicSyntax b l <|>
varParser b l
extSyntax :: P
extSyntax b l =
parensParser extSyntax b l <|>
absParser extSyntax b l <|>
cpsParser extSyntax b l <|>
varParser b l
| robdockins/lambda-shell | src/LambdaParser.hs | gpl-2.0 | 6,408 | 0 | 17 | 1,763 | 1,787 | 867 | 920 | 163 | 3 |
{-# language TypeFamilies, MultiParamTypeClasses, KindSignatures, FlexibleContexts, FlexibleInstances, ConstraintKinds #-}
{-# language AllowAmbiguousTypes #-}
{-# language CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Class
-- Copyright : (c) Marco Zocca 2017
-- License : GPL-3 (see the file LICENSE)
--
-- Maintainer : zocca marco gmail
-- Stability : experimental
-- Portability : portable
--
-- Typeclasses for linear algebra and related concepts
--
-----------------------------------------------------------------------------
module Numeric.LinearAlgebra.Class where
-- import Control.Applicative
import Data.Complex
-- import Control.Exception
-- import Control.Exception.Common
import Control.Monad.Catch
import Control.Monad.Log
import Control.Monad.IO.Class
-- import Data.Typeable (Typeable)
import qualified Data.Vector as V (Vector)
import Data.Sparse.Types
import Numeric.Eps
-- * Matrix and vector elements (optionally Complex)
class (Eq e , Fractional e, Floating e, Num (EltMag e), Ord (EltMag e)) => Elt e where
type EltMag e :: *
-- | Complex conjugate, or identity function if its input is real-valued
conj :: e -> e
conj = id
-- | Magnitude
mag :: e -> EltMag e
instance Elt Double where {type EltMag Double = Double ; mag = id}
instance Elt Float where {type EltMag Float = Float; mag = id}
instance (RealFloat e) => Elt (Complex e) where
type EltMag (Complex e) = e
conj = conjugate
mag = magnitude
infixl 6 ^+^, ^-^
-- * Additive group
class AdditiveGroup v where
-- | The zero element: identity for '(^+^)'
zeroV :: v
-- | Add vectors
(^+^) :: v -> v -> v
-- | Additive inverse
negateV :: v -> v
-- | Group subtraction
(^-^) :: v -> v -> v
(^-^) x y = x ^+^ negateV y
infixr 7 .*
-- * Vector space @v@.
class (AdditiveGroup v, Num (Scalar v)) => VectorSpace v where
type Scalar v :: *
-- | Scale a vector
(.*) :: Scalar v -> v -> v
-- | Adds inner (dot) products.
class VectorSpace v => InnerSpace v where
-- | Inner/dot product
(<.>) :: v -> v -> Scalar v
-- | Inner product
dot :: InnerSpace v => v -> v -> Scalar v
dot = (<.>)
infixr 7 ./
infixl 7 *.
-- | Scale a vector by the reciprocal of a number (e.g. for normalization)
(./) :: (VectorSpace v, s ~ Scalar v, Fractional s) => v -> s -> v
v ./ s = (recip s) .* v
-- | Vector multiplied by scalar
(*.) :: (VectorSpace v, s ~ Scalar v) => v -> s -> v
(*.) = flip (.*)
-- | Convex combination of two vectors (NB: 0 <= `a` <= 1).
cvx :: VectorSpace v => Scalar v -> v -> v -> v
cvx a u v = a .* u ^+^ ((1-a) .* v)
-- ** Hilbert-space distance function
-- |`hilbertDistSq x y = || x - y ||^2` computes the squared L2 distance between two vectors
hilbertDistSq :: InnerSpace v => v -> v -> Scalar v
hilbertDistSq x y = t <.> t where
t = x ^-^ y
-- * Normed vector spaces
class (InnerSpace v, Num (RealScalar v), Eq (RealScalar v), Epsilon (Magnitude v), Show (Magnitude v), Ord (Magnitude v)) => Normed v where
type Magnitude v :: *
type RealScalar v :: *
-- | L1 norm
norm1 :: v -> Magnitude v
-- | Euclidean (L2) norm squared
norm2Sq :: v -> Magnitude v
-- | Lp norm (p > 0)
normP :: RealScalar v -> v -> Magnitude v
-- | Normalize w.r.t. Lp norm
normalize :: RealScalar v -> v -> v
-- | Normalize w.r.t. L2 norm
normalize2 :: v -> v
-- | Normalize w.r.t. norm2' instead of norm2
normalize2' :: Floating (Scalar v) => v -> v
normalize2' x = x ./ norm2' x
-- | Euclidean (L2) norm
norm2 :: Floating (Magnitude v) => v -> Magnitude v
norm2 x = sqrt (norm2Sq x)
-- | Euclidean (L2) norm; returns a Complex (norm :+ 0) for Complex-valued vectors
norm2' :: Floating (Scalar v) => v -> Scalar v
norm2' x = sqrt $ x <.> x
-- | Lp norm (p > 0)
norm :: Floating (Magnitude v) => RealScalar v -> v -> Magnitude v
norm p v
| p == 1 = norm1 v
| p == 2 = norm2 v
| otherwise = normP p v
-- | Infinity-norm (Real)
normInftyR :: (Foldable t, Ord a) => t a -> a
normInftyR x = maximum x
-- | Infinity-norm (Complex)
normInftyC :: (Foldable t, RealFloat a, Functor t) => t (Complex a) -> a
normInftyC x = maximum (magnitude <$> x)
-- | Lp inner product (p > 0)
dotLp :: (Set t, Foldable t, Floating a) => a -> t a -> t a -> a
dotLp p v1 v2 = sum u**(1/p) where
f a b = (a*b)**p
u = liftI2 f v1 v2
-- | Reciprocal
reciprocal :: (Functor f, Fractional b) => f b -> f b
reciprocal = fmap recip
-- |Scale
scale :: (Num b, Functor f) => b -> f b -> f b
scale n = fmap (* n)
-- * Matrix ring
-- | A matrix ring is any collection of matrices over some ring R that form a ring under matrix addition and matrix multiplication
class (AdditiveGroup m, Epsilon (MatrixNorm m)) => MatrixRing m where
type MatrixNorm m :: *
-- | Matrix-matrix product
(##) :: m -> m -> m
-- | Matrix times matrix transpose (A B^T)
(##^) :: m -> m -> m
-- | Matrix transpose times matrix (A^T B)
(#^#) :: m -> m -> m
a #^# b = transpose a ## b
-- | Matrix transpose (Hermitian conjugate in the Complex case)
transpose :: m -> m
-- | Frobenius norm
normFrobenius :: m -> MatrixNorm m
-- a "sparse matrix ring" ?
-- class MatrixRing m a => SparseMatrixRing m a where
-- (#~#) :: Epsilon a => Matrix m a -> Matrix m a -> Matrix m a
-- * Linear vector space
class (VectorSpace v {-, MatrixRing (MatrixType v)-}) => LinearVectorSpace v where
type MatrixType v :: *
-- | Matrix-vector action
(#>) :: MatrixType v -> v -> v
-- | Dual matrix-vector action
(<#) :: v -> MatrixType v -> v
-- ** LinearVectorSpace + Normed
type V v = (LinearVectorSpace v, Normed v)
-- ** Linear systems
class LinearVectorSpace v => LinearSystem v where
-- | Solve a linear system; uses GMRES internally as default method
(<\>) :: (MonadThrow m, MonadLog String m) =>
MatrixType v -- ^ System matrix
-> v -- ^ Right-hand side
-> m v -- ^ Result
-- * FiniteDim : finite-dimensional objects
class FiniteDim f where
type FDSize f
-- | Dimension (i.e. Int for SpVector, (Int, Int) for SpMatrix)
dim :: f -> FDSize f
-- * HasData : accessing inner data (do not export)
class HasData f where
type HDData f
-- | Number of nonzeros
nnz :: f -> Int
dat :: f -> HDData f
-- * Sparse : sparse datastructures
class (FiniteDim f, HasData f) => Sparse f where
-- | Sparsity (fraction of nonzero elements)
spy :: Fractional b => f -> b
-- * Set : types that behave as sets
class Functor f => Set f where
-- | Union binary lift : apply function on _union_ of two "sets"
liftU2 :: (a -> a -> a) -> f a -> f a -> f a
-- | Intersection binary lift : apply function on _intersection_ of two "sets"
liftI2 :: (a -> a -> b) -> f a -> f a -> f b
-- * SpContainer : sparse container datastructures. Insertion, lookup, toList, lookup with 0 default
class Sparse c => SpContainer c where
type ScIx c :: *
type ScElem c
scInsert :: ScIx c -> ScElem c -> c -> c
scLookup :: c -> ScIx c -> Maybe (ScElem c)
scToList :: c -> [(ScIx c, ScElem c)]
-- -- | Lookup with default, infix form ("safe" : should throw an exception if lookup is outside matrix bounds)
(@@) :: c -> ScIx c -> ScElem c
-- * SparseVector
class SpContainer v => SparseVector v where
type SpvIx v :: *
svFromList :: Int -> [(SpvIx v, ScElem v)] -> v
svFromListDense :: Int -> [ScElem v] -> v
svConcat :: Foldable t => t v -> v
-- svZipWith :: (e -> e -> e) -> v e -> v e -> v e
-- * SparseMatrix
class SpContainer m => SparseMatrix m where
smFromVector :: LexOrd -> (Int, Int) -> V.Vector (IxRow, IxCol, ScElem m) -> m
-- smFromFoldableDense :: Foldable t => t e -> m e
smTranspose :: m -> m
-- smExtractSubmatrix ::
-- m e -> (IxRow, IxRow) -> (IxCol, IxCol) -> m e
encodeIx :: m -> LexOrd -> (IxRow, IxCol) -> LexIx
decodeIx :: m -> LexOrd -> LexIx -> (IxRow, IxCol)
-- data RowsFirst = RowsFirst
-- data ColsFirst = ColsFirst
-- * SparseMatVec
-- | Combining functions for relating (structurally) matrices and vectors, e.g. extracting/inserting rows/columns/submatrices
-- class (SparseMatrix m o e, SparseVector v e) => SparseMatVec m o v e where
-- smvInsertRow :: m e -> v e -> IxRow -> m e
-- smvInsertCol :: m e -> v e -> IxCol -> m e
-- smvExtractRow :: m e -> IxRow -> v e
-- smvExtractCol :: m e -> IxCol -> v e
-- * Utilities
-- | Lift a real number onto the complex plane
toC :: Num a => a -> Complex a
toC r = r :+ 0
-- | Instances for builtin types
#define ScalarType(t) \
instance AdditiveGroup (t) where {zeroV = 0; (^+^) = (+); negateV = negate};\
instance VectorSpace (t) where {type Scalar (t) = t; (.*) = (*) };
-- ScalarType(Int)
-- ScalarType(Integer)
ScalarType(Float)
ScalarType(Double)
ScalarType(Complex Float)
ScalarType(Complex Double)
-- ScalarType(CSChar)
-- ScalarType(CInt)
-- ScalarType(CShort)
-- ScalarType(CLong)
-- ScalarType(CLLong)
-- ScalarType(CIntMax)
-- ScalarType(CFloat)
-- ScalarType(CDouble)
#undef ScalarType
instance InnerSpace Float where {(<.>) = (*)}
instance InnerSpace Double where {(<.>) = (*)}
instance InnerSpace (Complex Float) where {x <.> y = x * conjugate y}
instance InnerSpace (Complex Double) where {x <.> y = x * conjugate y}
#define SimpleNormedInstance(t) \
instance Normed (t) where {type Magnitude (t) = t; type RealScalar (t) = t;\
norm1 = abs; norm2Sq = (**2); normP _ = abs; normalize _ = signum;\
normalize2 = signum; normalize2' = signum; norm2 = abs; norm2' = abs; norm _ = abs};
SimpleNormedInstance(Float)
SimpleNormedInstance(Double)
#undef SimpleNormedInstance
#define ComplexNormedInstance(t) \
instance Normed (Complex (t)) where {\
type Magnitude (Complex (t)) = t;\
type RealScalar (Complex (t)) = t;\
norm1 (r :+ i) = abs r + abs i;\
norm2Sq (r :+ i) = r*r + i*i;\
normP p (r :+ i) = (r**p + i**p)**(1/p);\
normalize p c = toC (1 / normP p c) * c;\
normalize2 c = (1 / norm2' c) * c;\
norm2 = magnitude;\
norm2' = toC . magnitude;};
ComplexNormedInstance(Float)
ComplexNormedInstance(Double)
#undef ComplexNormedInstance
| ocramz/sparse-linear-algebra | src/Numeric/LinearAlgebra/Class.hs | gpl-3.0 | 10,225 | 0 | 12 | 2,346 | 2,421 | 1,321 | 1,100 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-|
A ledger-compatible @register@ command.
-}
module Hledger.Cli.Register (
registermode
,register
,postingsReportAsText
-- ,showPostingWithBalanceForVty
,tests_Hledger_Cli_Register
) where
import Data.List
import Data.Maybe
import System.Console.CmdArgs.Explicit
import Text.CSV
import Test.HUnit
import Text.Printf
import Hledger
import Hledger.Cli.Options
import Hledger.Cli.Utils
registermode = (defCommandMode $ ["register"] ++ aliases) {
modeHelp = "show postings and running total" `withAliases` aliases
,modeGroupFlags = Group {
groupUnnamed = [
flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) "include prior postings in the running total"
,flagNone ["average","A"] (\opts -> setboolopt "average" opts) "show a running average instead of the running total (implies --empty)"
,flagNone ["related","r"] (\opts -> setboolopt "related" opts) "show postings' siblings instead"
,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N"
(unlines
["set output width (default:"
#ifdef mingw32_HOST_OS
,(show defaultWidth)
#else
,"terminal width"
#endif
,"or COLUMNS. -wN,M sets description width as well)"
])
]
++ outputflags
,groupHidden = []
,groupNamed = [generalflagsgroup1]
}
}
where aliases = ["reg"]
-- | Print a (posting) register report.
register :: CliOpts -> Journal -> IO ()
register opts@CliOpts{reportopts_=ropts} j = do
d <- getCurrentDay
let fmt = outputFormatFromOpts opts
render | fmt=="csv" = const ((++"\n") . printCSV . postingsReportAsCsv)
| otherwise = postingsReportAsText
writeOutput opts $ render opts $ postingsReport ropts (queryFromOpts d ropts) j
postingsReportAsCsv :: PostingsReport -> CSV
postingsReportAsCsv (_,is) =
["date","description","account","amount","running total or balance"]
:
map postingsReportItemAsCsvRecord is
postingsReportItemAsCsvRecord :: PostingsReportItem -> Record
postingsReportItemAsCsvRecord (_, _, _, p, b) = [date,desc,acct,amt,bal]
where
date = showDate $ postingDate p
desc = maybe "" tdescription $ ptransaction p
acct = bracket $ paccount p
where
bracket = case ptype p of
BalancedVirtualPosting -> (\s -> "["++s++"]")
VirtualPosting -> (\s -> "("++s++")")
_ -> id
amt = showMixedAmountOneLineWithoutPrice $ pamount p
bal = showMixedAmountOneLineWithoutPrice b
-- | Render a register report as plain text suitable for console output.
postingsReportAsText :: CliOpts -> PostingsReport -> String
postingsReportAsText opts = unlines . map (postingsReportItemAsText opts) . snd
tests_postingsReportAsText = [
"postingsReportAsText" ~: do
-- "unicode in register layout" ~: do
j <- readJournal'
"2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"
let opts = defreportopts
(postingsReportAsText defcliopts $ postingsReport opts (queryFromOpts (parsedate "2008/11/26") opts) j) `is` unlines
["2009/01/01 медвежья шкура расходы:покупки 100 100"
," актив:наличные -100 0"]
]
-- | Render one register report line item as plain text. Layout is like so:
-- @
-- <---------------- width (specified, terminal width, or 80) -------------------->
-- date (10) description account amount (12) balance (12)
-- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
-- @
-- If description's width is specified, account will use the remaining space.
-- Otherwise, description and account divide up the space equally.
--
-- With a reporting interval, the layout is like so:
-- @
-- <---------------- width (specified, terminal width, or 80) -------------------->
-- date (21) account amount (12) balance (12)
-- DDDDDDDDDDDDDDDDDDDDD aaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
-- @
--
-- date and description are shown for the first posting of a transaction only.
--
postingsReportItemAsText :: CliOpts -> PostingsReportItem -> String
postingsReportItemAsText opts (mdate, menddate, mdesc, p, b) =
intercalate "\n" $
[printf ("%-"++datew++"s %-"++descw++"s %-"++acctw++"s %"++amtw++"s %"++balw++"s")
date desc acct amtfirstline balfirstline]
++
[printf (spacer ++ "%"++amtw++"s %"++balw++"s") a b | (a,b) <- zip amtrest balrest ]
where
-- calculate widths
(totalwidth,mdescwidth) = registerWidthsFromOpts opts
amtwidth = 12
balwidth = 12
(datewidth, date) = case (mdate,menddate) of
(Just _, Just _) -> (21, showDateSpan (DateSpan mdate menddate))
(Nothing, Just _) -> (21, "")
(Just d, Nothing) -> (10, showDate d)
_ -> (10, "")
remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth)
(descwidth, acctwidth)
| hasinterval = (0, remaining - 2)
| otherwise = (w, remaining - 2 - w)
where
hasinterval = isJust menddate
w = fromMaybe ((remaining - 2) `div` 2) mdescwidth
[datew,descw,acctw,amtw,balw] = map show [datewidth,descwidth,acctwidth,amtwidth,balwidth]
-- gather content
desc = maybe "" (take descwidth . elideRight descwidth) mdesc
acct = parenthesise $ elideAccountName awidth $ paccount p
where
(parenthesise, awidth) = case ptype p of
BalancedVirtualPosting -> (\s -> "["++s++"]", acctwidth-2)
VirtualPosting -> (\s -> "("++s++")", acctwidth-2)
_ -> (id,acctwidth)
amt = showMixedAmountWithoutPrice $ pamount p
bal = showMixedAmountWithoutPrice b
(amtlines, ballines) = (lines amt, lines bal)
(amtlen, ballen) = (length amtlines, length ballines)
numlines = max amtlen ballen
(amtfirstline:amtrest) = take numlines $ amtlines ++ repeat "" -- posting amount is top-aligned
(balfirstline:balrest) = take numlines $ replicate (numlines - ballen) "" ++ ballines -- balance amount is bottom-aligned
spacer = replicate (totalwidth - (amtwidth + 2 + balwidth)) ' '
-- XXX
-- showPostingWithBalanceForVty showtxninfo p b = postingsReportItemAsText defreportopts $ mkpostingsReportItem showtxninfo p b
tests_Hledger_Cli_Register :: Test
tests_Hledger_Cli_Register = TestList
tests_postingsReportAsText
| kmels/hledger | hledger/Hledger/Cli/Register.hs | gpl-3.0 | 6,794 | 0 | 19 | 1,713 | 1,576 | 866 | 710 | 103 | 6 |
module Text.Shaun
( ShaunValue(..)
, Shaun(..)
)
where
import Text.Shaun.Lexer
import Text.Shaun.Parser
import Text.Shaun.Types
import Text.Shaun.Sweeper
import Data.List (intersperse, concat, length)
import Data.Maybe (fromMaybe)
import Control.Monad
import Data.ByteString.Char8 (pack)
import Control.Monad.IO.Class (liftIO)
indent :: String -> String
indent s = l ++ "\n" ++ unlines (map (" " ++) ls)
where (l:ls) = case lines s of [] -> [""]; a -> a
instance Show ShaunValue where
show (SBool b) = if b then "true" else "false"
show (SString s)
| length (lines s) > 1 = "\"\n" ++ s ++ "\""
| otherwise = "\"" ++ s ++ "\""
show (SNumber n mu) = show n ++ fromMaybe "" mu
show (SObject l) = "\n{ " ++ indent ((foldl showObj "" l)) ++ "}"
where
showObj prev (k,v) = prev ++ k ++ ": " ++ show v ++ "\n"
show (SList l) = "\n[ " ++ indent (unlines (map show l)) ++ "]"
instance Read ShaunValue where
readsPrec _ = \s ->
case makeLexer (pack s) >>= parseShaun of
Left _ -> []
Right r -> [(r, "")]
| Shumush/SNIHs | src/Text/Shaun.hs | gpl-3.0 | 1,068 | 0 | 12 | 254 | 477 | 254 | 223 | 29 | 2 |
import Text.ParserCombinators.Parsec hiding (spaces)
import Control.Monad
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Number Integer
| String String
| Bool Bool
parseNumber :: Parser LispVal
parseNumber = many1 digit >>= return . Number . read
| lifengsun/haskell-exercise | scheme/02/ex-1-1.b.hs | gpl-3.0 | 344 | 0 | 8 | 108 | 88 | 50 | 38 | 10 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Hoodle.Util.Verbatim
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Hoodle.Util.Verbatim where
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Lib
verbatim :: QuasiQuoter
verbatim = QuasiQuoter { quoteExp = litE . stringL
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
| wavewave/hoodle-core | src/Hoodle/Util/Verbatim.hs | gpl-3.0 | 716 | 0 | 7 | 180 | 72 | 51 | 21 | 8 | 1 |
import Data.Char
import Data.List
digitSum :: Int -> Int
digitSum = sum . map digitToInt . show
firstTo40 :: Maybe Int
firstTo40 = find (\x -> digitSum x == 40) [1..]
firstTo :: Int -> Maybe Int
firstTo n = find (\x -> digitSum x == n) [1..]
| medik/lang-hack | Haskell/LearnYouAHaskell/c06/cool-numbers.hs | gpl-3.0 | 245 | 0 | 9 | 51 | 115 | 60 | 55 | 8 | 1 |
module Types.Drupal where
import Text.Parsec
import Text.Parsec.ByteString (parseFromFile)
import System.FilePath.Posix
import Data.Tree
import Data.ByteString (ByteString)
import System.Directory
import qualified DirTree as DT
import Types
dpFindVersionFileLocation :: Website -> Maybe (FilePath)
dpFindVersionFileLocation (Website _ _ _ t) = DT.findChild t ((==) "bootstrap.inc" . filename) >>= return . rootLabel
where filename = takeFileName . rootLabel
dpVersionFileLocation :: Website -> FilePath
dpVersionFileLocation (Website _ _ _ t) = rootLabel t </> "includes" </> "bootstrap.inc"
dpModuleFolders :: Website -> [DirTree]
dpModuleFolders (Website _ _ _ t) = DT.findChilds t ((==) "modules" . takeFileName . rootLabel )
dpVersion :: Website -> IO Version
dpVersion w@(Website Drupal _ _ _) = do
result <- parseFromFile dpParseVersionFile (dpVersionFileLocation w)
case result of
Left _ -> return $ UnknownVersion
Right v -> return $ Version v
dpVersion _ = error "Can't lookup Drupal version for a non Drupal website"
dpModules :: Website -> IO [Plugin]
dpModules w = mapM dpFindModuleInfo $ map rootLabel $ concat $ map (flip DT.findTopChilds infos) $ dpModuleFolders w
where infos (Node n _) = takeExtension n == ".info"
dpFindModulesIn :: DirTree -> [FilePath]
dpFindModulesIn t = [ rootLabel f | f@(Node _ (_:_)) <- subForest t]
dpFindModuleInfo :: FilePath -> IO Plugin
dpFindModuleInfo p = do
fileExist <- doesFileExist p
case fileExist of
False -> return $ Plugin ("No .info file found for " ++ p) UnknownVersion
True -> do
plugin <- parseFromFile dpParseModuleInfo p
case plugin of
Left e -> return $ Plugin (show e) UnknownVersion
Right n -> return n
dpParseVersionFile :: Parsec ByteString () String
dpParseVersionFile = do
manyTill anyChar (try $ string "define('VERSION'")
manyTill anyChar anyQuote
manyTill anyChar anyQuote
where
anyQuote = char '\'' <|> char '"'
-- we use lookAhead because the version and name may not be in that order
dpParseModuleInfo :: Parsec ByteString () Plugin
dpParseModuleInfo = do
n <- lookAhead dpParseModuleName
version <- lookAhead dpParseModuleVersion
case version of
Just v -> return $ Plugin n (Version v)
Nothing -> return $ Plugin n UnknownVersion
dpParseModuleName :: Parsec ByteString () String
dpParseModuleName = dpInfoVariable "name"
dpParseModuleVersion :: Parsec ByteString () (Maybe String)
dpParseModuleVersion = optionMaybe (try $ dpInfoVariable "version")
dpInfoVariable :: String -> Parsec ByteString () String
dpInfoVariable v = do
manyTill anyChar (try $ varDecleration)
spaces >> char '=' >> spaces
between stringLike stringLike contents
where
varDecleration = string v >> (space <|> char '=')
stringLike = optional (char '\'' <|> char '"')
contents = many1 $ noneOf ['"', '\'', '\r', '\n']
| MarkArts/wubstuts | src/Types/Drupal.hs | gpl-3.0 | 3,207 | 0 | 18 | 849 | 936 | 464 | 472 | 63 | 3 |
{-# LANGUAGE PatternSynonyms #-}
{-|
Module : Keyboard
Description : Keyboard values sent by the Minitel
Copyright : (c) Frédéric BISSON, 2014
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
Keyboard values sent by the Minitel.
-}
module Minitel.Constants.Keyboard where
import qualified Minitel.Constants.ASCII as ASCII
import Minitel.Constants.CSI
import Minitel.Type.MNatural (MNat)
default (MNat)
-- * Direction keys
pattern Up = [0x0b]
pattern Down = [0x0a]
pattern Left = [0x08]
pattern Right = [0x09]
pattern ShiftUp = CSI1 0x4d
pattern ShiftDown = CSI1 0x4c
pattern ShiftLeft = CSI1 0x50
pattern ShiftRight = CSI2 0x34 0x68
pattern CtrlLeft = [0x7f]
-- * Return Key
pattern Return = [0x0d]
pattern ShiftReturn = CSI1 0x48
pattern CtrlReturn = CSI2 0x32 0x4a
-- * Function Keys
pattern FuncSend = [ASCII.DC3, 0x41]
pattern FuncPrev = [ASCII.DC3, 0x42]
pattern FuncRepeat = [ASCII.DC3, 0x43]
pattern FuncGuide = [ASCII.DC3, 0x44]
pattern FuncCancel = [ASCII.DC3, 0x45]
pattern FuncTOC = [ASCII.DC3, 0x46]
pattern FuncCorrection = [ASCII.DC3, 0x47]
pattern FuncNext = [ASCII.DC3, 0x48]
pattern FuncConnection = [ASCII.DC3, 0x49]
| Zigazou/HaMinitel | src/Minitel/Constants/Keyboard.hs | gpl-3.0 | 1,280 | 0 | 7 | 271 | 324 | 181 | 143 | 27 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.BillingAccounts.Exclusions.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all the exclusions in a parent resource.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.billingAccounts.exclusions.list@.
module Network.Google.Resource.Logging.BillingAccounts.Exclusions.List
(
-- * REST Resource
BillingAccountsExclusionsListResource
-- * Creating a Request
, billingAccountsExclusionsList
, BillingAccountsExclusionsList
-- * Request Lenses
, baelParent
, baelXgafv
, baelUploadProtocol
, baelAccessToken
, baelUploadType
, baelPageToken
, baelPageSize
, baelCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.billingAccounts.exclusions.list@ method which the
-- 'BillingAccountsExclusionsList' request conforms to.
type BillingAccountsExclusionsListResource =
"v2" :>
Capture "parent" Text :>
"exclusions" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListExclusionsResponse
-- | Lists all the exclusions in a parent resource.
--
-- /See:/ 'billingAccountsExclusionsList' smart constructor.
data BillingAccountsExclusionsList =
BillingAccountsExclusionsList'
{ _baelParent :: !Text
, _baelXgafv :: !(Maybe Xgafv)
, _baelUploadProtocol :: !(Maybe Text)
, _baelAccessToken :: !(Maybe Text)
, _baelUploadType :: !(Maybe Text)
, _baelPageToken :: !(Maybe Text)
, _baelPageSize :: !(Maybe (Textual Int32))
, _baelCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BillingAccountsExclusionsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'baelParent'
--
-- * 'baelXgafv'
--
-- * 'baelUploadProtocol'
--
-- * 'baelAccessToken'
--
-- * 'baelUploadType'
--
-- * 'baelPageToken'
--
-- * 'baelPageSize'
--
-- * 'baelCallback'
billingAccountsExclusionsList
:: Text -- ^ 'baelParent'
-> BillingAccountsExclusionsList
billingAccountsExclusionsList pBaelParent_ =
BillingAccountsExclusionsList'
{ _baelParent = pBaelParent_
, _baelXgafv = Nothing
, _baelUploadProtocol = Nothing
, _baelAccessToken = Nothing
, _baelUploadType = Nothing
, _baelPageToken = Nothing
, _baelPageSize = Nothing
, _baelCallback = Nothing
}
-- | Required. The parent resource whose exclusions are to be listed.
-- \"projects\/[PROJECT_ID]\" \"organizations\/[ORGANIZATION_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\" \"folders\/[FOLDER_ID]\"
baelParent :: Lens' BillingAccountsExclusionsList Text
baelParent
= lens _baelParent (\ s a -> s{_baelParent = a})
-- | V1 error format.
baelXgafv :: Lens' BillingAccountsExclusionsList (Maybe Xgafv)
baelXgafv
= lens _baelXgafv (\ s a -> s{_baelXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
baelUploadProtocol :: Lens' BillingAccountsExclusionsList (Maybe Text)
baelUploadProtocol
= lens _baelUploadProtocol
(\ s a -> s{_baelUploadProtocol = a})
-- | OAuth access token.
baelAccessToken :: Lens' BillingAccountsExclusionsList (Maybe Text)
baelAccessToken
= lens _baelAccessToken
(\ s a -> s{_baelAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
baelUploadType :: Lens' BillingAccountsExclusionsList (Maybe Text)
baelUploadType
= lens _baelUploadType
(\ s a -> s{_baelUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
baelPageToken :: Lens' BillingAccountsExclusionsList (Maybe Text)
baelPageToken
= lens _baelPageToken
(\ s a -> s{_baelPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
baelPageSize :: Lens' BillingAccountsExclusionsList (Maybe Int32)
baelPageSize
= lens _baelPageSize (\ s a -> s{_baelPageSize = a})
. mapping _Coerce
-- | JSONP
baelCallback :: Lens' BillingAccountsExclusionsList (Maybe Text)
baelCallback
= lens _baelCallback (\ s a -> s{_baelCallback = a})
instance GoogleRequest BillingAccountsExclusionsList
where
type Rs BillingAccountsExclusionsList =
ListExclusionsResponse
type Scopes BillingAccountsExclusionsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient BillingAccountsExclusionsList'{..}
= go _baelParent _baelXgafv _baelUploadProtocol
_baelAccessToken
_baelUploadType
_baelPageToken
_baelPageSize
_baelCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy ::
Proxy BillingAccountsExclusionsListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/BillingAccounts/Exclusions/List.hs | mpl-2.0 | 6,551 | 0 | 18 | 1,465 | 894 | 520 | 374 | 131 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Prediction.TrainedModels.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Add new data to a trained model.
--
-- /See:/ <https://developers.google.com/prediction/docs/developer-guide Prediction API Reference> for @prediction.trainedmodels.update@.
module Network.Google.Resource.Prediction.TrainedModels.Update
(
-- * REST Resource
TrainedModelsUpdateResource
-- * Creating a Request
, trainedModelsUpdate
, TrainedModelsUpdate
-- * Request Lenses
, tmuProject
, tmuPayload
, tmuId
) where
import Network.Google.Prediction.Types
import Network.Google.Prelude
-- | A resource alias for @prediction.trainedmodels.update@ method which the
-- 'TrainedModelsUpdate' request conforms to.
type TrainedModelsUpdateResource =
"prediction" :>
"v1.6" :>
"projects" :>
Capture "project" Text :>
"trainedmodels" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] Update :> Put '[JSON] Insert2
-- | Add new data to a trained model.
--
-- /See:/ 'trainedModelsUpdate' smart constructor.
data TrainedModelsUpdate = TrainedModelsUpdate'
{ _tmuProject :: !Text
, _tmuPayload :: !Update
, _tmuId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TrainedModelsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tmuProject'
--
-- * 'tmuPayload'
--
-- * 'tmuId'
trainedModelsUpdate
:: Text -- ^ 'tmuProject'
-> Update -- ^ 'tmuPayload'
-> Text -- ^ 'tmuId'
-> TrainedModelsUpdate
trainedModelsUpdate pTmuProject_ pTmuPayload_ pTmuId_ =
TrainedModelsUpdate'
{ _tmuProject = pTmuProject_
, _tmuPayload = pTmuPayload_
, _tmuId = pTmuId_
}
-- | The project associated with the model.
tmuProject :: Lens' TrainedModelsUpdate Text
tmuProject
= lens _tmuProject (\ s a -> s{_tmuProject = a})
-- | Multipart request metadata.
tmuPayload :: Lens' TrainedModelsUpdate Update
tmuPayload
= lens _tmuPayload (\ s a -> s{_tmuPayload = a})
-- | The unique name for the predictive model.
tmuId :: Lens' TrainedModelsUpdate Text
tmuId = lens _tmuId (\ s a -> s{_tmuId = a})
instance GoogleRequest TrainedModelsUpdate where
type Rs TrainedModelsUpdate = Insert2
type Scopes TrainedModelsUpdate =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/prediction"]
requestClient TrainedModelsUpdate'{..}
= go _tmuProject _tmuId (Just AltJSON) _tmuPayload
predictionService
where go
= buildClient
(Proxy :: Proxy TrainedModelsUpdateResource)
mempty
| rueshyna/gogol | gogol-prediction/gen/Network/Google/Resource/Prediction/TrainedModels/Update.hs | mpl-2.0 | 3,559 | 0 | 15 | 834 | 464 | 277 | 187 | 72 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List the preferred deals for this Ad Exchange account.
--
-- /See:/ <https://developers.google.com/ad-exchange/seller-rest/ Ad Exchange Seller API Reference> for @adexchangeseller.accounts.preferreddeals.list@.
module Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List
(
-- * REST Resource
AccountsPreferredDealsListResource
-- * Creating a Request
, accountsPreferredDealsList
, AccountsPreferredDealsList
-- * Request Lenses
, apdlAccountId
) where
import Network.Google.AdExchangeSeller.Types
import Network.Google.Prelude
-- | A resource alias for @adexchangeseller.accounts.preferreddeals.list@ method which the
-- 'AccountsPreferredDealsList' request conforms to.
type AccountsPreferredDealsListResource =
"adexchangeseller" :>
"v2.0" :>
"accounts" :>
Capture "accountId" Text :>
"preferreddeals" :>
QueryParam "alt" AltJSON :>
Get '[JSON] PreferredDeals
-- | List the preferred deals for this Ad Exchange account.
--
-- /See:/ 'accountsPreferredDealsList' smart constructor.
newtype AccountsPreferredDealsList =
AccountsPreferredDealsList'
{ _apdlAccountId :: Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsPreferredDealsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apdlAccountId'
accountsPreferredDealsList
:: Text -- ^ 'apdlAccountId'
-> AccountsPreferredDealsList
accountsPreferredDealsList pApdlAccountId_ =
AccountsPreferredDealsList' {_apdlAccountId = pApdlAccountId_}
-- | Account owning the deals.
apdlAccountId :: Lens' AccountsPreferredDealsList Text
apdlAccountId
= lens _apdlAccountId
(\ s a -> s{_apdlAccountId = a})
instance GoogleRequest AccountsPreferredDealsList
where
type Rs AccountsPreferredDealsList = PreferredDeals
type Scopes AccountsPreferredDealsList =
'["https://www.googleapis.com/auth/adexchange.seller",
"https://www.googleapis.com/auth/adexchange.seller.readonly"]
requestClient AccountsPreferredDealsList'{..}
= go _apdlAccountId (Just AltJSON)
adExchangeSellerService
where go
= buildClient
(Proxy :: Proxy AccountsPreferredDealsListResource)
mempty
| brendanhay/gogol | gogol-adexchange-seller/gen/Network/Google/Resource/AdExchangeSeller/Accounts/PreferredDeals/List.hs | mpl-2.0 | 3,248 | 0 | 13 | 675 | 307 | 189 | 118 | 53 | 1 |
module GlobalLocal where
topLevelFunction :: Integer -> Integer
topLevelFunction x = x + woot + topLevelValue
where woot :: Integer
woot = 10
topLevelValue :: Integer
topLevelValue = 5
| thewoolleyman/haskellbook | 03/03/chad/Global.hs | unlicense | 196 | 0 | 6 | 40 | 51 | 29 | 22 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
--import Network.Shed.Httpd
import Network.URI
import Network.Wai.Handler.Warp
import Network.Wai
import Network.HTTP.Types.Status
import Data.List
import System.IO
import Ajax
import Muste
import Muste.Grammar
import PGF
import qualified Data.Map.Strict as Map
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as LB
import System.Environment
import Data.Maybe
import Data.Map
import Muste.Tree
import Database.SQLite.Simple
import Database hiding (main)
import Protocol
import Data.Time
import Control.Monad
-- Switch loggin on/off
logging = True
logFile = "messagelog.txt"
filePath = "./demo"
webPrefix = "/"
getFileName :: String -> String
-- getFileName "/" = "index.html"
-- getFileName ('/':fn) = fn
getFileName name
| name == webPrefix = "index.html"
| isPrefixOf webPrefix name = drop (length webPrefix) name
| otherwise = error $ "bad name " ++ name
getType :: String -> String
getType fn
| isSuffixOf "html" fn = "text/html"
| isSuffixOf "css" fn = "text/css"
| isSuffixOf "js" fn = "application/javascript"
| isSuffixOf "ico" fn = "image/x-icon"
| otherwise = "text/plain"
-- Lesson -> Grammar
handleRequest :: Connection -> Map String Grammar -> LessonsPrecomputed -> Application
handleRequest conn grammars prec request response
| isInfixOf ("/cgi") (B.unpack $ rawPathInfo request) =
do
putStrLn $ "CGI-Request" ++ (show request)
body <- fmap (B.unpack . LB.toStrict) $ strictRequestBody request
when logging (do { timestamp <- formatTime defaultTimeLocale "%s" <$> getCurrentTime ; appendFile logFile $ timestamp ++ "\tCGI-Request\t" ++ show body ++ "\n"})
result <- handleClientRequest conn grammars prec body
when logging (do { timestamp <- formatTime defaultTimeLocale "%s" <$> getCurrentTime ; appendFile logFile $ timestamp ++ "\tCGI-Response\t" ++ show result ++ "\n"})
response (responseLBS status200 [("Content-type","application/json")] $ LB.fromStrict $ B.pack result)
| otherwise =
do
putStrLn $ "HTTP" ++ (show request)
let file = getFileName $ B.unpack $ rawPathInfo request
let typ = getType file
content <- B.readFile $ filePath ++ "/" ++ file
response (responseLBS status200 [("Content-type",B.pack typ)] $ LB.fromStrict content)
printHelp :: IO ()
printHelp =
do
putStrLn "Standalone backend for muste."
main :: IO ()
main =
do
args <- getArgs
dbConn <- open "muste.db"
(grammars,precs) <- initPrecomputed dbConn
let isHelp = elem "--help" args
if isHelp then printHelp
else runSettings (setPort 8080 defaultSettings) (handleRequest dbConn grammars precs)
| daherb/Haskell-Muste | ajax-backend/Main-Standalone.hs | artistic-2.0 | 2,752 | 0 | 16 | 532 | 809 | 411 | 398 | 70 | 2 |
{-# 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 | bsd-2-clause | 14,131 | 0 | 15 | 2,158 | 3,894 | 2,025 | 1,869 | -1 | -1 |
import System.Environment
import Test.DocTest
main = doctest ["word2vec"]
| RayRacine/hs-word2vec | word2vec-test.hs | bsd-3-clause | 75 | 0 | 6 | 9 | 22 | 12 | 10 | 3 | 1 |
{-# 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 | bsd-3-clause | 208 | 0 | 7 | 26 | 36 | 21 | 15 | 4 | 0 |
{-# LANGUAGE PackageImports #-}
module System.Posix.Internals (module M) where
import "base" System.Posix.Internals as M
| silkapp/base-noprelude | src/System/Posix/Internals.hs | bsd-3-clause | 126 | 0 | 4 | 18 | 23 | 17 | 6 | 3 | 0 |
{-# 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 | bsd-3-clause | 3,658 | 0 | 11 | 993 | 1,157 | 657 | 500 | 117 | 1 |
{-# 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 | bsd-3-clause | 3,726 | 0 | 16 | 1,285 | 567 | 315 | 252 | 42 | 1 |
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 | bsd-3-clause | 936 | 0 | 14 | 257 | 111 | 57 | 54 | 11 | 4 |
#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 | bsd-3-clause | 819 | 5 | 11 | 244 | 207 | 102 | 105 | 13 | 1 |
{-# 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 | bsd-3-clause | 64,297 | 0 | 21 | 19,112 | 12,735 | 7,171 | 5,564 | 999 | 9 |
{-# 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 | bsd-3-clause | 443 | 0 | 6 | 52 | 47 | 32 | 15 | 8 | 0 |
-- 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 <[email protected]>
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 | bsd-3-clause | 4,875 | 0 | 17 | 1,240 | 1,180 | 627 | 553 | 69 | 4 |
{-# 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 | bsd-3-clause | 1,399 | 15 | 10 | 288 | 359 | 192 | 167 | -1 | -1 |
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 | bsd-3-clause | 845 | 0 | 9 | 171 | 366 | 201 | 165 | 26 | 2 |
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 | bsd-3-clause | 3,184 | 0 | 12 | 729 | 445 | 244 | 201 | 45 | 2 |
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 | bsd-3-clause | 1,537 | 0 | 20 | 435 | 505 | 244 | 261 | 33 | 1 |
{-# 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 | apache-2.0 | 10,707 | 0 | 20 | 2,329 | 3,520 | 1,724 | 1,796 | 219 | 7 |
{-# LANGUAGE FlexibleInstances, ExistentialQuantification, MultiParamTypeClasses #-}
-- |
-- Module : Scion.Server.ConnectionIO
-- License : BSD-style
--
-- Maintainer : [email protected]
-- 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 | bsd-3-clause | 3,491 | 0 | 19 | 953 | 1,085 | 552 | 533 | 76 | 1 |
{-# 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 | bsd-3-clause | 569 | 0 | 9 | 114 | 331 | 190 | 141 | 13 | 1 |
module Grammatik.Grace -- Grammatik mit Trace
-- -- $Id$
where
import Language
import Grammatik
| Erdwolf/autotool-bonn | src/Grammatik/Grace.hs | gpl-2.0 | 102 | 0 | 3 | 20 | 14 | 10 | 4 | 3 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Redshift.DescribeClusterVersions
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Returns descriptions of the available Amazon Redshift cluster versions. You
-- can call this operation even before creating any clusters to learn more about
-- the Amazon Redshift versions. For more information about managing clusters,
-- go to <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html Amazon Redshift Clusters> in the /Amazon Redshift Cluster Management Guide/
--
--
-- <http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterVersions.html>
module Network.AWS.Redshift.DescribeClusterVersions
(
-- * Request
DescribeClusterVersions
-- ** Request constructor
, describeClusterVersions
-- ** Request lenses
, dcvClusterParameterGroupFamily
, dcvClusterVersion
, dcvMarker
, dcvMaxRecords
-- * Response
, DescribeClusterVersionsResponse
-- ** Response constructor
, describeClusterVersionsResponse
-- ** Response lenses
, dcvrClusterVersions
, dcvrMarker
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.Redshift.Types
import qualified GHC.Exts
data DescribeClusterVersions = DescribeClusterVersions
{ _dcvClusterParameterGroupFamily :: Maybe Text
, _dcvClusterVersion :: Maybe Text
, _dcvMarker :: Maybe Text
, _dcvMaxRecords :: Maybe Int
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeClusterVersions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcvClusterParameterGroupFamily' @::@ 'Maybe' 'Text'
--
-- * 'dcvClusterVersion' @::@ 'Maybe' 'Text'
--
-- * 'dcvMarker' @::@ 'Maybe' 'Text'
--
-- * 'dcvMaxRecords' @::@ 'Maybe' 'Int'
--
describeClusterVersions :: DescribeClusterVersions
describeClusterVersions = DescribeClusterVersions
{ _dcvClusterVersion = Nothing
, _dcvClusterParameterGroupFamily = Nothing
, _dcvMaxRecords = Nothing
, _dcvMarker = Nothing
}
-- | The name of a specific cluster parameter group family to return details for.
--
-- Constraints:
--
-- Must be 1 to 255 alphanumeric characters First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
--
dcvClusterParameterGroupFamily :: Lens' DescribeClusterVersions (Maybe Text)
dcvClusterParameterGroupFamily =
lens _dcvClusterParameterGroupFamily
(\s a -> s { _dcvClusterParameterGroupFamily = a })
-- | The specific cluster version to return.
--
-- Example: '1.0'
dcvClusterVersion :: Lens' DescribeClusterVersions (Maybe Text)
dcvClusterVersion =
lens _dcvClusterVersion (\s a -> s { _dcvClusterVersion = a })
-- | An optional parameter that specifies the starting point to return a set of
-- response records. When the results of a 'DescribeClusterVersions' request
-- exceed the value specified in 'MaxRecords', AWS returns a value in the 'Marker'
-- field of the response. You can retrieve the next set of response records by
-- providing the returned marker value in the 'Marker' parameter and retrying the
-- request.
dcvMarker :: Lens' DescribeClusterVersions (Maybe Text)
dcvMarker = lens _dcvMarker (\s a -> s { _dcvMarker = a })
-- | The maximum number of response records to return in each call. If the number
-- of remaining response records exceeds the specified 'MaxRecords' value, a value
-- is returned in a 'marker' field of the response. You can retrieve the next set
-- of records by retrying the command with the returned marker value.
--
-- Default: '100'
--
-- Constraints: minimum 20, maximum 100.
dcvMaxRecords :: Lens' DescribeClusterVersions (Maybe Int)
dcvMaxRecords = lens _dcvMaxRecords (\s a -> s { _dcvMaxRecords = a })
data DescribeClusterVersionsResponse = DescribeClusterVersionsResponse
{ _dcvrClusterVersions :: List "member" ClusterVersion
, _dcvrMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'DescribeClusterVersionsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcvrClusterVersions' @::@ ['ClusterVersion']
--
-- * 'dcvrMarker' @::@ 'Maybe' 'Text'
--
describeClusterVersionsResponse :: DescribeClusterVersionsResponse
describeClusterVersionsResponse = DescribeClusterVersionsResponse
{ _dcvrMarker = Nothing
, _dcvrClusterVersions = mempty
}
-- | A list of 'Version' elements.
dcvrClusterVersions :: Lens' DescribeClusterVersionsResponse [ClusterVersion]
dcvrClusterVersions =
lens _dcvrClusterVersions (\s a -> s { _dcvrClusterVersions = a })
. _List
-- | A value that indicates the starting point for the next set of response
-- records in a subsequent request. If a value is returned in a response, you
-- can retrieve the next set of records by providing this returned marker value
-- in the 'Marker' parameter and retrying the command. If the 'Marker' field is
-- empty, all response records have been retrieved for the request.
dcvrMarker :: Lens' DescribeClusterVersionsResponse (Maybe Text)
dcvrMarker = lens _dcvrMarker (\s a -> s { _dcvrMarker = a })
instance ToPath DescribeClusterVersions where
toPath = const "/"
instance ToQuery DescribeClusterVersions where
toQuery DescribeClusterVersions{..} = mconcat
[ "ClusterParameterGroupFamily" =? _dcvClusterParameterGroupFamily
, "ClusterVersion" =? _dcvClusterVersion
, "Marker" =? _dcvMarker
, "MaxRecords" =? _dcvMaxRecords
]
instance ToHeaders DescribeClusterVersions
instance AWSRequest DescribeClusterVersions where
type Sv DescribeClusterVersions = Redshift
type Rs DescribeClusterVersions = DescribeClusterVersionsResponse
request = post "DescribeClusterVersions"
response = xmlResponse
instance FromXML DescribeClusterVersionsResponse where
parseXML = withElement "DescribeClusterVersionsResult" $ \x -> DescribeClusterVersionsResponse
<$> x .@? "ClusterVersions" .!@ mempty
<*> x .@? "Marker"
instance AWSPager DescribeClusterVersions where
page rq rs
| stop (rs ^. dcvrMarker) = Nothing
| otherwise = (\x -> rq & dcvMarker ?~ x)
<$> (rs ^. dcvrMarker)
| kim/amazonka | amazonka-redshift/gen/Network/AWS/Redshift/DescribeClusterVersions.hs | mpl-2.0 | 7,276 | 0 | 12 | 1,516 | 812 | 488 | 324 | 86 | 1 |
{-# 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 | bsd-3-clause | 3,449 | 0 | 21 | 848 | 978 | 471 | 507 | 89 | 6 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- 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 | bsd-3-clause | 28,607 | 0 | 23 | 10,291 | 9,831 | 4,871 | 4,960 | 598 | 30 |
-- | 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 | bsd-3-clause | 4,168 | 20 | 13 | 800 | 870 | 500 | 370 | 60 | 1 |
tick y = y:tock y
tock y = y:tick y
| themattchan/tandoori | input/mutual.hs | bsd-3-clause | 36 | 0 | 6 | 10 | 31 | 14 | 17 | 2 | 1 |
{-# 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 | bsd-3-clause | 16,598 | 0 | 15 | 4,310 | 3,717 | 2,064 | 1,653 | 266 | 3 |
myEqual :: Eq a => a -> a -> Bool
myEqual x y = if x == y then True else False
foon :: Bool -> Bool -> Bool -> Bool
foon a b c = let
testName1 = myEqual a b
testName2 = myEqual b c
in
testName1 && testName2
| keithodulaigh/Hets | Haskell/test/HOL/ex_let.hs | gpl-2.0 | 213 | 0 | 9 | 57 | 102 | 51 | 51 | 7 | 2 |
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 | bsd-3-clause | 1,476 | 0 | 10 | 327 | 310 | 158 | 152 | 26 | 1 |
main :: IO ()
main = asdf
| MichielDerhaeg/stack | test/integration/tests/1659-skip-component/files/test/Spec.hs | bsd-3-clause | 26 | 0 | 6 | 7 | 16 | 8 | 8 | 2 | 1 |
-- (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 | bsd-3-clause | 9,605 | 0 | 13 | 3,325 | 2,427 | 1,350 | 1,077 | 182 | 4 |
module ShouldFail where
-- !!! Testing duplicate type variables
type T a a = Either a a
| urbanslug/ghc | testsuite/tests/module/mod23.hs | bsd-3-clause | 88 | 0 | 5 | 17 | 18 | 12 | 6 | 2 | 0 |
module Hesh ( sh, cmd, (|>), (/>), (!>), (&>), (</), (/>>), (!>>), (&>>), (<//), (.=)
, passThrough
) where
import Hesh.Process
import Hesh.Shell
| jekor/hesh | lib/Hesh.hs | mit | 171 | 0 | 4 | 48 | 75 | 56 | 19 | 4 | 0 |
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 | mit | 9,270 | 0 | 15 | 2,482 | 1,850 | 983 | 867 | 135 | 2 |
{-# 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 | mit | 2,945 | 0 | 12 | 621 | 1,151 | 620 | 531 | -1 | -1 |
{-# 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 | mit | 4,072 | 0 | 10 | 862 | 1,075 | 611 | 464 | 113 | 1 |
-- 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 | mit | 232 | 0 | 10 | 36 | 65 | 38 | 27 | 4 | 1 |
{-# LANGUAGE
OverloadedStrings
#-}
{-|
Module : HSat.Problem.Instances.CNF.Parser.Internal
Description : Helper functions for parsing CNF files
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
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 | mit | 3,495 | 0 | 15 | 746 | 699 | 368 | 331 | 55 | 1 |
{-# 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 | mit | 274 | 0 | 11 | 64 | 73 | 37 | 36 | 10 | 2 |
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 | mit | 4,629 | 0 | 14 | 1,136 | 541 | 286 | 255 | 38 | 1 |
{-# 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 | mit | 1,532 | 0 | 12 | 271 | 481 | 263 | 218 | 38 | 4 |
{-# 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 | mit | 30,824 | 0 | 19 | 8,187 | 3,840 | 2,034 | 1,806 | 201 | 3 |
{-# 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 | mit | 5,611 | 68 | 11 | 862 | 1,148 | 644 | 504 | 85 | 1 |
{-# 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 | mit | 8,002 | 0 | 16 | 1,879 | 2,229 | 1,159 | 1,070 | 143 | 5 |
{-# 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 | mit | 2,241 | 0 | 12 | 205 | 264 | 151 | 113 | 27 | 1 |
{- |
Module : $Header$
Description : SMT interface for set comparison
Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
This module defines an interface to the SMT solver yices for solving comparison
requests for integer sets defined by the usual boolean operations on the usual
comparison predicates.
The yices input is generated by producing input text files in yices format,
see http://yices.csl.sri.com/language.shtml for the syntax description.
There is also the yices-easy hackage entry which uses the C-API of yices.
This could be an alternative if speed and robustness will be a problem.
-}
module CSL.SMTComparison
( smtCompare
, smtCheck
, VarEnv(..)
, VarMap
) where
import Control.Monad
import qualified Data.Map as Map
import Data.List
import System.IO
import System.Process
import CSL.TreePO
import CSL.BoolBasic
-- ----------------------------------------------------------------------
-- * SMT output generation for SMT based comparison
-- ----------------------------------------------------------------------
-- | This maps are assumed to have distinct values in [1..Map.size varmap],
-- i.e., v::VarMap => Set.fromList (Map.elems v) = {1..Map.size v}
type VarMap = Map.Map String Int
type VarTypes = Map.Map String BoolRep
data VarEnv = VarEnv { varmap :: VarMap
, vartypes :: VarTypes
, loghandle :: Maybe Handle }
smtVars :: VarEnv -> String -> [String]
smtVars m s = smtGenericVars m ((s++) . show)
smtGenericVars :: VarEnv -> (Int -> a) -> [a]
smtGenericVars m f = map f [1 .. Map.size $ varmap m]
smtGenericStmt :: VarEnv -> String -> String -> String -> String
smtGenericStmt m s a b =
let vl = concat $ map (" "++) $ smtVars m "x"
in concat ["(assert+ (not (", s, " (", a, vl, ") (", b, vl, "))))"]
smtEQStmt :: VarEnv -> String -> String -> String
smtEQStmt m a b = smtGenericStmt m "=" a b
smtLEStmt :: VarEnv -> String -> String -> String
smtLEStmt m a b = smtGenericStmt m "=>" a b
smtDisjStmt :: VarEnv -> String -> String -> String
smtDisjStmt m a b =
let vl = concat $ map (" "++) $ smtVars m "x"
in concat ["(assert+ (and (", a, vl, ") (", b, vl, ")))"]
smtAllScript :: VarEnv -> BoolRep -> BoolRep -> String
smtAllScript m r1 r2 =
unlines [ smtScriptHead m r1 r2
, smtEQStmt m "A" "B", "(check) (retract 1)"
, smtLEStmt m "A" "B", "(check) (retract 2)"
, smtLEStmt m "B" "A", "(check) (retract 3)"
, smtDisjStmt m "A" "B", "(check)" ]
smtScriptHead :: VarEnv -> BoolRep -> BoolRep -> String
smtScriptHead = smtScriptHead'
data SMTStatus = Sat | Unsat deriving (Show, Eq)
smtCheck :: VarEnv -> BoolRep -> BoolRep -> IO [SMTStatus]
smtCheck m r1 r2 = smtMultiResponse (loghandle m) $ smtAllScript m r1 r2
-- | The result states of the smt solver are translated to the
-- adequate compare outcome. The boolean value is true if the corresponding
-- set is empty.
smtStatusCompareTable :: [SMTStatus] -> (SetOrdering, Bool, Bool)
smtStatusCompareTable l =
case l of
[Unsat, Unsat, Unsat, x] -> let b = x == Unsat in (Comparable EQ, b, b)
[Sat, Unsat, Sat, x] -> let b = x == Unsat in (Comparable LT, b, b)
[Sat, Sat, Unsat, x] -> let b = x == Unsat in (Comparable GT, b, b)
[Sat, Sat, Sat, Unsat] -> (Incomparable Disjoint, False, False)
[Sat, Sat, Sat, Sat] -> (Incomparable Overlap, False, False)
x -> error $ "smtStatusCompareTable: malformed status " ++ show x
smtCompare :: VarEnv -> BoolRep -> BoolRep -> IO (SetOrdering, Bool, Bool)
smtCompare m r1 r2 = liftM smtStatusCompareTable $ smtCheck m r1 r2
smtResponseToStatus :: String -> SMTStatus
smtResponseToStatus s
| s == "sat" = Sat
| s == "unsat" = Unsat
| s == "" = Sat
| isInfixOf "Error" s = error $ "yices-error: " ++ s
| otherwise = error $ "unknown yices error"
maybeWrite :: Maybe Handle -> String -> IO ()
maybeWrite mH s = case mH of
Just hdl -> hPutStrLn hdl s
_ -> return ()
smtMultiResponse :: Maybe Handle -> String -> IO [SMTStatus]
smtMultiResponse mH inp = do
maybeWrite mH $ "---------- Yices input ----------\n" ++ inp
s <- readProcess "yices" [] inp
maybeWrite mH $ "---------- Yices raw output ----------\n" ++ s
return $ map smtResponseToStatus $ lines s
-- * Alternative Script Generation (without subtypes)
smtScriptHead' :: VarEnv -> BoolRep -> BoolRep -> String
smtScriptHead' m r1 r2 =
unlines [ "(set-arith-only! true)"
, smtPredDef' m "A" r1
, smtPredDef' m "B" r2
, smtVarDef' m
, smtVarConstraint' m
]
-- | Predicate definition
smtPredDef' :: VarEnv -> String -> BoolRep -> String
smtPredDef' m s b = concat [ "(define ", s, "::(->"
, concat $ smtGenericVars m $ const " int"
, " bool) (lambda ("
, concat $ smtGenericVars m
(\ i -> let j = show i
in concat [" x", j, "::int"])
, ") ", smtBoolExp b, "))" ]
smtVarDef' :: VarEnv -> String
smtVarDef' m =
unlines
$ smtGenericVars m (\ i -> let j = show i
in concat ["(define x", j, "::int)"])
-- | Subtype constraints
smtVarConstraint' :: VarEnv -> String
smtVarConstraint' m = h l where
h [] = ""
h l' = concat ["(assert (and ", concat l' , "))"]
l = Map.foldWithKey f [] $ varmap m
g k = case Map.lookup k $ vartypes m of
Just br -> " " ++ smtBoolExp br
Nothing -> ""
f k _ l' = case g k of
"" -> l'
x -> l' ++ [x]
{-
smtAllScripts :: VarEnv -> BoolRep -> BoolRep -> [String]
smtAllScripts m r1 r2 =
let h = smtScriptHead m r1 r2
in [ unlines [h, smtEQStmt m "A" "B", "(check)"]
, unlines [h, smtLEStmt m "A" "B", "(check)"]
, unlines [h, smtLEStmt m "B" "A", "(check)"]
, unlines [h, smtDisjStmt m "A" "B", "(check)"]
]
smtCheck' :: VarEnv -> BoolRep -> BoolRep -> IO [SMTStatus]
smtCheck' m r1 r2 = mapM smtResponse $ smtAllScripts m r1 r2
smtResponse :: String -> IO SMTStatus
smtResponse inp = do
s <- readProcess "yices" [] inp
-- putStrLn "------ yices output ------"
-- putStrLn s
return $ smtResponseToStatus $
case lines s of
[] -> ""
x:_ -> x
smtScriptHeadOrig :: VarEnv -> BoolRep -> BoolRep -> String
smtScriptHeadOrig m r1 r2 =
unlines [ smtTypeDef m
, smtPredDef m "A" r1
, smtPredDef m "B" r2
, smtVarDef m ]
smtGenericScript :: VarEnv -> (VarEnv -> String -> String -> String)
-> BoolRep -> BoolRep -> String
smtGenericScript m f r1 r2 = smtScriptHead m r1 r2 ++ "\n" ++ f m "A" "B"
smtEQScript :: VarEnv -> BoolRep -> BoolRep -> String
smtEQScript m r1 r2 = smtGenericScript m smtEQStmt r1 r2
smtLEScript :: VarEnv -> BoolRep -> BoolRep -> String
smtLEScript m r1 r2 = smtGenericScript m smtLEStmt r1 r2
smtDisjScript :: VarEnv -> BoolRep -> BoolRep -> String
smtDisjScript m r1 r2 = smtGenericScript m smtDisjStmt r1 r2
-}
{-
emptyVarEnv :: Maybe Handle -> VarEnv
emptyVarEnv mHdl = VarEnv { varmap = Map.empty
, vartypes = Map.empty
, loghandle = mHdl }
-- | Type alias and subtype definitions for the domain of the extended params
smtTypeDef :: VarEnv -> String
smtTypeDef m = Map.foldWithKey f "" $ varmap m
where g k a = case Map.lookup k $ vartypes m of
Just br ->
concat [ "(define-type t", show a, " (subtype (x"
, show a, "::int) ", smtBoolExp br, "))" ]
Nothing ->
concat [ "(define-type t", show a, " int)" ]
f k a s = s ++ g k a ++ "\n"
-- | Predicate definition
smtPredDef :: VarEnv -> String -> BoolRep -> String
smtPredDef m s b = concat [ "(define ", s, "::(->"
, concat $ smtVars m " t"
, " bool) (lambda ("
, concat $ smtGenericVars m
(\ i -> let j = show i
in concat [" x", j, "::t", j])
, ") ", smtBoolExp b, "))" ]
smtVarDef :: VarEnv -> String
smtVarDef m =
unlines
$ smtGenericVars m (\ i -> let j = show i
in concat ["(define x", j, "::t", j, ")"])
-}
| nevrenato/Hets_Fork | CSL/SMTComparison.hs | gpl-2.0 | 8,722 | 0 | 15 | 2,598 | 1,622 | 855 | 767 | 104 | 6 |
module Logic.PropositionalLogic.Resolution where
import Control.Monad (forM_, unless)
import Notes hiding (color, directed,
not, (=:))
import Data.Maybe (fromJust)
import Prelude
import Utils
import Text.Dot
import Data.List (find, intercalate, nub,
sort, sortBy)
import Data.Ord (comparing)
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import Text.Blaze (customAttribute, (!))
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Blaze.Html4.Strict (table, td, tr)
import Text.Blaze.Html4.Strict.Attributes (border, cellpadding,
cellspacing)
import qualified Text.Blaze.Internal
import Logic.PropositionalLogic.Sentence
import Logic.PropositionalLogic.TruthTables
data CNFSentence = Conjunction [Disjunction]
deriving (Show, Eq)
instance Monoid CNFSentence where
mempty = Conjunction []
mappend (Conjunction s1) (Conjunction s2) = Conjunction $ s1 ++ s2
data Disjunction = Disjunct [CNFLit]
deriving (Eq)
instance Show Disjunction where
show (Disjunct ls) = intercalate " ∧ " $ map show ls
instance Ord Disjunction where
compare (Disjunct ls1) (Disjunct ls2) = compare (length ls1) (length ls2)
instance Monoid Disjunction where
mempty = Disjunct []
mappend (Disjunct s1) (Disjunct s2) = Disjunct $ s1 ++ s2
data CNFLit = JustLit Text
| NotLit Text
deriving (Eq)
instance Ord CNFLit where
compare = comparing textOfLit
where
textOfLit (JustLit t) = t
textOfLit (NotLit t) = t
instance Show CNFLit where
show (JustLit t) = T.unpack t
show (NotLit t) = "¬" ++ T.unpack t
fromSentence :: Sentence -> CNFSentence
fromSentence = go . cnfTransform
where
go :: Sentence -> CNFSentence
go s@(Literal _) = Conjunction $ [go2 s]
go s@(Or _ _) = Conjunction $ [go2 s]
go s@(Not _) = Conjunction $ [go2 s]
go (And s1 s2) = go s1 `mappend` go s2
go _ = error "CNF transformation didn't result in a CNF sentence."
go2 :: Sentence -> Disjunction
go2 (Literal (Lit True)) = Disjunct [JustLit "T", NotLit "T"] -- Something that works. In practice this won't be necessary.
go2 (Literal (Lit False)) = Disjunct []
go2 (Literal (Symbol s)) = Disjunct [JustLit s]
go2 (Not (Literal (Symbol s))) = Disjunct [NotLit s]
go2 (Or s1 s2) = go2 s1 `mappend` go2 s2
go2 _ = error "CNF transformation didn't result in a CNF sentence."
disjunctNode :: [Attribute] -> Disjunction -> DotGen NodeId
disjunctNode as (Disjunct []) = namelessNode $ [color =: "red", label =: tableCells ["False"]] ++ as
disjunctNode as (Disjunct ls) = namelessNode $ label =: (tableCells $ map show $ sort ls) : as
tableCells :: [String] -> Text
tableCells ls = toStrict $ renderHtml $ table' $ tr $ forM_ ls $ \l -> td $ fromString $ l
where
cellborder :: Text.Blaze.Internal.AttributeValue -> Text.Blaze.Internal.Attribute
cellborder = customAttribute "cellborder"
table' = table ! border "0" ! cellborder "1" ! cellspacing "0" ! cellpadding "5"
proofFig :: Note -> Double -> DotGraph -> Note
proofFig cap height g = do
fp <- dot2tex g
noindent
hereFigure $ do
packageDep_ "graphicx"
includegraphics [KeepAspectRatio True, IGHeight (Cm height), IGWidth (CustomMeasure $ textwidth)] fp
caption cap
proofUnsatisfiable :: Double -> [Sentence] -> Sentence -> Note
proofUnsatisfiable height kb query = do
proofFig cap height $ proofGraph kb query
where cap = do
"A diagram of the proof of "
m $ renderSentence query
proofGraph :: [Sentence] -> Sentence -> DotGraph
proofGraph kb query = graph_ directed $ proofGraphGen cnfSen
where cnfSen = mconcat $ fromSentence (Not query) : map fromSentence kb
proofGraphGen :: CNFSentence -> DotGen ()
proofGraphGen (Conjunction ds) = do
nodeDec [shape =: none]
rankdir leftRight
ids <- mapM (disjunctNode [color =: "green"]) $ map simplify ds
go [] $ zip ids ds
where
go :: [NodeId] -> [(NodeId, Disjunction)] -> DotGen ()
go _ [] = return ()
go _ [(_, Disjunct [])] = return ()
go ts ds = do
case find (\(n, d) -> justTrue d && notElem n ts) ds of
Just (n, _) -> do
n' <- node "true"
n --> n'
go (n:ts) ds
Nothing -> do
let isNew (_, d1) (_, d2) =
case simplify `fmap` resolve d1 d2 of
Nothing -> False
Just d3 -> not (justTrue d3) && (notElem d3 $ map snd ds)
case find (uncurry isNew) cp of
Nothing -> return ()
Just ((n1, d1), (n2, d2)) -> do
let d3 = simplify $ fromJust $ resolve d1 d2
n3 <- disjunctNode [] d3
n1 --> n3
n2 --> n3
let rest = sortBy (comparing snd) $ (n3, d3) : ds
unless (d3 == Disjunct []) $ go ts rest
where
cp :: [((NodeId, Disjunction), (NodeId, Disjunction))]
cp = pairs ds
simplify :: Disjunction -> Disjunction
simplify (Disjunct ls) = Disjunct . sort . nub $ ls
justTrue :: Disjunction -> Bool
justTrue (Disjunct ls) = any (uncurry canReselove) cp
where cp = pairs ls
resolve :: Disjunction -> Disjunction -> Maybe Disjunction
resolve (Disjunct d1) (Disjunct d2) =
case find (uncurry canReselove) cp of
Nothing -> Nothing
Just (a, b) -> Just $ Disjunct $ filter (/= a) d1 ++ filter (/= b) d2
where cp = crossproduct d1 d2
canReselove :: CNFLit -> CNFLit -> Bool
canReselove (JustLit s1) (NotLit s2) = s1 == s2
canReselove (NotLit s1) (JustLit s2) = s1 == s2
canReselove _ _ = False
| NorfairKing/the-notes | src/Logic/PropositionalLogic/Resolution.hs | gpl-2.0 | 6,303 | 0 | 26 | 2,104 | 2,146 | 1,104 | 1,042 | 131 | 10 |
{-# language OverlappingInstances #-}
module Inter.Collector where
import Inter.Types
import Data.Tree
import qualified Blank
import qualified Upload
import qualified PCProblem.Quiz
import qualified Boolean.Instance
import qualified Boolean.Quiz
import qualified Boolean2.Instance
import qualified Boolean2.Quiz
import qualified Sortier.Netz.Check
import qualified Sortier.Merge.Check
import qualified Sortier.Median.Check
import qualified Sortier.Programm.Check
import qualified JVM.Make
import qualified Turing.Make
import qualified Brainfuck.Make
import qualified Peano.Make
import qualified Fun.Quiz
import qualified Fun.Make
import qualified Fun.Direct
import qualified Haskell.Central
import qualified Haskell.Blueprint.Central
import qualified Specify.Inter
import qualified String_Matching.KMP.Central
import qualified String_Matching.BM.Central
import qualified Graph.Selfcom
import qualified Graph.Nachbar
import qualified Graph.Cross
import qualified Graph.MinSep
import qualified Graph.Ramsey
import qualified Graph.Van_der_Waerden
import qualified Graph.Col.Greedy.Central
import qualified Graph.Iso.Central
import qualified Graph.Iso.Quiz
import qualified Graph.MST.Plain
import qualified Graph.MST.Quiz
import qualified Graph.TSP.Plain
import qualified Graph.TSP.Quiz
import qualified Robots.Interface
import qualified Robots.Inverse
import qualified Robots3.Interface
import qualified Robots3.Inverse
import qualified Rushhour.Central
import qualified Graph.Col.Plain
import qualified Graph.Col.Quiz
import qualified Graph.Col.Gadget.Central
import qualified Graph.Cage.Central
import qualified Graph.Graceful.Central
import qualified Collatz.Plain
import qualified Collatz.Inverse
import qualified Collatz.Long
import qualified Hanoi.Semantik
import qualified Hanoi.Quiz
import qualified Type.Check
import qualified Type.Quiz
import qualified Type.Poly.Check
import qualified Type.Poly.Quiz
import qualified FP.Check
import qualified FP.Quiz
-- import qualified Object.Check
-- import qualified Object.Quiz
import qualified Palindrom.Plain
import qualified Faktor.Faktor
import qualified Faktor.Times
import qualified Faktor.Euklid
import qualified Faktor.Inverse
import qualified RSA.Break
import qualified RSA.Quiz
import qualified Diffie_Hellman.Break
import qualified Diffie_Hellman.Quiz
import qualified NFA.Convert
import qualified NFA.Equiv.Challenger
import qualified NFA.Nerode.Congruent.Check
import qualified NFA.Nerode.Congruent.Quiz
import qualified NFA.Nerode.Incongruent.Check
import qualified NFA.Nerode.Incongruent.Quiz
import qualified NFA.Nerode.Separation.Check
import qualified NFA.Compress.Inter
import qualified Exp.Convert
import qualified Exp.Smaller
import qualified Exp.Shortest_Missing
import qualified Pump.Inter
import qualified Pump.Inter2
-- import qualified Grammatik.Interface
import qualified Grammatik.CF.Interface
import qualified Grammatik.CF.Interface2
import qualified NPDA.Inter
import qualified NPDA.Inter2
-- import qualified Turing.Inter
import qualified Grammatik.Akzeptor
import qualified CNF.Optimize
import qualified SAT.SAT
import qualified Baum.Reconstruct
import qualified Baum.Binary
import qualified Baum.ZweiDrei
import qualified Baum.AVL
import qualified Baum.RedBlack
import qualified Baum.List
import qualified Baum.BinHeap
import qualified Baum.Leftist
import qualified Graph.TreeWidth
import qualified Graph.PartialKTree
import qualified Graph.Bi.Quiz
import qualified Graph.Bi.Plain
import qualified Graph.Circle.Quiz
import qualified Graph.Circle.Plain
import qualified Graph.Bisekt.Plain
import qualified Graph.Bisekt.Quiz
import qualified Graph.Way.Plain
import qualified Graph.Way.Quiz
import qualified Graph.Hamilton.Plain
import qualified Graph.Hamilton.Quiz
import qualified Number.Base.Central
import qualified Number.Float.From
import qualified Number.Float.To
import qualified LCS.Instance
import qualified SCS.Instance
import qualified Graph.VC.Central
import qualified Graph.VC.VCSAT
import qualified Partition.Central
import qualified Graph.EDS.Central
import qualified Binpack.Interface
import qualified Binpack.FFD
import qualified KnapsackFraction.Central
-- import qualified RM.Make
import qualified RAM.Make
import qualified Goto.Make
import qualified While.Make
import qualified Markov.Make
import qualified Fractran.Machine
import qualified Program.General.Central
import qualified Program.Array.Instance
import qualified Program.List.Instance
import qualified Program.Cexp.Interface
import qualified Code.Huffman.Boiler
import qualified Code.Quiz
import qualified Code.Class
import qualified Code.Param
import qualified Code.Move_To_Front as MTF
import qualified Code.Burrows_Wheeler as BW
import qualified Code.LZ
import qualified Code.Compress
import qualified Code.Hamming
import qualified Code.Nonprefix
import qualified Code.Nocode
import qualified Rewriting.TRS.Derive as RD
import qualified Rewriting.TRS.Numerical
import qualified Rewriting.Derive
import qualified Rewriting.Termination
import qualified Rewriting.Completion.Improved
import qualified Rewriting.Abstract.Fixed
import qualified Rewriting.Abstract.Quiz
import qualified Rewriting.TRS.Apply
import qualified Rewriting.SRS.Apply
import qualified Lambda.Apply
import qualified Lambda.Derive
import qualified Lambda.Derive2
import qualified Lambda.Backward_Join
import qualified CL.Find
import qualified Unify.Main
import qualified PL.Find_Model
import qualified PL.Split.Term.Fixed
import qualified PL.Split.Term.Quiz
import qualified Hilbert.Central
import qualified Resolution.Central
import qualified Algebraic.Central
import qualified Algebraic.Quiz
import Algebraic.Graph
import Algebraic.STGraph
import qualified Algebraic2.Central
import qualified Algebraic2.Quiz
import Algebraic.Integer
import Algebraic.Set
import Algebraic.Multiset
import Algebraic.Relation
import qualified Flow.Central
import qualified Flow.Common.Central
import qualified Petri.Reach
import qualified Petri.Deadlock
import qualified Petri.Remote
import qualified CSP.Derive
import qualified CSP.STS.Fail
import qualified CSP.STS.Bisi.Central
import qualified LTL.Find_Model
import qualified LTL.Separate
import qualified Network.Counting.Top
import qualified Regular.Top
import qualified Up.Central
import qualified BDD.Top
import qualified DPLL.Top
import qualified DPLLT.Top
import qualified FD.Top
import qualified SOS
import qualified Lattice.Reduce
import qualified Lattice.LLL.Task
import qualified Lattice.LLL.Inverse
import qualified Polynomial.Euclid
import qualified Polynomial.Task.Ideal
import qualified Polynomial.Positive
makers :: [ Make ]
makers = do Right make <- flatten tmakers ; return make
heading :: h -> [ Tree ( Either h i ) ] -> Tree ( Either h i )
heading h ts = Node ( Left h ) ts
item :: i -> Tree ( Either h i )
item i = Node ( Right i ) []
tmakers :: Tree ( Either String Make )
tmakers =
heading "Aufgaben"
[ heading "Spezialfälle"
[ item Blank.make
, item Upload.make
]
, heading "Automaten und Formale Sprachen"
[ heading "endliche Automaten"
[ item NFA.Convert.make
, item NFA.Convert.qmake
, item NFA.Equiv.Challenger.make
, item NFA.Equiv.Challenger.qmake
, item NFA.Compress.Inter.make_fixed
, item NFA.Compress.Inter.make_quiz
]
, heading "reguläre Ausdrücke"
[ item Exp.Convert.make
, item Exp.Convert.qmake
, item Exp.Smaller.make
, item Exp.Shortest_Missing.make
]
, heading "Spezifikationen regulärer Sprachen"
[ heading "konvertiere NFA zu ..."
[ item Regular.Top.make_nfa2nfa
, item Regular.Top.make_nfa2exp
, item Regular.Top.make_nfa2gram
, item Regular.Top.make_nfa2fo
]
, heading "konvertiere Exp zu ..."
[ item Regular.Top.make_exp2nfa
, item Regular.Top.make_exp2exp
, item Regular.Top.make_exp2gram
, item Regular.Top.make_exp2fo
]
, heading "konvertiere Grammatik zu ..."
[ item Regular.Top.make_gram2nfa
, item Regular.Top.make_gram2exp
, item Regular.Top.make_gram2gram
, item Regular.Top.make_gram2fo
]
, heading "konvertiere log. Formel zu ..."
[ item Regular.Top.make_fo2nfa
, item Regular.Top.make_fo2exp
, item Regular.Top.make_fo2gram
, item Regular.Top.make_fo2fo
]
]
, heading "Grammatiken (neu)"
[ item Grammatik.CF.Interface2.make
, item Grammatik.Akzeptor.acceptor
]
, heading "Grammatiken (veraltet)"
[ item Grammatik.CF.Interface.make
]
, heading "Kellerautomaten (neu)"
[ item NPDA.Inter2.make
]
, heading "Kellerautomaten (veraltet)"
[ item NPDA.Inter.make
]
, heading "Pumping-Lemma (neu)"
[ item Pump.Inter2.reg
, item Pump.Inter2.cf
]
, heading "Pumping-Lemma (veraltet)"
[ item Pump.Inter.reg
, item Pump.Inter.cf
]
, heading "Nerode-Kongruenz"
[ item NFA.Nerode.Congruent.Check.make
, item NFA.Nerode.Congruent.Quiz.make
, item NFA.Nerode.Incongruent.Check.make
, item NFA.Nerode.Incongruent.Quiz.make
, item NFA.Nerode.Separation.Check.make
]
, heading "Turing-Maschine (als Akzeptor)"
[ item Turing.Make.acceptor
]
]
, heading "Logik"
[ heading "Aussagenlogik"
[ heading "Umformen (neu)"
[ item Boolean2.Instance.make
, item Boolean2.Quiz.make
]
, heading "Umformen (alt)"
[ item Boolean.Instance.make
, item Boolean.Quiz.make
]
, item SAT.SAT.make_fixed
, item SAT.SAT.make_quiz
, item CNF.Optimize.make_fixed
, item Hilbert.Central.make_fixed
, item Resolution.Central.make_fixed
, item Resolution.Central.make_quiz
, item BDD.Top.make_fixed
, item BDD.Top.make_quiz
, item DPLL.Top.make_fixed
, item DPLL.Top.make_quiz
]
, heading "Prädikatenlogik (mit Constraint-Programmierung)"
[ item PL.Find_Model.make_fixed
, item PL.Split.Term.Fixed.make
, item PL.Split.Term.Quiz.make
, item DPLLT.Top.make_fixed
, item FD.Top.make_fixed
, item FD.Top.make_quiz
]
]
, heading "(Multi)Mengen und Relationen"
[ item $ Algebraic2.Central.make Algebraic_Set
, item $ Algebraic2.Quiz.make Algebraic_Set
, item $ Algebraic2.Central.make Algebraic_Multiset
, item $ Algebraic2.Quiz.make Algebraic_Multiset
, item $ Algebraic2.Central.make Algebraic_Relation
, item $ Algebraic2.Quiz.make Algebraic_Relation
]
, heading "Kombinatorik"
[ item PCProblem.Quiz.make_quiz
, item PCProblem.Quiz.make_fixed
, heading "Ramsey-Theorie"
[ item Graph.Ramsey.make
, item Graph.Van_der_Waerden.make
]
, heading "Lunar Lockout (original)"
[ item Robots.Interface.make
, item Robots.Interface.qmake
, item Robots.Inverse.make
, item Robots.Inverse.qmake
]
, heading "Solar Lockout (modified)"
[ item Robots3.Interface.make
, item Robots3.Interface.qmake
, item Robots3.Inverse.make
, item Robots3.Inverse.qmake
, item Rushhour.Central.make
]
-- , item Rushhour.Central.qmake
, item Hanoi.Semantik.make
, item Hanoi.Quiz.make
, heading "lange gemeinsame Teilfolge"
[ item LCS.Instance.make_fixed
, item LCS.Instance.make_quiz
]
, heading "kurze gemeinsame Superfolge"
[ item SCS.Instance.make_fixed
, item SCS.Instance.make_quiz
]
]
, heading "Berechnungsmodelle"
[ item JVM.Make.make
, item Turing.Make.computer
, item Program.Cexp.Interface.make_fixed
, heading "Programme mit Arrays"
[ item $ Program.General.Central.make_fixed
Program.Array.Instance.Program_Array
, item Program.Array.Instance.make_quiz
]
, heading "Programme mit Listen, Stacks, Queues"
[ heading "Programme mit Listen"
[ item $ Program.General.Central.make_fixed
Program.List.Instance.Program_List
, item Program.List.Instance.make_quiz
]
]
, heading "Primitiv rekursive Funktionen (neu)"
[ item Fun.Direct.make_fixed
, item Fun.Direct.make_quiz
]
, heading "Primitiv rekursive Funktionen (alt)"
[ item Fun.Make.make
, item Fun.Quiz.make
]
, heading "Goto-Programme"
[ item Goto.Make.make
]
, heading "While/Loop-Programme"
[ item While.Make.make
, item RAM.Make.make
]
, heading "Markov-Algorithmen"
[ item Markov.Make.make
]
, heading "Fractran-Programme"
[ item Fractran.Machine.make
]
-- , item RM.Make.make
, item Brainfuck.Make.computer
, heading "Peano-Zahlen und Folds"
[ item Peano.Make.make
]
]
, heading "Prozeßmodelle"
[ heading "Petri-Netze"
[ item $ Petri.Reach.make_fixed
, item $ Petri.Reach.make_quiz
, item $ Petri.Deadlock.make_fixed
, item $ Petri.Deadlock.make_quiz
, heading "Philosophen"
[ item $ Petri.Deadlock.make_diner 4
]
, item $ Petri.Remote.make_fixed
]
, heading "CSP (Prozeß-Algebra)"
[ item $ CSP.Derive.make_fixed
, item $ CSP.Derive.make_quiz
, item $ Exp.Convert.make_csp
, item $ Exp.Convert.qmake_csp
]
, heading "Ablehnungs-Semantik"
[ item CSP.STS.Fail.make_fixed
, item CSP.STS.Fail.make_quiz
]
, heading "Bisimulation"
[ item CSP.STS.Bisi.Central.make_fixed
, item CSP.STS.Bisi.Central.make_quiz
]
, heading "PLTL"
[ item LTL.Find_Model.make_fixed
, item LTL.Separate.make_fixed
]
]
, heading "Terme, Ersetzungssysteme"
[ heading "Abstract Rewriting"
[ item $ Rewriting.Abstract.Fixed.make
, item $ Rewriting.Abstract.Quiz.make
]
, heading "Wortersetzung"
[ item $ Rewriting.Derive.make_fixed Rewriting.SRS.Apply.For_SRS
]
, heading "Termersetzung"
[ item $ Rewriting.Derive.make_fixed Rewriting.TRS.Apply.For_TRS
, item RD.make_quiz
, item Rewriting.TRS.Numerical.make
, heading "Termination"
[ heading "Polynom-Interpretationen" [ item Rewriting.Termination.make_fixed_poly ]
, heading "Matrix-Interpretationen" [ item Rewriting.Termination.make_fixed_matrix ]
]
, item Rewriting.Completion.Improved.make_fixed
]
, heading "Lambda-Kalkül"
[ item $ Rewriting.Derive.make_fixed Lambda.Apply.For_Lambda
]
, heading "Kombinatorische Logik"
[ item $ CL.Find.make_fixed
]
, heading "Unifikation"
[ item $ Unify.Main.make_fixed
, item $ Unify.Main.make_quiz
]
]
, heading "Lambda-Kalkül"
[ item Lambda.Derive2.make_fixed
, item Lambda.Derive2.make_quiz
]
, heading "Lambda-Kalkül (veraltet)"
[ item Lambda.Derive.make_fixed
, item Lambda.Derive.make_quiz
, item Lambda.Backward_Join.make_fixed
]
, heading "Kombinatorische Logik"
[ item $ CL.Find.make_fixed
]
, heading "Graphen"
[ item Graph.Selfcom.make
, item Graph.Iso.Central.make
, item Graph.Iso.Quiz.make
-- , item Graph.Nachbar.make
, item Graph.Cross.make
, item Graph.Ramsey.make
, item Graph.MinSep.make
, item Graph.Col.Plain.make
, item Graph.Col.Quiz.make
, item Graph.Col.Greedy.Central.make
-- , item Graph.Cage.Central.make
, item Graph.Col.Gadget.Central.make
, item Graph.Graceful.Central.make
, item Graph.TreeWidth.make
, item Graph.PartialKTree.make
, item Graph.PartialKTree.qmake
, item Graph.Bi.Quiz.make
, item Graph.Bi.Plain.make
, item Graph.Circle.Quiz.make
, item Graph.Circle.Plain.make
, item Graph.Bisekt.Plain.make
, item Graph.Bisekt.Quiz.make
, item Graph.Way.Plain.make
, item Graph.Way.Quiz.make
, item Graph.MST.Plain.make
, item Graph.MST.Quiz.make
, item Graph.TSP.Plain.make
, item Graph.TSP.Quiz.make
, item Graph.Hamilton.Plain.make
, item Graph.Hamilton.Quiz.make
, heading "Graphoperationen"
[ item $ Algebraic.Central.make Algebraic_Graph
, item $ Algebraic.Quiz.make Algebraic_Graph
, item $ Algebraic.Central.make Algebraic_STGraph
, item $ Algebraic.Quiz.make Algebraic_STGraph
]
]
, heading "Programmierung"
[ item Type.Check.make
, item Type.Quiz.make
, item Type.Poly.Check.make
, item Type.Poly.Quiz.make
, item FP.Check.make
, item FP.Quiz.make
, heading "Programmablaufsteuerung (alt)"
[ item Flow.Central.goto_to_struct_fixed
, item Flow.Central.struct_to_goto_fixed
]
, heading "Programmablaufsteuerung (neu)"
[ item Flow.Common.Central.control_flow_fixed
]
, item Specify.Inter.make
, heading "Haskell-Programmierung"
[ item Haskell.Blueprint.Central.make_fixed
, item Haskell.Central.make_fixed
]
, heading "Unterprogramme (Frames)"
[ item Up.Central.make ]
]
, heading "Algorithmen"
[ heading "Sortiernetze"
[ item Sortier.Netz.Check.make
, item Sortier.Merge.Check.make
, item Sortier.Median.Check.make
]
, heading "Zählnetze"
[ item Network.Counting.Top.make
]
, heading "Sortierprogramme"
[ item Sortier.Programm.Check.make
, item SOS.make_fixed_plain
, item SOS.make_fixed_exp
]
, heading "String-Matching"
[ item String_Matching.KMP.Central.make_fixed
, item String_Matching.KMP.Central.make_quiz
, item String_Matching.BM.Central.make_fixed
, item String_Matching.BM.Central.make_quiz
]
]
, heading "Datenstrukturen"
[ heading "Bäume"
[ heading "Pre/In/Post/Level-Order"
[ item Baum.Reconstruct.make_fixed
, item Baum.Reconstruct.make_quiz
]
, heading "Suchbäume"
[ item Baum.Binary.make_quiz
, item Baum.AVL.make_quiz
, item Baum.RedBlack.make_quiz
, item Baum.ZweiDrei.make_quiz
]
, heading "Heap-geordnete Bäume"
[ item Baum.List.make_fixed
, item Baum.List.make_quiz
, item Baum.BinHeap.make_fixed
, item Baum.BinHeap.make_quiz
, item Baum.Leftist.make_fixed
, item Baum.Leftist.make_quiz
]
]
, heading "Programme mit Arrays"
[ item $ Program.General.Central.make_fixed
Program.Array.Instance.Program_Array
, item Program.Array.Instance.make_quiz
]
, heading "Programme mit Listen"
[ item $ Program.General.Central.make_fixed
Program.List.Instance.Program_List
, item Program.List.Instance.make_quiz
]
]
, heading "Zahlensysteme"
[ item Number.Base.Central.make_fixed
, item Number.Base.Central.make_quiz
, item Number.Float.From.make_fixed
, item Number.Float.From.make_quiz
, item Number.Float.To.make_fixed
, item Number.Float.To.make_quiz
]
, heading "Zahlentheorie"
[ item Collatz.Plain.make
, item Collatz.Plain.qmake
, item Collatz.Inverse.make
, item Collatz.Inverse.qmake
, item Collatz.Long.make
, item Faktor.Times.make_fixed
, item Faktor.Times.make_quiz
, item Faktor.Faktor.make_fixed
, item Faktor.Faktor.make_quiz
, item Faktor.Euklid.make_fixed
, item Faktor.Euklid.make_quiz
, item Faktor.Inverse.make_fixed
, item Faktor.Inverse.make_quiz
]
, heading "Codierung, Kompression, Verschlüsselung"
[ heading "Codierung"
[ item Code.Nonprefix.make_fixed
, item Code.Nocode.make_fixed
, item Code.Nocode.make_quiz
, item Code.Huffman.Boiler.make_fixed
, item Code.Huffman.Boiler.make_quiz
, item $ Code.Class.enc BW.Burrows_Wheeler
, item $ Code.Class.dec BW.Burrows_Wheeler
( "abracadabra", 2 )
, item $ Code.Quiz.enc MTF.Move_To_Front
, item $ Code.Quiz.enc BW.Burrows_Wheeler
, item $ Code.Quiz.dec MTF.Move_To_Front
, item $ Code.Quiz.dec BW.Burrows_Wheeler
, item Code.Hamming.make
]
, heading "Kompression"
[ item $ Code.Compress.make_quiz Code.LZ.Lempel_Ziv_Welch
, item $ Code.Compress.make_quiz Code.LZ.Lempel_Ziv_77
, item $ Code.Compress.make_fixed Code.LZ.Lempel_Ziv_77
]
, heading "Verschlüsselung"
[ item $ RSA.Break.make
, item $ RSA.Quiz.make
, item $ Diffie_Hellman.Break.make
, item $ Diffie_Hellman.Quiz.make
]
]
, heading "NP-vollständige Probleme"
[ item Binpack.Interface.make_fixed
, item Binpack.Interface.make_quiz
, item Binpack.FFD.make_fixed
, item Partition.Central.make_fixed
, item SAT.SAT.make_fixed
, item SAT.SAT.make_quiz
, item Partition.Central.make_quiz
, item KnapsackFraction.Central.make_fixed
, item KnapsackFraction.Central.make_quiz
, item Graph.VC.Central.make_fixed
, item Graph.VC.Central.make_quiz
, item Graph.VC.VCSAT.make_fixed
, item Graph.VC.VCSAT.make_quiz
, item Graph.EDS.Central.make_fixed
, item Graph.EDS.Central.make_quiz
]
, heading "Symbolisches Rechnen"
[ item Polynomial.Euclid.make_fixed_integer
, item Polynomial.Euclid.make_quiz_integer
, item Polynomial.Euclid.make_fixed_gauss
, item Polynomial.Euclid.make_quiz_gauss
, item Polynomial.Euclid.make_fixed_upoly
, item Polynomial.Euclid.make_quiz_upoly
, item Lattice.Reduce.make_fixed
, item Lattice.Reduce.make_quiz
, item Lattice.LLL.Task.make_fixed
, item Lattice.LLL.Inverse.make_fixed
, item Lattice.LLL.Inverse.make_quiz
, item Polynomial.Task.Ideal.make_fixed
, item Polynomial.Task.Ideal.make_quiz
, item Polynomial.Positive.make_fixed
]
, heading "experimentell"
[ item $ Algebraic2.Central.make Algebraic_Integer
, item $ Algebraic2.Quiz.make Algebraic_Integer
, item $ Algebraic.Central.make Algebraic_Graph
, item $ Algebraic.Quiz.make Algebraic_Graph
, item $ Algebraic.Central.make Algebraic_STGraph
, item $ Algebraic.Quiz.make Algebraic_STGraph
]
, heading "noch nicht eingeordnet"
[ item Palindrom.Plain.make
]
]
| marcellussiegburg/autotool | collection/src/Inter/Collector.hs | gpl-2.0 | 27,210 | 68 | 16 | 9,490 | 5,067 | 2,976 | 2,091 | 584 | 1 |
{-# language DeriveDataTypeable, TemplateHaskell #-}
{-# language TypeFamilies #-}
{-# language FlexibleInstances #-}
{-# language ScopedTypeVariables #-}
module Bank where
import Spieler
import qualified Data.Map as M
import Text.PrettyPrint.HughesPJ
import Data.List ( sortBy )
import Data.Ord ( comparing )
import Data.SafeCopy
import Data.Typeable
import Data.Acid
import Control.Monad.State
import Control.Monad.Reader
import Network.XmlRpc.THDeriveXmlRpcType
import Network.XmlRpc.Internals
data Konto = Konto { rating :: Double
, played :: Int
, points :: Int
, protocol_errors :: Int
}
deriving ( Show )
$(deriveSafeCopy 0 'base ''Konto)
$(asXmlRpcStruct ''Konto)
newtype Bank = Bank ( M.Map Name Konto )
deriving ( Typeable, Show )
$(deriveSafeCopy 0 'base ''Bank)
instance ( XmlRpcType v ) => XmlRpcType ( M.Map String v ) where
getType _ = TStruct
toValue m = ValueStruct $ M.toList $ M.map toValue m
fromValue v = case v of
ValueStruct kvs -> do
pairs <- forM kvs $ \ (k,v) ->
do w <- fromValue v ; return ( k, w )
return $ M.fromList pairs
instance XmlRpcType Bank where
getType _ = TStruct
toValue ( Bank m ) = toValue $ M.mapKeys show m
fromValue v = do m <- fromValue v ; return $ Bank $ M.mapKeys Name m
empty :: Bank
empty = Bank M.empty
-- | write the key-value-pairs into the bank,
-- replacing previous values associated to these keys
updates :: M.Map Name Konto -> Update Bank ()
updates m = do
Bank previous <- get
put $ Bank $ M.union m previous
snapshot :: Query Bank Bank
snapshot = ask
$(makeAcidic ''Bank [ 'updates, 'snapshot ])
total :: Bank -> Int
total (Bank b) = sum $ map points $ M.elems b
pretty (Bank b) =
( text "statistics, for" <+> text (show $ total $ Bank b)
<+> text "total points" )
$$ ( nest 3 $ vcat
$ map ( text . show )
$ sortBy ( comparing ( negate . rating . snd ) )
$ M.toList b
)
| jwaldmann/mex | src/Bank.hs | gpl-3.0 | 2,154 | 0 | 17 | 646 | 679 | 353 | 326 | 57 | 1 |
module Main where
import HEP.Util.Table
s1 :: Table Int
s1 = singletonTable 1
s2 = singletonTable 2
main :: IO ()
main = do
putStrLn "table test"
let x = (s1 <|> s2 <|> s1)
y = (s1 <|> s1 )
print (x <-> y)
print (resizeRow 3 [[Just 3]])
-- putStrLn (showLaTeX ((s1 <-> s2) <|> s1))
| wavewave/lhc-analysis-collection | exe/tabletest.hs | gpl-3.0 | 308 | 0 | 12 | 84 | 124 | 64 | 60 | 12 | 1 |
m :: c -> (a, b)
m x = (p x, q x) | hmemcpy/milewski-ctfp-pdf | src/content/1.5/code/haskell/snippet19.hs | gpl-3.0 | 33 | 0 | 6 | 12 | 36 | 19 | 17 | 2 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
--------------------------------------------------------------------------------
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
module MEnv.MEnv
(
MEnv,
MEnvInside (..),
menvUnwrap,
) where
import qualified Control.Monad.State as MState
import Control.Monad.Trans
import MEnv.Env
-- | the MEnv monad
newtype MEnv res a =
MEnv
{
menvUnwrap :: MState.StateT (Env res) IO a
} deriving (Monad,
MonadIO,
MState.MonadState (Env res),
Functor)
--------------------------------------------------------------------------------
-- MEnvInside
class MonadIO m => (MEnvInside res m) | m -> res where
liftMEnv :: (MEnv res) a -> m a
instance (MEnvInside res (MEnv res)) where
liftMEnv = id
instance (Monad m, MEnvInside res m) => MEnvInside res (MState.StateT s m) where
liftMEnv = lift . liftMEnv
| karamellpelle/grid | designer/source/MEnv/GLFW/MEnv.hs | gpl-3.0 | 1,804 | 3 | 10 | 374 | 254 | 150 | 104 | 26 | 0 |
module Main where
import HLocate.Options (Opts (..), parseOpts)
import Shared.File (File (..))
import Control.Monad (liftM2)
import Control.Monad.Trans.Reader (ReaderT, asks, runReaderT)
import Control.Lens (view)
import Pipes
import Pipes.Binary (decoded)
import System.IO (withFile, IOMode (..), Handle)
import qualified Pipes.ByteString as PB
import qualified Pipes.Prelude as P
main :: IO ()
main = parseOpts >>= runReaderT queryDB
queryDB :: ReaderT Opts IO ()
queryDB = do loc <- asks location
ao <- asks andOr
qs <- liftM2 (.) (asks matchFunc) (asks baseName) >>= (\f -> map f <$> asks queries)
ec <- asks endChar
liftIO . withFile loc ReadMode $ \h -> runEffect $
for (decoder (PB.fromHandle h)
>-> reconstruct
>-> P.filter (\x -> ao (($ x) <$> qs)))
(lift . (\x -> putStr x >> putChar ec))
-- Convert stream of bytes into stream of decoded values, skipping errors
decoder :: Producer PB.ByteString IO () -> Producer File IO ()
decoder = void . view decoded
-- Convert File back into full filepath
reconstruct :: Pipe File FilePath IO ()
reconstruct = re ""
where re fp = do f <- await
let new = take (prec f) fp ++ partial f
in yield new >> re new
| crossroads1112/hlocate | src/HLocate.hs | gpl-3.0 | 1,349 | 0 | 19 | 388 | 473 | 251 | 222 | 30 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AppState.States.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Update the data associated with the input key if and only if the passed
-- version matches the currently stored version. This method is safe in the
-- face of concurrent writes. Maximum per-key size is 128KB.
--
-- /See:/ <https://developers.google.com/games/services/web/api/states Google App State API Reference> for @appstate.states.update@.
module Network.Google.Resource.AppState.States.Update
(
-- * REST Resource
StatesUpdateResource
-- * Creating a Request
, statesUpdate
, StatesUpdate
-- * Request Lenses
, suCurrentStateVersion
, suStateKey
, suPayload
) where
import Network.Google.AppState.Types
import Network.Google.Prelude
-- | A resource alias for @appstate.states.update@ method which the
-- 'StatesUpdate' request conforms to.
type StatesUpdateResource =
"appstate" :>
"v1" :>
"states" :>
Capture "stateKey" (Textual Int32) :>
QueryParam "currentStateVersion" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UpdateRequest :>
Put '[JSON] WriteResult
-- | Update the data associated with the input key if and only if the passed
-- version matches the currently stored version. This method is safe in the
-- face of concurrent writes. Maximum per-key size is 128KB.
--
-- /See:/ 'statesUpdate' smart constructor.
data StatesUpdate =
StatesUpdate'
{ _suCurrentStateVersion :: !(Maybe Text)
, _suStateKey :: !(Textual Int32)
, _suPayload :: !UpdateRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatesUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'suCurrentStateVersion'
--
-- * 'suStateKey'
--
-- * 'suPayload'
statesUpdate
:: Int32 -- ^ 'suStateKey'
-> UpdateRequest -- ^ 'suPayload'
-> StatesUpdate
statesUpdate pSuStateKey_ pSuPayload_ =
StatesUpdate'
{ _suCurrentStateVersion = Nothing
, _suStateKey = _Coerce # pSuStateKey_
, _suPayload = pSuPayload_
}
-- | The version of the app state your application is attempting to update.
-- If this does not match the current version, this method will return a
-- conflict error. If there is no data stored on the server for this key,
-- the update will succeed irrespective of the value of this parameter.
suCurrentStateVersion :: Lens' StatesUpdate (Maybe Text)
suCurrentStateVersion
= lens _suCurrentStateVersion
(\ s a -> s{_suCurrentStateVersion = a})
-- | The key for the data to be retrieved.
suStateKey :: Lens' StatesUpdate Int32
suStateKey
= lens _suStateKey (\ s a -> s{_suStateKey = a}) .
_Coerce
-- | Multipart request metadata.
suPayload :: Lens' StatesUpdate UpdateRequest
suPayload
= lens _suPayload (\ s a -> s{_suPayload = a})
instance GoogleRequest StatesUpdate where
type Rs StatesUpdate = WriteResult
type Scopes StatesUpdate =
'["https://www.googleapis.com/auth/appstate"]
requestClient StatesUpdate'{..}
= go _suStateKey _suCurrentStateVersion
(Just AltJSON)
_suPayload
appStateService
where go
= buildClient (Proxy :: Proxy StatesUpdateResource)
mempty
| brendanhay/gogol | gogol-appstate/gen/Network/Google/Resource/AppState/States/Update.hs | mpl-2.0 | 4,102 | 0 | 14 | 927 | 489 | 292 | 197 | 75 | 1 |
func
:: Trither
lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd
(lkasdlkjalsdjlakjsdlkjasldkjalskdjlkajsd -> asd)
| lspitzner/brittany | data/Test18.hs | agpl-3.0 | 171 | 0 | 7 | 31 | 20 | 10 | 10 | 5 | 0 |
module Data.GI.CodeGen.Constant
( genConstant
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.GI.CodeGen.API
import Data.GI.CodeGen.Code
import Data.GI.CodeGen.Conversions
import Data.GI.CodeGen.Haddock (deprecatedPragma, writeDocumentation,
RelativeDocPosition(..))
import Data.GI.CodeGen.Type
import Data.GI.CodeGen.Util (tshow)
-- | Data for a bidrectional pattern synonym. It is either a simple
-- one of the form "pattern Name = value :: Type" or an explicit one
-- of the form
-- > pattern Name <- (view -> value) :: Type where
-- > Name = expression value :: Type
data PatternSynonym = SimpleSynonym PSValue PSType
| ExplicitSynonym PSView PSExpression PSValue PSType
-- Some simple types for legibility
type PSValue = Text
type PSType = Text
type PSView = Text
type PSExpression = Text
writePattern :: Text -> PatternSynonym -> CodeGen ()
writePattern name (SimpleSynonym value t) = line $
"pattern " <> name <> " = " <> value <> " :: " <> t
writePattern name (ExplicitSynonym view expression value t) = do
-- Supported only on ghc >= 7.10
setModuleMinBase Base48
line $ "pattern " <> name <> " <- (" <> view <> " -> "
<> value <> ") :: " <> t <> " where"
indent $ line $
name <> " = " <> expression <> " " <> value <> " :: " <> t
genConstant :: Name -> Constant -> CodeGen ()
genConstant (Name _ name) c = group $ do
setLanguagePragmas ["PatternSynonyms", "ScopedTypeVariables", "ViewPatterns"]
deprecatedPragma name (constantDeprecated c)
handleCGExc (\e -> line $ "-- XXX: Could not generate constant: " <> describeCGError e)
(do writeDocumentation DocBeforeSymbol (constantDocumentation c)
assignValue name (constantType c) (constantValue c)
exportToplevel ("pattern " <> name))
-- | Assign to the given name the given constant value, in a way that
-- can be assigned to the corresponding Haskell type.
assignValue :: Text -> Type -> Text -> ExcCodeGen ()
assignValue name t@(TBasicType TPtr) value = do
ht <- tshow <$> haskellType t
writePattern name (ExplicitSynonym "ptrToIntPtr" "intPtrToPtr" value ht)
assignValue name t@(TBasicType b) value = do
ht <- tshow <$> haskellType t
hv <- showBasicType b value
writePattern name (SimpleSynonym hv ht)
assignValue name t@(TInterface _) value = do
ht <- tshow <$> haskellType t
api <- findAPI t
case api of
Just (APIEnum _) ->
writePattern name (ExplicitSynonym "fromEnum" "toEnum" value ht)
Just (APIFlags _) -> do
-- gflagsToWord and wordToGFlags are polymorphic, so in this
-- case we need to specialize so the type of the pattern is
-- not ambiguous.
let wordValue = "(" <> value <> " :: Word64)"
writePattern name (ExplicitSynonym "gflagsToWord" "wordToGFlags" wordValue ht)
_ -> notImplementedError $ "Don't know how to treat constants of type " <> tshow t
assignValue _ t _ = notImplementedError $ "Don't know how to treat constants of type " <> tshow t
-- | Show a basic type, in a way that can be assigned to the
-- corresponding Haskell type.
showBasicType :: BasicType -> Text -> ExcCodeGen Text
showBasicType TInt i = return i
showBasicType TUInt i = return i
showBasicType TLong i = return i
showBasicType TULong i = return i
showBasicType TInt8 i = return i
showBasicType TUInt8 i = return i
showBasicType TInt16 i = return i
showBasicType TUInt16 i = return i
showBasicType TInt32 i = return i
showBasicType TUInt32 i = return i
showBasicType TInt64 i = return i
showBasicType TUInt64 i = return i
showBasicType TBoolean "0" = return "False"
showBasicType TBoolean "false" = return "False"
showBasicType TBoolean "1" = return "True"
showBasicType TBoolean "true" = return "True"
showBasicType TBoolean b = notImplementedError $ "Could not parse boolean \"" <> b <> "\""
showBasicType TFloat f = return f
showBasicType TDouble d = return d
showBasicType TUTF8 s = return . tshow $ s
showBasicType TFileName fn = return . tshow $ fn
showBasicType TUniChar c = return $ "'" <> c <> "'"
showBasicType TGType gtype = return $ "GType " <> gtype
showBasicType TIntPtr ptr = return ptr
showBasicType TUIntPtr ptr = return ptr
-- We take care of this one separately above
showBasicType TPtr _ = notImplementedError $ "Cannot directly show a pointer"
| ford-prefect/haskell-gi | lib/Data/GI/CodeGen/Constant.hs | lgpl-2.1 | 4,605 | 0 | 16 | 1,082 | 1,186 | 601 | 585 | 81 | 3 |
{-# 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 | apache-2.0 | 1,816 | 0 | 10 | 475 | 689 | 365 | 324 | 38 | 1 |
{-# Hey #-}
{-# LANGUAGE OhMyGod #-}
{-# OPTIONS_GHC --omG #-}
| rikvdkleij/intellij-haskell | src/test/testData/parsing-hs/Pragma.hs | apache-2.0 | 63 | 0 | 2 | 11 | 5 | 4 | 1 | 2 | 0 |
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 | bsd-2-clause | 3,136 | 0 | 20 | 717 | 899 | 476 | 423 | 68 | 2 |
{--
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 | bsd-2-clause | 4,077 | 0 | 23 | 1,089 | 580 | 294 | 286 | 49 | 4 |
-- 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 | bsd-2-clause | 31,062 | 0 | 20 | 8,174 | 6,901 | 3,360 | 3,541 | 651 | 4 |
{-# 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 | bsd-2-clause | 3,729 | 1 | 15 | 1,380 | 789 | 487 | 302 | -1 | -1 |
{-# 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 | bsd-2-clause | 108,770 | 0 | 15 | 16,741 | 34,440 | 17,499 | 16,941 | -1 | -1 |
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 | bsd-3-clause | 8,238 | 0 | 16 | 1,890 | 2,288 | 1,221 | 1,067 | 130 | 3 |
-- | 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 | bsd-3-clause | 9,785 | 0 | 17 | 2,352 | 3,469 | 1,698 | 1,771 | 251 | 6 |
{-# 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 | bsd-3-clause | 783 | 0 | 9 | 134 | 220 | 127 | 93 | 25 | 1 |
{-# 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 | bsd-3-clause | 4,007 | 0 | 12 | 928 | 1,200 | 648 | 552 | 100 | 1 |
[(Call, Env aam, Store d aam, Time aam)]
| davdar/quals | writeup-old/sections/04MonadicAAM/04Optimizations/00Widen/00BeforeSS.hs | bsd-3-clause | 41 | 0 | 7 | 8 | 30 | 15 | 15 | -1 | -1 |
{-# 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 <[email protected]>
-- 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 | bsd-3-clause | 6,454 | 0 | 17 | 2,087 | 2,406 | 1,258 | 1,148 | 177 | 3 |
-- 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 | bsd-3-clause | 932 | 0 | 7 | 223 | 191 | 122 | 69 | 41 | 0 |
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Either
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- 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 | bsd-3-clause | 609 | 0 | 5 | 106 | 33 | 27 | 6 | 4 | 0 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.TextureSwizzle
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- 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 | bsd-3-clause | 806 | 0 | 5 | 107 | 67 | 48 | 19 | 11 | 0 |
{-# 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 | bsd-3-clause | 2,970 | 0 | 13 | 516 | 871 | 474 | 397 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
import Common
main = putStrLn "=== Challange15 ==="
-- Challange done in library code
| andrewcchen/matasano-cryptopals-solutions | set2/Challange15.hs | bsd-3-clause | 124 | 0 | 5 | 21 | 14 | 8 | 6 | 3 | 1 |
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 | bsd-3-clause | 3,195 | 0 | 20 | 631 | 1,396 | 709 | 687 | -1 | -1 |
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 | bsd-3-clause | 1,280 | 0 | 14 | 293 | 566 | 306 | 260 | 32 | 1 |
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 | bsd-3-clause | 3,106 | 0 | 10 | 612 | 1,008 | 565 | 443 | 68 | 1 |
module Main where
import qualified Bot
main :: IO ()
main = Bot.run
| wimdu/alonzo | src/Main.hs | mit | 70 | 0 | 6 | 15 | 25 | 15 | 10 | 4 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.