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 TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RmToRn.Plot.FnView.State
Description : internal state of a FnView widget
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Internal module for FnView.
Internal state of a FnView widget.
-}
module Numeric.AERN.RmToRn.Plot.FnView.State
--(
--)
where
import Numeric.AERN.RmToRn.Plot.FnView.FnData
import Numeric.AERN.RmToRn.Plot.Params
import Numeric.AERN.RmToRn.Domain
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import qualified Numeric.AERN.RefinementOrder as RefOrd
data FnViewState f =
FnViewState
{
favstActiveFns :: [[Bool]],
favstTrackingDefaultEvalPt :: Bool,
favstCanvasParams :: CanvasParams (Domain f),
favstZoomPercent :: Double,
favstPanCentre :: (Domain f, Domain f)
}
initState ::
(ArithInOut.RoundedReal (Domain f))
=>
(ArithInOut.RoundedRealEffortIndicator (Domain f)) ->
(t, FnMetaData f) ->
FnViewState f
initState effReal (_, fnmeta) =
FnViewState
{
favstActiveFns = activeFns,
favstTrackingDefaultEvalPt = True,
favstCanvasParams =
(dataDefaultCanvasParams fnmeta)
{
cnvprmCoordSystem =
linearCoordsWithZoomAndCentre effReal defaultZoom centre $
getFnExtents fnmeta
},
favstZoomPercent = defaultZoom,
favstPanCentre = centre
}
where
centre = getDefaultCentre effReal fnmeta
activeFns = mergeDefaults (mergeDefaults $ \ _a b -> b) allTrue $ dataDefaultActiveFns fnmeta
allTrue = map (map $ const True) $ dataFnNames fnmeta
mergeDefaults :: (a -> a -> a) -> [a] -> [a] -> [a]
mergeDefaults _ [] _ = []
mergeDefaults _ list1 [] = list1
mergeDefaults mergeElems (h1:t1) (h2:t2) =
(mergeElems h1 h2) : (mergeDefaults mergeElems t1 t2)
updateShowAxes ::
Bool ->
(FnViewState f) ->
(FnViewState f)
updateShowAxes showAxes state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmShowAxes = showAxes }
}
updateFontSize ::
Maybe Double ->
(FnViewState f) ->
(FnViewState f)
updateFontSize maybeFontSize state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmShowSampleValuesFontSize = maybeFontSize }
}
defaultZoom :: Double
defaultZoom = 90
updateZoomPanCentreCoordSystem ::
Double ->
(Domain f, Domain f) ->
(CoordSystem (Domain f)) ->
(FnViewState f) ->
(FnViewState f)
updateZoomPanCentreCoordSystem zoomPercent panCentre coordSystem state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = coordSystem },
favstZoomPercent = zoomPercent,
favstPanCentre = panCentre
}
updatePanCentreCoordSystem ::
(Domain f, Domain f) ->
(CoordSystem (Domain f)) ->
(FnViewState f) ->
(FnViewState f)
updatePanCentreCoordSystem = updateZoomPanCentreCoordSystem defaultZoom
updateZoomPercentAndFnExtents ::
ArithInOut.RoundedReal (Domain f)
=>
ArithInOut.RoundedRealEffortIndicator (Domain f)
-> Double
-> (Domain f, Domain f, Domain f, Domain f)
-> FnViewState f
-> FnViewState f
updateZoomPercentAndFnExtents effFromDouble zoomPercent fnExtents state =
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = newCoordSystem },
favstZoomPercent = zoomPercent
}
where
newCoordSystem =
case cnvprmCoordSystem (favstCanvasParams state) of
csys@(CoordSystemLogSqueeze _) ->
csys
CoordSystemLinear _ ->
linearCoordsWithZoomAndCentre effFromDouble zoomPercent centre fnExtents
centre = favstPanCentre state
updateCentreByRatio ::
(ArithInOut.RoundedReal (Domain f),
RefOrd.IntervalLike (Domain f),
Show (Domain f))
=>
(ArithInOut.RoundedRealEffortIndicator (Domain f)) ->
(Double, Double) ->
FnViewState f ->
FnViewState f
updateCentreByRatio effReal (ratX, ratY) state =
case cnvprmCoordSystem (favstCanvasParams state) of
CoordSystemLogSqueeze _ -> state
CoordSystemLinear (Rectangle hi lo l r) ->
-- unsafePrint (
-- "updateCentreByRatio: CoordSystemLinear: "
-- ++ "\n ratX = " ++ show ratX
-- ++ "; ratY = " ++ show ratY
-- ++ "\n shiftX = " ++ show shiftX
-- ++ "; shiftY = " ++ show shiftY
-- ++ "\n old cX = " ++ show cX
-- ++ "; old cY = " ++ show cY
-- ++ "\n old Rect = " ++ show (hi,lo,l,r)
-- ++ "\n new system = " ++ show coordSystem
-- ) $
state
{
favstCanvasParams =
(favstCanvasParams state)
{ cnvprmCoordSystem = coordSystem },
favstPanCentre = (shiftX cX, shiftY cY)
}
where
(cX,cY) = favstPanCentre state
shiftX a =
fst $ RefOrd.getEndpointsOut $
a <-> (ratX |<*> fnDomWidth)
shiftY a =
fst $ RefOrd.getEndpointsOut $
a <-> (ratY |<*> fnRangeHeight)
fnDomWidth =
r <-> l
fnRangeHeight =
lo <-> hi
coordSystem =
CoordSystemLinear
(Rectangle
(shiftY hi) (shiftY lo)
(shiftX l) (shiftX r))
(<->) = ArithInOut.subtrOutEff effAdd
(|<*>) = flip $ ArithInOut.mixedMultOutEff effMultDbl
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effMultDbl =
ArithInOut.mxfldEffortMult sampleDom (1::Double) $ ArithInOut.rrEffortDoubleMixedField sampleDom effReal
sampleDom = cX
updateFnActive ::
Int ->
Int ->
Bool ->
(FnViewState f) ->
(FnViewState f)
updateFnActive fnNo dimNo isActive state =
state
{
favstActiveFns = updateDim $ favstActiveFns state
}
where
updateDim activeDims =
listUpdate fnNo activeFnDims activeDims
where
activeFnDims =
listUpdate dimNo isActive (activeDims !! fnNo)
linearCoordsWithZoom ::
(ArithInOut.RoundedReal t)
=>
ArithInOut.RoundedRealEffortIndicator t ->
Double {-^ zoom level in percent -} ->
(t,t,t,t)
{-^ upper, lower, left, right bounds of the function graph -} ->
CoordSystem t
linearCoordsWithZoom effReal zoomPercent fnExtents@(fnHI, fnLO, fnL, fnR) =
linearCoordsWithZoomAndCentre effReal zoomPercent (cX,cY) fnExtents
where
cX =
(fnL <+> fnR) </>| (2 :: Int)
cY =
(fnLO <+> fnHI) </>| (2 :: Int)
(<+>) = ArithInOut.addOutEff effAdd
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effDivInt =
ArithInOut.mxfldEffortDiv sampleDom (1::Int) $
ArithInOut.rrEffortIntMixedField sampleDom effReal
sampleDom = fnL
linearCoordsWithZoomAndCentre ::
(ArithInOut.RoundedReal t)
=>
ArithInOut.RoundedRealEffortIndicator t ->
Double {-^ zoom level in percent -} ->
(t, t) {-^ x,y coordinates of the centre -} ->
(t, t, t, t)
{-^ upper, lower, left, right bounds of the function graph -} ->
CoordSystem (t)
linearCoordsWithZoomAndCentre effReal zoomPercent (cX,cY) (fnHI, fnLO, fnL, fnR) =
CoordSystemLinear $ Rectangle hi lo l r
where
hi =
cY <+> heighHalf
lo =
cY <-> heighHalf
l =
cX <-> widthHalf
r =
cX <+> widthHalf
heighHalf =
zoomRatio |<*> fnHeightHalf
widthHalf =
zoomRatio |<*> fnWidthHalf
zoomRatio = 100 / zoomPercent
fnWidthHalf =
(fnR <-> fnL) </>| (2 :: Int)
fnHeightHalf =
(fnHI <-> fnLO) </>| (2 :: Int)
(<+>) = ArithInOut.addOutEff effAdd
(<->) = ArithInOut.subtrOutEff effAdd
(|<*>) = flip $ ArithInOut.mixedMultOutEff effMultDbl
(</>|) = ArithInOut.mixedDivOutEff effDivInt
effAdd =
ArithInOut.fldEffortAdd sampleDom $ ArithInOut.rrEffortField sampleDom effReal
effMultDbl =
ArithInOut.mxfldEffortMult sampleDom (1::Double) $
ArithInOut.rrEffortDoubleMixedField sampleDom effReal
effDivInt =
ArithInOut.mxfldEffortDiv sampleDom (1::Int) $
ArithInOut.rrEffortIntMixedField sampleDom effReal
sampleDom = cX
listUpdate :: Int -> a -> [a] -> [a]
listUpdate _ _ [] = error "FV: listUpdate: invalid index"
listUpdate i newx (x:xs)
| i == 0 = newx : xs
| i > 0 = x : (listUpdate (i - 1) newx xs)
| otherwise = error "FV: listUpdate: invalid index"
| michalkonecny/aern | aern-realfn-plot-gtk/src/Numeric/AERN/RmToRn/Plot/FnView/State.hs | bsd-3-clause | 9,417 | 0 | 14 | 2,945 | 2,123 | 1,155 | 968 | 218 | 3 |
module Sesyrel.FaultTree.Elimination (findOrdering, pretend, Algorithm(..)) where
import Sesyrel.FaultTree.Base (Variable)
import Data.Function (on)
import Data.Foldable
import Data.Maybe (fromMaybe)
import Data.List (partition)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Set (Set)
import qualified Data.Set as S
type Clique = Set Variable
type Graph = Map Variable (Set Variable)
data Algorithm = GraphMinFill | GraphMinNeighbors
pretend :: [Variable] -> [[Variable]] -> [[[Variable]]]
pretend vs = map (map S.toList) . pretend' vs . map S.fromList
pretend' :: [Variable] -> [Clique] -> [[Clique]]
pretend' [] cliques = [cliques]
pretend' (v : vs) cliques =
let (c, rest) = escapeClique v cliques
in cliques : pretend' vs (if null c then rest else c : rest)
escapeClique :: Variable -> [Clique] -> (Clique, [Clique])
escapeClique v cliques =
let (yes, no) = partition (elem v) cliques
c = S.delete v $ fold yes
in (c, no)
findOrdering :: Maybe Algorithm -> [Variable] -> [[Variable]] -> [(Variable, Int)]
findOrdering alg vs cs = findOrdering' alg (S.fromList vs) $ map S.fromList cs
findOrdering' :: Maybe Algorithm -> Set Variable -> [Clique] -> [(Variable, Int)]
findOrdering' Nothing = findOrdering' (Just GraphMinNeighbors)
findOrdering' (Just GraphMinFill) = findGraphOrdering costFunctionMinFill
findOrdering' (Just GraphMinNeighbors) = findGraphOrdering costFunctionMinNeighbors
findGraphOrdering :: (Graph -> Variable -> Int) -> Set Variable -> [Clique] -> [(Variable, Int)]
findGraphOrdering costFunction vars cliques = go vars (makeGraph cliques)
where
go vs g | S.null vs = []
| otherwise = let v = getNextVertex (costFunction g) vs
(g', sz) = removeVertex v g
in v `seq` sz `seq` ((v, sz) : go (S.delete v vs) g')
getNextVertex :: (Variable -> Int) -> Set Variable -> Variable
getNextVertex f vs = let costs = S.mapMonotonic (\v -> (v, f v)) vs
in fst $ minimumBy (compare `on` snd) costs
addClique :: Graph -> Clique -> Graph
addClique graph clique = foldl' (flip addEdge) graph edges
where
f = S.toList clique
edges = [(v1, v2) | v1 <- f, v2 <- f, v1 /= v2]
addEdge :: (Variable, Variable) -> Graph -> Graph
addEdge (a, b) = M.insertWith S.union a (S.singleton b)
removeEdge :: (Variable, Variable) -> Graph -> Graph
removeEdge (a, b) = M.adjust (S.delete b) a
removeVertex :: Variable -> Graph -> (Graph, Int)
removeVertex a g = let ns = fromMaybe S.empty (M.lookup a g)
sz = length ns
in ((`addClique` ns) . M.delete a $ foldl' (\g' b -> removeEdge (b, a) $ removeEdge (a, b) g') g ns, sz)
makeGraph :: [Clique] -> Graph
makeGraph cliques = foldl' addClique M.empty cliques
costFunctionMinFill :: Graph -> Variable -> Int
costFunctionMinFill g v =
let neighs = fromMaybe S.empty (M.lookup v g)
edgeNum k = S.size $ S.difference neighs (g M.! k)
in sum . map edgeNum . S.toList $ neighs
costFunctionMinNeighbors :: Graph -> Variable -> Int
costFunctionMinNeighbors g v = S.size . fromMaybe S.empty . M.lookup v $ g
| balodja/sesyrel | src/Sesyrel/FaultTree/Elimination.hs | bsd-3-clause | 3,159 | 0 | 16 | 665 | 1,318 | 701 | 617 | 61 | 2 |
import TCPServer(setupSocket)
import Prelude hiding (lookup)
import Network.Socket
import NaiveHttpRequestParser(naiveHttpRequestParser, Request(..), RequestType(..))
import Control.Concurrent(forkIO, threadDelay, MVar, newMVar, takeMVar, putMVar)
import Control.Monad(forM_, forever)
import Data.Map.Strict(Map, empty, lookup, insert)
newtype Database = Database (MVar (Map String String) )
createDB :: IO Database
createDB = Database <$> newMVar empty
threadPoolSize :: Int
threadPoolSize = 5000
main :: IO ()
main = do
listeningSocket <- setupSocket 3001
db <- createDB
forM_ [1..threadPoolSize] $ \num -> do
putStrLn $ "Forking thread " ++ show num
forkIO (runServer db num listeningSocket)
forever (threadDelay 10000000)
runServer :: Database -> Int -> Socket -> IO ()
runServer database num socket =
forever $ do
(connection, _) <- accept socket
erequest <- naiveHttpRequestParser <$> recv connection 4096
case erequest of
Right (Request GET _ path _) -> do
result <- runQuery path database
send connection result
Right (Request POST body _ _) -> do
newStore <- storeParams database body
send connection ("" ++ show newStore)
Left _ -> send connection "Invalid response"
close connection
runQuery :: String -> Database -> IO String
runQuery path (Database mvar) = do
db <- takeMVar mvar
putMVar mvar db
case lookup path db of
Just value -> return $ "Retrieved Value: " ++ value
Nothing -> return $ "No Value stored at: " ++ path
storeParams ::Database -> [(String, String)] -> IO ()
storeParams (Database mvar) params = do
db <- takeMVar mvar
let newDB = foldr (\(key, val) storage -> insert key val storage) db params
putMVar mvar newDB
| jvans1/haskell_servers | src/ThreadPool.hs | bsd-3-clause | 1,758 | 0 | 16 | 361 | 631 | 316 | 315 | 46 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Provers.SExpr
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Parsing of S-expressions (mainly used for parsing SMT-Lib get-value output)
-----------------------------------------------------------------------------
module Data.SBV.Provers.SExpr where
import Data.Char (isDigit, ord)
import Data.List (isPrefixOf)
import Numeric (readInt, readDec, readHex, fromRat)
import Data.SBV.BitVectors.AlgReals
import Data.SBV.BitVectors.Data (nan, infinity)
-- | ADT S-Expression format, suitable for representing get-model output of SMT-Lib
data SExpr = ECon String
| ENum Integer
| EReal AlgReal
| EFloat Float
| EDouble Double
| EApp [SExpr]
deriving Show
-- | Parse a string into an SExpr, potentially failing with an error message
parseSExpr :: String -> Either String SExpr
parseSExpr inp = do (sexp, extras) <- parse inpToks
if null extras
then return sexp
else die "Extra tokens after valid input"
where inpToks = let cln "" sofar = sofar
cln ('(':r) sofar = cln r (" ( " ++ sofar)
cln (')':r) sofar = cln r (" ) " ++ sofar)
cln (':':':':r) sofar = cln r (" :: " ++ sofar)
cln (c:r) sofar = cln r (c:sofar)
in reverse (map reverse (words (cln inp "")))
die w = fail $ "SBV.Provers.SExpr: Failed to parse S-Expr: " ++ w
++ "\n*** Input : <" ++ inp ++ ">"
parse [] = die "ran out of tokens"
parse ("(":toks) = do (f, r) <- parseApp toks []
f' <- cvt (EApp f)
return (f', r)
parse (")":_) = die "extra tokens after close paren"
parse [tok] = do t <- pTok tok
return (t, [])
parse _ = die "ill-formed s-expr"
parseApp [] _ = die "failed to grab s-expr application"
parseApp (")":toks) sofar = return (reverse sofar, toks)
parseApp ("(":toks) sofar = do (f, r) <- parse ("(":toks)
parseApp r (f : sofar)
parseApp (tok:toks) sofar = do t <- pTok tok
parseApp toks (t : sofar)
pTok "false" = return $ ENum 0
pTok "true" = return $ ENum 1
pTok ('0':'b':r) = mkNum $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
pTok ('b':'v':r) = mkNum $ readDec (takeWhile (/= '[') r)
pTok ('#':'b':r) = mkNum $ readInt 2 (`elem` "01") (\c -> ord c - ord '0') r
pTok ('#':'x':r) = mkNum $ readHex r
pTok n
| not (null n) && isDigit (head n)
= if '.' `elem` n then getReal n
else mkNum $ readDec n
pTok n = return $ ECon n
mkNum [(n, "")] = return $ ENum n
mkNum _ = die "cannot read number"
getReal n = return $ EReal $ mkPolyReal (Left (exact, n'))
where exact = not ("?" `isPrefixOf` reverse n)
n' | exact = n
| True = init n
-- simplify numbers and root-obj values
cvt (EApp [ECon "/", EReal a, EReal b]) = return $ EReal (a / b)
cvt (EApp [ECon "/", EReal a, ENum b]) = return $ EReal (a / fromInteger b)
cvt (EApp [ECon "/", ENum a, EReal b]) = return $ EReal (fromInteger a / b)
cvt (EApp [ECon "/", ENum a, ENum b]) = return $ EReal (fromInteger a / fromInteger b)
cvt (EApp [ECon "-", EReal a]) = return $ EReal (-a)
cvt (EApp [ECon "-", ENum a]) = return $ ENum (-a)
-- bit-vector value as CVC4 prints: (_ bv0 16) for instance
cvt (EApp [ECon "_", ENum a, ENum _b]) = return $ ENum a
cvt (EApp [ECon "root-obj", EApp (ECon "+":trms), ENum k]) = do ts <- mapM getCoeff trms
return $ EReal $ mkPolyReal (Right (k, ts))
cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FP", ENum 11, ENum 53]]) = getDouble n
cvt (EApp [ECon "as", n, EApp [ECon "_", ECon "FP", ENum 8, ENum 24]]) = getFloat n
cvt x = return x
getCoeff (EApp [ECon "*", ENum k, EApp [ECon "^", ECon "x", ENum p]]) = return (k, p) -- kx^p
getCoeff (EApp [ECon "*", ENum k, ECon "x" ] ) = return (k, 1) -- kx
getCoeff ( EApp [ECon "^", ECon "x", ENum p] ) = return (1, p) -- x^p
getCoeff ( ECon "x" ) = return (1, 1) -- x
getCoeff ( ENum k ) = return (k, 0) -- k
getCoeff x = die $ "Cannot parse a root-obj,\nProcessing term: " ++ show x
getDouble (ECon s) = case (s, rdFP (dropWhile (== '+') s)) of
("plusInfinity", _ ) -> return $ EDouble infinity
("minusInfinity", _ ) -> return $ EDouble (-infinity)
("NaN", _ ) -> return $ EDouble nan
(_, Just v) -> return $ EDouble v
_ -> die $ "Cannot parse a double value from: " ++ s
getDouble (EReal r) = return $ EDouble $ fromRat $ toRational r
getDouble x = die $ "Cannot parse a double value from: " ++ show x
getFloat (ECon s) = case (s, rdFP (dropWhile (== '+') s)) of
("plusInfinity", _ ) -> return $ EFloat infinity
("minusInfinity", _ ) -> return $ EFloat (-infinity)
("NaN", _ ) -> return $ EFloat nan
(_, Just v) -> return $ EFloat v
_ -> die $ "Cannot parse a float value from: " ++ s
getFloat (EReal r) = return $ EFloat $ fromRat $ toRational r
getFloat x = die $ "Cannot parse a float value from: " ++ show x
-- | Parses the Z3 floating point formatted numbers like so: 1.321p5/1.2123e9 etc.
rdFP :: (Read a, RealFloat a) => String -> Maybe a
rdFP s = case break (`elem` "pe") s of
(m, 'p':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * ( 2 ** e')
(m, 'e':e) -> rd m >>= \m' -> rd e >>= \e' -> return $ m' * (10 ** e')
(m, "") -> rd m
_ -> Nothing
where rd v = case reads v of
[(n, "")] -> Just n
_ -> Nothing
| TomMD/cryptol | sbv/Data/SBV/Provers/SExpr.hs | bsd-3-clause | 7,211 | 0 | 15 | 3,102 | 2,369 | 1,219 | 1,150 | 100 | 49 |
module Arhelk.Russian.Lemma.Adverb(
adverb
) where
import Arhelk.Core.Rule
import Arhelk.Russian.Lemma.Common
import Arhelk.Russian.Lemma.Data
import Control.Monad
import Data.Text as T
adverb :: Text -> Rule AdverbProperties
adverb w = do
when (w `endsWith` ["о"]) $ imply adverbDegree PositiveDegree
when (w `endsWith` ["е"]) $ imply adverbDegree ComparitiveDegree | Teaspot-Studio/arhelk-russian | src/Arhelk/Russian/Lemma/Adverb.hs | bsd-3-clause | 382 | 0 | 11 | 56 | 119 | 69 | 50 | 11 | 1 |
{-# LANGUAGE ScopedTypeVariables, RecursiveDo #-}
import Data.Char
import System.Environment
import Control.Applicative
import Text.Earley
data Expr
= Expr :+: Expr
| Expr :*: Expr
| Var String
| Lit Int
deriving (Show)
grammar :: forall r. Grammar r String (Prod r String Char Expr)
grammar = mdo
whitespace <- rule $ many $ satisfy isSpace
let token :: Prod r String Char a -> Prod r String Char a
token p = whitespace *> p
sym x = token $ symbol x <?> [x]
ident = token $ (:) <$> satisfy isAlpha <*> many (satisfy isAlphaNum) <?> "identifier"
num = token $ some (satisfy isDigit) <?> "number"
expr0 <- rule
$ (Lit . read) <$> num
<|> Var <$> ident
<|> sym '(' *> expr2 <* sym ')'
expr1 <- rule
$ (:*:) <$> expr1 <* sym '*' <*> expr0
<|> expr0
expr2 <- rule
$ (:+:) <$> expr2 <* sym '+' <*> expr1
<|> expr1
return $ expr2 <* whitespace
main :: IO ()
main = do
x:_ <- getArgs
print $ fullParses $ parser grammar x
| Axure/Earley | examples/Expr2.hs | bsd-3-clause | 1,013 | 0 | 16 | 275 | 396 | 199 | 197 | 34 | 1 |
{-
SkewHeap.hs
by Russell Bentley
A Haskell Implementation of a skew heap.
-}
module SkewHeap (Heap, emptyHeap, merge, insert, delete, minKey, minKeyValue, deleteMin ) where
-- | A binary tree data type.
data Heap k v = Nil | Node (k, v) (Heap k v) (Heap k v)
-- | Blank
emptyHeap :: Heap k v
emptyHeap = Nil
-- | The 'merge' function merges two scew heaps.
merge :: Ord k => Heap k v -> Heap k v -> Heap k v
merge t1 Nil = t1
merge Nil t2 = t2
merge (Node (k1, v1) lt1 rt1) (Node (k2, v2) lt2 rt2) = case compare k1 k2 of
LT -> Node (k1, v1) (merge rt1 (Node (k2, v2) lt2 rt2)) lt1
EQ -> Node (k1, v1) (merge rt1 (Node (k2, v2) lt2 rt2)) lt1
GT -> Node (k2, v2) (merge rt2 (Node (k1, v1) lt1 rt1)) lt2
-- | The insert method is used to put an element in the heap.
insert :: Ord k => (k, v) -> Heap k v -> Heap k v
insert (k, v) = merge (Node (k, v) Nil Nil)
-- | The `delete` method removes an element from a heap.
delete :: Ord k => k -> Heap k v -> Heap k v
delete _ Nil = Nil
delete k1 (Node (k2, v) tl tr) = case compare k1 k2 of
LT -> Node (k2, v) (delete k1 tl) (delete k1 tr)
GT -> Node (k2, v) tl tr
EQ -> tl `merge` tr
-- | NOTE! pattern mathing is non-exhaustive
minKey :: Heap k v -> k
minKey (Node (k, _) _ _) = k
-- | NOTE! pattern mathing is non-exhaustive
minKeyValue :: Heap k v -> (k, v)
minKeyValue (Node (k,v) _ _) = (k, v)
-- | Consider adding a deleteMinandInsert
deleteMin :: Ord k => Heap k v -> Heap k v
deleteMin Nil = Nil
deleteMin (Node _ tl tr) = tl `merge` tr
| ThermalSpan/haskell-euler | src/SkewHeap.hs | bsd-3-clause | 1,914 | 0 | 13 | 755 | 685 | 367 | 318 | 26 | 3 |
-- | A module to contain the magnitude of s-expression parsing.
module Data.AttoLisp.Easy
(fromLispString
,module L)
where
import qualified Data.AttoLisp as L
import qualified Data.Attoparsec as P
import qualified Data.ByteString as B
-- | Parse a single s-expr followed by optional whitespace and end of
-- file.
parseLispOnly :: B.ByteString -> Either String L.Lisp
parseLispOnly b =
case P.parseOnly lisp b of
Left err -> Left ("Bad s-expression: " ++ err)
Right ok -> Right ok
where
lisp = L.lisp
-- | Parse a single s-expr.
fromLispString :: L.FromLisp a => B.ByteString -> Either String a
fromLispString str = L.parseEither L.parseLisp =<< parseLispOnly str
| kini/ghc-server | src/Data/AttoLisp/Easy.hs | bsd-3-clause | 725 | 0 | 10 | 165 | 168 | 92 | 76 | 14 | 2 |
main = print (foldl lcm 1 [1 .. 20]) | foreverbell/project-euler-solutions | src/5.hs | bsd-3-clause | 36 | 0 | 8 | 8 | 25 | 13 | 12 | 1 | 1 |
-- | This module performs the translation of a parsed XML DTD into the
-- internal representation of corresponding Haskell data\/newtypes.
module Text.XML.HaXml.DtdToHaskell.Convert
( dtd2TypeDef
) where
import List (intersperse)
import Text.XML.HaXml.Types hiding (Name)
import Text.XML.HaXml.DtdToHaskell.TypeDef
---- Internal representation for database of DTD decls ----
data Record = R [AttDef] ContentSpec
type Db = [(String,Record)]
---- Build a database of DTD decls then convert them to typedefs ----
---- (Done in two steps because we need to merge ELEMENT and ATTLIST decls.)
---- Apparently multiple ATTLIST decls for the same element are permitted,
---- although only one ELEMENT decl for it is allowed.
dtd2TypeDef :: [MarkupDecl] -> [TypeDef]
dtd2TypeDef mds =
(concatMap convert . reverse . database []) mds
where
database db [] = db
database db (m:ms) =
case m of
(Element (ElementDecl n cs)) ->
case lookup n db of
Nothing -> database ((n, R [] cs):db) ms
(Just (R as _)) -> database (replace n (R as cs) db) ms
(AttList (AttListDecl n as)) ->
case lookup n db of
Nothing -> database ((n, R as EMPTY):db) ms
(Just (R a cs)) -> database (replace n (R (a++as) cs) db) ms
-- (MarkupPE _ m') -> database db (m':ms)
_ -> database db ms
replace n v [] = error "dtd2TypeDef.replace: no element to replace"
replace n v (x@(n0,_):db)
| n==n0 = (n,v): db
| otherwise = x: replace n v db
---- Convert DTD record to typedef ----
convert :: (String, Record) -> [TypeDef]
convert (n, R as cs) =
case cs of
EMPTY -> modifier None []
ANY -> modifier None [[Any]]
--error "NYI: contentspec of ANY"
(Mixed PCDATA) -> modifier None [[String]]
(Mixed (PCDATAplus ns)) -> modifier Star ([String]: map ((:[]) . Defined . name) ns)
(ContentSpec cp) ->
case cp of
(TagName n' m) -> modifier m [[Defined (name n')]]
(Choice cps m) -> modifier m (map ((:[]).inner) cps)
(Seq cps m) -> modifier m [map inner cps]
++ concatMap (mkAttrDef n) as
where
attrs :: AttrFields
attrs = map (mkAttrField n) as
modifier None sts = mkData sts attrs False (name n)
modifier m [[st]] = mkData [[modf m st]] attrs False (name n)
modifier m sts = mkData [[modf m (Defined (name_ n))]]
attrs False (name n) ++
mkData sts [] True (name_ n)
inner :: CP -> StructType
inner (TagName n' m) = modf m (Defined (name n'))
inner (Choice cps m) = modf m (OneOf (map inner cps))
inner (Seq cps None) = Tuple (map inner cps)
inner (Seq cps m) = modf m (Tuple (map inner cps))
modf None x = x
modf Query x = Maybe x
modf Star x = List x
modf Plus x = List1 x
mkData :: [[StructType]] -> AttrFields -> Bool -> Name -> [TypeDef]
mkData [] fs aux n = [DataDef aux n fs []]
mkData [ts] fs aux n = [DataDef aux n fs [(n, ts)]]
mkData tss fs aux n = [DataDef aux n fs (map (mkConstr n) tss)]
where
mkConstr n ts = (mkConsName n ts, ts)
mkConsName (Name x n) sts = Name x (n++concat (intersperse "_" (map flatten sts)))
flatten (Maybe st) = {-"Maybe_" ++ -} flatten st
flatten (List st) = {-"List_" ++ -} flatten st
flatten (List1 st) = {-"List1_" ++ -} flatten st
flatten (Tuple sts) = {-"Tuple" ++ show (length sts) ++ "_" ++ -}
concat (intersperse "_" (map flatten sts))
flatten String = "Str"
flatten (OneOf sts) = {-"OneOf" ++ show (length sts) ++ "_" ++ -}
concat (intersperse "_" (map flatten sts))
flatten Any = "Any"
flatten (Defined (Name _ n)) = n
mkAttrDef e (AttDef n StringType def) =
[]
mkAttrDef e (AttDef n (TokenizedType t) def) =
[] -- mkData [[String]] [] False (name n)
mkAttrDef e (AttDef n (EnumeratedType (NotationType nt)) def) =
[EnumDef (name_a e n) (map (name_ac e n) nt)]
mkAttrDef e (AttDef n (EnumeratedType (Enumeration es)) def) =
[EnumDef (name_a e n) (map (name_ac e n) es)]
-- Default attribute values not handled here
mkAttrField :: String -> AttDef -> (Name,StructType)
mkAttrField e (AttDef n typ req) = (name_f e n, mkType typ req)
where
mkType StringType REQUIRED = String
mkType StringType IMPLIED = Maybe String
mkType StringType (DefaultTo (AttValue [Left s]) f) = Defaultable String s
mkType (TokenizedType _) REQUIRED = String
mkType (TokenizedType _) IMPLIED = Maybe String
mkType (TokenizedType _) (DefaultTo (AttValue [Left s]) f) =
Defaultable String s
mkType (EnumeratedType _) REQUIRED = Defined (name_a e n)
mkType (EnumeratedType _) IMPLIED = Maybe (Defined (name_a e n))
mkType (EnumeratedType _) (DefaultTo (AttValue [Left s]) f) =
Defaultable (Defined (name_a e n)) (hName (name_ac e n s))
| FranklinChen/hugs98-plus-Sep2006 | packages/HaXml/src/Text/XML/HaXml/DtdToHaskell/Convert.hs | bsd-3-clause | 5,118 | 4 | 19 | 1,492 | 1,971 | 1,008 | 963 | 92 | 15 |
{-# LANGUAGE OverloadedStrings #-}
module Templates.Home where
import Core
import Templates
import Templates.CoreForm
import Data.Int
import Text.Blaze ((!))
import qualified Text.Blaze.Html4.Strict as H
import qualified Text.Blaze.Html4.Strict.Attributes as A
homeHtml :: CoreId -> H.Html
homeHtml nbCores = template "core-online: easily generate and share GHC Core for your haskell codeo"
[]
((H.h1 ! A.class_ "header" $ "core-online - get the GHC Core for your haskell code and share it")
>>
(H.p $ coreForm)
>>
(H.p ! A.class_ "footer" $ do
"The database currently contains "
>>
(H.b . H.toHtml $ show nbCores)
>>
" cores.")
) | alpmestan/core-online | src/Templates/Home.hs | bsd-3-clause | 941 | 0 | 14 | 404 | 169 | 97 | 72 | 22 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{- | The replay monad, for computations that can be replayed using traces
Example usage:
> running :: Replay Question Answer a -> IO a
> running prog = play emptyTrace
> where
> play t = do
> (eqa,t') <- run prog t this is the same prog every time!
> case eqa of
> Left q -> do
> putStr ("Question: " ++ q ++ " ")
> r <- getLine
> play (addAnswer t' r)
> Right x -> return x
>
> askAge :: Replay String String Int
> askAge = cut $ do
> birth <- ask "What is your birth year?"
> now <- ask "What is the current year?"
> return (read now - read birth)
>
> getTime :: IO Integer
> getTime = do
> TOD secs _ <- getClockTime
> return secs
>
> example1 :: Replay Question Answer Int
> example1 = do
> t0 <- lift getTime
> lift (putStrLn "Hello!")
> age <- ask "What is your age?"
> lift (putStrLn ("You are " ++ age))
> name <- ask "What is your name?"
> lift (putStrLn (name ++ " is " ++ age ++ " years old"))
> t1 <- lift getTime
> lift (putStrLn ("Total time: " ++ show (t1 - t0) ++ " seconds"))
> return (read age)
>
> example2 :: Replay Question Answer Int
> example2 = do
> t0 <- lift getTime
> age <- askAge
> lift (putStrLn ("You are " ++ (show age)))
> name <- ask "What is your name?"
> lift (putStrLn (name ++ " is " ++ (show age) ++ " years old"))
> t1 <- lift getTime
> lift (putStrLn ("Total time: " ++ show (t1 - t0) ++ " seconds"))
> return age
>
-}
module Control.Monad.Replay
( Replay, lift, ask, run, cut
, emptyTrace, addAnswer
, Trace, Question, Answer, Item(..)) where
import Control.Monad
import Control.Monad.Error (ErrorT)
import qualified Control.Monad.Error as CME
import Control.Monad.IO.Class
import Control.Monad.Supply
import Control.Monad.Writer (WriterT)
import qualified Control.Monad.Writer as CMW
import Data.List
{- | The `Replay` monad is parametrized over two types:
* q - The type of questions (usually `String`)
* r - The type of answers (usually `String`)
-}
newtype Replay q r a = R { replay :: ErrorT q (WriterT (Trace r) (SupplyT (Item r) IO)) a }
deriving (Monad, MonadSupply (Item r), MonadIO
, CME.MonadError q, CMW.MonadWriter (Trace r))
type Trace r = [Item r]
type Question = String
type Answer = String
data Item r = Answer r
| Result String
| Cut Bool String
deriving (Show,Read)
supplyM :: MonadSupply s m => m (Maybe s)
supplyM = do
x <- exhausted
if x then return Nothing else
liftM Just supply
lift :: (CME.Error q, Show a, Read a) => IO a -> Replay q r a
lift a = do
x <- supplyM
case x of
Nothing -> do
res <- liftIO a
CMW.tell [Result (show res)]
return res
Just (Result r) -> return (read r)
Just _ -> error "Expecting result"
ask :: (CME.Error q) => q -> Replay q r r
ask q = do
x <- supplyM
case x of
Nothing -> CME.throwError q
Just (Answer a) -> return a
Just _ -> error "Expecting answer"
cut :: (Read a, Show a, CME.Error q) => Replay q r a -> Replay q r a
cut m = do
x <- supplyM
case x of
Just (Cut True r) -> return (read r)
Just (Cut False _) -> do
res <- CMW.censor (const []) m
CMW.tell [Cut True (show res)]
return res
_ -> do
CMW.tell [Cut False ""]
res <- CMW.censor (const []) m
CMW.tell [Cut True (show res)]
return res
emptyTrace :: Trace r
emptyTrace = []
addAnswer :: Trace r -> r -> Trace r
addAnswer tr t = tr ++ [Answer t]
run :: Replay q r a -> Trace r -> IO (Either q a, Trace r)
run r tr = do
(res, tr') <- evalSupplyT (CMW.runWriterT (CME.runErrorT $ replay r)) tr
return (res, filterCuts (tr ++ tr'))
isFinal :: Item r -> Bool
isFinal (Cut x _) = x
isFinal _ = False
filterCuts :: Trace r -> Trace r
filterCuts xs =
case findIndex isFinal xs of
Nothing -> xs
Just i -> filterCuts' xs i
filterCuts' :: Trace r -> Int -> Trace r
filterCuts' [] _ = []
filterCuts' ((Cut False _):xs) i = filterCuts (drop (i-1) xs)
filterCuts' (x:xs) i = x:filterCuts' xs (i-1)
| co-dan/warm_fuzzy_things | src/Control/Monad/Replay.hs | bsd-3-clause | 4,350 | 0 | 16 | 1,257 | 1,148 | 584 | 564 | 81 | 3 |
{-
OnYourOwn1.hs (adapted from OpenGLApplication which is (c) 2004 Astle/Hawkins)
Copyright (c) Sven Panne 2004-2005 <[email protected]>
This file is part of HOpenGL and distributed under a BSD-style license
See the file libraries/GLUT/LICENSE
-}
import Control.Monad ( when, unless )
import Data.IORef ( IORef, newIORef )
import Data.Maybe ( isJust )
import Graphics.UI.GLUT hiding ( initialize )
import System.Console.GetOpt
import System.Environment ( getProgName )
import System.Exit ( exitWith, ExitCode(..) )
import System.IO ( hPutStr, stderr )
--------------------------------------------------------------------------------
-- Setup GLUT and OpenGL, drop into the event loop.
--------------------------------------------------------------------------------
main :: IO ()
main = do
-- Setup the basic GLUT stuff
(_, args) <- getArgsAndInitialize
opts <- parseOptions args
initialDisplayMode $= [ DoubleBuffered, RGBMode, WithDepthBuffer ]
(if useFullscreen opts then fullscreenMode else windowedMode) opts
state <- initialize
-- Register the event callback functions
displayCallback $= do render state; swapBuffers
reshapeCallback $= Just setupProjection
keyboardMouseCallback $= Just keyboardMouseHandler
idleCallback $= Just (do prepare state; postRedisplay Nothing)
-- At this point, control is relinquished to the GLUT event handler.
-- Control is returned as events occur, via the callback functions.
mainLoop
fullscreenMode :: Options -> IO ()
fullscreenMode opts = do
let addCapability c = maybe id (\x -> (Where' c IsEqualTo x :))
gameModeCapabilities $=
(addCapability GameModeWidth (Just (windowWidth opts)) .
addCapability GameModeHeight (Just (windowHeight opts)) .
addCapability GameModeBitsPerPlane (bpp opts) .
addCapability GameModeRefreshRate (refreshRate opts)) []
enterGameMode
maybeWin <- get currentWindow
if isJust maybeWin
then cursor $= None
else do
hPutStr stderr "Could not enter fullscreen mode, using windowed mode\n"
windowedMode (opts { useFullscreen = False } )
windowedMode :: Options -> IO ()
windowedMode opts = do
initialWindowSize $=
Size (fromIntegral (windowWidth opts)) (fromIntegral (windowHeight opts))
createWindow "BOGLGP - Chapter 2 - On Your Own 1"
return ()
--------------------------------------------------------------------------------
-- Option handling
--------------------------------------------------------------------------------
data Options = Options {
useFullscreen :: Bool,
windowWidth :: Int,
windowHeight :: Int,
bpp :: Maybe Int,
refreshRate :: Maybe Int
}
startOpt :: Options
startOpt = Options {
useFullscreen = False,
windowWidth = 800,
windowHeight = 600,
bpp = Nothing,
refreshRate = Nothing
}
options :: [OptDescr (Options -> IO Options)]
options = [
Option ['f'] ["fullscreen"]
(NoArg (\opt -> return opt { useFullscreen = True }))
"use fullscreen mode if possible",
Option ['w'] ["width"]
(ReqArg (\arg opt -> do w <- readInt "WIDTH" arg
return opt { windowWidth = w })
"WIDTH")
"use window width WIDTH",
Option ['h'] ["height"]
(ReqArg (\arg opt -> do h <- readInt "HEIGHT" arg
return opt { windowHeight = h })
"HEIGHT")
"use window height HEIGHT",
Option ['b'] ["bpp"]
(ReqArg (\arg opt -> do b <- readInt "BPP" arg
return opt { bpp = Just b })
"BPP")
"use BPP bits per plane (ignored in windowed mode)",
Option ['r'] ["refresh-rate"]
(ReqArg (\arg opt -> do r <- readInt "HZ" arg
return opt { refreshRate = Just r })
"HZ")
"use refresh rate HZ (ignored in windowed mode)",
Option ['?'] ["help"]
(NoArg (\_ -> do usage >>= putStr
safeExitWith ExitSuccess))
"show help" ]
readInt :: String -> String -> IO Int
readInt name arg =
case reads arg of
((x,[]) : _) -> return x
_ -> dieWith ["Can't parse " ++ name ++ " argument '" ++ arg ++ "'\n"]
usage :: IO String
usage = do
progName <- getProgName
return $ usageInfo ("Usage: " ++ progName ++ " [OPTION...]") options
parseOptions :: [String] -> IO Options
parseOptions args = do
let (optsActions, nonOptions, errs) = getOpt Permute options args
unless (null nonOptions && null errs) (dieWith errs)
foldl (>>=) (return startOpt) optsActions
dieWith :: [String] -> IO a
dieWith errs = do
u <- usage
mapM_ (hPutStr stderr) (errs ++ [u])
safeExitWith (ExitFailure 1)
--------------------------------------------------------------------------------
-- Handle mouse and keyboard events. For this simple demo, just exit when
-- ESCAPE is pressed.
--------------------------------------------------------------------------------
keyboardMouseHandler :: KeyboardMouseCallback
keyboardMouseHandler (Char '\27') Down _ _ = safeExitWith ExitSuccess
keyboardMouseHandler _ _ _ _ = return ()
safeExitWith :: ExitCode -> IO a
safeExitWith code = do
gma <- get gameModeActive
when gma leaveGameMode
exitWith code
--------------------------------------------------------------------------------
-- The globale state, which is only the current angle in this simple demo.
-- We don't need the window dimensions here, they are not used and would
-- be easily available via GLUT anyway.
--------------------------------------------------------------------------------
data State = State { angle :: IORef GLfloat }
makeState :: IO State
makeState = do
a <- newIORef 0
return $ State { angle = a }
--------------------------------------------------------------------------------
-- Do one time setup, i.e. set the clear color and create the global state.
--------------------------------------------------------------------------------
initialize :: IO State
initialize = do
-- clear to white background
clearColor $= Color4 1 1 1 0
makeState
--------------------------------------------------------------------------------
-- Reset the viewport for window changes.
--------------------------------------------------------------------------------
setupProjection :: ReshapeCallback
setupProjection (Size width height) = do
-- don't want a divide by zero
let h = max 1 height
-- reset the viewport to new dimensions
viewport $= (Position 0 0, Size width h)
-- set projection matrix as the current matrix
matrixMode $= Projection
-- reset projection matrix
loadIdentity
-- calculate aspect ratio of window
perspective 52 (fromIntegral width / fromIntegral h) 1 1000
-- set modelview matrix
matrixMode $= Modelview 0
-- reset modelview matrix
loadIdentity
--------------------------------------------------------------------------------
-- Perform any data-specific updates for a frame. Here we only increment the
-- angle for the rotation of the triangle.
--------------------------------------------------------------------------------
prepare :: State -> IdleCallback
prepare state = do
angle state $~ (+ 0.1)
--------------------------------------------------------------------------------
-- Clear and redraw the scene.
--------------------------------------------------------------------------------
render :: State -> DisplayCallback
render state = do
-- clear screen and depth buffer
clear [ ColorBuffer, DepthBuffer ]
loadIdentity
-- resolve overloading, not needed in "real" programs
let translate3f = translate :: Vector3 GLfloat -> IO ()
color3f = color :: Color3 GLfloat -> IO ()
vertex3f = vertex :: Vertex3 GLfloat -> IO ()
-- move back 5 units and rotate about all 3 axes
translate3f (Vector3 0 0 (-5))
a <- get (angle state)
rotate a (Vector3 1 0 0)
rotate a (Vector3 0 1 0)
rotate a (Vector3 0 0 1)
-- red color
color3f (Color3 1 0 0)
-- draw the triangle such that the rotation point is in the center
renderPrimitive Triangles $ do
vertex3f (Vertex3 1 (-1) 0)
vertex3f (Vertex3 (-1) (-1) 0)
vertex3f (Vertex3 0 1 0)
| FranklinChen/hugs98-plus-Sep2006 | packages/GLUT/examples/BOGLGP/Chapter02/OnYourOwn1.hs | bsd-3-clause | 8,277 | 0 | 17 | 1,775 | 1,892 | 966 | 926 | 148 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module ETA.Iface.BuildTyCl (
buildSynonymTyCon,
buildFamilyTyCon,
buildAlgTyCon,
buildDataCon,
buildPatSyn,
TcMethInfo, buildClass,
distinctAbstractTyConRhs, totallyAbstractTyConRhs,
mkNewTyConRhs, mkDataTyConRhs,
newImplicitBinder
) where
import ETA.Iface.IfaceEnv
import ETA.Types.FamInstEnv( FamInstEnvs )
import ETA.BasicTypes.DataCon
import ETA.BasicTypes.PatSyn
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.BasicTypes
import ETA.BasicTypes.Name
import ETA.BasicTypes.MkId
import ETA.Types.Class
import ETA.Types.TyCon
import ETA.Types.Type
import ETA.BasicTypes.Id
import ETA.Types.Coercion
import ETA.TypeCheck.TcType
import ETA.Main.DynFlags
import ETA.TypeCheck.TcRnMonad
import ETA.BasicTypes.UniqSupply
import ETA.Utils.Util
import ETA.Utils.Outputable
------------------------------------------------------
buildSynonymTyCon :: Name -> [TyVar] -> [Role]
-> Type
-> Kind -- ^ Kind of the RHS
-> TcRnIf m n TyCon
buildSynonymTyCon tc_name tvs roles rhs rhs_kind
= return (mkSynonymTyCon tc_name kind tvs roles rhs)
where kind = mkPiKinds tvs rhs_kind
buildFamilyTyCon :: Name -> [TyVar]
-> FamTyConFlav
-> Kind -- ^ Kind of the RHS
-> TyConParent
-> TcRnIf m n TyCon
buildFamilyTyCon tc_name tvs rhs rhs_kind parent
= return (mkFamilyTyCon tc_name kind tvs rhs parent)
where kind = mkPiKinds tvs rhs_kind
------------------------------------------------------
distinctAbstractTyConRhs, totallyAbstractTyConRhs :: AlgTyConRhs
distinctAbstractTyConRhs = AbstractTyCon True
totallyAbstractTyConRhs = AbstractTyCon False
mkDataTyConRhs :: [DataCon] -> AlgTyConRhs
mkDataTyConRhs cons
= DataTyCon {
data_cons = cons,
is_enum = not (null cons) && all is_enum_con cons
-- See Note [Enumeration types] in TyCon
}
where
is_enum_con con
| (_tvs, theta, arg_tys, _res) <- dataConSig con
= null theta && null arg_tys
mkNewTyConRhs :: Name -> TyCon -> DataCon -> TcRnIf m n AlgTyConRhs
-- ^ Monadic because it makes a Name for the coercion TyCon
-- We pass the Name of the parent TyCon, as well as the TyCon itself,
-- because the latter is part of a knot, whereas the former is not.
mkNewTyConRhs tycon_name tycon con
= do { co_tycon_name <- newImplicitBinder tycon_name mkNewTyCoOcc
; let co_tycon = mkNewTypeCo co_tycon_name tycon etad_tvs etad_roles etad_rhs
; traceIf (text "mkNewTyConRhs" <+> ppr co_tycon)
; return (NewTyCon { data_con = con,
nt_rhs = rhs_ty,
nt_etad_rhs = (etad_tvs, etad_rhs),
nt_co = co_tycon } ) }
-- Coreview looks through newtypes with a Nothing
-- for nt_co, or uses explicit coercions otherwise
where
tvs = tyConTyVars tycon
roles = tyConRoles tycon
inst_con_ty = applyTys (dataConUserType con) (mkTyVarTys tvs)
rhs_ty = {-ASSERT( isFunTy inst_con_ty )-} funArgTy inst_con_ty
-- Instantiate the data con with the
-- type variables from the tycon
-- NB: a newtype DataCon has a type that must look like
-- forall tvs. <arg-ty> -> T tvs
-- Note that we *can't* use dataConInstOrigArgTys here because
-- the newtype arising from class Foo a => Bar a where {}
-- has a single argument (Foo a) that is a *type class*, so
-- dataConInstOrigArgTys returns [].
etad_tvs :: [TyVar] -- Matched lazily, so that mkNewTypeCo can
etad_roles :: [Role] -- return a TyCon without pulling on rhs_ty
etad_rhs :: Type -- See Note [Tricky iface loop] in LoadIface
(etad_tvs, etad_roles, etad_rhs) = eta_reduce (reverse tvs) (reverse roles) rhs_ty
eta_reduce :: [TyVar] -- Reversed
-> [Role] -- also reversed
-> Type -- Rhs type
-> ([TyVar], [Role], Type) -- Eta-reduced version
-- (tyvars in normal order)
eta_reduce (a:as) (_:rs) ty | Just (fun, arg) <- splitAppTy_maybe ty,
Just tv <- getTyVar_maybe arg,
tv == a,
not (a `elemVarSet` tyVarsOfType fun)
= eta_reduce as rs fun
eta_reduce tvs rs ty = (reverse tvs, reverse rs, ty)
------------------------------------------------------
buildDataCon :: FamInstEnvs
-> Name -> Bool
-> [HsBang]
-> [Name] -- Field labels
-> [TyVar] -> [TyVar] -- Univ and ext
-> [(TyVar,Type)] -- Equality spec
-> ThetaType -- Does not include the "stupid theta"
-- or the GADT equalities
-> [Type] -> Type -- Argument and result types
-> TyCon -- Rep tycon
-> TcRnIf m n DataCon
-- A wrapper for DataCon.mkDataCon that
-- a) makes the worker Id
-- b) makes the wrapper Id if necessary, including
-- allocating its unique (hence monadic)
buildDataCon fam_envs src_name declared_infix arg_stricts field_lbls
univ_tvs ex_tvs eq_spec ctxt arg_tys res_ty rep_tycon
= do { wrap_name <- newImplicitBinder src_name mkDataConWrapperOcc
; work_name <- newImplicitBinder src_name mkDataConWorkerOcc
-- This last one takes the name of the data constructor in the source
-- code, which (for Haskell source anyway) will be in the DataName name
-- space, and puts it into the VarName name space
; us <- newUniqueSupply
; dflags <- getDynFlags
; let
stupid_ctxt = mkDataConStupidTheta rep_tycon arg_tys univ_tvs
data_con = mkDataCon src_name declared_infix
arg_stricts field_lbls
univ_tvs ex_tvs eq_spec ctxt
arg_tys res_ty rep_tycon
stupid_ctxt dc_wrk dc_rep
dc_wrk = mkDataConWorkId work_name data_con
dc_rep = initUs_ us (mkDataConRep dflags fam_envs wrap_name data_con)
; return data_con }
-- The stupid context for a data constructor should be limited to
-- the type variables mentioned in the arg_tys
-- ToDo: Or functionally dependent on?
-- This whole stupid theta thing is, well, stupid.
mkDataConStupidTheta :: TyCon -> [Type] -> [TyVar] -> [PredType]
mkDataConStupidTheta tycon arg_tys univ_tvs
| null stupid_theta = [] -- The common case
| otherwise = filter in_arg_tys stupid_theta
where
tc_subst = zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
stupid_theta = substTheta tc_subst (tyConStupidTheta tycon)
-- Start by instantiating the master copy of the
-- stupid theta, taken from the TyCon
arg_tyvars = tyVarsOfTypes arg_tys
in_arg_tys pred = not $ isEmptyVarSet $
tyVarsOfType pred `intersectVarSet` arg_tyvars
------------------------------------------------------
buildPatSyn :: Name -> Bool
-> (Id,Bool) -> Maybe (Id, Bool)
-> ([TyVar], ThetaType) -- ^ Univ and req
-> ([TyVar], ThetaType) -- ^ Ex and prov
-> [Type] -- ^ Argument types
-> Type -- ^ Result type
-> PatSyn
buildPatSyn src_name declared_infix matcher@(matcher_id,_) builder
(univ_tvs, req_theta) (ex_tvs, prov_theta) arg_tys pat_ty
= -- ASSERT((and [ univ_tvs == univ_tvs'
-- , ex_tvs == ex_tvs'
-- , pat_ty `eqType` pat_ty'
-- , prov_theta `eqTypes` prov_theta'
-- , req_theta `eqTypes` req_theta'
-- , arg_tys `eqTypes` arg_tys'
-- ]))
mkPatSyn src_name declared_infix
(univ_tvs, req_theta) (ex_tvs, prov_theta)
arg_tys pat_ty
matcher builder
where
((_:univ_tvs'), req_theta', tau) = tcSplitSigmaTy $ idType matcher_id
([pat_ty', cont_sigma, _], _) = tcSplitFunTys tau
(ex_tvs', prov_theta', cont_tau) = tcSplitSigmaTy cont_sigma
(arg_tys', _) = tcSplitFunTys cont_tau
-- ------------------------------------------------------
type TcMethInfo = (Name, DefMethSpec, Type)
-- A temporary intermediate, to communicate between
-- tcClassSigs and buildClass.
buildClass :: Name -> [TyVar] -> [Role] -> ThetaType
-> [FunDep TyVar] -- Functional dependencies
-> [ClassATItem] -- Associated types
-> [TcMethInfo] -- Method info
-> ClassMinimalDef -- Minimal complete definition
-> RecFlag -- Info for type constructor
-> TcRnIf m n Class
buildClass tycon_name tvs roles sc_theta fds at_items sig_stuff mindef tc_isrec
= fixM $ \ rec_clas -> -- Only name generation inside loop
do { traceIf (text "buildClass")
; datacon_name <- newImplicitBinder tycon_name mkClassDataConOcc
-- The class name is the 'parent' for this datacon, not its tycon,
-- because one should import the class to get the binding for
-- the datacon
; op_items <- mapM (mk_op_item rec_clas) sig_stuff
-- Build the selector id and default method id
-- Make selectors for the superclasses
; sc_sel_names <- mapM (newImplicitBinder tycon_name . mkSuperDictSelOcc)
[1..length sc_theta]
; let sc_sel_ids = [ mkDictSelId sc_name rec_clas
| sc_name <- sc_sel_names]
-- We number off the Dict superclass selectors, 1, 2, 3 etc so that we
-- can construct names for the selectors. Thus
-- class (C a, C b) => D a b where ...
-- gives superclass selectors
-- D_sc1, D_sc2
-- (We used to call them D_C, but now we can have two different
-- superclasses both called C!)
; let use_newtype = isSingleton arg_tys
-- Use a newtype if the data constructor
-- (a) has exactly one value field
-- i.e. exactly one operation or superclass taken together
-- (b) that value is of lifted type (which they always are, because
-- we box equality superclasses)
-- See note [Class newtypes and equality predicates]
-- We treat the dictionary superclasses as ordinary arguments.
-- That means that in the case of
-- class C a => D a
-- we don't get a newtype with no arguments!
args = sc_sel_names ++ op_names
op_tys = [ty | (_,_,ty) <- sig_stuff]
op_names = [op | (op,_,_) <- sig_stuff]
arg_tys = sc_theta ++ op_tys
rec_tycon = classTyCon rec_clas
; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
datacon_name
False -- Not declared infix
(map (const HsNoBang) args)
[{- No fields -}]
tvs [{- no existentials -}]
[{- No GADT equalities -}]
[{- No theta -}]
arg_tys
(mkTyConApp rec_tycon (mkTyVarTys tvs))
rec_tycon
; rhs <- if use_newtype
then mkNewTyConRhs tycon_name rec_tycon dict_con
else return (mkDataTyConRhs [dict_con])
; let { clas_kind = mkPiKinds tvs constraintKind
; tycon = mkClassTyCon tycon_name clas_kind tvs roles
rhs rec_clas tc_isrec
-- A class can be recursive, and in the case of newtypes
-- this matters. For example
-- class C a where { op :: C b => a -> b -> Int }
-- Because C has only one operation, it is represented by
-- a newtype, and it should be a *recursive* newtype.
-- [If we don't make it a recursive newtype, we'll expand the
-- newtype like a synonym, but that will lead to an infinite
-- type]
; result = mkClass tvs fds
sc_theta sc_sel_ids at_items
op_items mindef tycon
}
; traceIf (text "buildClass" <+> ppr tycon)
; return result }
where
mk_op_item :: Class -> TcMethInfo -> TcRnIf n m ClassOpItem
mk_op_item rec_clas (op_name, dm_spec, _)
= do { dm_info <- case dm_spec of
NoDM -> return NoDefMeth
GenericDM -> do { dm_name <- newImplicitBinder op_name mkGenDefMethodOcc
; return (GenDefMeth dm_name) }
VanillaDM -> do { dm_name <- newImplicitBinder op_name mkDefaultMethodOcc
; return (DefMeth dm_name) }
; return (mkDictSelId op_name rec_clas, dm_info) }
{-
Note [Class newtypes and equality predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
class (a ~ F b) => C a b where
op :: a -> b
We cannot represent this by a newtype, even though it's not
existential, because there are two value fields (the equality
predicate and op. See Trac #2238
Moreover,
class (a ~ F b) => C a b where {}
Here we can't use a newtype either, even though there is only
one field, because equality predicates are unboxed, and classes
are boxed.
-}
| alexander-at-github/eta | compiler/ETA/Iface/BuildTyCl.hs | bsd-3-clause | 14,445 | 0 | 17 | 5,113 | 2,224 | 1,235 | 989 | 190 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
#ifdef DataPolyKinds
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
#endif
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE ExplicitNamespaces #-}
#endif
module GHC.Generics.Compat
( V1
, U1 (U1)
, Par1 (Par1, unPar1)
, Rec1 (Rec1, unRec1)
, K1 (K1, unK1)
, M1 (M1, unM1)
, (:+:) (L1, R1)
, (:*:) ((:*:))
, (:.:) (Comp1, unComp1)
#if MIN_VERSION_base(4, 9, 0)
, URec
( UAddr
, UChar
, UDouble
, UFloat
, UInt
, UWord
, uAddr#
, uChar#
, uDouble#
, uFloat#
, uInt#
, uWord#
)
, UAddr
, UChar
, UDouble
, UFloat
, UInt
, UWord
#endif
, Rec0
, R
, D1
, C1
, S1
, D
, C
, S
, Datatype (..)
, Constructor (..)
, Selector (..)
, Fixity (Prefix, Infix)
, FixityI (PrefixI, InfixI)
, PrefixI
, InfixI
, Associativity (LeftAssociative, RightAssociative, NotAssociative)
, LeftAssociative
, RightAssociative
, NotAssociative
, prec
, Meta (MetaData, MetaCons, MetaSel)
, MetaData
, MetaCons
, MetaSel
, DecidedStrictness (DecidedLazy, DecidedStrict, DecidedUnpack)
, DecidedLazy
, DecidedStrict
, DecidedUnpack
, SourceStrictness (NoSourceStrictness, SourceLazy, SourceStrict)
, NoSourceStrictness
, SourceLazy
, SourceStrict
, SourceUnpackedness (NoSourceUnpackedness, SourceNoUnpack, SourceUnpack)
, NoSourceUnpackedness
, SourceNoUnpack
, SourceUnpack
, Generic (type Rep, from, to)
, Generic1 (type Rep1, from1, to1)
)
where
-- base ----------------------------------------------------------------------
#if !MIN_VERSION_base(4, 9, 0)
import Data.Ix (Ix)
#endif
import GHC.Generics
#if MIN_VERSION_base(4, 8, 0)
import Numeric.Natural (Natural)
#endif
-- types ---------------------------------------------------------------------
#if defined(DataPolyKinds) && !MIN_VERSION_base(4, 9, 0)
import GHC.TypeLits.Compat (Nat, Symbol)
#endif
#if !MIN_VERSION_base(4, 9, 0)
import Type.Maybe (Just, Nothing)
#endif
import Type.Meta (Known, Val, val)
import Type.Meta.Proxy (Proxy (Proxy))
------------------------------------------------------------------------------
#if MIN_VERSION_base(4, 8, 0)
type NatVal = Natural
#else
type NatVal = Integer
#endif
#ifndef DataPolyKinds
------------------------------------------------------------------------------
type Nat = NatVal
type Symbol = String
#endif
#if !MIN_VERSION_base(4, 9, 0)
------------------------------------------------------------------------------
data FixityI = PrefixI | InfixI Associativity Nat
------------------------------------------------------------------------------
data Meta
= MetaData Symbol Symbol Symbol Bool
| MetaCons Symbol FixityI Bool
| MetaSel
(Maybe Symbol)
SourceUnpackedness
SourceStrictness
DecidedStrictness
------------------------------------------------------------------------------
data DecidedStrictness
= DecidedLazy
| DecidedStrict
| DecidedUnpack
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
------------------------------------------------------------------------------
data SourceStrictness
= NoSourceStrictness
| SourceStrict
| SourceLazy
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
------------------------------------------------------------------------------
data SourceUnpackedness
= NoSourceUnpackedness
| SourceNoUnpack
| SourceUnpack
deriving (Eq, Ord, Read, Show, Enum, Bounded, Ix, Generic)
#endif
------------------------------------------------------------------------------
#ifdef DataPolyKinds
type PrefixI = 'PrefixI
type InfixI = 'InfixI
type LeftAssociative = 'LeftAssociative
type RightAssociative = 'RightAssociative
type NotAssociative = 'NotAssociative
#if MIN_VERSION_base(4, 9, 0)
type MetaData = 'MetaData
type MetaCons = 'MetaCons
type MetaSel = 'MetaSel
#else
-- D1 etc will want a *-kinded type argument on GHC < 8; use Proxy to get this
type MetaData n m p nt = Proxy ('MetaData n m p nt)
type MetaCons n f s = Proxy ('MetaCons n f s)
type MetaSel mn su ss ds = Proxy ('MetaSel mn su ss ds)
#endif
type DecidedLazy = 'DecidedLazy
type DecidedStrict = 'DecidedStrict
type DecidedUnpack = 'DecidedUnpack
type NoSourceStrictness = 'NoSourceStrictness
type SourceLazy = 'SourceLazy
type SourceStrict = 'SourceStrict
type NoSourceUnpackedness = 'NoSourceUnpackedness
type SourceNoUnpack = 'SourceNoUnpack
type SourceUnpack = 'SourceUnpack
#else
data PrefixI
data InfixI a n
data LeftAssociative
data RightAssociative
data NotAssociative
data MetaData n m p nt
data MetaCons n f s
data MetaSel mn su ss ds
data DecidedLazy
data DecidedStrict
data DecidedUnpack
data NoSourceStrictness
data SourceLazy
data SourceStrict
data NoSourceUnpackedness
data SourceNoUnpack
data SourceUnpack
#endif
------------------------------------------------------------------------------
instance (Known PrefixI) where
type Val PrefixI = Fixity
val _ = Prefix
instance (Known a, Val a ~ Associativity, Known n, Val n ~ NatVal) =>
Known (InfixI a n)
where
type Val (InfixI a n) = Fixity
val _ =
Infix (val (Proxy :: Proxy a)) (fromIntegral (val (Proxy :: Proxy n)))
instance Known LeftAssociative where
type Val LeftAssociative = Associativity
val _ = LeftAssociative
instance Known RightAssociative where
type Val RightAssociative = Associativity
val _ = RightAssociative
instance Known NotAssociative where
type Val NotAssociative = Associativity
val _ = NotAssociative
instance Known DecidedLazy where
type Val DecidedLazy = DecidedStrictness
val _ = DecidedLazy
instance Known DecidedStrict where
type Val DecidedStrict = DecidedStrictness
val _ = DecidedStrict
instance Known DecidedUnpack where
type Val DecidedUnpack = DecidedStrictness
val _ = DecidedUnpack
instance Known NoSourceStrictness where
type Val NoSourceStrictness = SourceStrictness
val _ = NoSourceStrictness
instance Known SourceLazy where
type Val SourceLazy = SourceStrictness
val _ = SourceLazy
instance Known SourceStrict where
type Val SourceStrict = SourceStrictness
val _ = SourceStrict
instance Known NoSourceUnpackedness where
type Val NoSourceUnpackedness = SourceUnpackedness
val _ = NoSourceUnpackedness
instance Known SourceNoUnpack where
type Val SourceNoUnpack = SourceUnpackedness
val _ = SourceNoUnpack
instance Known SourceUnpack where
type Val SourceUnpack = SourceUnpackedness
val _ = SourceUnpack
#if !MIN_VERSION_base(4, 9, 0)
------------------------------------------------------------------------------
instance
( Known n, Val n ~ String, Known m, Val m ~ String, Known nt
, Val nt ~ Bool
)
=>
Datatype (MetaData n m p nt)
where
datatypeName _ = val (Proxy :: Proxy n)
moduleName _ = val (Proxy :: Proxy m)
#if MIN_VERSION_base(4, 7, 0)
isNewtype _ = val (Proxy :: Proxy nt)
#endif
------------------------------------------------------------------------------
instance
(Known n, Val n ~ String, Known f, Val f ~ Fixity, Known r, Val r ~ Bool)
=>
Constructor (MetaCons n f r)
where
conName _ = val (Proxy :: Proxy n)
conFixity _ = val (Proxy :: Proxy f)
conIsRecord _ = val (Proxy :: Proxy r)
------------------------------------------------------------------------------
instance (Known s, Val s ~ String) =>
Selector (MetaSel (Just s) su ss ds)
where
selName _ = val (Proxy :: Proxy s)
------------------------------------------------------------------------------
instance Selector (MetaSel Nothing su ss ds) where
selName _ = ""
#endif
| duairc/symbols | types/src/GHC/Generics/Compat.hs | bsd-3-clause | 8,221 | 13 | 11 | 1,673 | 1,611 | 973 | 638 | -1 | -1 |
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module GRIN.GrinCase where
import GRIN.GrinIdentifiers
import GRIN.GrinLiteral
import GRIN.GrinValue
import GRIN.GrinTag
import Data.Data
data GrinAlternative f expr where
Alternative :: {pat :: GrinConstantPattern f , expr :: expr } -> GrinAlternative f expr
deriving instance (Show expr, Show (f GrinIdentifier)) => Show (GrinAlternative f expr)
deriving instance Functor (GrinAlternative f )
deriving instance Foldable (GrinAlternative f )
deriving instance Traversable (GrinAlternative f )
deriving instance (Data expr, Typeable f, Data (f GrinIdentifier)) => Data (GrinAlternative f expr)
deriving instance Typeable (GrinAlternative)
data GrinConstantPattern f where
LiteralPattern :: GrinLiteral -> GrinConstantPattern f
TagPattern :: Tag -> GrinConstantPattern f
ConstantNodePattern :: Tag -> f GrinIdentifier -> GrinConstantPattern f
deriving (Typeable)
deriving instance (Data (f GrinIdentifier), Typeable f) => Data (GrinConstantPattern f)
deriving instance (Show (f GrinIdentifier)) => Show (GrinConstantPattern f)
| spacekitteh/libgrin | src/GRIN/GrinCase.hs | bsd-3-clause | 1,288 | 0 | 8 | 187 | 324 | 177 | 147 | -1 | -1 |
module Nut.Color.Spectrum.XYZ
( XYZ(..)
) where
import Control.Applicative
import Data.Foldable
import Data.Traversable
import Data.Monoid
import Nut.Numeric.Double
import Nut.Numeric.Float
data XYZ a = XYZ a a a deriving (Eq,Ord,Show,Read)
instance Functor XYZ where
fmap f (XYZ x y z) = XYZ (f x) (f y) (f z)
instance Applicative XYZ where
pure a = XYZ a a a
XYZ fx fy fz <*> XYZ x y z = XYZ (fx x) (fy y) (fz z)
instance Traversable XYZ where
traverse f (XYZ x y z) = XYZ <$> f x <*> f y <*> f z
instance Foldable XYZ where
foldMap f (XYZ x y z) = f x `mappend` f y `mappend` f z
instance Num a => Num (XYZ a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
(-) = liftA2 (-)
abs = fmap abs
signum = fmap signum
fromInteger = pure . fromInteger
instance Fractional a => Fractional (XYZ a) where
(/) = liftA2 (/)
recip = fmap recip
fromRational = pure . fromRational
instance Floating a => Floating (XYZ a) where
pi = pure pi
exp = fmap exp
sqrt = fmap sqrt
log = fmap log
(**) = liftA2 (**)
logBase = liftA2 logBase
sin = fmap sin
cos = fmap cos
tan = fmap tan
asin = fmap asin
acos = fmap acos
atan = fmap atan
sinh = fmap sinh
cosh = fmap cosh
tanh = fmap tanh
asinh = fmap asinh
acosh = fmap acosh
atanh = fmap atanh
instance FromFloat a => FromFloat (XYZ a) where
fromFloat = pure . fromFloat
instance FromDouble a => FromDouble (XYZ a) where
fromDouble = pure . fromDouble
| ekmett/colorimetry | Colorimetry/Spectrum/XYZ.hs | bsd-3-clause | 1,454 | 0 | 9 | 356 | 667 | 348 | 319 | 52 | 0 |
-----------------------------------------------------------------------
--
-- Haskell: The Craft of Functional Programming, 3e
-- Simon Thompson
-- (c) Addison-Wesley, 1996-2011.
--
-- Chapter 14, part 1
-- Also covers the properties in Section 14.7
--
-----------------------------------------------------------------------
module Craft.Chapter14_1 where
import Prelude hiding (Either(..),either,Maybe(..),maybe)
import Test.QuickCheck
import Control.Monad
-- Algebraic types
-- ^^^^^^^^^^^^^^^
-- Introducing algebraic types
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- We give a sequence of examples of increasing complexity ...
-- Enumerated types
-- ^^^^^^^^^^^^^^^^
-- Two enumerated types
data Temp = Cold | Hot
deriving (Show)
data Season = Spring | Summer | Autumn | Winter
deriving (Show,Eq,Enum)
-- A function over Season, defined using pattern matching.
weather :: Season -> Temp
weather Summer = Hot
weather _ = Cold
-- The Ordering type, as used in the class Ord.
-- data Ordering = LT | EQ | GT
-- Declaring Temp an instance of Eq.
instance Eq Temp where
Cold == Cold = True
Hot == Hot = True
_ == _ = False
-- Recursive algebraic types
-- ^^^^^^^^^^^^^^^^^^^^^^^^^
-- Expressions -- ^^^^^^^^^^^
-- Representing an integer expression.
data Expr = Lit Integer |
Add Expr Expr |
Sub Expr Expr |
If BExp Expr Expr
deriving (Show,Eq)
-- Three examples from Expr.
expr1 = Lit 2
expr2 = Add (Lit 2) (Lit 3)
expr3 = Add (Sub (Lit 3) (Lit 1)) (Lit 3)
-- Evaluating an expression.
eval :: Expr -> Integer
eval (Lit n) = n
eval (Add e1 e2) = (eval e1) + (eval e2)
eval (Sub e1 e2) = (eval e1) - (eval e2)
eval (If b e1 e2)
| bEval b = eval e1
| otherwise = eval e2
-- Showing an expression.
-- instance Show Expr where
--
-- show (Lit n) = show n
-- show (Add e1 e2)
-- = "(" ++ show e1 ++ "+" ++ show e2 ++ ")"
-- show (Sub e1 e2)
-- = "(" ++ show e1 ++ "-" ++ show e2 ++ ")"
-- Trees of integers
-- ^^^^^^^^^^^^^^^^^
-- The type definition.
data NTree = NilT |
Node Integer NTree NTree
deriving (Show,Eq,Read,Ord)
-- Example trees
treeEx1 = Node 10 NilT NilT
treeEx2 = Node 17 (Node 14 NilT NilT) (Node 20 NilT NilT)
-- Definitions of many functions are primitive recursive. For instance,
sumTree,depth :: NTree -> Integer
sumTree NilT = 0
sumTree (Node n t1 t2) = n + sumTree t1 + sumTree t2
depth NilT = 0
depth (Node n t1 t2) = 1 + max (depth t1) (depth t2)
-- How many times does an integer occur in a tree?
occurs :: NTree -> Integer -> Integer
occurs NilT p = 0
occurs (Node n t1 t2) p
| n==p = 1 + occurs t1 p + occurs t2 p
| otherwise = occurs t1 p + occurs t2 p
-- Rearranging expressions
-- ^^^^^^^^^^^^^^^^^^^^^^^
-- Right-associating additions in expressions.
assoc :: Expr -> Expr
assoc (Add (Add e1 e2) e3)
= assoc (Add e1 (Add e2 e3))
assoc (Add e1 e2)
= Add (assoc e1) (assoc e2)
assoc (Sub e1 e2)
= Sub (assoc e1) (assoc e2)
assoc (Lit n)
= Lit n
assoc' (e1 `Add` (e2 `Add` e3))
= assoc' (e1 `Add` e2 `Add` e3)
-- Infix constructors
-- ^^^^^^^^^^^^^^^^^^
-- An alternative definition of Expr.
data Expr' = Lit' Integer |
Expr' :+: Expr' |
Expr' :-: Expr'
-- Mutual Recursion
-- ^^^^^^^^^^^^^^^^
-- Mutually recursive types ...
data Person = Adult Name Address Biog |
Child Name
data Biog = Parent String [Person] |
NonParent String
type Name = String
type Address = [String]
-- ... and functions.
showPerson (Adult nm ad bio)
= show nm ++ show ad ++ showBiog bio
showBiog (Parent st perList)
= st ++ concat (map showPerson perList)
-- Alternative definition of Expr (as used later in the calculator case
-- study.
-- data Expr = Lit Int |
-- Op Ops Expr Expr
-- data Ops = Add | Sub | Mul | Div
-- It is possible to extend the type Expr so that it contains
-- conditional expressions, \texttt{If b e1 e2}.
-- data Expr = Lit Int |
-- Op Ops Expr Expr |
-- If BExp Expr Expr
-- Boolean expressions.
data BExp = BoolLit Bool |
And BExp BExp |
Not BExp |
Equal Expr Expr |
Greater Expr Expr
deriving (Show, Eq)
bEval :: BExp -> Bool
bEval (BoolLit a) = a
bEval (And a b) = and [bEval a, bEval b]
bEval (Not a) = not (bEval a)
bEval (Equal a b) = eval a == eval b
bEval (Greater a b) = eval a >= eval b
infixl 5 :::&
data L' a = N | a :::& L' a
-- QuickCheck for algebraic types
instance Arbitrary NTree where
arbitrary = sized arbNTree
arbNTree :: Int -> Gen NTree
arbNTree 0 = return NilT
arbNTree n
| n>0
= frequency[(1, return NilT),
(3, liftM3 Node arbitrary bush bush)]
where
bush = arbNTree (div n 2)
instance Arbitrary Expr where
arbitrary = sized arbExpr
arbExpr :: Int -> Gen Expr
arbExpr 0 = liftM Lit arbitrary
arbExpr n
| n>0
= frequency[(1, liftM Lit arbitrary),
(2, liftM2 Add bush bush),
(2, liftM2 Sub bush bush)]
where
bush = arbExpr (div n 2)
prop_assoc :: Expr -> Bool
prop_assoc expr =
eval expr == eval (assoc expr)
prop_depth :: NTree -> Bool
prop_depth t =
size t < 2^(depth t)
size :: NTree -> Integer
size NilT = 0
size (Node n t1 t2) = 1 + (size t1) + (depth t2)
| Numberartificial/workflow | snipets/src/Craft/Chapter14_1.hs | mit | 5,523 | 0 | 9 | 1,550 | 1,602 | 853 | 749 | 111 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module LambdaCms.Core.Classes
( PageHeadProperties (..)
) where
import LambdaCms.Core.Import
import Data.Text (intercalate)
type Follow = Bool
type Index = Bool
class PageHeadProperties res where
title :: res -> Text
author :: res -> Maybe Text
author _ = Nothing
editor :: res -> Maybe Text
editor _ = Nothing
description :: res -> Maybe Text
description _ = Nothing
keywords :: res -> [Text]
keywords _ = []
robots :: res -> Maybe (Index, Follow)
robots _ = Nothing
otherMetas :: res -> [[(Text, Text)]]
otherMetas _ = []
facebook :: res -> [(Text, Text)]
facebook _ = []
twitter :: res -> [(Text, Text)]
twitter _ = []
googlePlus :: res -> [(Text, Text)]
googlePlus _ = []
pageHeadTags :: LambdaCmsAdmin master => res -> WidgetT master IO ()
pageHeadTags res = toWidgetHead $(hamletFile "templates/pagehead.hamlet")
where
robotsText :: Maybe Text
robotsText = case robots res of
Just (index, follow) -> Just $ (if index then "Index" else "NoIndex")
<> ", "
<> (if follow then "Follow" else "NoFollow")
Nothing -> Nothing
| lambdacms/lambdacms | lambdacms-core/LambdaCms/Core/Classes.hs | mit | 1,358 | 0 | 16 | 446 | 407 | 224 | 183 | 36 | 0 |
{-# LANGUAGE LambdaCase #-}
module Cardano.Wallet.Kernel.Addresses (
createAddress
, newHdAddress
, importAddresses
-- * Errors
, CreateAddressError(..)
, ImportAddressError(..)
) where
import qualified Prelude
import Universum
import Control.Lens (to)
import Control.Monad.Except (throwError)
import Formatting (bprint, build, formatToString, (%))
import qualified Formatting as F
import qualified Formatting.Buildable
import System.Random.MWC (GenIO, createSystemRandom, uniformR)
import Data.Acid (update)
import Pos.Core (Address, IsBootstrapEraAddr (..), deriveLvl2KeyPair)
import Pos.Core.NetworkMagic (NetworkMagic, makeNetworkMagic)
import Pos.Crypto (EncryptedSecretKey, PassPhrase,
ShouldCheckPassphrase (..))
import Cardano.Wallet.Kernel.DB.AcidState (CreateHdAddress (..))
import Cardano.Wallet.Kernel.DB.HdWallet (HdAccountId,
HdAccountIx (..), HdAddress, HdAddressId (..),
HdAddressIx (..), HdRootId (..), IsOurs (..),
hdAccountIdIx, hdAccountIdParent, hdAddressIdIx)
import Cardano.Wallet.Kernel.DB.HdWallet.Create
(CreateHdAddressError (..), initHdAddress)
import Cardano.Wallet.Kernel.DB.HdWallet.Derivation
(HardeningMode (..), deriveIndex)
import Cardano.Wallet.Kernel.Internal (PassiveWallet, walletKeystore,
walletProtocolMagic, wallets)
import qualified Cardano.Wallet.Kernel.Keystore as Keystore
import Cardano.Wallet.Kernel.Types (AccountId (..), WalletId (..))
import Cardano.Wallet.WalletLayer.Kernel.Conv (toCardanoAddress)
import Test.QuickCheck (Arbitrary (..), oneof)
data CreateAddressError =
CreateAddressUnknownHdAccount HdAccountId
-- ^ When trying to create the 'Address', the parent 'Account' was not
-- there.
| CreateAddressKeystoreNotFound AccountId
-- ^ When trying to create the 'Address', the 'Keystore' didn't have
-- any secret associated with this 'Account'.
-- there.
| CreateAddressHdRndGenerationFailed HdAccountId
-- ^ The crypto-related part of address generation failed. This is
-- likely to happen if the 'PassPhrase' does not match the one used
-- to encrypt the 'EncryptedSecretKey'.
| CreateAddressHdRndAddressSpaceSaturated HdAccountId
-- ^ The available number of HD addresses in use in such that trying
-- to find another random index would be too expensive
deriving Eq
instance Arbitrary CreateAddressError where
arbitrary = oneof
[ CreateAddressUnknownHdAccount <$> arbitrary
, CreateAddressKeystoreNotFound . AccountIdHdRnd <$> arbitrary
, CreateAddressHdRndGenerationFailed <$> arbitrary
, CreateAddressHdRndAddressSpaceSaturated <$> arbitrary
]
instance Buildable CreateAddressError where
build (CreateAddressUnknownHdAccount uAccount) =
bprint ("CreateAddressUnknownHdAccount " % F.build) uAccount
build (CreateAddressKeystoreNotFound accId) =
bprint ("CreateAddressKeystoreNotFound " % F.build) accId
build (CreateAddressHdRndGenerationFailed hdAcc) =
bprint ("CreateAddressHdRndGenerationFailed " % F.build) hdAcc
build (CreateAddressHdRndAddressSpaceSaturated hdAcc) =
bprint ("CreateAddressHdRndAddressSpaceSaturated " % F.build) hdAcc
instance Show CreateAddressError where
show = formatToString build
-- | Creates a new 'Address' for the input account.
createAddress :: PassPhrase
-- ^ The 'Passphrase' (a.k.a the \"Spending Password\").
-> AccountId
-- ^ An abstract notion of an 'Account' identifier
-> PassiveWallet
-> IO (Either CreateAddressError Address)
createAddress spendingPassword accId pw = do
let nm = makeNetworkMagic (pw ^. walletProtocolMagic)
keystore = pw ^. walletKeystore
case accId of
-- \"Standard\" HD random derivation. The strategy is as follows:
--
-- 1. Generate the Address' @index@ and @HdAddress@ structure outside
-- of an atomic acid-state transaction. This could lead to data
-- races in the sense that an index is picked and such index
-- is already claimed, but if this happens we simply try again.
-- 2. Perform the actual creation of the 'HdAddress' as an atomic
-- transaction in acid-state.
--
-- The reason why we do this is because:
-- 1. We cannot do IO (thus index derivation) in an acid-state
-- transaction
-- 2. In order to create an 'HdAddress' we need a proper 'Address',
-- but this cannot be derived with having access to the
-- 'EncryptedSecretKey' and the 'PassPhrase', and we do not want
-- these exposed in the acid-state transaction log.
(AccountIdHdRnd hdAccId) -> do
mbEsk <- Keystore.lookup nm
(WalletIdHdRnd (hdAccId ^. hdAccountIdParent))
keystore
case mbEsk of
Nothing -> return (Left $ CreateAddressKeystoreNotFound accId)
Just esk -> createHdRndAddress spendingPassword esk hdAccId pw
-- | Creates a new 'Address' using the random HD derivation under the hood.
-- Being this an operation bound not only by the number of available derivation
-- indexes \"left\" in the account, some form of short-circuiting is necessary.
-- Currently, the algorithm is as follows:
--
-- 1. Try to generate an 'Address' by picking a random index;
-- 2. If the operation succeeds, return the 'Address';
-- 3. If the DB operation fails due to a collision, try again, up to a max of
-- 1024 attempts.
-- 4. If after 1024 attempts there is still no result, flag this upstream.
createHdRndAddress :: PassPhrase
-> EncryptedSecretKey
-> HdAccountId
-> PassiveWallet
-> IO (Either CreateAddressError Address)
createHdRndAddress spendingPassword esk accId pw = do
gen <- createSystemRandom
go gen 0
where
go :: GenIO -> Word32 -> IO (Either CreateAddressError Address)
go gen collisions =
case collisions >= maxAllowedCollisions of
True -> return $ Left (CreateAddressHdRndAddressSpaceSaturated accId)
False -> tryGenerateAddress gen collisions
tryGenerateAddress :: GenIO
-> Word32
-- ^ The current number of collisions
-> IO (Either CreateAddressError Address)
tryGenerateAddress gen collisions = do
newIndex <- deriveIndex (flip uniformR gen) HdAddressIx HardDerivation
let hdAddressId = HdAddressId accId newIndex
nm = makeNetworkMagic $ pw ^. walletProtocolMagic
mbAddr = newHdAddress nm esk spendingPassword accId hdAddressId
case mbAddr of
Nothing -> return (Left $ CreateAddressHdRndGenerationFailed accId)
Just hdAddress -> do
let db = pw ^. wallets
res <- update db (CreateHdAddress hdAddress)
case res of
(Left (CreateHdAddressExists _)) ->
go gen (succ collisions)
(Left (CreateHdAddressUnknown _)) ->
return (Left $ CreateAddressUnknownHdAccount accId)
Right () -> return (Right $ toCardanoAddress hdAddress)
-- The maximum number of allowed collisions.
maxAllowedCollisions :: Word32
maxAllowedCollisions = 1024
-- | Generates a new 'HdAddress' by performing the HD crypto derivation
-- underneath. Returns 'Nothing' if the cryptographic derivation fails.
newHdAddress :: NetworkMagic
-> EncryptedSecretKey
-> PassPhrase
-> HdAccountId
-> HdAddressId
-> Maybe HdAddress
newHdAddress nm esk spendingPassword accId hdAddressId =
let mbAddr = deriveLvl2KeyPair nm
(IsBootstrapEraAddr True)
(ShouldCheckPassphrase True)
spendingPassword
esk
(accId ^. hdAccountIdIx . to getHdAccountIx)
(hdAddressId ^. hdAddressIdIx . to getHdAddressIx)
in case mbAddr of
Nothing -> Nothing
Just (newAddress, _) -> Just $ initHdAddress hdAddressId newAddress
data ImportAddressError
= ImportAddressKeystoreNotFound HdRootId
-- ^ When trying to import the 'Address', the parent root was not there.
deriving Eq
instance Arbitrary ImportAddressError where
arbitrary = oneof
[ ImportAddressKeystoreNotFound <$> arbitrary
]
instance Buildable ImportAddressError where
build = \case
ImportAddressKeystoreNotFound rootId ->
bprint ("ImportAddressError" % F.build) rootId
instance Show ImportAddressError where
show = formatToString build
-- | Import already existing addresses into the DB. A typical use-case for that
-- is backend migration, where users (e.g. exchanges) want to import unused
-- addresses they've generated in the past (and likely communicated to their
-- users). Because Addresses in the old scheme are generated randomly, there's
-- no guarantee that addresses would be generated in the same order on a new
-- node (they better not actually!).
importAddresses
:: HdRootId
-> [Address]
-> PassiveWallet
-> IO (Either ImportAddressError [Either Address ()])
importAddresses rootId addrs pw = runExceptT $ do
esk <- lookupSecretKey rootId
lift $ forM addrs (flip importOneAddress [(rootId, esk)])
where
lookupSecretKey
:: HdRootId
-> ExceptT ImportAddressError IO EncryptedSecretKey
lookupSecretKey k = do
let nm = makeNetworkMagic (pw ^. walletProtocolMagic)
let keystore = pw ^. walletKeystore
lift (Keystore.lookup nm (WalletIdHdRnd k) keystore) >>= \case
Nothing -> throwError (ImportAddressKeystoreNotFound rootId)
Just esk -> return esk
importOneAddress
:: Address
-> [(HdRootId, EncryptedSecretKey)]
-> IO (Either Address ())
importOneAddress addr = evalStateT $ do
let updateLifted = fmap Just . lift . update (pw ^. wallets)
res <- state (isOurs addr) >>= \case
Nothing -> return Nothing
Just hdAddr -> updateLifted $ CreateHdAddress hdAddr
return $ case res of
Just (Right _) -> Right ()
_ -> Left addr
| input-output-hk/pos-haskell-prototype | wallet/src/Cardano/Wallet/Kernel/Addresses.hs | mit | 11,037 | 0 | 20 | 3,282 | 1,808 | 985 | 823 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudTrail.CreateTrail
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- From the command line, use 'create-subscription'.
--
-- Creates a trail that specifies the settings for delivery of log data to
-- an Amazon S3 bucket.
--
-- /See:/ <http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_CreateTrail.html AWS API Reference> for CreateTrail.
module Network.AWS.CloudTrail.CreateTrail
(
-- * Creating a Request
createTrail
, CreateTrail
-- * Request Lenses
, ctS3KeyPrefix
, ctSNSTopicName
, ctCloudWatchLogsLogGroupARN
, ctIncludeGlobalServiceEvents
, ctCloudWatchLogsRoleARN
, ctName
, ctS3BucketName
-- * Destructuring the Response
, createTrailResponse
, CreateTrailResponse
-- * Response Lenses
, ctrsS3KeyPrefix
, ctrsSNSTopicName
, ctrsCloudWatchLogsLogGroupARN
, ctrsName
, ctrsIncludeGlobalServiceEvents
, ctrsCloudWatchLogsRoleARN
, ctrsS3BucketName
, ctrsResponseStatus
) where
import Network.AWS.CloudTrail.Types
import Network.AWS.CloudTrail.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Specifies the settings for each trail.
--
-- /See:/ 'createTrail' smart constructor.
data CreateTrail = CreateTrail'
{ _ctS3KeyPrefix :: !(Maybe Text)
, _ctSNSTopicName :: !(Maybe Text)
, _ctCloudWatchLogsLogGroupARN :: !(Maybe Text)
, _ctIncludeGlobalServiceEvents :: !(Maybe Bool)
, _ctCloudWatchLogsRoleARN :: !(Maybe Text)
, _ctName :: !Text
, _ctS3BucketName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateTrail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctS3KeyPrefix'
--
-- * 'ctSNSTopicName'
--
-- * 'ctCloudWatchLogsLogGroupARN'
--
-- * 'ctIncludeGlobalServiceEvents'
--
-- * 'ctCloudWatchLogsRoleARN'
--
-- * 'ctName'
--
-- * 'ctS3BucketName'
createTrail
:: Text -- ^ 'ctName'
-> Text -- ^ 'ctS3BucketName'
-> CreateTrail
createTrail pName_ pS3BucketName_ =
CreateTrail'
{ _ctS3KeyPrefix = Nothing
, _ctSNSTopicName = Nothing
, _ctCloudWatchLogsLogGroupARN = Nothing
, _ctIncludeGlobalServiceEvents = Nothing
, _ctCloudWatchLogsRoleARN = Nothing
, _ctName = pName_
, _ctS3BucketName = pS3BucketName_
}
-- | Specifies the Amazon S3 key prefix that precedes the name of the bucket
-- you have designated for log file delivery.
ctS3KeyPrefix :: Lens' CreateTrail (Maybe Text)
ctS3KeyPrefix = lens _ctS3KeyPrefix (\ s a -> s{_ctS3KeyPrefix = a});
-- | Specifies the name of the Amazon SNS topic defined for notification of
-- log file delivery.
ctSNSTopicName :: Lens' CreateTrail (Maybe Text)
ctSNSTopicName = lens _ctSNSTopicName (\ s a -> s{_ctSNSTopicName = a});
-- | Specifies a log group name using an Amazon Resource Name (ARN), a unique
-- identifier that represents the log group to which CloudTrail logs will
-- be delivered. Not required unless you specify CloudWatchLogsRoleArn.
ctCloudWatchLogsLogGroupARN :: Lens' CreateTrail (Maybe Text)
ctCloudWatchLogsLogGroupARN = lens _ctCloudWatchLogsLogGroupARN (\ s a -> s{_ctCloudWatchLogsLogGroupARN = a});
-- | Specifies whether the trail is publishing events from global services
-- such as IAM to the log files.
ctIncludeGlobalServiceEvents :: Lens' CreateTrail (Maybe Bool)
ctIncludeGlobalServiceEvents = lens _ctIncludeGlobalServiceEvents (\ s a -> s{_ctIncludeGlobalServiceEvents = a});
-- | Specifies the role for the CloudWatch Logs endpoint to assume to write
-- to a user’s log group.
ctCloudWatchLogsRoleARN :: Lens' CreateTrail (Maybe Text)
ctCloudWatchLogsRoleARN = lens _ctCloudWatchLogsRoleARN (\ s a -> s{_ctCloudWatchLogsRoleARN = a});
-- | Specifies the name of the trail.
ctName :: Lens' CreateTrail Text
ctName = lens _ctName (\ s a -> s{_ctName = a});
-- | Specifies the name of the Amazon S3 bucket designated for publishing log
-- files.
ctS3BucketName :: Lens' CreateTrail Text
ctS3BucketName = lens _ctS3BucketName (\ s a -> s{_ctS3BucketName = a});
instance AWSRequest CreateTrail where
type Rs CreateTrail = CreateTrailResponse
request = postJSON cloudTrail
response
= receiveJSON
(\ s h x ->
CreateTrailResponse' <$>
(x .?> "S3KeyPrefix") <*> (x .?> "SnsTopicName") <*>
(x .?> "CloudWatchLogsLogGroupArn")
<*> (x .?> "Name")
<*> (x .?> "IncludeGlobalServiceEvents")
<*> (x .?> "CloudWatchLogsRoleArn")
<*> (x .?> "S3BucketName")
<*> (pure (fromEnum s)))
instance ToHeaders CreateTrail where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.CreateTrail"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON CreateTrail where
toJSON CreateTrail'{..}
= object
(catMaybes
[("S3KeyPrefix" .=) <$> _ctS3KeyPrefix,
("SnsTopicName" .=) <$> _ctSNSTopicName,
("CloudWatchLogsLogGroupArn" .=) <$>
_ctCloudWatchLogsLogGroupARN,
("IncludeGlobalServiceEvents" .=) <$>
_ctIncludeGlobalServiceEvents,
("CloudWatchLogsRoleArn" .=) <$>
_ctCloudWatchLogsRoleARN,
Just ("Name" .= _ctName),
Just ("S3BucketName" .= _ctS3BucketName)])
instance ToPath CreateTrail where
toPath = const "/"
instance ToQuery CreateTrail where
toQuery = const mempty
-- | Returns the objects or data listed below if successful. Otherwise,
-- returns an error.
--
-- /See:/ 'createTrailResponse' smart constructor.
data CreateTrailResponse = CreateTrailResponse'
{ _ctrsS3KeyPrefix :: !(Maybe Text)
, _ctrsSNSTopicName :: !(Maybe Text)
, _ctrsCloudWatchLogsLogGroupARN :: !(Maybe Text)
, _ctrsName :: !(Maybe Text)
, _ctrsIncludeGlobalServiceEvents :: !(Maybe Bool)
, _ctrsCloudWatchLogsRoleARN :: !(Maybe Text)
, _ctrsS3BucketName :: !(Maybe Text)
, _ctrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateTrailResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctrsS3KeyPrefix'
--
-- * 'ctrsSNSTopicName'
--
-- * 'ctrsCloudWatchLogsLogGroupARN'
--
-- * 'ctrsName'
--
-- * 'ctrsIncludeGlobalServiceEvents'
--
-- * 'ctrsCloudWatchLogsRoleARN'
--
-- * 'ctrsS3BucketName'
--
-- * 'ctrsResponseStatus'
createTrailResponse
:: Int -- ^ 'ctrsResponseStatus'
-> CreateTrailResponse
createTrailResponse pResponseStatus_ =
CreateTrailResponse'
{ _ctrsS3KeyPrefix = Nothing
, _ctrsSNSTopicName = Nothing
, _ctrsCloudWatchLogsLogGroupARN = Nothing
, _ctrsName = Nothing
, _ctrsIncludeGlobalServiceEvents = Nothing
, _ctrsCloudWatchLogsRoleARN = Nothing
, _ctrsS3BucketName = Nothing
, _ctrsResponseStatus = pResponseStatus_
}
-- | Specifies the Amazon S3 key prefix that precedes the name of the bucket
-- you have designated for log file delivery.
ctrsS3KeyPrefix :: Lens' CreateTrailResponse (Maybe Text)
ctrsS3KeyPrefix = lens _ctrsS3KeyPrefix (\ s a -> s{_ctrsS3KeyPrefix = a});
-- | Specifies the name of the Amazon SNS topic defined for notification of
-- log file delivery.
ctrsSNSTopicName :: Lens' CreateTrailResponse (Maybe Text)
ctrsSNSTopicName = lens _ctrsSNSTopicName (\ s a -> s{_ctrsSNSTopicName = a});
-- | Specifies the Amazon Resource Name (ARN) of the log group to which
-- CloudTrail logs will be delivered.
ctrsCloudWatchLogsLogGroupARN :: Lens' CreateTrailResponse (Maybe Text)
ctrsCloudWatchLogsLogGroupARN = lens _ctrsCloudWatchLogsLogGroupARN (\ s a -> s{_ctrsCloudWatchLogsLogGroupARN = a});
-- | Specifies the name of the trail.
ctrsName :: Lens' CreateTrailResponse (Maybe Text)
ctrsName = lens _ctrsName (\ s a -> s{_ctrsName = a});
-- | Specifies whether the trail is publishing events from global services
-- such as IAM to the log files.
ctrsIncludeGlobalServiceEvents :: Lens' CreateTrailResponse (Maybe Bool)
ctrsIncludeGlobalServiceEvents = lens _ctrsIncludeGlobalServiceEvents (\ s a -> s{_ctrsIncludeGlobalServiceEvents = a});
-- | Specifies the role for the CloudWatch Logs endpoint to assume to write
-- to a user’s log group.
ctrsCloudWatchLogsRoleARN :: Lens' CreateTrailResponse (Maybe Text)
ctrsCloudWatchLogsRoleARN = lens _ctrsCloudWatchLogsRoleARN (\ s a -> s{_ctrsCloudWatchLogsRoleARN = a});
-- | Specifies the name of the Amazon S3 bucket designated for publishing log
-- files.
ctrsS3BucketName :: Lens' CreateTrailResponse (Maybe Text)
ctrsS3BucketName = lens _ctrsS3BucketName (\ s a -> s{_ctrsS3BucketName = a});
-- | The response status code.
ctrsResponseStatus :: Lens' CreateTrailResponse Int
ctrsResponseStatus = lens _ctrsResponseStatus (\ s a -> s{_ctrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-cloudtrail/gen/Network/AWS/CloudTrail/CreateTrail.hs | mpl-2.0 | 10,093 | 0 | 18 | 2,272 | 1,571 | 933 | 638 | 180 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Main (main) where
import Test.Tasty
import Test.AWS.ElastiCache
import Test.AWS.ElastiCache.Internal
main :: IO ()
main = defaultMain $ testGroup "ElastiCache"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
| olorin/amazonka | amazonka-elasticache/test/Main.hs | mpl-2.0 | 546 | 0 | 8 | 103 | 76 | 47 | 29 | 9 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
-- | Primitive Feldspar expressions
module Feldspar.Primitive.Representation where
import Data.Array
import Data.Bits
import Data.Complex
import Data.Int
import Data.Typeable
import Data.Word
import Data.Constraint (Dict (..))
import Language.Embedded.Expression
import Language.Embedded.Imperative.CMD (IArr (..))
import Language.Syntactic
import Language.Syntactic.TH
import Language.Syntactic.Functional
--------------------------------------------------------------------------------
-- * Types
--------------------------------------------------------------------------------
type Length = Word32
type Index = Word32
-- | Representation of primitive supported types
data PrimTypeRep a
where
BoolT :: PrimTypeRep Bool
Int8T :: PrimTypeRep Int8
Int16T :: PrimTypeRep Int16
Int32T :: PrimTypeRep Int32
Int64T :: PrimTypeRep Int64
Word8T :: PrimTypeRep Word8
Word16T :: PrimTypeRep Word16
Word32T :: PrimTypeRep Word32
Word64T :: PrimTypeRep Word64
FloatT :: PrimTypeRep Float
DoubleT :: PrimTypeRep Double
ComplexFloatT :: PrimTypeRep (Complex Float)
ComplexDoubleT :: PrimTypeRep (Complex Double)
data IntTypeRep a
where
Int8Type :: IntTypeRep Int8
Int16Type :: IntTypeRep Int16
Int32Type :: IntTypeRep Int32
Int64Type :: IntTypeRep Int64
data WordTypeRep a
where
Word8Type :: WordTypeRep Word8
Word16Type :: WordTypeRep Word16
Word32Type :: WordTypeRep Word32
Word64Type :: WordTypeRep Word64
data IntWordTypeRep a
where
IntType :: IntTypeRep a -> IntWordTypeRep a
WordType :: WordTypeRep a -> IntWordTypeRep a
data FloatingTypeRep a
where
FloatType :: FloatingTypeRep Float
DoubleType :: FloatingTypeRep Double
data ComplexTypeRep a
where
ComplexFloatType :: ComplexTypeRep (Complex Float)
ComplexDoubleType :: ComplexTypeRep (Complex Double)
-- | A different view of 'PrimTypeRep' that allows matching on similar types
data PrimTypeView a
where
PrimTypeBool :: PrimTypeView Bool
PrimTypeIntWord :: IntWordTypeRep a -> PrimTypeView a
PrimTypeFloating :: FloatingTypeRep a -> PrimTypeView a
PrimTypeComplex :: ComplexTypeRep a -> PrimTypeView a
deriving instance Show (PrimTypeRep a)
deriving instance Show (IntTypeRep a)
deriving instance Show (WordTypeRep a)
deriving instance Show (IntWordTypeRep a)
deriving instance Show (FloatingTypeRep a)
deriving instance Show (ComplexTypeRep a)
deriving instance Show (PrimTypeView a)
viewPrimTypeRep :: PrimTypeRep a -> PrimTypeView a
viewPrimTypeRep BoolT = PrimTypeBool
viewPrimTypeRep Int8T = PrimTypeIntWord $ IntType $ Int8Type
viewPrimTypeRep Int16T = PrimTypeIntWord $ IntType $ Int16Type
viewPrimTypeRep Int32T = PrimTypeIntWord $ IntType $ Int32Type
viewPrimTypeRep Int64T = PrimTypeIntWord $ IntType $ Int64Type
viewPrimTypeRep Word8T = PrimTypeIntWord $ WordType $ Word8Type
viewPrimTypeRep Word16T = PrimTypeIntWord $ WordType $ Word16Type
viewPrimTypeRep Word32T = PrimTypeIntWord $ WordType $ Word32Type
viewPrimTypeRep Word64T = PrimTypeIntWord $ WordType $ Word64Type
viewPrimTypeRep FloatT = PrimTypeFloating FloatType
viewPrimTypeRep DoubleT = PrimTypeFloating DoubleType
viewPrimTypeRep ComplexFloatT = PrimTypeComplex ComplexFloatType
viewPrimTypeRep ComplexDoubleT = PrimTypeComplex ComplexDoubleType
unviewPrimTypeRep :: PrimTypeView a -> PrimTypeRep a
unviewPrimTypeRep PrimTypeBool = BoolT
unviewPrimTypeRep (PrimTypeIntWord (IntType Int8Type)) = Int8T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int16Type)) = Int16T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int32Type)) = Int32T
unviewPrimTypeRep (PrimTypeIntWord (IntType Int64Type)) = Int64T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word8Type)) = Word8T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word16Type)) = Word16T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word32Type)) = Word32T
unviewPrimTypeRep (PrimTypeIntWord (WordType Word64Type)) = Word64T
unviewPrimTypeRep (PrimTypeFloating FloatType) = FloatT
unviewPrimTypeRep (PrimTypeFloating DoubleType) = DoubleT
unviewPrimTypeRep (PrimTypeComplex ComplexFloatType) = ComplexFloatT
unviewPrimTypeRep (PrimTypeComplex ComplexDoubleType) = ComplexDoubleT
primTypeIntWidth :: PrimTypeRep a -> Maybe Int
primTypeIntWidth Int8T = Just 8
primTypeIntWidth Int16T = Just 16
primTypeIntWidth Int32T = Just 32
primTypeIntWidth Int64T = Just 64
primTypeIntWidth Word8T = Just 8
primTypeIntWidth Word16T = Just 16
primTypeIntWidth Word32T = Just 32
primTypeIntWidth Word64T = Just 64
primTypeIntWidth _ = Nothing
-- | Primitive supported types
class (Eq a, Show a, Typeable a) => PrimType' a
where
-- | Reify a primitive type
primTypeRep :: PrimTypeRep a
instance PrimType' Bool where primTypeRep = BoolT
instance PrimType' Int8 where primTypeRep = Int8T
instance PrimType' Int16 where primTypeRep = Int16T
instance PrimType' Int32 where primTypeRep = Int32T
instance PrimType' Int64 where primTypeRep = Int64T
instance PrimType' Word8 where primTypeRep = Word8T
instance PrimType' Word16 where primTypeRep = Word16T
instance PrimType' Word32 where primTypeRep = Word32T
instance PrimType' Word64 where primTypeRep = Word64T
instance PrimType' Float where primTypeRep = FloatT
instance PrimType' Double where primTypeRep = DoubleT
instance PrimType' (Complex Float) where primTypeRep = ComplexFloatT
instance PrimType' (Complex Double) where primTypeRep = ComplexDoubleT
-- | Convenience function; like 'primTypeRep' but with an extra argument to
-- constrain the type parameter. The extra argument is ignored.
primTypeOf :: PrimType' a => a -> PrimTypeRep a
primTypeOf _ = primTypeRep
-- | Check whether two type representations are equal
primTypeEq :: PrimTypeRep a -> PrimTypeRep b -> Maybe (Dict (a ~ b))
primTypeEq BoolT BoolT = Just Dict
primTypeEq Int8T Int8T = Just Dict
primTypeEq Int16T Int16T = Just Dict
primTypeEq Int32T Int32T = Just Dict
primTypeEq Int64T Int64T = Just Dict
primTypeEq Word8T Word8T = Just Dict
primTypeEq Word16T Word16T = Just Dict
primTypeEq Word32T Word32T = Just Dict
primTypeEq Word64T Word64T = Just Dict
primTypeEq FloatT FloatT = Just Dict
primTypeEq DoubleT DoubleT = Just Dict
primTypeEq ComplexFloatT ComplexFloatT = Just Dict
primTypeEq ComplexDoubleT ComplexDoubleT = Just Dict
primTypeEq _ _ = Nothing
-- | Reflect a 'PrimTypeRep' to a 'PrimType'' constraint
witPrimType :: PrimTypeRep a -> Dict (PrimType' a)
witPrimType BoolT = Dict
witPrimType Int8T = Dict
witPrimType Int16T = Dict
witPrimType Int32T = Dict
witPrimType Int64T = Dict
witPrimType Word8T = Dict
witPrimType Word16T = Dict
witPrimType Word32T = Dict
witPrimType Word64T = Dict
witPrimType FloatT = Dict
witPrimType DoubleT = Dict
witPrimType ComplexFloatT = Dict
witPrimType ComplexDoubleT = Dict
--------------------------------------------------------------------------------
-- * Expressions
--------------------------------------------------------------------------------
-- | Primitive operations
data Primitive sig
where
FreeVar :: PrimType' a => String -> Primitive (Full a)
Lit :: (Eq a, Show a) => a -> Primitive (Full a)
Add :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Sub :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Mul :: (Num a, PrimType' a) => Primitive (a :-> a :-> Full a)
Neg :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Abs :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Sign :: (Num a, PrimType' a) => Primitive (a :-> Full a)
Quot :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Rem :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Div :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
Mod :: (Integral a, PrimType' a) => Primitive (a :-> a :-> Full a)
FDiv :: (Fractional a, PrimType' a) => Primitive (a :-> a :-> Full a)
Pi :: (Floating a, PrimType' a) => Primitive (Full a)
Exp :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Log :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Sqrt :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Pow :: (Floating a, PrimType' a) => Primitive (a :-> a :-> Full a)
Sin :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Cos :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Tan :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Asin :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Acos :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Atan :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Sinh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Cosh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Tanh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Asinh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Acosh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Atanh :: (Floating a, PrimType' a) => Primitive (a :-> Full a)
Complex :: (Num a, PrimType' a, PrimType' (Complex a)) => Primitive (a :-> a :-> Full (Complex a))
Polar :: (Floating a, PrimType' a, PrimType' (Complex a)) => Primitive (a :-> a :-> Full (Complex a))
Real :: (PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Imag :: (PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Magnitude :: (RealFloat a, PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Phase :: (RealFloat a, PrimType' a, PrimType' (Complex a)) => Primitive (Complex a :-> Full a)
Conjugate :: (Num a, PrimType' (Complex a)) => Primitive (Complex a :-> Full (Complex a))
I2N :: (Integral a, Num b, PrimType' a, PrimType' b) => Primitive (a :-> Full b)
I2B :: (Integral a, PrimType' a) => Primitive (a :-> Full Bool)
B2I :: (Integral a, PrimType' a) => Primitive (Bool :-> Full a)
Round :: (RealFrac a, Num b, PrimType' a, PrimType' b) => Primitive (a :-> Full b)
Not :: Primitive (Bool :-> Full Bool)
And :: Primitive (Bool :-> Bool :-> Full Bool)
Or :: Primitive (Bool :-> Bool :-> Full Bool)
Eq :: (Eq a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
NEq :: (Eq a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Lt :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Gt :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Le :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
Ge :: (Ord a, PrimType' a) => Primitive (a :-> a :-> Full Bool)
BitAnd :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitOr :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitXor :: (Bits a, PrimType' a) => Primitive (a :-> a :-> Full a)
BitCompl :: (Bits a, PrimType' a) => Primitive (a :-> Full a)
ShiftL :: (Bits a, PrimType' a, Integral b, PrimType' b) => Primitive (a :-> b :-> Full a)
ShiftR :: (Bits a, PrimType' a, Integral b, PrimType' b) => Primitive (a :-> b :-> Full a)
ArrIx :: PrimType' a => IArr Index a -> Primitive (Index :-> Full a)
Cond :: Primitive (Bool :-> a :-> a :-> Full a)
deriving instance Show (Primitive a)
-- The `PrimType'` constraints on certain symbols require an explanation: The
-- constraints are actually not needed for anything in the modules in
-- `Feldspar.Primitive.*`, but they are needed by `Feldspar.Run.Compile`. They
-- guarantee to the compiler that these symbols don't operate on tuples.
--
-- It would seem more consistent to have a `PrimType'` constraint on all
-- polymorphic symbols. However, this would prevent using some symbols for
-- non-primitive types in `Feldspar.Representation`. For example, `Lit` and
-- `Cond` are used `Feldspar.Representation`, and there they can also be used
-- for tuple types. The current design was chosen because it "just works".
deriveSymbol ''Primitive
instance Render Primitive
where
renderSym (FreeVar v) = v
renderSym (Lit a) = show a
renderSym (ArrIx (IArrComp arr)) = "ArrIx " ++ arr
renderSym (ArrIx _) = "ArrIx ..."
renderSym s = show s
renderArgs = renderArgsSmart
instance StringTree Primitive
instance Eval Primitive
where
evalSym (FreeVar v) = error $ "evaluating free variable " ++ show v
evalSym (Lit a) = a
evalSym Add = (+)
evalSym Sub = (-)
evalSym Mul = (*)
evalSym Neg = negate
evalSym Abs = abs
evalSym Sign = signum
evalSym Quot = quot
evalSym Rem = rem
evalSym Div = div
evalSym Mod = mod
evalSym FDiv = (/)
evalSym Pi = pi
evalSym Exp = exp
evalSym Log = log
evalSym Sqrt = sqrt
evalSym Pow = (**)
evalSym Sin = sin
evalSym Cos = cos
evalSym Tan = tan
evalSym Asin = asin
evalSym Acos = acos
evalSym Atan = atan
evalSym Sinh = sinh
evalSym Cosh = cosh
evalSym Tanh = tanh
evalSym Asinh = asinh
evalSym Acosh = acosh
evalSym Atanh = atanh
evalSym Complex = (:+)
evalSym Polar = mkPolar
evalSym Real = realPart
evalSym Imag = imagPart
evalSym Magnitude = magnitude
evalSym Phase = phase
evalSym Conjugate = conjugate
evalSym I2N = fromInteger . toInteger
evalSym I2B = (/=0)
evalSym B2I = \a -> if a then 1 else 0
evalSym Round = fromInteger . round
evalSym Not = not
evalSym And = (&&)
evalSym Or = (||)
evalSym Eq = (==)
evalSym NEq = (/=)
evalSym Lt = (<)
evalSym Gt = (>)
evalSym Le = (<=)
evalSym Ge = (>=)
evalSym BitAnd = (.&.)
evalSym BitOr = (.|.)
evalSym BitXor = xor
evalSym BitCompl = complement
evalSym ShiftL = \a -> shiftL a . fromIntegral
evalSym ShiftR = \a -> shiftR a . fromIntegral
evalSym Cond = \c t f -> if c then t else f
evalSym (ArrIx (IArrRun arr)) = \i ->
if i<l || i>h
then error $ "ArrIx: index "
++ show (toInteger i)
++ " out of bounds "
++ show (toInteger l, toInteger h)
else arr!i
where
(l,h) = bounds arr
evalSym (ArrIx (IArrComp arr)) = error $ "evaluating symbolic array " ++ arr
-- | Assumes no occurrences of 'FreeVar' and concrete representation of arrays
instance EvalEnv Primitive env
instance Equality Primitive
where
equal s1 s2 = show s1 == show s2
-- NOTE: It is very important not to use `renderSym` here, because it will
-- render all concrete arrays equal.
-- This method uses string comparison. It is probably slightly more
-- efficient to pattern match directly on the constructors. Unfortunately
-- `deriveEquality ''Primitive` doesn't work, so it gets quite tedious to
-- write it with pattern matching.
type PrimDomain = Primitive :&: PrimTypeRep
-- | Primitive expressions
newtype Prim a = Prim { unPrim :: ASTF PrimDomain a }
instance Syntactic (Prim a)
where
type Domain (Prim a) = PrimDomain
type Internal (Prim a) = a
desugar = unPrim
sugar = Prim
-- | Evaluate a closed expression
evalPrim :: Prim a -> a
evalPrim = go . unPrim
where
go :: AST PrimDomain sig -> Denotation sig
go (Sym (s :&: _)) = evalSym s
go (f :$ a) = go f $ go a
sugarSymPrim
:: ( Signature sig
, fi ~ SmartFun dom sig
, sig ~ SmartSig fi
, dom ~ SmartSym fi
, dom ~ PrimDomain
, SyntacticN f fi
, sub :<: Primitive
, PrimType' (DenResult sig)
)
=> sub sig -> f
sugarSymPrim = sugarSymDecor primTypeRep
instance FreeExp Prim
where
type FreePred Prim = PrimType'
constExp = sugarSymPrim . Lit
varExp = sugarSymPrim . FreeVar
instance EvalExp Prim
where
evalExp = evalPrim
--------------------------------------------------------------------------------
-- * Interface
--------------------------------------------------------------------------------
instance (Num a, PrimType' a) => Num (Prim a)
where
fromInteger = constExp . fromInteger
(+) = sugarSymPrim Add
(-) = sugarSymPrim Sub
(*) = sugarSymPrim Mul
negate = sugarSymPrim Neg
abs = sugarSymPrim Abs
signum = sugarSymPrim Sign
| kmate/raw-feldspar | src/Feldspar/Primitive/Representation.hs | bsd-3-clause | 17,478 | 0 | 13 | 4,680 | 5,101 | 2,635 | 2,466 | -1 | -1 |
-- A simple let statement, to ensure the layout is detected
module Layout.LetStmt where
foo = do
{- ffo -}let x = 1
y = 2 -- baz
x+y
| mpickering/ghc-exactprint | tests/examples/ghc710/LetStmt.hs | bsd-3-clause | 158 | 0 | 9 | 54 | 35 | 20 | 15 | 5 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{- |
Module : Verifier.SAW.Change
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.Change
( ChangeMonad(..)
, Change(..)
, ChangeT(..)
, change
, changeList
, commitChange
, commitChangeT
, preserveChangeT
, flatten
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad (liftM, liftM2)
import Control.Monad.Trans
----------------------------------------------------------------------
-- Monads for tracking whether values have changed
class (Monad m, Applicative m) => ChangeMonad m where
preserve :: a -> m a -> m a
taint :: m a -> m a
taint m = m >>= modified
modified :: a -> m a
modified x = taint (pure x)
-- Laws (not a minimal set):
-- taint (taint m) = taint m
-- taint (pure x) = modified x
-- fmap f (taint m) = taint (fmap f m)
-- taint m1 <*> m2 = taint (m1 <*> m2)
-- m1 <*> taint m2 = taint (m1 <*> m2)
-- fmap f (modified x) = modified (f x)
-- modified x >>= k = taint (k x)
-- m >>= modified = taint m
-- taint (modified x) = modified x
-- taint (return x) = modified x
-- taint (m >>= k) = taint m >>= k
-- taint (m >>= k) = m >>= (taint . k)
-- preserve x (pure _) = pure x
-- preserve _ (modified y) = modified y
-- preserve _ (taint m) = taint m
change :: ChangeMonad m => (a -> Maybe a) -> a -> m a
change f a =
case f a of
Nothing -> pure a
Just x -> modified x
changeList :: ChangeMonad m => (a -> m a) -> [a] -> m [a]
changeList f xs =
preserve xs $
case xs of
[] -> pure []
y : ys -> (:) <$> f y <*> changeList f ys
----------------------------------------------------------------------
-- Change monad
data Change a = Original a | Modified a
deriving (Show, Functor)
instance Applicative Change where
pure x = Original x
Original f <*> Original x = Original (f x)
Original f <*> Modified x = Modified (f x)
Modified f <*> Original x = Modified (f x)
Modified f <*> Modified x = Modified (f x)
instance Monad Change where
return x = Original x
Original x >>= k = k x
Modified x >>= k = taint (k x)
instance ChangeMonad Change where
preserve x (Original _) = Original x
preserve _ c@(Modified _) = c
taint (Original x) = Modified x
taint c@(Modified _) = c
modified x = Modified x
commitChange :: Change a -> a
commitChange (Original x) = x
commitChange (Modified x) = x
-- ^ Satisfies the following laws:
-- @commitChange (fmap f m) = f (commitChange m)@
-- @commitChange (taint m) = commitChange m@
-- @commitChange (m >>= k) = commitChange (k (commitChange m))@
----------------------------------------------------------------------
-- Change monad transformer
newtype ChangeT m a = ChangeT { runChangeT :: m (Change a) }
instance Monad m => Functor (ChangeT m) where
fmap f (ChangeT m) = ChangeT (liftM (fmap f) m)
instance Monad m => Applicative (ChangeT m) where
pure x = ChangeT (return (Original x))
ChangeT m1 <*> ChangeT m2 = ChangeT (liftM2 (<*>) m1 m2)
instance Monad m => Monad (ChangeT m) where
return x = ChangeT (return (Original x))
ChangeT m >>= k = ChangeT (m >>= f)
where f (Original x) = runChangeT (k x)
f (Modified x) = runChangeT (k x) >>= (return . taint)
instance MonadTrans ChangeT where
lift m = ChangeT (liftM Original m)
instance MonadIO m => MonadIO (ChangeT m) where
liftIO m = lift (liftIO m)
instance Monad m => ChangeMonad (ChangeT m) where
preserve x (ChangeT m) = ChangeT (liftM (preserve x) m)
taint (ChangeT m) = ChangeT (liftM taint m)
modified x = ChangeT (return (modified x))
commitChangeT :: Monad m => ChangeT m a -> m a
commitChangeT (ChangeT m) = liftM commitChange m
-- ^ Is a natural transformation from @ChangeT m@ to @m@:
-- @commitChangeT (fmap f m) = fmap f (commitChangeT m)@
-- @commitChangeT (lift m) = m@
-- @commitChangeT (m >>= k) = commitChangeT m >>= (commitChangeT . k)@
-- @commitChangeT (return x) = return x@
-- @commitChangeT (taint m) = commitChangeT m@
preserveChangeT :: Monad m => a -> ChangeT m (m a) -> ChangeT m a
preserveChangeT x (ChangeT c) = ChangeT (c >>= k)
where k (Original _) = return (Original x)
k (Modified m) = liftM Modified m
-- ^ Satisfies @preserveChangeT x (return _) = return x@ and
-- @preserveChangeT _ (modified m) = taint (lift m)@.
flatten :: Monad m => (a -> ChangeT m (m a)) -> a -> ChangeT m a
flatten f x = ChangeT (runChangeT (f x) >>= k)
where k (Original _) = return (Original x)
k (Modified m) = liftM Modified m
-- ^ @flatten f x = preserveChangeT x (f x)@
| GaloisInc/saw-script | saw-core/src/Verifier/SAW/Change.hs | bsd-3-clause | 4,832 | 0 | 11 | 1,057 | 1,438 | 726 | 712 | 85 | 2 |
{-# LANGUAGE CPP #-}
module Test(main) where
import Development.Shake.Command
import System.Directory.Extra
import System.IO.Extra
import System.Time.Extra
import System.Environment.Extra
import System.FilePath
import Control.Monad.Extra
import Control.Exception.Extra
import Control.Concurrent
import System.Process
import Data.List.Extra
import Data.IORef
import Data.Char
import Control.Applicative
import qualified Example
import Prelude
import Development.Bake.Test.Simulate
main :: IO ()
main = do
args <- getArgs
if args /= [] then Example.main else do
simulate
dir <- getCurrentDirectory
test $ dir ++ "/.bake-test"
test :: FilePath -> IO ()
test dir = do
let repo = "file:///" ++ dropWhile (== '/') (replace "\\" "/" dir) ++ "/repo"
b <- doesDirectoryExist dir
when b $ do
unit $ cmd "chmod -R 755 .bake-test"
unit $ cmd "rm -rf .bake-test"
return ()
#if __GLASGOW_HASKELL__ >= 708
setEnv "http_proxy" ""
#endif
createDirectoryIfMissing True (dir </> "repo")
withCurrentDirectory (dir </> "repo") $ do
unit $ cmd "git init"
unit $ cmd "git config user.email" ["[email protected]"]
unit $ cmd "git config user.name" ["Ms Gwen"]
writeFile "Main.hs" "module Main where\n\n-- Entry point\nmain = print 1\n"
unit $ cmd "git add Main.hs"
unit $ cmd "git commit -m" ["Initial version"]
unit $ cmd "git checkout -b none" -- so I can git push to master
forM_ ["bob","tony"] $ \s -> do
createDirectoryIfMissing True (dir </> "repo-" ++ s)
withCurrentDirectory (dir </> "repo-" ++ s) $ do
print "clone"
unit $ cmd "git clone" repo "."
unit $ cmd "git config user.email" [s ++ "@example.com"]
unit $ cmd "git config user.name" ["Mr " ++ toUpper (head s) : map toLower (tail s)]
unit $ cmd "git checkout -b" s
aborting <- newIORef False
let createProcessAlive p = do
t <- myThreadId
(_,_,_,pid) <- createProcess p
forkIO $ do
waitForProcess pid
b <- readIORef aborting
when (not b) $ throwTo t $ ErrorCall "Process died"
sleep 2
return pid
exe <- getExecutablePath
createDirectoryIfMissing True $ dir </> "server"
curdir <- getCurrentDirectory
environment <- (\env -> ("REPO",repo):("bake_datadir",curdir):env) <$> getEnvironment
p0 <- createProcessAlive (proc exe ["server","--author=admin"])
{cwd=Just $ dir </> "server", env=Just environment}
sleep 5
ps <- forM (zip [1..] Example.platforms) $ \(i,p) -> do
sleep 0.5 -- so they don't ping at the same time
createDirectoryIfMissing True $ dir </> "client-" ++ show p
createProcessAlive (proc exe $
["client","--ping=1","--name=" ++ show p,"--threads=" ++ show i,"--provide=" ++ show p])
{cwd=Just $ dir </> "client-" ++ show p,env=Just environment}
flip finally (do writeIORef aborting True; mapM_ terminateProcess $ p0 : ps) $ do
let edit name act = withCurrentDirectory (dir </> "repo-" ++ name) $ do
act
unit $ cmd "git add *"
unit $ cmd "git commit -m" ["Update from " ++ name]
unit $ cmd "git push origin" name
Stdout sha1 <- cmd "git rev-parse HEAD"
unit $ cmd exe "addpatch" ("--name=" ++ name ++ "=" ++ sha1) ("--author=" ++ name)
putStrLn "% MAKING EDIT AS BOB"
edit "bob" $
writeFile "Main.hs" "module Main(main) where\n\n-- Entry point\nmain = print 1\n"
sleep 2
putStrLn "% MAKING EDIT AS TONY"
edit "tony" $
writeFile "Main.hs" "module Main where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
retry 10 $ do
sleep 10
withTempDir $ \d -> withCurrentDirectory d $ do
unit $ cmd "git clone" repo "."
unit $ cmd "git checkout master"
src <- readFile "Main.hs"
let expect = "module Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
when (src /= expect) $ do
error $ "Expected to have updated Main, but got:\n" ++ src
unit $ cmd exe "pause"
putStrLn "% MAKING A GOOD EDIT AS BOB"
edit "bob" $ do
unit $ cmd "git fetch origin"
unit $ cmd "git merge origin/master"
writeFile "Main.hs" "module Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n\n"
putStrLn "% MAKING A BAD EDIT AS BOB"
edit "bob" $
writeFile "Main.hs" "module Main(main) where\nimport System.Environment\n-- Entry point\nmain :: IO ()\nmain = do [[_]] <- getArgs; print 1\n\n"
putStrLn "% MAKING A GOOD EDIT AS TONY"
edit "tony" $ do
unit $ cmd "git fetch origin"
unit $ cmd "git merge origin/master"
writeFile "Main.hs" "-- Tony waz ere\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
putStrLn "% MAKING A MERGE CONFLICT AS BOB"
edit "bob" $
writeFile "Main.hs" "-- Bob waz ere\nmodule Main(main) where\nimport System.Environment\n-- Entry point\nmain :: IO ()\nmain = do [[_]] <- getArgs; print 1\n\n"
putStrLn "% MAKING ANOTHER GOOD EDIT AS TONY"
edit "tony" $ do
writeFile "Main.hs" "-- Tony waz ere 1981\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n"
unit $ cmd exe "unpause"
retry 15 $ do
sleep 10
withTempDir $ \d -> withCurrentDirectory d $ do
unit $ cmd "git clone" repo "."
unit $ cmd "git checkout master"
src <- readFile "Main.hs"
let expect = "-- Tony waz ere 1981\nmodule Main(main) where\n\n-- Entry point\nmain :: IO ()\nmain = print 1\n\n"
when (src /= expect) $ do
error $ "Expected to have updated Main, but got:\n" ++ src
putStrLn "Completed successfully!"
-- putStrLn "Waiting (time to view webpage)..." >> sleep 120
| Pitometsu/bake | src/Test.hs | bsd-3-clause | 6,242 | 0 | 22 | 1,904 | 1,545 | 716 | 829 | 129 | 2 |
module PCP.Solutions where
import PCP.Type
sol_001 =
( [ 1 % 1, 2 % 1, 1 % 1 ]
, [ [ 0, 0 ]
, [ 1, 1, 2, 0 ]
, [ 2, 2, 0, 1, 2, 0 ]
, [ 2, 0, 0, 1, 0, 1, 2, 0 ]
, [ 2, 0, 0, 2, 2, 0, 0, 1, 2, 0 ]
]
, [ [ 0, 2, 2, 0, 0, 1, 2, 0, 1, 2 ]
, [ 0, 2, 2, 2, 2, 0, 1, 2 ]
, [ 0, 2, 2, 1, 1, 2 ]
, [ 0, 2, 2, 0 ]
, [ 0, 1 ]
]
)
sol_0001 =
( [ 3 % 1, 2 % 1, 1 % 1 ]
, [ [ 0, 0, 0 ]
, [ 1, 1, 1, 2, 0, 0 ]
, [ 2, 2, 2, 0, 1, 1, 2, 0, 0 ]
, [ 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 0, 0 ]
, [ 2, 2, 2, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 0, 0 ]
, [ 2, 0, 0, 0, 1, 2, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 0, 0 ]
, [ 2, 0, 0, 1, 1, 1, 2, 1, 2, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 0, 0 ]
]
, [ [ 0, 2, 2, 2, 1, 1, 1, 2, 2, 2, 0, 1, 1, 2, 0, 0, 1, 1, 1, 2, 1 ]
, [ 0, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 0, 0, 1, 1, 1, 2, 1 ]
, [ 0, 2, 2, 2, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 1 ]
, [ 0, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 1 ]
, [ 0, 2, 2, 2, 0, 1, 1, 2, 1 ]
, [ 0, 1, 1, 1, 2, 1 ]
, [ 0, 0, 1 ]
]
)
sol_00001 =
( [ 3 % 1, 2 % 1, 1 % 1 ]
, [ [ 0, 0, 0, 0 ]
, [ 1, 1, 1, 1, 2, 0, 0, 0 ]
, [ 2, 2, 2, 2, 0, 1, 1, 1, 2, 0, 0, 0 ]
, [ 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0 ]
, [ 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0 ]
, [ 2, 0, 0, 0, 0, 1, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0 ]
, [ 2, 0, 0, 0, 1, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 0, 0, 0 ]
]
, [ [ 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 0, 1, 1, 1, 2, 0, 0, 0, 1, 1, 1, 1, 2, 1 ]
, [ 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 1, 1, 1, 1, 2, 1 ]
, [ 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 1 ]
, [ 0, 0, 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1 ]
, [ 0, 0, 2, 2, 2, 2, 0, 1, 1, 1, 2, 1 ]
, [ 0, 0, 1, 1, 1, 1, 2, 1 ]
, [ 0, 0, 0, 1 ]
]
)
sol_01011 =
( [ 2 % 1, 2 % 1, 2 % 1 ]
, [ [ 0, 1, 0, 1 ] -- 0
, [ 1, 2, 1, 2, 2, 1, 0, 1 ] -- 0
, [ 2, 0, 2, 0, 0, 2, 1, 2, 2, 1, 0, 1 ] -- 1
, [ 2, 1, 2, 1, 2, 2, 2, 0, 0, 2, 1, 2, 2, 1, 0, 1 ] -- 5
, [ 2, 1, 2, 1, 2, 0, 1, 0, 1, 1, 2, 0, 0, 2, 1, 2, 2, 1, 0, 1 ] -- 9
, [ 2, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0, 2, 0, 0, 2, 0, 0, 2, 1, 2, 2, 1, 0, 1 ] -- 12
, [ 2, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0, 2, 1, 2, 1, 2, 2, 0, 2, 0, 0, 2, 1, 2, 2, 1, 0, 1 ]
]
, [ [ 1, 0, 1, 2, 0, 2, 0, 1, 2, 1, 0, 1, 0, 1, 1, 2, 1, 2, 2, 1, 0, 1, 1, 0, 2, 0, 0, 2 ]
, [ 1, 0, 1, 2, 0, 2, 0, 1, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 2, 0, 0, 2 ] -- 14
, [ 1, 0, 1, 2, 0, 2, 0, 1, 2, 1, 0, 1, 0, 1, 2, 0, 2, 0, 0, 2 ] -- 14
, [ 1, 0, 1, 2, 0, 2, 0, 1, 2, 1, 0, 1, 0, 1, 1, 2 ] -- 14
, [ 1, 0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 2 ] -- 10
, [ 1, 0, 1, 2, 0, 2, 0, 0 ] -- 7
, [ 1, 0, 1, 1 ] -- 3
]
)
| Erdwolf/autotool-bonn | src/PCP/Solutions.hs | gpl-2.0 | 2,970 | 0 | 7 | 1,322 | 2,347 | 1,559 | 788 | 62 | 1 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.IO.Handle.FD (module M) where
import "base" GHC.IO.Handle.FD as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/GHC/IO/Handle/FD.hs | apache-2.0 | 747 | 0 | 4 | 136 | 27 | 21 | 6 | 4 | 0 |
{-# LANGUAGE CPP #-}
module TcInteract (
solveSimpleGivens, -- Solves [EvVar],GivenLoc
solveSimpleWanteds -- Solves Cts
) where
#include "HsVersions.h"
import BasicTypes ( infinity, IntWithInf, intGtLimit )
import HsTypes ( hsIPNameFS )
import FastString
import TcCanonical
import TcFlatten
import VarSet
import Type
import Kind ( isKind )
import InstEnv( DFunInstType, lookupInstEnv, instanceDFunId )
import CoAxiom(sfInteractTop, sfInteractInert)
import Var
import TcType
import PrelNames ( knownNatClassName, knownSymbolClassName,
callStackTyConKey, typeableClassName )
import TysWiredIn ( ipClass, typeNatKind, typeSymbolKind )
import Id( idType )
import CoAxiom ( Eqn, CoAxiom(..), CoAxBranch(..), fromBranches )
import Class
import TyCon
import DataCon( dataConWrapId )
import FunDeps
import FamInst
import FamInstEnv
import Inst( tyVarsOfCt )
import Unify ( tcUnifyTyWithTFs )
import TcEvidence
import Outputable
import TcRnTypes
import TcSMonad
import Bag
import MonadUtils ( concatMapM )
import Data.List( partition, foldl', deleteFirstsBy )
import SrcLoc
import VarEnv
import Control.Monad
import Maybes( isJust )
import Pair (Pair(..))
import Unique( hasKey )
import DynFlags
import Util
{-
**********************************************************************
* *
* Main Interaction Solver *
* *
**********************************************************************
Note [Basic Simplifier Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Pick an element from the WorkList if there exists one with depth
less than our context-stack depth.
2. Run it down the 'stage' pipeline. Stages are:
- canonicalization
- inert reactions
- spontaneous reactions
- top-level intreactions
Each stage returns a StopOrContinue and may have sideffected
the inerts or worklist.
The threading of the stages is as follows:
- If (Stop) is returned by a stage then we start again from Step 1.
- If (ContinueWith ct) is returned by a stage, we feed 'ct' on to
the next stage in the pipeline.
4. If the element has survived (i.e. ContinueWith x) the last stage
then we add him in the inerts and jump back to Step 1.
If in Step 1 no such element exists, we have exceeded our context-stack
depth and will simply fail.
Note [Unflatten after solving the simple wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We unflatten after solving the wc_simples of an implication, and before attempting
to float. This means that
* The fsk/fmv flatten-skolems only survive during solveSimples. We don't
need to worry about them across successive passes over the constraint tree.
(E.g. we don't need the old ic_fsk field of an implication.
* When floating an equality outwards, we don't need to worry about floating its
associated flattening constraints.
* Another tricky case becomes easy: Trac #4935
type instance F True a b = a
type instance F False a b = b
[w] F c a b ~ gamma
(c ~ True) => a ~ gamma
(c ~ False) => b ~ gamma
Obviously this is soluble with gamma := F c a b, and unflattening
will do exactly that after solving the simple constraints and before
attempting the implications. Before, when we were not unflattening,
we had to push Wanted funeqs in as new givens. Yuk!
Another example that becomes easy: indexed_types/should_fail/T7786
[W] BuriedUnder sub k Empty ~ fsk
[W] Intersect fsk inv ~ s
[w] xxx[1] ~ s
[W] forall[2] . (xxx[1] ~ Empty)
=> Intersect (BuriedUnder sub k Empty) inv ~ Empty
Note [Running plugins on unflattened wanteds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is an annoying mismatch between solveSimpleGivens and
solveSimpleWanteds, because the latter needs to fiddle with the inert
set, unflatten and zonk the wanteds. It passes the zonked wanteds
to runTcPluginsWanteds, which produces a replacement set of wanteds,
some additional insolubles and a flag indicating whether to go round
the loop again. If so, prepareInertsForImplications is used to remove
the previous wanteds (which will still be in the inert set). Note
that prepareInertsForImplications will discard the insolubles, so we
must keep track of them separately.
-}
solveSimpleGivens :: CtLoc -> [EvVar] -> TcS Cts
-- Solves the givens, adding them to the inert set
-- Returns any insoluble givens, which represent inaccessible code,
-- taking those ones out of the inert set
solveSimpleGivens loc givens
| null givens -- Shortcut for common case
= return emptyCts
| otherwise
= do { go (map mk_given_ct givens)
; takeGivenInsolubles }
where
mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evar = ev_id
, ctev_pred = evVarPred ev_id
, ctev_loc = loc })
go givens = do { solveSimples (listToBag givens)
; new_givens <- runTcPluginsGiven
; when (notNull new_givens) (go new_givens)
}
solveSimpleWanteds :: Cts -> TcS WantedConstraints
-- NB: 'simples' may contain /derived/ equalities, floated
-- out from a nested implication. So don't discard deriveds!
solveSimpleWanteds simples
= do { traceTcS "solveSimples {" (ppr simples)
; dflags <- getDynFlags
; (n,wc) <- go 1 (solverIterations dflags) (emptyWC { wc_simple = simples })
; traceTcS "solveSimples end }" $
vcat [ ptext (sLit "iterations =") <+> ppr n
, ptext (sLit "residual =") <+> ppr wc ]
; return wc }
where
go :: Int -> IntWithInf -> WantedConstraints -> TcS (Int, WantedConstraints)
go n limit wc
| n `intGtLimit` limit
= failTcS (hang (ptext (sLit "solveSimpleWanteds: too many iterations")
<+> parens (ptext (sLit "limit =") <+> ppr limit))
2 (vcat [ ptext (sLit "Set limit with -fsolver-iterations=n; n=0 for no limit")
, ptext (sLit "Simples =") <+> ppr simples
, ptext (sLit "WC =") <+> ppr wc ]))
| isEmptyBag (wc_simple wc)
= return (n,wc)
| otherwise
= do { -- Solve
(unif_count, wc1) <- solve_simple_wanteds wc
-- Run plugins
; (rerun_plugin, wc2) <- runTcPluginsWanted wc1
-- See Note [Running plugins on unflattened wanteds]
; if unif_count == 0 && not rerun_plugin
then return (n, wc2) -- Done
else do { traceTcS "solveSimple going round again:" (ppr rerun_plugin)
; go (n+1) limit wc2 } } -- Loop
solve_simple_wanteds :: WantedConstraints -> TcS (Int, WantedConstraints)
-- Try solving these constraints
-- Affects the unification state (of course) but not the inert set
solve_simple_wanteds (WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 })
= nestTcS $
do { solveSimples simples1
; (implics2, tv_eqs, fun_eqs, insols2, others) <- getUnsolvedInerts
; (unif_count, unflattened_eqs) <- reportUnifications $
unflatten tv_eqs fun_eqs
-- See Note [Unflatten after solving the simple wanteds]
; return ( unif_count
, WC { wc_simple = others `andCts` unflattened_eqs
, wc_insol = insols1 `andCts` insols2
, wc_impl = implics1 `unionBags` implics2 }) }
{- Note [The solveSimpleWanteds loop]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Solving a bunch of simple constraints is done in a loop,
(the 'go' loop of 'solveSimpleWanteds'):
1. Try to solve them; unflattening may lead to improvement that
was not exploitable during solving
2. Try the plugin
3. If step 1 did improvement during unflattening; or if the plugin
wants to run again, go back to step 1
Non-obviously, improvement can also take place during
the unflattening that takes place in step (1). See TcFlatten,
See Note [Unflattening can force the solver to iterate]
-}
-- The main solver loop implements Note [Basic Simplifier Plan]
---------------------------------------------------------------
solveSimples :: Cts -> TcS ()
-- Returns the final InertSet in TcS
-- Has no effect on work-list or residual-implications
-- The constraints are initially examined in left-to-right order
solveSimples cts
= {-# SCC "solveSimples" #-}
do { updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts)
; solve_loop }
where
solve_loop
= {-# SCC "solve_loop" #-}
do { sel <- selectNextWorkItem
; case sel of
Nothing -> return ()
Just ct -> do { runSolverPipeline thePipeline ct
; solve_loop } }
-- | Extract the (inert) givens and invoke the plugins on them.
-- Remove solved givens from the inert set and emit insolubles, but
-- return new work produced so that 'solveSimpleGivens' can feed it back
-- into the main solver.
runTcPluginsGiven :: TcS [Ct]
runTcPluginsGiven
= do { plugins <- getTcPlugins
; if null plugins then return [] else
do { givens <- getInertGivens
; if null givens then return [] else
do { p <- runTcPlugins plugins (givens,[],[])
; let (solved_givens, _, _) = pluginSolvedCts p
; updInertCans (removeInertCts solved_givens)
; mapM_ emitInsoluble (pluginBadCts p)
; return (pluginNewCts p) } } }
-- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on
-- them and produce an updated bag of wanteds (possibly with some new
-- work) and a bag of insolubles. The boolean indicates whether
-- 'solveSimpleWanteds' should feed the updated wanteds back into the
-- main solver.
runTcPluginsWanted :: WantedConstraints -> TcS (Bool, WantedConstraints)
runTcPluginsWanted wc@(WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 })
| isEmptyBag simples1
= return (False, wc)
| otherwise
= do { plugins <- getTcPlugins
; if null plugins then return (False, wc) else
do { given <- getInertGivens
; simples1 <- zonkSimples simples1 -- Plugin requires zonked inputs
; let (wanted, derived) = partition isWantedCt (bagToList simples1)
; p <- runTcPlugins plugins (given, derived, wanted)
; let (_, _, solved_wanted) = pluginSolvedCts p
(_, unsolved_derived, unsolved_wanted) = pluginInputCts p
new_wanted = pluginNewCts p
-- SLPJ: I'm deeply suspicious of this
-- ; updInertCans (removeInertCts $ solved_givens ++ solved_deriveds)
; mapM_ setEv solved_wanted
; return ( notNull (pluginNewCts p)
, WC { wc_simple = listToBag new_wanted `andCts` listToBag unsolved_wanted
`andCts` listToBag unsolved_derived
, wc_insol = listToBag (pluginBadCts p) `andCts` insols1
, wc_impl = implics1 } ) } }
where
setEv :: (EvTerm,Ct) -> TcS ()
setEv (ev,ct) = case ctEvidence ct of
CtWanted {ctev_evar = evar} -> setWantedEvBind evar ev
_ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!"
-- | A triple of (given, derived, wanted) constraints to pass to plugins
type SplitCts = ([Ct], [Ct], [Ct])
-- | A solved triple of constraints, with evidence for wanteds
type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)])
-- | Represents collections of constraints generated by typechecker
-- plugins
data TcPluginProgress = TcPluginProgress
{ pluginInputCts :: SplitCts
-- ^ Original inputs to the plugins with solved/bad constraints
-- removed, but otherwise unmodified
, pluginSolvedCts :: SolvedCts
-- ^ Constraints solved by plugins
, pluginBadCts :: [Ct]
-- ^ Constraints reported as insoluble by plugins
, pluginNewCts :: [Ct]
-- ^ New constraints emitted by plugins
}
getTcPlugins :: TcS [TcPluginSolver]
getTcPlugins = do { tcg_env <- getGblEnv; return (tcg_tc_plugins tcg_env) }
-- | Starting from a triple of (given, derived, wanted) constraints,
-- invoke each of the typechecker plugins in turn and return
--
-- * the remaining unmodified constraints,
-- * constraints that have been solved,
-- * constraints that are insoluble, and
-- * new work.
--
-- Note that new work generated by one plugin will not be seen by
-- other plugins on this pass (but the main constraint solver will be
-- re-invoked and they will see it later). There is no check that new
-- work differs from the original constraints supplied to the plugin:
-- the plugin itself should perform this check if necessary.
runTcPlugins :: [TcPluginSolver] -> SplitCts -> TcS TcPluginProgress
runTcPlugins plugins all_cts
= foldM do_plugin initialProgress plugins
where
do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress
do_plugin p solver = do
result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p))
return $ progress p result
progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress
progress p (TcPluginContradiction bad_cts) =
p { pluginInputCts = discard bad_cts (pluginInputCts p)
, pluginBadCts = bad_cts ++ pluginBadCts p
}
progress p (TcPluginOk solved_cts new_cts) =
p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p)
, pluginSolvedCts = add solved_cts (pluginSolvedCts p)
, pluginNewCts = new_cts ++ pluginNewCts p
}
initialProgress = TcPluginProgress all_cts ([], [], []) [] []
discard :: [Ct] -> SplitCts -> SplitCts
discard cts (xs, ys, zs) =
(xs `without` cts, ys `without` cts, zs `without` cts)
without :: [Ct] -> [Ct] -> [Ct]
without = deleteFirstsBy eqCt
eqCt :: Ct -> Ct -> Bool
eqCt c c' = case (ctEvidence c, ctEvidence c') of
(CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred'
(CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred'
(CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred'
(_ , _ ) -> False
add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts
add xs scs = foldl' addOne scs xs
addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts
addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of
CtGiven {} -> (ct:givens, deriveds, wanteds)
CtDerived{} -> (givens, ct:deriveds, wanteds)
CtWanted {} -> (givens, deriveds, (ev,ct):wanteds)
type WorkItem = Ct
type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct)
runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline
-> WorkItem -- The work item
-> TcS ()
-- Run this item down the pipeline, leaving behind new work and inerts
runSolverPipeline pipeline workItem
= do { initial_is <- getTcSInerts
; traceTcS "Start solver pipeline {" $
vcat [ ptext (sLit "work item = ") <+> ppr workItem
, ptext (sLit "inerts = ") <+> ppr initial_is]
; bumpStepCountTcS -- One step for each constraint processed
; final_res <- run_pipeline pipeline (ContinueWith workItem)
; final_is <- getTcSInerts
; case final_res of
Stop ev s -> do { traceFireTcS ev s
; traceTcS "End solver pipeline (discharged) }"
(ptext (sLit "inerts =") <+> ppr final_is)
; return () }
ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert"))
; traceTcS "End solver pipeline (kept as inert) }" $
vcat [ ptext (sLit "final_item =") <+> ppr ct
, pprTvBndrs (varSetElems $ tyVarsOfCt ct)
, ptext (sLit "inerts =") <+> ppr final_is]
; addInertCan ct }
}
where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct
-> TcS (StopOrContinue Ct)
run_pipeline [] res = return res
run_pipeline _ (Stop ev s) = return (Stop ev s)
run_pipeline ((stg_name,stg):stgs) (ContinueWith ct)
= do { traceTcS ("runStage " ++ stg_name ++ " {")
(text "workitem = " <+> ppr ct)
; res <- stg ct
; traceTcS ("end stage " ++ stg_name ++ " }") empty
; run_pipeline stgs res }
{-
Example 1:
Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given)
Reagent: a ~ [b] (given)
React with (c~d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t]
React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True []
Example 2:
Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty}
Reagent: a ~w [b]
React with (c ~w d) ==> IR (ContinueWith (a~[b])) True []
React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!)
etc.
Example 3:
Inert: {a ~ Int, F Int ~ b} (given)
Reagent: F a ~ b (wanted)
React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True []
React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing
-}
thePipeline :: [(String,SimplifierStage)]
thePipeline = [ ("canonicalization", TcCanonical.canonicalize)
, ("interact with inerts", interactWithInertsStage)
, ("top-level reactions", topReactionsStage) ]
{-
*********************************************************************************
* *
The interact-with-inert Stage
* *
*********************************************************************************
Note [The Solver Invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We always add Givens first. So you might think that the solver has
the invariant
If the work-item is Given,
then the inert item must Given
But this isn't quite true. Suppose we have,
c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int
After processing the first two, we get
c1: [G] beta ~ [alpha], c2 : [W] blah
Now, c3 does not interact with the the given c1, so when we spontaneously
solve c3, we must re-react it with the inert set. So we can attempt a
reaction between inert c2 [W] and work-item c3 [G].
It *is* true that [Solver Invariant]
If the work-item is Given,
AND there is a reaction
then the inert item must Given
or, equivalently,
If the work-item is Given,
and the inert item is Wanted/Derived
then there is no reaction
-}
-- Interaction result of WorkItem <~> Ct
type StopNowFlag = Bool -- True <=> stop after this interaction
interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct)
-- Precondition: if the workitem is a CTyEqCan then it will not be able to
-- react with anything at this stage.
interactWithInertsStage wi
= do { inerts <- getTcSInerts
; let ics = inert_cans inerts
; case wi of
CTyEqCan {} -> interactTyVarEq ics wi
CFunEqCan {} -> interactFunEq ics wi
CIrredEvCan {} -> interactIrred ics wi
CDictCan {} -> interactDict ics wi
_ -> pprPanic "interactWithInerts" (ppr wi) }
-- CHoleCan are put straight into inert_frozen, so never get here
-- CNonCanonical have been canonicalised
data InteractResult
= IRKeep -- Keep the existing inert constraint in the inert set
| IRReplace -- Replace the existing inert constraint with the work item
| IRDelete -- Delete the existing inert constraint from the inert set
instance Outputable InteractResult where
ppr IRKeep = ptext (sLit "keep")
ppr IRReplace = ptext (sLit "replace")
ppr IRDelete = ptext (sLit "delete")
solveOneFromTheOther :: CtEvidence -- Inert
-> CtEvidence -- WorkItem
-> TcS (InteractResult, StopNowFlag)
-- Preconditions:
-- 1) inert and work item represent evidence for the /same/ predicate
-- 2) ip/class/irred evidence (no coercions) only
solveOneFromTheOther ev_i ev_w
| isDerived ev_w -- Work item is Derived; just discard it
= return (IRKeep, True)
| isDerived ev_i -- The inert item is Derived, we can just throw it away,
= return (IRDelete, False) -- The ev_w is inert wrt earlier inert-set items,
-- so it's safe to continue on from this point
| CtWanted { ctev_loc = loc_w } <- ev_w
, prohibitedSuperClassSolve (ctEvLoc ev_i) loc_w
= return (IRDelete, False)
| CtWanted { ctev_evar = ev_id } <- ev_w -- Inert is Given or Wanted
= do { setWantedEvBind ev_id (ctEvTerm ev_i)
; return (IRKeep, True) }
| CtWanted { ctev_loc = loc_i } <- ev_i -- Work item is Given
, prohibitedSuperClassSolve (ctEvLoc ev_w) loc_i
= return (IRKeep, False) -- Just discard the un-usable Given
-- This never actually happens because
-- Givens get processed first
| CtWanted { ctev_evar = ev_id } <- ev_i -- Work item is Given
= do { setWantedEvBind ev_id (ctEvTerm ev_w)
; return (IRReplace, True) }
-- So they are both Given
-- See Note [Replacement vs keeping]
| lvl_i == lvl_w
= do { binds <- getTcEvBindsMap
; return (same_level_strategy binds, True) }
| otherwise -- Both are Given, levels differ
= return (different_level_strategy, True)
where
pred = ctEvPred ev_i
loc_i = ctEvLoc ev_i
loc_w = ctEvLoc ev_w
lvl_i = ctLocLevel loc_i
lvl_w = ctLocLevel loc_w
different_level_strategy
| isIPPred pred, lvl_w > lvl_i = IRReplace
| lvl_w < lvl_i = IRReplace
| otherwise = IRKeep
same_level_strategy binds -- Both Given
| GivenOrigin (InstSC s_i) <- ctLocOrigin loc_i
= case ctLocOrigin loc_w of
GivenOrigin (InstSC s_w) | s_w < s_i -> IRReplace
| otherwise -> IRKeep
_ -> IRReplace
| GivenOrigin (InstSC {}) <- ctLocOrigin loc_w
= IRKeep
| has_binding binds ev_w
, not (has_binding binds ev_i)
= IRReplace
| otherwise = IRKeep
has_binding binds ev = isJust (lookupEvBind binds (ctEvId ev))
{-
Note [Replacement vs keeping]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we have two Given constraints both of type (C tys), say, which should
we keep? More subtle than you might think!
* Constraints come from different levels (different_level_strategy)
- For implicit parameters we want to keep the innermost (deepest)
one, so that it overrides the outer one.
See Note [Shadowing of Implicit Parameters]
- For everything else, we want to keep the outermost one. Reason: that
makes it more likely that the inner one will turn out to be unused,
and can be reported as redundant. See Note [Tracking redundant constraints]
in TcSimplify.
It transpires that using the outermost one is reponsible for an
8% performance improvement in nofib cryptarithm2, compared to
just rolling the dice. I didn't investigate why.
* Constaints coming from the same level (i.e. same implication)
- Always get rid of InstSC ones if possible, since they are less
useful for solving. If both are InstSC, choose the one with
the smallest TypeSize
See Note [Solving superclass constraints] in TcInstDcls
- Keep the one that has a non-trivial evidence binding.
Note [Tracking redundant constraints] again.
Example: f :: (Eq a, Ord a) => blah
then we may find [G] sc_sel (d1::Ord a) :: Eq a
[G] d2 :: Eq a
We want to discard d2 in favour of the superclass selection from
the Ord dictionary.
* Finally, when there is still a choice, use IRKeep rather than
IRReplace, to avoid unnecessary munging of the inert set.
Doing the depth-check for implicit parameters, rather than making the work item
always overrride, is important. Consider
data T a where { T1 :: (?x::Int) => T Int; T2 :: T a }
f :: (?x::a) => T a -> Int
f T1 = ?x
f T2 = 3
We have a [G] (?x::a) in the inert set, and at the pattern match on T1 we add
two new givens in the work-list: [G] (?x::Int)
[G] (a ~ Int)
Now consider these steps
- process a~Int, kicking out (?x::a)
- process (?x::Int), the inner given, adding to inert set
- process (?x::a), the outer given, overriding the inner given
Wrong! The depth-check ensures that the inner implicit parameter wins.
(Actually I think that the order in which the work-list is processed means
that this chain of events won't happen, but that's very fragile.)
*********************************************************************************
* *
interactIrred
* *
*********************************************************************************
-}
-- Two pieces of irreducible evidence: if their types are *exactly identical*
-- we can rewrite them. We can never improve using this:
-- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not
-- mean that (ty1 ~ ty2)
interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w })
| let pred = ctEvPred ev_w
(matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred)
(inert_irreds inerts)
, (ct_i : rest) <- bagToList matching_irreds
, let ctev_i = ctEvidence ct_i
= ASSERT( null rest )
do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertIrreds (\_ -> others)
IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem)
-- These const upd's assume that solveOneFromTheOther
-- has no side effects on InertCans
; if stop_now then
return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect)))
; else
continueWith workItem }
| otherwise
= continueWith workItem
interactIrred _ wi = pprPanic "interactIrred" (ppr wi)
{-
*********************************************************************************
* *
interactDict
* *
*********************************************************************************
-}
interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct)
interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys })
-- don't ever try to solve CallStack IPs directly from other dicts,
-- we always build new dicts instead.
-- See Note [Overview of implicit CallStacks]
| Just mkEvCs <- isCallStackIP (ctEvLoc ev_w) cls tys
, isWanted ev_w
= do let ev_cs =
case lookupInertDict inerts cls tys of
Just ev | isGiven ev -> mkEvCs (ctEvTerm ev)
_ -> mkEvCs (EvCallStack EvCsEmpty)
-- now we have ev_cs :: CallStack, but the evidence term should
-- be a dictionary, so we have to coerce ev_cs to a
-- dictionary for `IP ip CallStack`
let ip_ty = mkClassPred cls tys
let ev_tm = mkEvCast (EvCallStack ev_cs) (TcCoercion $ wrapIP ip_ty)
addSolvedDict ev_w cls tys
setWantedEvBind (ctEvId ev_w) ev_tm
stopWith ev_w "Wanted CallStack IP"
| Just ctev_i <- lookupInertDict inerts cls tys
= do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w
; case inert_effect of
IRKeep -> return ()
IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys
IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem
; if stop_now then
return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect)))
else
continueWith workItem }
| cls == ipClass
, isGiven ev_w
= interactGivenIP inerts workItem
| otherwise
= do { addFunDepWork inerts ev_w cls
; continueWith workItem }
interactDict _ wi = pprPanic "interactDict" (ppr wi)
addFunDepWork :: InertCans -> CtEvidence -> Class -> TcS ()
-- Add derived constraints from type-class functional dependencies.
addFunDepWork inerts work_ev cls
= mapBagM_ add_fds (findDictsByClass (inert_dicts inerts) cls)
-- No need to check flavour; fundeps work between
-- any pair of constraints, regardless of flavour
-- Importantly we don't throw workitem back in the
-- worklist because this can cause loops (see #5236)
where
work_pred = ctEvPred work_ev
work_loc = ctEvLoc work_ev
add_fds inert_ct
= emitFunDepDeriveds $
improveFromAnother derived_loc inert_pred work_pred
-- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok
-- NB: We do create FDs for given to report insoluble equations that arise
-- from pairs of Givens, and also because of floating when we approximate
-- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs
where
inert_pred = ctPred inert_ct
inert_loc = ctLoc inert_ct
derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc
inert_pred inert_loc }
{-
*********************************************************************************
* *
Implicit parameters
* *
*********************************************************************************
-}
interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Work item is Given (?x:ty)
-- See Note [Shadowing of Implicit Parameters]
interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls
, cc_tyargs = tys@(ip_str:_) })
= do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem }
; stopWith ev "Given IP" }
where
dicts = inert_dicts inerts
ip_dicts = findDictsByClass dicts cls
other_ip_dicts = filterBag (not . is_this_ip) ip_dicts
filtered_dicts = addDictsByClass dicts cls other_ip_dicts
-- Pick out any Given constraints for the same implicit parameter
is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ })
= isGiven ev && ip_str `tcEqType` ip_str'
is_this_ip _ = False
interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi)
{-
Note [Shadowing of Implicit Parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following example:
f :: (?x :: Char) => Char
f = let ?x = 'a' in ?x
The "let ?x = ..." generates an implication constraint of the form:
?x :: Char => ?x :: Char
Furthermore, the signature for `f` also generates an implication
constraint, so we end up with the following nested implication:
?x :: Char => (?x :: Char => ?x :: Char)
Note that the wanted (?x :: Char) constraint may be solved in
two incompatible ways: either by using the parameter from the
signature, or by using the local definition. Our intention is
that the local definition should "shadow" the parameter of the
signature, and we implement this as follows: when we add a new
*given* implicit parameter to the inert set, it replaces any existing
givens for the same implicit parameter.
This works for the normal cases but it has an odd side effect
in some pathological programs like this:
-- This is accepted, the second parameter shadows
f1 :: (?x :: Int, ?x :: Char) => Char
f1 = ?x
-- This is rejected, the second parameter shadows
f2 :: (?x :: Int, ?x :: Char) => Int
f2 = ?x
Both of these are actually wrong: when we try to use either one,
we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char),
which would lead to an error.
I can think of two ways to fix this:
1. Simply disallow multiple constratits for the same implicit
parameter---this is never useful, and it can be detected completely
syntactically.
2. Move the shadowing machinery to the location where we nest
implications, and add some code here that will produce an
error if we get multiple givens for the same implicit parameter.
*********************************************************************************
* *
interactFunEq
* *
*********************************************************************************
-}
interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- Try interacting the work item with the inert set
interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc
, cc_tyargs = args, cc_fsk = fsk })
| Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts
= if ev_i `canDischarge` ev
then -- Rewrite work-item using inert
do { traceTcS "reactFunEq (discharge work item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; reactFunEq ev_i fsk_i ev fsk
; stopWith ev "Inert rewrites work item" }
else -- Rewrite inert using work-item
ASSERT2( ev `canDischarge` ev_i, ppr ev $$ ppr ev_i )
do { traceTcS "reactFunEq (rewrite inert item):" $
vcat [ text "workItem =" <+> ppr workItem
, text "inertItem=" <+> ppr ev_i ]
; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem
-- Do the updInertFunEqs before the reactFunEq, so that
-- we don't kick out the inertItem as well as consuming it!
; reactFunEq ev fsk ev_i fsk_i
; stopWith ev "Work item rewrites inert" }
| otherwise -- Try improvement
= do { improveLocalFunEqs loc inerts tc args fsk
; continueWith workItem }
where
loc = ctEvLoc ev
funeqs = inert_funeqs inerts
matching_inerts = findFunEqs funeqs tc args
interactFunEq _ workItem = pprPanic "interactFunEq" (ppr workItem)
improveLocalFunEqs :: CtLoc -> InertCans -> TyCon -> [TcType] -> TcTyVar
-> TcS ()
-- Generate derived improvement equalities, by comparing
-- the current work item with inert CFunEqs
-- E.g. x + y ~ z, x + y' ~ z => [D] y ~ y'
improveLocalFunEqs loc inerts fam_tc args fsk
| not (null improvement_eqns)
= do { traceTcS "interactFunEq improvements: " $
vcat [ ptext (sLit "Eqns:") <+> ppr improvement_eqns
, ptext (sLit "Candidates:") <+> ppr funeqs_for_tc
, ptext (sLit "TvEqs:") <+> ppr tv_eqs ]
; mapM_ (unifyDerived loc Nominal) improvement_eqns }
| otherwise
= return ()
where
tv_eqs = inert_model inerts
funeqs = inert_funeqs inerts
funeqs_for_tc = findFunEqsByTyCon funeqs fam_tc
rhs = lookupFlattenTyVar tv_eqs fsk
--------------------
improvement_eqns
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= -- Try built-in families, notably for arithmethic
concatMap (do_one_built_in ops) funeqs_for_tc
| Injective injective_args <- familyTyConInjectivityInfo fam_tc
= -- Try improvement from type families with injectivity annotations
concatMap (do_one_injective injective_args) funeqs_for_tc
| otherwise
= []
--------------------
do_one_built_in ops (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk })
= sfInteractInert ops args rhs iargs (lookupFlattenTyVar tv_eqs ifsk)
do_one_built_in _ _ = pprPanic "interactFunEq 1" (ppr fam_tc)
--------------------
-- See Note [Type inference for type families with injectivity]
do_one_injective injective_args
(CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk })
| rhs `tcEqType` lookupFlattenTyVar tv_eqs ifsk
= [Pair arg iarg | (arg, iarg, True)
<- zip3 args iargs injective_args ]
| otherwise
= []
do_one_injective _ _ = pprPanic "interactFunEq 2" (ppr fam_tc)
-------------
lookupFlattenTyVar :: InertModel -> TcTyVar -> TcType
-- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs;
-- this is used only when dealing with a CFunEqCan
lookupFlattenTyVar model ftv
= case lookupVarEnv model ftv of
Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq }) -> rhs
_ -> mkTyVarTy ftv
reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1
-> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2
-> TcS ()
reactFunEq from_this fsk1 (CtGiven { ctev_evar = evar, ctev_loc = loc }) fsk2
= do { let fsk_eq_co = mkTcSymCo (mkTcCoVarCo evar)
`mkTcTransCo` ctEvCoercion from_this
-- :: fsk2 ~ fsk1
fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1)
; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co)
; emitWorkNC [new_ev] }
reactFunEq from_this fuv1 ev fuv2
= do { traceTcS "reactFunEq" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2)
; dischargeFmv ev fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1)
; traceTcS "reactFunEq done" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2) }
{-
Note [Type inference for type families with injectivity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have a type family with an injectivity annotation:
type family F a b = r | r -> b
Then if we have two CFunEqCan constraints for F with the same RHS
F s1 t1 ~ rhs
F s2 t2 ~ rhs
then we can use the injectivity to get a new Derived constraint on
the injective argument
[D] t1 ~ t2
That in turn can help GHC solve constraints that would otherwise require
guessing. For example, consider the ambiguity check for
f :: F Int b -> Int
We get the constraint
[W] F Int b ~ F Int beta
where beta is a unification variable. Injectivity lets us pick beta ~ b.
Injectivity information is also used at the call sites. For example:
g = f True
gives rise to
[W] F Int b ~ Bool
from which we can derive b. This requires looking at the defining equations of
a type family, ie. finding equation with a matching RHS (Bool in this example)
and infering values of type variables (b in this example) from the LHS patterns
of the matching equation. For closed type families we have to perform
additional apartness check for the selected equation to check that the selected
is guaranteed to fire for given LHS arguments.
These new constraints are simply *Derived* constraints; they have no evidence.
We could go further and offer evidence from decomposing injective type-function
applications, but that would require new evidence forms, and an extension to
FC, so we don't do that right now (Dec 14).
See also Note [Injective type families] in TyCon
Note [Cache-caused loops]
~~~~~~~~~~~~~~~~~~~~~~~~~
It is very dangerous to cache a rewritten wanted family equation as 'solved' in our
solved cache (which is the default behaviour or xCtEvidence), because the interaction
may not be contributing towards a solution. Here is an example:
Initial inert set:
[W] g1 : F a ~ beta1
Work item:
[W] g2 : F a ~ beta2
The work item will react with the inert yielding the _same_ inert set plus:
i) Will set g2 := g1 `cast` g3
ii) Will add to our solved cache that [S] g2 : F a ~ beta2
iii) Will emit [W] g3 : beta1 ~ beta2
Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2
and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it
will set
g1 := g ; sym g3
and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but
remember that we have this in our solved cache, and it is ... g2! In short we
created the evidence loop:
g2 := g1 ; g3
g3 := refl
g1 := g2 ; sym g3
To avoid this situation we do not cache as solved any workitems (or inert)
which did not really made a 'step' towards proving some goal. Solved's are
just an optimization so we don't lose anything in terms of completeness of
solving.
Note [Efficient Orientation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we are interacting two FunEqCans with the same LHS:
(inert) ci :: (F ty ~ xi_i)
(work) cw :: (F ty ~ xi_w)
We prefer to keep the inert (else we pass the work item on down
the pipeline, which is a bit silly). If we keep the inert, we
will (a) discharge 'cw'
(b) produce a new equality work-item (xi_w ~ xi_i)
Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w):
new_work :: xi_w ~ xi_i
cw := ci ; sym new_work
Why? Consider the simplest case when xi1 is a type variable. If
we generate xi1~xi2, porcessing that constraint will kick out 'ci'.
If we generate xi2~xi1, there is less chance of that happening.
Of course it can and should still happen if xi1=a, xi1=Int, say.
But we want to avoid it happening needlessly.
Similarly, if we *can't* keep the inert item (because inert is Wanted,
and work is Given, say), we prefer to orient the new equality (xi_i ~
xi_w).
Note [Carefully solve the right CFunEqCan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---- OLD COMMENT, NOW NOT NEEDED
---- because we now allow multiple
---- wanted FunEqs with the same head
Consider the constraints
c1 :: F Int ~ a -- Arising from an application line 5
c2 :: F Int ~ Bool -- Arising from an application line 10
Suppose that 'a' is a unification variable, arising only from
flattening. So there is no error on line 5; it's just a flattening
variable. But there is (or might be) an error on line 10.
Two ways to combine them, leaving either (Plan A)
c1 :: F Int ~ a -- Arising from an application line 5
c3 :: a ~ Bool -- Arising from an application line 10
or (Plan B)
c2 :: F Int ~ Bool -- Arising from an application line 10
c4 :: a ~ Bool -- Arising from an application line 5
Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error
on the *totally innocent* line 5. An example is test SimpleFail16
where the expected/actual message comes out backwards if we use
the wrong plan.
The second is the right thing to do. Hence the isMetaTyVarTy
test when solving pairwise CFunEqCan.
*********************************************************************************
* *
interactTyVarEq
* *
*********************************************************************************
-}
interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct)
-- CTyEqCans are always consumed, so always returns Stop
interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv
, cc_rhs = rhs
, cc_ev = ev
, cc_eq_rel = eq_rel })
| (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv
, ev_i `canDischarge` ev
, rhs_i `tcEqType` rhs ]
= -- Inert: a ~ b
-- Work item: a ~ b
do { setEvBindIfWanted ev (ctEvTerm ev_i)
; stopWith ev "Solved from inert" }
| Just tv_rhs <- getTyVar_maybe rhs
, (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i }
<- findTyEqs inerts tv_rhs
, ev_i `canDischarge` ev
, rhs_i `tcEqType` mkTyVarTy tv ]
= -- Inert: a ~ b
-- Work item: b ~ a
do { setEvBindIfWanted ev
(EvCoercion (mkTcSymCo (ctEvCoercion ev_i)))
; stopWith ev "Solved from inert (r)" }
| otherwise
= do { tclvl <- getTcLevel
; if canSolveByUnification tclvl ev eq_rel tv rhs
then do { solveByUnification ev tv rhs
; n_kicked <- kickOutAfterUnification tv
; return (Stop ev (ptext (sLit "Solved by unification") <+> ppr_kicked n_kicked)) }
else do { traceTcS "Can't solve tyvar equality"
(vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv)
, ppWhen (isMetaTyVar tv) $
nest 4 (text "TcLevel of" <+> ppr tv
<+> text "is" <+> ppr (metaTyVarTcLevel tv))
, text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs)
, text "TcLevel =" <+> ppr tclvl ])
; addInertEq workItem
; return (Stop ev (ptext (sLit "Kept as inert"))) } }
interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi)
-- @trySpontaneousSolve wi@ solves equalities where one side is a
-- touchable unification variable.
-- Returns True <=> spontaneous solve happened
canSolveByUnification :: TcLevel -> CtEvidence -> EqRel
-> TcTyVar -> Xi -> Bool
canSolveByUnification tclvl gw eq_rel tv xi
| ReprEq <- eq_rel -- we never solve representational equalities this way.
= False
| isGiven gw -- See Note [Touchables and givens]
= False
| isTouchableMetaTyVar tclvl tv
= case metaTyVarInfo tv of
SigTv -> is_tyvar xi
_ -> True
| otherwise -- Untouchable
= False
where
is_tyvar xi
= case tcGetTyVar_maybe xi of
Nothing -> False
Just tv -> case tcTyVarDetails tv of
MetaTv { mtv_info = info }
-> case info of
SigTv -> True
_ -> False
SkolemTv {} -> True
FlatSkol {} -> False
RuntimeUnk -> True
solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS ()
-- Solve with the identity coercion
-- Precondition: kind(xi) is a sub-kind of kind(tv)
-- Precondition: CtEvidence is Wanted or Derived
-- Precondition: CtEvidence is nominal
-- Returns: workItem where
-- workItem = the new Given constraint
--
-- NB: No need for an occurs check here, because solveByUnification always
-- arises from a CTyEqCan, a *canonical* constraint. Its invariants
-- say that in (a ~ xi), the type variable a does not appear in xi.
-- See TcRnTypes.Ct invariants.
--
-- Post: tv is unified (by side effect) with xi;
-- we often write tv := xi
solveByUnification wd tv xi
= do { let tv_ty = mkTyVarTy tv
; traceTcS "Sneaky unification:" $
vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi,
text "Coercion:" <+> pprEq tv_ty xi,
text "Left Kind is:" <+> ppr (typeKind tv_ty),
text "Right Kind is:" <+> ppr (typeKind xi) ]
; let xi' = defaultKind xi
-- We only instantiate kind unification variables
-- with simple kinds like *, not OpenKind or ArgKind
-- cf TcUnify.uUnboundKVar
; unifyTyVar tv xi'
; setEvBindIfWanted wd (EvCoercion (mkTcNomReflCo xi')) }
ppr_kicked :: Int -> SDoc
ppr_kicked 0 = empty
ppr_kicked n = parens (int n <+> ptext (sLit "kicked out"))
{- Note [Avoid double unifications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The spontaneous solver has to return a given which mentions the unified unification
variable *on the left* of the equality. Here is what happens if not:
Original wanted: (a ~ alpha), (alpha ~ Int)
We spontaneously solve the first wanted, without changing the order!
given : a ~ alpha [having unified alpha := a]
Now the second wanted comes along, but he cannot rewrite the given, so we simply continue.
At the end we spontaneously solve that guy, *reunifying* [alpha := Int]
We avoid this problem by orienting the resulting given so that the unification
variable is on the left. [Note that alternatively we could attempt to
enforce this at canonicalization]
See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding
double unifications is the main reason we disallow touchable
unification variables as RHS of type family equations: F xis ~ alpha.
************************************************************************
* *
* Functional dependencies, instantiation of equations
* *
************************************************************************
When we spot an equality arising from a functional dependency,
we now use that equality (a "wanted") to rewrite the work-item
constraint right away. This avoids two dangers
Danger 1: If we send the original constraint on down the pipeline
it may react with an instance declaration, and in delicate
situations (when a Given overlaps with an instance) that
may produce new insoluble goals: see Trac #4952
Danger 2: If we don't rewrite the constraint, it may re-react
with the same thing later, and produce the same equality
again --> termination worries.
To achieve this required some refactoring of FunDeps.hs (nicer
now!).
-}
emitFunDepDeriveds :: [FunDepEqn CtLoc] -> TcS ()
emitFunDepDeriveds fd_eqns
= mapM_ do_one_FDEqn fd_eqns
where
do_one_FDEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc })
| null tvs -- Common shortcut
= mapM_ (unifyDerived loc Nominal) eqs
| otherwise
= do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution
; mapM_ (do_one_eq loc subst) eqs }
do_one_eq loc subst (Pair ty1 ty2)
= unifyDerived loc Nominal $
Pair (Type.substTy subst ty1) (Type.substTy subst ty2)
{-
*********************************************************************************
* *
The top-reaction Stage
* *
*********************************************************************************
-}
topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct)
topReactionsStage wi
= do { tir <- doTopReact wi
; case tir of
ContinueWith wi -> continueWith wi
Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) }
doTopReact :: WorkItem -> TcS (StopOrContinue Ct)
-- The work item does not react with the inert set, so try interaction with top-level
-- instances. Note:
--
-- (a) The place to add superclasses in not here in doTopReact stage.
-- Instead superclasses are added in the worklist as part of the
-- canonicalization process. See Note [Adding superclasses].
doTopReact work_item
= do { traceTcS "doTopReact" (ppr work_item)
; case work_item of
CDictCan {} -> do { inerts <- getTcSInerts
; doTopReactDict inerts work_item }
CFunEqCan {} -> doTopReactFunEq work_item
_ -> -- Any other work item does not react with any top-level equations
continueWith work_item }
--------------------
doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct)
-- Try to use type-class instance declarations to simplify the constraint
doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls
, cc_tyargs = xis })
| isGiven fl -- Never use instances for Given constraints
= do { try_fundep_improvement
; continueWith work_item }
| Just ev <- lookupSolvedDict inerts cls xis -- Cached
= do { setEvBindIfWanted fl (ctEvTerm ev);
; stopWith fl "Dict/Top (cached)" }
| isDerived fl -- Use type-class instances for Deriveds, in the hope
-- of generating some improvements
-- C.f. Example 3 of Note [The improvement story]
-- It's easy because no evidence is involved
= do { dflags <- getDynFlags
; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc
; case lkup_inst_res of
GenInst preds _ s -> do { emitNewDeriveds dict_loc preds
; unless s $
insertSafeOverlapFailureTcS work_item
; stopWith fl "Dict/Top (solved)" }
NoInstance -> do { -- If there is no instance, try improvement
try_fundep_improvement
; continueWith work_item } }
| otherwise -- Wanted, but not cached
= do { dflags <- getDynFlags
; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc
; case lkup_inst_res of
GenInst theta mk_ev s -> do { addSolvedDict fl cls xis
; unless s $
insertSafeOverlapFailureTcS work_item
; solve_from_instance theta mk_ev }
NoInstance -> do { try_fundep_improvement
; continueWith work_item } }
where
dict_pred = mkClassPred cls xis
dict_loc = ctEvLoc fl
dict_origin = ctLocOrigin dict_loc
deeper_loc = zap_origin (bumpCtLocDepth dict_loc)
zap_origin loc -- After applying an instance we can set ScOrigin to
-- infinity, so that prohibitedSuperClassSolve never fires
| ScOrigin {} <- dict_origin
= setCtLocOrigin loc (ScOrigin infinity)
| otherwise
= loc
solve_from_instance :: [TcPredType] -> ([EvId] -> EvTerm) -> TcS (StopOrContinue Ct)
-- Precondition: evidence term matches the predicate workItem
solve_from_instance theta mk_ev
| null theta
= do { traceTcS "doTopReact/found nullary instance for" $ ppr fl
; setWantedEvBind (ctEvId fl) (mk_ev [])
; stopWith fl "Dict/Top (solved, no new work)" }
| otherwise
= do { checkReductionDepth deeper_loc dict_pred
; traceTcS "doTopReact/found non-nullary instance for" $ ppr fl
; evc_vars <- mapM (newWantedEvVar deeper_loc) theta
; setWantedEvBind (ctEvId fl) (mk_ev (map (ctEvId . fst) evc_vars))
; emitWorkNC (freshGoals evc_vars)
; stopWith fl "Dict/Top (solved, more work)" }
-- We didn't solve it; so try functional dependencies with
-- the instance environment, and return
-- See also Note [Weird fundeps]
try_fundep_improvement
= do { traceTcS "try_fundeps" (ppr work_item)
; instEnvs <- getInstEnvs
; emitFunDepDeriveds $
improveFromInstEnv instEnvs mk_ct_loc dict_pred }
mk_ct_loc :: PredType -- From instance decl
-> SrcSpan -- also from instance deol
-> CtLoc
mk_ct_loc inst_pred inst_loc
= dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin
inst_pred inst_loc }
doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w)
--------------------
doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct)
doTopReactFunEq work_item = do { fam_envs <- getFamInstEnvs
; do_top_fun_eq fam_envs work_item }
do_top_fun_eq :: FamInstEnvs -> Ct -> TcS (StopOrContinue Ct)
do_top_fun_eq fam_envs work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc
, cc_tyargs = args , cc_fsk = fsk })
| Just (ax_co, rhs_ty) <- reduceTyFamApp_maybe fam_envs Nominal fam_tc args
-- Look up in top-level instances, or built-in axiom
-- See Note [MATCHING-SYNONYMS]
= reduce_top_fun_eq old_ev fsk (TcCoercion ax_co) rhs_ty
| otherwise
= do { improveTopFunEqs (ctEvLoc old_ev) fam_envs fam_tc args fsk
; continueWith work_item }
do_top_fun_eq _ w = pprPanic "doTopReactFunEq" (ppr w)
reduce_top_fun_eq :: CtEvidence -> TcTyVar -> TcCoercion -> TcType
-> TcS (StopOrContinue Ct)
-- Found an applicable top-level axiom: use it to reduce
reduce_top_fun_eq old_ev fsk ax_co rhs_ty
| Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty
, isTypeFamilyTyCon tc
, tc_args `lengthIs` tyConArity tc -- Short-cut
= shortCutReduction old_ev fsk ax_co tc tc_args
-- Try shortcut; see Note [Short cut for top-level reaction]
| isGiven old_ev -- Not shortcut
= do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co
-- final_co :: fsk ~ rhs_ty
; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty,
EvCoercion final_co)
; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty
; stopWith old_ev "Fun/Top (given)" }
-- So old_ev is Wanted or Derived
| not (fsk `elemVarSet` tyVarsOfType rhs_ty)
= do { dischargeFmv old_ev fsk ax_co rhs_ty
; traceTcS "doTopReactFunEq" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr ax_co ]
; stopWith old_ev "Fun/Top (wanted)" }
| otherwise -- We must not assign ufsk := ...ufsk...!
= do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk)
; let pred = mkTcEqPred alpha_ty rhs_ty
; new_ev <- case old_ev of
CtWanted {} -> do { ev <- newWantedEvVarNC loc pred
; updWorkListTcS (extendWorkListEq (mkNonCanonical ev))
; return ev }
CtDerived {} -> do { ev <- newDerivedNC loc pred
; updWorkListTcS (extendWorkListDerived loc ev)
; return ev }
_ -> pprPanic "reduce_top_fun_eq" (ppr old_ev)
-- By emitting this as non-canonical, we deal with all
-- flattening, occurs-check, and ufsk := ufsk issues
; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev)
-- ax_co :: fam_tc args ~ rhs_ty
-- ev :: alpha ~ rhs_ty
-- ufsk := alpha
-- final_co :: fam_tc args ~ alpha
; dischargeFmv old_ev fsk final_co alpha_ty
; traceTcS "doTopReactFunEq (occurs)" $
vcat [ text "old_ev:" <+> ppr old_ev
, nest 2 (text ":=") <+> ppr final_co
, text "new_ev:" <+> ppr new_ev ]
; stopWith old_ev "Fun/Top (wanted)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth loc
improveTopFunEqs :: CtLoc -> FamInstEnvs
-> TyCon -> [TcType] -> TcTyVar -> TcS ()
improveTopFunEqs loc fam_envs fam_tc args fsk
= do { model <- getInertModel
; eqns <- improve_top_fun_eqs fam_envs fam_tc args
(lookupFlattenTyVar model fsk)
; mapM_ (unifyDerived loc Nominal) eqns }
improve_top_fun_eqs :: FamInstEnvs
-> TyCon -> [TcType] -> TcType
-> TcS [Eqn]
improve_top_fun_eqs fam_envs fam_tc args rhs_ty
| Just ops <- isBuiltInSynFamTyCon_maybe fam_tc
= return (sfInteractTop ops args rhs_ty)
-- see Note [Type inference for type families with injectivity]
| isOpenTypeFamilyTyCon fam_tc
, Injective injective_args <- familyTyConInjectivityInfo fam_tc
= -- it is possible to have several compatible equations in an open type
-- family but we only want to derive equalities from one such equation.
concatMapM (injImproveEqns injective_args) (take 1 $
buildImprovementData (lookupFamInstEnvByTyCon fam_envs fam_tc)
fi_tys fi_rhs (const Nothing))
| Just ax <- isClosedSynFamilyTyConWithAxiom_maybe fam_tc
, Injective injective_args <- familyTyConInjectivityInfo fam_tc
= concatMapM (injImproveEqns injective_args) $
buildImprovementData (fromBranches (co_ax_branches ax))
cab_lhs cab_rhs Just
| otherwise
= return []
where
buildImprovementData
:: [a] -- axioms for a TF (FamInst or CoAxBranch)
-> (a -> [Type]) -- get LHS of an axiom
-> (a -> Type) -- get RHS of an axiom
-> (a -> Maybe CoAxBranch) -- Just => apartness check required
-> [( [Type], TvSubst, TyVarSet, Maybe CoAxBranch )]
-- Result:
-- ( [arguments of a matching axiom]
-- , RHS-unifying substitution
-- , axiom variables without substitution
-- , Maybe matching axiom [Nothing - open TF, Just - closed TF ] )
buildImprovementData axioms axiomLHS axiomRHS wrap =
[ (ax_args, subst, unsubstTvs, wrap axiom)
| axiom <- axioms
, let ax_args = axiomLHS axiom
, let ax_rhs = axiomRHS axiom
, Just subst <- [tcUnifyTyWithTFs False ax_rhs rhs_ty]
, let tvs = tyVarsOfTypes ax_args
notInSubst tv = not (tv `elemVarEnv` getTvSubstEnv subst)
unsubstTvs = filterVarSet notInSubst tvs ]
injImproveEqns :: [Bool]
-> ([Type], TvSubst, TyVarSet, Maybe CoAxBranch)
-> TcS [Eqn]
injImproveEqns inj_args (ax_args, theta, unsubstTvs, cabr) = do
(theta', _) <- instFlexiTcS (varSetElems unsubstTvs)
let subst = theta `unionTvSubst` theta'
return [ Pair arg (substTy subst ax_arg)
| case cabr of
Just cabr' -> apartnessCheck (substTys subst ax_args) cabr'
_ -> True
, (arg, ax_arg, True) <- zip3 args ax_args inj_args ]
shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion
-> TyCon -> [TcType] -> TcS (StopOrContinue Ct)
-- See Note [Top-level reductions for type functions]
shortCutReduction old_ev fsk ax_co fam_tc tc_args
| isGiven old_ev
= ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- old_ev :: F args ~ fsk
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
; new_ev <- newGivenEvVar deeper_loc
( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)
, EvCoercion (mkTcTyConAppCo Nominal fam_tc cos
`mkTcTransCo` mkTcSymCo ax_co
`mkTcTransCo` ctEvCoercion old_ev) )
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitWorkCt new_ct
; stopWith old_ev "Fun/Top (given, shortcut)" }
| otherwise
= ASSERT( not (isDerived old_ev) ) -- Caller ensures this
ASSERT( ctEvEqRel old_ev == NomEq )
do { (xis, cos) <- flattenManyNom old_ev tc_args
-- ax_co :: F args ~ G tc_args
-- cos :: xis ~ tc_args
-- G cos ; sym ax_co ; old_ev :: G xis ~ fsk
-- new_ev :: G xis ~ fsk
-- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev
; new_ev <- newWantedEvVarNC deeper_loc
(mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk))
; setWantedEvBind (ctEvId old_ev)
(EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos)
`mkTcTransCo` ctEvCoercion new_ev))
; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk }
; emitWorkCt new_ct
; stopWith old_ev "Fun/Top (wanted, shortcut)" }
where
loc = ctEvLoc old_ev
deeper_loc = bumpCtLocDepth loc
dischargeFmv :: CtEvidence -> TcTyVar -> TcCoercion -> TcType -> TcS ()
-- (dischargeFmv x fmv co ty)
-- [W] ev :: F tys ~ fmv
-- co :: F tys ~ xi
-- Precondition: fmv is not filled, and fuv `notElem` xi
--
-- Then set fmv := xi,
-- set ev := co
-- kick out any inert things that are now rewritable
--
-- Does not evaluate 'co' if 'ev' is Derived
dischargeFmv ev fmv co xi
= ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr ev $$ ppr fmv $$ ppr xi )
do { setEvBindIfWanted ev (EvCoercion co)
; unflattenFmv fmv xi
; n_kicked <- kickOutAfterUnification fmv
; traceTcS "dischargeFmv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) }
{- Note [Top-level reductions for type functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c.f. Note [The flattening story] in TcFlatten
Suppose we have a CFunEqCan F tys ~ fmv/fsk, and a matching axiom.
Here is what we do, in four cases:
* Wanteds: general firing rule
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ rhs
Then:
Discharge fmv := alpha
Discharge x := ax_co ; sym x2
New wanted [W] x2 : alpha ~ rhs (Non-canonical)
This is *the* way that fmv's get unified; even though they are
"untouchable".
NB: it can be the case that fmv appears in the (instantiated) rhs.
In that case the new Non-canonical wanted will be loopy, but that's
ok. But it's good reason NOT to claim that it is canonical!
* Wanteds: short cut firing rule
Applies when the RHS of the axiom is another type-function application
(work item) [W] x : F tys ~ fmv
instantiate axiom: ax_co : F tys ~ G rhs_tys
It would be a waste to create yet another fmv for (G rhs_tys).
Instead (shortCutReduction):
- Flatten rhs_tys (cos : rhs_tys ~ rhs_xis)
- Add G rhs_xis ~ fmv to flat cache (note: the same old fmv)
- New canonical wanted [W] x2 : G rhs_xis ~ fmv (CFunEqCan)
- Discharge x := ax_co ; G cos ; x2
* Givens: general firing rule
(work item) [G] g : F tys ~ fsk
instantiate axiom: ax_co : F tys ~ rhs
Now add non-canonical given (since rhs is not flat)
[G] (sym g ; ax_co) : fsk ~ rhs (Non-canonical)
* Givens: short cut firing rule
Applies when the RHS of the axiom is another type-function application
(work item) [G] g : F tys ~ fsk
instantiate axiom: ax_co : F tys ~ G rhs_tys
It would be a waste to create yet another fsk for (G rhs_tys).
Instead (shortCutReduction):
- Flatten rhs_tys: flat_cos : tys ~ flat_tys
- Add new Canonical given
[G] (sym (G flat_cos) ; co ; g) : G flat_tys ~ fsk (CFunEqCan)
Note [Cached solved FunEqs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
When trying to solve, say (FunExpensive big-type ~ ty), it's important
to see if we have reduced (FunExpensive big-type) before, lest we
simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover
we must use `canDischarge` because both uses might (say) be Wanteds,
and we *still* want to save the re-computation.
Note [MATCHING-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~
When trying to match a dictionary (D tau) to a top-level instance, or a
type family equation (F taus_1 ~ tau_2) to a top-level family instance,
we do *not* need to expand type synonyms because the matcher will do that for us.
Note [RHS-FAMILY-SYNONYMS]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The RHS of a family instance is represented as yet another constructor which is
like a type synonym for the real RHS the programmer declared. Eg:
type instance F (a,a) = [a]
Becomes:
:R32 a = [a] -- internal type synonym introduced
F (a,a) ~ :R32 a -- instance
When we react a family instance with a type family equation in the work list
we keep the synonym-using RHS without expansion.
Note [FunDep and implicit parameter reactions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Currently, our story of interacting two dictionaries (or a dictionary
and top-level instances) for functional dependencies, and implicit
paramters, is that we simply produce new Derived equalities. So for example
class D a b | a -> b where ...
Inert:
d1 :g D Int Bool
WorkItem:
d2 :w D Int alpha
We generate the extra work item
cv :d alpha ~ Bool
where 'cv' is currently unused. However, this new item can perhaps be
spontaneously solved to become given and react with d2,
discharging it in favour of a new constraint d2' thus:
d2' :w D Int Bool
d2 := d2' |> D Int cv
Now d2' can be discharged from d1
We could be more aggressive and try to *immediately* solve the dictionary
using those extra equalities, but that requires those equalities to carry
evidence and derived do not carry evidence.
If that were the case with the same inert set and work item we might dischard
d2 directly:
cv :w alpha ~ Bool
d2 := d1 |> D Int cv
But in general it's a bit painful to figure out the necessary coercion,
so we just take the first approach. Here is a better example. Consider:
class C a b c | a -> b
And:
[Given] d1 : C T Int Char
[Wanted] d2 : C T beta Int
In this case, it's *not even possible* to solve the wanted immediately.
So we should simply output the functional dependency and add this guy
[but NOT its superclasses] back in the worklist. Even worse:
[Given] d1 : C T Int beta
[Wanted] d2: C T beta Int
Then it is solvable, but its very hard to detect this on the spot.
It's exactly the same with implicit parameters, except that the
"aggressive" approach would be much easier to implement.
Note [Weird fundeps]
~~~~~~~~~~~~~~~~~~~~
Consider class Het a b | a -> b where
het :: m (f c) -> a -> m b
class GHet (a :: * -> *) (b :: * -> *) | a -> b
instance GHet (K a) (K [a])
instance Het a b => GHet (K a) (K b)
The two instances don't actually conflict on their fundeps,
although it's pretty strange. So they are both accepted. Now
try [W] GHet (K Int) (K Bool)
This triggers fundeps from both instance decls;
[D] K Bool ~ K [a]
[D] K Bool ~ K beta
And there's a risk of complaining about Bool ~ [a]. But in fact
the Wanted matches the second instance, so we never get as far
as the fundeps.
Trac #7875 is a case in point.
Note [Overriding implicit parameters]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
f :: (?x::a) -> Bool -> a
g v = let ?x::Int = 3
in (f v, let ?x::Bool = True in f v)
This should probably be well typed, with
g :: Bool -> (Int, Bool)
So the inner binding for ?x::Bool *overrides* the outer one.
Hence a work-item Given overrides an inert-item Given.
-}
-- | Indicates if Instance met the Safe Haskell overlapping instances safety
-- check.
--
-- See Note [Safe Haskell Overlapping Instances] in TcSimplify
-- See Note [Safe Haskell Overlapping Instances Implementation] in TcSimplify
type SafeOverlapping = Bool
data LookupInstResult
= NoInstance
| GenInst [TcPredType] ([EvId] -> EvTerm) SafeOverlapping
instance Outputable LookupInstResult where
ppr NoInstance = text "NoInstance"
ppr (GenInst ev _ s) = text "GenInst" <+> ppr ev <+> ss
where ss = text $ if s then "[safe]" else "[unsafe]"
matchClassInst, match_class_inst
:: DynFlags -> InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult
matchClassInst dflags inerts clas tys loc
= do { traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr (mkClassPred clas tys) ]
; res <- match_class_inst dflags inerts clas tys loc
; traceTcS "matchClassInst result" $ ppr res
; return res }
-- First check whether there is an in-scope Given that could
-- match this constraint. In that case, do not use top-level
-- instances. See Note [Instance and Given overlap]
match_class_inst dflags inerts clas tys loc
| not (xopt Opt_IncoherentInstances dflags)
, let matchable_givens = matchableGivens loc pred inerts
, not (isEmptyBag matchable_givens)
= do { traceTcS "Delaying instance application" $
vcat [ text "Work item=" <+> pprType pred
, text "Potential matching givens:" <+> ppr matchable_givens ]
; return NoInstance }
where
pred = mkClassPred clas tys
match_class_inst _ _ clas [ ty ] _
| className clas == knownNatClassName
, Just n <- isNumLitTy ty = makeDict (EvNum n)
| className clas == knownSymbolClassName
, Just s <- isStrLitTy ty = makeDict (EvStr s)
where
{- This adds a coercion that will convert the literal into a dictionary
of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit]
in TcEvidence. The coercion happens in 2 steps:
Integer -> SNat n -- representation of literal to singleton
SNat n -> KnownNat n -- singleton to dictionary
The process is mirrored for Symbols:
String -> SSymbol n
SSymbol n -> KnownSymbol n
-}
makeDict evLit
| Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty]
-- co_dict :: KnownNat n ~ SNat n
, [ meth ] <- classMethods clas
, Just tcRep <- tyConAppTyCon_maybe -- SNat
$ funResultTy -- SNat n
$ dropForAlls -- KnownNat n => SNat n
$ idType meth -- forall n. KnownNat n => SNat n
, Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty]
-- SNat n ~ Integer
, let ev_tm = mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep))
= return $ GenInst [] (\_ -> ev_tm) True
| otherwise
= panicTcS (text "Unexpected evidence for" <+> ppr (className clas)
$$ vcat (map (ppr . idType) (classMethods clas)))
match_class_inst _ _ clas ts _
| isCTupleClass clas
, let data_con = tyConSingleDataCon (classTyCon clas)
tuple_ev = EvDFunApp (dataConWrapId data_con) ts
= return (GenInst ts tuple_ev True)
-- The dfun is the data constructor!
match_class_inst _ _ clas [k,t] _
| className clas == typeableClassName
= matchTypeableClass clas k t
match_class_inst dflags _ clas tys loc
= do { instEnvs <- getInstEnvs
; let safeOverlapCheck = safeHaskell dflags `elem` [Sf_Safe, Sf_Trustworthy]
(matches, unify, unsafeOverlaps) = lookupInstEnv True instEnvs clas tys
safeHaskFail = safeOverlapCheck && not (null unsafeOverlaps)
; case (matches, unify, safeHaskFail) of
-- Nothing matches
([], _, _)
-> do { traceTcS "matchClass not matching" $
vcat [ text "dict" <+> ppr pred ]
; return NoInstance }
-- A single match (& no safe haskell failure)
([(ispec, inst_tys)], [], False)
-> do { let dfun_id = instanceDFunId ispec
; traceTcS "matchClass success" $
vcat [text "dict" <+> ppr pred,
text "witness" <+> ppr dfun_id
<+> ppr (idType dfun_id) ]
-- Record that this dfun is needed
; match_one (null unsafeOverlaps) dfun_id inst_tys }
-- More than one matches (or Safe Haskell fail!). Defer any
-- reactions of a multitude until we learn more about the reagent
(matches, _, _)
-> do { traceTcS "matchClass multiple matches, deferring choice" $
vcat [text "dict" <+> ppr pred,
text "matches" <+> ppr matches]
; return NoInstance } }
where
pred = mkClassPred clas tys
match_one :: SafeOverlapping -> DFunId -> [DFunInstType] -> TcS LookupInstResult
-- See Note [DFunInstType: instantiating types] in InstEnv
match_one so dfun_id mb_inst_tys
= do { checkWellStagedDFun pred dfun_id loc
; (tys, theta) <- instDFunType dfun_id mb_inst_tys
; return $ GenInst theta (EvDFunApp dfun_id tys) so }
{- Note [Instance and Given overlap]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Example, from the OutsideIn(X) paper:
instance P x => Q [x]
instance (x ~ y) => R y [x]
wob :: forall a b. (Q [b], R b a) => a -> Int
g :: forall a. Q [a] => [a] -> Int
g x = wob x
This will generate the impliation constraint:
Q [a] => (Q [beta], R beta [a])
If we react (Q [beta]) with its top-level axiom, we end up with a
(P beta), which we have no way of discharging. On the other hand,
if we react R beta [a] with the top-level we get (beta ~ a), which
is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is
now solvable by the given Q [a].
The solution is that:
In matchClassInst (and thus in topReact), we return a matching
instance only when there is no Given in the inerts which is
unifiable to this particular dictionary.
We treat any meta-tyvar as "unifiable" for this purpose,
*including* untouchable ones
The end effect is that, much as we do for overlapping instances, we
delay choosing a class instance if there is a possibility of another
instance OR a given to match our constraint later on. This fixes
Trac #4981 and #5002.
Other notes:
* The check is done *first*, so that it also covers classes
with built-in instance solving, such as
- constraint tuples
- natural numbers
- Typeable
* The given-overlap problem is arguably not easy to appear in practice
due to our aggressive prioritization of equality solving over other
constraints, but it is possible. I've added a test case in
typecheck/should-compile/GivenOverlapping.hs
* Another "live" example is Trac #10195; another is #10177.
* We ignore the overlap problem if -XIncoherentInstances is in force:
see Trac #6002 for a worked-out example where this makes a
difference.
* Moreover notice that our goals here are different than the goals of
the top-level overlapping checks. There we are interested in
validating the following principle:
If we inline a function f at a site where the same global
instance environment is available as the instance environment at
the definition site of f then we should get the same behaviour.
But for the Given Overlap check our goal is just related to completeness of
constraint solving.
-}
-- | Is the constraint for an implicit CallStack parameter?
-- i.e. (IP "name" CallStack)
isCallStackIP :: CtLoc -> Class -> [Type] -> Maybe (EvTerm -> EvCallStack)
isCallStackIP loc cls tys
| cls == ipClass
, [_ip_name, ty] <- tys
, Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` callStackTyConKey
= occOrigin (ctLocOrigin loc)
| otherwise
= Nothing
where
locSpan = ctLocSpan loc
-- We only want to grab constraints that arose due to the use of an IP or a
-- function call. See Note [Overview of implicit CallStacks]
occOrigin (OccurrenceOf n) = Just (EvCsPushCall n locSpan)
occOrigin (IPOccOrigin n) = Just (EvCsTop ('?' `consFS` hsIPNameFS n) locSpan)
occOrigin _ = Nothing
-- | Assumes that we've checked that this is the 'Typeable' class,
-- and it was applied to the correct argument.
matchTypeableClass :: Class -> Kind -> Type -> TcS LookupInstResult
matchTypeableClass clas k t
-- See Note [No Typeable for qualified types]
| isForAllTy t = return NoInstance
-- Is the type of the form `C => t`?
| isJust (tcSplitPredFunTy_maybe t) = return NoInstance
| eqType k typeNatKind = doTyLit knownNatClassName
| eqType k typeSymbolKind = doTyLit knownSymbolClassName
| Just (tc, ks) <- splitTyConApp_maybe t
, all isKind ks = doTyCon tc ks
| Just (f,kt) <- splitAppTy_maybe t = doTyApp f kt
| otherwise = return NoInstance
where
-- Representation for type constructor applied to some kinds
doTyCon tc ks =
case mapM kindRep ks of
Nothing -> return NoInstance
Just kReps ->
return $ GenInst [] (\_ -> EvTypeable (EvTypeableTyCon tc kReps) ) True
{- Representation for an application of a type to a type-or-kind.
This may happen when the type expression starts with a type variable.
Example (ignoring kind parameter):
Typeable (f Int Char) -->
(Typeable (f Int), Typeable Char) -->
(Typeable f, Typeable Int, Typeable Char) --> (after some simp. steps)
Typeable f
-}
doTyApp f tk
| isKind tk
= return NoInstance -- We can't solve until we know the ctr.
| otherwise
= return $ GenInst [mk_typeable_pred f, mk_typeable_pred tk]
(\[t1,t2] -> EvTypeable $ EvTypeableTyApp (EvId t1,f) (EvId t2,tk))
True
-- Representation for concrete kinds. We just use the kind itself,
-- but first check to make sure that it is "simple" (i.e., made entirely
-- out of kind constructors).
kindRep ki = do (_,ks) <- splitTyConApp_maybe ki
mapM_ kindRep ks
return ki
-- Emit a `Typeable` constraint for the given type.
mk_typeable_pred ty = mkClassPred clas [ typeKind ty, ty ]
-- Given KnownNat / KnownSymbol, generate appropriate sub-goal
-- and make evidence for a type-level literal.
doTyLit c = do clas <- tcLookupClass c
let p = mkClassPred clas [ t ]
return $ GenInst [p] (\[i] -> EvTypeable
$ EvTypeableTyLit (EvId i,t)) True
{- Note [No Typeable for polytype or for constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We do not support impredicative typeable, such as
Typeable (forall a. a->a)
Typeable (Eq a => a -> a)
Typeable (() => Int)
Typeable (((),()) => Int)
See Trac #9858. For forall's the case is clear: we simply don't have
a TypeRep for them. For qualified but not polymorphic types, like
(Eq a => a -> a), things are murkier. But:
* We don't need a TypeRep for these things. TypeReps are for
monotypes only.
* Perhaps we could treat `=>` as another type constructor for `Typeable`
purposes, and thus support things like `Eq Int => Int`, however,
at the current state of affairs this would be an odd exception as
no other class works with impredicative types.
For now we leave it off, until we have a better story for impredicativity.
-}
| ml9951/ghc | compiler/typecheck/TcInteract.hs | bsd-3-clause | 83,885 | 29 | 22 | 24,666 | 12,484 | 6,440 | 6,044 | -1 | -1 |
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
module Parse.Type where
import Control.Applicative ((<$>),(<*>),(<*))
import Data.List (intercalate)
import Text.Parsec ((<|>), (<?>), char, many, optionMaybe, string, try)
import qualified AST.Type as T
import qualified AST.Variable as Var
import Parse.Helpers
tvar :: IParser T.RawType
tvar =
T.Var <$> lowVar <?> "type variable"
tuple :: IParser T.RawType
tuple =
do ts <- parens (commaSep expr)
case ts of
[t] -> return t
_ -> return (T.tupleOf ts)
record :: IParser T.RawType
record =
do char '{'
whitespace
rcrd <- extended <|> normal
dumbWhitespace
char '}'
return rcrd
where
normal = flip T.Record Nothing <$> commaSep field
-- extended record types require at least one field
extended = do
ext <- try (lowVar <* (whitespace >> string "|"))
whitespace
flip T.Record (Just (T.Var ext)) <$> commaSep1 field
field = do
lbl <- rLabel
whitespace >> hasType >> whitespace
(,) lbl <$> expr
capTypeVar :: IParser String
capTypeVar =
intercalate "." <$> dotSep1 capVar
constructor0 :: IParser T.RawType
constructor0 =
do name <- capTypeVar
return (T.Type (Var.Raw name))
term :: IParser T.RawType
term =
tuple <|> record <|> tvar <|> constructor0
app :: IParser T.RawType
app =
do f <- constructor0 <|> try tupleCtor <?> "type constructor"
args <- spacePrefix term
case args of
[] -> return f
_ -> return (T.App f args)
where
tupleCtor = do
n <- length <$> parens (many (char ','))
let ctor = "_Tuple" ++ show (if n == 0 then 0 else n+1)
return (T.Type (Var.Raw ctor))
expr :: IParser T.RawType
expr =
do t1 <- app <|> term
arr <- optionMaybe $ try (whitespace >> arrow)
case arr of
Just _ -> T.Lambda t1 <$> (whitespace >> expr)
Nothing -> return t1
constructor :: IParser (String, [T.RawType])
constructor =
(,) <$> (capTypeVar <?> "another type constructor")
<*> spacePrefix term
| avh4/elm-compiler | src/Parse/Type.hs | bsd-3-clause | 2,080 | 0 | 16 | 546 | 755 | 383 | 372 | 66 | 3 |
module KeepCafs2 where
import KeepCafsBase
foreign export ccall "getX"
getX :: IO Int
getX :: IO Int
getX = return (x + 1)
| sdiehl/ghc | testsuite/tests/rts/KeepCafs2.hs | bsd-3-clause | 128 | 0 | 7 | 28 | 45 | 25 | 20 | 6 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-@ LIQUID "--c-files=../ffi-include/foo.c" @-}
{-@ LIQUID "-i../ffi-include" @-}
module Main where
import Foreign.C.Types
{-@ embed CInt as int @-}
{-@ embed Integer as int @-}
{-@ assume c_foo :: x:{CInt | x > 0} -> IO {v:CInt | v = x} @-}
foreign import ccall unsafe "foo.c foo" c_foo
:: CInt -> IO CInt
main :: IO ()
main = print . fromIntegral =<< c_foo 1
| mightymoose/liquidhaskell | tests/pos/FFI.hs | bsd-3-clause | 409 | 0 | 7 | 76 | 63 | 37 | 26 | 7 | 1 |
{-# LANGUAGE DataKinds, PolyKinds #-}
module T14209 where
data MyProxy k (a :: k) = MyProxy
data Foo (z :: MyProxy k (a :: k))
| sdiehl/ghc | testsuite/tests/polykinds/T14209.hs | bsd-3-clause | 128 | 0 | 8 | 26 | 41 | 27 | 14 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE RankNTypes #-}
module ShouldSucceed where
data Empty q = Empty (forall a. Ord a => q a)
q :: (Ord a) => [a]
q = []
e0, e1, e2 :: Empty []
e0 = Empty []
e1 = Empty ([] :: (Ord a) => [a])
e2 = Empty q
| olsner/ghc | testsuite/tests/typecheck/should_compile/tc092.hs | bsd-3-clause | 458 | 0 | 10 | 249 | 118 | 68 | 50 | 10 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : GHC.ExecutionStack
-- Copyright : (c) The University of Glasgow 2013-2015
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- This is a module for efficient stack traces. This stack trace implementation
-- is considered low overhead. Basic usage looks like this:
--
-- @
-- import GHC.ExecutionStack
--
-- myFunction :: IO ()
-- myFunction = do
-- putStrLn =<< showStackTrace
-- @
--
-- Your GHC must have been built with @libdw@ support for this to work.
--
-- @
-- user@host:~$ ghc --info | grep libdw
-- ,("RTS expects libdw","YES")
-- @
--
-- @since 4.9.0.0
-----------------------------------------------------------------------------
module GHC.ExecutionStack (
Location (..)
, SrcLoc (..)
, getStackTrace
, showStackTrace
) where
import Control.Monad (join)
import GHC.ExecutionStack.Internal
-- | Get a trace of the current execution stack state.
--
-- Returns @Nothing@ if stack trace support isn't available on host machine.
getStackTrace :: IO (Maybe [Location])
getStackTrace = (join . fmap stackFrames) `fmap` collectStackTrace
-- | Get a string representation of the current execution stack state.
showStackTrace :: IO (Maybe String)
showStackTrace = fmap (\st -> showStackFrames st "") `fmap` getStackTrace
| tolysz/prepare-ghcjs | spec-lts8/base/GHC/ExecutionStack.hs | bsd-3-clause | 1,463 | 0 | 9 | 243 | 157 | 106 | 51 | 11 | 1 |
{-# LANGUAGE TypeFamilies #-}
module T11408 where
type family UL a
type family UR a
type family MT a b
mkMerge :: a -> UL a -> UR a -> Int
mkMerge = undefined
merger :: a -> b -> MT a b
merger = undefined
{-
merge ::
forall a b. (UL (MT a b) ~ a, UR (MT a b) ~ b) => a -> b -> Int
or
forall t. (MT (UL t) (UR t) ~ t) => UL t -> UR t -> Int
These types are equivalent, and in fact neither is ambiguous,
but the solver has to work quite hard to prove that.
-}
merge x y = mkMerge (merger x y) x y
| ezyang/ghc | testsuite/tests/indexed-types/should_compile/T11408.hs | bsd-3-clause | 502 | 0 | 8 | 127 | 101 | 56 | 45 | 10 | 1 |
module T7312 where
-- this works
mac :: Double -> (Double->Double) -> (Double-> Double)
mac ac m = \ x -> ac + x * m x
-- this doesn't
mac2 :: Double -> (->) Double Double -> (->) Double Double
mac2 ac m = \ x -> ac + x * m x
| wxwxwwxxx/ghc | testsuite/tests/typecheck/should_compile/T7312.hs | bsd-3-clause | 228 | 0 | 8 | 56 | 114 | 61 | 53 | 5 | 1 |
module Main where
import GHC.Conc
-- Create a new TVar, update it and check that it contains the expected value after the
-- transaction
main = do
putStr "Before\n"
t <- atomically ( newTVar 42 )
atomically ( writeTVar t 17 )
r <- atomically ( readTVar t )
putStr ("After " ++ (show r) ++ "\n")
| wxwxwwxxx/ghc | testsuite/tests/concurrent/should_run/conc043.hs | bsd-3-clause | 318 | 0 | 12 | 80 | 91 | 44 | 47 | 8 | 1 |
{-# LANGUAGE CPP, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module System.Process.Text.Lazy where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.DeepSeq (force)
import qualified Control.Exception as C (evaluate)
import Data.ListLike.IO (hGetContents)
import Data.Text.Lazy (Text, fromStrict, toChunks)
import Prelude hiding (null)
import System.Process
import System.Process.Common
import System.Exit (ExitCode)
instance ProcessText Text Char
-- | Like 'System.Process.readProcessWithExitCode', but using 'Text'
instance ListLikeProcessIO Text Char where
forceOutput = C.evaluate . force
readChunks h = (map fromStrict . toChunks) <$> hGetContents h
-- | Specialized version for backwards compatibility.
readProcessWithExitCode
:: FilePath -- ^ command to run
-> [String] -- ^ any arguments
-> Text -- ^ standard input
-> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readProcessWithExitCode = System.Process.Common.readProcessWithExitCode
readCreateProcessWithExitCode
:: CreateProcess -- ^ command and arguments to run
-> Text -- ^ standard input
-> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr
readCreateProcessWithExitCode = System.Process.Common.readCreateProcessWithExitCode
| seereason/process-extras | src/System/Process/Text/Lazy.hs | mit | 1,392 | 0 | 9 | 275 | 244 | 150 | 94 | 27 | 1 |
module Exercises where
tensDigit :: Integral a => a -> a
tensDigit x = d
where
(xLast, _) = x `divMod` 10
d = xLast `mod` 10
foldBool :: a -> a -> Bool -> a
foldBool x y z =
case z of
True -> x
False -> y
foldBool2 :: a -> a -> Bool -> a
foldBool2 x y z
| z == True = x
| otherwise = y
g :: (a -> b) -> (a, c) -> (b, c)
g aTob (a, c) = (aTob a, c)
| andrewMacmurray/haskell-book-solutions | src/ch7/exercises.hs | mit | 388 | 0 | 8 | 132 | 209 | 113 | 96 | 16 | 2 |
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
module Main where
import System.Random.TF.Init
import Types
import Encode
import Mix
import Melody.GameOfThrones
import Generator.Sin
import Generator.Rand
import Generator.KarplusStrong
import Envelope.ADSR
settings :: MixSettings
settings = MixSettings
{ mixGenerator = generatorKarplusStrong
, mixTempo = 0.35
, mixLoudness = 0.1
, mixEnvelope = envelopeADSR 0.01 0.2 0.7 2.5
}
main = do
g <- initTFGen
encodeAndWrite "test.pcm" . mix settings g $ gameOfThrones
| feuerbach/music | Main.hs | mit | 556 | 0 | 9 | 84 | 122 | 71 | 51 | 20 | 1 |
scoreToLetter :: Int -> Char
scoreToLetter n
| n > 90 = 'A'
| n > 80 = 'B'
| n > 70 = 'C'
| otherwise = 'F'
len [] = 0
len (x:s) = 1 + len s
listCopy [] = []
listCopy (x:s) = x : listCopy s
ones = 1 : ones
twos = 2 : twos
lists = [ones, twos]
front :: Int -> [a] -> [a]
front _ [] = []
front 0 (x:s) = []
front n (x:s) = x : front (n-1) s
tB :: [String] -> [Int] -> [(String, Int)]
tB [] _ = []
tB (f:fs) (b:bs) = (f,b) : tB fs bs
timeBonuses finishers =
tB finishers ([20, 12, 8] ++ cycle[0])
zipOp :: (a -> b -> c) -> [a] -> [b] -> [c]
zipOp f [] _ = []
zipOp f _ [] = []
zipOp f (a:as) (b:bs) = (f a b) : zipOp f as bs
myZip = zipOp (\ a b -> (a,b))
seed = [1, 1]
ouput = zipOp (+) seed (tail seed)
fibs = 1 : 1 : zipOp (+) fibs (tail fibs)
type Identifier = String
type Value = Int
type Env = [(Identifier, Value)]
data WAE = Num Int
| Add WAE WAE
| Id Identifier
| With Identifier WAE WAE
mlookup :: Identifier -> Env -> Value
mlookup var ((i,v):r)
| (var == i) = v
| otherwise = mlookup var r
extend :: Env -> Identifier -> Value -> Env
extend env i v = (i,v):env
--interp :: WAE -> Env -> Value
interp (Num n) env = n
interp (Add lhs rhs) env = interp lhs env + interp rhs env
interp (Id i) env = mlookup i env
interp (With bound_id named_expr bound_body) env =
interp bound_body
(extend env bound_id (interp named_expr env))
| hectoregm/lenguajes | class-notes/class-notes-30-september.hs | mit | 1,452 | 0 | 9 | 426 | 828 | 438 | 390 | 49 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Gaia.SearchEngine (
runQuery2,
runQuery3
) where
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.List as D
import qualified Gaia.AesonValuesFileSystemCorrespondance as XP1
import qualified Gaia.AesonValuesAionPointAbstractionsCorrespondance as XP2
import qualified Gaia.Directives as GD
import qualified Gaia.FSRootsManagement as FSM
import qualified Gaia.GeneralUtils as GU
import qualified Gaia.ScanningAndRecordingManager as SRM
import Gaia.Types
import qualified PStorageServices.ContentAddressableStore as CAS
import qualified System.FilePath as FS
import System.IO.Unsafe (unsafePerformIO)
-- -----------------------------------------------------------
-- Utils
-- -----------------------------------------------------------
isInfixOfCaseIndependent2 :: String -> String -> Bool
isInfixOfCaseIndependent2 pattern name = D.isInfixOf (GU.stringToLower pattern) (GU.stringToLower name)
shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives :: LocationPath -> [GD.GaiaFileDirective] -> String -> Bool
shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives _ parsedirectives pattern =
any (\directive ->
case directive of
GaiaFileDirective GaiaFileTag body -> isInfixOfCaseIndependent2 pattern body
) parsedirectives
casKeyToAionName :: String -> IO (Maybe String)
casKeyToAionName key = do
aionPointAsByteString <- CAS.get key
case aionPointAsByteString of
Nothing -> return Nothing
Just aionPointAsByteString' -> do
let aesonValue = XP1.convertJSONStringIntoAesonValue (Char8.unpack aionPointAsByteString')
case aesonValue of
Nothing -> return Nothing
Just aesonValue' -> do
let x1 = XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric (ExtendedAesonValue aesonValue' key)
return $ Just (extractNameFromAionExtendedPointAbstractionGeneric x1)
where
extractNameFromAionExtendedPointAbstractionGeneric (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromFile (AionPointAbstractionFile filename _ _)) _) = filename
extractNameFromAionExtendedPointAbstractionGeneric (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromDirectory (AionPointAbstractionDirectory foldername _)) _) = foldername
-- -----------------------------------------------------------
-- Aion Points Recursive Analysis
-- -----------------------------------------------------------
{-
Each Aion point is a location of the File System
Therefore each Aeson Value is a location of the file system
In the below <current path> is the full FS path to the object (which is not known by the object itself and must be computed recursively from some root)
-}
{-
extractLocationPathsForAesonValueFileAndPatternAndLocationPath :: A.Value -> String -> LocationPath -> IO [ LocationPath ]
extractLocationPathsForAesonValueFileAndPatternAndLocationPath aesonValueFile pattern locationpath =
do
let tap = XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric aesonValueFile
if name1 tap =="gaia"
then do
-- parseDirectivesFile :: FilePath -> MaybeT IO [Directive]
directives <- GD.parseDirectivesFile locationpath
if shouldRetainThisLocationPathAsDirectoryGivenTheseGaiaDirectives locationpath directives pattern
then
return [ FS.takeDirectory locationpath ]
else
return []
else
if isInfixOfCaseIndependent2 pattern (name1 tap)
then
return [ locationpath ]
else
return []
-}
extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath :: AionPointAbstractionFile -> String -> LocationPath -> String -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath (AionPointAbstractionFile filename _ _) pattern locationpath caskey = do
if isInfixOfCaseIndependent2 pattern filename
then
return [ SEAtom locationpath caskey ]
else
return []
extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath :: AionPointAbstractionDirectory -> String -> LocationPath -> String -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath (AionPointAbstractionDirectory foldername caskeys) pattern locationpath caskey = do
let x1 = map (\xcaskey -> do
maybename <- casKeyToAionName xcaskey
case maybename of
Nothing -> return []
-- extractSEAtomForAionCASKeyAndPatternAndLocationPath :: String -> String -> LocationPath -> IO [LocationPath]
-- extractSEAtomForAionCASKeyAndPatternAndLocationPath <aion cas hash> <search pattern> <current path>
Just name -> extractSEAtomForAionCASKeyAndPatternAndLocationPath xcaskey pattern (FS.normalise $ FS.joinPath [locationpath, name])
) caskeys
-- x1 :: [IO [SEAtom]]
let x2 = sequence x1
-- x2 :: IO [[SEAtom]]
let x3 = fmap concat x2
-- x3 :: IO [SEAtom]
if isInfixOfCaseIndependent2 pattern foldername
then do
x4 <- x3
return $ (SEAtom locationpath caskey) : x4
else
x3
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 :: ExtendedAionPointAbstractionGeneric -> String -> LocationPath -> IO [SEAtom]
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromFile taionpointfile) caskey) pattern locationpath = extractLocationPathsForAionPointAbstractionFileAndPatternAndLocationPath taionpointfile pattern locationpath caskey
extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (ExtendedAionPointAbstractionGeneric (AionPointAbstractionGenericFromDirectory taionpointdirectory) caskey) pattern locationpath = extractLocationPathsForAionPointAbstractionDirectoryAndPatternAndLocationPath taionpointdirectory pattern locationpath caskey
extractSEAtomForAionCASKeyAndPatternAndLocationPath :: String -> String -> LocationPath -> IO [SEAtom]
extractSEAtomForAionCASKeyAndPatternAndLocationPath aion_cas_hash pattern locationpath = do
aionJSONValueAsString <- XP1.getAionJSONStringForCASKey3 aion_cas_hash
case aionJSONValueAsString of
Nothing -> return []
Just aionJSONValueAsString' -> do
let aionJSONValue = XP1.convertJSONStringIntoAesonValue aionJSONValueAsString'
case aionJSONValue of
Nothing -> return []
Just aionJSONValue' -> extractLocationPathsForAionPointAbstractionGenericAndPatternAndLocationPath2 (XP2.extendedAesonValueToExtendedAionPointAbstractionGeneric (ExtendedAesonValue aionJSONValue' aion_cas_hash)) pattern locationpath
-- -----------------------------------------------------------
-- Running queries against Merkle Roots
-- -----------------------------------------------------------
{-
The Merkle root refers to a particular aion snapshot of the file system.
The fsroot is used to recursively construct paths.
Paths returned by the process are essentially the fsroot and recursively locationnames constructed by looking up the aion points.
This is due to the fact that the Merkle root doesn't know which node of the file system (fsroot) it represents.
The pattern is the search query.
-}
runQueryAgainMerkleRootUsingStoredData :: LocationPath -> String -> String -> IO [SEAtom]
runQueryAgainMerkleRootUsingStoredData fsroot merkleroot pattern =
extractSEAtomForAionCASKeyAndPatternAndLocationPath merkleroot pattern fsroot
-- -----------------------------------------------------------
-- Search Engine Interface
-- -----------------------------------------------------------
runQuery1 :: String -> IO [SEAtom]
runQuery1 pattern = do
-- getFSScanRoots :: IO [String]
scanroots <- FSM.getFSScanRoots
let x = map (\scanroot -> do
merkleroot <- SRM.getCurrentMerkleRootForFSScanRoot scanroot
case merkleroot of
Nothing -> return []
Just merkleroot' -> runQueryAgainMerkleRootUsingStoredData scanroot merkleroot' pattern
) scanroots
-- x :: [IO [SEAtom]]
fmap concat ( sequence x )
runQuery2 :: String -> [SEAtom]
runQuery2 pattern = unsafePerformIO $ runQuery1 pattern
runQuery3 :: String -> [SEAtom]
runQuery3 pattern = unsafePerformIO $ runQuery1 pattern
| shtukas/Gaia | src/Gaia/SearchEngine.hs | mit | 9,015 | 15 | 34 | 1,910 | 1,201 | 611 | 590 | 89 | 4 |
main = putStrLn "Hello World"
//added some comments
//showing how to do stuff
| Yelmogus/Lambda_Interpreter | HW1.hs | mit | 78 | 5 | 7 | 13 | 38 | 14 | 24 | 1 | 1 |
{- Copyright (C) 2015 Calvin Beck
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Text.MathForm.Readers.Sage where
import Text.MathForm.MathTypes
import Text.MathForm.Readers.SageTokens
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Text
import Control.Monad
import Control.Monad.Identity
import qualified Data.Text as T
parseSage :: Parser MathForm
parseSage = buildExpressionParser table term
term :: Parser MathForm
term = parens parseSage
<|> fmap (either IntLit FloatLit) naturalOrFloat
<|> liftM Symbol identifier
-- | https://hackage.haskell.org/package/parsec-3.1.9/docs/Text-Parsec-Expr.html
-- is pretty much exactly what we need here.
table :: OperatorTable T.Text st Identity MathForm
table = [ [binary "**" Pow AssocLeft, binary "^" Pow AssocLeft]
, [prefix "-" Neg, prefix "+" Pos]
, [binary "*" Mult AssocLeft, binary "/" Div AssocLeft]
, [binary "+" Plus AssocLeft, binary "-" Sub AssocLeft]
]
binary name fun = Infix (do { reservedOp name; return fun })
prefix name fun = Prefix (do { reservedOp name; return fun })
postfix name fun = Postfix (do { reservedOp name; return fun })
| Chobbes/mathform | src/Text/MathForm/Readers/Sage.hs | mit | 2,207 | 0 | 9 | 422 | 322 | 173 | 149 | 23 | 1 |
module HaskellBook.Case where
funcZ x =
case x + 1 == 1 of
True -> "AWESOME"
False -> "wut"
pal xs =
case xs == reverse xs of
True -> "yes"
False -> "no"
pal' xs =
case y of
True -> "yes"
False -> "no"
where y = xs == reverse xs
| brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/Case.hs | mit | 278 | 0 | 8 | 102 | 107 | 54 | 53 | 14 | 2 |
module Reader (reader, toPandoc) where
import qualified Data.Text as T
import Text.Pandoc.Class (runIOorExplode)
import Text.Pandoc.Definition (Pandoc)
import Text.Pandoc.Options
import Text.Pandoc.Readers.Markdown (readMarkdown)
reader :: ReaderOptions
reader = def
{ readerStandalone = True
, readerExtensions = disableExtension Ext_pandoc_title_block
. disableExtension Ext_yaml_metadata_block
. disableExtension Ext_table_captions
$ pandocExtensions
}
toPandoc :: String -> IO Pandoc
toPandoc = runIOorExplode . readMarkdown reader . T.pack
| Thhethssmuz/ppp | src/Reader.hs | mit | 617 | 0 | 10 | 131 | 135 | 79 | 56 | 15 | 1 |
-- | http://www2.stetson.edu/~efriedma/mathmagic/0916.html
-- On an N×N chessboard, when we place Q queens,
-- what is the maximum number of squares
-- that can be attacked exactly A times?
{-# language LambdaCase #-}
import Prelude hiding ((&&),(||),not,and,or)
import qualified Prelude as P
import OBDD
import OBDD.Linopt
import Data.Ix (inRange)
import qualified Data.Array as A
import Control.Monad ( guard )
import System.Environment ( getArgs )
import Data.List (sort)
import qualified Data.Map.Strict as M
main = getArgs >>= \ case
[] -> run 6 2 0
[n,q,a] -> run (read n) (read q) (read a)
run n q a = putStrLn $ form n q a
$ linopt ( board n q a )
$ M.fromList
$ zip ((\ p -> Var p Attacked) <$> positions n) (repeat 1)
++ zip ((\ p -> Var p Queen) <$> positions n) (repeat 0)
type Position = (Int,Int)
positions :: Int -> [ Position ]
positions n = (,) <$> [1..n] <*> [1..n]
data Type = Attacked | Queen deriving (Eq, Ord, Show)
data Var = Var !Position !Type deriving (Eq, Ord, Show)
type Bit = OBDD Var
queen p = variable $ Var p Queen
attacked p = variable $ Var p Attacked
header n q a w = unwords
[ "n =", show n
, "q =", show q
, "a =", show a
, "m =", show w
]
form n q a (Just (w,m)) = unlines $ header n q a w : do
row <- [1..n]
return $ do
col <- [1..n]
let c = if m M.! Var (row,col) Queen then 'Q'
else if m M.! Var (row,col) Attacked then '+'
else '.'
[ c, ' ' ]
for = flip map
board :: Int -> Int -> Int -> Bit
board n q a = let r = ray n in and
$ ( exactly q $ queen <$> positions n )
: ( for ( positions n) $ \ p ->
(not $ queen p) || (not $ attacked p) )
++ ( for (positions n) $ \ p -> attacked p ==>
( exactly a $ for directions $ \ d -> r A.! (d,p)))
-- | ray n ! (d,p) == looking in direction d from p,
-- there is (at least one) queen (which might be on p)
ray n =
let bounds = (((-1,-1),(1,1)),((1,1),(n,n)))
result = A.array bounds $ do
(d,p) <- A.range bounds
let q = shift d p
return ( (d,p)
, queen p
|| if onboard n q then result A.! (d,q) else false
)
in result
directions = filter (/= (0,0))
$ (,) <$> [ -1 .. 1 ] <*> [ -1 .. 1 ]
onboard n (x,y) = inRange (1,n) x P.&& inRange (1,n) y
shift (dx,dy) (x,y) = (x+dx,y+dy)
exactly :: Int -> [Bit] -> Bit
exactly k xs =
if k <= 8 P.&& length xs <= 8
then exactly_direct k xs
else exactly_rectangle k xs
exactly_rectangle n xs = last $
foldl ( \ cs x -> zipWith ( \ a b -> choose a b x )
cs (false : cs)
) (true : replicate n false) xs
exactly_direct k xs = atmost k xs && atleast k xs
atmost k xs = not $ atleast (k+1) xs
atleast k xs = or $ for (select k xs) and
select 0 xs = return []
select k [] = []
select k (x:xs) = select k xs ++ ( (x:) <$> select (k-1) xs )
| jwaldmann/haskell-obdd | examples/MM0916.hs | gpl-2.0 | 2,962 | 24 | 18 | 892 | 1,453 | 752 | 701 | -1 | -1 |
module Matrizer.Util
( optimizeStr,
doParse,
doOptimize,
parseFile,
runDebug,
equivCheck
) where
import qualified Data.Map as Map
import Matrizer.MTypes
import Matrizer.Parsing
import Matrizer.Optimization
import Matrizer.RewriteRules
import Matrizer.Analysis
import Matrizer.Preprocess
import Matrizer.CodeGen
import Matrizer.Equivalence
import Control.Monad
---------------------------------------------------------------
fakeSymbols :: SymbolTable
fakeSymbols = Map.fromList [("A", (Matrix 1000 1000 [], Nothing)), ("B", (Matrix 1000 1000 [], Nothing)), ("x", (Matrix 1000 1 [], Nothing))]
fakeTree :: Expr
fakeTree = Branch2 MProduct (Branch2 MProduct (Leaf "A") (Leaf "B") ) (Leaf "x")
doParse :: String -> ThrowsError (SymbolTable, Expr, Maybe Int)
doParse inp = do (tbl, tree) <- readInput inp
prgm <- preprocess tree tbl
matr <- typeCheck prgm tbl
case treeFLOPs prgm tbl of
(Right flops) -> return $ (tbl, prgm, Just flops)
(Left err) -> return $ (tbl, prgm, Nothing)
showBeam [] = ""
showBeam ((BeamNode expr n _ _):beam) = "**** " ++ (show n) ++ "\n" ++ pprint expr ++ "\n" ++ (showBeam beam)
runDebug :: SymbolTable -> Expr -> IO ()
runDebug tbl prgm = let beams = beamSearchDebug treeFLOPs optimizationRules 5 20 4 tbl [(BeamNode prgm 0 "init" Nothing)] in
case beams of
(Left err) -> putStrLn (show err)
(Right bbeams) -> void $ mapM writeBeam (zip [1..(length bbeams)] bbeams)
where writeBeam (n, beam) = writeFile ("beam" ++ show n) (showBeam beam)
doOptimize :: String -> Int -> Int -> Int -> ThrowsError (Expr, Expr, Expr, Int, Int, BeamNode)
doOptimize prgm iters beamSize nRewrites =
do (tbl, tree, mflops) <- doParse prgm
ctree <- makeConcrete tbl tree
flops <- treeFLOPs ctree tbl
node <- beamSearchWrapper treeFLOPs iters beamSize nRewrites tbl ctree
let (BeamNode optTree oflops _ _) = node in
return $ (tree, ctree, optTree, flops, oflops, node)
loadConcrete :: String -> ThrowsError (SymbolTable, Expr)
loadConcrete str = do (tbl, tree, mflops) <- doParse str
ctree <- makeConcrete tbl tree
return $ (tbl, ctree)
-- read two files
-- show what they're both parsed as
equivCheck :: String -> String -> ThrowsError String
equivCheck s1 s2 = do (tbl1, ctree1) <- loadConcrete s1
(tbl2, ctree2) <- loadConcrete s2
let equiv = testEquivalence tbl1 ctree1 ctree2
return $ "First concrete:\n" ++ (pprint ctree1) ++ "\nSecond concrete:\n" ++ (pprint ctree2) ++ "\nequivalence check: " ++ (show equiv)
dumpInfo :: SymbolTable -> Expr -> ThrowsError String
dumpInfo tbl raw_prgm = do prgm <- preprocess raw_prgm tbl
matr <- typeCheck prgm tbl
ctree <- makeConcrete tbl prgm
cmatr <- typeCheck ctree tbl
flops <- treeFLOPs ctree tbl
optimizedBN <- optimize ctree tbl
let (BeamNode optPrgm oflops _ _) = optimizedBN in
return $ "Preamble symbol table: " ++ show tbl ++ "\nCode parsed as:\n" ++ pprint prgm ++ (if (ctree == prgm) then "" else "\nTransformed to concrete expression: " ++ pprint ctree ++ "\nType comparison: " ++ (show matr) ++ " vs " ++ (show cmatr)) ++ "\nNaive FLOPs required: " ++ show flops ++ "\nNaive code generated:\n" ++ generateNumpy ctree ++ "\n\noptimizations:\n" ++ pprintOptPath optimizedBN ++ "\n\nOptimized FLOPs required: " ++ show oflops ++"\nOptimized program:\n" ++ pprint optPrgm ++ "\nOptimized code generated:\n" ++ generateNumpy optPrgm
dumpRaw tbl raw_prgm = do prgm <- preprocess raw_prgm tbl
flops <- treeFLOPs prgm tbl
return $ "Preamble symbol table: " ++ show tbl ++ "\nCode parsed as:\n" ++ pprint prgm ++ "\nNaive FLOPs required: " ++ show flops ++ "\nNaive code generated:\n" ++ generateNumpy prgm
errorStr :: ThrowsError String -> String
errorStr ts = case ts of
Left err -> show err
Right s -> s
optimizeStr :: String -> String
optimizeStr inp = case readInput inp of
Left err -> show err
Right (tbl, tree) -> errorStr $ dumpInfo tbl tree
parseFile :: String -> IO (SymbolTable, Expr)
parseFile fname = do contents <- readFile fname
let Right (tbl, tree, mflops) = doParse contents
return $ (tbl, tree) | davmre/matrizer | src/Matrizer/Util.hs | gpl-2.0 | 4,772 | 0 | 29 | 1,428 | 1,481 | 744 | 737 | 77 | 2 |
{-# OPTIONS -Wall #-}
-- | Options parsing
module Opts
( Opts(..), parseOpts
) where
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import Data.Time.Clock (NominalDiffTime)
import qualified Git.CLI as Git
import Options.Applicative
data Opts = Opts
{ optsPollInterval :: NominalDiffTime
, optsRepoPath :: Git.RepoPath
} deriving (Show)
defaultPollInterval :: NominalDiffTime
defaultPollInterval = 20
desc :: String
desc =
intercalate "\n"
[ "Run a git push-q"
, ""
, "<TODO>"
]
opt :: Read a => Mod OptionFields a -> Parser (Maybe a)
opt = optional . option auto
strOpt :: Mod OptionFields String -> Parser (Maybe String)
strOpt = optional . strOption
fromDouble :: Fractional a => Double -> a
fromDouble = realToFrac
parser :: Parser Opts
parser =
Opts
<$> (maybe defaultPollInterval fromDouble
<$> opt (long "interval" <> metavar "interval" <> help "poll interval in (fractional) seconds"))
<*> (fromMaybe "." <$> strOpt (long "path" <> metavar "repopath" <> help "The path to the git repo"))
parseOpts :: IO Opts
parseOpts =
execParser $
info (helper <*> parser)
(fullDesc <> progDesc desc <> header "buildsome - build an awesome project")
| Peaker/git-pushq | Opts.hs | gpl-2.0 | 1,279 | 0 | 13 | 301 | 356 | 191 | 165 | 37 | 1 |
{-| Implementation of the Ganeti configuration database.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Ganeti.Config
( LinkIpMap
, NdParamObject(..)
, loadConfig
, saveConfig
, getNodeInstances
, getNodeRole
, getNodeNdParams
, getDefaultNicLink
, getDefaultHypervisor
, getInstancesIpByLink
, getMasterNodes
, getMasterCandidates
, getMasterOrCandidates
, getMasterNetworkParameters
, getOnlineNodes
, getNode
, getInstance
, getDisk
, getGroup
, getGroupNdParams
, getGroupIpolicy
, getGroupDiskParams
, getGroupNodes
, getGroupInstances
, getGroupOfNode
, getInstPrimaryNode
, getInstMinorsForNode
, getInstAllNodes
, getInstDisks
, getInstDisksFromObj
, getDrbdMinorsForInstance
, getFilledInstHvParams
, getFilledInstBeParams
, getFilledInstOsParams
, getNetwork
, MAC
, getAllMACs
, getAllDrbdSecrets
, NodeLVsMap
, getInstanceLVsByNode
, getAllLVs
, buildLinkIpInstnameMap
, instNodes
) where
import Control.Applicative
import Control.Monad
import Control.Monad.State
import qualified Data.Foldable as F
import Data.List (foldl', nub)
import Data.Monoid
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Text.JSON as J
import System.IO
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.Errors
import Ganeti.JSON
import Ganeti.Objects
import Ganeti.Types
import qualified Ganeti.Utils.MultiMap as MM
-- | Type alias for the link and ip map.
type LinkIpMap = M.Map String (M.Map String String)
-- * Operations on the whole configuration
-- | Reads the config file.
readConfig :: FilePath -> IO (Result String)
readConfig = runResultT . liftIO . readFile
-- | Parses the configuration file.
parseConfig :: String -> Result ConfigData
parseConfig = fromJResult "parsing configuration" . J.decodeStrict
-- | Encodes the configuration file.
encodeConfig :: ConfigData -> String
encodeConfig = J.encodeStrict
-- | Wrapper over 'readConfig' and 'parseConfig'.
loadConfig :: FilePath -> IO (Result ConfigData)
loadConfig = fmap (>>= parseConfig) . readConfig
-- | Wrapper over 'hPutStr' and 'encodeConfig'.
saveConfig :: Handle -> ConfigData -> IO ()
saveConfig fh = hPutStr fh . encodeConfig
-- * Query functions
-- | Computes the nodes covered by a disk.
computeDiskNodes :: Disk -> S.Set String
computeDiskNodes dsk =
case diskLogicalId dsk of
LIDDrbd8 nodeA nodeB _ _ _ _ -> S.fromList [nodeA, nodeB]
_ -> S.empty
-- | Computes all disk-related nodes of an instance. For non-DRBD,
-- this will be empty, for DRBD it will contain both the primary and
-- the secondaries.
instDiskNodes :: ConfigData -> Instance -> S.Set String
instDiskNodes cfg inst =
case getInstDisksFromObj cfg inst of
Ok disks -> S.unions $ map computeDiskNodes disks
Bad _ -> S.empty
-- | Computes all nodes of an instance.
instNodes :: ConfigData -> Instance -> S.Set String
instNodes cfg inst = instPrimaryNode inst `S.insert` instDiskNodes cfg inst
-- | Computes the secondary nodes of an instance. Since this is valid
-- only for DRBD, we call directly 'instDiskNodes', skipping over the
-- extra primary insert.
instSecondaryNodes :: ConfigData -> Instance -> S.Set String
instSecondaryNodes cfg inst =
instPrimaryNode inst `S.delete` instDiskNodes cfg inst
-- | Get instances of a given node.
-- The node is specified through its UUID.
getNodeInstances :: ConfigData -> String -> ([Instance], [Instance])
getNodeInstances cfg nname =
let all_inst = M.elems . fromContainer . configInstances $ cfg
pri_inst = filter ((== nname) . instPrimaryNode) all_inst
sec_inst = filter ((nname `S.member`) . instSecondaryNodes cfg) all_inst
in (pri_inst, sec_inst)
-- | Computes the role of a node.
getNodeRole :: ConfigData -> Node -> NodeRole
getNodeRole cfg node
| nodeUuid node == clusterMasterNode (configCluster cfg) = NRMaster
| nodeMasterCandidate node = NRCandidate
| nodeDrained node = NRDrained
| nodeOffline node = NROffline
| otherwise = NRRegular
-- | Get the list of the master nodes (usually one).
getMasterNodes :: ConfigData -> [Node]
getMasterNodes cfg =
filter ((==) NRMaster . getNodeRole cfg) . F.toList . configNodes $ cfg
-- | Get the list of master candidates, /not including/ the master itself.
getMasterCandidates :: ConfigData -> [Node]
getMasterCandidates cfg =
filter ((==) NRCandidate . getNodeRole cfg) . F.toList . configNodes $ cfg
-- | Get the list of master candidates, /including/ the master.
getMasterOrCandidates :: ConfigData -> [Node]
getMasterOrCandidates cfg =
let isMC r = (r == NRCandidate) || (r == NRMaster)
in filter (isMC . getNodeRole cfg) . F.toList . configNodes $ cfg
-- | Get the network parameters for the master IP address.
getMasterNetworkParameters :: ConfigData -> MasterNetworkParameters
getMasterNetworkParameters cfg =
let cluster = configCluster cfg
in MasterNetworkParameters
{ masterNetworkParametersUuid = clusterMasterNode cluster
, masterNetworkParametersIp = clusterMasterIp cluster
, masterNetworkParametersNetmask = clusterMasterNetmask cluster
, masterNetworkParametersNetdev = clusterMasterNetdev cluster
, masterNetworkParametersIpFamily = clusterPrimaryIpFamily cluster
}
-- | Get the list of online nodes.
getOnlineNodes :: ConfigData -> [Node]
getOnlineNodes = filter (not . nodeOffline) . F.toList . configNodes
-- | Returns the default cluster link.
getDefaultNicLink :: ConfigData -> String
getDefaultNicLink =
nicpLink . (M.! C.ppDefault) . fromContainer .
clusterNicparams . configCluster
-- | Returns the default cluster hypervisor.
getDefaultHypervisor :: ConfigData -> Hypervisor
getDefaultHypervisor cfg =
case clusterEnabledHypervisors $ configCluster cfg of
-- FIXME: this case shouldn't happen (configuration broken), but
-- for now we handle it here because we're not authoritative for
-- the config
[] -> XenPvm
x:_ -> x
-- | Returns instances of a given link.
getInstancesIpByLink :: LinkIpMap -> String -> [String]
getInstancesIpByLink linkipmap link =
M.keys $ M.findWithDefault M.empty link linkipmap
-- | Generic lookup function that converts from a possible abbreviated
-- name to a full name.
getItem :: String -> String -> M.Map String a -> ErrorResult a
getItem kind name allitems = do
let lresult = lookupName (M.keys allitems) name
err msg = Bad $ OpPrereqError (kind ++ " name " ++ name ++ " " ++ msg)
ECodeNoEnt
fullname <- case lrMatchPriority lresult of
PartialMatch -> Ok $ lrContent lresult
ExactMatch -> Ok $ lrContent lresult
MultipleMatch -> err "has multiple matches"
FailMatch -> err "not found"
maybe (err "not found after successfull match?!") Ok $
M.lookup fullname allitems
-- | Looks up a node by name or uuid.
getNode :: ConfigData -> String -> ErrorResult Node
getNode cfg name =
let nodes = fromContainer (configNodes cfg)
in case getItem "Node" name nodes of
-- if not found by uuid, we need to look it up by name
Ok node -> Ok node
Bad _ -> let by_name = M.mapKeys
(nodeName . (M.!) nodes) nodes
in getItem "Node" name by_name
-- | Looks up an instance by name or uuid.
getInstance :: ConfigData -> String -> ErrorResult Instance
getInstance cfg name =
let instances = fromContainer (configInstances cfg)
in case getItem "Instance" name instances of
-- if not found by uuid, we need to look it up by name
Ok inst -> Ok inst
Bad _ -> let by_name = M.mapKeys
(instName . (M.!) instances) instances
in getItem "Instance" name by_name
-- | Looks up a disk by uuid.
getDisk :: ConfigData -> String -> ErrorResult Disk
getDisk cfg name =
let disks = fromContainer (configDisks cfg)
in getItem "Disk" name disks
-- | Looks up a node group by name or uuid.
getGroup :: ConfigData -> String -> ErrorResult NodeGroup
getGroup cfg name =
let groups = fromContainer (configNodegroups cfg)
in case getItem "NodeGroup" name groups of
-- if not found by uuid, we need to look it up by name, slow
Ok grp -> Ok grp
Bad _ -> let by_name = M.mapKeys
(groupName . (M.!) groups) groups
in getItem "NodeGroup" name by_name
-- | Computes a node group's node params.
getGroupNdParams :: ConfigData -> NodeGroup -> FilledNDParams
getGroupNdParams cfg ng =
fillNDParams (clusterNdparams $ configCluster cfg) (groupNdparams ng)
-- | Computes a node group's ipolicy.
getGroupIpolicy :: ConfigData -> NodeGroup -> FilledIPolicy
getGroupIpolicy cfg ng =
fillIPolicy (clusterIpolicy $ configCluster cfg) (groupIpolicy ng)
-- | Computes a group\'s (merged) disk params.
getGroupDiskParams :: ConfigData -> NodeGroup -> GroupDiskParams
getGroupDiskParams cfg ng =
GenericContainer $
fillDict (fromContainer . clusterDiskparams $ configCluster cfg)
(fromContainer $ groupDiskparams ng) []
-- | Get nodes of a given node group.
getGroupNodes :: ConfigData -> String -> [Node]
getGroupNodes cfg gname =
let all_nodes = M.elems . fromContainer . configNodes $ cfg in
filter ((==gname) . nodeGroup) all_nodes
-- | Get (primary, secondary) instances of a given node group.
getGroupInstances :: ConfigData -> String -> ([Instance], [Instance])
getGroupInstances cfg gname =
let gnodes = map nodeUuid (getGroupNodes cfg gname)
ginsts = map (getNodeInstances cfg) gnodes in
(concatMap fst ginsts, concatMap snd ginsts)
-- | Retrieves the instance hypervisor params, missing values filled with
-- cluster defaults.
getFilledInstHvParams :: [String] -> ConfigData -> Instance -> HvParams
getFilledInstHvParams globals cfg inst =
-- First get the defaults of the parent
let hvName = hypervisorToRaw . instHypervisor $ inst
hvParamMap = fromContainer . clusterHvparams $ configCluster cfg
parentHvParams = maybe M.empty fromContainer $ M.lookup hvName hvParamMap
-- Then the os defaults for the given hypervisor
osName = instOs inst
osParamMap = fromContainer . clusterOsHvp $ configCluster cfg
osHvParamMap = maybe M.empty fromContainer $ M.lookup osName osParamMap
osHvParams = maybe M.empty fromContainer $ M.lookup hvName osHvParamMap
-- Then the child
childHvParams = fromContainer . instHvparams $ inst
-- Helper function
fillFn con val = fillDict con val globals
in GenericContainer $ fillFn (fillFn parentHvParams osHvParams) childHvParams
-- | Retrieves the instance backend params, missing values filled with cluster
-- defaults.
getFilledInstBeParams :: ConfigData -> Instance -> ErrorResult FilledBeParams
getFilledInstBeParams cfg inst = do
let beParamMap = fromContainer . clusterBeparams . configCluster $ cfg
parentParams <- getItem "FilledBeParams" C.ppDefault beParamMap
return $ fillBeParams parentParams (instBeparams inst)
-- | Retrieves the instance os params, missing values filled with cluster
-- defaults. This does NOT include private and secret parameters.
getFilledInstOsParams :: ConfigData -> Instance -> OsParams
getFilledInstOsParams cfg inst =
let osLookupName = takeWhile (/= '+') (instOs inst)
osParamMap = fromContainer . clusterOsparams $ configCluster cfg
childOsParams = instOsparams inst
in case getItem "OsParams" osLookupName osParamMap of
Ok parentOsParams -> GenericContainer $
fillDict (fromContainer parentOsParams)
(fromContainer childOsParams) []
Bad _ -> childOsParams
-- | Looks up an instance's primary node.
getInstPrimaryNode :: ConfigData -> String -> ErrorResult Node
getInstPrimaryNode cfg name =
liftM instPrimaryNode (getInstance cfg name) >>= getNode cfg
-- | Retrieves all nodes hosting a DRBD disk
getDrbdDiskNodes :: ConfigData -> Disk -> [Node]
getDrbdDiskNodes cfg disk =
let retrieved = case diskLogicalId disk of
LIDDrbd8 nodeA nodeB _ _ _ _ ->
justOk [getNode cfg nodeA, getNode cfg nodeB]
_ -> []
in retrieved ++ concatMap (getDrbdDiskNodes cfg) (diskChildren disk)
-- | Retrieves all the nodes of the instance.
--
-- As instances not using DRBD can be sent as a parameter as well,
-- the primary node has to be appended to the results.
getInstAllNodes :: ConfigData -> String -> ErrorResult [Node]
getInstAllNodes cfg name = do
inst_disks <- getInstDisks cfg name
let diskNodes = concatMap (getDrbdDiskNodes cfg) inst_disks
pNode <- getInstPrimaryNode cfg name
return . nub $ pNode:diskNodes
-- | Get disks for a given instance.
-- The instance is specified by name or uuid.
getInstDisks :: ConfigData -> String -> ErrorResult [Disk]
getInstDisks cfg iname =
getInstance cfg iname >>= mapM (getDisk cfg) . instDisks
-- | Get disks for a given instance object.
getInstDisksFromObj :: ConfigData -> Instance -> ErrorResult [Disk]
getInstDisksFromObj cfg =
getInstDisks cfg . instUuid
-- | Collects a value for all DRBD disks
collectFromDrbdDisks
:: (Monoid a)
=> (String -> String -> Int -> Int -> Int -> DRBDSecret -> a)
-- ^ NodeA, NodeB, Port, MinorA, MinorB, Secret
-> Disk -> a
collectFromDrbdDisks f = col
where
col Disk { diskLogicalId = (LIDDrbd8 nA nB port mA mB secret)
, diskChildren = ch
} = f nA nB port mA mB secret <> F.foldMap col ch
col d = F.foldMap col (diskChildren d)
-- | Returns the DRBD secrets of a given 'Disk'
getDrbdSecretsForDisk :: Disk -> [DRBDSecret]
getDrbdSecretsForDisk = collectFromDrbdDisks (\_ _ _ _ _ secret -> [secret])
-- | Returns the DRBD minors of a given 'Disk'
getDrbdMinorsForDisk :: Disk -> [(Int, String)]
getDrbdMinorsForDisk =
collectFromDrbdDisks (\nA nB _ mnA mnB _ -> [(mnA, nA), (mnB, nB)])
-- | Filters DRBD minors for a given node.
getDrbdMinorsForNode :: String -> Disk -> [(Int, String)]
getDrbdMinorsForNode node disk =
let child_minors = concatMap (getDrbdMinorsForNode node) (diskChildren disk)
this_minors =
case diskLogicalId disk of
LIDDrbd8 nodeA nodeB _ minorA minorB _
| nodeA == node -> [(minorA, nodeB)]
| nodeB == node -> [(minorB, nodeA)]
_ -> []
in this_minors ++ child_minors
-- | Returns the DRBD minors of a given instance
getDrbdMinorsForInstance :: ConfigData -> Instance
-> ErrorResult [(Int, String)]
getDrbdMinorsForInstance cfg =
liftM (concatMap getDrbdMinorsForDisk) . getInstDisksFromObj cfg
-- | String for primary role.
rolePrimary :: String
rolePrimary = "primary"
-- | String for secondary role.
roleSecondary :: String
roleSecondary = "secondary"
-- | Gets the list of DRBD minors for an instance that are related to
-- a given node.
getInstMinorsForNode :: ConfigData
-> String -- ^ The UUID of a node.
-> Instance
-> [(String, Int, String, String, String, String)]
getInstMinorsForNode cfg node inst =
let role = if node == instPrimaryNode inst
then rolePrimary
else roleSecondary
iname = instName inst
inst_disks = case getInstDisksFromObj cfg inst of
Ok disks -> disks
Bad _ -> []
-- FIXME: the disk/ build there is hack-ish; unify this in a
-- separate place, or reuse the iv_name (but that is deprecated on
-- the Python side)
in concatMap (\(idx, dsk) ->
[(node, minor, iname, "disk/" ++ show idx, role, peer)
| (minor, peer) <- getDrbdMinorsForNode node dsk]) .
zip [(0::Int)..] $ inst_disks
-- | Builds link -> ip -> instname map.
--
-- TODO: improve this by splitting it into multiple independent functions:
--
-- * abstract the \"fetch instance with filled params\" functionality
--
-- * abstsract the [instance] -> [(nic, instance_name)] part
--
-- * etc.
buildLinkIpInstnameMap :: ConfigData -> LinkIpMap
buildLinkIpInstnameMap cfg =
let cluster = configCluster cfg
instances = M.elems . fromContainer . configInstances $ cfg
defparams = (M.!) (fromContainer $ clusterNicparams cluster) C.ppDefault
nics = concatMap (\i -> [(instName i, nic) | nic <- instNics i])
instances
in foldl' (\accum (iname, nic) ->
let pparams = nicNicparams nic
fparams = fillNicParams defparams pparams
link = nicpLink fparams
in case nicIp nic of
Nothing -> accum
Just ip -> let oldipmap = M.findWithDefault M.empty
link accum
newipmap = M.insert ip iname oldipmap
in M.insert link newipmap accum
) M.empty nics
-- | Returns a node's group, with optional failure if we can't find it
-- (configuration corrupt).
getGroupOfNode :: ConfigData -> Node -> Maybe NodeGroup
getGroupOfNode cfg node =
M.lookup (nodeGroup node) (fromContainer . configNodegroups $ cfg)
-- | Returns a node's ndparams, filled.
getNodeNdParams :: ConfigData -> Node -> Maybe FilledNDParams
getNodeNdParams cfg node = do
group <- getGroupOfNode cfg node
let gparams = getGroupNdParams cfg group
return $ fillNDParams gparams (nodeNdparams node)
-- * Network
-- | Looks up a network. If looking up by uuid fails, we look up
-- by name.
getNetwork :: ConfigData -> String -> ErrorResult Network
getNetwork cfg name =
let networks = fromContainer (configNetworks cfg)
in case getItem "Network" name networks of
Ok net -> Ok net
Bad _ -> let by_name = M.mapKeys
(fromNonEmpty . networkName . (M.!) networks)
networks
in getItem "Network" name by_name
-- ** MACs
type MAC = String
-- | Returns all MAC addresses used in the cluster.
getAllMACs :: ConfigData -> [MAC]
getAllMACs = F.foldMap (map nicMac . instNics) . configInstances
-- ** DRBD secrets
getAllDrbdSecrets :: ConfigData -> [DRBDSecret]
getAllDrbdSecrets = F.foldMap getDrbdSecretsForDisk . configDisks
-- ** LVs
-- | A map from node UUIDs to
--
-- FIXME: After adding designated types for UUIDs,
-- use them to replace 'String' here.
type NodeLVsMap = MM.MultiMap String LogicalVolume
getInstanceLVsByNode :: ConfigData -> Instance -> ErrorResult NodeLVsMap
getInstanceLVsByNode cd inst =
(MM.fromList . lvsByNode (instPrimaryNode inst))
<$> getInstDisksFromObj cd inst
where
lvsByNode :: String -> [Disk] -> [(String, LogicalVolume)]
lvsByNode node = concatMap (lvsByNode1 node)
lvsByNode1 :: String -> Disk -> [(String, LogicalVolume)]
lvsByNode1 _ Disk { diskLogicalId = (LIDDrbd8 nA nB _ _ _ _)
, diskChildren = ch
} = lvsByNode nA ch ++ lvsByNode nB ch
lvsByNode1 node Disk { diskLogicalId = (LIDPlain lv) }
= [(node, lv)]
lvsByNode1 node Disk { diskChildren = ch }
= lvsByNode node ch
getAllLVs :: ConfigData -> ErrorResult (S.Set LogicalVolume)
getAllLVs cd = mconcat <$> mapM (liftM MM.values . getInstanceLVsByNode cd)
(F.toList $ configInstances cd)
-- * ND params
-- | Type class denoting objects which have node parameters.
class NdParamObject a where
getNdParamsOf :: ConfigData -> a -> Maybe FilledNDParams
instance NdParamObject Node where
getNdParamsOf = getNodeNdParams
instance NdParamObject NodeGroup where
getNdParamsOf cfg = Just . getGroupNdParams cfg
instance NdParamObject Cluster where
getNdParamsOf _ = Just . clusterNdparams
| ribag/ganeti-experiments | src/Ganeti/Config.hs | gpl-2.0 | 20,620 | 0 | 20 | 4,748 | 4,610 | 2,409 | 2,201 | 356 | 4 |
{-# LANGUAGE CPP, ViewPatterns, MultiWayIf, TupleSections, NamedFieldPuns #-}
module Schafkopf where
import Utility
import Utility.Choice
import Utility.Cond
import Cards
import qualified Cards.Parse as Parse
import Cards.Shuffle
import Trick.Rules
import Schafkopf.GameTypes
import Schafkopf.Score
import Schafkopf.AI as AI
import Prelude hiding ((||), (&&), not, or, and)
import Data.List hiding (and, or)
import Control.Monad
import Control.Applicative
import Control.Exception
mainSchafkopf :: IO ()
mainGameChoice :: [Bool] -> GameState -> IO ()
mainPlay :: GameState -> IO ()
mainFinish :: GameState -> IO ()
mainFinishSolo :: Bool -> Int -> Int -> GameState -> IO ()
mainSchafkopf = do
(map $ sortTR normalTR -> hs @ (h0:_)) <- getCards 1 4 8 -- 1 deck, 4 players, 8 cards each
putStrLn $ "Dein Blatt: " ++ showListNatural h0
putStrLn ""
case elemIndex officers hs of -- here we use that hs are sorted (sortTR)
Just 0 -> putStrLn "Du hast einen Sie. Herzlichen Glückwunsch!" >> mainSchafkopf
Just i -> putStrLn ("Spieler " ++ show i ++ " hat einen Sie. Neues Spiel.") >> mainSchafkopf
Nothing -> return ()
let canCall = mayCallRS normalTrumps h0
mayCall = or canCall
games = ("Weiter", Ramsch) : option mayCall ("Rufspiel", Rufspiel Hearts)
_g <- choiceNum "Was für ein Spiel soll es sein?" $ games ++
[
("Farb-Wenz", Wenz $ Just Hearts),
("Wenz", Wenz Nothing),
("Solo", Solo Hearts)
]
let state = AI.overbid hs _g -- this + expr above can be (AI.overbid hs -> state) <- (expr above)
case player state of
Just 0 -> putStrLn "Du darfst spielen." >> mainGameChoice canCall state
Just n -> putStrLn ("Spieler " ++ show n ++ " spielt " ++ show (game state) ++ ".") >> mainPlay state
Nothing -> putStrLn "Wir spielen einen Ramsch." >> mainPlay state
-- Rufspiel
mainGameChoice canCall state @ AI.GameState { hands, game = Rufspiel _ } = do
let sts = zipPred canCall suits
calledSuit <- choiceAlpha "Wähle eine Farbe:" $ zip (show <$> sts) sts
let newState = state
{
game = Rufspiel calledSuit,
rules = playerRulesRS calledSuit hands,
trRule = normalTR
}
mainPlay newState
-- Farbwenz
mainGameChoice _ state @ (game -> Wenz (Just _)) = do
calledSuit <- choiceAlpha "Wähle eine Farbe:" $ zipWith ((,) . show) suits suits
let game = Wenz $ Just calledSuit
let newState = state
{
game,
rules = replicate 4 $ const $ cardAllowed $ trumps game,
trRule = trickRule game
}
mainPlay newState
-- Farbsolo
mainGameChoice _ state @ (game -> Solo _) = do
calledSuit <- choiceAlpha "Wähle eine Farbe:" $ zipWith ((,) . show) suits suits
let game = Solo calledSuit
let newState = state
{
game,
rules = replicate 4 $ const $ cardAllowed $ trumps game,
trRule = trickRule game
}
mainPlay newState
-- Alle anderen Spiele (Wenz, ...) nichts zu tun.
mainGameChoice _ state = mainPlay state
mainPlay st = do
state <- foldUM st const (const trick) [1::Int .. 8]
putStrLn ""
mainFinish state
where
-- trick :: GameState -> IO GameState
trick GameState { hands = [] } = error "This shall not occur."
trick GameState { rules = [] } = error "This shall not occur."
trick state @ GameState
{
playerNames,
no,
hands = hs @ (h0:_),
score,
takenTr,
rules = rs @ (r0:_),
trRule,
condRS
} = do
(reverse -> playedCards) <- foldUM [] (:) giveBy [0 .. 3]
let (add no mod 4 -> plNo, crd) = takesTrick trRule playedCards
let scr = sum $ cardScore <$> playedCards
let newScores = addSc plNo score scr
let newTricks = addSc plNo takenTr 1
putStrLn $ if plNo == 0 then "Deine Karte macht den Stich mit " ++ show scr ++ " Augen."
else show crd ++ " von " ++ playerNames !! plNo ++ " gewinnt den Stich mit " ++ show scr ++ " Augen."
putStrLn ""
putStrLn ""
return state
{
no = plNo,
hands = filter (`notElem` playedCards) <$> hs,
score = newScores,
takenTr = newTricks,
rules = if condRS (head playedCards)
then replicate 4 $ const $ cardAllowed normalTrumps
else rs
}
where
suitChars = ['s', 'h', 'g', 'e']
rankChars = if Ten < Under then ['7', '8', '9', 'X', 'U', 'O', 'K', 'A']
else ['7', '8', '9', 'U', 'O', 'K', 'X', 'A']
readCard = Parse.readCard suitChars rankChars
giveBy = giveBy' . add no mod 4
giveBy' 0 t = do -- Player 0 is human player
putStrLn "Du hast die folgenden Karten:"
putStrLn $ showListNatural h0
putStrLn $ if null t then "Du darfst mit folgenden Karten herauskommen:" else "Du darfst die folgenden Karten ausspielen:"
putStrLn $ showListNatural availableCards
readCard "Welche Karte soll es sein?"
`untilM` ((`elem` h0), putStrLn "Du hast diese Karte nicht.")
`untilM` ((`elem` availableCards), putStrLn "Diese Karte darfst du nicht ausspielen.")
where
availableCards = if null r then h0 else r
r = filter (r0 h0 $ maybeLast t) h0
giveBy' n t = do
c <- AI.play t availableCards state
putStrLn $ (playerNames !! n) ++ (if null t then " kommt mit " ++ show c ++ " heraus." else " gibt " ++ show c ++ " zu.")
return c
where
hn = hs !! n
rn = rs !! n
av = filter (rn hn $ maybeLast t) hn
availableCards = if null av then hn else av -- Salvatorische Klausel
mainFinish GameState
{
game = Rufspiel _,
playerNames,
player = Just p,
mate = Just mt,
score
} | p == 0 || mt == 0 = finalMessage (p + mt) playerPartySc contraPartySc -- human is in player party
| otherwise = finalMessage (6 - p - mt) contraPartySc playerPartySc -- human is in contra party
where
playerParty = [p, mt]
contraParty = [0 .. 3] \\ playerParty
playerPartySc = (score !! p) + (score !! mt)
contraPartySc = 120 - playerPartySc
winnerParty = if contraPartySc < 60 then playerParty else contraParty
schneider = if playerPartySc <= 30 || contraPartySc < 30 then 2 else 0
schwarz = if playerPartySc == 0 || contraPartySc == 0 then 2 else 0
finalMessage :: Int -> Int -> Int -> IO ()
finalMessage m hs os = do -- human + mate score / other's score
putStrLn $ "Du spieltest mit Spieler " ++ (playerNames !! m) ++ " zusammen."
putStrLn $ "Ihr habt " ++ show hs ++ " Augen gemacht."
putStrLn $ if | hs == 0 -> "Schwarz... wohl arg Pech gehabt."
| hs < 32 -> "Ihr seid im Schneider; das kostet."
| hs < 61 -> "Einmal wird man vom Bären gefressen, ein andermal frisst einen der Bär."
| os == 0 -> "Schwarz! So ein Spiel sieht man nicht alle Tage."
| os < 30 -> "Sie sind Schneider! Alle Achtung."
| otherwise -> "Ein einfacher Sieg ist auch ein Sieg."
mapM_ (putStrLn . payget) [0..3]
payget :: Int -> String
payget n | n `elem` winnerParty = (if n == 0 then "Du bekommst " else playerNames !! n ++ " bekommt ")
++ show ((2 :: Int) + schneider + schwarz) ++ "."
| otherwise = (if n == 0 then "Du zahlst " else playerNames !! n ++ " zahlt ")
++ show ((2 :: Int) + schneider + schwarz) ++ "."
mainFinish GameState
{
game = Ramsch,
playerNames,
score,
takenTr = (elemIndex 8 -> durchmarsch)
} | Just n <- durchmarsch = do
putStrLn $ if n == 0 then "Du hast einen Durchmarsch geschafft! Wow."
else playerNames !! n ++ " hat einen Durchmarsch geschafft."
mapM_ (putStrLn . payget) $ sort $ zip (snd <$> reverse orderedScore) (snd payment)
| otherwise = do
putStrLn $ "Spielende:"
putStrLn $ "Du hast " ++ show (head score) ++ " Augen."
forM_ [1..3] (\n -> putStrLn $ (playerNames !! n) ++ " hat " ++ show (score !! n) ++ " Augen.")
putStrLn $ "Es blieben " ++ (show $ fst payment) ++ " Spieler Jungfrau."
mapM_ (putStrLn . payget) $ sort $ zip (snd <$> orderedScore) (snd payment)
where
orderedScore = sort $ zip score [0::Int ..]
payget ( 0, py) | py < 0 = "Du zahlst " ++ show (-py) ++ "."
| py > 0 = "Du bekommst " ++ show py ++ "."
payget (plno, py) | py < 0 = playerNames !! plno ++ " zahlt " ++ show (-py) ++ "."
| py > 0 = playerNames !! plno ++ " bekommt " ++ show py ++ "."
payget _ = ""
payment :: (Int, [Int]) -- virgins, payment
payment = let vs = (fst $== 0) <$> orderedScore -- vs (Virgins) when trick == 0
vc = length $ filter (== True) vs
compare_fst (fst -> a) (fst -> b) = compare a b
in (vc,) $ (2^vc *) <$> case zipBetweenWith compare_fst orderedScore of
[LT, LT, LT] -> [3, 1, -1, -3]
[LT, LT, EQ] -> [3, 1, -2, -2]
[LT, EQ, LT] -> [3, 0, 0, -3]
[EQ, LT, LT] -> [2, 2, -1, -3]
[LT, EQ, EQ] -> [3, 1, -1, -1]
[EQ, LT, EQ] -> [2, 2, -2, -2]
[EQ, EQ, LT] -> [1, 1, 1, -3]
[EQ, EQ, EQ] -> [0, 0, 0, 0]
_ -> error "This shall not occur. The list is not 3 long or not ordered."
mainFinish state @ GameState
{
game = Bettel,
player = Just p,
playerNames,
takenTr = (elemIndex 8 -> bettel_sieger)
} | Just n <- bettel_sieger, n == p = do
putStrLn $ show (playerNames !! p) ++ " hat das Bettel gewonnen."
mainFinishSolo True 0 0 state
| otherwise = do
putStrLn $ show (playerNames !! p) ++ " hat das Bettel leider verloren."
mainFinishSolo False 0 0 state
mainFinish state @ GameState
{
game,
player = Just p,
playerNames,
score
} = do
putStrLn $
(if p == 0 then "Du hast " else playerNames !! p ++ " hat ") ++
show game ++
(if | schwarz /= 0 -> " schwarz " | schneider /= 0 -> " mit Schneider " | otherwise -> "") ++
(if playerWon then " gewonnen." else " verloren.")
mainFinishSolo playerWon schneider schwarz state
where
playerScore = score !! p
contraScore = 120 - playerScore
playerWon = playerScore > 60
schneider, schwarz :: Int
schneider = if playerScore <= 30 || contraScore < 30 then 5 else 0
schwarz = if playerScore == 0 || contraScore == 0 then 5 else 0
mainFinish _ = error "Kein Spieler, aber kein Ramsch? Das kann nicht sein."
mainFinishSolo True schneider schwarz GameState
{
player = Just p,
playerNames
} = do
putStrLn $ (if p == 0 then "Du bekommst " else playerNames !! p ++ " bekommt ") ++ show (3 * spielWert) ++ "."
forM_ contraParty $ \i -> putStrLn $ (if i == 0 then "Du zahlst " else playerNames !! i ++ " zahlt ") ++ show spielWert ++ "."
return ()
where
spielWert = 5 + schneider + schwarz
contraParty = [0..3] \\ [p]
mainFinishSolo False schneider schwarz GameState
{
player = Just p,
playerNames
} = do
putStrLn $ (if p == 0 then "Du zahlst " else playerNames !! p ++ " zahlt ") ++ show (3 * spielWert) ++ "."
forM_ contraParty $ \i -> putStrLn $ (if i == 0 then "Du bekommst " else playerNames !! i ++ " bekommt ") ++ show spielWert ++ "."
return ()
where
spielWert = 2 + schneider + schwarz
contraParty = [0..3] \\ [p]
mainFinishSolo _ _ _ _ = error "Solo without player..." | Bolpat/CardGames | src/Schafkopf.hs | gpl-3.0 | 12,973 | 131 | 54 | 4,823 | 3,805 | 1,998 | 1,807 | 239 | 28 |
{-# LANGUAGE ScopedTypeVariables, Arrows #-}
-- | A Netwire FRP executable model for the Netrobots game.
module Game.Netrobots.FRP.Robot where
import System.ZMQ4.Monadic
import Control.Monad (forever)
import Data.ByteString.Char8 (pack, unpack)
import Control.Concurrent (threadDelay)
import qualified Text.ProtocolBuffers.Basic as PB
import qualified Text.ProtocolBuffers.WireMessage as PB
import qualified Text.ProtocolBuffers.Reflections as PB
import qualified Data.Text as Text
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Angle as Angle
import Control.Applicative
import Control.Arrow
import Data.Angle
import Game.Netrobots.Proto.CreateRobot as CreateRobot
import Game.Netrobots.Proto.RobotCommand as RobotCommand
import Game.Netrobots.Proto.DeleteRobot
import Game.Netrobots.Proto.Drive as Drive
import Game.Netrobots.Proto.Scan as Scan
import Game.Netrobots.Proto.Cannon as Cannon
import Game.Netrobots.Proto.MainCommand
import Game.Netrobots.Proto.RobotStatus as Status
import Game.Netrobots.Proto.ScanStatus as ScanStatus
import Game.Netrobots.Game
import qualified Control.Monad.State.Lazy as MS
import Control.Wire.Core
import Control.Wire.Switch
import Control.Wire.Event
import Prelude hiding ((.), id, until)
-- ----------------------------------------------------------
-- HRobot Netwire related definitions
-- | The state of a Robot. The state is shared with all the Wires of the FRP Network. In this case is it a Satete Monad, so each node can read and modify some part of the shared state.
type HRobotCommand
= MS.State (Status.RobotStatus, Maybe Drive.Drive, Maybe Scan.Scan, Maybe Cannon.Cannon)
-- | The wire of robots:
-- * use Float as time
-- * use () as error
-- * run inside HRobotCommand state monad, that stores the selected commands, and the robot status
type HRobotWire a b = Wire Float () HRobotCommand a b
-- | True if the robot has win (the last robot on the Board)
-- False if the robot was destroyed.
-- TODO extend the server for supporting WIN/LOOSE situations
type IsWinner = Bool
-- | Execute a HRobot until completition.
runHRobot
:: ConnectionConfiguration
-> CreateRobot.CreateRobot
-> a
-> HRobotWire a b
-> IO IsWinner
runHRobot connConf robotParams input0 wire0 = runZMQ $ do
-- Init Robot
s <- socket Req
connect s (gameServerAddress connConf)
let cmd = MainCommand {
createRobot = Just robotParams
, robotCommand = Nothing
, deleteRobot = Nothing
}
state0 <- sendMainCmd s cmd
let tok = Status.token state0
case Status.isWellSpecifiedRobot state0 of
False
-> return False
True
-> runHRobot' s tok 0 state0 (Right input0) wire0
where
runHRobot' sock tok time1 robotState1 input1 wire1 =
case Status.isDead robotState1 of
True
-> return False
False
-> case Status.isWinner robotState1 of
True
-> return True
False
-> let time2 = Status.globalTime robotState1
deltaTime = time2 - time1
((maybeErr, wire2), cmd)
= MS.runState
(stepWire wire1 deltaTime input1)
(robotState1, Nothing, Nothing, Nothing)
(_, driveCmd, scanCmd, fireCmd)
= case maybeErr of
Left _ -> (robotState1, Nothing, Nothing, Nothing)
-- in case of error do not execute any command
Right _ -> cmd
robotCommand
= RobotCommand.RobotCommand {
RobotCommand.token = tok
, RobotCommand.drive = driveCmd
, RobotCommand.scan = scanCmd
, RobotCommand.cannon = fireCmd
}
in do robotState2 <- sendCmd sock tok robotCommand
runHRobot' sock tok time2 robotState2 input1 wire2
sendMainCmd s cmd
= do
let protoCmd = LBS.toStrict $ PB.messagePut cmd
send s [] protoCmd
bs <- receive s
let status :: RobotStatus = fromProtoBuffer $ LBS.fromStrict bs
liftIO $ putStrLn $ "Robot status: " ++ show status ++ "\n"
return status
sendCmd s tok cmd
= do let mainCmd = MainCommand {
createRobot = Nothing
, robotCommand = Just $ cmd { RobotCommand.token = tok }
, deleteRobot = Nothing
}
sendMainCmd s mainCmd
fromProtoBuffer :: (PB.ReflectDescriptor msg, PB.Wire msg) => LBS.ByteString -> msg
fromProtoBuffer bs
= case PB.messageGet bs of
Left err -> error $ "Error reading proto buffer message: " ++ err
Right (r, _) -> r
-- | Execute a default Robot initialization, and run it.
runHRobotWithDefaultParams :: ConnectionConfiguration -> String -> HRobotWire () b -> IO ()
runHRobotWithDefaultParams conf robotName w = do
runHRobot conf (defaultRobotParams robotName) () w
return ()
-- -----------------------------------------------------------
-- Basic Robot Wires
-- NOTE: use preferibaly more high level functions instead.
executeDrive :: HRobotWire (Maybe Drive.Drive) ()
executeDrive = mkGen_ $ \v -> do
(s, _, sc, cn) <- MS.get
MS.put (s, v, sc, cn)
return $ Right ()
executeScan :: HRobotWire (Maybe Scan.Scan) ()
executeScan = mkGen_ $ \v -> do
(s, dr, _, cn) <- MS.get
MS.put (s, dr, v, cn)
return $ Right ()
executeFire :: HRobotWire (Maybe Cannon.Cannon) ()
executeFire = mkGen_ $ \v -> do
(s, dr, sc, _) <- MS.get
MS.put (s, dr, sc, v)
return $ Right ()
robotStatus :: HRobotWire a Status.RobotStatus
robotStatus = mkGen_ $ \_ -> do
(s, _, _, _) <- MS.get
return $ Right s
robot_scanStatus :: HRobotWire a (Maybe ScanStatus)
robot_scanStatus = fmap (Status.scan) robotStatus
-- ------------------------------------------------------------
-- Wires for sending Robot Commands
robotCmd_fire :: HRobotWire (Direction, Distance) ()
robotCmd_fire = proc (a, b) -> do
executeFire -< Just $ Cannon {
Cannon.direction = fromIntegral a
, Cannon.distance = fromIntegral b }
robotCmd_drive :: HRobotWire (Direction, Speed) ()
robotCmd_drive = proc (a, b) -> do
executeDrive -< Just $ Drive {
Drive.direction = fromIntegral a
, Drive.speed = fromIntegral b }
robotCmd_scan :: HRobotWire (Direction, SemiAperture) ()
robotCmd_scan = proc (a, b) -> do
executeScan -< Just $ Scan {
Scan.direction = fromIntegral a
, Scan.semiaperture = fromIntegral b }
robotCmd_disableScan :: HRobotWire a ()
robotCmd_disableScan = proc _ -> do
executeScan -< Nothing
-- ------------------------------------------------------------
-- Wires for reading Robot status
-- | The current simulation time expressed in seconds.
robot_globalTime :: HRobotWire a Float
robot_globalTime = proc _ -> do
s <- robotStatus -< ()
returnA -< Status.globalTime s
-- | The next command will be executed after this time tick, expressed in seconds.
robot_timeTick :: HRobotWire a Float
robot_timeTick = proc _ -> do
s <- robotStatus -< ()
returnA -< Status.timeTick s
-- | The server accept the next command after this time, expressed in seconds.
-- This is the real time the client has for calculating next move, sending the move,
-- and hoping it reach the server in time.
robot_realTimeTick :: HRobotWire a Float
robot_realTimeTick = proc _ -> do
s <- robotStatus -< ()
returnA -< Status.realTimeTick s
-- | Robot left power. When 0 the robot is dead.
robot_hp :: HRobotWire a Int
robot_hp = proc _ -> do
s <- robotStatus -< ()
returnA -< fromIntegral $ Status.hp s
-- | Robot current direction.
robot_direction :: HRobotWire a Direction
robot_direction = proc _ -> do
s <- robotStatus -< ()
returnA -< fromIntegral $ Status.direction s
-- | Robot current speed.
robot_speed :: HRobotWire a Speed
robot_speed = fmap (\s -> fromIntegral $ Status.speed s) robotStatus
robot_x :: HRobotWire a Int
robot_x = fmap (\s -> fromIntegral $ Status.x s) robotStatus
robot_y :: HRobotWire a Int
robot_y = fmap (\s -> fromIntegral $ Status.y s) robotStatus
robot_position :: HRobotWire a Position
robot_position
= fmap (\s -> (fromIntegral $ Status.x s, fromIntegral $ Status.y s)) robotStatus
robot_isDead :: HRobotWire a Bool
robot_isDead = fmap (Status.isDead) robotStatus
robot_isWinner :: HRobotWire a Bool
robot_isWinner = fmap (Status.isWinner) robotStatus
robot_isWellSpecifiedRobot :: HRobotWire a Bool
robot_isWellSpecifiedRobot = fmap (Status.isWellSpecifiedRobot) robotStatus
robot_maxSpeed :: HRobotWire a Speed
robot_maxSpeed = fmap (\s -> fromIntegral $ Status.maxSpeed s) robotStatus
robot_isReloading :: HRobotWire a Bool
robot_isReloading = fmap (Status.isReloading) robotStatus
robot_firedNewMissile :: HRobotWire a Bool
robot_firedNewMissile = fmap (Status.firedNewMissile) robotStatus
-- | Nothing if no object was found.
robot_scanDistance :: HRobotWire a (Maybe Distance)
robot_scanDistance
= fmap (\s -> case Status.scan s of
Nothing -> Nothing
Just s' -> Just $ fromIntegral $ ScanStatus.distance s'
) robotStatus
robot_scanDirection :: HRobotWire a (Maybe Direction)
robot_scanDirection
= fmap (\s -> case Status.scan s of
Nothing -> Nothing
Just s' -> Just $ fromIntegral $ ScanStatus.direction s'
) robotStatus
robot_scanSemiAperture :: HRobotWire a (Maybe SemiAperture)
robot_scanSemiAperture
= fmap (\s -> case Status.scan s of
Nothing -> Nothing
Just s' -> Just $ fromIntegral $ ScanStatus.semiaperture s'
) robotStatus
-- -----------------------------------------------------------
-- High Level Tasks
robotCmd_gotoForwardPosition :: HRobotWire (Position, Speed) ()
robotCmd_gotoForwardPosition = proc ((x1, y1), speed) -> do
(x0, y0) <- robot_position -< ()
let (Angle.Degrees dg) = Angle.degrees $ Angle.Radians $ atan2 (fromIntegral $ y1 - y0) (fromIntegral $ x1 - x0)
let heading = fromInteger $ toInteger $ round dg
robotCmd_drive -< (heading, speed)
-- | Goto near position, and the Wire fail when it is near position
robotCmd_gotoNearPosition :: HRobotWire (Position, Speed, Distance) ()
robotCmd_gotoNearPosition = proc (position, speed, distance) -> do
robotCmd_gotoForwardPosition -< (position, speed)
whileWire robot_isFarFromPosition -< (position, distance)
robotCmd_changeSpeed :: HRobotWire Speed ()
robotCmd_changeSpeed = proc speed -> do
direction <- robot_direction -< ()
robotCmd_drive -< (direction, speed)
-- | Execute until the direction is not reached.
robot_isNearPosition :: HRobotWire (Position, Distance) Bool
robot_isNearPosition = proc ((x1, y1), maxDistance) -> do
(x0, y0) <- robot_position -< ()
let d = point_distance (x0, y0) (x1, y1)
returnA -< (d < (fromIntegral $ maxDistance))
robot_isFarFromPosition :: HRobotWire (Position, Distance) Bool
robot_isFarFromPosition = proc (p, d) -> do
r <- robot_isNearPosition -< (p, d)
returnA -< not r
robot_isMoving :: HRobotWire a Bool
robot_isMoving = fmap ((>) 0) robot_speed
-- | Fail when the Wire on the argument fail.
whileWire :: HRobotWire a Bool -> HRobotWire a ()
whileWire w = proc a -> do
b <- w -< a
case b of
True -> returnA -< ()
False -> zeroArrow -< ()
-- TODO it should calculate stop deceleration, and stop in the correct position
-- and then perform slow adjustement
robotCmd_gotoPositionAndStop :: HRobotWire (Position, Speed) ()
robotCmd_gotoPositionAndStop = proc (position, speed) -> do
(robotCmd_gotoNearPosition -< (position, speed, 80))
--> (do robotCmd_changeSpeed -< 0
whileWire robot_isMoving -< ()
)
--- --------------------------------------------
-- Example Robots
-- | An example of Robot.
demo1 :: HRobotWire a ()
demo1 = proc _ -> do
robotCmd_gotoPositionAndStop -< ((100, 200), 100)
demo2 :: HRobotWire a ()
demo2 = proc _ -> do
robotCmd_gotoNearPosition -< ((100, 200), 100, 80)
-- TODO copy tutorial example
| massimo-zaniboni/hrobots | src/Game/Netrobots/FRP/Robot.hs | gpl-3.0 | 12,417 | 18 | 20 | 3,002 | 3,196 | 1,703 | 1,493 | 244 | 6 |
{-# LANGUAGE BangPatterns #-}
module Rabin where
import System.IO
import Primes
import Data.Word
import Data.Bits
import Data.List
import qualified Data.ByteString.Lazy as BS
import System.Directory
import Numeric (showHex)
getKeys :: IO (Integer,Integer)
getKeys = do
exists <- doesFileExist "keys.txt"
if exists
then getKeys'
else do
putStr "Keyfile does not exist. Creating...\n"
writeKeys "keys.txt"
getKeys'
where
getKeys' = do
filecontent <- readFile "keys.txt"
return $ read filecontent
testmsg :: [Word8]
testmsg = [0..4]
--31,43
main :: IO ()
main = do
(p,q) <- getKeys
let n = p * q
let m = roll testmsg
if m > n then error "M is too large." else return ()
putStr $ "Message: " ++ (showHex m "") ++ "\n\n"
let ciphertext = m^(2::Integer) `mod` n
putStr $ "Ciphertext: " ++ (showHex ciphertext "") ++ "\n\n"
roots <- squareroots ciphertext p q
putStr $ foldr (\x y -> y ++ (showHex x "") ++ "\n\n\n") "" roots
putStr "Complete."
encrypt :: Integer -> BS.ByteString -> IO Integer
encrypt n msg = do
let m = roll $ BS.unpack msg
if m > n then error "M is too large." else return ()
let ciphertext = m^(2::Integer) `mod` n
return ciphertext
decrypt :: Integer -> Integer -> Integer -> IO [BS.ByteString]
decrypt p q ct = do
roots <- squareroots ct p q
return $ map (BS.pack . unroll) roots
--Algorithm 3.44 from the book
squareroots :: Integer -> Integer -> Integer -> IO [Integer]
squareroots m p q = do
let n = (p*q)
(r,_,s,_) <- sqrts m p q
let (_,c,d) = eeuclid p q
let x = (r*d*q + s*c*p) `mod` n
let y = (r*d*q - s*c*p) `mod` n
let !x1 = x `mod` n
let !x2 = -1 * x1 + n
let !y1 = y `mod` n
let y2 = -1 * y1 + n
return [x1,x2,y1,y2]
--Taken from Data.Binary Internal source code
roll :: [Word8] -> Integer
roll = foldr unstep 0
where
unstep b a = a `shiftL` 8 .|. fromIntegral b
unroll :: Integer -> [Word8]
unroll = unfoldr step
where
step 0 = Nothing
step i = Just (fromIntegral i, i `shiftR` 8)
---End take
--
--Extended Euclidian from the Handbook of Applied Cryptography
--This is a gnarly fat tuple way of doing it without using my brain
--a -> b -> (d,x,y)
--
eeuclid :: Integer -> Integer -> (Integer,Integer,Integer)
eeuclid a 0 = (a,1,0)
eeuclid a b = let start = ((0::Integer),(0::Integer),(0::Integer),(1::Integer),(1::Integer),(0::Integer),a,b)
(_,_,_,x2',_,y2',a',_) = eproc start
in (a',x2',y2')
where
eproc :: (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer) -> (Integer,Integer,Integer,Integer,Integer,Integer,Integer,Integer)
eproc (x,y,x1,x2,y1,y2,alpha,0) = (x,y,x1,x2,y1,y2,alpha,0)
eproc (_,_,x1,x2,y1,y2,alpha,beta) = let q = alpha `div` beta
r = alpha - q*beta
x' = x2 - q * x1
y' = y2 - q * y1
a' = beta
b' = r
x2' = x1
x1' = x'
y2' = y1
y1' = y'
in
eproc (x',y',x1',x2',y1',y2',a',b')
sqrts :: Integer -> Integer -> Integer -> IO (Integer,Integer,Integer,Integer)
sqrts a p q = do
let r = msqrt3 a p
let s = msqrt3 a q
let s' = q - s
let r' = p - r
return (r,r',s,s')
--For chosen p's and q's === 3 `mod` 4
--Requires that your keys are Gaussian Primes
msqrt3 :: Integer -> Integer -> Integer
msqrt3 c p = smpow c ((p+1) `div` 4) p --c^((p+1) `div` 4) `mod` p
--
twofactor :: Integer -> (Integer,Integer)
twofactor i = twofactor' (0::Integer,i)
twofactor' :: (Integer,Integer) -> (Integer,Integer)
twofactor' (p,t) = if testBit t 0
then (p,t)
else twofactor' (p+1,t `div` 2)
--Powermodulus schnier style
smpow :: Integer -> Integer -> Integer -> Integer
smpow !b !e !m = let e' = binNot e
in
mpow b e'
where
mpow beta es = mpow' beta es 1
mpow' _ [] r = r
mpow' beta (x:xs) r = if x
then mpow' (beta^(2::Integer) `mod` m) xs (r*beta `mod` m)
else mpow' (beta^(2::Integer) `mod` m) xs r
binNot ns = binNot' (0::Integer) ns
binNot' _ 0 = []
binNot' i n = if testBit n 0
then (True) : binNot' (i+1) (shiftR n 1)
else (False) : binNot' (i+1) (shiftR n 1)
| igraves/rabin-haskell | Rabin.hs | gpl-3.0 | 5,415 | 0 | 16 | 2,293 | 1,893 | 1,025 | 868 | 111 | 5 |
{-
Copyright (C) 2017-2018 defanor <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(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, see <http://www.gnu.org/licenses/>.
-}
{- |
Module : Text.Pandoc.Readers.Gopher
Maintainer : defanor <[email protected]>
Stability : unstable
Portability : portable
Loosely based on <https://www.ietf.org/rfc/rfc1436.txt RFC 1436>, but
since the commonly found in the wild directories tend to differ from
that, there are some adjustments.
-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Pandoc.Readers.Gopher ( readGopher ) where
import Text.Pandoc.Definition
import Text.Parsec
import Text.Parsec.Text
import Text.Pandoc.Readers.Plain
import Text.Pandoc.Class
import qualified Data.Text as T
import Control.Monad.Except (throwError)
import Text.Pandoc.Error
-- | UNASCII ::= ASCII - [Tab CR-LF NUL].
unascii :: Parser Char
unascii = noneOf ['\t', '\n', '\r', '\0']
-- | Creates a type prefix for directory entries.
mkPrefix :: String -> [Inline]
mkPrefix s = replicate (6 - length s) Space ++ [Str s, Space]
-- | An informational directory entry.
pInfo :: Parser [Inline]
pInfo = do
_ <- char 'i'
info <- manyTill unascii tab
_ <- manyTill unascii tab
_ <- manyTill unascii tab
_ <- many1 digit
pure $ mkPrefix "" ++ lineToInlines info
-- | A file\/link (i.e., any other than informational) directory
-- entry.
pLink :: Parser [Inline]
pLink = do
t <- anyChar
name <- manyTill unascii tab
selector <- manyTill unascii tab
host <- manyTill unascii tab
port <- many1 digit
let uri = concat ["gopher://", host, ":", port, "/", [t], selector]
prefix = mkPrefix $ case t of
'0' -> "(text)"
'1' -> "(dir)"
'3' -> "(err)"
'h' -> "(html)"
'9' -> "(bin)"
'g' -> "(gif)"
'I' -> "(img)"
's' -> "(snd)"
'7' -> "(srch)"
_ -> "(?)"
line = case t of
'3' -> prefix ++ lineToInlines name
_ -> [Link (name, [], []) (prefix ++ lineToInlines name) (uri, "")]
pure $ line
-- | An erroneous directory entry. Still parsing it, since there is a
-- lot of broken directories out there -- but marking as an error.
pError :: Parser [Inline]
pError = do
line <- manyTill anyChar (lookAhead $ try pEOL)
pure $ [Strong $ mkPrefix "error"] ++ lineToInlines line
-- | Parses last line, with adjustments for what's used in the wild.
pLastLine :: Parser ()
-- Sometimes there's additional newline, sometimes there's no dot or
-- multiple dots, and sometimes LF is used instead of CRLF.
pLastLine = optional (try $ optional endOfLine *> char '.' *> endOfLine) *> eof
-- | Parses end-of-line, skipping Gopher+ extensions if present.
pEOL :: Parser ()
pEOL = (endOfLine *> pure ())
<|> (tab >> char '+' >> manyTill anyChar endOfLine *> pure ())
-- | Parses a directory.
pDirEntries :: Parser [[Inline]]
pDirEntries =
manyTill (choice ([ try pInfo <?> "info entry"
, try pLink <?> "link entry"
, pError <?> "erroneous entry"])
<* pEOL)
pLastLine
-- | Reads Gopher directory entries.
readGopher :: PandocMonad m => T.Text -> m Pandoc
readGopher s =
case parse pDirEntries "directory entry" s of
Left err -> throwError $ PandocParseError $ show err
Right r -> pure . Pandoc mempty . pure $ LineBlock r
| defanor/pancake | Text/Pandoc/Readers/Gopher.hs | gpl-3.0 | 3,841 | 0 | 17 | 835 | 816 | 424 | 392 | 66 | 11 |
-- -*- coding: utf-8 -*-
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
import TMM.Types
import TMM.Selector
import qualified TMM.Workers as S
import TMM.Downloader
import ZhiHu.ZSession
import Data.Text(Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.HTML.TagSoup
import qualified Data.List as L
import Data.Maybe
import System.Environment (getArgs)
import Data.Aeson
import Data.Aeson.Types
import Control.Applicative ((<$>), (<*>))
import Debug.Trace
import System.IO
import Control.Monad
import qualified Data.HashMap.Strict as M
import Data.Typeable
import Control.DeepSeq
main = do
config <- initConfig
sum <- S.executeAction config startUrls
S.verbose sum
where
initConfig = do
return S.defaultConfig { S._cParsers = [("topic", topicPageParser, Tags)]
, S._cProcessors = [ ("topic", valuePrinter)]
, S._cInitSession = Just $ zhiHuLogin
, S._cCookieAction = Just $ S.CookieAction updateCookieXsrf
, S._cEnableCookie = True
, S._cFixAgent = True
}
startUrls = [("https://www.zhihu.com/topic", M.empty, "topic")]
data Topic = Topic Text Text Text Int deriving (Show, Typeable)
instance NFData Topic where
rnf (Topic topic url vote author) = rnf topic `seq` rnf url `seq` rnf vote `seq` rnf author
topicPageParser :: SourceData -> IO [YieldData]
topicPageParser od = trace "topicPageParser run" $
return $ runSelector (originTags od) selector
where
selector = at "#zh-topic-feed-list" $ many ".feed-item .feed-content" $ do
topic <- textOf "h2"
url <- attrOf ".entry-body link" "href"
nVote <- t2i <$> textOf ".zm-item-vote a"
author <- textOf ".author-link-line a"
return $ yieldData od $ Topic topic url author nVote
valuePrinter :: ResultData -> IO ()
valuePrinter rd = do
let (Topic topic url author vote) = resultData rd
T.putStrLn "--------------------------------------------------"
T.putStrLn $ T.concat ["topic: ", topic, "\nurl: ", url,
"\nvote: ", T.pack $ show vote, "\nauthor: ", author]
| stone-guru/tmmha | src/ZTopic.hs | gpl-3.0 | 2,305 | 1 | 12 | 548 | 630 | 343 | 287 | 55 | 1 |
{-
This file is part of Deutsche Nummers.
Deutsche Nummers 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.
Deutsche Nummers 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 Deutsche Nummers. If not, see <http://www.gnu.org/licenses/>.
-}
module Main where
import System.Random
import Data.IORef
import HTk.Toplevel.HTk
import Nummer
data Screen = Haupt | Lesen | Schreiben | Frei
run window Haupt = do
lesenB <- newButton window [text "Lesen"]
schreibenB <- newButton window [text "Schreiben"]
freiB <- newButton window [text "Frei"]
beendenB <- newButton window [text "Beenden"]
pack lesenB [Side AtTop, Fill X]
pack schreibenB [Side AtTop, Fill X]
pack freiB [Side AtTop, Fill X]
pack beendenB [Side AtBottom, Fill X]
lesenCl <- clicked lesenB
schreibenCl <- clicked schreibenB
freiCl <- clicked freiB
beendenCl <- clicked beendenB
let exit = do
destroy lesenB
destroy schreibenB
destroy freiB
destroy beendenB
done
let lesenAction = do
exit
run window Lesen
done
let schreibenAction = do
exit
run window Schreiben
done
let freiAction = do
exit
run window Frei
done
_ <- spawnEvent (forever (
(beendenCl >>> destroy window) +>
(schreibenCl >>> schreibenAction) +>
(freiCl >>> freiAction) +>
(lesenCl >>> lesenAction)))
finishHTk
run window Lesen = do
zuruckB <- newButton window [text "Zurück"]
beendenB <- newButton window [text "Beenden"]
val <- randomRIO (0,1000)
answer <- newIORef val
status <- newLabel window [text "", font (Lucida,18::Int)]
nummer <- newLabel window [text (schreibenNummer val), relief Raised]
entry <- (newEntry window [value "", width 30])::IO (Entry String)
pack status [Side AtTop, IPadX 10 ,PadX 10, PadY 5]
pack nummer [Side AtTop, IPadX 10 ,PadX 10, PadY 20]
pack entry [Side AtTop, IPadX 10 ,PadX 10, PadY 10]
pack beendenB [Side AtBottom, Fill X]
pack zuruckB [Side AtBottom, Fill X]
(entered,_) <- bind entry [WishEvent [] (KeyPress (Just (KeySym "Return")))]
zuruckCl <- clicked zuruckB
beendenCl <- clicked beendenB
let exit = do
destroy status
destroy nummer
destroy entry
destroy zuruckB
destroy beendenB
done
let enterAction = do
attempt <- (getValue entry)::IO String
correct <- readIORef answer
if attempt == show correct then do
val <- randomRIO (0,1000)
_ <- writeIORef answer val
nummer # text (schreibenNummer val)
status # text "Richtig"
status # foreground (0::Int,130::Int,0::Int)
else do
status # text "Falsch"
status # foreground (170::Int,10::Int,0::Int)
entry # value ""
done
let zuruckAction = do
exit
run window Haupt
done
_ <- spawnEvent (forever (
(beendenCl >>> destroy window) +>
(entered >>> enterAction) +>
(zuruckCl >>> zuruckAction)) )
finishHTk
run window Schreiben = do
zuruckB <- newButton window [text "Zurück"]
beendenB <- newButton window [text "Beenden"]
val <- randomRIO (0,1000)
answer <- newIORef (schreibenNummer val)
status <- newLabel window [text "", font (Lucida,18::Int)]
nummer <- newLabel window [text (show val), relief Raised]
entry <- (newEntry window [value "", width 30])::IO (Entry String)
pack status [Side AtTop, IPadX 10 ,PadX 10, PadY 5]
pack nummer [Side AtTop, IPadX 10 ,PadX 10, PadY 20]
pack entry [Side AtTop, IPadX 10 ,PadX 10, PadY 10]
pack beendenB [Side AtBottom, Fill X]
pack zuruckB [Side AtBottom, Fill X]
(entered,_) <- bind entry [WishEvent [] (KeyPress (Just (KeySym "Return")))]
zuruckCl <- clicked zuruckB
beendenCl <- clicked beendenB
let exit = do
destroy status
destroy nummer
destroy entry
destroy zuruckB
destroy beendenB
done
let enterAction = do
attempt <- (getValue entry)::IO String
correct <- readIORef answer
if attempt == correct then do
val <- randomRIO (0,1000)
_ <- writeIORef answer (schreibenNummer val)
nummer # text (show val)
status # text "Richtig"
status # foreground (0::Int,130::Int,0::Int)
else do
status # text "Falsch"
status # foreground (170::Int,10::Int,0::Int)
entry # value ""
done
let zuruckAction = do
exit
run window Haupt
done
_ <- spawnEvent (forever (
(beendenCl >>> destroy window) +>
(entered >>> enterAction) +>
(zuruckCl >>> zuruckAction)) )
finishHTk
run window Frei = do
zuruckB <- newButton window [text "Zurück"]
beendenB <- newButton window [text "Beenden"]
nummer <- newMessage window [text "", aspect 1000 ,relief Raised]
entry <- (newEntry window [value "", width 30])::IO (Entry String)
pack nummer [Side AtTop, IPadX 10 ,PadX 10, PadY 5]
pack entry [Side AtTop, IPadX 10 ,PadX 10, PadY 10]
pack beendenB [Side AtBottom, Fill X]
pack zuruckB [Side AtBottom, Fill X]
(entered,_) <- bind entry [WishEvent [] (KeyPress (Just (KeySym "Return")))]
zuruckCl <- clicked zuruckB
beendenCl <- clicked beendenB
let exit = do
destroy nummer
destroy entry
destroy zuruckB
destroy beendenB
done
let enterAction = do
attempt <- (getValue entry)::IO String
nummer # text (schreibenNummer (read attempt::Int))
entry # value ""
done
let zuruckAction = do
exit
run window Haupt
done
_ <- spawnEvent (forever (
(beendenCl >>> destroy window) +>
(entered >>> enterAction) +>
(zuruckCl >>> zuruckAction)) )
finishHTk
-- run _ _ = return ()
main = do
window <- initHTk [text "Nummers auf Deutsch", size (500,200)]
run window Haupt | mgmillani/deutsche-helfer | deutscheNummers/Main.hs | gpl-3.0 | 6,076 | 26 | 18 | 1,431 | 2,322 | 1,077 | 1,245 | 170 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Scotty where
import Web.Scotty
import Data.Monoid (mconcat)
import Web.Scotty.Internal.Types (ActionT(..))
import Control.Monad.IO.Class
import Control.Monad.Trans.State.Lazy hiding (get)
main =
scotty 3000 $
get "/:word" $ do
beam <- param "word"
liftIO (putStrLn "hello")
html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"]
| maruks/haskell-book | src/scotty.hs | gpl-3.0 | 388 | 0 | 10 | 64 | 117 | 67 | 50 | 13 | 1 |
import QFeldspar.QDSL
import qualified QFeldspar.Environment.Typed as ET
import qualified QFeldspar.Environment.Scoped as ES
import qualified QFeldspar.Type.GADT as TG
import qualified QFeldspar.Nat.GADT as NG
import QFeldspar.Expression.Utils.TemplateHaskell as TH
iff :: Bool -> a -> a -> a
iff l m n = if l then m else n
-- below is generated automatically by the tool using Template Haskell
et = ET.Ext (TG.Arr TG.Bol (TG.Arr (TG.TVr NG.Zro)
(TG.Arr (TG.TVr NG.Zro) (TG.TVr NG.Zro)))) ET.Emp
-- below is generated automatically by the tool using Template Haskell
es = ES.Ext (TH.stripNameSpace ('iff)) ES.Emp
testQ1 :: Qt (Bool -> Float)
testQ1 = [|| \ x -> iff x 1.1 1.1 ||]
miniFeldspar1 = translateFWith et es testQ1
{- gives us
(\ x0 -> (Prm $(nat 0 "") (
Ext (x0) (
Ext (ConF (1.1)) (
Ext (ConF (1.1)) (Emp))))))
which with some clean ups to make it more human readable it
would be equivalent to
(\ x0 -> Prm 0 (x0 <+> ConF 1.1 <+> ConF 1.1 <+> Emp))
where 0 ranges over the provided environment, representing iff
-}
testQ2 :: Qt Float
testQ2 = [|| (\ x -> iff x 1.1 1.1) True ||]
miniFeldspar2 = translateWith et es testQ2
{- gives us
Prm $(nat 0 "") (
Ext (ConB (True)) (
Ext (ConF (1.1)) (
Ext (ConF (1.1)) (Emp))))
which with some clean ups to make it more human readable it
would be equivalent to
Prm 0 (ConB True <+> ConF 1.1 <+> ConF 1.1 <+> Emp)
where 0 ranges over the provided environment, representing iff
-}
-- I am no implementing free evaluator and optimiser
-- (e.g. partial evaluator), which would for example reduce above to
-- ConF 1.1 (based on Haskell semantics)
| shayan-najd/QFeldspar | Tests/PolyMorphism.hs | gpl-3.0 | 1,673 | 9 | 14 | 361 | 316 | 173 | 143 | -1 | -1 |
module Main where
import Web.Fjord
import Web.Fjord.Types
import Web.Fjord.KeyBinds
import Web.Fjord.Modifier
import qualified Data.Map as Map
defaultConfig = FjordConfig {
_keybinds = Map.fromList [ createKeyBind [] (Just 'k') scrollUp
, createKeyBind [] (Just 'j') scrollDown
, createKeyBind [shift] (Just ':') showEntry]
}
main = fjord defaultConfig
| arjuncomar/fjord | Main.hs | gpl-3.0 | 413 | 0 | 11 | 106 | 116 | 66 | 50 | 11 | 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.Content.Accounts.Returncarrier.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 available return carriers in the merchant account.
--
-- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.accounts.returncarrier.list@.
module Network.Google.Resource.Content.Accounts.Returncarrier.List
(
-- * REST Resource
AccountsReturncarrierListResource
-- * Creating a Request
, accountsReturncarrierList
, AccountsReturncarrierList
-- * Request Lenses
, arlXgafv
, arlUploadProtocol
, arlAccessToken
, arlUploadType
, arlAccountId
, arlCallback
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.accounts.returncarrier.list@ method which the
-- 'AccountsReturncarrierList' request conforms to.
type AccountsReturncarrierListResource =
"content" :>
"v2.1" :>
"accounts" :>
Capture "accountId" (Textual Int64) :>
"returncarrier" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListAccountReturnCarrierResponse
-- | Lists available return carriers in the merchant account.
--
-- /See:/ 'accountsReturncarrierList' smart constructor.
data AccountsReturncarrierList =
AccountsReturncarrierList'
{ _arlXgafv :: !(Maybe Xgafv)
, _arlUploadProtocol :: !(Maybe Text)
, _arlAccessToken :: !(Maybe Text)
, _arlUploadType :: !(Maybe Text)
, _arlAccountId :: !(Textual Int64)
, _arlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsReturncarrierList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'arlXgafv'
--
-- * 'arlUploadProtocol'
--
-- * 'arlAccessToken'
--
-- * 'arlUploadType'
--
-- * 'arlAccountId'
--
-- * 'arlCallback'
accountsReturncarrierList
:: Int64 -- ^ 'arlAccountId'
-> AccountsReturncarrierList
accountsReturncarrierList pArlAccountId_ =
AccountsReturncarrierList'
{ _arlXgafv = Nothing
, _arlUploadProtocol = Nothing
, _arlAccessToken = Nothing
, _arlUploadType = Nothing
, _arlAccountId = _Coerce # pArlAccountId_
, _arlCallback = Nothing
}
-- | V1 error format.
arlXgafv :: Lens' AccountsReturncarrierList (Maybe Xgafv)
arlXgafv = lens _arlXgafv (\ s a -> s{_arlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
arlUploadProtocol :: Lens' AccountsReturncarrierList (Maybe Text)
arlUploadProtocol
= lens _arlUploadProtocol
(\ s a -> s{_arlUploadProtocol = a})
-- | OAuth access token.
arlAccessToken :: Lens' AccountsReturncarrierList (Maybe Text)
arlAccessToken
= lens _arlAccessToken
(\ s a -> s{_arlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
arlUploadType :: Lens' AccountsReturncarrierList (Maybe Text)
arlUploadType
= lens _arlUploadType
(\ s a -> s{_arlUploadType = a})
-- | Required. The Merchant Center Account Id under which the Return Carrier
-- is to be linked.
arlAccountId :: Lens' AccountsReturncarrierList Int64
arlAccountId
= lens _arlAccountId (\ s a -> s{_arlAccountId = a})
. _Coerce
-- | JSONP
arlCallback :: Lens' AccountsReturncarrierList (Maybe Text)
arlCallback
= lens _arlCallback (\ s a -> s{_arlCallback = a})
instance GoogleRequest AccountsReturncarrierList
where
type Rs AccountsReturncarrierList =
ListAccountReturnCarrierResponse
type Scopes AccountsReturncarrierList =
'["https://www.googleapis.com/auth/content"]
requestClient AccountsReturncarrierList'{..}
= go _arlAccountId _arlXgafv _arlUploadProtocol
_arlAccessToken
_arlUploadType
_arlCallback
(Just AltJSON)
shoppingContentService
where go
= buildClient
(Proxy :: Proxy AccountsReturncarrierListResource)
mempty
| brendanhay/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Accounts/Returncarrier/List.hs | mpl-2.0 | 5,082 | 0 | 18 | 1,177 | 728 | 423 | 305 | 107 | 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.Books.MyConfig.UpdateUserSettings
-- 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)
--
-- Sets the settings for the user. If a sub-object is specified, it will
-- overwrite the existing sub-object stored in the server. Unspecified
-- sub-objects will retain the existing value.
--
-- /See:/ <https://developers.google.com/books/docs/v1/getting_started Books API Reference> for @books.myconfig.updateUserSettings@.
module Network.Google.Resource.Books.MyConfig.UpdateUserSettings
(
-- * REST Resource
MyConfigUpdateUserSettingsResource
-- * Creating a Request
, myConfigUpdateUserSettings
, MyConfigUpdateUserSettings
-- * Request Lenses
, mcuusPayload
) where
import Network.Google.Books.Types
import Network.Google.Prelude
-- | A resource alias for @books.myconfig.updateUserSettings@ method which the
-- 'MyConfigUpdateUserSettings' request conforms to.
type MyConfigUpdateUserSettingsResource =
"books" :>
"v1" :>
"myconfig" :>
"updateUserSettings" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] UserSettings :>
Post '[JSON] UserSettings
-- | Sets the settings for the user. If a sub-object is specified, it will
-- overwrite the existing sub-object stored in the server. Unspecified
-- sub-objects will retain the existing value.
--
-- /See:/ 'myConfigUpdateUserSettings' smart constructor.
newtype MyConfigUpdateUserSettings = MyConfigUpdateUserSettings'
{ _mcuusPayload :: UserSettings
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'MyConfigUpdateUserSettings' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mcuusPayload'
myConfigUpdateUserSettings
:: UserSettings -- ^ 'mcuusPayload'
-> MyConfigUpdateUserSettings
myConfigUpdateUserSettings pMcuusPayload_ =
MyConfigUpdateUserSettings'
{ _mcuusPayload = pMcuusPayload_
}
-- | Multipart request metadata.
mcuusPayload :: Lens' MyConfigUpdateUserSettings UserSettings
mcuusPayload
= lens _mcuusPayload (\ s a -> s{_mcuusPayload = a})
instance GoogleRequest MyConfigUpdateUserSettings
where
type Rs MyConfigUpdateUserSettings = UserSettings
type Scopes MyConfigUpdateUserSettings =
'["https://www.googleapis.com/auth/books"]
requestClient MyConfigUpdateUserSettings'{..}
= go (Just AltJSON) _mcuusPayload booksService
where go
= buildClient
(Proxy :: Proxy MyConfigUpdateUserSettingsResource)
mempty
| rueshyna/gogol | gogol-books/gen/Network/Google/Resource/Books/MyConfig/UpdateUserSettings.hs | mpl-2.0 | 3,355 | 0 | 13 | 700 | 312 | 193 | 119 | 50 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.CustomSearch
-- 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)
--
-- Lets you search over a website or collection of websites
--
-- /See:/ <https://developers.google.com/custom-search/v1/using_rest CustomSearch API Reference>
module Network.Google.CustomSearch
(
-- * Service Configuration
customSearchService
-- * API Declaration
, CustomSearchAPI
-- * Resources
-- ** search.cse.list
, module Network.Google.Resource.Search.CSE.List
-- * Types
-- ** CSEListImgType
, CSEListImgType (..)
-- ** PromotionImage
, PromotionImage
, promotionImage
, piHeight
, piWidth
, piSource
-- ** Context
, Context
, context
, cFacets
, cTitle
-- ** CSEListSiteSearchFilter
, CSEListSiteSearchFilter (..)
-- ** SearchQueries
, SearchQueries
, searchQueries
, sqAddtional
-- ** ResultPagemapAdditionalItem
, ResultPagemapAdditionalItem
, resultPagemapAdditionalItem
, rpaiAddtional
-- ** SearchURL
, SearchURL
, searchURL
, suType
, suTemplate
-- ** SearchSpelling
, SearchSpelling
, searchSpelling
, ssCorrectedQuery
, ssHTMLCorrectedQuery
-- ** CSEListImgDominantColor
, CSEListImgDominantColor (..)
-- ** ResultImage
, ResultImage
, resultImage
, riThumbnailLink
, riHeight
, riByteSize
, riContextLink
, riThumbnailHeight
, riWidth
, riThumbnailWidth
-- ** CSEListSafe
, CSEListSafe (..)
-- ** ResultPagemap
, ResultPagemap
, resultPagemap
, rpAddtional
-- ** CSEListImgColorType
, CSEListImgColorType (..)
-- ** Result
, Result
, result
, rMime
, rImage
, rPagemap
, rDisplayLink
, rFileFormat
, rSnippet
, rKind
, rLink
, rHTMLSnippet
, rHTMLFormattedURL
, rCacheId
, rFormattedURL
, rHTMLTitle
, rLabels
, rTitle
-- ** ResultLabelsItem
, ResultLabelsItem
, resultLabelsItem
, rliName
, rliDisplayName
, rliLabelWithOp
-- ** SearchSearchInformation
, SearchSearchInformation
, searchSearchInformation
, ssiSearchTime
, ssiFormattedSearchTime
, ssiTotalResults
, ssiFormattedTotalResults
-- ** CSEListFilter
, CSEListFilter (..)
-- ** Query
, Query
, query
, qImgDominantColor
, qOutputEncoding
, qSiteSearchFilter
, qInputEncoding
, qOrTerms
, qSearchTerms
, qStartPage
, qRights
, qCount
, qExcludeTerms
, qFileType
, qSearchType
, qGoogleHost
, qDisableCnTwTranslation
, qRelatedSite
, qHl
, qCref
, qSort
, qLanguage
, qSiteSearch
, qFilter
, qTotalResults
, qDateRestrict
, qTitle
, qLinkSite
, qLowRange
, qImgType
, qGl
, qCx
, qImgColorType
, qImgSize
, qExactTerms
, qStartIndex
, qCr
, qSafe
, qHq
, qHighRange
-- ** PromotionBodyLinesItem
, PromotionBodyLinesItem
, promotionBodyLinesItem
, pbliLink
, pbliURL
, pbliHTMLTitle
, pbliTitle
-- ** Promotion
, Promotion
, promotion
, pImage
, pDisplayLink
, pBodyLines
, pLink
, pHTMLTitle
, pTitle
-- ** Search
, Search
, search
, sQueries
, sContext
, sKind
, sURL
, sItems
, sSearchInformation
, sPromotions
, sSpelling
-- ** CSEListLr
, CSEListLr (..)
-- ** ContextFacetsItemItem
, ContextFacetsItemItem
, contextFacetsItemItem
, cfiiAnchor
, cfiiLabelWithOp
, cfiiLabel
-- ** CSEListSearchType
, CSEListSearchType (..)
-- ** CSEListImgSize
, CSEListImgSize (..)
) where
import Network.Google.CustomSearch.Types
import Network.Google.Prelude
import Network.Google.Resource.Search.CSE.List
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the CustomSearch API service.
type CustomSearchAPI = CSEListResource
| rueshyna/gogol | gogol-customsearch/gen/Network/Google/CustomSearch.hs | mpl-2.0 | 4,482 | 0 | 5 | 1,293 | 557 | 393 | 164 | 154 | 0 |
module TesML.Data where
import TesML.Data.Types
import qualified TesML.Data.Plugin as PL
import qualified TesML.Data.RecordData as RD
import qualified TesML.Data.RecordHeader as RH
import Control.Monad.Trans.Except (ExceptT (ExceptT), runExceptT)
import qualified Data.ByteString.Lazy as BSL
import Data.Binary.Get ( runGet
, runGetOrFail
, skip
)
readPlugin :: FilePath -> ExceptT String IO PL.Plugin
readPlugin pth = ExceptT $ fmap f $ BSL.readFile pth
where f bts = let r = runGetOrFail (PL.decoder pth) bts in
case r of Left (_, x, msg) -> Left $ "Decoder error at offset " ++ show x ++ ": " ++ msg
Right (_, _, p) -> Right p
readPluginSet :: [FilePath] -> ExceptT String IO PL.PluginSet
readPluginSet fnames = fios >>= ExceptT . pure . foldr f (Right [])
where fios :: ExceptT String IO [PL.Plugin]
fios = sequenceA $ readPlugin <$> fnames
f :: PL.Plugin -> Either String PL.PluginSet -> Either String PL.PluginSet
f p eps = eps >>= PL.addPlugin p
readRecordData' :: FilePath -> RH.RecordHeader -> IO (ReadResult RD.RecordData)
readRecordData' pluginPath hdr = (runGet $ skipper >> decoder) <$> BSL.readFile pluginPath
where skipper = skip $ fromIntegral (RH.offset hdr + entryHeaderSize)
decoder = runExceptT $ RD.getDecoder $ RH.name hdr
readRecordData :: PL.ModEntry RH.RecordHeader -> IO (ReadResult RD.RecordData)
readRecordData (PL.ModEntry path _ hdr) = readRecordData' path hdr
| Kromgart/tesML | lib/TesML/Data.hs | agpl-3.0 | 1,582 | 0 | 15 | 400 | 510 | 271 | 239 | 27 | 2 |
-- | Parsing of structs.
module Data.GI.GIR.Struct
( Struct(..)
, parseStruct
) where
import Data.Text (Text)
import Data.GI.GIR.Allocation (AllocationInfo(..), unknownAllocationInfo)
import Data.GI.GIR.Field (Field, parseFields)
import Data.GI.GIR.Method (Method, MethodType(..), parseMethod)
import Data.GI.GIR.Parser
import Data.GI.GIR.Type (queryCType)
data Struct = Struct {
structIsBoxed :: Bool,
structAllocationInfo :: AllocationInfo,
structTypeInit :: Maybe Text,
structCType :: Maybe Text,
structSize :: Int,
gtypeStructFor :: Maybe Name,
-- https://bugzilla.gnome.org/show_bug.cgi?id=560248
structIsDisguised :: Bool,
structFields :: [Field],
structMethods :: [Method],
structDeprecated :: Maybe DeprecationInfo,
structDocumentation :: Documentation }
deriving Show
parseStruct :: Parser (Name, Struct)
parseStruct = do
name <- parseName
deprecated <- parseDeprecation
doc <- parseDocumentation
structFor <- queryAttrWithNamespace GLibGIRNS "is-gtype-struct-for" >>= \case
Just t -> (fmap Just . qualifyName) t
Nothing -> return Nothing
typeInit <- queryAttrWithNamespace GLibGIRNS "get-type"
maybeCType <- queryCType
disguised <- optionalAttr "disguised" False parseBool
fields <- parseFields
constructors <- parseChildrenWithLocalName "constructor" (parseMethod Constructor)
methods <- parseChildrenWithLocalName "method" (parseMethod OrdinaryMethod)
functions <- parseChildrenWithLocalName "function" (parseMethod MemberFunction)
return (name,
Struct {
structIsBoxed = error ("[boxed] unfixed struct " ++ show name)
, structAllocationInfo = unknownAllocationInfo
, structTypeInit = typeInit
, structCType = maybeCType
, structSize = error ("[size] unfixed struct " ++ show name)
, gtypeStructFor = structFor
, structIsDisguised = disguised
, structFields = fields
, structMethods = constructors ++ methods ++ functions
, structDeprecated = deprecated
, structDocumentation = doc
})
| ford-prefect/haskell-gi | lib/Data/GI/GIR/Struct.hs | lgpl-2.1 | 2,150 | 0 | 15 | 472 | 500 | 282 | 218 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module MedianOfTwoSortedArrays (
findMedian,
sample
) where
import Data.Vector (fromList, (!), Vector)
import Data.Vector as Vec
import Debug.Trace
data Median a = Pair a a
| Single a
deriving (Show)
-- After using scoped type variables, we could give type-signatures
-- to subterms which reference the type in parent functions.
findMedian :: forall a. (Ord a) => Vector a -> Vector a -> Median a
-- findMedian :: (Ord a) => Vector a -> Vector a -> Median a
-- 1 -- 2
-- 3 -- 4
findMedian vec1 vec2 = if even (len1 + len2)
then Pair (kth vec1 vec2 halflen) (kth vec1 vec2 (halflen+1))
else Single $ kth vec1 vec2 (halflen+1)
where len1 = Vec.length vec1
len2 = Vec.length vec2
div2 = (`div` 2)
halflen = div2 (len1 + len2)
kth :: (Ord a) => Vector a -> Vector a -> Int -> a
kth vec1 vec2 k = go 0 (len1-1) 0 (len2-1) k
where go :: (Ord a) => Int -> Int -> Int -> Int -> Int -> a
go p1 r1 p2 r2 k
| p1 > r1 = vec2 ! (p2+k-1)
| p2 > r2 = vec1 ! (p1+k-1)
| v1 < v2 && hflen < k = go (m1+1) r1 p2 r2 (k-hflen1) -- discard part 1
| v1 < v2 && hflen >= k = go p1 r1 p2 (m2-1) k -- discard part 4
| v1 >= v2 && hflen < k = go p1 r1 (m2+1) r2 (k-hflen2) -- discard part 3
| v1 >= v2 && hflen >= k = go p1 (m1-1) p2 r2 k -- discard part 2
where (m1::Int) = div2 (p1+r1)
(m2::Int) = div2 (p2+r2)
v1 = vec1 Vec.! m1
v2 = vec2 Vec.! m2
hflen1 = m1-p1+1
hflen2 = m2-p2+1
hflen = hflen1+hflen2-1
sample = [findMedian (fromList [1,4]) (fromList [2,3]),
findMedian (fromList [1,2]) (fromList [3,4,5]),
findMedian (fromList [1]) (fromList [2,3]),
findMedian (fromList [1]) (fromList [2])
]
| seckcoder/lang-learn | haskell/algo/src/Leetcode/MedianOfTwoSortedArrays.hs | unlicense | 2,799 | 0 | 14 | 1,516 | 818 | 438 | 380 | 39 | 2 |
-- Copyright 2020-2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE CPP #-}
{-# LANGUAGE NegativeLiterals #-}
{-# LANGUAGE TypeOperators #-}
module DoubleNegation where
-- HLint doesn't parse the thing we're trying to test here, so shut it up.
#if !defined(__HLINT__)
import Data.Fin.Int (Fin)
import Data.Word (Word8)
import Data.Type.Equality ((:~:)(Refl))
import Data.SInt (SInt)
-- Turns out you can have both syntactic negation and a negative literal in the
-- same pattern/expression. We should not have a bug when doing that.
x0 :: Int -> String
x0 x = case x of
-1 -> "-1"
- -2 -> "2...?"
_ -> "_"
-- Make sure we in fact get proof for +2 out of matching on @- -2@.
x1 :: SInt n -> Maybe (n :~: 2)
x1 x = case x of
- -2 -> Just Refl
_ -> Nothing
x2 :: Word8
x2 = - -8
x3 :: Fin 5
x3 = - -4
x4 :: SInt 2 -> SInt 2
x4 x = case x of
- -2 -> x
_ -> x
#endif
| google/hs-dependent-literals | dependent-literals-plugin/tests/DoubleNegation.hs | apache-2.0 | 1,424 | 5 | 8 | 291 | 246 | 143 | 103 | -1 | -1 |
-- layout can still have explicit semicolons
f x = let a = 1
; b = 2
c = 3
in x
| metaborg/jsglr | org.spoofax.jsglr/tests-offside/terms/doaitse/layout5.hs | apache-2.0 | 106 | 2 | 8 | 49 | 36 | 17 | 19 | 4 | 1 |
{-| Implementation of the job queue.
-}
{-
Copyright (C) 2010, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.JQueue
( queuedOpCodeFromMetaOpCode
, queuedJobFromOpCodes
, changeOpCodePriority
, changeJobPriority
, cancelQueuedJob
, failQueuedJob
, fromClockTime
, noTimestamp
, currentTimestamp
, advanceTimestamp
, reasonTrailTimestamp
, setReceivedTimestamp
, extendJobReasonTrail
, getJobDependencies
, opStatusFinalized
, extractOpSummary
, calcJobStatus
, jobStarted
, jobFinalized
, jobArchivable
, calcJobPriority
, jobFileName
, liveJobFile
, archivedJobFile
, determineJobDirectories
, getJobIDs
, sortJobIDs
, loadJobFromDisk
, noSuchJob
, readSerialFromDisk
, allocateJobIds
, allocateJobId
, writeJobToDisk
, replicateManyJobs
, writeAndReplicateJob
, isQueueOpen
, startJobs
, cancelJob
, tellJobPriority
, notifyJob
, waitUntilJobExited
, queueDirPermissions
, archiveJobs
-- re-export
, Timestamp
, InputOpCode(..)
, QueuedOpCode(..)
, QueuedJob(..)
) where
import Control.Applicative (liftA2, (<|>))
import Control.Arrow (first, second)
import Control.Concurrent (forkIO, threadDelay)
import Control.Exception
import Control.Lens (over)
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Maybe
import Data.List
import Data.Maybe
import Data.Ord (comparing)
-- workaround what seems to be a bug in ghc 7.4's TH shadowing code
import Prelude hiding (id, log)
import System.Directory
import System.FilePath
import System.IO.Error (isDoesNotExistError)
import System.Posix.Files
import System.Posix.Signals (sigHUP, sigTERM, sigUSR1, sigKILL, signalProcess)
import System.Posix.Types (ProcessID)
import System.Time
import qualified Text.JSON
import Text.JSON.Types
import Ganeti.BasicTypes
import qualified Ganeti.Config as Config
import qualified Ganeti.Constants as C
import Ganeti.Errors (ErrorResult, ResultG)
import Ganeti.JQueue.Lens (qoInputL, validOpCodeL)
import Ganeti.JQueue.Objects
import Ganeti.JSON (fromJResult, fromObjWithDefault)
import Ganeti.Logging
import Ganeti.Luxi
import Ganeti.Objects (ConfigData, Node)
import Ganeti.OpCodes
import Ganeti.OpCodes.Lens (metaParamsL, opReasonL)
import Ganeti.Path
import Ganeti.Query.Exec as Exec
import Ganeti.Rpc (executeRpcCall, ERpcError, logRpcErrors,
RpcCallJobqueueUpdate(..), RpcCallJobqueueRename(..))
import Ganeti.Runtime (GanetiDaemon(..), GanetiGroup(..), MiscGroup(..))
import Ganeti.Types
import Ganeti.Utils
import Ganeti.Utils.Atomic
import Ganeti.Utils.Livelock (Livelock, isDead)
import Ganeti.Utils.MVarLock
import Ganeti.VCluster (makeVirtualPath)
-- * Data types
-- | Missing timestamp type.
noTimestamp :: Timestamp
noTimestamp = (-1, -1)
-- | Obtain a Timestamp from a given clock time
fromClockTime :: ClockTime -> Timestamp
fromClockTime (TOD ctime pico) =
(fromIntegral ctime, fromIntegral $ pico `div` 1000000)
-- | Get the current time in the job-queue timestamp format.
currentTimestamp :: IO Timestamp
currentTimestamp = fromClockTime `liftM` getClockTime
-- | From a given timestamp, obtain the timestamp of the
-- time that is the given number of seconds later.
advanceTimestamp :: Int -> Timestamp -> Timestamp
advanceTimestamp = first . (+)
-- | From an InputOpCode obtain the MetaOpCode, if any.
toMetaOpCode :: InputOpCode -> [MetaOpCode]
toMetaOpCode (ValidOpCode mopc) = [mopc]
toMetaOpCode _ = []
-- | Invalid opcode summary.
invalidOp :: String
invalidOp = "INVALID_OP"
-- | Tries to extract the opcode summary from an 'InputOpCode'. This
-- duplicates some functionality from the 'opSummary' function in
-- "Ganeti.OpCodes".
extractOpSummary :: InputOpCode -> String
extractOpSummary (ValidOpCode metaop) = opSummary $ metaOpCode metaop
extractOpSummary (InvalidOpCode (JSObject o)) =
case fromObjWithDefault (fromJSObject o) "OP_ID" ("OP_" ++ invalidOp) of
Just s -> drop 3 s -- drop the OP_ prefix
Nothing -> invalidOp
extractOpSummary _ = invalidOp
-- | Convenience function to obtain a QueuedOpCode from a MetaOpCode
queuedOpCodeFromMetaOpCode :: MetaOpCode -> QueuedOpCode
queuedOpCodeFromMetaOpCode op =
QueuedOpCode { qoInput = ValidOpCode op
, qoStatus = OP_STATUS_QUEUED
, qoPriority = opSubmitPriorityToRaw . opPriority . metaParams
$ op
, qoLog = []
, qoResult = JSNull
, qoStartTimestamp = Nothing
, qoEndTimestamp = Nothing
, qoExecTimestamp = Nothing
}
-- | From a job-id and a list of op-codes create a job. This is
-- the pure part of job creation, as allocating a new job id
-- lives in IO.
queuedJobFromOpCodes :: (Monad m) => JobId -> [MetaOpCode] -> m QueuedJob
queuedJobFromOpCodes jobid ops = do
ops' <- mapM (`resolveDependencies` jobid) ops
return QueuedJob { qjId = jobid
, qjOps = map queuedOpCodeFromMetaOpCode ops'
, qjReceivedTimestamp = Nothing
, qjStartTimestamp = Nothing
, qjEndTimestamp = Nothing
, qjLivelock = Nothing
, qjProcessId = Nothing
}
-- | Attach a received timestamp to a Queued Job.
setReceivedTimestamp :: Timestamp -> QueuedJob -> QueuedJob
setReceivedTimestamp ts job = job { qjReceivedTimestamp = Just ts }
-- | Build a timestamp in the format expected by the reason trail (nanoseconds)
-- starting from a JQueue Timestamp.
reasonTrailTimestamp :: Timestamp -> Integer
reasonTrailTimestamp (sec, micro) =
let sec' = toInteger sec
micro' = toInteger micro
in sec' * 1000000000 + micro' * 1000
-- | Append an element to the reason trail of an input opcode.
extendInputOpCodeReasonTrail :: JobId -> Timestamp -> Int -> InputOpCode
-> InputOpCode
extendInputOpCodeReasonTrail _ _ _ op@(InvalidOpCode _) = op
extendInputOpCodeReasonTrail jid ts i (ValidOpCode vOp) =
let metaP = metaParams vOp
op = metaOpCode vOp
trail = opReason metaP
reasonSrc = opReasonSrcID op
reasonText = "job=" ++ show (fromJobId jid) ++ ";index=" ++ show i
reason = (reasonSrc, reasonText, reasonTrailTimestamp ts)
trail' = trail ++ [reason]
in ValidOpCode $ vOp { metaParams = metaP { opReason = trail' } }
-- | Append an element to the reason trail of a queued opcode.
extendOpCodeReasonTrail :: JobId -> Timestamp -> Int -> QueuedOpCode
-> QueuedOpCode
extendOpCodeReasonTrail jid ts i op =
let inOp = qoInput op
in op { qoInput = extendInputOpCodeReasonTrail jid ts i inOp }
-- | Append an element to the reason trail of all the OpCodes of a queued job.
extendJobReasonTrail :: QueuedJob -> QueuedJob
extendJobReasonTrail job =
let jobId = qjId job
mTimestamp = qjReceivedTimestamp job
-- This function is going to be called on QueuedJobs that already contain
-- a timestamp. But for safety reasons we cannot assume mTimestamp will
-- be (Just timestamp), so we use the value 0 in the extremely unlikely
-- case this is not true.
timestamp = fromMaybe (0, 0) mTimestamp
in job
{ qjOps =
zipWith (extendOpCodeReasonTrail jobId timestamp) [0..] $
qjOps job
}
-- | From a queued job obtain the list of jobs it depends on.
getJobDependencies :: QueuedJob -> [JobId]
getJobDependencies job = do
op <- qjOps job
mopc <- toMetaOpCode $ qoInput op
dep <- fromMaybe [] . opDepends $ metaParams mopc
getJobIdFromDependency dep
-- | Change the priority of a QueuedOpCode, if it is not already
-- finalized.
changeOpCodePriority :: Int -> QueuedOpCode -> QueuedOpCode
changeOpCodePriority prio op =
if qoStatus op > OP_STATUS_RUNNING
then op
else op { qoPriority = prio }
-- | Set the state of a QueuedOpCode to canceled.
cancelOpCode :: Timestamp -> QueuedOpCode -> QueuedOpCode
cancelOpCode now op =
op { qoStatus = OP_STATUS_CANCELED, qoEndTimestamp = Just now }
-- | Change the priority of a job, i.e., change the priority of the
-- non-finalized opcodes.
changeJobPriority :: Int -> QueuedJob -> QueuedJob
changeJobPriority prio job =
job { qjOps = map (changeOpCodePriority prio) $ qjOps job }
-- | Transform a QueuedJob that has not been started into its canceled form.
cancelQueuedJob :: Timestamp -> QueuedJob -> QueuedJob
cancelQueuedJob now job =
let ops' = map (cancelOpCode now) $ qjOps job
in job { qjOps = ops', qjEndTimestamp = Just now }
-- | Set the state of a QueuedOpCode to failed
-- and set the Op result using the given reason message.
failOpCode :: ReasonElem -> Timestamp -> QueuedOpCode -> QueuedOpCode
failOpCode reason@(_, msg, _) now op =
over (qoInputL . validOpCodeL . metaParamsL . opReasonL) (++ [reason])
op { qoStatus = OP_STATUS_ERROR
, qoResult = Text.JSON.JSString . Text.JSON.toJSString $ msg
, qoEndTimestamp = Just now }
-- | Transform a QueuedJob that has not been started into its failed form.
failQueuedJob :: ReasonElem -> Timestamp -> QueuedJob -> QueuedJob
failQueuedJob reason now job =
let ops' = map (failOpCode reason now) $ qjOps job
in job { qjOps = ops', qjEndTimestamp = Just now }
-- | Job file prefix.
jobFilePrefix :: String
jobFilePrefix = "job-"
-- | Computes the filename for a given job ID.
jobFileName :: JobId -> FilePath
jobFileName jid = jobFilePrefix ++ show (fromJobId jid)
-- | Parses a job ID from a file name.
parseJobFileId :: (Monad m) => FilePath -> m JobId
parseJobFileId path =
case stripPrefix jobFilePrefix path of
Nothing -> fail $ "Job file '" ++ path ++
"' doesn't have the correct prefix"
Just suffix -> makeJobIdS suffix
-- | Computes the full path to a live job.
liveJobFile :: FilePath -> JobId -> FilePath
liveJobFile rootdir jid = rootdir </> jobFileName jid
-- | Computes the full path to an archives job. BROKEN.
archivedJobFile :: FilePath -> JobId -> FilePath
archivedJobFile rootdir jid =
let subdir = show (fromJobId jid `div` C.jstoreJobsPerArchiveDirectory)
in rootdir </> jobQueueArchiveSubDir </> subdir </> jobFileName jid
-- | Map from opcode status to job status.
opStatusToJob :: OpStatus -> JobStatus
opStatusToJob OP_STATUS_QUEUED = JOB_STATUS_QUEUED
opStatusToJob OP_STATUS_WAITING = JOB_STATUS_WAITING
opStatusToJob OP_STATUS_SUCCESS = JOB_STATUS_SUCCESS
opStatusToJob OP_STATUS_RUNNING = JOB_STATUS_RUNNING
opStatusToJob OP_STATUS_CANCELING = JOB_STATUS_CANCELING
opStatusToJob OP_STATUS_CANCELED = JOB_STATUS_CANCELED
opStatusToJob OP_STATUS_ERROR = JOB_STATUS_ERROR
-- | Computes a queued job's status.
calcJobStatus :: QueuedJob -> JobStatus
calcJobStatus QueuedJob { qjOps = ops } =
extractOpSt (map qoStatus ops) JOB_STATUS_QUEUED True
where
terminalStatus OP_STATUS_ERROR = True
terminalStatus OP_STATUS_CANCELING = True
terminalStatus OP_STATUS_CANCELED = True
terminalStatus _ = False
softStatus OP_STATUS_SUCCESS = True
softStatus OP_STATUS_QUEUED = True
softStatus _ = False
extractOpSt [] _ True = JOB_STATUS_SUCCESS
extractOpSt [] d False = d
extractOpSt (x:xs) d old_all
| terminalStatus x = opStatusToJob x -- abort recursion
| softStatus x = extractOpSt xs d new_all -- continue unchanged
| otherwise = extractOpSt xs (opStatusToJob x) new_all
where new_all = x == OP_STATUS_SUCCESS && old_all
-- | Determine if a job has started
jobStarted :: QueuedJob -> Bool
jobStarted = (> JOB_STATUS_QUEUED) . calcJobStatus
-- | Determine if a job is finalised.
jobFinalized :: QueuedJob -> Bool
jobFinalized = (> JOB_STATUS_RUNNING) . calcJobStatus
-- | Determine if a job is finalized and its timestamp is before
-- a given time.
jobArchivable :: Timestamp -> QueuedJob -> Bool
jobArchivable ts = liftA2 (&&) jobFinalized
$ maybe False (< ts)
. liftA2 (<|>) qjEndTimestamp qjStartTimestamp
-- | Determine whether an opcode status is finalized.
opStatusFinalized :: OpStatus -> Bool
opStatusFinalized = (> OP_STATUS_RUNNING)
-- | Compute a job's priority.
calcJobPriority :: QueuedJob -> Int
calcJobPriority QueuedJob { qjOps = ops } =
helper . map qoPriority $ filter (not . opStatusFinalized . qoStatus) ops
where helper [] = C.opPrioDefault
helper ps = minimum ps
-- | Log but ignore an 'IOError'.
ignoreIOError :: a -> Bool -> String -> IOError -> IO a
ignoreIOError a ignore_noent msg e = do
unless (isDoesNotExistError e && ignore_noent) .
logWarning $ msg ++ ": " ++ show e
return a
-- | Compute the list of existing archive directories. Note that I/O
-- exceptions are swallowed and ignored.
allArchiveDirs :: FilePath -> IO [FilePath]
allArchiveDirs rootdir = do
let adir = rootdir </> jobQueueArchiveSubDir
contents <- getDirectoryContents adir `Control.Exception.catch`
ignoreIOError [] False
("Failed to list queue directory " ++ adir)
let fpaths = map (adir </>) $ filter (not . ("." `isPrefixOf`)) contents
filterM (\path ->
liftM isDirectory (getFileStatus (adir </> path))
`Control.Exception.catch`
ignoreIOError False True
("Failed to stat archive path " ++ path)) fpaths
-- | Build list of directories containing job files. Note: compared to
-- the Python version, this doesn't ignore a potential lost+found
-- file.
determineJobDirectories :: FilePath -> Bool -> IO [FilePath]
determineJobDirectories rootdir archived = do
other <- if archived
then allArchiveDirs rootdir
else return []
return $ rootdir:other
-- | Computes the list of all jobs in the given directories.
getJobIDs :: [FilePath] -> IO (GenericResult IOError [JobId])
getJobIDs = runResultT . liftM concat . mapM getDirJobIDs
-- | Sorts the a list of job IDs.
sortJobIDs :: [JobId] -> [JobId]
sortJobIDs = sortBy (comparing fromJobId)
-- | Computes the list of jobs in a given directory.
getDirJobIDs :: FilePath -> ResultT IOError IO [JobId]
getDirJobIDs path =
withErrorLogAt WARNING ("Failed to list job directory " ++ path) .
liftM (mapMaybe parseJobFileId) $ liftIO (getDirectoryContents path)
-- | Reads the job data from disk.
readJobDataFromDisk :: FilePath -> Bool -> JobId -> IO (Maybe (String, Bool))
readJobDataFromDisk rootdir archived jid = do
let live_path = liveJobFile rootdir jid
archived_path = archivedJobFile rootdir jid
all_paths = if archived
then [(live_path, False), (archived_path, True)]
else [(live_path, False)]
foldM (\state (path, isarchived) ->
liftM (\r -> Just (r, isarchived)) (readFile path)
`Control.Exception.catch`
ignoreIOError state True
("Failed to read job file " ++ path)) Nothing all_paths
-- | Failed to load job error.
noSuchJob :: Result (QueuedJob, Bool)
noSuchJob = Bad "Can't load job file"
-- | Loads a job from disk.
loadJobFromDisk :: FilePath -> Bool -> JobId -> IO (Result (QueuedJob, Bool))
loadJobFromDisk rootdir archived jid = do
raw <- readJobDataFromDisk rootdir archived jid
-- note: we need some stricness below, otherwise the wrapping in a
-- Result will create too much lazyness, and not close the file
-- descriptors for the individual jobs
return $! case raw of
Nothing -> noSuchJob
Just (str, arch) ->
liftM (\qj -> (qj, arch)) .
fromJResult "Parsing job file" $ Text.JSON.decode str
-- | Write a job to disk.
writeJobToDisk :: FilePath -> QueuedJob -> IO (Result ())
writeJobToDisk rootdir job = do
let filename = liveJobFile rootdir . qjId $ job
content = Text.JSON.encode . Text.JSON.showJSON $ job
tryAndLogIOError (atomicWriteFile filename content)
("Failed to write " ++ filename) Ok
-- | Replicate a job to all master candidates.
replicateJob :: FilePath -> [Node] -> QueuedJob -> IO [(Node, ERpcError ())]
replicateJob rootdir mastercandidates job = do
let filename = liveJobFile rootdir . qjId $ job
content = Text.JSON.encode . Text.JSON.showJSON $ job
filename' <- makeVirtualPath filename
callresult <- executeRpcCall mastercandidates
$ RpcCallJobqueueUpdate filename' content
let result = map (second (() <$)) callresult
_ <- logRpcErrors result
return result
-- | Replicate many jobs to all master candidates.
replicateManyJobs :: FilePath -> [Node] -> [QueuedJob] -> IO ()
replicateManyJobs rootdir mastercandidates =
mapM_ (replicateJob rootdir mastercandidates)
-- | Writes a job to a file and replicates it to master candidates.
writeAndReplicateJob :: (Error e)
=> ConfigData -> FilePath -> QueuedJob
-> ResultT e IO [(Node, ERpcError ())]
writeAndReplicateJob cfg rootdir job = do
mkResultT $ writeJobToDisk rootdir job
liftIO $ replicateJob rootdir (Config.getMasterCandidates cfg) job
-- | Read the job serial number from disk.
readSerialFromDisk :: IO (Result JobId)
readSerialFromDisk = do
filename <- jobQueueSerialFile
tryAndLogIOError (readFile filename) "Failed to read serial file"
(makeJobIdS . rStripSpace)
-- | Allocate new job ids.
-- To avoid races while accessing the serial file, the threads synchronize
-- over a lock, as usual provided by a Lock.
allocateJobIds :: [Node] -> Lock -> Int -> IO (Result [JobId])
allocateJobIds mastercandidates lock n =
if n <= 0
then if n == 0
then return $ Ok []
else return . Bad
$ "Can only allocate non-negative number of job ids"
else withLock lock $ do
rjobid <- readSerialFromDisk
case rjobid of
Bad s -> return . Bad $ s
Ok jid -> do
let current = fromJobId jid
serial_content = show (current + n) ++ "\n"
serial <- jobQueueSerialFile
write_result <- try $ atomicWriteFile serial serial_content
:: IO (Either IOError ())
case write_result of
Left e -> do
let msg = "Failed to write serial file: " ++ show e
logError msg
return . Bad $ msg
Right () -> do
serial' <- makeVirtualPath serial
_ <- executeRpcCall mastercandidates
$ RpcCallJobqueueUpdate serial' serial_content
return $ mapM makeJobId [(current+1)..(current+n)]
-- | Allocate one new job id.
allocateJobId :: [Node] -> Lock -> IO (Result JobId)
allocateJobId mastercandidates lock = do
jids <- allocateJobIds mastercandidates lock 1
return (jids >>= monadicThe "Failed to allocate precisely one Job ID")
-- | Decide if job queue is open
isQueueOpen :: IO Bool
isQueueOpen = liftM not (jobQueueDrainFile >>= doesFileExist)
-- | Start enqueued jobs by executing the Python code.
startJobs :: Livelock -- ^ Luxi's livelock path
-> Lock -- ^ lock for forking new processes
-> [QueuedJob] -- ^ the list of jobs to start
-> IO [ErrorResult QueuedJob]
startJobs luxiLivelock forkLock jobs = do
qdir <- queueDir
let updateJob job llfile =
void . mkResultT . writeJobToDisk qdir
$ job { qjLivelock = Just llfile }
let runJob job = withLock forkLock $ do
(llfile, _) <- Exec.forkJobProcess job luxiLivelock
(updateJob job)
return $ job { qjLivelock = Just llfile }
mapM (runResultT . runJob) jobs
-- | Try to prove that a queued job is dead. This function needs to know
-- the livelock of the caller (i.e., luxid) to avoid considering a job dead
-- that is in the process of forking off.
isQueuedJobDead :: MonadIO m => Livelock -> QueuedJob -> m Bool
isQueuedJobDead ownlivelock =
maybe (return False) (liftIO . isDead)
. mfilter (/= ownlivelock)
. qjLivelock
-- | Waits for a job's process to exit
waitUntilJobExited :: Livelock -- ^ LuxiD's own livelock
-> QueuedJob -- ^ the job to wait for
-> Int -- ^ timeout in milliseconds
-> ResultG (Bool, String)
waitUntilJobExited ownlivelock job tmout = do
let sleepDelay = 100 :: Int -- ms
jName = ("Job " ++) . show . fromJobId . qjId $ job
logDebug $ "Waiting for " ++ jName ++ " to exit"
start <- liftIO getClockTime
let tmoutPicosec :: Integer
tmoutPicosec = fromIntegral $ tmout * 1000 * 1000 * 1000
wait = noTimeDiff { tdPicosec = tmoutPicosec }
deadline = addToClockTime wait start
liftIO . fix $ \loop -> do
-- fail if the job is in the startup phase or has no livelock
dead <- maybe (fail $ jName ++ " has not yet started up")
(liftIO . isDead) . mfilter (/= ownlivelock) . qjLivelock $ job
curtime <- getClockTime
let elapsed = timeDiffToString $ System.Time.diffClockTimes
curtime start
case dead of
True -> return (True, jName ++ " process exited after " ++ elapsed)
_ | curtime < deadline -> threadDelay (sleepDelay * 1000) >> loop
_ -> fail $ jName ++ " still running after " ++ elapsed
-- | Waits for a job ordered to cancel to react, and returns whether it was
-- canceled, and a user-intended description of the reason.
waitForJobCancelation :: JobId -> Int -> ResultG (Bool, String)
waitForJobCancelation jid tmout = do
qDir <- liftIO queueDir
let jobfile = liveJobFile qDir jid
load = liftM fst <$> loadJobFromDisk qDir False jid
finalizedR = genericResult (const False) jobFinalized
jobR <- liftIO $ watchFileBy jobfile tmout finalizedR load
case calcJobStatus <$> jobR of
Ok s | s == JOB_STATUS_CANCELED ->
return (True, "Job successfully cancelled")
| finalizedR jobR ->
return (False, "Job exited before it could have been canceled,\
\ status " ++ show s)
| otherwise ->
return (False, "Job could not be canceled, status "
++ show s)
Bad e -> failError $ "Can't read job status: " ++ e
-- | Try to cancel a job that has already been handed over to execution,
-- by terminating the process.
cancelJob :: Bool -- ^ if True, use sigKILL instead of sigTERM
-> Livelock -- ^ Luxi's livelock path
-> JobId -- ^ the job to cancel
-> IO (ErrorResult (Bool, String))
cancelJob kill luxiLivelock jid = runResultT $ do
-- we can't terminate the job if it's just being started, so
-- retry several times in such a case
result <- runMaybeT . msum . flip map [0..5 :: Int] $ \tryNo -> do
-- if we're retrying, sleep for some time
when (tryNo > 0) . liftIO . threadDelay $ 100000 * (2 ^ tryNo)
-- first check if the job is alive so that we don't kill some other
-- process by accident
qDir <- liftIO queueDir
(job, _) <- lift . mkResultT $ loadJobFromDisk qDir True jid
let jName = ("Job " ++) . show . fromJobId . qjId $ job
dead <- isQueuedJobDead luxiLivelock job
case qjProcessId job of
_ | dead ->
return (True, jName ++ " has been already dead")
Just pid -> do
liftIO $ signalProcess (if kill then sigKILL else sigTERM) pid
if not kill then
if calcJobStatus job > JOB_STATUS_WAITING
then return (False, "Job no longer waiting, can't cancel\
\ (informed it anyway)")
else lift $ waitForJobCancelation jid C.luxiCancelJobTimeout
else return (True, "SIGKILL send to the process")
_ -> do
logDebug $ jName ++ " in its startup phase, retrying"
mzero
return $ fromMaybe (False, "Timeout: job still in its startup phase") result
-- | Inform a job that it is requested to change its priority. This is done
-- by writing the new priority to a file and sending SIGUSR1.
tellJobPriority :: Livelock -- ^ Luxi's livelock path
-> JobId -- ^ the job to inform
-> Int -- ^ the new priority
-> IO (ErrorResult (Bool, String))
tellJobPriority luxiLivelock jid prio = runResultT $ do
let jidS = show $ fromJobId jid
jName = "Job " ++ jidS
mDir <- liftIO luxidMessageDir
let prioFile = mDir </> jidS ++ ".prio"
liftIO . atomicWriteFile prioFile $ show prio
qDir <- liftIO queueDir
(job, _) <- mkResultT $ loadJobFromDisk qDir True jid
dead <- isQueuedJobDead luxiLivelock job
case qjProcessId job of
_ | dead -> do
liftIO $ removeFile prioFile
return (False, jName ++ " is dead")
Just pid -> do
liftIO $ signalProcess sigUSR1 pid
return (True, jName ++ " with pid " ++ show pid ++ " signaled")
_ -> return (False, jName ++ "'s pid unknown")
-- | Notify a job that something relevant happened, e.g., a lock became
-- available. We do this by sending sigHUP to the process.
notifyJob :: ProcessID -> IO (ErrorResult ())
notifyJob pid = runResultT $ do
logDebug $ "Signalling process " ++ show pid
liftIO $ signalProcess sigHUP pid
-- | Permissions for the archive directories.
queueDirPermissions :: FilePermissions
queueDirPermissions = FilePermissions { fpOwner = Just GanetiMasterd
, fpGroup = Just $ ExtraGroup DaemonsGroup
, fpPermissions = 0o0750
}
-- | Try, at most until the given endtime, to archive some of the given
-- jobs, if they are older than the specified cut-off time; also replicate
-- archival of the additional jobs. Return the pair of the number of jobs
-- archived, and the number of jobs remaining int he queue, asuming the
-- given numbers about the not considered jobs.
archiveSomeJobsUntil :: ([JobId] -> IO ()) -- ^ replication function
-> FilePath -- ^ queue root directory
-> ClockTime -- ^ Endtime
-> Timestamp -- ^ cut-off time for archiving jobs
-> Int -- ^ number of jobs alread archived
-> [JobId] -- ^ Additional jobs to replicate
-> [JobId] -- ^ List of job-ids still to consider
-> IO (Int, Int)
archiveSomeJobsUntil replicateFn _ _ _ arch torepl [] = do
unless (null torepl) . (>> return ())
. forkIO $ replicateFn torepl
return (arch, 0)
archiveSomeJobsUntil replicateFn qDir endt cutt arch torepl (jid:jids) = do
let archiveMore = archiveSomeJobsUntil replicateFn qDir endt cutt
continue = archiveMore arch torepl jids
jidname = show $ fromJobId jid
time <- getClockTime
if time >= endt
then do
_ <- forkIO $ replicateFn torepl
return (arch, length (jid:jids))
else do
logDebug $ "Inspecting job " ++ jidname ++ " for archival"
loadResult <- loadJobFromDisk qDir False jid
case loadResult of
Bad _ -> continue
Ok (job, _) ->
if jobArchivable cutt job
then do
let live = liveJobFile qDir jid
archive = archivedJobFile qDir jid
renameResult <- safeRenameFile queueDirPermissions
live archive
case renameResult of
Bad s -> do
logWarning $ "Renaming " ++ live ++ " to " ++ archive
++ " failed unexpectedly: " ++ s
continue
Ok () -> do
let torepl' = jid:torepl
if length torepl' >= 10
then do
_ <- forkIO $ replicateFn torepl'
archiveMore (arch + 1) [] jids
else archiveMore (arch + 1) torepl' jids
else continue
-- | Archive jobs older than the given time, but do not exceed the timeout for
-- carrying out this task.
archiveJobs :: ConfigData -- ^ cluster configuration
-> Int -- ^ time the job has to be in the past in order
-- to be archived
-> Int -- ^ timeout
-> [JobId] -- ^ jobs to consider
-> IO (Int, Int)
archiveJobs cfg age timeout jids = do
now <- getClockTime
qDir <- queueDir
let endtime = addToClockTime (noTimeDiff { tdSec = timeout }) now
cuttime = if age < 0 then noTimestamp
else advanceTimestamp (- age) (fromClockTime now)
mcs = Config.getMasterCandidates cfg
replicateFn jobs = do
let olds = map (liveJobFile qDir) jobs
news = map (archivedJobFile qDir) jobs
_ <- executeRpcCall mcs . RpcCallJobqueueRename $ zip olds news
return ()
archiveSomeJobsUntil replicateFn qDir endtime cuttime 0 [] jids
| mbakke/ganeti | src/Ganeti/JQueue.hs | bsd-2-clause | 30,285 | 0 | 26 | 7,671 | 6,612 | 3,482 | 3,130 | 549 | 8 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsEllipseItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsEllipseItem_h where
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QGraphicsEllipseItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsEllipseItem_unSetUserMethod" qtc_QGraphicsEllipseItem_unSetUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsEllipseItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsEllipseItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsEllipseItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsEllipseItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setUserMethod" qtc_QGraphicsEllipseItem_setUserMethod :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setUserMethodVariant" qtc_QGraphicsEllipseItem_setUserMethodVariant :: Ptr (TQGraphicsEllipseItem a) -> CInt -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsEllipseItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsEllipseItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsEllipseItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsEllipseItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QGraphicsEllipseItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsEllipseItem_unSetHandler" qtc_QGraphicsEllipseItem_unSetHandler :: Ptr (TQGraphicsEllipseItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsEllipseItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsEllipseItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler1" qtc_QGraphicsEllipseItem_setHandler1 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQRectF t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqqboundingRect_h (QGraphicsEllipseItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect" qtc_QGraphicsEllipseItem_boundingRect :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsEllipseItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsEllipseItem_boundingRect_qth" qtc_QGraphicsEllipseItem_boundingRect_qth :: Ptr (TQGraphicsEllipseItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsEllipseItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler2" qtc_QGraphicsEllipseItem_setHandler2 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPointF t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqcontains_h (QGraphicsEllipseItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsEllipseItem_contains_qth" qtc_QGraphicsEllipseItem_contains_qth :: Ptr (TQGraphicsEllipseItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsEllipseItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsEllipseItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsEllipseItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contains" qtc_QGraphicsEllipseItem_contains :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsEllipseItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler3" qtc_QGraphicsEllipseItem_setHandler3 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler4" qtc_QGraphicsEllipseItem_setHandler4 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QisObscuredBy_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy" qtc_QGraphicsEllipseItem_isObscuredBy :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem" qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler5" qtc_QGraphicsEllipseItem_setHandler5 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (Ptr (TQPainterPath t0))
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QopaqueArea_h (QGraphicsEllipseItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_opaqueArea" qtc_QGraphicsEllipseItem_opaqueArea :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsEllipseItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler6" qtc_QGraphicsEllipseItem_setHandler6 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem6 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- qObjectFromPtr x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qpaint_h (QGraphicsEllipseItem ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsEllipseItem_paint1" qtc_QGraphicsEllipseItem_paint1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsEllipseItemSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where
paint_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QGraphicsEllipseItem_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsEllipseItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_shape" qtc_QGraphicsEllipseItem_shape :: Ptr (TQGraphicsEllipseItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsEllipseItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_shape cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler7" qtc_QGraphicsEllipseItem_setHandler7 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7 :: (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qqtype_h (QGraphicsEllipseItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
foreign import ccall "qtc_QGraphicsEllipseItem_type" qtc_QGraphicsEllipseItem_type :: Ptr (TQGraphicsEllipseItem a) -> IO CInt
instance Qqtype_h (QGraphicsEllipseItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_type cobj_x0
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler8" qtc_QGraphicsEllipseItem_setHandler8 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8 :: (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qadvance_h (QGraphicsEllipseItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_advance" qtc_QGraphicsEllipseItem_advance :: Ptr (TQGraphicsEllipseItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsEllipseItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler9" qtc_QGraphicsEllipseItem_setHandler9 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler10" qtc_QGraphicsEllipseItem_setHandler10 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem" qtc_QGraphicsEllipseItem_collidesWithItem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1" qtc_QGraphicsEllipseItem_collidesWithItem1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler11" qtc_QGraphicsEllipseItem_setHandler11 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler12" qtc_QGraphicsEllipseItem_setHandler12 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcollidesWithPath_h (QGraphicsEllipseItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath" qtc_QGraphicsEllipseItem_collidesWithPath :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsEllipseItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsEllipseItem_collidesWithPath1" qtc_QGraphicsEllipseItem_collidesWithPath1 :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsEllipseItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler13" qtc_QGraphicsEllipseItem_setHandler13 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcontextMenuEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_contextMenuEvent" qtc_QGraphicsEllipseItem_contextMenuEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragEnterEvent" qtc_QGraphicsEllipseItem_dragEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragLeaveEvent" qtc_QGraphicsEllipseItem_dragLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dragMoveEvent" qtc_QGraphicsEllipseItem_dragMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_dropEvent" qtc_QGraphicsEllipseItem_dropEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusInEvent" qtc_QGraphicsEllipseItem_focusInEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsEllipseItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_focusOutEvent" qtc_QGraphicsEllipseItem_focusOutEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsEllipseItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverEnterEvent" qtc_QGraphicsEllipseItem_hoverEnterEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverLeaveEvent" qtc_QGraphicsEllipseItem_hoverLeaveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_hoverMoveEvent" qtc_QGraphicsEllipseItem_hoverMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsEllipseItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodEvent" qtc_QGraphicsEllipseItem_inputMethodEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsEllipseItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler14" qtc_QGraphicsEllipseItem_setHandler14 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QGraphicsEllipseItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsEllipseItem_inputMethodQuery" qtc_QGraphicsEllipseItem_inputMethodQuery :: Ptr (TQGraphicsEllipseItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsEllipseItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsEllipseItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler15" qtc_QGraphicsEllipseItem_setHandler15 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem15 :: (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
let x1enum = qEnum_fromInt $ fromCLong x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QitemChange_h (QGraphicsEllipseItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_itemChange" qtc_QGraphicsEllipseItem_itemChange :: Ptr (TQGraphicsEllipseItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsEllipseItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyPressEvent" qtc_QGraphicsEllipseItem_keyPressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsEllipseItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_keyReleaseEvent" qtc_QGraphicsEllipseItem_keyReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsEllipseItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseDoubleClickEvent" qtc_QGraphicsEllipseItem_mouseDoubleClickEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseMoveEvent" qtc_QGraphicsEllipseItem_mouseMoveEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mousePressEvent" qtc_QGraphicsEllipseItem_mousePressEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_mouseReleaseEvent" qtc_QGraphicsEllipseItem_mouseReleaseEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler16" qtc_QGraphicsEllipseItem_setHandler16 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEvent_h (QGraphicsEllipseItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEvent" qtc_QGraphicsEllipseItem_sceneEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsEllipseItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler17" qtc_QGraphicsEllipseItem_setHandler17 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem17 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGraphicsEllipseItem ()) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGraphicsEllipseItem_setHandler18" qtc_QGraphicsEllipseItem_setHandler18 :: Ptr (TQGraphicsEllipseItem a) -> CWString -> Ptr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem18 :: (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsEllipseItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsEllipseItemSc a) (QGraphicsEllipseItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsEllipseItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsEllipseItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsEllipseItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsEllipseItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- objectFromPtr_nf x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsceneEventFilter_h (QGraphicsEllipseItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter" qtc_QGraphicsEllipseItem_sceneEventFilter :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc a) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsEllipseItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsEllipseItemSc a) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsEllipseItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsEllipseItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsEllipseItem_wheelEvent" qtc_QGraphicsEllipseItem_wheelEvent :: Ptr (TQGraphicsEllipseItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsEllipseItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsEllipseItem_wheelEvent cobj_x0 cobj_x1
| uduki/hsQt | Qtc/Gui/QGraphicsEllipseItem_h.hs | bsd-2-clause | 100,132 | 0 | 18 | 20,810 | 30,658 | 14,667 | 15,991 | -1 | -1 |
-- | This module provides the type of an (abstract) object.
module Jat.PState.Object
(
Object (..)
, className
, fieldTable
, isInstance
, mapValuesO
, referencesO
, FieldTable
, elemsFT
, updateFT
, emptyFT
, lookupFT
, assocsFT
)
where
import Jat.PState.AbstrValue
import Jat.Utils.Pretty
import qualified Jinja.Program as P
import Data.Char (toLower)
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
-- | A 'FieldTable' maps pairs of class name and field name to abstract values.
type FieldTable i = M.Map (P.ClassId, P.FieldId) (AbstrValue i)
-- | An 'Object' may be a concrete instance or an abstract variable.
data Object i =
Instance P.ClassId (FieldTable i)
| AbsVar P.ClassId
deriving (Show)
-- | Returns the class name of an object.
className :: Object i -> P.ClassId
className (Instance cn _) = cn
className (AbsVar cn) = cn
-- | Returns the field table of an object.
fieldTable :: Object i -> FieldTable i
fieldTable (Instance _ ft) = ft
fieldTable _ = error "assert: illegal access to fieldtable"
-- | Checks if the object is an conrete instance.
isInstance :: Object i -> Bool
isInstance (Instance _ _) = True
isInstance _ = False
-- | Maps a value function over the object.
mapValuesO :: (AbstrValue i -> AbstrValue i) -> Object i -> Object i
mapValuesO f (Instance cn ft) = Instance cn (M.map f ft)
mapValuesO _ var = var
-- | Returns the the addresses stored in an 'Object'.
referencesO :: Object i -> [Address]
referencesO (Instance _ ft) = [ ref | RefVal ref <- M.elems ft ]
referencesO (AbsVar _) = []
-- | Returns an aempty field table.
emptyFT :: FieldTable i
emptyFT = M.empty
-- | Updates a field table.
updateFT :: P.ClassId -> P.FieldId -> AbstrValue i -> FieldTable i -> FieldTable i
updateFT cn fn = M.insert (cn, fn)
-- | Returns the value of the given field of the field table.
-- Returns an error if the field does not exist.
lookupFT :: P.ClassId -> P.FieldId -> FieldTable i -> AbstrValue i
lookupFT cn fn ft = errmsg `fromMaybe` M.lookup (cn,fn) ft
where errmsg = error $ "Jat.PState.Object.lookupFT: element not found " ++ show (cn,fn)
-- | Retuns the entries of the field table as pair of identifier and value.
assocsFT :: FieldTable i -> [((P.ClassId,P.FieldId),AbstrValue i)]
assocsFT = M.assocs
-- | Returns the values of the field table.
elemsFT :: FieldTable i -> [AbstrValue i]
elemsFT = M.elems
instance Pretty i => Pretty (Object i) where
pretty (Instance cn ft) = pretty cn <> encloseSep lparen rparen comma (prettyFT ft)
where
prettyFT = map prettyElem . M.toList
prettyElem ((cne,fne),v) = pretty cne <> dot <> pretty fne <> equals <> pretty v
pretty (AbsVar cn) = text . map toLower . show $ pretty cn
| ComputationWithBoundedResources/jat | src/Jat/PState/Object.hs | bsd-3-clause | 2,779 | 0 | 12 | 582 | 808 | 432 | 376 | 56 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module BitBasket where
import Data.Maybe
import Data.Word
import Data.Bits
import Control.Monad
-- Right-to-Left bit basket
data BitBasket a = BitBasket Int a
deriving(Eq,Show)
unsafeUnBasket :: (Bits a) => BitBasket a -> a
unsafeUnBasket (BitBasket 0 _) = 0
unsafeUnBasket (BitBasket p b) =
let x = bit (p-1) in b .&. (x.|.(x - 1))
unBasket :: (Bits a) => BitBasket a -> Maybe a
unBasket (BitBasket 0 _) = Nothing
unBasket bb@(BitBasket _ _) = Just $ unsafeUnBasket $ bb
mkBasket :: (Bits a) => a -> BitBasket a
mkBasket a = BitBasket (bitSize a) a
bbhead :: (Bits a) => BitBasket a -> a
bbhead (BitBasket 0 _) = error "empty BitBasket"
bbhead (BitBasket p b) = if testBit b (p-1) then 1 else 0
bbtail :: (Bits a) => BitBasket a -> BitBasket a
bbtail (BitBasket 0 _) = error "empty BitBasket"
bbtail (BitBasket p b) = BitBasket (p-1) b
bbtake :: (Bits a) => Int -> BitBasket a -> a
bbtake 0 _ = 0
bbtake p bs = (h `shiftR` p) .&. bbtake (p-1) t
where (h,t) = (bbhead bs, bbtail bs)
bbunpack :: (Bits a) => BitBasket a -> [Bool]
bbunpack (BitBasket 0 _) = []
bbunpack (BitBasket p b) = (testBit b (p-1)) : (bbunpack $ BitBasket (p-1) b)
bbnull :: BitBasket a -> Bool
bbnull (BitBasket 0 _) = True
bbnull (BitBasket _ _) = False
bbempty :: (Bits a) => BitBasket a
bbempty = BitBasket 0 0
bblength :: (Bits a) => BitBasket a -> Int
bblength (BitBasket p b) = 0 `max` ((bitSize b) `min` p)
bbappend :: (Bits a) => BitBasket a -> BitBasket a -> BitBasket a
bbappend bb1@(BitBasket p1 b1) bb2@(BitBasket p2 b2)
| (p1 + p2) > bitSize b1 = error "BitBasket: no space left in basket"
| otherwise = BitBasket (p1 + p2) ((b1 `shiftL` p2) .|. (unsafeUnBasket bb2))
bbsplitAt :: (Bits a) => Int -> BitBasket a -> (BitBasket a, BitBasket a)
bbsplitAt n' (BitBasket p b) = (b1,b2)
where
n = 0 `max` (n' `min` p)
b1 = BitBasket n (b `shiftR`(p-n))
b2 = BitBasket (p-n) b
bbparse :: (Bits a) => BitBasket a -> [Int] -> Maybe [a]
bbparse _ [] = Just []
bbparse bb@(BitBasket p b) (w:ws) = do
when (w>p) (fail "Not enough bits")
v <- unBasket (BitBasket w (b `shiftR`(p-w)))
vs <- bbparse (BitBasket (p-w) b) ws
return (v:vs)
getBits :: (Bits a, Monad m) => [Int] -> a -> m [a]
getBits ws v = case bbparse (mkBasket v) ws of
Nothing -> fail "bbparse failed"
Just l -> return l
| ierton/yteratee | src/BitBasket.hs | bsd-3-clause | 2,497 | 0 | 14 | 569 | 1,230 | 640 | 590 | 59 | 2 |
{-# LANGUAGE DeriveDataTypeable, NoMonomorphismRestriction #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.Backend.Pdf.CmdLine
-- Copyright : (c) 2013 alpheccar.org (see LICENSE)
-- License : BSD-style (see LICENSE)
--
-- Convenient creation of command-line-driven executables for
-- rendering diagrams using the Pdf backend.
--
-- * 'defaultMain' creates an executable which can render a single
-- diagram at various options.
--
-----------------------------------------------------------------------------
module Diagrams.Backend.Pdf.CmdLine
( defaultMain
, multipleMain
, Pdf
) where
import Diagrams.Prelude hiding (width, height, interval)
import Diagrams.Backend.Pdf
import System.Console.CmdArgs.Implicit hiding (args)
import Prelude
import Data.List.Split
import System.Environment (getProgName)
import qualified Graphics.PDF as P
data DiagramOpts = DiagramOpts
{ width :: Maybe Int
, height :: Maybe Int
, output :: FilePath
, compressed :: Maybe Bool
, author :: Maybe String
}
deriving (Show, Data, Typeable)
diagramOpts :: String -> DiagramOpts
diagramOpts prog = DiagramOpts
{ width = def
&= typ "INT"
&= help "Desired width of the output image (default 400)"
, height = def
&= typ "INT"
&= help "Desired height of the output image (default 400)"
, output = def
&= typFile
&= help "Output file"
, compressed = def
&= typ "BOOL"
&= help "Compressed PDF file"
, author = def
&= typ "STRING"
&= help "Author of the document"
}
&= summary "Command-line diagram generation."
&= program prog
-- | This is the simplest way to render diagrams, and is intended to
-- be used like so:
--
-- > ... other definitions ...
-- > myDiagram = ...
-- >
-- > main = defaultMain myDiagram
--
-- Compiling a source file like the above example will result in an
-- executable which takes command-line options for setting the size,
-- output file, and so on, and renders @myDiagram@ with the
-- specified options.
--
-- Pass @--help@ to the generated executable to see all available
-- options. Currently it looks something like
--
-- @
-- Command-line diagram generation.
--
-- Foo [OPTIONS]
--
-- Common flags:
-- -w --width=INT Desired width of the output image (default 400)
-- -h --height=INT Desired height of the output image (default 400)
-- -o --output=FILE Output file
-- -c --compressed Compressed PDF file
-- -? --help Display help message
-- -V --version Print version information
-- @
--
-- For example, a couple common scenarios include
--
-- @
-- $ ghc --make MyDiagram
--
-- # output image.eps with a width of 400pt (and auto-determined height)
-- $ ./MyDiagram --compressed -o image.pdf -w 400
-- @
defaultMain :: Diagram Pdf R2 -> IO ()
defaultMain d = do
prog <- getProgName
opts <- cmdArgs (diagramOpts prog)
let sizeSpec = case (width opts, height opts) of
(Nothing, Nothing) -> Absolute
(Just wi, Nothing) -> Width (fromIntegral wi)
(Nothing, Just he) -> Height (fromIntegral he)
(Just wi, Just he) -> Dims (fromIntegral wi)
(fromIntegral he)
(w,h) = sizeFromSpec sizeSpec
theAuthor = maybe "diagrams-pdf" id (author opts)
compression = maybe False id (compressed opts)
docRect = P.PDFRect 0 0 (floor w) (floor h)
pdfOpts = PdfOptions sizeSpec
ifCanRender opts $ do
P.runPdf (output opts)
(P.standardDocInfo { P.author=P.toPDFString theAuthor, P.compressed = compression}) docRect $ do
page1 <- P.addPage Nothing
P.drawWithPage page1 $ renderDia Pdf pdfOpts d
-- | Generate a multipage PDF document from several diagrams.
-- Each diagram is scaled to the page size
multipleMain :: [Diagram Pdf R2] -> IO ()
multipleMain d = do
prog <- getProgName
opts <- cmdArgs (diagramOpts prog)
let sizeSpec = case (width opts, height opts) of
(Nothing, Nothing) -> Absolute
(Just wi, Nothing) -> Width (fromIntegral wi)
(Nothing, Just he) -> Height (fromIntegral he)
(Just wi, Just he) -> Dims (fromIntegral wi)
(fromIntegral he)
(w,h) = sizeFromSpec sizeSpec
theAuthor = maybe "diagrams-pdf" id (author opts)
compression = maybe False id (compressed opts)
docRect = P.PDFRect 0 0 (floor w) (floor h)
pdfOpts = PdfOptions sizeSpec
createPage aDiag = do
page1 <- P.addPage Nothing
P.drawWithPage page1 $ renderDia Pdf pdfOpts aDiag
ifCanRender opts $ do
P.runPdf (output opts)
(P.standardDocInfo { P.author=P.toPDFString theAuthor, P.compressed = compression}) docRect $ do
mapM_ createPage d
ifCanRender :: DiagramOpts -> IO () -> IO ()
ifCanRender opts action =
case splitOn "." (output opts) of
[""] -> putStrLn "No output file given."
ps | last ps `elem` ["pdf"] -> action
| otherwise -> putStrLn $ "Unknown file type: " ++ last ps
| alpheccar/diagrams-pdf | src/Diagrams/Backend/Pdf/CmdLine.hs | bsd-3-clause | 5,541 | 0 | 16 | 1,662 | 1,151 | 610 | 541 | 86 | 4 |
{-# LANGUAGE ForeignFunctionInterface, TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, ScopedTypeVariables, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Licence : BSD-style (see LICENSE)
--
-- Exports data types and functions required by the generated binding files.
--
-----------------------------------------------------------------------------
module Foreign.Salsa.Binding (
module Foreign.Salsa.Common,
module Foreign.Salsa.Core,
module Foreign.Salsa.CLR,
module Foreign.Salsa.Resolver,
FunPtr, unsafePerformIO, liftM,
type_GetType
) where
import Foreign.Salsa.Common
import Foreign.Salsa.Core
import Foreign.Salsa.CLR
import Foreign.Salsa.Resolver
import System.IO.Unsafe ( unsafePerformIO )
import Foreign hiding (new, unsafePerformIO)
import Foreign.C.String
import Control.Monad (liftM)
-- TODO: Perhaps move some/all of this into the generator, so that it can be
-- CLR-version neutral.
--
-- Import the System.Type.GetType(String) and System.Type.MakeArrayType(Int32)
-- methods so they can be used in the implementations of 'typeOf' as produced by
-- the generator.
--
type Type_GetType_stub = SalsaString -> Bool -> IO ObjectId
foreign import ccall "dynamic" make_Type_GetType_stub :: FunPtr Type_GetType_stub -> Type_GetType_stub
{-# NOINLINE type_GetType_stub #-}
type_GetType_stub :: Type_GetType_stub
type_GetType_stub = make_Type_GetType_stub $ unsafePerformIO $ getMethodStub
"System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" "GetType"
"System.String;System.Boolean"
type_GetType typeName = marshalMethod2s type_GetType_stub undefined undefined (typeName, True)
type Type_MakeArrayType_stub = ObjectId -> Int32 -> IO ObjectId
foreign import ccall "dynamic" make_Type_MakeArrayType_stub :: FunPtr Type_MakeArrayType_stub -> Type_MakeArrayType_stub
{-# NOINLINE type_MakeArrayType_stub #-}
type_MakeArrayType_stub :: Type_MakeArrayType_stub
type_MakeArrayType_stub = make_Type_MakeArrayType_stub $ unsafePerformIO $ getMethodStub
"System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" "MakeArrayType"
"System.Int32"
--
-- SalsaForeignType instances for primitive types
--
instance SalsaForeignType Int32 where foreignTypeOf _ = foreignTypeFromString "System.Int32"
instance SalsaForeignType String where foreignTypeOf _ = foreignTypeFromString "System.String"
instance SalsaForeignType Bool where foreignTypeOf _ = foreignTypeFromString "System.Boolean"
instance SalsaForeignType Double where foreignTypeOf _ = foreignTypeFromString "System.Double"
foreignTypeFromString :: String -> Obj Type_
foreignTypeFromString s = unsafePerformIO $ do
-- putStrLn $ "typeOfString: " ++ s
type_GetType s
-- marshalMethod1s type_GetType_stub undefined undefined s
-- Define the foreignTypeOf function for arrays by first calling foreignTypeOf on the element type,
-- and then using the Type.MakeArrayType method to return the associated one-dimensional
-- array type:
instance SalsaForeignType t => SalsaForeignType (Arr t) where
foreignTypeOf _ = unsafePerformIO $
marshalMethod1i type_MakeArrayType_stub (foreignTypeOf (undefined :: t)) undefined (1 :: Int32)
-- Note: this function requires ScopedTypeVariables
-- Define foreignTypeOf for reference types in terms of the associated static type.
instance SalsaForeignType t => SalsaForeignType (Obj t) where
foreignTypeOf _ = foreignTypeOf (undefined :: t)
-- vim:set sw=4 ts=4 expandtab:
| tim-m89/Salsa | Foreign/Salsa/Binding.hs | bsd-3-clause | 3,595 | 0 | 10 | 469 | 490 | 280 | 210 | 44 | 1 |
{-# LANGUAGE GADTs, DataKinds, KindSignatures, PolyKinds, ConstraintKinds, TypeOperators #-}
module Tests.Util.TypeEquality where
import GHC.Exts
data (:==:) :: k -> k -> * where
Refl :: a :==: a
cong :: (a :==: b) -> (f a :==: f b)
cong Refl = Refl
data Exists :: (a -> *) -> * where
ExI :: f a -> Exists f
data Exists2 :: (a -> b -> *) -> * where
ExI2 :: f a b -> Exists2 f
subst :: (a :==: b) -> f a -> f b
subst Refl x = x
| liamoc/geordi | Tests/Util/TypeEquality.hs | bsd-3-clause | 443 | 0 | 8 | 110 | 184 | 101 | 83 | 13 | 1 |
-- |
-- Copyright : (C) 2014 Seagate Technology Limited.
-- License : BSD3
import Control.Applicative
import Control.Alternative.Freer
import qualified Options.Applicative as CL
import qualified Options.Applicative.Help.Core as CL
data Foo x = Foo {
name :: String
, reader :: String -> x
}
instance Functor Foo where
fmap f (Foo n r) = Foo n $ f . r
mkParser :: Foo a -> CL.Parser a
mkParser (Foo n _) = CL.option CL.disabled ( CL.long n )
type Bar a = Alt Foo a
foo :: String -> (String -> x) -> Bar x
foo n r = liftAlt $ Foo n r
myFoo :: Bar [String]
myFoo = many $ foo "Hello" (\_ -> "Hello")
clFoo :: CL.Parser [String]
clFoo = runAlt mkParser $ myFoo
hangs = CL.cmdDesc clFoo
main :: IO ()
main = print hangs
| seagate-ssg/options-schema | test/Applicative.hs | bsd-3-clause | 736 | 4 | 9 | 160 | 302 | 156 | 146 | 21 | 1 |
module SSH.Supported where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Serialize as S
import Crypto.HMAC (MacKey(..), hmac)
import Crypto.Hash.CryptoAPI (MD5, SHA1)
import SSH.Crypto
import SSH.Internal.Util
version :: String
version = "SSH-2.0-DarcsDen"
-- | The required key exchange algorithms are specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.5 rfc4253 section 6.5>.
supportedKeyExchanges :: [String]
supportedKeyExchanges =
[ "diffie-hellman-group1-sha1"
-- TODO: The SSH rfc requires that the following method is also
-- supported.
-- , "diffie-hellman-group-exchange-sha1"
]
-- | The supported key algorithms. Specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.6 rfc4253 section 6.6>.
supportedKeyAlgorithms :: [String]
supportedKeyAlgorithms = ["ssh-rsa", "ssh-dss"]
-- | Suporrted Ciphers.
--
-- Defined in <https://tools.ietf.org/html/rfc4253#section-6.3 rfc4253
-- section 6.3>.
supportedCiphers :: [(String, Cipher)]
supportedCiphers =
[ ("aes256-cbc", aesCipher 32)
, ("aes192-cbc", aesCipher 24)
, ("aes128-cbc", aesCipher 16)
]
where
aesCipher :: Int -> Cipher
aesCipher s = Cipher AES CBC 16 s
-- | The required macs are specified in
-- <https://tools.ietf.org/html/rfc4253#section-6.4 rfc4253 section 6.4>.
supportedMACs :: [(String, LBS.ByteString -> HMAC)]
supportedMACs =
[ ("hmac-sha1", sha)
, ("hmac-md5", md5)
]
where
sha, md5 :: LBS.ByteString -> HMAC
sha k = HMAC 20 $ \b -> bsToLBS . S.runPut $ S.put (hmac (MacKey (strictLBS (LBS.take 20 k))) b :: SHA1)
md5 k = HMAC 16 $ \b -> bsToLBS . S.runPut $ S.put (hmac (MacKey (strictLBS (LBS.take 16 k))) b :: MD5)
bsToLBS :: BS.ByteString -> LBS.ByteString
bsToLBS = LBS.fromChunks . (: [])
-- | Supported compression algorithms.
--
-- Defined in <https://tools.ietf.org/html/rfc4253#section-6.2 rfc4253
-- section 6.2>.
supportedCompression :: String
supportedCompression = "none"
supportedLanguages :: String
supportedLanguages = ""
| cdepillabout/ssh | src/SSH/Supported.hs | bsd-3-clause | 2,090 | 0 | 19 | 351 | 462 | 275 | 187 | 35 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module RevealHs.TH where
import Control.Monad
import Data.HashMap.Strict as HM
import Data.IORef
import Data.Maybe
import Data.String.Interpolate
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import RevealHs.Internal as I
import RevealHs.Options
import RevealHs.QQ
import System.IO.Unsafe
{-# NOINLINE slidesRef #-}
slidesRef :: IORef SlideMap
slidesRef = unsafePerformIO $ newIORef empty
{-# NOINLINE slideGroupOrderRef #-}
slideGroupOrderRef :: IORef [Module]
slideGroupOrderRef = unsafePerformIO $ newIORef []
slide :: (SlideOptions -> Slide) -> DecsQ
slide = slide' defSlideOptions
slide' :: SlideOptions -> (SlideOptions -> Slide) -> DecsQ
slide' so s = do
mod <- thisModule
runIO $ do
slides <- readIORef slidesRef
when (isNothing $ HM.lookup mod slides) $
modifyIORef' slideGroupOrderRef (mod:)
modifyIORef' slidesRef (alter addSlide mod)
return []
where
addSlide Nothing = Just (defGroupOptions, [s so])
addSlide (Just (opts, slides)) = Just (opts, s so:slides)
groupOptions :: GroupOptions -> DecsQ
groupOptions opts = do
mod <- thisModule
runIO $ do
slides <- readIORef slidesRef
when (isNothing $ HM.lookup mod slides) $
modifyIORef' slideGroupOrderRef (mod:)
modifyIORef' slidesRef (alter setOpts mod)
return []
where
setOpts Nothing = Just (opts, [])
setOpts (Just (_, slides)) = Just (opts, slides)
mkRevealPage :: RevealOptions -> DecsQ
mkRevealPage ro = [d|main = putStrLn $export|]
where
export :: ExpQ
export = do
s <- runIO $ do
slides <- readIORef slidesRef
slideGroupOrder <- readIORef slideGroupOrderRef
return $ I.exportRevealPage ro slides slideGroupOrder
stringE s
| KenetJervet/reveal-hs | src/RevealHs/TH.hs | bsd-3-clause | 1,923 | 0 | 15 | 481 | 550 | 285 | 265 | 53 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module EFA.Data.Axis.Mono where
import EFA.Utility(Caller,merror, ModuleName(..),FunctionName, genCaller)
import qualified EFA.Data.Vector as DV
-- | TODO -- how many points are allowed to have the same time, only two or more ?
m :: ModuleName
m = ModuleName "Axis.Mono"
nc :: FunctionName -> Caller
nc = genCaller m
-- | Datatype with monotonically rising values
data Axis typ label vec a = Axis {
getLabel :: label,
getVec :: vec a} deriving (Show,Eq)
newtype Idx = Idx {getInt :: Int} deriving Show
map ::
(DV.Walker vec,
DV.Storage vec b,
DV.Storage vec a) =>
(a -> b) -> Axis typ label vec a -> Axis typ label vec b
map f (Axis label vec) = Axis label $ DV.map f vec
imap ::
(DV.Walker vec,
DV.Storage vec b,
DV.Storage vec a) =>
(Idx -> a -> b) -> Axis typ label vec a -> Axis typ label vec b
imap f (Axis label vec) = Axis label $ DV.imap (f . Idx) vec
indexAdd :: Idx -> Int -> Idx
indexAdd (Idx idx) num = Idx $ (idx+num)
len ::
(DV.Storage vec a, DV.Length vec)=>
Axis typ label vec a -> Int
len (Axis _ vec) = DV.length vec
fromVec ::
(DV.Storage vec Bool, DV.Singleton vec,
DV.Zipper vec, DV.Storage vec a,Ord a) =>
Caller -> label -> vec a -> Axis typ label vec a
fromVec caller label vec =
if isMonoton then Axis label vec
else merror caller m "fromVec" "Vector of elements is not monotonically rising"
where isMonoton = DV.all (==True) $ DV.deltaMap (\ x1 x2 -> x2 >= x1) vec
findIndex ::
(DV.Storage vec a, DV.Find vec)=>
(a -> Bool) -> Axis typ label vec a -> Maybe Idx
findIndex f (Axis _ vec) = fmap Idx $ DV.findIndex f vec
lookupUnsafe ::
DV.LookupUnsafe vec a =>
Axis typ label vec a -> Idx -> a
lookupUnsafe (Axis _ axis) (Idx idx) = DV.lookupUnsafe axis idx
findRightInterpolationIndex ::
(DV.Storage vec a, DV.Find vec, Ord a, DV.Length vec) =>
Axis typ label vec a -> a -> Idx
findRightInterpolationIndex axis x = rightIndex
where
idx = findIndex (>x) axis
rightIndex = case idx of
Just (Idx ix) -> if ix==0 then Idx 1 else Idx ix
Nothing -> Idx $ (len axis)-1
-- | TODO -- Code ist wrong -- exact point hits have to be considered
-- | get all Points involved in the interpolation of a point on the given coordinates
getSupportPoints ::
(Ord a,
DV.Storage vec a,
DV.Length vec,
DV.Find vec,
DV.LookupUnsafe vec a) =>
Axis typ label vec a -> a -> ((Idx,Idx),(a,a))
getSupportPoints axis x = ((leftIndex,rightIndex),
(lookupUnsafe axis leftIndex, lookupUnsafe axis rightIndex))
where rightIndex = findRightInterpolationIndex axis x
leftIndex = indexAdd rightIndex (-1) | energyflowanalysis/efa-2.1 | src/EFA/Data/Axis/Mono.hs | bsd-3-clause | 2,684 | 0 | 13 | 610 | 1,039 | 547 | 492 | 65 | 3 |
module Expectation where
import Test.Hspec
import System.Directory
import Control.Exception as E
shouldContain :: Eq a => [a] -> a -> Expectation
shouldContain containers element = do
let res = element `elem` containers
res `shouldBe` True
withDirectory_ :: FilePath -> IO a -> IO a
withDirectory_ dir action = bracket getCurrentDirectory
setCurrentDirectory
(\_ -> setCurrentDirectory dir >> action)
withDirectory :: FilePath -> (FilePath -> IO a) -> IO a
withDirectory dir action = bracket getCurrentDirectory
setCurrentDirectory
(\d -> setCurrentDirectory dir >> action d)
| eagletmt/ghc-mod | test/Expectation.hs | bsd-3-clause | 730 | 0 | 10 | 236 | 190 | 99 | 91 | 16 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Graphics.Tooty
(
module Graphics.Tooty.Image,
module Graphics.Tooty.Matrix,
module Graphics.Tooty.Geometry,
module Graphics.Tooty.Text,
-- * OpenGL context preparation
setup2D,
positionViewport,
) where
import Graphics.Rendering.OpenGL ( GLfloat, ($=) )
import qualified Graphics.Rendering.OpenGL as GL
import Linear.V2
import Graphics.Tooty.Geometry
import Graphics.Tooty.Image
import Graphics.Tooty.Matrix
import Graphics.Tooty.Text
setup2D :: V2 Int -> IO ()
setup2D (V2 w h) = do
GL.depthMask $= GL.Disabled
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.ortho 0 (fromIntegral w) 0 (fromIntegral h) (-1) 1
GL.matrixMode $= GL.Modelview 0
GL.loadIdentity
GL.translate (GL.Vector3 0.375 0.375 0 :: GL.Vector3 GLfloat)
-- Functionality not specific to 2D:
GL.lineSmooth $= GL.Enabled
GL.pointSmooth $= GL.Enabled
GL.blend $= GL.Enabled
GL.blendFunc $= (GL.SrcAlpha, GL.OneMinusSrcAlpha)
positionViewport :: V2 Int -> IO ()
positionViewport p = do
(_, size) <- GL.get GL.viewport
GL.viewport $= (GL.Position x y, size)
where
V2 x y = fmap fromIntegral p
| cdxr/haskell-tooty | Graphics/Tooty.hs | bsd-3-clause | 1,217 | 0 | 10 | 245 | 379 | 202 | 177 | 34 | 1 |
-- |
-- Module : Text.PrettyPrint.Mainland
-- Copyright : (c) Harvard University 2006-2011
-- (c) Geoffrey Mainland 2011-2012
-- License : BSD-style
-- Maintainer : [email protected]
--
-- Stability : provisional
-- Portability : portable
--
-- This module is based on /A Prettier Printer/ by Phil Wadler in /The Fun of
-- Programming/, Jeremy Gibbons and Oege de Moor (eds)
-- <http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf>
--
-- At the time it was originally written I didn't know about Daan Leijen's
-- pretty printing module based on the same paper. I have since incorporated
-- many of his improvements. This module is geared towards pretty printing
-- source code; its main advantages over other libraries are a 'Pretty' class
-- that handles precedence and the ability to automatically track the source
-- locations associated with pretty printed values and output appropriate
-- #line pragmas.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverlappingInstances #-}
module Text.PrettyPrint.Mainland (
-- * The document type
Doc,
-- * Basic combinators
empty, text, char, string, fromText, fromLazyText,
line, nest, srcloc, column, nesting,
softline, softbreak, group,
-- * Operators
(<>), (<+>), (</>), (<+/>), (<//>),
-- * Character documents
backquote, colon, comma, dot, dquote, equals, semi, space, spaces, squote,
star, langle, rangle, lbrace, rbrace, lbracket, rbracket, lparen, rparen,
-- * Bracketing combinators
enclose,
angles, backquotes, braces, brackets, dquotes, parens, parensIf, squotes,
-- * Alignment and indentation
align, hang, indent,
-- * Combining lists of documents
folddoc, spread, stack, cat, sep,
punctuate, commasep, semisep,
encloseSep,
tuple, list,
-- * The rendered document type
RDoc(..),
-- * Document rendering
render, renderCompact,
displayS, prettyS, pretty,
displayPragmaS, prettyPragmaS, prettyPragma,
displayLazyText, prettyLazyText,
displayPragmaLazyText, prettyPragmaLazyText,
-- * Document output
putDoc, hPutDoc,
-- * The 'Pretty' type class for pretty printing
Pretty(..),
faildoc, errordoc
) where
import Data.Int
import Data.Loc (L(..),
Loc(..),
Located(..),
Pos(..),
posFile,
posLine)
import qualified Data.Map as Map
import Data.Monoid
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy.IO as TIO
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Builder as B
import Data.Word
import GHC.Real (Ratio(..))
import System.IO (Handle)
infixr 5 </>, <+/>, <//>
infixr 6 <+>
data Doc = Empty -- ^ The empty document
| Char Char -- ^ A single character
| String !Int String -- ^ 'String' with associated length (to avoid
-- recomputation)
| Text T.Text -- ^ 'T.Text'
| LazyText L.Text -- ^ 'L.Text'
| Line -- ^ Newline
| Nest !Int Doc -- ^ Indented document
| SrcLoc Loc -- ^ Tag output with source location
| Doc `Cat` Doc -- ^ Document concatenation
| Doc `Alt` Doc -- ^ Provide alternatives. Invariants: all
-- layouts of the two arguments flatten to the
-- same layout
| Column (Int -> Doc) -- ^ Calculate document based on current column
| Nesting (Int -> Doc) -- ^ Calculate document based on current nesting
-- | The empty document.
empty :: Doc
empty = Empty
-- | The document @'text' s@ consists of the string @s@, which should not
-- contain any newlines. For a string that may include newlines, use 'string'.
text :: String -> Doc
text s = String (length s) s
-- | The document @'char' c@ consists the single character @c@.
char :: Char -> Doc
char '\n' = line
char c = Char c
-- | The document @'string' s@ consists of all the characters in @s@ but with
-- newlines replaced by 'line'.
string :: String -> Doc
string "" = empty
string ('\n' : s) = line <> string s
string s = case span (/= '\n') s of
(xs, ys) -> text xs <> string ys
-- | The document @'fromText' s@ consists of the 'T.Text' @s@, which should not
-- contain any newlines.
fromText :: T.Text -> Doc
fromText = Text
-- | The document @'fromLazyText' s@ consists of the 'L.Text' @s@, which should
-- not contain any newlines.
fromLazyText :: L.Text -> Doc
fromLazyText = LazyText
-- | The document @'line'@ advances to the next line and indents to the current
-- indentation level. When undone by 'group', it behaves like 'space'.
line :: Doc
line = Line
-- | The document @'nest' i d@ renders the document @d@ with the current
-- indentation level increased by @i@.
nest :: Int -> Doc -> Doc
nest i d = Nest i d
-- | The document @'srcloc' x@ adds the.
srcloc :: Located a => a -> Doc
srcloc x = SrcLoc (locOf x)
column :: (Int -> Doc) -> Doc
column = Column
nesting :: (Int -> Doc) -> Doc
nesting = Nesting
softline :: Doc
softline = space `Alt` line
softbreak :: Doc
softbreak = empty `Alt` line
group :: Doc -> Doc
group d = flatten d `Alt` d
flatten :: Doc -> Doc
flatten Empty = Empty
flatten (Char c) = Char c
flatten (String l s) = String l s
flatten (Text s) = Text s
flatten (LazyText s) = LazyText s
flatten Line = Char ' '
flatten (x `Cat` y) = flatten x `Cat` flatten y
flatten (Nest i x) = Nest i (flatten x)
flatten (x `Alt` _) = flatten x
flatten (SrcLoc loc) = SrcLoc loc
flatten (Column f) = Column (flatten . f)
flatten (Nesting f) = Nesting (flatten . f)
(<+>) :: Doc -> Doc -> Doc
x <+> y = x <> space <> y
(</>) :: Doc -> Doc -> Doc
x </> y = x <> line <> y
(<+/>) :: Doc -> Doc -> Doc
x <+/> y = x <> softline <> y
(<//>) :: Doc -> Doc -> Doc
x <//> y = x <> softbreak <> y
-- | The document @backquote@ consists of a backquote, \"`\".
backquote :: Doc
backquote = char '`'
-- | The document @colon@ consists of a colon, \":\".
colon :: Doc
colon = char ':'
-- | The document @comma@ consists of a comma, \",\".
comma :: Doc
comma = char ','
-- | The document @dot@ consists of a period, \".\".
dot :: Doc
dot = char '.'
-- | The document @dquote@ consists of a double quote, \"\\\"\".
dquote :: Doc
dquote = char '"'
-- | The document @equals@ consists of an equals sign, \"=\".
equals :: Doc
equals = char '='
-- | The document @semi@ consists of a semicolon, \";\".
semi :: Doc
semi = char ';'
-- | The document @space@ consists of a space, \" \".
space :: Doc
space = char ' '
-- | The document @'space' n@ consists of n spaces.
spaces :: Int -> Doc
spaces n = text (replicate n ' ')
-- | The document @squote@ consists of a single quote, \"\\'\".
squote :: Doc
squote = char '\''
-- | The document @star@ consists of an asterisk, \"*\".
star :: Doc
star = char '*'
-- | The document @langle@ consists of a less-than sign, \"<\".
langle :: Doc
langle = char '<'
-- | The document @rangle@ consists of a greater-than sign, \">\".
rangle :: Doc
rangle = char '>'
-- | The document @lbrace@ consists of a left brace, \"{\".
lbrace :: Doc
lbrace = char '{'
-- | The document @rbrace@ consists of a right brace, \"}\".
rbrace :: Doc
rbrace = char '}'
-- | The document @lbracket@ consists of a right brace, \"[\".
lbracket :: Doc
lbracket = char '['
-- | The document @rbracket@ consists of a right brace, \"]\".
rbracket :: Doc
rbracket = char ']'
-- | The document @lparen@ consists of a right brace, \"(\".
lparen :: Doc
lparen = char '('
-- | The document @rparen@ consists of a right brace, \")\".
rparen :: Doc
rparen = char ')'
-- | The document @'enclose' l r d)@ encloses the document @d@ between the
-- documents @l@ and @r@ using @<>@. It obeys the law
--
-- @'enclose' l r d = l <> d <> r@
enclose :: Doc -> Doc -> Doc -> Doc
enclose left right d = left <> d <> right
-- | The document @'angles' d@ encloses the aligned document @d@ in <...>.
angles :: Doc -> Doc
angles = enclose langle rangle . align
-- | The document @'backquotes' d@ encloses the aligned document @d@ in `...`.
backquotes :: Doc -> Doc
backquotes = enclose backquote backquote . align
-- | The document @'brackets' d@ encloses the aligned document @d@ in [...].
brackets :: Doc -> Doc
brackets = enclose lbracket rbracket . align
-- | The document @'braces' d@ encloses the aligned document @d@ in {...}.
braces :: Doc -> Doc
braces = enclose lbrace rbrace . align
-- | The document @'dquotes' d@ encloses the aligned document @d@ in "...".
dquotes :: Doc -> Doc
dquotes = enclose dquote dquote . align
-- | The document @'parens' d@ encloses the aligned document @d@ in (...).
parens :: Doc -> Doc
parens = enclose lparen rparen . align
-- | The document @'parensIf' p d@ encloses the document @d@ in parenthesis if
-- @p@ is @True@, and otherwise yields just @d@.
parensIf :: Bool -> Doc -> Doc
parensIf True doc = parens doc
parensIf False doc = doc
-- | The document @'parens' d@ encloses the document @d@ in '...'.
squotes :: Doc -> Doc
squotes = enclose squote squote . align
-- | The document @'align' d@ renders @d@ with a nesting level set to the current
-- column.
align :: Doc -> Doc
align d = column $ \k ->
nesting $ \i ->
nest (k - i) d
-- | The document @'hang' i d@ renders @d@ with a nesting level set to the
-- current column plus @i@. This differs from 'indent' in that the first line of
-- @d@ /is not/ indented.
hang :: Int -> Doc -> Doc
hang i d = align (nest i d)
-- | The document @'indent' i d@ indents @d@ @i@ spaces relative to the current
-- column. This differs from 'hang' in that the first line of @d@ /is/ indented.
indent :: Int -> Doc -> Doc
indent i d = align (nest i (spaces i <> d))
-- | The document @'folddoc' f ds@ obeys the laws:
--
-- * @'folddoc' f [] = 'empty'@
-- * @'folddoc' f [d1, d2, ..., dnm1, dn] = d1 `f` (d2 `f` ... (dnm1 `f` dn))@
folddoc :: (Doc -> Doc -> Doc) -> [Doc] -> Doc
folddoc _ [] = empty
folddoc _ [x] = x
folddoc f (x:xs) = f x (folddoc f xs)
-- | The document @'spread' ds@ concatenates the documents @ds@ using @<+>@.
spread :: [Doc] -> Doc
spread = folddoc (<+>)
-- | The document @'stack' ds@ concatenates the documents @ds@ using @</>@.
stack :: [Doc] -> Doc
stack = folddoc (</>)
-- | The document @'cat' ds@ separates the documents @ds@ with the empty
-- document as long as there is room, and uses newlines when there isn't.
cat :: [Doc] -> Doc
cat = group . folddoc (<//>)
-- | The document @'sep' ds@ separates the documents @ds@ with the empty
-- document as long as there is room, and uses spaces when there isn't.
sep :: [Doc] -> Doc
sep = group . folddoc (<+/>)
-- | The document @'punctuate' p ds@ obeys the law:
--
-- @'punctuate' p [d1, d2, ..., dn] = [d1 <> p, d2 <> p, ..., dn]@
punctuate :: Doc -> [Doc] -> [Doc]
punctuate _ [] = []
punctuate _ [d] = [d]
punctuate p (d:ds) = (d <> p) : punctuate p ds
-- | The document @'commasep' ds@ comma-space separates @ds@, aligning the
-- resulting document to the current nesting level.
commasep :: [Doc] -> Doc
commasep = align . sep . punctuate comma
-- | The document @'semisep' ds@ semicolon-space separates @ds@, aligning the
-- resulting document to the current nesting level.
semisep :: [Doc] -> Doc
semisep = align . sep . punctuate semi
-- | The document @'encloseSep' l r p ds@ separates @ds@ with the punctuation @p@
-- and encloses the result using @l@ and @r@. When wrapped, punctuation appears
-- at the end of the line. The enclosed portion of the document is aligned one
-- column to the right of the opening document.
--
-- @
-- \> ws = map text (words \"The quick brown fox jumps over the lazy dog\")
-- \> test = pretty 15 (encloseSep lparen rparen comma ws)
-- @
--
-- will be layed out as:
--
-- @
-- (The, quick,
-- brown, fox,
-- jumps, over,
-- the, lazy,
-- dog)
-- @
encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc
encloseSep left right p ds =
case ds of
[] -> left <> right
[d] -> left <> d <> right
_ -> left <> align (sep (punctuate p ds)) <> right
-- | The document @'tuple' ds@ separates @ds@ with commas and encloses them with
-- parentheses.
tuple :: [Doc] -> Doc
tuple = encloseSep lparen rparen comma
-- | The document @'tuple' ds@ separates @ds@ with commas and encloses them with
-- brackets.
list :: [Doc] -> Doc
list = encloseSep lbracket rbracket comma
-- | Equivalent of 'fail', but with a document instead of a string.
faildoc :: Monad m => Doc -> m a
faildoc = fail . show
-- | Equivalent of 'error', but with a document instead of a string.
errordoc :: Doc -> a
errordoc = error . show
-- | Render a document given a maximum width.
render :: Int -> Doc -> RDoc
render w x = best w 0 x
-- | Render a document without indentation on infinitely long lines. Since no
-- \'pretty\' printing is involved, this renderer is fast. The resulting output
-- contains fewer characters.
renderCompact :: Doc -> RDoc
renderCompact doc = scan 0 [doc]
where
scan :: Int -> [Doc] -> RDoc
scan !_ [] = REmpty
scan !k (d:ds) =
case d of
Empty -> scan k ds
Char c -> RChar c (scan (k+1) ds)
String l s -> RString l s (scan (k+l) ds)
Text s -> RText s (scan (k+T.length s) ds)
LazyText s -> RLazyText s (scan (k+fromIntegral (L.length s)) ds)
Line -> RLine 0 (scan 0 ds)
Nest _ x -> scan k (x:ds)
SrcLoc _ -> scan k ds
Cat x y -> scan k (x:y:ds)
Alt x _ -> scan k (x:ds)
Column f -> scan k (f k:ds)
Nesting f -> scan k (f 0:ds)
-- | Display a rendered document.
displayS :: RDoc -> ShowS
displayS = go
where
go :: RDoc -> ShowS
go REmpty = id
go (RChar c x) = showChar c . go x
go (RString _ s x) = showString s . go x
go (RText s x) = showString (T.unpack s) . go x
go (RLazyText s x) = showString (L.unpack s) . go x
go (RPos _ x) = go x
go (RLine i x) = showString ('\n' : replicate i ' ') . go x
-- | Render and display a document.
prettyS :: Int -> Doc -> ShowS
prettyS w x = displayS (render w x)
-- | Render and convert a document to a 'String'.
pretty :: Int -> Doc -> String
pretty w x = prettyS w x ""
-- | Display a rendered document with #line pragmas.
displayPragmaS :: RDoc -> ShowS
displayPragmaS = go
where
go :: RDoc -> ShowS
go REmpty = id
go (RChar c x) = showChar c . go x
go (RString _ s x) = showString s . go x
go (RText s x) = showString (T.unpack s) . go x
go (RLazyText s x) = showString (L.unpack s) . go x
go (RPos p x) = showChar '\n' .
showString "#line " .
shows (posLine p) .
showChar ' ' .
shows (posFile p) .
go x
go (RLine i x) = showString ('\n' : replicate i ' ') .
go x
-- | Render and display a document with #line pragmas.
prettyPragmaS :: Int -> Doc -> ShowS
prettyPragmaS w x = displayPragmaS (render w x)
-- | Render and convert a document to a 'String' with #line pragmas.
prettyPragma :: Int -> Doc -> String
prettyPragma w x = prettyPragmaS w x ""
-- | Display a rendered document as 'L.Text'. Uses a builder.
displayLazyText :: RDoc -> L.Text
displayLazyText = B.toLazyText . go
where
go :: RDoc -> B.Builder
go REmpty = mempty
go (RChar c x) = B.singleton c `mappend` go x
go (RString _ s x) = B.fromString s `mappend` go x
go (RText s x) = B.fromText s `mappend` go x
go (RLazyText s x) = B.fromLazyText s `mappend` go x
go (RPos _ x) = go x
go (RLine i x) = B.fromString ('\n':replicate i ' ') `mappend` go x
-- | Render and display a document as 'L.Text'. Uses a builder.
prettyLazyText :: Int -> Doc -> L.Text
prettyLazyText w x = displayLazyText (render w x)
-- | Display a rendered document with #line pragmas as 'L.Text'. Uses a builder.
displayPragmaLazyText :: RDoc -> L.Text
displayPragmaLazyText = B.toLazyText . go
where
go :: RDoc -> B.Builder
go REmpty = mempty
go (RChar c x) = B.singleton c `mappend` go x
go (RText s x) = B.fromText s `mappend` go x
go (RLazyText s x) = B.fromLazyText s `mappend` go x
go (RString _ s x) = B.fromString s `mappend` go x
go (RPos p x) = B.singleton '\n' `mappend`
B.fromString "#line " `mappend`
(go . renderCompact . ppr) (posLine p) `mappend`
B.singleton ' ' `mappend`
(go . renderCompact . ppr) (posFile p) `mappend`
go x
go (RLine i x) = B.fromString ('\n':replicate i ' ') `mappend`
go x
-- | Render and convert a document to 'L.Text' with #line pragmas. Uses a builder.
prettyPragmaLazyText :: Int -> Doc -> L.Text
prettyPragmaLazyText w x = displayPragmaLazyText (render w x)
merge :: Maybe Pos -> Loc -> Maybe Pos
merge Nothing NoLoc = Nothing
merge Nothing (Loc p _) = Just p
merge (Just p) NoLoc = Just p
merge (Just p1) (Loc p2 _) = let p = min p1 p2 in p `seq` Just p
lineloc :: Maybe Pos -- ^ Previous source position
-> Maybe Pos -- ^ Current source position
-> (Maybe Pos, RDocS) -- ^ Current source position and position to
-- output
lineloc Nothing Nothing = (Nothing, id)
lineloc Nothing (Just p) = (Just p, RPos p)
lineloc (Just p1) (Just p2)
| posFile p2 == posFile p1 &&
posLine p2 == posLine p1 + 1 = (Just p2, id)
| otherwise = (Just p2, RPos p2)
lineloc (Just p1) Nothing
| posFile p2 == posFile p1 &&
posLine p2 == posLine p1 + 1 = (Just p2, id)
| otherwise = (Just p2, RPos p2)
where
p2 = advance p1
advance :: Pos -> Pos
advance (Pos f l c coff) = Pos f (l+1) c coff
-- | A rendered document.
data RDoc = REmpty -- ^ The empty document
| RChar Char RDoc -- ^ A single character
| RString !Int String RDoc -- ^ 'String' with associated length (to
-- avoid recomputation)
| RText T.Text RDoc -- ^ 'T.Text'
| RLazyText L.Text RDoc -- ^ 'L.Text'
| RPos Pos RDoc -- ^ Tag output with source location
| RLine !Int RDoc -- ^ A newline with the indentation of the
-- subsequent line
type RDocS = RDoc -> RDoc
data Docs = Nil -- ^ No document.
| Cons !Int Doc Docs -- ^ Indentation, document and tail
best :: Int -> Int -> Doc -> RDoc
best !w k x = be Nothing Nothing k id (Cons 0 x Nil)
where
be :: Maybe Pos -- ^ Previous source position
-> Maybe Pos -- ^ Current source position
-> Int -- ^ Current column
-> RDocS
-> Docs
-> RDoc
be _ _ !_ f Nil = f REmpty
be p p' !k f (Cons i d ds) =
case d of
Empty -> be p p' k f ds
Char c -> be p p' (k+1) (f . RChar c) ds
String l s -> be p p' (k+l) (f . RString l s) ds
Text s -> be p p' (k+T.length s) (f . RText s) ds
LazyText s -> be p p' (k+fromIntegral (L.length s)) (f . RLazyText s) ds
Line -> (f . pragma . RLine i) (be p'' Nothing i id ds)
x `Cat` y -> be p p' k f (Cons i x (Cons i y ds))
Nest j x -> be p p' k f (Cons (i+j) x ds)
x `Alt` y -> better k f (be p p' k id (Cons i x ds))
(be p p' k id (Cons i y ds))
SrcLoc loc -> be p (merge p' loc) k f ds
Column g -> be p p' k f (Cons i (g k) ds)
Nesting g -> be p p' k f (Cons i (g i) ds)
where
(p'', pragma) = lineloc p p'
better :: Int -> RDocS -> RDoc -> RDoc -> RDoc
better !k f x y | fits (w - k) x = f x
| otherwise = f y
fits :: Int -> RDoc -> Bool
fits !w _ | w < 0 = False
fits !_ REmpty = True
fits !w (RChar _ x) = fits (w - 1) x
fits !w (RString l _ x) = fits (w - l) x
fits !w (RText s x) = fits (w - T.length s) x
fits !w (RLazyText s x) = fits (w - fromIntegral (L.length s)) x
fits !w (RPos _ x) = fits w x
fits !_ (RLine _ _) = True
-- | Render a document with a width of 80 and print it to standard output.
putDoc :: Doc -> IO ()
putDoc = TIO.putStr . prettyLazyText 80
-- | Render a document with a width of 80 and print it to the specified handle.
hPutDoc :: Handle -> Doc -> IO ()
hPutDoc h = TIO.hPutStr h . prettyLazyText 80
#if !MIN_VERSION_base(4,5,0)
infixr 6 <>
(<>) :: Doc -> Doc -> Doc
x <> y = x `Cat` y
#endif /* !MIN_VERSION_base(4,5,0) */
instance Monoid Doc where
mempty = empty
mappend = Cat
instance Show Doc where
showsPrec _ = prettyS 80
class Pretty a where
ppr :: a -> Doc
pprPrec :: Int -> a -> Doc
pprList :: [a] -> Doc
ppr = pprPrec 0
pprPrec _ = ppr
pprList xs = list (map ppr xs)
instance Pretty Int where
ppr = text . show
instance Pretty Integer where
ppr = text . show
instance Pretty Float where
ppr = text . show
instance Pretty Double where
ppr = text . show
ratioPrec, ratioPrec1 :: Int
ratioPrec = 7 -- Precedence of ':%' constructor
ratioPrec1 = ratioPrec + 1
instance (Integral a, Pretty a) => Pretty (Ratio a) where
{-# SPECIALIZE instance Pretty Rational #-}
pprPrec p (x:%y) =
parensIf (p > ratioPrec) $
pprPrec ratioPrec1 x <+> char '%' <+> pprPrec ratioPrec1 y
instance Pretty Bool where
ppr = text . show
instance Pretty Char where
ppr = text . show
pprList = text . show
instance Pretty T.Text where
ppr = text . show
instance Pretty L.Text where
ppr = text . show
instance Pretty a => Pretty [a] where
ppr = pprList
instance Pretty () where
ppr () =
tuple []
instance (Pretty a, Pretty b)
=> Pretty (a, b) where
ppr (a, b) =
tuple [ppr a, ppr b]
instance (Pretty a, Pretty b, Pretty c)
=> Pretty (a, b, c) where
ppr (a, b, c) =
tuple [ppr a, ppr b, ppr c]
instance (Pretty a, Pretty b, Pretty c, Pretty d)
=> Pretty (a, b, c, d) where
ppr (a, b, c, d) =
tuple [ppr a, ppr b, ppr c, ppr d]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e)
=> Pretty (a, b, c, d, e) where
ppr (a, b, c, d, e) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f)
=> Pretty (a, b, c, d, e, f) where
ppr (a, b, c, d, e, f) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g)
=> Pretty (a, b, c, d, e, f, g) where
ppr (a, b, c, d, e, f, g) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h)
=> Pretty (a, b, c, d, e, f, g, h) where
ppr (a, b, c, d, e, f, g, h) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i)
=> Pretty (a, b, c, d, e, f, g, h, i) where
ppr (a, b, c, d, e, f, g, h, i) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j)
=> Pretty (a, b, c, d, e, f, g, h, i, j) where
ppr (a, b, c, d, e, f, g, h, i, j) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k) where
ppr (a, b, c, d, e, f, g, h, i, j, k) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m, Pretty n)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m, n) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m, ppr n]
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e,
Pretty f, Pretty g, Pretty h, Pretty i, Pretty j,
Pretty k, Pretty l, Pretty m, Pretty n, Pretty o)
=> Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where
ppr (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) =
tuple [ppr a, ppr b, ppr c, ppr d, ppr e,
ppr f, ppr g, ppr h, ppr i, ppr j,
ppr k, ppr l, ppr m, ppr n, ppr o]
instance Pretty a => Pretty (Maybe a) where
pprPrec _ Nothing = empty
pprPrec p (Just a) = pprPrec p a
instance Pretty Pos where
ppr p@(Pos _ l c _) =
text (posFile p) <> colon <> ppr l <> colon <> ppr c
instance Pretty Loc where
ppr NoLoc = text "<no location info>"
ppr (Loc p1@(Pos f1 l1 c1 _) p2@(Pos f2 l2 c2 _))
| f1 == f2 = text (posFile p1) <> colon <//> pprLineCol l1 c1 l2 c2
| otherwise = ppr p1 <> text "-" <> ppr p2
where
pprLineCol :: Int -> Int -> Int -> Int -> Doc
pprLineCol l1 c1 l2 c2
| l1 == l2 && c1 == c2 = ppr l1 <//> colon <//> ppr c1
| l1 == l2 && c1 /= c2 = ppr l1 <//> colon <//>
ppr c1 <> text "-" <> ppr c2
| otherwise = ppr l1 <//> colon <//> ppr c1
<> text "-" <>
ppr l2 <//> colon <//> ppr c2
instance Pretty x => Pretty (L x) where
pprPrec p (L _ x) = pprPrec p x
instance (Pretty k, Pretty v) => Pretty (Map.Map k v) where
ppr = pprList . Map.toList
instance Pretty a => Pretty (Set.Set a) where
ppr = pprList . Set.toList
instance Pretty Word8 where
ppr = text . show
instance Pretty Word16 where
ppr = text . show
instance Pretty Word32 where
ppr = text . show
instance Pretty Word64 where
ppr = text . show
instance Pretty Int8 where
ppr = text . show
instance Pretty Int16 where
ppr = text . show
instance Pretty Int32 where
ppr = text . show
instance Pretty Int64 where
ppr = text . show
| flowbox-public/mainland-pretty | Text/PrettyPrint/Mainland.hs | bsd-3-clause | 27,921 | 0 | 18 | 8,379 | 9,224 | 4,927 | 4,297 | 548 | 20 |
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Optimization.Quantified
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Test suite for optimization iwth quantifiers
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
module TestSuite.Optimization.Quantified(tests) where
import Data.List (isPrefixOf)
import Utils.SBVTestFramework
import qualified Control.Exception as C
-- Test suite
tests :: TestTree
tests =
testGroup "Optimization.Reals"
[ goldenString "optQuant1" $ optE q1
, goldenVsStringShow "optQuant2" $ opt q2
, goldenVsStringShow "optQuant3" $ opt q3
, goldenVsStringShow "optQuant4" $ opt q4
, goldenString "optQuant5" $ optE q5
]
where opt = optimize Lexicographic
optE q = (show <$> optimize Lexicographic q) `C.catch` (\(e::C.SomeException) -> return (pick (show e)))
pick s = unlines [l | l <- lines s, "***" `isPrefixOf` l]
q1 :: Goal
q1 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
minimize "goal" $ 2*x
q2 :: Goal
q2 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
minimize "goal" a
q3 :: Goal
q3 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
minimize "goal" a
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
q4 :: Goal
q4 = do a <- sInteger "a"
[b1, b2] <- sIntegers ["b1", "b2"]
minimize "goal" $ 2*a
x <- forall "x" :: Symbolic SInteger
constrain $ 2 * (a * x + b1) .== 2
constrain $ 4 * (a * x + b2) .== 4
constrain $ a .>= 0
q5 :: Goal
q5 = do a <- sInteger "a"
x <- forall "x" :: Symbolic SInteger
y <- forall "y" :: Symbolic SInteger
b <- sInteger "b"
constrain $ a .>= 0
constrain $ b .>= 0
constrain $ x+y .>= 0
minimize "goal" $ a+b
{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
| josefs/sbv | SBVTestSuite/TestSuite/Optimization/Quantified.hs | bsd-3-clause | 2,532 | 0 | 14 | 742 | 874 | 438 | 436 | 58 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Tray icon with configurable popup menu that uses wxWidgets as
-- a backend.
-- Copyright: (c) 2015 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Tray icon with configurable popup menu that uses wxWidgets as a backend.
module Main (main)
where
import Control.Exception (SomeException, handle)
import Control.Monad (Monad((>>=), return), (=<<), mapM_, void)
import Data.Bool ((||), otherwise)
import Data.Eq (Eq((==)))
import Data.Function ((.), ($), flip)
import Data.Functor ((<$))
import Data.Monoid ((<>))
import Data.String (String)
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (IO, hPrint, hPutStrLn, stderr)
import System.FilePath ((</>))
import System.Process (system)
import Control.Lens ((^.), foldMapOf)
import Graphics.UI.WX
( Menu
, Prop((:=))
, command
, help
, menuItem
, menuPane
, on
, start
, text
)
import Graphics.UI.WXCore.Events
( EventTaskBarIcon(TaskBarIconLeftDown, TaskBarIconRightDown)
, evtHandlerOnTaskBarIconEvent
)
import Graphics.UI.WXCore.Image (iconCreateFromFile)
import Graphics.UI.WXCore.WxcClasses
( taskBarIconCreate
, taskBarIconSetIcon
, taskBarIconPopupMenu
)
import Graphics.UI.WXCore.WxcClassTypes (Icon, TaskBarIcon)
import Graphics.UI.WXCore.WxcTypes (sizeNull)
import Options.Applicative (fullDesc)
import System.Environment.XDG.BaseDir (getUserConfigFile)
import Main.ConfigFile (getMenuItems, readConfigFile, readUserConfigFile)
import Main.Options (execParser, optionsParser)
import Main.Type.MenuItem (MenuItem)
import Main.Type.MenuItem.Lens (menuItems)
import qualified Main.Type.MenuItem.Lens as MenuItem
( command
, description
, name
)
import qualified Main.Type.Options.Lens as Options (iconFile)
import Paths_toolbox (getDataFileName)
taskBarIcon
:: Icon ()
-> String
-> (TaskBarIcon () -> EventTaskBarIcon -> IO ())
-> IO ()
taskBarIcon icon str f = do
tbi <- taskBarIconCreate
_ <- taskBarIconSetIcon tbi icon str
evtHandlerOnTaskBarIconEvent tbi $ f tbi
main :: IO ()
main = getArgs >>= execParser optionsParser fullDesc >>= \options -> start $ do
menu <- getMenuItems options onConfigError
[ readConfigFile getDataFileName
, readUserConfigFile (getUserConfigFile "toolbox")
]
icon <- flip iconCreateFromFile sizeNull
=<< case options ^. Options.iconFile of
fileName@(c : _)
| c == '/' -> return fileName
| otherwise -> getDataFileName fileName
"" -> getDataFileName $ "icons" </> iconFileName
toolboxMenu <- menuPane [text := "Toolbox"]
foldMapOf menuItems (mapM_ $ addMenuItem toolboxMenu) menu
addMenuItem' toolboxMenu "Exit toolbox" "Exit toolbox" exitSuccess
taskBarIcon icon "Toolbox" $ \tbi evt -> case evt of
_ | evt == TaskBarIconLeftDown || evt == TaskBarIconRightDown
-> () <$ taskBarIconPopupMenu tbi toolboxMenu
| otherwise
-> return ()
where
iconFileName = "elegantthemes-tools-icon.png"
-- iconFileName = "elegantthemes-beautiful-flat-icons-tools-icon.png"
handleExceptions = handle $ \e -> hPrint stderr (e :: SomeException)
addMenuItem :: Menu a -> MenuItem -> IO ()
addMenuItem m item = addMenuItem' m
(item ^. MenuItem.name)
(item ^. MenuItem.description)
. handleExceptions . void . system $ item ^. MenuItem.command
addMenuItem' :: Menu a -> String -> String -> IO () -> IO ()
addMenuItem' m name desc action = () <$ menuItem m
[ text := name
, help := desc
, on command := action
]
onConfigError msg = do
hPutStrLn stderr $ "Parsing configuration failed: " <> msg
exitFailure
| trskop/toolbox-tray-icon | src/WxMain.hs | bsd-3-clause | 4,019 | 0 | 20 | 899 | 1,049 | 594 | 455 | 91 | 2 |
{-# OPTIONS -fglasgow-exts #-}
--
-- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library 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
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
-- | An interface to the GHC runtime's dynamic linker, providing runtime
-- loading and linking of Haskell object files, commonly known as
-- /plugins/.
module System.Plugins.Load (
-- * The @LoadStatus@ type
LoadStatus(..)
-- * High-level interface
, load
, load_
, dynload
, pdynload
, pdynload_
, unload
, unloadAll
, reload
, Module(..)
-- * Low-level interface
, initLinker -- start it up
, loadModule -- load a vanilla .o
, loadFunction -- retrieve a function from an object
, loadFunction_ -- retrieve a function from an object
, loadPackageFunction
, loadPackage -- load a ghc library and its cbits
, unloadPackage -- unload a ghc library and its cbits
, loadPackageWith -- load a pkg using the package.conf provided
, loadShared -- load a .so object file
, resolveObjs -- and resolve symbols
, loadRawObject -- load a bare .o. no dep chasing, no .hi file reading
, Symbol
, getImports
) where
#include "../../../config.h"
import System.Plugins.Make ( build )
import System.Plugins.Env
import System.Plugins.Utils
import System.Plugins.Consts ( sysPkgSuffix, hiSuf, prefixUnderscore )
import System.Plugins.LoadTypes
-- import Language.Hi.Parser
import BinIface
import HscTypes
import Module (moduleName, moduleNameString)
import PackageConfig (packageIdString)
import HscMain (newHscEnv)
import TcRnMonad (initTcRnIf)
import Data.Dynamic ( fromDynamic, Dynamic )
import Data.Typeable ( Typeable )
import Data.List ( isSuffixOf, nub, nubBy )
import Control.Monad ( when, filterM, liftM )
import System.Directory ( doesFileExist, removeFile )
import Foreign.C.String ( CString, withCString, peekCString )
import GHC.Ptr ( Ptr(..), nullPtr )
import GHC.Exts ( addrToHValue# )
import GHC.Prim ( unsafeCoerce# )
#if DEBUG
import System.IO ( hFlush, stdout )
#endif
import System.IO ( hClose )
ifaceModuleName = moduleNameString . moduleName . mi_module
readBinIface' :: FilePath -> IO ModIface
readBinIface' hi_path = do
-- kludgy as hell
e <- newHscEnv undefined
initTcRnIf 'r' e undefined undefined (readBinIface hi_path)
-- TODO need a loadPackage p package.conf :: IO () primitive
--
-- | The @LoadStatus@ type encodes the return status of functions that
-- perform dynamic loading in a type isomorphic to 'Either'. Failure
-- returns a list of error strings, success returns a reference to a
-- loaded module, and the Haskell value corresponding to the symbol that
-- was indexed.
--
data LoadStatus a
= LoadSuccess Module a
| LoadFailure Errors
--
-- | 'load' is the basic interface to the dynamic loader. A call to
-- 'load' imports a single object file into the caller's address space,
-- returning the value associated with the symbol requested. Libraries
-- and modules that the requested module depends upon are loaded and
-- linked in turn.
--
-- The first argument is the path to the object file to load, the second
-- argument is a list of directories to search for dependent modules.
-- The third argument is a list of paths to user-defined, but
-- unregistered, /package.conf/ files. The 'Symbol' argument is the
-- symbol name of the value you with to retrieve.
--
-- The value returned must be given an explicit type signature, or
-- provided with appropriate type constraints such that Haskell compiler
-- can determine the expected type returned by 'load', as the return
-- type is notionally polymorphic.
--
-- Example:
--
-- > do mv <- load "Plugin.o" ["api"] [] "resource"
-- > case mv of
-- > LoadFailure msg -> print msg
-- > LoadSuccess _ v -> return v
--
load :: FilePath -- ^ object file
-> [FilePath] -- ^ any include paths
-> [PackageConf] -- ^ list of package.conf paths
-> Symbol -- ^ symbol to find
-> IO (LoadStatus a)
load obj incpaths pkgconfs sym = do
initLinker
-- load extra package information
mapM_ addPkgConf pkgconfs
(hif,moduleDeps) <- loadDepends obj incpaths
-- why is this the package name?
#if DEBUG
putStr (' ':(decode $ ifaceModuleName hif)) >> hFlush stdout
#endif
m' <- loadObject obj . Object . ifaceModuleName $ hif
let m = m' { iface = hif }
resolveObjs (mapM_ unloadAll (m:moduleDeps))
#if DEBUG
putStrLn " ... done" >> hFlush stdout
#endif
addModuleDeps m' moduleDeps
v <- loadFunction m sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m a
--
-- | Like load, but doesn't want a package.conf arg (they are rarely used)
--
load_ :: FilePath -> [FilePath] -> Symbol -> IO (LoadStatus a)
load_ o i s = load o i [] s
--
-- A work-around for Dynamics. The keys used to compare two TypeReps are
-- somehow not equal for the same type in hs-plugin's loaded objects.
-- Solution: implement our own dynamics...
--
-- The problem with dynload is that it requires the plugin to export
-- a value that is a Dynamic (in our case a (TypeRep,a) pair). If this
-- is not the case, we core dump. Use pdynload if you don't trust the
-- user to supply you with a Dynamic
--
dynload :: Typeable a
=> FilePath
-> [FilePath]
-> [PackageConf]
-> Symbol
-> IO (LoadStatus a)
dynload obj incpaths pkgconfs sym = do
s <- load obj incpaths pkgconfs sym
case s of e@(LoadFailure _) -> return e
LoadSuccess m dyn_v -> return $
case fromDynamic (unsafeCoerce# dyn_v :: Dynamic) of
Just v' -> LoadSuccess m v'
Nothing -> LoadFailure ["Mismatched types in interface"]
------------------------------------------------------------------------
--
-- The super-replacement for dynload
--
-- Use GHC at runtime so we get staged type inference, providing full
-- power dynamics, *on module interfaces only*. This is quite suitable
-- for plugins, of coures :)
--
-- TODO where does the .hc file go in the call to build() ?
--
pdynload :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths
-> [PackageConf] -- ^ package confs
-> Type -- ^ API type
-> Symbol -- ^ symbol
-> IO (LoadStatus a)
pdynload object incpaths pkgconfs ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths [] ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
--
-- | Like pdynload, but you can specify extra arguments to the
-- typechecker.
--
pdynload_ :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths for loading
-> [PackageConf] -- ^ any extra package.conf files
-> [Arg] -- ^ extra arguments to ghc, when typechecking
-> Type -- ^ expected type
-> Symbol -- ^ symbol to load
-> IO (LoadStatus a)
pdynload_ object incpaths pkgconfs args ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths args ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
------------------------------------------------------------------------
-- run the typechecker over the constraint file
--
-- Problem: if the user depends on a non-auto package to build the
-- module, then that package will not be in scope when we try to build
-- the module, when performing `unify'. Normally make() will handle this
-- (as it takes extra ghc args). pdynload ignores these, atm -- but it
-- shouldn't. Consider a pdynload() that accepts extra -package flags?
--
-- Also, pdynload() should accept extra in-scope modules.
-- Maybe other stuff we want to hack in here.
--
unify obj incs args ty sym = do
(tmpf,hdl) <- mkTemp
(tmpf1,hdl1) <- mkTemp -- and send .hi file here.
hClose hdl1
let nm = mkModid (basename tmpf)
src = mkTest nm (hierize' . mkModid . hierize $ obj)
(fst $ break (=='.') ty) ty sym
is = map ("-i"++) incs -- api
i = "-i" ++ dirname obj -- plugin
hWrite hdl src
e <- build tmpf tmpf1 (i:is++args++["-fno-code","-ohi "++tmpf1])
mapM_ removeFile [tmpf,tmpf1]
return e
where
-- fix up hierarchical names
hierize [] = []
hierize ('/':cs) = '\\' : hierize cs
hierize (c:cs) = c : hierize cs
hierize'[] = []
hierize' ('\\':cs) = '.' : hierize' cs
hierize' (c:cs) = c : hierize' cs
mkTest modnm plugin api ty sym =
"module "++ modnm ++" where" ++
"\nimport qualified " ++ plugin ++
"\nimport qualified " ++ api ++
"{-# LINE 1 \"<typecheck>\" #-}" ++
"\n_ = "++ plugin ++"."++ sym ++" :: "++ty
------------------------------------------------------------------------
{-
--
-- old version that tried to rip stuff from .hi files
--
pdynload obj incpaths pkgconfs sym ty = do
(m, v) <- load obj incpaths pkgconfs sym
ty' <- mungeIface sym obj
if ty == ty'
then return $ Just (m, v)
else return Nothing -- mismatched types
where
-- grab the iface output from GHC. find the line relevant to our
-- symbol. grab the string rep of the type.
mungeIface sym o = do
let hi = replaceSuffix o hiSuf
(out,_) <- exec ghc ["--show-iface", hi]
case find (\s -> (sym ++ " :: ") `isPrefixOf` s) out of
Nothing -> return undefined
Just v -> do let v' = drop 3 $ dropWhile (/= ':') v
return v'
-}
{-
--
-- a version of load the also unwraps and types a Dynamic object
--
dynload2 :: Typeable a =>
FilePath ->
FilePath ->
Maybe [PackageConf] ->
Symbol ->
IO (Module, a)
dynload2 obj incpath pkgconfs sym = do
(m, v) <- load obj incpath pkgconfs sym
case fromDynamic v of
Nothing -> panic $ "load: couldn't type "++(show v)
Just a -> return (m,a)
-}
------------------------------------------------------------------------
--
-- | unload a module (not its dependencies)
-- we have the dependencies, so cascaded unloading is possible
--
-- once you unload it, you can't 'load' it again, you have to 'reload'
-- it. Cause we don't unload all the dependencies
--
unload :: Module -> IO ()
unload m = rmModuleDeps m >> unloadObj m
------------------------------------------------------------------------
--
-- | unload a module and its dependencies
-- we have the dependencies, so cascaded unloading is possible
--
unloadAll :: Module -> IO ()
unloadAll m = do moduleDeps <- getModuleDeps m
rmModuleDeps m
mapM_ unloadAll moduleDeps
unload m
--
-- | this will be nice for panTHeon, needs thinking about the interface
-- reload a single object file. don't care about depends, assume they
-- are loaded. (should use state to store all this)
--
-- assumes you've already done a 'load'
--
-- should factor the code
--
reload :: Module -> Symbol -> IO (LoadStatus a)
reload m@(Module{path = p, iface = hi}) sym = do
unloadObj m -- unload module (and delete)
#if DEBUG
putStr ("Reloading "++(mname m)++" ... ") >> hFlush stdout
#endif
m_ <- loadObject p . Object . ifaceModuleName $ hi -- load object at path p
let m' = m_ { iface = hi }
resolveObjs (unloadAll m)
#if DEBUG
putStrLn "done" >> hFlush stdout
#endif
v <- loadFunction m' sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m' a
-- ---------------------------------------------------------------------
-- This is a stripped-down version of André Pang's runtime_loader,
-- which in turn is based on GHC's ghci\/ObjLinker.lhs binding
--
-- Load and unload\/Haskell modules at runtime. This is not really
-- \'dynamic loading\', as such -- that implies that you\'re working
-- with proper shared libraries, whereas this is far more simple and
-- only loads object files. But it achieves the same goal: you can
-- load a Haskell module at runtime, load a function from it, and run
-- the function. I have no idea if this works for types, but that
-- doesn\'t mean that you can\'t try it :).
--
-- read $fptools\/ghc\/compiler\/ghci\/ObjLinker.lhs for how to use this stuff
--
------------------------------------------------------------------------
-- | Call the initLinker function first, before calling any of the other
-- functions in this module - otherwise you\'ll get unresolved symbols.
-- initLinker :: IO ()
-- our initLinker transparently calls the one in GHC
--
-- | Load a function from a module (which must be loaded and resolved first).
--
loadFunction :: Module -- ^ The module the value is in
-> String -- ^ Symbol name of value
-> IO (Maybe a) -- ^ The value you want
loadFunction (Module { iface = i }) valsym
= loadFunction_ (ifaceModuleName i) valsym
loadFunction_ :: String
-> String
-> IO (Maybe a)
loadFunction_ = loadFunction__ Nothing
loadFunction__ :: Maybe String
-> String
-> String
-> IO (Maybe a)
loadFunction__ pkg m valsym
= do let symbol = prefixUnderscore++(maybe "" (\p -> encode p++"_") pkg)
++encode m++"_"++(encode valsym)++"_closure"
#if DEBUG
putStrLn $ "Looking for <<"++symbol++">>"
#endif
ptr@(~(Ptr addr)) <- withCString symbol c_lookupSymbol
if (ptr == nullPtr)
then return Nothing
else case addrToHValue# addr of
(# hval #) -> return ( Just hval )
-- | Loads a function from a package module, given the package name,
-- module name and symbol name.
loadPackageFunction :: String -- ^ Package name, including version number.
-> String -- ^ Module name
-> String -- ^ Symbol to lookup in the module
-> IO (Maybe a)
loadPackageFunction pkgName modName functionName =
do loadPackage pkgName
resolveObjs (unloadPackage pkgName)
loadFunction__ (Just pkgName) modName functionName
--
-- | Load a GHC-compiled Haskell vanilla object file.
-- The first arg is the path to the object file
--
-- We make it idempotent to stop the nasty problem of loading the same
-- .o twice. Also the rts is a very special package that is already
-- loaded, even if we ask it to be loaded. N.B. we should insert it in
-- the list of known packages.
--
-- NB the environment stores the *full path* to an object. So if you
-- want to know if a module is already loaded, you need to supply the
-- *path* to that object, not the name.
--
-- NB -- let's try just the module name.
--
-- loadObject loads normal .o objs, and packages too. .o objs come with
-- a nice canonical Z-encoded modid. packages just have a simple name.
-- Do we want to ensure they won't clash? Probably.
--
--
-- the second argument to loadObject is a string to use as the unique
-- identifier for this object. For normal .o objects, it should be the
-- Z-encoded modid from the .hi file. For archives\/packages, we can
-- probably get away with the package name
--
loadObject :: FilePath -> Key -> IO Module
loadObject p ky@(Object k) = loadObject' p ky k
loadObject p ky@(Package k) = loadObject' p ky k
loadObject' :: FilePath -> Key -> String -> IO Module
loadObject' p ky k
| ("HSrts"++sysPkgSuffix) `isSuffixOf` p = return (emptyMod p)
| otherwise
= do alreadyLoaded <- isLoaded k
when (not alreadyLoaded) $ do
r <- withCString p c_loadObj
when (not r) (panic $ "Could not load module `"++p++"'")
addModule k (emptyMod p) -- needs to Z-encode module name
return (emptyMod p)
where emptyMod q = Module q (mkModid q) Vanilla undefined ky
--
-- load a single object. no dependencies. You should know what you're
-- doing.
--
loadModule :: FilePath -> IO Module
loadModule obj = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then error $ "No .hi file found for "++show obj
else do hiface <- readBinIface' hifile
loadObject obj (Object (ifaceModuleName hiface))
--
-- | Load a generic .o file, good for loading C objects.
-- You should know what you're doing..
-- Returns a fairly meaningless iface value.
--
loadRawObject :: FilePath -> IO Module
loadRawObject obj = loadObject obj (Object k)
where
k = encode (mkModid obj) -- Z-encoded module name
--
-- | Resolve (link) the modules loaded by the 'loadObject' function.
--
resolveObjs :: IO a -> IO ()
resolveObjs unloadLoaded
= do r <- c_resolveObjs
when (not r) $ unloadLoaded >> panic "resolvedObjs failed."
-- | Unload a module
unloadObj :: Module -> IO ()
unloadObj (Module { path = p, kind = k, key = ky }) = case k of
Vanilla -> withCString p $ \c_p -> do
removed <- rmModule name
when (removed) $ do r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
Shared -> return () -- can't unload .so?
where name = case ky of Object s -> s ; Package pk -> pk
--
-- | from ghci\/ObjLinker.c
--
-- Load a .so type object file.
--
loadShared :: FilePath -> IO Module
loadShared str = do
#if DEBUG
putStrLn $ " shared: " ++ str
#endif
maybe_errmsg <- withCString str $ \dll -> c_addDLL dll
if maybe_errmsg == nullPtr
then return (Module str (mkModid str) Shared undefined (Package (mkModid str)))
else do e <- peekCString maybe_errmsg
panic $ "loadShared: couldn't load `"++str++"\' because "++e
--
-- Load a -package that we might need, implicitly loading the cbits too
-- The argument is the name of package (e.g. \"concurrent\")
--
-- How to find a package is determined by the package.conf info we store
-- in the environment. It is just a matter of looking it up.
--
-- Not printing names of dependent pkgs
--
loadPackage :: String -> IO ()
loadPackage p = do
#if DEBUG
putStr (' ':p) >> hFlush stdout
#endif
(libs,dlls) <- lookupPkg p
mapM_ (\l -> loadObject l (Package (mkModid l))) libs
#if DEBUG
putStr (' ':show libs) >> hFlush stdout
putStr (' ':show dlls) >> hFlush stdout
#endif
mapM_ loadShared dlls
--
-- Unload a -package, that has already been loaded. Unload the cbits
-- too. The argument is the name of the package.
--
-- May need to check if it exists.
--
-- Note that we currently need to unload everything. grumble grumble.
--
-- We need to add the version number to the package name with 6.4 and
-- over. "yi-0.1" for example. This is a bug really.
--
unloadPackage :: String -> IO ()
unloadPackage pkg = do
let pkg' = takeWhile (/= '-') pkg -- in case of *-0.1
libs <- liftM (\(a,_) -> (filter (isSublistOf pkg') ) a) (lookupPkg pkg)
flip mapM_ libs $ \p -> withCString p $ \c_p -> do
r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
rmModule (mkModid p) -- unrecord this module
--
-- load a package using the given package.conf to help
-- TODO should report if it doesn't actually load the package, instead
-- of mapM_ doing nothing like above.
--
loadPackageWith :: String -> [PackageConf] -> IO ()
loadPackageWith p pkgconfs = do
#if DEBUG
putStr "Loading package" >> hFlush stdout
#endif
mapM_ addPkgConf pkgconfs
loadPackage p
#if DEBUG
putStrLn " done"
#endif
-- ---------------------------------------------------------------------
-- module dependency loading
--
-- given an Foo.o vanilla object file, supposed to be a plugin compiled
-- by our library, find the associated .hi file. If this is found, load
-- the dependencies, packages first, then the modules. If it doesn't
-- exist, assume the user knows what they are doing and continue. The
-- linker will crash on them anyway. Second argument is any include
-- paths to search in
--
-- ToDo problem with absolute and relative paths, and different forms of
-- relative paths. A user may cause a dependency to be loaded, which
-- will search the incpaths, and perhaps find "./Foo.o". The user may
-- then explicitly load "Foo.o". These are the same, and the loader
-- should ignore the second load request. However, isLoaded will say
-- that "Foo.o" is not loaded, as the full string is used as a key to
-- the modenv fm. We need a canonical form for the keys -- is basename
-- good enough?
--
loadDepends :: FilePath -> [FilePath] -> IO (ModIface,[Module])
loadDepends obj incpaths = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then do
#if DEBUG
putStrLn "No .hi file found." >> hFlush stdout
#endif
return (undefined,[]) -- could be considered fatal
else do hiface <- readBinIface' hifile
let ds = mi_deps hiface
-- remove ones that we've already loaded
ds' <- filterM loaded . map (moduleNameString . fst) . dep_mods $ ds
-- now, try to generate a path to the actual .o file
-- fix up hierachical names
let mods_ = map (\s -> (s, map (\c ->
if c == '.' then '/' else c) $ s)) ds'
-- construct a list of possible dependent modules to load
let mods = concatMap (\p ->
map (\(hi,m) -> (hi,p </> m++".o")) mods_) incpaths
-- remove modules that don't exist
mods' <- filterM (\(_,y) -> doesFileExist y) $
nubBy (\v u -> snd v == snd u) mods
-- now remove duplicate valid paths to the same object
let mods'' = nubBy (\v u -> fst v == fst u) mods'
-- and find some packages to load, as well.
let ps = dep_pkgs ds
ps' <- filterM loaded . map packageIdString . nub $ ps
#if DEBUG
when (not (null ps')) $
putStr "Loading package" >> hFlush stdout
#endif
mapM_ loadPackage ps'
#if DEBUG
when (not (null ps')) $
putStr " ... linking ... " >> hFlush stdout
#endif
resolveObjs (mapM_ unloadPackage ps')
#if DEBUG
when (not (null ps')) $ putStrLn "done"
putStr "Loading object"
mapM_ (\(m,_) -> putStr (" "++ m) >> hFlush stdout) mods''
#endif
moduleDeps <- mapM (\(hi,m) -> loadObject m (Object hi)) mods''
return (hiface,moduleDeps)
-- ---------------------------------------------------------------------
-- Nice interface to .hi parser
--
getImports :: String -> IO [String]
getImports m = do
hi <- readBinIface' (m ++ hiSuf)
return . map (moduleNameString . fst) . dep_mods . mi_deps $ hi
-- ---------------------------------------------------------------------
-- C interface
--
foreign import ccall threadsafe "lookupSymbol"
c_lookupSymbol :: CString -> IO (Ptr a)
foreign import ccall unsafe "loadObj"
c_loadObj :: CString -> IO Bool
foreign import ccall unsafe "unloadObj"
c_unloadObj :: CString -> IO Bool
foreign import ccall unsafe "resolveObjs"
c_resolveObjs :: IO Bool
foreign import ccall unsafe "addDLL"
c_addDLL :: CString -> IO CString
foreign import ccall unsafe "initLinker"
initLinker :: IO ()
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/src/System/Plugins/Load.hs | bsd-3-clause | 25,431 | 1 | 22 | 7,137 | 4,387 | 2,336 | 2,051 | -1 | -1 |
-- | Definitions of kinds of factions present in a game, both human
-- and computer-controlled.
module Content.FactionKind
( -- * Group name patterns
pattern EXPLORER_REPRESENTATIVE, pattern EXPLORER_SHORT, pattern EXPLORER_NO_ESCAPE, pattern EXPLORER_MEDIUM, pattern EXPLORER_TRAPPED, pattern EXPLORER_AUTOMATED, pattern EXPLORER_AUTOMATED_TRAPPED, pattern EXPLORER_CAPTIVE, pattern EXPLORER_PACIFIST, pattern COMPETITOR_REPRESENTATIVE, pattern COMPETITOR_SHORT, pattern COMPETITOR_NO_ESCAPE, pattern CIVILIAN_REPRESENTATIVE, pattern CONVICT_REPRESENTATIVE, pattern MONSTER_REPRESENTATIVE, pattern MONSTER_ANTI, pattern MONSTER_ANTI_CAPTIVE, pattern MONSTER_ANTI_PACIFIST, pattern MONSTER_TOURIST, pattern MONSTER_TOURIST_PASSIVE, pattern MONSTER_CAPTIVE, pattern MONSTER_CAPTIVE_NARRATING, pattern ANIMAL_REPRESENTATIVE, pattern ANIMAL_MAGNIFICENT, pattern ANIMAL_EXQUISITE, pattern ANIMAL_CAPTIVE, pattern ANIMAL_NARRATING, pattern ANIMAL_MAGNIFICENT_NARRATING, pattern ANIMAL_CAPTIVE_NARRATING, pattern HORROR_REPRESENTATIVE, pattern HORROR_CAPTIVE, pattern HORROR_PACIFIST
, pattern REPRESENTATIVE
, groupNamesSingleton, groupNames
, -- * Content
content
#ifdef EXPOSE_INTERNAL
-- * Group name patterns
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Game.LambdaHack.Content.FactionKind
import qualified Game.LambdaHack.Content.ItemKind as IK
import Game.LambdaHack.Definition.Ability
import Game.LambdaHack.Definition.Defs
import Game.LambdaHack.Definition.DefsInternal
import Content.ItemKindActor
import Content.ItemKindOrgan
-- * Group name patterns
groupNamesSingleton :: [GroupName FactionKind]
groupNamesSingleton =
[EXPLORER_REPRESENTATIVE, EXPLORER_SHORT, EXPLORER_NO_ESCAPE, EXPLORER_MEDIUM, EXPLORER_TRAPPED, EXPLORER_AUTOMATED, EXPLORER_AUTOMATED_TRAPPED, EXPLORER_CAPTIVE, EXPLORER_PACIFIST, COMPETITOR_REPRESENTATIVE, COMPETITOR_SHORT, COMPETITOR_NO_ESCAPE, CIVILIAN_REPRESENTATIVE, CONVICT_REPRESENTATIVE, MONSTER_REPRESENTATIVE, MONSTER_ANTI, MONSTER_ANTI_CAPTIVE, MONSTER_ANTI_PACIFIST, MONSTER_TOURIST, MONSTER_TOURIST_PASSIVE, MONSTER_CAPTIVE, MONSTER_CAPTIVE_NARRATING, ANIMAL_REPRESENTATIVE, ANIMAL_MAGNIFICENT, ANIMAL_EXQUISITE, ANIMAL_CAPTIVE, ANIMAL_NARRATING, ANIMAL_MAGNIFICENT_NARRATING, ANIMAL_CAPTIVE_NARRATING, HORROR_REPRESENTATIVE, HORROR_CAPTIVE, HORROR_PACIFIST]
pattern EXPLORER_REPRESENTATIVE, EXPLORER_SHORT, EXPLORER_NO_ESCAPE, EXPLORER_MEDIUM, EXPLORER_TRAPPED, EXPLORER_AUTOMATED, EXPLORER_AUTOMATED_TRAPPED, EXPLORER_CAPTIVE, EXPLORER_PACIFIST, COMPETITOR_REPRESENTATIVE, COMPETITOR_SHORT, COMPETITOR_NO_ESCAPE, CIVILIAN_REPRESENTATIVE, CONVICT_REPRESENTATIVE, MONSTER_REPRESENTATIVE, MONSTER_ANTI, MONSTER_ANTI_CAPTIVE, MONSTER_ANTI_PACIFIST, MONSTER_TOURIST, MONSTER_TOURIST_PASSIVE, MONSTER_CAPTIVE, MONSTER_CAPTIVE_NARRATING, ANIMAL_REPRESENTATIVE, ANIMAL_MAGNIFICENT, ANIMAL_EXQUISITE, ANIMAL_CAPTIVE, ANIMAL_NARRATING, ANIMAL_MAGNIFICENT_NARRATING, ANIMAL_CAPTIVE_NARRATING, HORROR_REPRESENTATIVE, HORROR_CAPTIVE, HORROR_PACIFIST :: GroupName FactionKind
groupNames :: [GroupName FactionKind]
groupNames = [REPRESENTATIVE]
pattern REPRESENTATIVE :: GroupName FactionKind
pattern REPRESENTATIVE = GroupName "representative"
pattern EXPLORER_REPRESENTATIVE = GroupName "explorer"
pattern EXPLORER_SHORT = GroupName "explorer short"
pattern EXPLORER_NO_ESCAPE = GroupName "explorer no escape"
pattern EXPLORER_MEDIUM = GroupName "explorer medium"
pattern EXPLORER_TRAPPED = GroupName "explorer trapped"
pattern EXPLORER_AUTOMATED = GroupName "explorer automated"
pattern EXPLORER_AUTOMATED_TRAPPED = GroupName "explorer automated trapped"
pattern EXPLORER_CAPTIVE = GroupName "explorer captive"
pattern EXPLORER_PACIFIST = GroupName "explorer pacifist"
pattern COMPETITOR_REPRESENTATIVE = GroupName "competitor"
pattern COMPETITOR_SHORT = GroupName "competitor short"
pattern COMPETITOR_NO_ESCAPE = GroupName "competitor no escape"
pattern CIVILIAN_REPRESENTATIVE = GroupName "civilian"
pattern CONVICT_REPRESENTATIVE = GroupName "convict"
pattern MONSTER_REPRESENTATIVE = GroupName "monster"
pattern MONSTER_ANTI = GroupName "monster anti"
pattern MONSTER_ANTI_CAPTIVE = GroupName "monster anti captive"
pattern MONSTER_ANTI_PACIFIST = GroupName "monster anti pacifist"
pattern MONSTER_TOURIST = GroupName "monster tourist"
pattern MONSTER_TOURIST_PASSIVE = GroupName "monster tourist passive"
pattern MONSTER_CAPTIVE = GroupName "monster captive"
pattern MONSTER_CAPTIVE_NARRATING = GroupName "monster captive narrating"
pattern ANIMAL_REPRESENTATIVE = GroupName "animal"
pattern ANIMAL_MAGNIFICENT = GroupName "animal magnificent"
pattern ANIMAL_EXQUISITE = GroupName "animal exquisite"
pattern ANIMAL_CAPTIVE = GroupName "animal captive"
pattern ANIMAL_NARRATING = GroupName "animal narrating"
pattern ANIMAL_MAGNIFICENT_NARRATING = GroupName "animal magnificent narrating"
pattern ANIMAL_CAPTIVE_NARRATING = GroupName "animal captive narrating"
pattern HORROR_REPRESENTATIVE = GroupName "horror"
pattern HORROR_CAPTIVE = GroupName "horror captive"
pattern HORROR_PACIFIST = GroupName "horror pacifist"
-- * Teams
teamCompetitor, teamCivilian, teamConvict, teamMonster, teamAnimal, teamHorror, teamOther :: TeamContinuity
teamCompetitor = TeamContinuity 2
teamCivilian = TeamContinuity 3
teamConvict = TeamContinuity 4
teamMonster = TeamContinuity 5
teamAnimal = TeamContinuity 6
teamHorror = TeamContinuity 7
teamOther = TeamContinuity 10
-- * Content
content :: [FactionKind]
content = [factExplorer, factExplorerShort, factExplorerNoEscape, factExplorerMedium, factExplorerTrapped, factExplorerAutomated, factExplorerAutomatedTrapped, factExplorerCaptive, factExplorerPacifist, factCompetitor, factCompetitorShort, factCompetitorNoEscape, factCivilian, factConvict, factMonster, factMonsterAnti, factMonsterAntiCaptive, factMonsterAntiPacifist, factMonsterTourist, factMonsterTouristPassive, factMonsterCaptive, factMonsterCaptiveNarrating, factAnimal, factAnimalMagnificent, factAnimalExquisite, factAnimalCaptive, factAnimalNarrating, factAnimalMagnificentNarrating, factAnimalCaptiveNarrating, factHorror, factHorrorCaptive, factHorrorPacifist]
factExplorer, factExplorerShort, factExplorerNoEscape, factExplorerMedium, factExplorerTrapped, factExplorerAutomated, factExplorerAutomatedTrapped, factExplorerCaptive, factExplorerPacifist, factCompetitor, factCompetitorShort, factCompetitorNoEscape, factCivilian, factConvict, factMonster, factMonsterAnti, factMonsterAntiCaptive, factMonsterAntiPacifist, factMonsterTourist, factMonsterTouristPassive, factMonsterCaptive, factMonsterCaptiveNarrating, factAnimal, factAnimalMagnificent, factAnimalExquisite, factAnimalCaptive, factAnimalNarrating, factAnimalMagnificentNarrating, factAnimalCaptiveNarrating, factHorror, factHorrorCaptive, factHorrorPacifist :: FactionKind
-- * Content
-- ** teamExplorer
factExplorer = FactionKind
{ fname = "Explorer"
, ffreq = [(EXPLORER_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamExplorer
, fgroups = [(HERO, 100)] -- don't spam the escapists, etc., in description
, fskillsOther = meleeAdjacent
, fcanEscape = True
, fneverEmpty = True
, fhiCondPoly = hiHeroLong
, fhasGender = True
, finitDoctrine = TExplore
, fspawnsFast = False
, fhasPointman = True
, fhasUI = True
, finitUnderAI = False
, fenemyTeams = [teamCompetitor, teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
factExplorerShort = factExplorer
{ ffreq = [(EXPLORER_SHORT, 1)]
, fhiCondPoly = hiHeroShort
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
}
factExplorerNoEscape = factExplorer
{ ffreq = [(EXPLORER_NO_ESCAPE, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroMedium
}
factExplorerMedium = factExplorer
{ ffreq = [(EXPLORER_MEDIUM, 1)]
, fhiCondPoly = hiHeroMedium
}
factExplorerTrapped = factExplorer
{ ffreq = [(EXPLORER_TRAPPED, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroLong
}
factExplorerAutomated = factExplorer
{ ffreq = [(EXPLORER_AUTOMATED, 1)]
, fhasUI = False
, finitUnderAI = True
}
factExplorerAutomatedTrapped = factExplorerAutomated
{ ffreq = [(EXPLORER_AUTOMATED_TRAPPED, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroLong
}
factExplorerCaptive = factExplorer
{ ffreq = [(EXPLORER_CAPTIVE, 1)]
, fneverEmpty = True -- already there
}
factExplorerPacifist = factExplorerCaptive
{ ffreq = [(EXPLORER_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
-- ** teamCompetitor, symmetric opponents of teamExplorer
factCompetitor = factExplorer
{ fname = "Indigo Researcher"
, ffreq = [(COMPETITOR_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamCompetitor
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
factCompetitorShort = factCompetitor
{ fname = "Indigo Founder" -- early
, ffreq = [(COMPETITOR_SHORT, 1)]
, fhiCondPoly = hiHeroShort
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
}
factCompetitorNoEscape = factCompetitor
{ ffreq = [(COMPETITOR_NO_ESCAPE, 1)]
, fcanEscape = False
, fhiCondPoly = hiHeroMedium
}
-- ** teamCivilian
factCivilian = FactionKind
{ fname = "Civilian"
, ffreq = [(CIVILIAN_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamCivilian
, fgroups = [(HERO, 100), (CIVILIAN, 100)] -- symmetric vs player
, fskillsOther = zeroSkills -- not coordinated by any leadership
, fcanEscape = False
, fneverEmpty = True
, fhiCondPoly = hiHeroMedium
, fhasGender = True
, finitDoctrine = TPatrol
, fspawnsFast = False
, fhasPointman = False -- unorganized
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
-- ** teamConvict, different demographics
factConvict = factCivilian
{ fname = "Hunam Convict"
, ffreq = [(CONVICT_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamConvict
, fhasPointman = True -- convicts organize better
, finitUnderAI = True
, fenemyTeams = [teamMonster, teamAnimal, teamHorror]
, falliedTeams = []
}
-- ** teamMonster
factMonster = FactionKind
{ fname = "Monster Hive"
, ffreq = [(MONSTER_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamMonster
, fgroups = [ (MONSTER, 100)
, (MOBILE_MONSTER, 1) ]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = hiDweller
, fhasGender = False
, finitDoctrine = TExplore
, fspawnsFast = True
, fhasPointman = True
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = [teamAnimal]
}
-- This has continuity @teamMonster@, despite being playable.
factMonsterAnti = factMonster
{ ffreq = [(MONSTER_ANTI, 1)]
, fhasUI = True
, finitUnderAI = False
}
factMonsterAntiCaptive = factMonsterAnti
{ ffreq = [(MONSTER_ANTI_CAPTIVE, 1)]
, fneverEmpty = True
}
factMonsterAntiPacifist = factMonsterAntiCaptive
{ ffreq = [(MONSTER_ANTI_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
-- More flavour and special backstory, but the same team.
factMonsterTourist = factMonsterAnti
{ fname = "Monster Tourist Office"
, ffreq = [(MONSTER_TOURIST, 1)]
, fcanEscape = True
, fneverEmpty = True -- no spawning
, fhiCondPoly = hiHeroMedium
, finitDoctrine = TFollow -- follow-the-guide, as tourists do
, fspawnsFast = False -- on a trip, so no spawning
, finitUnderAI = False
, fenemyTeams =
[teamAnimal, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factMonsterTouristPassive = factMonsterTourist
{ ffreq = [(MONSTER_TOURIST_PASSIVE, 1)]
, fhasUI = False
, finitUnderAI = True
}
factMonsterCaptive = factMonster
{ ffreq = [(MONSTER_CAPTIVE, 1)]
, fneverEmpty = True
}
factMonsterCaptiveNarrating = factMonsterAntiCaptive
{ ffreq = [(MONSTER_CAPTIVE_NARRATING, 1)]
, fhasUI = True
}
-- ** teamAnimal
factAnimal = FactionKind
{ fname = "Animal Kingdom"
, ffreq = [(ANIMAL_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamAnimal
, fgroups = [ (ANIMAL, 100), (INSECT, 100), (GEOPHENOMENON, 100)
-- only the distinct enough ones
, (MOBILE_ANIMAL, 1), (IMMOBILE_ANIMAL, 1), (SCAVENGER, 1) ]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = hiDweller
, fhasGender = False
, finitDoctrine = TRoam -- can't pick up, so no point exploring
, fspawnsFast = True
, fhasPointman = False
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = [teamMonster]
}
-- These two differ from outside, but share information and boasting
-- about them tends to be general, too.
factAnimalMagnificent = factAnimal
{ fname = "Animal Magnificent Specimen Variety"
, ffreq = [(ANIMAL_MAGNIFICENT, 1)]
, fneverEmpty = True
, fenemyTeams =
[teamMonster, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factAnimalExquisite = factAnimal
{ fname = "Animal Exquisite Herds and Packs Galore"
, ffreq = [(ANIMAL_EXQUISITE, 1)]
, fteam = teamOther
-- in the same mode as @factAnimalMagnificent@, so borrow
-- identity from horrors to avoid a clash
, fneverEmpty = True
, fenemyTeams =
[teamMonster, teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factAnimalCaptive = factAnimal
{ ffreq = [(ANIMAL_CAPTIVE, 1)]
, fneverEmpty = True
}
factAnimalNarrating = factAnimal
{ ffreq = [(ANIMAL_NARRATING, 1)]
, fhasUI = True
}
factAnimalMagnificentNarrating = factAnimalMagnificent
{ ffreq = [(ANIMAL_MAGNIFICENT_NARRATING, 1)]
, fhasPointman = True
, fhasUI = True
, finitUnderAI = False
}
factAnimalCaptiveNarrating = factAnimalCaptive
{ ffreq = [(ANIMAL_CAPTIVE_NARRATING, 1)]
, fhasUI = True
}
-- ** teamHorror, not much of a continuity intended, but can't be ignored
-- | A special faction, for summoned actors that don't belong to any
-- of the main factions of a given game. E.g., animals summoned during
-- a brawl game between two hero factions land in the horror faction.
-- In every game, either all factions for which summoning items exist
-- should be present or a horror faction should be added to host them.
factHorror = FactionKind
{ fname = "Horror Den"
, ffreq = [(HORROR_REPRESENTATIVE, 1), (REPRESENTATIVE, 1)]
, fteam = teamHorror
, fgroups = [(IK.HORROR, 100)]
, fskillsOther = zeroSkills
, fcanEscape = False
, fneverEmpty = False
, fhiCondPoly = []
, fhasGender = False
, finitDoctrine = TPatrol -- disoriented
, fspawnsFast = False
, fhasPointman = False
, fhasUI = False
, finitUnderAI = True
, fenemyTeams = [teamExplorer, teamCompetitor, teamCivilian, teamConvict]
, falliedTeams = []
}
factHorrorCaptive = factHorror
{ ffreq = [(HORROR_CAPTIVE, 1)]
, fneverEmpty = True
}
factHorrorPacifist = factHorrorCaptive
{ ffreq = [(HORROR_PACIFIST, 1)]
, fenemyTeams = []
, falliedTeams = []
}
| LambdaHack/LambdaHack | GameDefinition/Content/FactionKind.hs | bsd-3-clause | 15,238 | 63 | 9 | 2,309 | 3,066 | 1,934 | 1,132 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Test cases for Data.DHT.Type.Result module.
-- Copyright: (c) 2015 Jan Šipr, Matej Kollár; 2015-2016 Peter Trško
-- License: BSD3
--
-- Stability: stable
-- Portability: GHC specific language extensions.
--
-- Test cases for "Data.DHT.Type.Result" module.
module TestCase.Data.DHT.Type.Result (tests)
where
import Control.Exception (Exception(fromException), SomeException)
import Control.Monad (Monad((>>=), return))
import Data.Bool (Bool(False, True))
import Data.Eq (Eq)
import Data.Function (($))
import Data.Maybe (Maybe(Just, Nothing))
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import System.IO (IO)
import Text.Show (Show(show))
import Test.HUnit (Assertion, assertBool, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Data.DHT.Type.Result
( exception
, result
, wait'
)
tests :: [Test]
tests =
[ testGroup "wait'"
[ testCase "Handle received exception"
handleExceptionTest
, testCase "Receive result without handler being invoked"
handleResultTest
]
]
handleExceptionTest :: Assertion
handleExceptionTest =
exception DummyException >>= wait' handler >>= checkResult
where
handler :: SomeException -> IO Bool
handler ex = case fromException ex of
Just DummyException -> return True
Nothing -> do
assertFailure $ "Received unexpected exception: " <> show ex
return False
checkResult = assertBool
"Exception handler wasn't invoked, which it should have been."
handleResultTest :: Assertion
handleResultTest = result True >>= wait' handler >>= checkResult
where
handler :: SomeException -> IO Bool
handler _exception = return False
checkResult = assertBool
"Exception handler was invoked, which it wasn't supposed to."
data DummyException = DummyException
deriving (Eq, Show, Typeable)
instance Exception DummyException
| FPBrno/dht-api | test/TestCase/Data/DHT/Type/Result.hs | bsd-3-clause | 2,153 | 0 | 13 | 449 | 443 | 259 | 184 | 48 | 2 |
{-# LANGUAGE CPP #-}
module Main where
import System.Posix.Internals (c_read, c_open, c_close, c_write, o_RDWR, o_CREAT, o_NONBLOCK)
import Foreign.C.String
import Foreign.Marshal.Alloc
import Control.Monad
import Control.Concurrent.Async (forConcurrently_)
import System.Environment
import Data.Bits
#if defined(mingw32_HOST_OS)
import Foreign.Ptr (castPtr)
#endif
main :: IO ()
main = do
[file] <- getArgs
forConcurrently_ [0..100] $ \ i -> do
let file' = file ++ "-" ++ show i
withCString file $ \ fp -> do
withCString file' $ \ fp' -> do
#if defined(mingw32_HOST_OS)
fd <- c_open (castPtr fp) (o_RDWR .|. o_NONBLOCK) 0o666
fd' <- c_open (castPtr fp') (o_CREAT .|. o_RDWR .|. o_NONBLOCK) 0o666
#else
fd <- c_open fp (o_RDWR .|. o_NONBLOCK) 0o666
fd' <- c_open fp' (o_CREAT .|. o_RDWR .|. o_NONBLOCK) 0o666
#endif
loop fd fd'
c_close fd
c_close fd'
where
loop fd fd' = do
ptr <- mallocBytes 32750
siz <- c_read fd ptr 32750
loopWrite fd' ptr (fromIntegral siz)
free ptr
case siz `compare` 0 of
LT -> error ("error:" ++ show siz)
EQ -> return ()
GT -> loop fd fd'
loopWrite fd ptr n = do
siz <- fromIntegral `fmap` c_write fd ptr n
case siz `compare` n of
LT -> loopWrite fd ptr (n - siz)
EQ -> return ()
GT -> error ("over write:" ++ show siz)
| winterland1989/stdio | bench/diskIO/UnSafeFFI.hs | bsd-3-clause | 1,537 | 0 | 23 | 498 | 467 | 237 | 230 | 36 | 5 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
-- NonZero4aryRandomAccessList
module PFDS.Sec9.Ex18 where
import Data.Vector (Vector, (!?), (//))
import qualified Data.Vector as V
import PFDS.Commons.RandomAccessList
import Prelude hiding (head, tail, lookup)
data Tree a = Leaf a | Node (Vector (Tree a))
-- ^^^^^^ 4 trees
type RList a = [Vector (Tree a)]
-- ^^^^^^ 1 ~ 4 trees
type instance Elem (RList a) = a
instance RandomAccessList (RList a) where
empty :: RList a
empty = []
isEmpty :: RList a -> Bool
isEmpty = null
cons :: a -> RList a -> RList a
cons x vs = consTree (Leaf x) vs
head :: RList a -> a -- raise Empty
head vs = let (Leaf x, _) = unconsTree vs in x
tail :: RList a -> RList a -- raise Empty
tail vs = let (_, vs') = unconsTree vs in vs'
lookup :: Int -> RList a -> a -- raise Subscript
lookup i vs = lookupList i 1 vs
update :: Int -> a -> RList a -> RList a -- raise Subscript
update i y vs = updateList i 1 y vs
-- helper
consTree :: Tree a -> RList a -> RList a
consTree t [] = [V.singleton t]
consTree t (v : vs) = if V.length v < 4
then V.cons t v : vs
else V.singleton t : consTree (Node v) vs
unconsTree :: RList a -> (Tree a, RList a)
unconsTree [] = error "Empty"
unconsTree [v] | V.length v == 1 = (V.head v, [])
unconsTree (v : vs) = if V.length v > 1
then (V.head v, V.tail v : vs)
else let (Node v', vs') = unconsTree vs in (V.head v, V.tail v : vs')
lookupList :: Int -> Int -> RList a -> a
lookupList i w [] = error "Subscript"
lookupList i w (v : vs) = if i <= w * V.length v
then lookupVector i w v
else lookupList (i - w * V.length v) (w * 4) vs
lookupVector :: Int -> Int -> Vector (Tree a) -> a
lookupVector i w v = let j = i `div` w in case v !? j of
Nothing -> error "Subscript"
Just (Leaf x) -> x
Just (Node v') -> lookupVector (i - j) (w `div` 4) v'
updateList :: Int -> Int -> a -> RList a -> RList a
updateList i w y [] = error "Subscript"
updateList i w y (v : vs) = if i <= w * V.length v
then updateVector i w y v : vs
else v : updateList (i - w * V.length v) (w * 4) y vs
updateVector :: Int -> Int -> a -> Vector (Tree a) -> Vector (Tree a)
updateVector i w y v = let j = i `div` w in case v !? j of
Nothing -> error "Subscript"
Just (Leaf _) -> v // [(j, Leaf y)]
Just (Node v') -> updateVector (i - j) (w `div` 4) y v'
| matonix/pfds | src/PFDS/Sec9/Ex18.hs | bsd-3-clause | 2,474 | 0 | 13 | 625 | 1,194 | 613 | 581 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module :
-- Copyright : (c) 2012 Boyun Tang
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
--
--
-----------------------------------------------------------------------------
module Bio.Sequence.GB.Types
where
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (unpack,append)
import qualified Data.ByteString.Char8 as B8
import Data.Char (isDigit,toLower)
import Data.List (intercalate)
import Data.List.Split (splitEvery)
import Data.Maybe (fromMaybe)
import Text.Printf (printf)
getDEFINITION :: GBRecord -> ByteString
getDEFINITION = definitionToBS . definition
getACCESSION :: GBRecord -> ByteString
getACCESSION = accessionToBS . accession
getKEYWORDS :: GBRecord -> ByteString
getKEYWORDS = keywordsToBS . keywords
getSOURCE :: GBRecord -> ORGANISM
getSOURCE = sourceToOG . source
data GBRecord = GB {
locus :: LOCUS
,definition :: DEFINITION
,accession :: ACCESSION
,version :: VERSION
,dblink :: Maybe DBLINK
,keywords :: KEYWORDS
,segment :: Maybe SEGMENT
,source :: SOURCE
,references :: Maybe [REFERENCE] -- e.g. NM_053042 has no reference
,comment :: Maybe COMMENT
,features :: [FEATURE]
,origin :: ORIGIN
}
data GeneBankDivision = PRI -- ^ primate sequences
| ROD -- ^ rodent sequences
| MAM -- ^ other mammalian sequences
| VRT -- ^ other vertebrate sequences
| INV -- ^ invertebrate sequences
| PLN -- ^ plant, fungal, and algal sequences
| BCT -- ^ bacterial sequences
| VRL -- ^ viral sequences
| PHG -- ^ bacteriophage sequences
| SYN -- ^ synthetic sequences
| UNA -- ^ unannotated sequences
| EST -- ^ EST sequences (expressed sequence tags)
| PAT -- ^ patent sequences
| STS -- ^ STS sequences (sequence tagged sites)
| GSS -- ^ GSS sequences (genome survey sequences)
| HTG -- ^ HTG sequences (high-throughput genomic sequences)
| HTC -- ^ unfinished high-throughput cDNA sequencing
| ENV -- ^ environmental sampling sequences
deriving (Show,Read)
data MoleculeType = MoleculeType {
molType :: !ByteString
,topo :: !(Maybe Topology)
}
data Topology = Linear
| Circular
deriving (Show,Read)
-- data Polymer = DNA
-- | RNA
-- | PRO
-- deriving (Show,Eq,Read)
data LOCUS = LOCUS {
locusName :: !ByteString
,sequenceLength :: {-# UNPACK #-} !Int
,moleculeType :: !MoleculeType
,geneBankDivision :: !GeneBankDivision
,modificationDate :: !ByteString
}
data VERSION = VERSION ByteString !GI
type Genus = ByteString
type Species = ByteString
data ORGANISM = ORGANISM !Genus !Species
data DBLINK = Project !ByteString
| BioProject !ByteString
data REFERENCE = REFERENCE {
author :: !(Maybe ByteString)
,consortium :: !(Maybe ByteString)
,title :: !(Maybe ByteString)
,journal :: !ByteString
,pubmed :: !(Maybe ByteString)
,remark :: !(Maybe ByteString)
}
data FEATURE = FEATURE {
feature :: !ByteString
,locationDescriptor :: !ByteString
,values :: ![(ByteString,ByteString)]
}
newtype SEGMENT = SEGMENT {
segmentToBS :: ByteString
}
newtype CONTIG = CONTIG {
contigToBS :: ByteString
}
newtype ORIGIN = ORIGIN {
originToBS :: ByteString
}
newtype DEFINITION = DEFINITION {
definitionToBS :: ByteString
}
newtype ACCESSION = ACCESSION {
accessionToBS :: ByteString
}
newtype GI = GI {
giToBS :: ByteString
}
newtype KEYWORDS = KEYWORDS {
keywordsToBS :: ByteString
}
newtype SOURCE = SOURCE {
sourceToOG :: ORGANISM
}
newtype COMMENT = COMMENT {
commentToBS :: ByteString
}
instance Show LOCUS where
show (LOCUS name len mole gbd date) =
"LOCUS" ++ "\t" ++
unpack name ++ "\t" ++
show len ++
" " ++ locusStr ++ "\t" ++
show gbd ++
"\t" ++ unpack date
where
locusStr = case mole of
MoleculeType poly (Just str) ->
let unit =
if "NP_" `B8.isPrefixOf` name
then "aa"
else "bp"
in unit ++ "\t" ++ unpack poly ++ "\t" ++ (map toLower $ show str)
MoleculeType poly _ ->
let unit =
if "NP_" `B8.isPrefixOf` name
then "aa"
else "bp"
in unit ++ "\t" ++ unpack poly
instance Show DEFINITION where
show (DEFINITION str) = "DEFINITION\t" ++ unpack str
instance Show ACCESSION where
show (ACCESSION str) = "ACCESSION\t" ++ unpack str
instance Show VERSION where
show (VERSION str1 (GI str2)) = "VERSION\t" ++ unpack str1 ++
"\t" ++ unpack str2
instance Show DBLINK where
show dbl =
case dbl of
Project str -> "DBLINK\t" ++ "Project: " ++ unpack str
BioProject str -> "DBLINK\t" ++ "BioProject: " ++ unpack str
instance Show KEYWORDS where
show (KEYWORDS str) = "KEYWORDS\t" ++ unpack str
instance Show SEGMENT where
show (SEGMENT str) = "SEGMENT\t" ++ unpack str
instance Show SOURCE where
show (SOURCE (ORGANISM str1 str2)) = "SOURCE\n " ++ "ORGANISM\t" ++
unpack str1 ++ " " ++ unpack str2
instance Show REFERENCE where
show art =
unpack $
B8.intercalate "\n" $
filter (not . B8.null) $
map (fromMaybe "") $
zipWith ($)
[fmap (s2 `append` "AUTHORS\t" `append`) . author
,fmap (s2 `append` "CONSRTM\t" `append`) . consortium
,fmap (s2 `append` "TITLE\t" `append`) . title
,fmap (s2 `append` "JOURNAL\t" `append`) . Just . journal
,fmap (s3 `append` "PUBMED\t" `append`) . pubmed
,fmap (s2 `append` "REMARK\t" `append`) . remark] $
repeat art
where
s2 = " "
s3 = " "
instance Show COMMENT where
show (COMMENT str) = "COMMENT\t" ++ unpack str
instance Show FEATURE where
show (FEATURE na loc ps) =
myShow na loc ps
where
myShow str l vs = s5 ++ unpack str ++ "\t" ++ unpack l ++ "\n" ++ showPS vs
s5 = replicate 5 ' '
showPS ss =
B8.unpack $ B8.intercalate "\n" $
map (\(k,v) ->
let v' = if (all isDigit $ unpack v) || (k == "number") || (k == "citation")
then v
else '"' `B8.cons` v `B8.snoc` '"'
s21 = B8.pack (replicate 21 ' ') `B8.snoc` '/'
in if k /= "translation"
then s21 `B8.append` k `B8.snoc` '=' `B8.append` v'
else let (vh,vt) = B8.splitAt 45 v'
s' = '\n' `B8.cons` B8.pack (replicate 21 ' ')
vS = B8.intercalate s' $
vh:map B8.pack (splitEvery 58 $ B8.unpack vt)
in s21 `B8.append` k `B8.snoc` '=' `B8.append` vS
) ss
instance Show ORIGIN where
show (ORIGIN str) = "ORIGIN" ++ "\n" ++
intercalate "\n"
(map (\(i,s) ->
printf "%10d" (i * 60 + 1) ++ " " ++ s) $
zip ([0..]::[Int]) $ map unwords $
splitEvery 6 $ splitEvery 10 (unpack str)) ++ "\n//"
instance Show GBRecord where
show gb =
intercalate "\n" $
filter (not . null) $
map (fromMaybe "") $
zipWith ($)
[fmap show . Just . locus
,fmap show . Just . definition
,fmap show . Just . accession
,fmap show . Just . version
,fmap show . dblink
,fmap show . Just . keywords
,fmap show . segment
,fmap show . Just . source
,fmap
(intercalate "\n" . map
(\(i,r) ->
"REFERENCE\t" ++ show i ++ "\n" ++ show r
) . zip ([1..]::[Int])) . references
,fmap show . comment
,fmap (("FEATURES\tLocation/Qualifiers\n" ++) .
intercalate "\n" . map show) . Just . features
,fmap show . Just . origin] $
repeat gb
| tangboyun/bio-seq-gb | Bio/Sequence/GB/Types.hs | bsd-3-clause | 8,871 | 1 | 26 | 3,211 | 2,306 | 1,270 | 1,036 | 246 | 1 |
{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-}
module IRTS.Compiler where
import IRTS.Lang
import IRTS.Defunctionalise
import IRTS.Simplified
import IRTS.CodegenCommon
import IRTS.CodegenC
import IRTS.CodegenJava
import IRTS.DumpBC
import IRTS.CodegenJavaScript
#ifdef IDRIS_LLVM
import IRTS.CodegenLLVM
#else
import Util.LLVMStubs
#endif
import IRTS.Inliner
import Idris.AbsSyntax
import Idris.UnusedArgs
import Idris.Error
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Core.CaseTree
import Control.Monad.State
import Data.List
import System.Process
import System.IO
import System.Directory
import System.Environment
import System.FilePath ((</>), addTrailingPathSeparator)
import Paths_idris
compile :: Codegen -> FilePath -> Term -> Idris ()
compile codegen f tm
= do checkMVs
let tmnames = namesUsed (STerm tm)
usedIn <- mapM (allNames []) tmnames
let used = [sUN "prim__subBigInt", sUN "prim__addBigInt"] : usedIn
defsIn <- mkDecls tm (concat used)
findUnusedArgs (concat used)
maindef <- irMain tm
objs <- getObjectFiles codegen
libs <- getLibs codegen
flags <- getFlags codegen
hdrs <- getHdrs codegen
impdirs <- allImportDirs
let defs = defsIn ++ [(sMN 0 "runMain", maindef)]
-- iputStrLn $ showSep "\n" (map show defs)
let (nexttag, tagged) = addTags 65536 (liftAll defs)
let ctxtIn = addAlist tagged emptyContext
iLOG "Defunctionalising"
let defuns_in = defunctionalise nexttag ctxtIn
logLvl 5 $ show defuns_in
iLOG "Inlining"
let defuns = inline defuns_in
logLvl 5 $ show defuns
iLOG "Resolving variables for CG"
-- iputStrLn $ showSep "\n" (map show (toAlist defuns))
let checked = checkDefs defuns (toAlist defuns)
outty <- outputTy
dumpCases <- getDumpCases
dumpDefun <- getDumpDefun
case dumpCases of
Nothing -> return ()
Just f -> runIO $ writeFile f (showCaseTrees defs)
case dumpDefun of
Nothing -> return ()
Just f -> runIO $ writeFile f (dumpDefuns defuns)
triple <- targetTriple
cpu <- targetCPU
optimize <- optLevel
iLOG "Building output"
case checked of
OK c -> runIO $ case codegen of
ViaC ->
codegenC c f outty hdrs
(concatMap mkObj objs)
(concatMap mkLib libs)
(concatMap mkFlag flags ++
concatMap incdir impdirs) NONE
ViaJava ->
codegenJava [] c f hdrs libs outty
ViaJavaScript ->
codegenJavaScript JavaScript c f outty
ViaNode ->
codegenJavaScript Node c f outty
ViaLLVM -> codegenLLVM c triple cpu optimize f outty
Bytecode -> dumpBC c f
Error e -> ierror e
where checkMVs = do i <- getIState
case map fst (idris_metavars i) \\ primDefs of
[] -> return ()
ms -> ifail $ "There are undefined metavariables: " ++ show ms
inDir d h = do let f = d </> h
ex <- doesFileExist f
if ex then return f else return h
mkObj f = f ++ " "
mkLib l = "-l" ++ l ++ " "
mkFlag l = l ++ " "
incdir i = "-I" ++ i ++ " "
irMain :: TT Name -> Idris LDecl
irMain tm = do i <- ir tm
return $ LFun [] (sMN 0 "runMain") [] (LForce i)
mkDecls :: Term -> [Name] -> Idris [(Name, LDecl)]
mkDecls t used
= do i <- getIState
let ds = filter (\ (n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i)
mapM traceUnused used
decls <- mapM build ds
return decls
showCaseTrees :: [(Name, LDecl)] -> String
showCaseTrees ds = showSep "\n\n" (map showCT ds)
where
showCT (n, LFun _ f args lexp)
= show n ++ " " ++ showSep " " (map show args) ++ " =\n\t "
++ show lexp
showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a
isCon (TyDecl _ _) = True
isCon _ = False
class ToIR a where
ir :: a -> Idris LExp
build :: (Name, Def) -> Idris (Name, LDecl)
build (n, d)
= do i <- getIState
case lookup n (idris_scprims i) of
Just (ar, op) ->
let args = map (\x -> sMN x "op") [0..] in
return (n, (LFun [] n (take ar args)
(LOp op (map (LV . Glob) (take ar args)))))
_ -> do def <- mkLDecl n d
logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def
return (n, def)
getPrim :: IState -> Name -> [LExp] -> Maybe LExp
getPrim i n args = case lookup n (idris_scprims i) of
Just (ar, op) ->
if (ar == length args)
then return (LOp op args)
else Nothing
_ -> Nothing
declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x
declArgs args inl n x = LFun (if inl then [Inline] else []) n args x
mkLDecl n (Function tm _) = do e <- ir tm
return (declArgs [] True n e)
mkLDecl n (CaseOp ci _ _ _ pats cd)
= let (args, sc) = cases_runtime cd in
do e <- ir (args, sc)
return (declArgs [] (case_inlinable ci) n e)
mkLDecl n (TyDecl (DCon t a) _) = return $ LConstructor n t a
mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a
mkLDecl n _ = return (LFun [] n [] (LError ("Impossible declaration " ++ show n)))
instance ToIR (TT Name) where
ir tm = ir' [] tm where
ir' env tm@(App f a)
| (P _ (UN m) _, args) <- unApply tm,
m == txt "mkForeignPrim"
= doForeign env args
| (P _ (UN u) _, [_, arg]) <- unApply tm,
u == txt "unsafePerformPrimIO"
= ir' env arg
-- TMP HACK - until we get inlining.
| (P _ (UN r) _, [_, _, _, _, _, arg]) <- unApply tm,
r == txt "replace"
= ir' env arg
| (P _ (UN l) _, [_, arg]) <- unApply tm,
l == txt "lazy"
= do arg' <- ir' env arg
return $ LLazyExp arg'
| (P _ (UN a) _, [_, _, _, arg]) <- unApply tm,
a == txt "assert_smaller"
= ir' env arg
| (P _ (UN p) _, [_, arg]) <- unApply tm,
p == txt "par"
= do arg' <- ir' env arg
return $ LOp LPar [LLazyExp arg']
| (P _ (UN pf) _, [arg]) <- unApply tm,
pf == txt "prim_fork"
= do arg' <- ir' env arg
return $ LOp LFork [LLazyExp arg']
| (P _ (UN m) _, [_,size,t]) <- unApply tm,
m == txt "malloc"
= do size' <- ir' env size
t' <- ir' env t
return t' -- TODO $ malloc_ size' t'
| (P _ (UN tm) _, [_,t]) <- unApply tm,
tm == txt "trace_malloc"
= do t' <- ir' env t
return t' -- TODO
-- | (P _ (NS (UN "S") ["Nat", "Prelude"]) _, [k]) <- unApply tm
-- = do k' <- ir' env k
-- return (LOp LBPlus [k', LConst (BI 1)])
| (P (DCon t a) n _, args) <- unApply tm
= irCon env t a n args
| (P (TCon t a) n _, args) <- unApply tm
= return LNothing
| (P _ n _, args) <- unApply tm
= do i <- getIState
args' <- mapM (ir' env) args
case getPrim i n args' of
Just tm -> return tm
_ -> do
let collapse
= case lookupCtxtExact n
(idris_optimisation i) of
Just oi -> collapsible oi
_ -> False
let unused
= case lookupCtxtExact n
(idris_callgraph i) of
Just (CGInfo _ _ _ _ unusedpos) ->
unusedpos
_ -> []
if collapse
then return LNothing
else return (LApp False (LV (Glob n))
(mkUnused unused 0 args'))
| (f, args) <- unApply tm
= do f' <- ir' env f
args' <- mapM (ir' env) args
return (LApp False f' args')
where mkUnused u i [] = []
mkUnused u i (x : xs) | i `elem` u = LNothing : mkUnused u (i + 1) xs
| otherwise = x : mkUnused u (i + 1) xs
-- ir' env (P _ (NS (UN "Z") ["Nat", "Prelude"]) _)
-- = return $ LConst (BI 0)
ir' env (P _ n _) = return $ LV (Glob n)
ir' env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i))
| otherwise = ifail $ "IR fail " ++ show i ++ " " ++ show tm
ir' env (Bind n (Lam _) sc)
= do let n' = uniqueName n env
sc' <- ir' (n' : env) sc
return $ LLam [n'] sc'
ir' env (Bind n (Let _ v) sc)
= do sc' <- ir' (n : env) sc
v' <- ir' env v
return $ LLet n v' sc'
ir' env (Bind _ _ _) = return $ LNothing
ir' env (Proj t i) | i == -1
= do t' <- ir' env t
return $ LOp (LMinus (ATInt ITBig))
[t', LConst (BI 1)]
ir' env (Proj t i) = do t' <- ir' env t
return $ LProj t' i
ir' env (Constant c) = return $ LConst c
ir' env (TType _) = return $ LNothing
ir' env Erased = return $ LNothing
ir' env Impossible = return $ LNothing
-- ir' env _ = return $ LError "Impossible"
irCon env t arity n args
| length args == arity = buildApp env (LV (Glob n)) args
| otherwise = let extra = satArgs (arity - length args) in
do sc' <- irCon env t arity n
(args ++ map (\n -> P Bound n undefined) extra)
return $ LLam extra sc'
satArgs n = map (\i -> sMN i "sat") [1..n]
buildApp env e [] = return e
buildApp env e xs = do xs' <- mapM (ir' env) xs
return $ LApp False e xs'
doForeign :: [Name] -> [TT Name] -> Idris LExp
doForeign env (_ : fgn : args)
| (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn
= let maybeTys = getFTypes fgnArgTys
rty = mkIty' ret in
case maybeTys of
Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args)
Just tys -> do
args' <- mapM (ir' env) (init args)
-- wrap it in a prim__IO
-- return $ con_ 0 @@ impossible @@
return $ -- LLazyExp $
LForeign LANG_C rty fgnName (zip tys args')
| otherwise = ifail "Badly formed foreign function call"
getFTypes :: TT Name -> Maybe [FType]
getFTypes tm = case unApply tm of
(nil, []) -> Just []
(cons, [ty, xs]) ->
fmap (mkIty' ty :) (getFTypes xs)
_ -> Nothing
mkIty' (P _ (UN ty) _) = mkIty (str ty)
mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _))
| fi == txt "FIntT" = mkIntIty (str intTy)
mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _)))
| ff == txt "FFunction" && fa == txt "FAny" &&
io == txt "IO"
= FFunctionIO
mkIty' (App (App (P _ (UN ff) _) _) _)
| ff == txt "FFunction" = FFunction
mkIty' _ = FAny
-- would be better if these FInt types were evaluated at compile time
-- TODO: add %eval directive for such things
mkIty "FFloat" = FArith ATFloat
mkIty "FInt" = mkIntIty "ITNative"
mkIty "FChar" = mkIntIty "ITChar"
mkIty "FByte" = mkIntIty "IT8"
mkIty "FShort" = mkIntIty "IT16"
mkIty "FLong" = mkIntIty "IT64"
mkIty "FBits8" = mkIntIty "IT8"
mkIty "FBits16" = mkIntIty "IT16"
mkIty "FBits32" = mkIntIty "IT32"
mkIty "FBits64" = mkIntIty "IT64"
mkIty "FString" = FString
mkIty "FPtr" = FPtr
mkIty "FUnit" = FUnit
mkIty "FFunction" = FFunction
mkIty "FFunctionIO" = FFunctionIO
mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16))
mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8))
mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4))
mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2))
mkIty x = error $ "Unknown type " ++ x
mkIntIty "ITNative" = FArith (ATInt ITNative)
mkIntIty "ITChar" = FArith (ATInt ITChar)
mkIntIty "IT8" = FArith (ATInt (ITFixed IT8))
mkIntIty "IT16" = FArith (ATInt (ITFixed IT16))
mkIntIty "IT32" = FArith (ATInt (ITFixed IT32))
mkIntIty "IT64" = FArith (ATInt (ITFixed IT64))
zname = sNS (sUN "Z") ["Nat","Prelude"]
sname = sNS (sUN "S") ["Nat","Prelude"]
instance ToIR ([Name], SC) where
ir (args, tree) = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree
tree' <- ir tree
return $ LLam args tree'
instance ToIR SC where
ir t = ir' t where
ir' (STerm t) = ir t
ir' (UnmatchedCase str) = return $ LError str
ir' (ProjCase tm alts) = do tm' <- ir tm
alts' <- mapM (mkIRAlt tm') alts
return $ LCase tm' alts'
ir' (Case n alts) = do alts' <- mapM (mkIRAlt (LV (Glob n))) alts
return $ LCase (LV (Glob n)) alts'
ir' ImpossibleCase = return LNothing
-- special cases for Z and S
-- Needs rethink: projections make this fail
-- mkIRAlt n (ConCase z _ [] rhs) | z == zname
-- = mkIRAlt n (ConstCase (BI 0) rhs)
-- mkIRAlt n (ConCase s _ [arg] rhs) | s == sname
-- = do n' <- ir n
-- rhs' <- ir rhs
-- return $ LDefaultCase
-- (LLet arg (LOp LBMinus [n', LConst (BI 1)])
-- rhs')
mkIRAlt _ (ConCase n t args rhs)
= do rhs' <- ir rhs
return $ LConCase (-1) n args rhs'
mkIRAlt _ (ConstCase x rhs)
| matchable x
= do rhs' <- ir rhs
return $ LConstCase x rhs'
| matchableTy x
= do rhs' <- ir rhs
return $ LDefaultCase rhs'
mkIRAlt tm (SucCase n rhs)
= do rhs' <- ir rhs
return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig))
[tm,
LConst (BI 1)]) rhs')
-- return $ LSucCase n rhs'
mkIRAlt _ (ConstCase c rhs)
= ifail $ "Can't match on (" ++ show c ++ ")"
mkIRAlt _ (DefaultCase rhs)
= do rhs' <- ir rhs
return $ LDefaultCase rhs'
matchable (I _) = True
matchable (BI _) = True
matchable (Ch _) = True
matchable (Str _) = True
matchable _ = False
matchableTy (AType (ATInt ITNative)) = True
matchableTy (AType (ATInt ITBig)) = True
matchableTy (AType (ATInt ITChar)) = True
matchableTy StrType = True
matchableTy (AType (ATInt (ITFixed IT8))) = True
matchableTy (AType (ATInt (ITFixed IT16))) = True
matchableTy (AType (ATInt (ITFixed IT32))) = True
matchableTy (AType (ATInt (ITFixed IT64))) = True
matchableTy _ = False
| ctford/Idris-Elba-dev | src/IRTS/Compiler.hs | bsd-3-clause | 16,544 | 0 | 24 | 6,979 | 5,743 | 2,779 | 2,964 | 345 | 11 |
{-# LANGUAGE OverloadedStrings #-}
import EditRope
import Criterion.Main
import TestHelper
main :: IO ()
main = do
let toTest = renderTokensForLine attrMap
defaultMain [
bgroup "renderTokensForLine" [
bench "original line" $ whnf (toTest []) lineABC
, bench "lineABC" $ whnf (toTest tokensLineABC) lineABC
, bench "lineABC_123" $ whnf (toTest tokensLineABC_123) lineABC_123
, bench "lineABC_123_rev" $ whnf (toTest tokensLineABC_123_rev) lineABC_123
]
] | clojj/hsedit | test/Criterion.hs | bsd-3-clause | 568 | 1 | 16 | 175 | 144 | 68 | 76 | 13 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Numeric.Natural.QuickCheck where
import Numeric.Natural
import Test.QuickCheck (Arbitrary, arbitrary, CoArbitrary, coarbitrary, suchThat, variant)
import Control.Applicative ((<$>))
instance Arbitrary Natural where
arbitrary = fromInteger <$> (arbitrary `suchThat` (0 <=))
instance CoArbitrary Natural where
coarbitrary = variant
| kmyk/proof-haskell | Numeric/Natural/QuickCheck.hs | mit | 386 | 0 | 9 | 50 | 93 | 58 | 35 | 9 | 0 |
module API.RequestSpec (spec) where
import Universum
import Data.Either (isLeft)
import Formatting (build, sformat)
import Test.Hspec
import Cardano.Wallet.API.Request.Filter
import Cardano.Wallet.API.Request.Sort
import Cardano.Wallet.API.V1.Types
import qualified Pos.Core as Core
spec :: Spec
spec = describe "Request" $ do
describe "Sort" sortSpec
describe "Filter" filterSpec
sortSpec :: Spec
sortSpec =
describe "parseSortOperation" $ do
describe "Transaction" $ do
let ptimestamp = Proxy @(V1 Core.Timestamp)
pt = Proxy @Transaction
it "knows the query param" $ do
parseSortOperation pt ptimestamp "ASC[created_at]"
`shouldBe`
Right (SortByIndex SortAscending ptimestamp)
it "infers DESC for nonspecified sort" $
parseSortOperation pt ptimestamp "created_at"
`shouldBe`
Right (SortByIndex SortDescending ptimestamp)
it "fails if the param name is wrong" $ do
parseSortOperation pt ptimestamp "ASC[balance]"
`shouldSatisfy`
isLeft
it "fails if the syntax is wrong" $ do
parseSortOperation pt ptimestamp "ASC[created_at"
`shouldSatisfy`
isLeft
filterSpec :: Spec
filterSpec = do
describe "parseFilterOperation" $ do
describe "Wallet" $ do
let pw = Proxy @Wallet
pwid = Proxy @WalletId
pcoin = Proxy @Core.Coin
it "supports index" $ do
parseFilterOperation pw pwid "asdf"
`shouldBe`
Right (FilterByIndex (WalletId "asdf"))
forM_ [minBound .. maxBound] $ \p ->
it ("supports predicate: " <> show p) $ do
parseFilterOperation pw pwid
(sformat build p <> "[asdf]")
`shouldBe`
Right (FilterByPredicate p (WalletId "asdf"))
it "supports range" $ do
parseFilterOperation pw pcoin "RANGE[123,456]"
`shouldBe`
Right
(FilterByRange (Core.mkCoin 123)
(Core.mkCoin 456))
it "fails if the thing can't be parsed" $ do
parseFilterOperation pw pcoin "nope"
`shouldSatisfy`
isLeft
it "supports IN" $ do
parseFilterOperation pw pcoin "IN[1,2,3]"
`shouldBe`
Right
(FilterIn (map Core.mkCoin [1,2,3]))
describe "toQueryString" $ do
let ops = FilterByRange (Core.mkCoin 2345) (Core.mkCoin 2348)
`FilterOp` FilterByIndex (WalletId "hello")
`FilterOp` NoFilters
:: FilterOperations '[Core.Coin, WalletId] Wallet
it "does what you'd want it to do" $ do
toQueryString ops
`shouldBe`
[ ("balance", Just "RANGE[2345,2348]")
, ("id", Just "hello")
]
describe "toFilterOperations" $ do
let params :: [(Text, Maybe Text)]
params =
[ ("id", Just "3")
, ("balance", Just "RANGE[10,50]")
]
fops :: FilterOperations '[WalletId, Core.Coin] Wallet
fops = FilterByIndex (WalletId "3")
`FilterOp` FilterByRange (Core.mkCoin 10) (Core.mkCoin 50)
`FilterOp` NoFilters
prxy :: Proxy '[WalletId, Core.Coin]
prxy = Proxy
it "can parse the thing" $ do
toFilterOperations params prxy
`shouldBe`
fops
| input-output-hk/pos-haskell-prototype | wallet/test/unit/API/RequestSpec.hs | mit | 4,025 | 0 | 23 | 1,715 | 909 | 460 | 449 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Search
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Search/Replace functions
module Yi.Search (
setRegexE, -- :: SearchExp -> EditorM ()
resetRegexE, -- :: EditorM ()
getRegexE, -- :: EditorM (Maybe SearchExp)
SearchMatch,
SearchResult(..),
SearchOption(..),
doSearch, -- :: (Maybe String) -> [SearchOption]
-- -> Direction -> YiM ()
searchInit, -- :: String
-- -> [SearchOption]
-- -> IO SearchExp
continueSearch, -- :: SearchExp
-- -> IO SearchResult
makeSimpleSearch,
-- * Batch search-replace
searchReplaceRegionB,
searchReplaceSelectionB,
replaceString,
searchAndRepRegion,
searchAndRepRegion0,
searchAndRepUnit, -- :: String -> String -> Bool -> TextUnit -> EditorM Bool
-- * Incremental Search
isearchInitE,
isearchIsEmpty,
isearchAddE,
isearchPrevE,
isearchNextE,
isearchWordE,
isearchHistory,
isearchDelE,
isearchCancelE,
isearchFinishE,
isearchCancelWithE,
isearchFinishWithE,
-- * Replace
qrNext,
qrReplaceAll,
qrReplaceOne,
qrFinish
) where
import Lens.Micro.Platform ((.=))
import Control.Monad (void, when)
import Data.Binary (Binary, get, put)
import Data.Char (isAlpha, isUpper)
import Data.Default (Default, def)
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T (Text, any, break, empty, length, null, takeWhile, unpack)
import qualified Data.Text.Encoding as E (decodeUtf8, encodeUtf8)
import Data.Typeable (Typeable)
import Yi.Buffer
import Yi.Editor
import Yi.History (historyFinishGen, historyMoveGen, historyStartGen)
import Yi.Regex
import qualified Yi.Rope as R (YiString, null, toString, toText)
import Yi.Search.Internal (getRegexE, resetRegexE, setRegexE)
import Yi.String (showT)
import Yi.Types (YiVariable)
import Yi.Utils (fst3)
import Yi.Window (Window)
-- ---------------------------------------------------------------------
--
-- | Global searching. Search for regex and move point to that position.
-- @Nothing@ means reuse the last regular expression. @Just s@ means use
-- @s@ as the new regular expression. Direction of search can be
-- specified as either @Backward@ or @Forward@ (forwards in the buffer).
-- Arguments to modify the compiled regular expression can be supplied
-- as well.
--
type SearchMatch = Region
data SearchResult = PatternFound
| PatternNotFound
| SearchWrapped
deriving Eq
doSearch :: Maybe String -- ^ @Nothing@ means used previous
-- pattern, if any. Complain otherwise.
-- Use getRegexE to check for previous patterns
-> [SearchOption] -- ^ Flags to modify the compiled regex
-> Direction -- ^ @Backward@ or @Forward@
-> EditorM SearchResult
doSearch (Just re) fs d = searchInit re d fs >>= withCurrentBuffer . continueSearch
doSearch Nothing _ d = do
mre <- getRegexE
case mre of
Nothing -> fail "No previous search pattern" -- NB
Just r -> withCurrentBuffer (continueSearch (r,d))
-- | Set up a search.
searchInit :: String -> Direction -> [SearchOption] -> EditorM (SearchExp, Direction)
searchInit re d fs = do
let Right c_re = makeSearchOptsM fs re
setRegexE c_re
searchDirectionA .= d
return (c_re,d)
-- | Do a search, placing cursor at first char of pattern, if found.
-- Keymaps may implement their own regex language. How do we provide for this?
-- Also, what's happening with ^ not matching sol?
continueSearch :: (SearchExp, Direction) -> BufferM SearchResult
continueSearch (c_re, dir) = do
mp <- savingPointB $ do
moveB Character dir -- start immed. after cursor
rs <- regexB dir c_re
moveB Document (reverseDir dir) -- wrap around
ls <- regexB dir c_re
return $ listToMaybe $ fmap Right rs ++ fmap Left ls
maybe (return ()) (moveTo . regionStart . either id id) mp
return $ f mp
where
f (Just (Right _)) = PatternFound
f (Just (Left _)) = SearchWrapped
f Nothing = PatternNotFound
------------------------------------------------------------------------
-- Batch search and replace
--
-- | Search and Replace all within the current region.
-- Note the region is the final argument since we might perform
-- the same search and replace over multiple regions however we are
-- unlikely to perform several search and replaces over the same region
-- since the first such may change the bounds of the region.
searchReplaceRegionB :: R.YiString -- ^ The string to search for
-> R.YiString -- ^ The string to replace it with
-> Region -- ^ The region to perform this over
-> BufferM Int
searchReplaceRegionB from to =
searchAndRepRegion0 (makeSimpleSearch from) to True
-- | Peform a search and replace on the selection
searchReplaceSelectionB :: R.YiString -- ^ text to search for
-> R.YiString -- ^ text to replace it with
-> BufferM Int
searchReplaceSelectionB from to =
getSelectRegionB >>= searchReplaceRegionB from to
-- | Replace a string by another everywhere in the document
replaceString :: R.YiString -> R.YiString -> BufferM Int
replaceString a b = regionOfB Document >>= searchReplaceRegionB a b
------------------------------------------------------------------------
-- | Search and replace in the given region.
--
-- If the input boolean is True, then the replace is done globally,
-- otherwise only the first match is replaced. Returns the number of
-- replacements done.
searchAndRepRegion0 :: SearchExp -> R.YiString -> Bool -> Region -> BufferM Int
searchAndRepRegion0 c_re str globally region = do
mp <- (if globally then id else take 1) <$> regexRegionB c_re region -- find the regex
-- mp' is a maybe not reversed version of mp, the goal
-- is to avoid replaceRegionB to mess up the next regions.
-- So we start from the end.
let mp' = mayReverse (reverseDir $ regionDirection region) mp
mapM_ (`replaceRegionB` str) mp'
return (length mp)
searchAndRepRegion :: R.YiString -> R.YiString -> Bool -> Region -> EditorM Bool
searchAndRepRegion s str globally region = case R.null s of
False -> return False
True -> do
let c_re = makeSimpleSearch s
setRegexE c_re -- store away for later use
searchDirectionA .= Forward
withCurrentBuffer $ (/= 0) <$> searchAndRepRegion0 c_re str globally region
------------------------------------------------------------------------
-- | Search and replace in the region defined by the given unit.
-- The rest is as in 'searchAndRepRegion'.
searchAndRepUnit :: R.YiString -> R.YiString -> Bool -> TextUnit -> EditorM Bool
searchAndRepUnit re str g unit =
withCurrentBuffer (regionOfB unit) >>= searchAndRepRegion re str g
--------------------------
-- Incremental search
newtype Isearch = Isearch [(T.Text, Region, Direction)]
deriving (Typeable, Show)
instance Binary Isearch where
put (Isearch ts) = put (map3 E.encodeUtf8 ts)
get = Isearch . map3 E.decodeUtf8 <$> get
map3 :: (a -> d) -> [(a, b, c)] -> [(d, b, c)]
map3 _ [] = []
map3 f ((a, b, c):xs) = (f a, b, c) : map3 f xs
-- This contains: (string currently searched, position where we
-- searched it, direction, overlay for highlighting searched text)
-- Note that this info cannot be embedded in the Keymap state: the state
-- modification can depend on the state of the editor.
instance Default Isearch where
def = Isearch []
instance YiVariable Isearch
isearchInitE :: Direction -> EditorM ()
isearchInitE dir = do
historyStartGen iSearch
p <- withCurrentBuffer pointB
putEditorDyn (Isearch [(T.empty ,mkRegion p p, dir)])
printMsg "I-search: "
isearchIsEmpty :: EditorM Bool
isearchIsEmpty = do
Isearch s <- getEditorDyn
return . not . T.null . fst3 $ head s
isearchAddE :: T.Text -> EditorM ()
isearchAddE inc = isearchFunE (<> inc)
-- | Create a SearchExp that matches exactly its argument
makeSimpleSearch :: R.YiString -> SearchExp
makeSimpleSearch s = se
where Right se = makeSearchOptsM [QuoteRegex] (R.toString s)
makeISearch :: T.Text -> SearchExp
makeISearch s = case makeSearchOptsM opts (T.unpack s) of
Left _ -> SearchExp (T.unpack s) emptyRegex emptyRegex []
Right search -> search
where opts = QuoteRegex : if T.any isUpper s then [] else [IgnoreCase]
isearchFunE :: (T.Text -> T.Text) -> EditorM ()
isearchFunE fun = do
Isearch s <- getEditorDyn
case s of
[_] -> resetRegexE
_ -> return ()
let (previous,p0,direction) = head s
current = fun previous
srch = makeISearch current
printMsg $ "I-search: " <> current
setRegexE srch
prevPoint <- withCurrentBuffer pointB
matches <- withCurrentBuffer $ do
moveTo $ regionStart p0
when (direction == Backward) $
moveN $ T.length current
regexB direction srch
let onSuccess p = do withCurrentBuffer $ moveTo (regionEnd p)
putEditorDyn $ Isearch ((current, p, direction) : s)
case matches of
(p:_) -> onSuccess p
[] -> do matchesAfterWrap <- withCurrentBuffer $ do
case direction of
Forward -> moveTo 0
Backward -> do
bufferLength <- sizeB
moveTo bufferLength
regexB direction srch
case matchesAfterWrap of
(p:_) -> onSuccess p
[] -> do withCurrentBuffer $ moveTo prevPoint -- go back to where we were
putEditorDyn $ Isearch ((current, p0, direction) : s)
printMsg $ "Failing I-search: " <> current
isearchDelE :: EditorM ()
isearchDelE = do
Isearch s <- getEditorDyn
case s of
(_:(text,p,dir):rest) -> do
withCurrentBuffer $
moveTo $ regionEnd p
putEditorDyn $ Isearch ((text,p,dir):rest)
setRegexE $ makeISearch text
printMsg $ "I-search: " <> text
_ -> return () -- if the searched string is empty, don't try to remove chars from it.
isearchHistory :: Int -> EditorM ()
isearchHistory delta = do
Isearch ((current,_p0,_dir):_) <- getEditorDyn
h <- historyMoveGen iSearch delta (return current)
isearchFunE (const h)
isearchPrevE :: EditorM ()
isearchPrevE = isearchNext0 Backward
isearchNextE :: EditorM ()
isearchNextE = isearchNext0 Forward
isearchNext0 :: Direction -> EditorM ()
isearchNext0 newDir = do
Isearch ((current,_p0,_dir):_rest) <- getEditorDyn
if T.null current
then isearchHistory 1
else isearchNext newDir
isearchNext :: Direction -> EditorM ()
isearchNext direction = do
Isearch ((current, p0, _dir) : rest) <- getEditorDyn
withCurrentBuffer $ moveTo (regionStart p0 + startOfs)
mp <- withCurrentBuffer $
regexB direction (makeISearch current)
case mp of
[] -> do
endPoint <- withCurrentBuffer $ do
moveTo (regionEnd p0) -- revert to offset we were before.
sizeB
printMsg "isearch: end of document reached"
let wrappedOfs = case direction of
Forward -> mkRegion 0 0
Backward -> mkRegion endPoint endPoint
putEditorDyn $ Isearch ((current,wrappedOfs,direction):rest) -- prepare to wrap around.
(p:_) -> do
withCurrentBuffer $
moveTo (regionEnd p)
printMsg $ "I-search: " <> current
putEditorDyn $ Isearch ((current,p,direction):rest)
where startOfs = case direction of
Forward -> 1
Backward -> -1
isearchWordE :: EditorM ()
isearchWordE = do
-- add maximum 32 chars at a time.
text <- R.toText <$> withCurrentBuffer (pointB >>= nelemsB 32)
let (prefix, rest) = T.break isAlpha text
word = T.takeWhile isAlpha rest
isearchAddE $ prefix <> word
-- | Succesfully finish a search. Also see 'isearchFinishWithE'.
isearchFinishE :: EditorM ()
isearchFinishE = isearchEnd True
-- | Cancel a search. Also see 'isearchCancelWithE'.
isearchCancelE :: EditorM ()
isearchCancelE = isearchEnd False
-- | Wrapper over 'isearchEndWith' that passes through the action and
-- accepts the search as successful (i.e. when the user wants to stay
-- at the result).
isearchFinishWithE :: EditorM a -> EditorM ()
isearchFinishWithE act = isearchEndWith act True
-- | Wrapper over 'isearchEndWith' that passes through the action and
-- marks the search as unsuccessful (i.e. when the user wants to
-- jump back to where the search started).
isearchCancelWithE :: EditorM a -> EditorM ()
isearchCancelWithE act = isearchEndWith act False
iSearch :: T.Text
iSearch = "isearch"
-- | Editor action describing how to end finish incremental search.
-- The @act@ parameter allows us to specify an extra action to run
-- before finishing up the search. For Vim, we don't want to do
-- anything so we use 'isearchEnd' which just does nothing. For emacs,
-- we want to cancel highlighting and stay where we are.
isearchEndWith :: EditorM a -> Bool -> EditorM ()
isearchEndWith act accept = getEditorDyn >>= \case
Isearch [] -> return ()
Isearch s@((lastSearched, _, dir):_) -> do
let (_,p0,_) = last s
historyFinishGen iSearch (return lastSearched)
searchDirectionA .= dir
if accept
then do void act
printMsg "Quit"
else do resetRegexE
withCurrentBuffer $ moveTo $ regionStart p0
-- | Specialised 'isearchEndWith' to do nothing as the action.
isearchEnd :: Bool -> EditorM ()
isearchEnd = isearchEndWith (return ())
-----------------
-- Query-Replace
-- | Find the next match and select it.
-- Point is end, mark is beginning.
qrNext :: Window -> BufferRef -> SearchExp -> EditorM ()
qrNext win b what = do
mp <- withGivenBufferAndWindow win b $ regexB Forward what
case mp of
[] -> do
printMsg "String to search not found"
qrFinish
(r:_) -> withGivenBufferAndWindow win b $ setSelectRegionB r
-- | Replace all the remaining occurrences.
qrReplaceAll :: Window -> BufferRef -> SearchExp -> R.YiString -> EditorM ()
qrReplaceAll win b what replacement = do
n <- withGivenBufferAndWindow win b $ do
exchangePointAndMarkB -- so we replace the current occurence too
searchAndRepRegion0 what replacement True =<< regionOfPartB Document Forward
printMsg $ "Replaced " <> showT n <> " occurrences"
qrFinish
-- | Exit from query/replace.
qrFinish :: EditorM ()
qrFinish = do
currentRegexA .= Nothing
closeBufferAndWindowE -- the minibuffer.
-- | We replace the currently selected match and then move to the next
-- match.
qrReplaceOne :: Window -> BufferRef -> SearchExp -> R.YiString -> EditorM ()
qrReplaceOne win b reg replacement = do
qrReplaceCurrent win b replacement
qrNext win b reg
-- | This may actually be a bit more general it replaces the current
-- selection with the given replacement string in the given window and
-- buffer.
qrReplaceCurrent :: Window -> BufferRef -> R.YiString -> EditorM ()
qrReplaceCurrent win b replacement =
withGivenBufferAndWindow win b $
flip replaceRegionB replacement =<< getRawestSelectRegionB
| siddhanathan/yi | yi-core/src/Yi/Search.hs | gpl-2.0 | 16,120 | 0 | 21 | 4,173 | 3,612 | 1,873 | 1,739 | 293 | 5 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{- |
Module : Neovim.RPC.SocketReader
Description : The component which reads RPC messages from the neovim instance
Copyright : (c) Sebastian Witte
License : Apache-2.0
Maintainer : [email protected]
Stability : experimental
-}
module Neovim.RPC.SocketReader (
runSocketReader,
parseParams,
) where
import Neovim.Classes
import Neovim.Context
import qualified Neovim.Context.Internal as Internal
import Neovim.Plugin.Classes (CommandArguments (..),
CommandOption (..),
FunctionName (..),
FunctionalityDescription (..),
getCommandOptions)
import Neovim.Plugin.IPC.Classes
import Neovim.Plugin (registerInStatelessContext)
import qualified Neovim.RPC.Classes as MsgpackRPC
import Neovim.RPC.Common
import Neovim.RPC.FunctionCall
import Control.Applicative
import Control.Concurrent (forkIO)
import Control.Concurrent.STM
import Control.Monad (void)
import Control.Monad.Trans.Class (lift)
import Data.Conduit as C
import Data.Conduit.Binary
import Data.Conduit.Cereal
import Data.Default (def)
import Data.Foldable (foldl', forM_)
import qualified Data.Map as Map
import Data.MessagePack
import Data.Monoid
import qualified Data.Serialize (get)
import System.IO (Handle)
import System.Log.Logger
import Prelude
logger :: String
logger = "Socket Reader"
type SocketHandler = Neovim RPCConfig ()
-- | This function will establish a connection to the given socket and read
-- msgpack-rpc events from it.
runSocketReader :: Handle
-> Internal.Config RPCConfig st
-> IO ()
runSocketReader readableHandle cfg =
void . runNeovim (Internal.retypeConfig (Internal.customConfig cfg) () cfg) () $ do
-- addCleanup (cleanUpHandle h) (sourceHandle h)
-- TODO test whether/how this should be handled
-- this has been commented out because I think that restarting the
-- plugin provider should not cause the stdin and stdout handles to be
-- closed since that would cause neovim to stop the plugin provider (I
-- think).
sourceHandle readableHandle
$= conduitGet Data.Serialize.get
$$ messageHandlerSink
-- | Sink that delegates the messages depending on their type.
-- <https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md>
messageHandlerSink :: Sink Object SocketHandler ()
messageHandlerSink = awaitForever $ \rpc -> do
liftIO . debugM logger $ "Received: " <> show rpc
case fromObject rpc of
Right (MsgpackRPC.Request (Request fn i ps)) ->
handleRequestOrNotification (Just i) fn ps
Right (MsgpackRPC.Response i r) ->
handleResponse i r
Right (MsgpackRPC.Notification (Notification fn ps)) ->
handleRequestOrNotification Nothing fn ps
Left e -> liftIO . errorM logger $
"Unhandled rpc message: " <> show e
handleResponse :: Int64 -> Either Object Object -> Sink a SocketHandler ()
handleResponse i result = do
answerMap <- asks recipients
mReply <- Map.lookup i <$> liftIO (readTVarIO answerMap)
case mReply of
Nothing -> liftIO $ warningM logger
"Received response but could not find a matching recipient."
Just (_,reply) -> do
atomically' . modifyTVar' answerMap $ Map.delete i
atomically' $ putTMVar reply result
-- | Act upon the received request or notification. The main difference between
-- the two is that a notification does not generate a reply. The distinction
-- between those two cases is done via the first paramater which is 'Maybe' the
-- function call identifier.
handleRequestOrNotification :: Maybe Int64 -> FunctionName -> [Object] -> Sink a SocketHandler ()
handleRequestOrNotification mi m params = do
cfg <- lift Internal.ask'
void . liftIO . forkIO $ handle cfg
where
lookupFunction
:: TMVar Internal.FunctionMap
-> STM (Maybe (FunctionalityDescription, Internal.FunctionType))
lookupFunction funMap = Map.lookup m <$> readTMVar funMap
handle :: Internal.Config RPCConfig () -> IO ()
handle rpc = atomically (lookupFunction (Internal.globalFunctionMap rpc)) >>= \case
Nothing -> do
let errM = "No provider for: " <> show m
debugM logger errM
forM_ mi $ \i -> atomically' . writeTQueue (Internal.eventQueue rpc)
. SomeMessage $ MsgpackRPC.Response i (Left (toObject errM))
Just (copts, Internal.Stateless f) -> do
liftIO . debugM logger $ "Executing stateless function with ID: " <> show mi
-- Stateless function: Create a boring state object for the
-- Neovim context.
-- drop the state of the result with (fmap fst <$>)
let rpc' = rpc
{ Internal.customConfig = ()
, Internal.pluginSettings = Just . Internal.StatelessSettings $
registerInStatelessContext (\_ -> return ())
}
res <- fmap fst <$> runNeovim rpc' () (f $ parseParams copts params)
-- Send the result to the event handler
forM_ mi $ \i -> atomically' . writeTQueue (Internal.eventQueue rpc)
. SomeMessage . MsgpackRPC.Response i $ either (Left . toObject) Right res
Just (copts, Internal.Stateful c) -> do
now <- liftIO getCurrentTime
reply <- liftIO newEmptyTMVarIO
let q = (recipients . Internal.customConfig) rpc
liftIO . debugM logger $ "Executing stateful function with ID: " <> show mi
case mi of
Just i -> do
atomically' . modifyTVar q $ Map.insert i (now, reply)
atomically' . writeTQueue c . SomeMessage $
Request m i (parseParams copts params)
Nothing ->
atomically' . writeTQueue c . SomeMessage $
Notification m (parseParams copts params)
parseParams :: FunctionalityDescription -> [Object] -> [Object]
parseParams (Function _ _) args = case args of
-- Defining a function on the remote host creates a function that, that
-- passes all arguments in a list. At the time of this writing, no other
-- arguments are passed for such a function.
--
-- The function generating the function on neovim side is called:
-- @remote#define#FunctionOnHost@
[ObjectArray fArgs] -> fArgs
_ -> args
parseParams cmd@(Command _ opts) args = case args of
(ObjectArray _ : _) ->
let cmdArgs = filter isPassedViaRPC (getCommandOptions opts)
(c,args') =
foldl' createCommandArguments (def, []) $
zip cmdArgs args
in toObject c : args'
_ -> parseParams cmd $ [ObjectArray args]
where
isPassedViaRPC :: CommandOption -> Bool
isPassedViaRPC = \case
CmdSync{} -> False
_ -> True
-- Neovim passes arguments in a special form, depending on the
-- CommandOption values used to export the (command) function (e.g. via
-- 'command' or 'command'').
createCommandArguments :: (CommandArguments, [Object])
-> (CommandOption, Object)
-> (CommandArguments, [Object])
createCommandArguments old@(c, args') = \case
(CmdRange _, o) ->
either (const old) (\r -> (c { range = Just r }, args')) $ fromObject o
(CmdCount _, o) ->
either (const old) (\n -> (c { count = Just n }, args')) $ fromObject o
(CmdBang, o) ->
either (const old) (\b -> (c { bang = Just b }, args')) $ fromObject o
(CmdNargs "*", ObjectArray os) ->
-- CommandArguments -> [String] -> Neovim r st a
(c, os)
(CmdNargs "+", ObjectArray (o:os)) ->
-- CommandArguments -> String -> [String] -> Neovim r st a
(c, o : [ObjectArray os])
(CmdNargs "?", ObjectArray [o]) ->
-- CommandArguments -> Maybe String -> Neovim r st a
(c, [toObject (Just o)])
(CmdNargs "?", ObjectArray []) ->
-- CommandArguments -> Maybe String -> Neovim r st a
(c, [toObject (Nothing :: Maybe Object)])
(CmdNargs "0", ObjectArray []) ->
-- CommandArguments -> Neovim r st a
(c, [])
(CmdNargs "1", ObjectArray [o]) ->
-- CommandArguments -> String -> Neovim r st a
(c, [o])
(CmdRegister, o) ->
either (const old) (\r -> (c { register = Just r }, args')) $ fromObject o
_ -> old
parseParams (Autocmd _ _ _) args = case args of
[ObjectArray fArgs] -> fArgs
_ -> args
| lslah/nvim-hs | library/Neovim/RPC/SocketReader.hs | apache-2.0 | 9,448 | 0 | 23 | 3,063 | 2,121 | 1,114 | 1,007 | 151 | 15 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TupleSections #-}
-- | Generate HPC (Haskell Program Coverage) reports
module Stack.Coverage
( deleteHpcReports
, updateTixFile
, generateHpcReport
, HpcReportOpts(..)
, generateHpcReportForTargets
, generateHpcUnifiedReport
, generateHpcMarkupIndex
) where
import Stack.Prelude hiding (Display (..))
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as BL
import Data.List
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Distribution.Version (mkVersion)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO
import Stack.Build.Target
import Stack.Constants
import Stack.Constants.Config
import Stack.Package
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.NamedComponent
import Stack.Types.Package
import Stack.Types.SourceMap
import System.FilePath (isPathSeparator)
import qualified RIO
import RIO.PrettyPrint
import RIO.Process
import Trace.Hpc.Tix
import Web.Browser (openBrowser)
newtype CoverageException = NonTestSuiteTarget PackageName deriving Typeable
instance Exception CoverageException
instance Show CoverageException where
show (NonTestSuiteTarget name) =
"Can't specify anything except test-suites as hpc report targets (" ++
packageNameString name ++
" is used with a non test-suite target)"
-- | Invoked at the beginning of running with "--coverage"
deleteHpcReports :: HasEnvConfig env => RIO env ()
deleteHpcReports = do
hpcDir <- hpcReportDir
liftIO $ ignoringAbsence (removeDirRecur hpcDir)
-- | Move a tix file into a sub-directory of the hpc report directory. Deletes the old one if one is
-- present.
updateTixFile :: HasEnvConfig env => PackageName -> Path Abs File -> String -> RIO env ()
updateTixFile pkgName' tixSrc testName = do
exists <- doesFileExist tixSrc
when exists $ do
tixDest <- tixFilePath pkgName' testName
liftIO $ ignoringAbsence (removeFile tixDest)
ensureDir (parent tixDest)
-- Remove exe modules because they are problematic. This could be revisited if there's a GHC
-- version that fixes https://ghc.haskell.org/trac/ghc/ticket/1853
mtix <- readTixOrLog tixSrc
case mtix of
Nothing -> logError $ "Failed to read " <> fromString (toFilePath tixSrc)
Just tix -> do
liftIO $ writeTix (toFilePath tixDest) (removeExeModules tix)
-- TODO: ideally we'd do a file move, but IIRC this can
-- have problems. Something about moving between drives
-- on windows?
copyFile tixSrc =<< parseAbsFile (toFilePath tixDest ++ ".premunging")
liftIO $ ignoringAbsence (removeFile tixSrc)
-- | Get the directory used for hpc reports for the given pkgId.
hpcPkgPath :: HasEnvConfig env => PackageName -> RIO env (Path Abs Dir)
hpcPkgPath pkgName' = do
outputDir <- hpcReportDir
pkgNameRel <- parseRelDir (packageNameString pkgName')
return (outputDir </> pkgNameRel)
-- | Get the tix file location, given the name of the file (without extension), and the package
-- identifier string.
tixFilePath :: HasEnvConfig env
=> PackageName -> String -> RIO env (Path Abs File)
tixFilePath pkgName' testName = do
pkgPath <- hpcPkgPath pkgName'
tixRel <- parseRelFile (testName ++ "/" ++ testName ++ ".tix")
return (pkgPath </> tixRel)
-- | Generates the HTML coverage report and shows a textual coverage summary for a package.
generateHpcReport :: HasEnvConfig env
=> Path Abs Dir -> Package -> [Text] -> RIO env ()
generateHpcReport pkgDir package tests = do
compilerVersion <- view actualCompilerVersionL
-- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See
-- https://github.com/commercialhaskell/stack/issues/785
let pkgName' = T.pack $ packageNameString (packageName package)
pkgId = packageIdentifierString (packageIdentifier package)
ghcVersion = getGhcVersion compilerVersion
hasLibrary =
case packageLibraries package of
NoLibraries -> False
HasLibraries _ -> True
internalLibs = packageInternalLibraries package
eincludeName <-
-- Pre-7.8 uses plain PKG-version in tix files.
if ghcVersion < mkVersion [7, 10] then return $ Right $ Just [pkgId]
-- We don't expect to find a package key if there is no library.
else if not hasLibrary && Set.null internalLibs then return $ Right Nothing
-- Look in the inplace DB for the package key.
-- See https://github.com/commercialhaskell/stack/issues/1181#issuecomment-148968986
else do
-- GHC 8.0 uses package id instead of package key.
-- See https://github.com/commercialhaskell/stack/issues/2424
let hpcNameField = if ghcVersion >= mkVersion [8, 0] then "id" else "key"
eincludeName <- findPackageFieldForBuiltPackage pkgDir (packageIdentifier package) internalLibs hpcNameField
case eincludeName of
Left err -> do
logError $ RIO.display err
return $ Left err
Right includeNames -> return $ Right $ Just $ map T.unpack includeNames
forM_ tests $ \testName -> do
tixSrc <- tixFilePath (packageName package) (T.unpack testName)
let report = "coverage report for " <> pkgName' <> "'s test-suite \"" <> testName <> "\""
reportDir = parent tixSrc
case eincludeName of
Left err -> generateHpcErrorReport reportDir (RIO.display (sanitize (T.unpack err)))
-- Restrict to just the current library code, if there is a library in the package (see
-- #634 - this will likely be customizable in the future)
Right mincludeName -> do
let extraArgs = case mincludeName of
Just includeNames -> "--include" : intersperse "--include" (map (\n -> n ++ ":") includeNames)
Nothing -> []
mreportPath <- generateHpcReportInternal tixSrc reportDir report extraArgs extraArgs
forM_ mreportPath (displayReportPath report . pretty)
generateHpcReportInternal :: HasEnvConfig env
=> Path Abs File -> Path Abs Dir -> Text -> [String] -> [String]
-> RIO env (Maybe (Path Abs File))
generateHpcReportInternal tixSrc reportDir report extraMarkupArgs extraReportArgs = do
-- If a .tix file exists, move it to the HPC output directory and generate a report for it.
tixFileExists <- doesFileExist tixSrc
if not tixFileExists
then do
logError $
"Didn't find .tix for " <>
RIO.display report <>
" - expected to find it at " <>
fromString (toFilePath tixSrc) <>
"."
return Nothing
else (`catch` \(err :: ProcessException) -> do
logError $ displayShow err
generateHpcErrorReport reportDir $ RIO.display $ sanitize $ show err
return Nothing) $
(`onException` logError ("Error occurred while producing " <> RIO.display report)) $ do
-- Directories for .mix files.
hpcRelDir <- hpcRelativeDir
-- Compute arguments used for both "hpc markup" and "hpc report".
pkgDirs <- view $ buildConfigL.to (map ppRoot . Map.elems . smwProject . bcSMWanted)
let args =
-- Use index files from all packages (allows cross-package coverage results).
concatMap (\x -> ["--srcdir", toFilePathNoTrailingSep x]) pkgDirs ++
-- Look for index files in the correct dir (relative to each pkgdir).
["--hpcdir", toFilePathNoTrailingSep hpcRelDir, "--reset-hpcdirs"]
logInfo $ "Generating " <> RIO.display report
outputLines <- liftM (map (S8.filter (/= '\r')) . S8.lines . BL.toStrict . fst) $
proc "hpc"
( "report"
: toFilePath tixSrc
: (args ++ extraReportArgs)
)
readProcess_
if all ("(0/0)" `S8.isSuffixOf`) outputLines
then do
let msg html =
"Error: The " <>
RIO.display report <>
" did not consider any code. One possible cause of this is" <>
" if your test-suite builds the library code (see stack " <>
(if html then "<a href='https://github.com/commercialhaskell/stack/issues/1008'>" else "") <>
"issue #1008" <>
(if html then "</a>" else "") <>
"). It may also indicate a bug in stack or" <>
" the hpc program. Please report this issue if you think" <>
" your coverage report should have meaningful results."
logError (msg False)
generateHpcErrorReport reportDir (msg True)
return Nothing
else do
let reportPath = reportDir </> relFileHpcIndexHtml
-- Print output, stripping @\r@ characters because Windows.
forM_ outputLines (logInfo . displayBytesUtf8)
-- Generate the markup.
void $ proc "hpc"
( "markup"
: toFilePath tixSrc
: ("--destdir=" ++ toFilePathNoTrailingSep reportDir)
: (args ++ extraMarkupArgs)
)
readProcess_
return (Just reportPath)
data HpcReportOpts = HpcReportOpts
{ hroptsInputs :: [Text]
, hroptsAll :: Bool
, hroptsDestDir :: Maybe String
, hroptsOpenBrowser :: Bool
} deriving (Show)
generateHpcReportForTargets :: HasEnvConfig env
=> HpcReportOpts -> [Text] -> [Text] -> RIO env ()
generateHpcReportForTargets opts tixFiles targetNames = do
targetTixFiles <-
-- When there aren't any package component arguments, and --all
-- isn't passed, default to not considering any targets.
if not (hroptsAll opts) && null targetNames
then return []
else do
when (hroptsAll opts && not (null targetNames)) $
logWarn $ "Since --all is used, it is redundant to specify these targets: " <> displayShow targetNames
targets <- view $ envConfigL.to envConfigSourceMap.to smTargets.to smtTargets
liftM concat $ forM (Map.toList targets) $ \(name, target) ->
case target of
TargetAll PTDependency -> throwString $
"Error: Expected a local package, but " ++
packageNameString name ++
" is either an extra-dep or in the snapshot."
TargetComps comps -> do
pkgPath <- hpcPkgPath name
forM (toList comps) $ \nc ->
case nc of
CTest testName ->
liftM (pkgPath </>) $ parseRelFile (T.unpack testName ++ "/" ++ T.unpack testName ++ ".tix")
_ -> throwIO $ NonTestSuiteTarget name
TargetAll PTProject -> do
pkgPath <- hpcPkgPath name
exists <- doesDirExist pkgPath
if exists
then do
(dirs, _) <- listDir pkgPath
liftM concat $ forM dirs $ \dir -> do
(_, files) <- listDir dir
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
else return []
tixPaths <- liftM (\xs -> xs ++ targetTixFiles) $ mapM (resolveFile' . T.unpack) tixFiles
when (null tixPaths) $
throwString "Not generating combined report, because no targets or tix files are specified."
outputDir <- hpcReportDir
reportDir <- case hroptsDestDir opts of
Nothing -> return (outputDir </> relDirCombined </> relDirCustom)
Just destDir -> do
dest <- resolveDir' destDir
ensureDir dest
return dest
let report = "combined report"
mreportPath <- generateUnionReport report reportDir tixPaths
forM_ mreportPath $ \reportPath ->
if hroptsOpenBrowser opts
then do
prettyInfo $ "Opening" <+> pretty reportPath <+> "in the browser."
void $ liftIO $ openBrowser (toFilePath reportPath)
else displayReportPath report (pretty reportPath)
generateHpcUnifiedReport :: HasEnvConfig env => RIO env ()
generateHpcUnifiedReport = do
outputDir <- hpcReportDir
ensureDir outputDir
(dirs, _) <- listDir outputDir
tixFiles0 <- liftM (concat . concat) $ forM (filter (("combined" /=) . dirnameString) dirs) $ \dir -> do
(dirs', _) <- listDir dir
forM dirs' $ \dir' -> do
(_, files) <- listDir dir'
return (filter ((".tix" `isSuffixOf`) . toFilePath) files)
extraTixFiles <- findExtraTixFiles
let tixFiles = tixFiles0 ++ extraTixFiles
reportDir = outputDir </> relDirCombined </> relDirAll
if length tixFiles < 2
then logInfo $
(if null tixFiles then "No tix files" else "Only one tix file") <>
" found in " <>
fromString (toFilePath outputDir) <>
", so not generating a unified coverage report."
else do
let report = "unified report"
mreportPath <- generateUnionReport report reportDir tixFiles
forM_ mreportPath (displayReportPath report . pretty)
generateUnionReport :: HasEnvConfig env
=> Text -> Path Abs Dir -> [Path Abs File]
-> RIO env (Maybe (Path Abs File))
generateUnionReport report reportDir tixFiles = do
(errs, tix) <- fmap (unionTixes . map removeExeModules) (mapMaybeM readTixOrLog tixFiles)
logDebug $ "Using the following tix files: " <> fromString (show tixFiles)
unless (null errs) $ logWarn $
"The following modules are left out of the " <>
RIO.display report <>
" due to version mismatches: " <>
mconcat (intersperse ", " (map fromString errs))
tixDest <- liftM (reportDir </>) $ parseRelFile (dirnameString reportDir ++ ".tix")
ensureDir (parent tixDest)
liftIO $ writeTix (toFilePath tixDest) tix
generateHpcReportInternal tixDest reportDir report [] []
readTixOrLog :: HasLogFunc env => Path b File -> RIO env (Maybe Tix)
readTixOrLog path = do
mtix <- liftIO (readTix (toFilePath path)) `catchAny` \errorCall -> do
logError $ "Error while reading tix: " <> fromString (show errorCall)
return Nothing
when (isNothing mtix) $
logError $ "Failed to read tix file " <> fromString (toFilePath path)
return mtix
-- | Module names which contain '/' have a package name, and so they weren't built into the
-- executable.
removeExeModules :: Tix -> Tix
removeExeModules (Tix ms) = Tix (filter (\(TixModule name _ _ _) -> '/' `elem` name) ms)
unionTixes :: [Tix] -> ([String], Tix)
unionTixes tixes = (Map.keys errs, Tix (Map.elems outputs))
where
(errs, outputs) = Map.mapEither id $ Map.unionsWith merge $ map toMap tixes
toMap (Tix ms) = Map.fromList (map (\x@(TixModule k _ _ _) -> (k, Right x)) ms)
merge (Right (TixModule k hash1 len1 tix1))
(Right (TixModule _ hash2 len2 tix2))
| hash1 == hash2 && len1 == len2 = Right (TixModule k hash1 len1 (zipWith (+) tix1 tix2))
merge _ _ = Left ()
generateHpcMarkupIndex :: HasEnvConfig env => RIO env ()
generateHpcMarkupIndex = do
outputDir <- hpcReportDir
let outputFile = outputDir </> relFileIndexHtml
ensureDir outputDir
(dirs, _) <- listDir outputDir
rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do
(subdirs, _) <- listDir dir
forM subdirs $ \subdir -> do
let indexPath = subdir </> relFileHpcIndexHtml
exists' <- doesFileExist indexPath
if not exists' then return Nothing else do
relPath <- stripProperPrefix outputDir indexPath
let package = dirname dir
testsuite = dirname subdir
return $ Just $ T.concat
[ "<tr><td>"
, pathToHtml package
, "</td><td><a href=\""
, pathToHtml relPath
, "\">"
, pathToHtml testsuite
, "</a></td></tr>"
]
writeBinaryFileAtomic outputFile $
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" <>
-- Part of the css from HPC's output HTML
"<style type=\"text/css\">" <>
"table.dashboard { border-collapse: collapse; border: solid 1px black }" <>
".dashboard td { border: solid 1px black }" <>
".dashboard th { border: solid 1px black }" <>
"</style>" <>
"</head>" <>
"<body>" <>
(if null rows
then
"<b>No hpc_index.html files found in \"" <>
encodeUtf8Builder (pathToHtml outputDir) <>
"\".</b>"
else
"<table class=\"dashboard\" width=\"100%\" border=\"1\"><tbody>" <>
"<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>" <>
"<tr><th>Package</th><th>TestSuite</th><th>Modification Time</th></tr>" <>
foldMap encodeUtf8Builder rows <>
"</tbody></table>") <>
"</body></html>"
unless (null rows) $
logInfo $ "\nAn index of the generated HTML coverage reports is available at " <>
fromString (toFilePath outputFile)
generateHpcErrorReport :: MonadIO m => Path Abs Dir -> Utf8Builder -> m ()
generateHpcErrorReport dir err = do
ensureDir dir
let fp = toFilePath (dir </> relFileHpcIndexHtml)
writeFileUtf8Builder fp $
"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></head><body>" <>
"<h1>HPC Report Generation Error</h1>" <>
"<p>" <>
err <>
"</p>" <>
"</body></html>"
pathToHtml :: Path b t -> Text
pathToHtml = T.dropWhileEnd (=='/') . sanitize . toFilePath
-- | Escape HTML symbols (copied from Text.Hastache)
htmlEscape :: LT.Text -> LT.Text
htmlEscape = LT.concatMap proc_
where
proc_ '&' = "&"
proc_ '\\' = "\"
proc_ '"' = """
proc_ '\'' = "'"
proc_ '<' = "<"
proc_ '>' = ">"
proc_ h = LT.singleton h
sanitize :: String -> Text
sanitize = LT.toStrict . htmlEscape . LT.pack
dirnameString :: Path r Dir -> String
dirnameString = dropWhileEnd isPathSeparator . toFilePath . dirname
findPackageFieldForBuiltPackage
:: HasEnvConfig env
=> Path Abs Dir -> PackageIdentifier -> Set.Set Text -> Text
-> RIO env (Either Text [Text])
findPackageFieldForBuiltPackage pkgDir pkgId internalLibs field = do
distDir <- distDirFromDir pkgDir
let inplaceDir = distDir </> relDirPackageConfInplace
pkgIdStr = packageIdentifierString pkgId
notFoundErr = return $ Left $ "Failed to find package key for " <> T.pack pkgIdStr
extractField path = do
contents <- readFileUtf8 (toFilePath path)
case asum (map (T.stripPrefix (field <> ": ")) (T.lines contents)) of
Just result -> return $ Right $ T.strip result
Nothing -> notFoundErr
cabalVer <- view cabalVersionL
if cabalVer < mkVersion [1, 24]
then do
-- here we don't need to handle internal libs
path <- liftM (inplaceDir </>) $ parseRelFile (pkgIdStr ++ "-inplace.conf")
logDebug $ "Parsing config in Cabal < 1.24 location: " <> fromString (toFilePath path)
exists <- doesFileExist path
if exists then fmap (:[]) <$> extractField path else notFoundErr
else do
-- With Cabal-1.24, it's in a different location.
logDebug $ "Scanning " <> fromString (toFilePath inplaceDir) <> " for files matching " <> fromString pkgIdStr
(_, files) <- handleIO (const $ return ([], [])) $ listDir inplaceDir
logDebug $ displayShow files
-- From all the files obtained from the scanning process above, we
-- need to identify which are .conf files and then ensure that
-- there is at most one .conf file for each library and internal
-- library (some might be missing if that component has not been
-- built yet). We should error if there are more than one .conf
-- file for a component or if there are no .conf files at all in
-- the searched location.
let toFilename = T.pack . toFilePath . filename
-- strip known prefix and suffix from the found files to determine only the conf files
stripKnown = T.stripSuffix ".conf" <=< T.stripPrefix (T.pack (pkgIdStr ++ "-"))
stripped = mapMaybe (\file -> fmap (,file) . stripKnown . toFilename $ file) files
-- which component could have generated each of these conf files
stripHash n = let z = T.dropWhile (/= '-') n in if T.null z then "" else T.tail z
matchedComponents = map (\(n, f) -> (stripHash n, [f])) stripped
byComponents = Map.restrictKeys (Map.fromListWith (++) matchedComponents) $ Set.insert "" internalLibs
logDebug $ displayShow byComponents
if Map.null $ Map.filter (\fs -> length fs > 1) byComponents
then case concat $ Map.elems byComponents of
[] -> notFoundErr
-- for each of these files, we need to extract the requested field
paths -> do
(errors, keys) <- partitionEithers <$> traverse extractField paths
case errors of
(a:_) -> return $ Left a -- the first error only, since they're repeated anyway
[] -> return $ Right keys
else return $ Left $ "Multiple files matching " <> T.pack (pkgIdStr ++ "-*.conf") <> " found in " <>
T.pack (toFilePath inplaceDir) <> ". Maybe try 'stack clean' on this package?"
displayReportPath :: (HasTerm env)
=> Text -> StyleDoc -> RIO env ()
displayReportPath report reportPath =
prettyInfo $ "The" <+> fromString (T.unpack report) <+> "is available at" <+> reportPath
findExtraTixFiles :: HasEnvConfig env => RIO env [Path Abs File]
findExtraTixFiles = do
outputDir <- hpcReportDir
let dir = outputDir </> relDirExtraTixFiles
dirExists <- doesDirExist dir
if dirExists
then do
(_, files) <- listDir dir
return $ filter ((".tix" `isSuffixOf`) . toFilePath) files
else return []
| juhp/stack | src/Stack/Coverage.hs | bsd-3-clause | 24,184 | 0 | 30 | 7,727 | 5,337 | 2,656 | 2,681 | 411 | 8 |
--
-- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
-- | client interface for sending data to the vault.
--
-- This module provides functions for preparing and queuing points to be sent
-- by a server to the vault.
--
-- If you call close, you can be assured that your data is safe and will at
-- some point end up in the data vault (excluding local disk failure). This
-- assumption is based on a functional marquise daemon with connectivity
-- eventually running within your namespace.
--
-- We provide no way to *absolutely* ensure that a point is currently written
-- to the vault. Such a guarantee would require blocking and complex queuing,
-- or observing various underlying mechanisms that should ideally remain
-- abstract.
--
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- Hide warnings for the deprecated ErrorT transformer:
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module Marquise.Client.Core where
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad.Error
import Crypto.MAC.SipHash
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.Char (isAlphaNum)
import Data.Packer
import Data.Word (Word64)
import Pipes
import Marquise.Classes
import Marquise.Types
import Vaultaire.Types
-- | Create a SpoolName. Only alphanumeric characters are allowed, max length
-- is 32 characters.
makeSpoolName :: Monad m => String -> m SpoolName
makeSpoolName s
| any (not . isAlphaNum) s = E.throw $ MarquiseException s
| otherwise = return (SpoolName s)
-- | Create a name in the spool. Only alphanumeric characters are allowed, max length
-- is 32 characters.
createSpoolFiles :: MarquiseSpoolFileMonad m
=> String
-> m SpoolFiles
createSpoolFiles s = do
n <- makeSpoolName s
createDirectories n
randomSpoolFiles n
-- | Deterministically convert a ByteString to an Address by taking the
-- most significant 63 bytes of its SipHash-2-4[0] with a zero key. The
-- LSB of the resulting 64-bit value is not part of the unique portion
-- of the address; it is set when queueing writes, depending on the
-- point type (simple or extended) being written.
--
-- [0] https://131002.net/siphash/
hashIdentifier :: ByteString -> Address
hashIdentifier = Address . (`clearBit` 0) . unSipHash . hash iv
where
iv = SipKey 0 0
unSipHash (SipHash h) = h :: Word64
-- | Generate an un-used Address. You will need to store this for later re-use.
requestUnique :: MarquiseContentsMonad m conn
=> Origin
-> conn
-> m Address
requestUnique origin conn = do
sendContentsRequest GenerateNewAddress origin conn
response <- recvContentsResponse conn
case response of
RandomAddress addr -> return addr
_ -> error "requestUnique: Invalid response"
-- | Set the key,value tags as metadata on the given Address.
updateSourceDict :: MarquiseContentsMonad m conn
=> Address
-> SourceDict
-> Origin
-> conn
-> m ()
updateSourceDict addr source_dict origin conn = do
sendContentsRequest (UpdateSourceTag addr source_dict) origin conn
response <- recvContentsResponse conn
case response of
UpdateSuccess -> return ()
_ -> error "requestSourceDictUpdate: Invalid response"
-- | Remove the supplied key,value tags from metadata on the Address, if present.
removeSourceDict :: MarquiseContentsMonad m conn
=> Address
-> SourceDict
-> Origin
-> conn
-> m ()
removeSourceDict addr source_dict origin conn = do
sendContentsRequest (RemoveSourceTag addr source_dict) origin conn
response <- recvContentsResponse conn
case response of
RemoveSuccess -> return ()
_ -> error "requestSourceDictRemoval: Invalid response"
-- | Stream read every Address associated with the given Origin
enumerateOrigin :: MarquiseContentsMonad m conn
=> Origin
-> conn
-> Producer (Address, SourceDict) m ()
enumerateOrigin origin conn = do
lift $ sendContentsRequest ContentsListRequest origin conn
loop
where
loop = do
resp <- lift $ recvContentsResponse conn
case resp of
ContentsListEntry addr dict -> do
yield (addr, dict)
loop
EndOfContentsList -> return ()
_ -> error "enumerateOrigin loop: Invalid response"
-- | Stream read every SimpleBurst from the Address between the given times
readSimple :: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' SimpleBurst m ()
readSimple addr start end origin conn = do
lift $ sendReaderRequest (SimpleReadRequest addr start end) origin conn
loop
where
loop = do
response <- lift $ recvReaderResponse conn
case response of
SimpleStream burst ->
yield burst >> loop
EndOfStream ->
return ()
InvalidReadOrigin ->
error "readSimple loop: Invalid origin"
_ ->
error "readSimple loop: Invalid response"
-- | Like @readSimple@ but also decodes the points.
--
readSimplePoints
:: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' SimplePoint m ()
readSimplePoints addr start end origin conn
= for (readSimple addr start end origin conn >-> decodeSimple) yield
-- | Stream read every ExtendedBurst from the Address between the given times
readExtended :: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' ExtendedBurst m ()
readExtended addr start end origin conn = do
lift $ sendReaderRequest (ExtendedReadRequest addr start end) origin conn
loop
where
loop = do
response <- lift $ recvReaderResponse conn
case response of
ExtendedStream burst ->
yield burst >> loop
EndOfStream ->
return ()
_ ->
error "readExtended loop: Invalid response"
-- | Like @readExtended@ but also decodes the points.
--
readExtendedPoints
:: MarquiseReaderMonad m conn
=> Address
-> TimeStamp
-> TimeStamp
-> Origin
-> conn
-> Producer' ExtendedPoint m ()
readExtendedPoints addr start end origin conn
= for (readExtended addr start end origin conn >-> decodeExtended) yield
-- | Stream converts raw SimpleBursts into SimplePoints
decodeSimple :: Monad m => Pipe SimpleBurst SimplePoint m ()
decodeSimple = forever (unSimpleBurst <$> await >>= emitFrom 0)
where
emitFrom os chunk
| os >= BS.length chunk = return ()
| otherwise = do
yield $ decodeSimple' os chunk
emitFrom (os + 24) chunk
-- | Decodes a single point at an offset.
decodeSimple' :: Int -> ByteString -> SimplePoint
decodeSimple' offset chunk = flip runUnpacking chunk $ do
unpackSetPosition offset
addr <- Address <$> getWord64LE
time <- TimeStamp <$> getWord64LE
payload <- getWord64LE
return $ SimplePoint addr time payload
-- | Stream converts raw ExtendedBursts into ExtendedPoints
decodeExtended :: Monad m => Pipe ExtendedBurst ExtendedPoint m ()
decodeExtended = forever (unExtendedBurst <$> await >>= emitFrom 0)
where
emitFrom os chunk
| os >= BS.length chunk = return ()
| otherwise = do
let result = runUnpacking (unpack os) chunk
yield result
let size = BS.length (extendedPayload result) + 24
emitFrom (os + size) chunk
unpack os = do
unpackSetPosition os
addr <- Address <$> getWord64LE
time <- TimeStamp <$> getWord64LE
len <- fromIntegral <$> getWord64LE
payload <- if len == 0
then return BS.empty
else getBytes len
return $ ExtendedPoint addr time payload
-- | Send a "simple" data point. Interpretation of this point, e.g.
-- float/signed is up to you, but it must be sent in the form of a Word64.
-- Clears the least-significant bit of the address to indicate that this
-- is a simple datapoint.
queueSimple
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> TimeStamp
-> Word64
-> m ()
queueSimple sfs (Address ad) (TimeStamp ts) w = appendPoints sfs bytes
where
bytes = runPacking 24 $ do
putWord64LE (ad `clearBit` 0)
putWord64LE ts
putWord64LE w
-- | Send an "extended" data point. Again, representation is up to you.
-- Sets the least-significant bit of the address to indicate that this is
-- an extended data point.
queueExtended
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> TimeStamp
-> ByteString
-> m ()
queueExtended sfs (Address ad) (TimeStamp ts) bs = appendPoints sfs bytes
where
len = BS.length bs
bytes = runPacking (24 + len) $ do
putWord64LE (ad `setBit` 0)
putWord64LE ts
putWord64LE $ fromIntegral len
putBytes bs
-- | Updates the SourceDict at addr with source_dict
queueSourceDictUpdate
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> Address
-> SourceDict
-> m ()
queueSourceDictUpdate sfs (Address addr) source_dict = appendContents sfs bytes
where
source_dict_bytes = toWire source_dict
source_dict_len = BS.length source_dict_bytes
bytes = runPacking (source_dict_len + 16) $ do
putWord64LE addr
putWord64LE (fromIntegral source_dict_len)
putBytes source_dict_bytes
-- | Ensure that all sent points have hit the local disk.
flush
:: MarquiseSpoolFileMonad m
=> SpoolFiles
-> m ()
flush = close
| anchor/marquise | lib/Marquise/Client/Core.hs | bsd-3-clause | 10,352 | 0 | 16 | 2,828 | 2,057 | 1,013 | 1,044 | 219 | 4 |
{-# OPTIONS_GHC -Wall #-}
module Optimize.Inline (inline) where
import Control.Arrow (second, (***))
import Control.Monad (foldM)
import qualified Data.List as List
import qualified Data.Map as Map
import AST.Expression.Optimized (Expr(..), Decider(..), Choice(..))
import qualified AST.Expression.Optimized as Opt
import qualified AST.Variable as Var
import qualified Optimize.Environment as Env
inline :: Map.Map String Opt.Expr -> Opt.Expr -> Env.Optimizer Opt.Expr
inline rawSubs expression =
let
counts =
count expression
annotatedSubs =
Map.toList (Map.intersectionWith (,) counts rawSubs)
in
do (Subs subs defs) <- foldM processSubs (Subs Map.empty []) annotatedSubs
let inlinedExpr = replace subs expression
return $
if null defs then
inlinedExpr
else
Let (map (\(name, expr) -> Opt.Def Opt.dummyFacts name expr) defs) inlinedExpr
data Subs = Subs
{ _substitutions :: Map.Map String Opt.Expr
, _definitions :: [(String, Opt.Expr)]
}
processSubs :: Subs -> (String, (Int, Opt.Expr)) -> Env.Optimizer Subs
processSubs (Subs subs defs) (name, (n, expr)) =
if n == 1 then
return $ Subs (Map.insert name expr subs) defs
else
do uniqueName <- Env.freshName
return $ Subs
(Map.insert name (Opt.Var (Var.local uniqueName)) subs)
((uniqueName, expr) : defs)
-- HELPERS
deleteBatch :: [String] -> Map.Map String a -> Map.Map String a
deleteBatch names dict =
List.foldl' (flip Map.delete) dict names
getDefName :: Opt.Def -> String
getDefName def =
case def of
Opt.Def _ name _ ->
name
Opt.TailDef _ name _ _ ->
name
-- COUNT VARIABLE APPEARANCES
count :: Opt.Expr -> Map.Map String Int
count expression =
let
count2 a b =
Map.unionWith (+) (count a) (count b)
countMany xs =
Map.unionsWith (+) (map count xs)
in
case expression of
Literal _ ->
Map.empty
Var (Var.Canonical home name) ->
case home of
Var.Local ->
Map.singleton name 1
Var.BuiltIn ->
Map.empty
Var.Module _ ->
Map.empty
Var.TopLevel _ ->
Map.empty
Range lo hi ->
count2 lo hi
ExplicitList exprs ->
countMany exprs
Binop _op left right ->
count2 left right
Function args body ->
deleteBatch args (count body)
Call func args ->
Map.unionWith (+) (count func) (countMany args)
TailCall _name _argNames args ->
countMany args
If branches finally ->
Map.unionsWith (+) (count finally : map (uncurry count2) branches)
Let defs expr ->
let
countDef def =
case def of
Opt.Def _ name body ->
Map.delete name (count body)
Opt.TailDef _ name argNames body ->
deleteBatch (name:argNames) (count body)
exprCount =
deleteBatch (map getDefName defs) (count expr)
in
Map.unionsWith (+) (exprCount : map countDef defs)
Case _ decider jumps ->
let
countDecider dcdr =
case dcdr of
Leaf (Inline expr) ->
count expr
Leaf (Jump _) ->
Map.empty
Chain _ success failure ->
Map.unionWith (+) (countDecider success) (countDecider failure)
FanOut _path tests fallback ->
Map.unionsWith (+) (map countDecider (fallback : map snd tests))
in
Map.unionsWith (+) (countDecider decider : map (count . snd) jumps)
Data _tag values ->
countMany values
DataAccess root _index ->
count root
Access record _field ->
count record
Update record fields ->
Map.unionWith (+) (count record) (countMany (map snd fields))
Record fields ->
countMany (map snd fields)
Cmd _ ->
Map.empty
Sub _ ->
Map.empty
OutgoingPort _ _ ->
Map.empty
IncomingPort _ _ ->
Map.empty
Program _ expr ->
count expr
GLShader _ _ _ ->
Map.empty
Crash _ _ maybeBranchProblem ->
maybe Map.empty count maybeBranchProblem
-- REPLACE
replace :: Map.Map String Opt.Expr -> Opt.Expr -> Opt.Expr
replace substitutions expression =
let
go = replace substitutions
in
case expression of
Literal _ ->
expression
Var (Var.Canonical Var.Local name) ->
maybe expression id (Map.lookup name substitutions)
Var _ ->
expression
Range lo hi ->
Range (go lo) (go hi)
ExplicitList exprs ->
ExplicitList (map go exprs)
Binop op left right ->
Binop op (go left) (go right)
Function args body ->
Function args (replace (deleteBatch args substitutions) body)
Call func args ->
Call (go func) (map go args)
TailCall name argNames args ->
TailCall name argNames (map go args)
If branches finally ->
If (map (go *** go) branches) (go finally)
Let defs expr ->
let
replaceDef def =
case def of
Opt.Def facts name body ->
Opt.Def facts name
(replace (Map.delete name substitutions) body)
Opt.TailDef facts name argNames body ->
Opt.TailDef facts name argNames
(replace (deleteBatch (name:argNames) substitutions) body)
boundNames =
map getDefName defs
in
Let
(map replaceDef defs)
(replace (deleteBatch boundNames substitutions) expr)
Case exprName decider jumps ->
let
goDecider dcdr =
case dcdr of
Leaf (Inline expr) ->
Leaf (Inline (go expr))
Leaf (Jump _target) ->
dcdr
Chain chain success failure ->
Chain chain (goDecider success) (goDecider failure)
FanOut path tests fallback ->
FanOut path (map (second goDecider) tests) (goDecider fallback)
in
Case exprName (goDecider decider) (map (second go) jumps)
Data tag values ->
Data tag (map go values)
DataAccess root index ->
DataAccess (go root) index
Access record field ->
Access (go record) field
Update record fields ->
Update (go record) (map (second go) fields)
Record fields ->
Record (map (second go) fields)
Cmd _ ->
expression
Sub _ ->
expression
OutgoingPort _ _ ->
expression
IncomingPort _ _ ->
expression
Program kind expr ->
Program kind (go expr)
GLShader _ _ _ ->
expression
Crash home region maybeBranchProblem ->
Crash home region (fmap go maybeBranchProblem)
| mgold/Elm | src/Optimize/Inline.hs | bsd-3-clause | 7,028 | 0 | 23 | 2,463 | 2,343 | 1,150 | 1,193 | 203 | 30 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-}
module Text.Parsec.Indentation.Char where
import Text.Parsec.Prim (ParsecT, mkPT, runParsecT,
Stream(..),
Consumed(..), Reply(..),
State(..))
import Text.Parsec.Pos (sourceColumn)
import Text.Parser.Indentation.Implementation (Indentation)
----------------
-- Unicode char
-- newtype UnicodeIndentStream
----------------
-- Based on Char
{-# INLINE mkCharIndentStream #-}
mkCharIndentStream :: s -> CharIndentStream s
mkCharIndentStream s = CharIndentStream 1 s
data CharIndentStream s = CharIndentStream { charIndentStreamColumn :: {-# UNPACK #-} !Indentation,
charIndentStreamStream :: !s } deriving (Show)
instance (Stream s m Char) => Stream (CharIndentStream s) m (Char, Indentation) where
uncons (CharIndentStream i s) = do
x <- uncons s
case x of
Nothing -> return Nothing
Just (c, cs) -> return (Just ((c, i), CharIndentStream (updateColumn i c) cs))
{-# INLINE updateColumn #-}
updateColumn :: Integral a => a -> Char -> a
updateColumn _ '\n' = 1
updateColumn i '\t' = i + 8 - ((i-1) `mod` 8)
updateColumn i _ = i + 1
{-# INLINE charIndentStreamParser #-}
charIndentStreamParser :: (Monad m) => ParsecT s u m t -> ParsecT (CharIndentStream s) u m (t, Indentation)
charIndentStreamParser p = mkPT $ \state ->
let go (Ok a state' e) = return (Ok (a, sourceColumn $ statePos state) (state' { stateInput = CharIndentStream (sourceColumn $ statePos state') (stateInput state') }) e)
go (Error e) = return (Error e)
in runParsecT p (state { stateInput = charIndentStreamStream (stateInput state) })
>>= consumed (return . Consumed . go) (return . Empty . go)
{-# INLINE consumed #-}
consumed :: (Monad m) => (a -> m b) -> (a -> m b) -> Consumed (m a) -> m b
consumed c _ (Consumed m) = m >>= c
consumed _ e (Empty m) = m >>= e
| lambdageek/indentation | indentation-parsec/src/Text/Parsec/Indentation/Char.hs | bsd-3-clause | 1,980 | 0 | 20 | 453 | 677 | 365 | 312 | 37 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.