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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-
Copyright 2016, Dominic Orchard, Andrew Rice, Mistral Contrastin, Matthew Danish
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.
-}
{-
This files gives an executable implementation of the model for
abstract stencil specifications. This model is used to drive both
the specification checking and program synthesis features.
-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE MultiWayIf #-}
module Camfort.Specification.Stencils.Model ( Interval(..)
, Bound(..)
, approxVec
, Offsets(..)
, UnionNF
, vecLength
, unfCompare
, optimise
, maximas
, Approximation(..)
, lowerBound, upperBound
, fromExact
, Multiplicity(..)
, Peelable(..)
) where
import qualified Control.Monad as CM
import Algebra.Lattice
import Data.Semigroup
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as S
import Data.Foldable
import Data.SBV
import Data.Data
import Data.List (sortBy, nub)
import Data.Maybe (fromJust)
import qualified Data.PartialOrd as PO
import qualified Camfort.Helpers.Vec as V
import System.IO.Unsafe
import Debug.Trace
-- Utility container
class Container a where
type MemberTyp a
type CompTyp a
member :: MemberTyp a -> a -> Bool
compile :: a -> (CompTyp a -> SBool)
--------------------------------------------------------------------------------
-- Arbitrary sets representing offsets
--------------------------------------------------------------------------------
data Offsets =
Offsets (S.Set Int64)
| SetOfIntegers
deriving Eq
instance Ord Offsets where
Offsets s `compare` Offsets s' = s `compare` s'
Offsets _ `compare` SetOfIntegers = LT
SetOfIntegers `compare` Offsets _ = GT
SetOfIntegers `compare` SetOfIntegers = EQ
instance Container Offsets where
type MemberTyp Offsets = Int64
type CompTyp Offsets = SInt64
member i (Offsets s) = i `S.member` s
member _ _ = True
compile (Offsets s) i = i `sElem` map fromIntegral (S.toList s)
compile SetOfIntegers _ = true
instance JoinSemiLattice Offsets where
(Offsets s) \/ (Offsets s') = Offsets $ s `S.union` s'
_ \/ _ = SetOfIntegers
instance MeetSemiLattice Offsets where
(Offsets s) /\ (Offsets s') = Offsets $ s `S.intersection` s'
off@Offsets{} /\ _ = off
_ /\ o = o
instance Lattice Offsets
instance BoundedJoinSemiLattice Offsets where
bottom = Offsets S.empty
instance BoundedMeetSemiLattice Offsets where
top = SetOfIntegers
instance BoundedLattice Offsets
--------------------------------------------------------------------------------
-- Interval as defined in the paper
--------------------------------------------------------------------------------
data Bound = Arbitrary | Standard
-- | Interval data structure assumes the following:
-- 1. The first num. param. is less than the second;
-- 2. For holed intervals, first num. param. <= 0 <= second num. param.;
data Interval a where
IntervArbitrary :: Int -> Int -> Interval Arbitrary
IntervInfiniteArbitrary :: Interval Arbitrary
IntervHoled :: Int64 -> Int64 -> Bool -> Interval Standard
IntervInfinite :: Interval Standard
deriving instance Eq (Interval a)
instance Show (Interval Standard) where
show IntervInfinite = "IntervInfinite"
show (IntervHoled lb up p) =
"Interv [" ++ show lb ++ "," ++ show up ++ "]^" ++ show p
approxInterv :: Interval Arbitrary -> Approximation (Interval Standard)
approxInterv (IntervArbitrary a b)
| a > b = error
"Interval condition violated: lower bound is bigger than the upper bound."
| a <= 0, b >= 0 = Exact $ IntervHoled a' b' True
| a <= -1, b == -1 = Exact $ IntervHoled a' 0 False
| a == 1, b >= 1 = Exact $ IntervHoled 0 b' False
| a > 1, b > 1 = Bound Nothing $ Just $ IntervHoled 0 b' False
| a < -1, b < -1 = Bound Nothing $ Just $ IntervHoled a' 0 False
| otherwise = error "Impossible: All posibilities are covered."
where
a' = fromIntegral a
b' = fromIntegral b
approxInterv IntervInfiniteArbitrary = Exact IntervInfinite
approxVec :: forall n .
V.Vec n (Interval Arbitrary)
-> Approximation (V.Vec n (Interval Standard))
approxVec v =
case findApproxIntervs stdVec of
([],_) -> Exact . fmap fromExact $ stdVec
_ -> Bound Nothing (Just $ upperBound <$> stdVec)
where
stdVec :: V.Vec n (Approximation (Interval Standard))
stdVec = fmap approxInterv v
findApproxIntervs :: forall n . V.Vec n (Approximation (Interval Standard))
-> ([ Int ], [ Int ])
findApproxIntervs v = findApproxIntervs' 0 v ([],[])
findApproxIntervs' :: forall n . Int
-> V.Vec n (Approximation (Interval Standard))
-> ([ Int ], [ Int ])
-> ([ Int ], [ Int ])
findApproxIntervs' _ V.Nil acc = acc
findApproxIntervs' i (V.Cons x xs) (bixs, eixs) =
findApproxIntervs' (i+1) xs $
case x of
Bound{} -> (i:bixs, eixs)
Exact{} -> (bixs, i:eixs)
instance Container (Interval Standard) where
type MemberTyp (Interval Standard) = Int64
type CompTyp (Interval Standard) = SInt64
member 0 (IntervHoled _ _ b) = b
member i (IntervHoled a b _) = i >= a && i <= b
member _ _ = True
compile (IntervHoled i1 i2 b) i
| b = inRange i range
| otherwise = inRange i range &&& i ./= 0
where
range = (fromIntegral i1, fromIntegral i2)
compile IntervInfinite _ = true
instance JoinSemiLattice (Interval Standard) where
(IntervHoled lb ub noHole) \/ (IntervHoled lb' ub' noHole') =
IntervHoled (min lb lb') (max ub ub') (noHole || noHole')
_ \/ _ = top
instance MeetSemiLattice (Interval Standard) where
(IntervHoled lb ub noHole) /\ (IntervHoled lb' ub' noHole') =
IntervHoled (max lb lb') (min ub ub') (noHole && noHole')
int@IntervHoled{} /\ _ = int
_ /\ int = int
instance Lattice (Interval Standard)
instance BoundedJoinSemiLattice (Interval Standard) where
bottom = IntervHoled 0 0 False
instance BoundedMeetSemiLattice (Interval Standard) where
top = IntervInfinite
instance BoundedLattice (Interval Standard)
--------------------------------------------------------------------------------
-- Union of cartesian products normal form
--------------------------------------------------------------------------------
type UnionNF n a = NE.NonEmpty (V.Vec n a)
vecLength :: UnionNF n a -> V.Natural n
vecLength = V.lengthN . NE.head
instance Container a => Container (UnionNF n a) where
type MemberTyp (UnionNF n a) = V.Vec n (MemberTyp a)
type CompTyp (UnionNF n a) = V.Vec n (CompTyp a)
member is = any (member' is)
where
member' is space = and $ V.zipWith member is space
compile spaces is = foldr1 (|||) $ NE.map (`compile'` is) spaces
where
compile' space is =
foldr' (\(set, i) -> (&&&) $ compile set i) true $ V.zip space is
instance JoinSemiLattice (UnionNF n a) where
oi \/ oi' = oi <> oi'
instance BoundedLattice a => MeetSemiLattice (UnionNF n a) where
(/\) = CM.liftM2 (V.zipWith (/\))
instance BoundedLattice a => Lattice (UnionNF n a)
unfCompare :: forall a b n . ( Container a, Container b
, MemberTyp a ~ Int64, MemberTyp b ~ Int64
, CompTyp a ~ SInt64, CompTyp b ~ SInt64
)
=> UnionNF n a -> UnionNF n b -> Ordering
unfCompare oi oi' = unsafePerformIO $ do
thmRes <- prove pred
case thmRes of
-- Tell the user if there was a hard proof error (e.g., if
-- z3 is not installed/accessible).
-- TODO: give more information
ThmResult (ProofError _ msgs) -> fail $ unlines msgs
_ ->
if modelExists thmRes
then do
ce <- counterExample thmRes
case V.fromList ce of
V.VecBox cev ->
case V.proveEqSize (NE.head oi) cev of
Just V.ReflEq ->
-- TODO: The second branch is defensive programming the
-- member check is not necessary unless the counter example
-- is bogus (it shouldn't be). Delete if it adversely
-- effects the performance.
if | cev `member` oi -> return GT
| cev `member` oi' -> return LT
| otherwise -> fail
"Impossible: counter example is in \
\neither of the operands"
Nothing -> fail
"Impossible: Counter example size doesn't \
\match the original vector size."
else "EQ branch" `trace` return EQ
where
counterExample :: ThmResult -> IO [ Int64 ]
counterExample thmRes =
case getModel thmRes of
Right (False, ce) -> return ce
Right (True, _) -> fail "Returned probable model."
Left str -> fail str
pred :: Predicate
pred = do
freeVars <- (mkFreeVars . dimensionality) oi :: Symbolic [ SInt64 ]
case V.fromList freeVars of
V.VecBox freeVarVec ->
case V.proveEqSize (NE.head oi) freeVarVec of
Just V.ReflEq -> return $
compile oi freeVarVec .== compile oi' freeVarVec
Nothing -> fail $
"Impossible: Free variables size doesn't match that of the " ++
"union parameter."
dimensionality = V.length . NE.head
--------------------------------------------------------------------------------
-- Optimise unions
--------------------------------------------------------------------------------
instance PO.PartialOrd Offsets where
(Offsets s) <= (Offsets s') = s <= s'
SetOfIntegers <= Offsets{} = False
_ <= SetOfIntegers = True
instance PO.PartialOrd (Interval Standard) where
(IntervHoled lb ub p) <= (IntervHoled lb' ub' p') =
(p' || not p) && lb >= lb' && ub <= ub'
IntervInfinite <= IntervHoled{} = False
_ <= IntervInfinite = True
instance PO.PartialOrd a => PO.PartialOrd (V.Vec n a) where
v <= v' = and $ V.zipWith (PO.<=) v v'
optimise :: UnionNF n (Interval Standard) -> UnionNF n (Interval Standard)
optimise = NE.fromList . maximas . fixedPointUnion . NE.toList
where
fixedPointUnion unf =
let unf' = unionLemma . maximas $ unf
in if unf' == unf then unf' else fixedPointUnion unf'
sensibleGroupBy :: Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> [ a ]
-> [ [ a ] ]
sensibleGroupBy ord p l = nub . map (\el -> sortBy ord . filter (p el) $ l) $ l
maximas :: [ V.Vec n (Interval Standard) ] -> [ V.Vec n (Interval Standard) ]
maximas = nub
. fmap (head . PO.maxima)
. sensibleGroupBy ord (PO.<=)
where
ord a b = fromJust $ a `PO.compare` b
-- | Union lemma says that if we have a product of intervals (as defined in
-- the paper) and we union two that agrees in each dimension except one.
-- The union is again a product of intervals that agrees with the original
-- dimensions in all dimensions except the original differing one. At that
-- point it is the union of intervals, which is itself still an interval.
unionLemma :: [ V.Vec n (Interval Standard) ] -> [ V.Vec n (Interval Standard) ]
unionLemma = map (foldr1 (V.zipWith (\/)))
. sensibleGroupBy (\a b -> if a == b then EQ else LT) agreeButOne
where
-- This function returns true if two vectors agree at all points but one.
-- It also holds if two vectors are identical.
agreeButOne :: Eq a => V.Vec n a -> V.Vec n a -> Bool
agreeButOne = go False
where
go :: Eq a => Bool -> V.Vec n a -> V.Vec n a -> Bool
go _ V.Nil V.Nil = True
go False (V.Cons x xs) (V.Cons y ys)
| x == y = go False xs ys
| otherwise = go True xs ys
go True (V.Cons x xs) (V.Cons y ys)
| x == y = go True xs ys
| otherwise = False
--------------------------------------------------------------------------------
-- Injections for multiplicity and exactness
--------------------------------------------------------------------------------
data Approximation a = Exact a | Bound (Maybe a) (Maybe a)
deriving (Eq, Show, Functor, Foldable, Traversable, Data, Typeable)
fromExact :: Approximation a -> a
fromExact (Exact a) = a
fromExact _ = error "Can't retrieve from bounded as if it was exact."
lowerBound :: Approximation a -> a
lowerBound (Bound (Just a) _) = a
lowerBound (Bound Nothing _) = error "Approximation doesn't have a lower bound."
lowerBound (Exact a) = a
upperBound :: Approximation a -> a
upperBound (Bound _ (Just a)) = a
upperBound (Bound _ Nothing) = error "Approximation doesn't have a upper bound."
upperBound (Exact a) = a
class Peelable a where
type CoreTyp a
peel :: a -> CoreTyp a
data Multiplicity a = Mult a | Once a
deriving (Eq, Show, Functor, Foldable, Traversable, Data, Typeable)
instance Peelable (Multiplicity a) where
type CoreTyp (Multiplicity a) = a
peel (Mult a) = a
peel (Once a) = a
{-
data Approximation a = Exact a | Lower a | Upper a
deriving (Eq, Show, Functor, Data, Typeable)
instance Peelable Approximation where
peel (Exact a) = a
peel (Lower a) = a
peel (Upper a) = a
-}
| mrd/camfort | src/Camfort/Specification/Stencils/Model.hs | apache-2.0 | 14,669 | 0 | 24 | 4,122 | 3,974 | 2,043 | 1,931 | 264 | 9 |
module Main where
import Control.Concurrent (threadDelay)
import Control.Lens
import System.Exit (exitWith, ExitCode(..))
import X
import Graphics
import MenuConf
strs = ["räksmörgåßαr", "hello, world!", "conjure me", "and more"]
main :: IO ()
main =
-- withXConf sets up the necessary basic X configuration
-- withMenuBar sets up the X window for the menu bar
withXConf . withMenuBar $
run strs (MenuConf "#000000" "#ffff77")
run :: [String] -> MenuConf -> WinConf -> IO ()
run str mc wc = do
drawMenu mc wc str
ev <- parseXEvent (wc^.xc.dpy) (xicGetKeySym (wc^.xic))
case ev of
Just Abort -> return ()
_ -> run str mc wc
| kqr/hmenu | Main.hs | bsd-2-clause | 667 | 0 | 12 | 141 | 215 | 115 | 100 | -1 | -1 |
-- http://www.codewars.com/kata/5520714decb43308ea000083
module Codewars.Kata.NthRoot where
root :: Double -> Double -> Double
root x n = exp $ log x / n | Bodigrim/katas | src/haskell/B-Nth-Root-of-a-Number.hs | bsd-2-clause | 154 | 0 | 7 | 22 | 42 | 23 | 19 | 3 | 1 |
module Substitution where
import Syntax
import Control.Arrow (first, second)
import qualified Data.Map as M
import qualified Data.Set as S
type InScopeSet = (S.Set Var, S.Set CoVar)
emptyInScopeSet :: InScopeSet
emptyInScopeSet = (S.empty, S.empty)
varInInScopeSet :: InScopeSet -> Var -> Bool
varInInScopeSet = flip S.member . fst
coVarInInScopeSet :: InScopeSet -> CoVar -> Bool
coVarInInScopeSet = flip S.member . snd
extendInScopeSetVar :: InScopeSet -> Var -> InScopeSet
extendInScopeSetVar iss x = first (S.insert x) iss
extendInScopeSetCoVar :: InScopeSet -> CoVar -> InScopeSet
extendInScopeSetCoVar iss a = second (S.insert a) iss
data Subst = Subst {
subst_terms :: M.Map Var Term,
subst_coterms :: M.Map CoVar CoTerm,
subst_inscope :: InScopeSet
}
emptySubst :: InScopeSet -> Subst
emptySubst iss = Subst M.empty M.empty iss
termSubst :: Var -> Term -> Subst
termSubst = extendSubstTerm (emptySubst emptyInScopeSet)
coTermSubst :: CoVar -> CoTerm -> Subst
coTermSubst = extendSubstCoTerm (emptySubst emptyInScopeSet)
extendSubstTerm :: Subst -> Var -> Term -> Subst
extendSubstTerm s x m = s { subst_terms = M.insert x m (subst_terms s) }
extendSubstCoTerm :: Subst -> CoVar -> CoTerm -> Subst
extendSubstCoTerm s a k = s { subst_coterms = M.insert a k (subst_coterms s) }
uniqAway :: String -> S.Set String -> String
uniqAway x iss = go 0
where go n | x' `S.notMember` iss = x'
| otherwise = go (n + 1)
where x' = x ++ show n
substAnyBinder :: (InScopeSet -> S.Set String) -> (InScopeSet -> S.Set String -> InScopeSet)
-> (Subst -> M.Map String a) -> (Subst -> M.Map String a -> Subst)
-> (String -> a)
-> Subst -> String -> (Subst, String)
substAnyBinder get set get_map set_map inj s x = (s' { subst_inscope = set iss (S.insert x' my_iss) }, x')
where
iss = subst_inscope s
my_iss = get iss
(s', x') | x `S.member` my_iss
, let x' = uniqAway x my_iss = (set_map s (M.insert x (inj x') (get_map s)), x')
| otherwise = (set_map s (M.delete x (get_map s)), x)
substBinder :: Subst -> Var -> (Subst, Var)
substBinder = substAnyBinder fst (\iss set -> (set, snd iss)) subst_terms (\s m -> s { subst_terms = m }) Var
substCoBinder :: Subst -> CoVar -> (Subst, CoVar)
substCoBinder = substAnyBinder snd (\iss set -> (fst iss, set)) subst_coterms (\s m -> s { subst_coterms = m }) CoVar
substVar :: Subst -> Var -> Term
substVar s x = M.findWithDefault (Var x) x (subst_terms s)
substCoVar :: Subst -> CoVar -> CoTerm
substCoVar s a = M.findWithDefault (CoVar a) a (subst_coterms s)
substTerm :: Subst -> Term -> Term
substTerm subst m = case m of
Var x -> substVar subst x
Data m lr -> Data (substTerm subst m) lr
Tup m n -> Tup (substTerm subst m) (substTerm subst n)
Not k -> Not (substCoTerm subst k)
Lam x m -> Lam x' (substTerm subst' m)
where (subst', x') = substBinder subst x
Bind s a -> Bind (substStmt subst' s) a'
where (subst', a') = substCoBinder subst a
Fix x m -> Fix x' (substTerm subst' m)
where (subst', x') = substBinder subst x
substCoTerm :: Subst -> CoTerm -> CoTerm
substCoTerm subst k = case k of
CoVar a -> substCoVar subst a
CoData k l -> CoData (substCoTerm subst k) (substCoTerm subst l)
CoTup i k -> CoTup i (substCoTerm subst k)
CoNot m -> CoNot (substTerm subst m)
CoLam m k -> CoLam (substTerm subst m) (substCoTerm subst k)
CoBind x s -> CoBind x' (substStmt subst' s)
where (subst', x') = substBinder subst x
substStmt :: Subst -> Stmt -> Stmt
substStmt subst (m `Cut` k) = substTerm subst m `Cut` substCoTerm subst k
| batterseapower/dual-calculus | Substitution.hs | bsd-3-clause | 3,693 | 2 | 19 | 844 | 1,519 | 782 | 737 | 76 | 7 |
module Dir.Reuse(reused) where
import Dir.Reexport
import Dir.TypesOnly
import Foo.Used()
reused = (0 :: Word8) `seq` Ctor1 1 1
| ndmitchell/weeder | test/foo/src/Dir/Reuse.hs | bsd-3-clause | 131 | 0 | 6 | 21 | 51 | 31 | 20 | 5 | 1 |
module Main where
import ShakespeareTrie
main :: IO ()
main = someFunc
| krisajenkins/Shakespeare-Trie | app/Main.hs | bsd-3-clause | 73 | 0 | 6 | 14 | 22 | 13 | 9 | 4 | 1 |
import Lib
import Test as T
testEq :: Value -> Value -> Result
testEq input expected = T.test (show input) ((\(Prog value _) -> value ) (eval (Prog input defaultContext)) == expected)
main :: IO ()
main = T.runTests
[ testEq (Var "I") (Lambda "x" (Var "x"))
, testEq (Var "K") (Lambda "x" (Lambda "y" (Var "x")))
, testEq (Apply (Apply (Var "K") (Var "I")) (Var "I")) (Lambda "x" (Var "x"))
, testEq (Apply (Apply (Apply (Var "S") (Var "K")) (Var "K")) (Var "I")) (Lambda "x" (Var "x"))
]
| sleexyz/untyped | test/Spec.hs | bsd-3-clause | 506 | 0 | 15 | 106 | 295 | 150 | 145 | 10 | 1 |
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2012
--
-- The GHC API
--
-- -----------------------------------------------------------------------------
module GHC (
-- * Initialisation
defaultErrorHandler,
defaultCleanupHandler,
prettyPrintGhcErrors,
installSignalHandlers,
withCleanupSession,
-- * GHC Monad
Ghc, GhcT, GhcMonad(..), HscEnv,
runGhc, runGhcT, initGhcMonad,
gcatch, gbracket, gfinally,
printException,
handleSourceError,
needsTemplateHaskell,
-- * Flags and settings
DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt,
GhcMode(..), GhcLink(..), defaultObjectTarget,
parseDynamicFlags,
getSessionDynFlags, setSessionDynFlags,
getProgramDynFlags, setProgramDynFlags,
getInteractiveDynFlags, setInteractiveDynFlags,
parseStaticFlags,
-- * Targets
Target(..), TargetId(..), Phase,
setTargets,
getTargets,
addTarget,
removeTarget,
guessTarget,
-- * Loading\/compiling the program
depanal,
load, LoadHowMuch(..), InteractiveImport(..),
SuccessFlag(..), succeeded, failed,
defaultWarnErrLogger, WarnErrLogger,
workingDirectoryChanged,
parseModule, typecheckModule, desugarModule, loadModule,
ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
TypecheckedSource, ParsedSource, RenamedSource, -- ditto
TypecheckedMod, ParsedMod,
moduleInfo, renamedSource, typecheckedSource,
parsedSource, coreModule,
-- ** Compiling to Core
CoreModule(..),
compileToCoreModule, compileToCoreSimplified,
-- * Inspecting the module structure of the program
ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
getModSummary,
getModuleGraph,
isLoaded,
topSortModuleGraph,
-- * Inspecting modules
ModuleInfo,
getModuleInfo,
modInfoTyThings,
modInfoTopLevelScope,
modInfoExports,
modInfoExportsWithSelectors,
modInfoInstances,
modInfoIsExportedName,
modInfoLookupName,
modInfoIface,
modInfoSafe,
lookupGlobalName,
findGlobalAnns,
mkPrintUnqualifiedForModule,
ModIface(..),
SafeHaskellMode(..),
-- * Querying the environment
-- packageDbModules,
-- * Printing
PrintUnqualified, alwaysQualify,
-- * Interactive evaluation
#ifdef GHCI
-- ** Executing statements
execStmt, ExecOptions(..), execOptions, ExecResult(..),
resumeExec,
-- ** Adding new declarations
runDecls, runDeclsWithLocation,
-- ** Get/set the current context
parseImportDecl,
setContext, getContext,
setGHCiMonad, getGHCiMonad,
#endif
-- ** Inspecting the current context
getBindings, getInsts, getPrintUnqual,
findModule, lookupModule,
#ifdef GHCI
isModuleTrusted, moduleTrustReqs,
getNamesInScope,
getRdrNamesInScope,
getGRE,
moduleIsInterpreted,
getInfo,
showModule,
isModuleInterpreted,
-- ** Inspecting types and kinds
exprType, TcRnExprMode(..),
typeKind,
-- ** Looking up a Name
parseName,
#endif
lookupName,
#ifdef GHCI
-- ** Compiling expressions
HValue, parseExpr, compileParsedExpr,
InteractiveEval.compileExpr, dynCompileExpr,
ForeignHValue,
compileExprRemote, compileParsedExprRemote,
-- ** Other
runTcInteractive, -- Desired by some clients (Trac #8878)
isStmt, hasImport, isImport, isDecl,
-- ** The debugger
SingleStep(..),
Resume(..),
History(historyBreakInfo, historyEnclosingDecls),
GHC.getHistorySpan, getHistoryModule,
abandon, abandonAll,
getResumeContext,
GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
modInfoModBreaks,
ModBreaks(..), BreakIndex,
BreakInfo(breakInfo_number, breakInfo_module),
InteractiveEval.back,
InteractiveEval.forward,
-- ** Deprecated API
RunResult(..),
runStmt, runStmtWithLocation,
resume,
#endif
-- * Abstract syntax elements
-- ** Packages
UnitId,
-- ** Modules
Module, mkModule, pprModule, moduleName, moduleUnitId,
ModuleName, mkModuleName, moduleNameString,
-- ** Names
Name,
isExternalName, nameModule, pprParenSymName, nameSrcSpan,
NamedThing(..),
RdrName(Qual,Unqual),
-- ** Identifiers
Id, idType,
isImplicitId, isDeadBinder,
isExportedId, isLocalId, isGlobalId,
isRecordSelector,
isPrimOpId, isFCallId, isClassOpId_maybe,
isDataConWorkId, idDataCon,
isBottomingId, isDictonaryId,
recordSelectorTyCon,
-- ** Type constructors
TyCon,
tyConTyVars, tyConDataCons, tyConArity,
isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon,
isPrimTyCon, isFunTyCon,
isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon,
tyConClass_maybe,
synTyConRhs_maybe, synTyConDefn_maybe, tyConKind,
-- ** Type variables
TyVar,
alphaTyVars,
-- ** Data constructors
DataCon,
dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
dataConIsInfix, isVanillaDataCon, dataConUserType,
dataConSrcBangs,
StrictnessMark(..), isMarkedStrict,
-- ** Classes
Class,
classMethods, classSCTheta, classTvsFds, classATs,
pprFundeps,
-- ** Instances
ClsInst,
instanceDFunId,
pprInstance, pprInstanceHdr,
pprFamInst,
FamInst,
-- ** Types and Kinds
Type, splitForAllTys, funResultTy,
pprParendType, pprTypeApp,
Kind,
PredType,
ThetaType, pprForAll, pprForAllImplicit, pprThetaArrowTy,
-- ** Entities
TyThing(..),
-- ** Syntax
module HsSyn, -- ToDo: remove extraneous bits
-- ** Fixities
FixityDirection(..),
defaultFixity, maxPrecedence,
negateFixity,
compareFixity,
-- ** Source locations
SrcLoc(..), RealSrcLoc,
mkSrcLoc, noSrcLoc,
srcLocFile, srcLocLine, srcLocCol,
SrcSpan(..), RealSrcSpan,
mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
srcSpanStart, srcSpanEnd,
srcSpanFile,
srcSpanStartLine, srcSpanEndLine,
srcSpanStartCol, srcSpanEndCol,
-- ** Located
GenLocated(..), Located,
-- *** Constructing Located
noLoc, mkGeneralLocated,
-- *** Deconstructing Located
getLoc, unLoc,
-- *** Combining and comparing Located values
eqLocated, cmpLocated, combineLocs, addCLoc,
leftmost_smallest, leftmost_largest, rightmost,
spans, isSubspanOf,
-- * Exceptions
GhcException(..), showGhcException,
-- * Token stream manipulations
Token,
getTokenStream, getRichTokenStream,
showRichTokenStream, addSourceToTokens,
-- * Pure interface to the parser
parser,
-- * API Annotations
ApiAnns,AnnKeywordId(..),AnnotationComment(..),
getAnnotation, getAndRemoveAnnotation,
getAnnotationComments, getAndRemoveAnnotationComments,
unicodeAnn,
-- * Miscellaneous
--sessionHscEnv,
cyclicModuleErr,
) where
{-
ToDo:
* inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
* what StaticFlags should we expose, if any?
-}
#include "HsVersions.h"
#ifdef GHCI
import ByteCodeTypes
import InteractiveEval
import InteractiveEvalTypes
import TcRnDriver ( runTcInteractive )
import GHCi
import GHCi.RemoteTypes
#endif
import PprTyThing ( pprFamInst )
import HscMain
import GhcMake
import DriverPipeline ( compileOne' )
import GhcMonad
import TcRnMonad ( finalSafeMode, fixSafeInstances )
import TcRnTypes
import Packages
import NameSet
import RdrName
import HsSyn
import Type hiding( typeKind )
import TcType hiding( typeKind )
import Id
import TysPrim ( alphaTyVars )
import TyCon
import Class
import DataCon
import Name hiding ( varName )
import Avail
import InstEnv
import FamInstEnv ( FamInst )
import SrcLoc
import CoreSyn
import TidyPgm
import DriverPhases ( Phase(..), isHaskellSrcFilename )
import Finder
import HscTypes
import DynFlags
import StaticFlags
import SysTools
import Annotations
import Module
import Panic
import Platform
import Bag ( unitBag )
import ErrUtils
import MonadUtils
import Util
import StringBuffer
import Outputable
import BasicTypes
import Maybes ( expectJust )
import FastString
import qualified Parser
import Lexer
import ApiAnnotation
import qualified GHC.LanguageExtensions as LangExt
import System.Directory ( doesFileExist )
import Data.Maybe
import Data.List ( find )
import Data.Time
import Data.Typeable ( Typeable )
import Data.Word ( Word8 )
import Control.Monad
import System.Exit ( exitWith, ExitCode(..) )
import Exception
import Data.IORef
import System.FilePath
import System.IO
import Prelude hiding (init)
-- %************************************************************************
-- %* *
-- Initialisation: exception handlers
-- %* *
-- %************************************************************************
-- | Install some default exception handlers and run the inner computation.
-- Unless you want to handle exceptions yourself, you should wrap this around
-- the top level of your program. The default handlers output the error
-- message(s) to stderr and exit cleanly.
defaultErrorHandler :: (ExceptionMonad m)
=> FatalMessager -> FlushOut -> m a -> m a
defaultErrorHandler fm (FlushOut flushOut) inner =
-- top-level exception handler: any unrecognised exception is a compiler bug.
ghandle (\exception -> liftIO $ do
flushOut
case fromException exception of
-- an IO exception probably isn't our fault, so don't panic
Just (ioe :: IOException) ->
fatalErrorMsg'' fm (show ioe)
_ -> case fromException exception of
Just UserInterrupt ->
-- Important to let this one propagate out so our
-- calling process knows we were interrupted by ^C
liftIO $ throwIO UserInterrupt
Just StackOverflow ->
fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it"
_ -> case fromException exception of
Just (ex :: ExitCode) -> liftIO $ throwIO ex
_ ->
fatalErrorMsg'' fm
(show (Panic (show exception)))
exitWith (ExitFailure 1)
) $
-- error messages propagated as exceptions
handleGhcException
(\ge -> liftIO $ do
flushOut
case ge of
Signal _ -> exitWith (ExitFailure 1)
_ -> do fatalErrorMsg'' fm (show ge)
exitWith (ExitFailure 1)
) $
inner
-- | This function is no longer necessary, cleanup is now done by
-- runGhc/runGhcT.
{-# DEPRECATED defaultCleanupHandler "Cleanup is now done by runGhc/runGhcT" #-}
defaultCleanupHandler :: (ExceptionMonad m) => DynFlags -> m a -> m a
defaultCleanupHandler _ m = m
where _warning_suppression = m `gonException` undefined
-- %************************************************************************
-- %* *
-- The Ghc Monad
-- %* *
-- %************************************************************************
-- | Run function for the 'Ghc' monad.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
--
-- Any errors not handled inside the 'Ghc' action are propagated as IO
-- exceptions.
runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> Ghc a -- ^ The action to perform.
-> IO a
runGhc mb_top_dir ghc = do
ref <- newIORef (panic "empty session")
let session = Session ref
flip unGhc session $ do
liftIO installSignalHandlers -- catch ^C
initGhcMonad mb_top_dir
withCleanupSession ghc
-- XXX: unregister interrupt handlers here?
-- | Run function for 'GhcT' monad transformer.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
runGhcT :: ExceptionMonad m =>
Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> GhcT m a -- ^ The action to perform.
-> m a
runGhcT mb_top_dir ghct = do
ref <- liftIO $ newIORef (panic "empty session")
let session = Session ref
flip unGhcT session $ do
liftIO installSignalHandlers -- catch ^C
initGhcMonad mb_top_dir
withCleanupSession ghct
withCleanupSession :: GhcMonad m => m a -> m a
withCleanupSession ghc = ghc `gfinally` cleanup
where
cleanup = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
cleanTempFiles dflags
cleanTempDirs dflags
#ifdef GHCI
stopIServ hsc_env -- shut down the IServ
#endif
-- exceptions will be blocked while we clean the temporary files,
-- so there shouldn't be any difficulty if we receive further
-- signals.
-- | Initialise a GHC session.
--
-- If you implement a custom 'GhcMonad' you must call this function in the
-- monad run function. It will initialise the session variable and clear all
-- warnings.
--
-- The first argument should point to the directory where GHC's library files
-- reside. More precisely, this should be the output of @ghc --print-libdir@
-- of the version of GHC the module using this API is compiled with. For
-- portability, you should use the @ghc-paths@ package, available at
-- <http://hackage.haskell.org/package/ghc-paths>.
initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
initGhcMonad mb_top_dir
= do { env <- liftIO $
do { initStaticOpts
; mySettings <- initSysTools mb_top_dir
; dflags <- initDynFlags (defaultDynFlags mySettings)
; checkBrokenTablesNextToCode dflags
; setUnsafeGlobalDynFlags dflags
-- c.f. DynFlags.parseDynamicFlagsFull, which
-- creates DynFlags and sets the UnsafeGlobalDynFlags
; newHscEnv dflags }
; setSession env }
-- | The binutils linker on ARM emits unnecessary R_ARM_COPY relocations which
-- breaks tables-next-to-code in dynamically linked modules. This
-- check should be more selective but there is currently no released
-- version where this bug is fixed.
-- See https://sourceware.org/bugzilla/show_bug.cgi?id=16177 and
-- https://ghc.haskell.org/trac/ghc/ticket/4210#comment:29
checkBrokenTablesNextToCode :: MonadIO m => DynFlags -> m ()
checkBrokenTablesNextToCode dflags
= do { broken <- checkBrokenTablesNextToCode' dflags
; when broken
$ do { _ <- liftIO $ throwIO $ mkApiErr dflags invalidLdErr
; fail "unsupported linker"
}
}
where
invalidLdErr = text "Tables-next-to-code not supported on ARM" <+>
text "when using binutils ld (please see:" <+>
text "https://sourceware.org/bugzilla/show_bug.cgi?id=16177)"
checkBrokenTablesNextToCode' :: MonadIO m => DynFlags -> m Bool
checkBrokenTablesNextToCode' dflags
| not (isARM arch) = return False
| WayDyn `notElem` ways dflags = return False
| not (tablesNextToCode dflags) = return False
| otherwise = do
linkerInfo <- liftIO $ getLinkerInfo dflags
case linkerInfo of
GnuLD _ -> return True
_ -> return False
where platform = targetPlatform dflags
arch = platformArch platform
-- %************************************************************************
-- %* *
-- Flags & settings
-- %* *
-- %************************************************************************
-- $DynFlags
--
-- The GHC session maintains two sets of 'DynFlags':
--
-- * The "interactive" @DynFlags@, which are used for everything
-- related to interactive evaluation, including 'runStmt',
-- 'runDecls', 'exprType', 'lookupName' and so on (everything
-- under \"Interactive evaluation\" in this module).
--
-- * The "program" @DynFlags@, which are used when loading
-- whole modules with 'load'
--
-- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the
-- interactive @DynFlags@.
--
-- 'setProgramDynFlags', 'getProgramDynFlags' work with the
-- program @DynFlags@.
--
-- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags'
-- retrieves the program @DynFlags@ (for backwards compatibility).
-- | Updates both the interactive and program DynFlags in a Session.
-- This also reads the package database (unless it has already been
-- read), and prepares the compilers knowledge about packages. It can
-- be called again to load new packages: just add new package flags to
-- (packageFlags dflags).
--
-- Returns a list of new packages that may need to be linked in using
-- the dynamic linker (see 'linkPackages') as a result of new package
-- flags. If you are not doing linking or doing static linking, you
-- can ignore the list of packages returned.
--
setSessionDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId]
setSessionDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags''
, hsc_IC = (hsc_IC h){ ic_dflags = dflags'' } }
invalidateModSummaryCache
return preload
-- | Sets the program 'DynFlags'.
setProgramDynFlags :: GhcMonad m => DynFlags -> m [InstalledUnitId]
setProgramDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
(dflags'', preload) <- liftIO $ initPackages dflags'
modifySession $ \h -> h{ hsc_dflags = dflags'' }
invalidateModSummaryCache
return preload
-- When changing the DynFlags, we want the changes to apply to future
-- loads, but without completely discarding the program. But the
-- DynFlags are cached in each ModSummary in the hsc_mod_graph, so
-- after a change to DynFlags, the changes would apply to new modules
-- but not existing modules; this seems undesirable.
--
-- Furthermore, the GHC API client might expect that changing
-- log_action would affect future compilation messages, but for those
-- modules we have cached ModSummaries for, we'll continue to use the
-- old log_action. This is definitely wrong (#7478).
--
-- Hence, we invalidate the ModSummary cache after changing the
-- DynFlags. We do this by tweaking the date on each ModSummary, so
-- that the next downsweep will think that all the files have changed
-- and preprocess them again. This won't necessarily cause everything
-- to be recompiled, because by the time we check whether we need to
-- recopmile a module, we'll have re-summarised the module and have a
-- correct ModSummary.
--
invalidateModSummaryCache :: GhcMonad m => m ()
invalidateModSummaryCache =
modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) }
where
inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) }
-- | Returns the program 'DynFlags'.
getProgramDynFlags :: GhcMonad m => m DynFlags
getProgramDynFlags = getSessionDynFlags
-- | Set the 'DynFlags' used to evaluate interactive expressions.
-- Note: this cannot be used for changes to packages. Use
-- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the
-- 'pkgState' into the interactive @DynFlags@.
setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
setInteractiveDynFlags dflags = do
dflags' <- checkNewDynFlags dflags
modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags' }}
-- | Get the 'DynFlags' used to evaluate interactive expressions.
getInteractiveDynFlags :: GhcMonad m => m DynFlags
getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h))
parseDynamicFlags :: MonadIO m =>
DynFlags -> [Located String]
-> m (DynFlags, [Located String], [Located String])
parseDynamicFlags = parseDynamicFlagsCmdLine
-- | Checks the set of new DynFlags for possibly erroneous option
-- combinations when invoking 'setSessionDynFlags' and friends, and if
-- found, returns a fixed copy (if possible).
checkNewDynFlags :: MonadIO m => DynFlags -> m DynFlags
checkNewDynFlags dflags = do
-- See Note [DynFlags consistency]
let (dflags', warnings) = makeDynFlagsConsistent dflags
liftIO $ handleFlagWarnings dflags warnings
return dflags'
-- %************************************************************************
-- %* *
-- Setting, getting, and modifying the targets
-- %* *
-- %************************************************************************
-- ToDo: think about relative vs. absolute file paths. And what
-- happens when the current directory changes.
-- | Sets the targets for this session. Each target may be a module name
-- or a filename. The targets correspond to the set of root modules for
-- the program\/library. Unloading the current program is achieved by
-- setting the current set of targets to be empty, followed by 'load'.
setTargets :: GhcMonad m => [Target] -> m ()
setTargets targets = modifySession (\h -> h{ hsc_targets = targets })
-- | Returns the current set of targets
getTargets :: GhcMonad m => m [Target]
getTargets = withSession (return . hsc_targets)
-- | Add another target.
addTarget :: GhcMonad m => Target -> m ()
addTarget target
= modifySession (\h -> h{ hsc_targets = target : hsc_targets h })
-- | Remove a target
removeTarget :: GhcMonad m => TargetId -> m ()
removeTarget target_id
= modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) })
where
filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ]
-- | Attempts to guess what Target a string refers to. This function
-- implements the @--make@/GHCi command-line syntax for filenames:
--
-- - if the string looks like a Haskell source filename, then interpret it
-- as such
--
-- - if adding a .hs or .lhs suffix yields the name of an existing file,
-- then use that
--
-- - otherwise interpret the string as a module name
--
guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target
guessTarget str (Just phase)
= return (Target (TargetFile str (Just phase)) True Nothing)
guessTarget str Nothing
| isHaskellSrcFilename file
= return (target (TargetFile file Nothing))
| otherwise
= do exists <- liftIO $ doesFileExist hs_file
if exists
then return (target (TargetFile hs_file Nothing))
else do
exists <- liftIO $ doesFileExist lhs_file
if exists
then return (target (TargetFile lhs_file Nothing))
else do
if looksLikeModuleName file
then return (target (TargetModule (mkModuleName file)))
else do
dflags <- getDynFlags
liftIO $ throwGhcExceptionIO
(ProgramError (showSDoc dflags $
text "target" <+> quotes (text file) <+>
text "is not a module name or a source file"))
where
(file,obj_allowed)
| '*':rest <- str = (rest, False)
| otherwise = (str, True)
hs_file = file <.> "hs"
lhs_file = file <.> "lhs"
target tid = Target tid obj_allowed Nothing
-- | Inform GHC that the working directory has changed. GHC will flush
-- its cache of module locations, since it may no longer be valid.
--
-- Note: Before changing the working directory make sure all threads running
-- in the same session have stopped. If you change the working directory,
-- you should also unload the current program (set targets to empty,
-- followed by load).
workingDirectoryChanged :: GhcMonad m => m ()
workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches)
-- %************************************************************************
-- %* *
-- Running phases one at a time
-- %* *
-- %************************************************************************
class ParsedMod m where
modSummary :: m -> ModSummary
parsedSource :: m -> ParsedSource
class ParsedMod m => TypecheckedMod m where
renamedSource :: m -> Maybe RenamedSource
typecheckedSource :: m -> TypecheckedSource
moduleInfo :: m -> ModuleInfo
tm_internals :: m -> (TcGblEnv, ModDetails)
-- ToDo: improvements that could be made here:
-- if the module succeeded renaming but not typechecking,
-- we can still get back the GlobalRdrEnv and exports, so
-- perhaps the ModuleInfo should be split up into separate
-- fields.
class TypecheckedMod m => DesugaredMod m where
coreModule :: m -> ModGuts
-- | The result of successful parsing.
data ParsedModule =
ParsedModule { pm_mod_summary :: ModSummary
, pm_parsed_source :: ParsedSource
, pm_extra_src_files :: [FilePath]
, pm_annotations :: ApiAnns }
-- See Note [Api annotations] in ApiAnnotation.hs
instance ParsedMod ParsedModule where
modSummary m = pm_mod_summary m
parsedSource m = pm_parsed_source m
-- | The result of successful typechecking. It also contains the parser
-- result.
data TypecheckedModule =
TypecheckedModule { tm_parsed_module :: ParsedModule
, tm_renamed_source :: Maybe RenamedSource
, tm_typechecked_source :: TypecheckedSource
, tm_checked_module_info :: ModuleInfo
, tm_internals_ :: (TcGblEnv, ModDetails)
}
instance ParsedMod TypecheckedModule where
modSummary m = modSummary (tm_parsed_module m)
parsedSource m = parsedSource (tm_parsed_module m)
instance TypecheckedMod TypecheckedModule where
renamedSource m = tm_renamed_source m
typecheckedSource m = tm_typechecked_source m
moduleInfo m = tm_checked_module_info m
tm_internals m = tm_internals_ m
-- | The result of successful desugaring (i.e., translation to core). Also
-- contains all the information of a typechecked module.
data DesugaredModule =
DesugaredModule { dm_typechecked_module :: TypecheckedModule
, dm_core_module :: ModGuts
}
instance ParsedMod DesugaredModule where
modSummary m = modSummary (dm_typechecked_module m)
parsedSource m = parsedSource (dm_typechecked_module m)
instance TypecheckedMod DesugaredModule where
renamedSource m = renamedSource (dm_typechecked_module m)
typecheckedSource m = typecheckedSource (dm_typechecked_module m)
moduleInfo m = moduleInfo (dm_typechecked_module m)
tm_internals m = tm_internals_ (dm_typechecked_module m)
instance DesugaredMod DesugaredModule where
coreModule m = dm_core_module m
type ParsedSource = Located (HsModule RdrName)
type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
Maybe LHsDocString)
type TypecheckedSource = LHsBinds Id
-- NOTE:
-- - things that aren't in the output of the typechecker right now:
-- - the export list
-- - the imports
-- - type signatures
-- - type/data/newtype declarations
-- - class declarations
-- - instances
-- - extra things in the typechecker's output:
-- - default methods are turned into top-level decls.
-- - dictionary bindings
-- | Return the 'ModSummary' of a module with the given name.
--
-- The module must be part of the module graph (see 'hsc_mod_graph' and
-- 'ModuleGraph'). If this is not the case, this function will throw a
-- 'GhcApiError'.
--
-- This function ignores boot modules and requires that there is only one
-- non-boot module with the given name.
getModSummary :: GhcMonad m => ModuleName -> m ModSummary
getModSummary mod = do
mg <- liftM hsc_mod_graph getSession
case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of
[] -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph")
[ms] -> return ms
multiple -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple)
-- | Parse a module.
--
-- Throws a 'SourceError' on parse error.
parseModule :: GhcMonad m => ModSummary -> m ParsedModule
parseModule ms = do
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
hpm <- liftIO $ hscParse hsc_env_tmp ms
return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm)
(hpm_annotations hpm))
-- See Note [Api annotations] in ApiAnnotation.hs
-- | Typecheck and rename a parsed module.
--
-- Throws a 'SourceError' if either fails.
typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule
typecheckModule pmod = do
let ms = modSummary pmod
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
(tc_gbl_env, rn_info)
<- liftIO $ hscTypecheckRename hsc_env_tmp ms $
HsParsedModule { hpm_module = parsedSource pmod,
hpm_src_files = pm_extra_src_files pmod,
hpm_annotations = pm_annotations pmod }
details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env
safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env
return $
TypecheckedModule {
tm_internals_ = (tc_gbl_env, details),
tm_parsed_module = pmod,
tm_renamed_source = rn_info,
tm_typechecked_source = tcg_binds tc_gbl_env,
tm_checked_module_info =
ModuleInfo {
minf_type_env = md_types details,
minf_exports = md_exports details,
minf_rdr_env = Just (tcg_rdr_env tc_gbl_env),
minf_instances = fixSafeInstances safe $ md_insts details,
minf_iface = Nothing,
minf_safe = safe
#ifdef GHCI
,minf_modBreaks = emptyModBreaks
#endif
}}
-- | Desugar a typechecked module.
desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule
desugarModule tcm = do
let ms = modSummary tcm
let (tcg, _) = tm_internals tcm
hsc_env <- getSession
let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms }
guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg
return $
DesugaredModule {
dm_typechecked_module = tcm,
dm_core_module = guts
}
-- | Load a module. Input doesn't need to be desugared.
--
-- A module must be loaded before dependent modules can be typechecked. This
-- always includes generating a 'ModIface' and, depending on the
-- 'DynFlags.hscTarget', may also include code generation.
--
-- This function will always cause recompilation and will always overwrite
-- previous compilation results (potentially files on disk).
--
loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod
loadModule tcm = do
let ms = modSummary tcm
let mod = ms_mod_name ms
let loc = ms_location ms
let (tcg, _details) = tm_internals tcm
mb_linkable <- case ms_obj_date ms of
Just t | t > ms_hs_date ms -> do
l <- liftIO $ findObjectLinkable (ms_mod ms)
(ml_obj_file loc) t
return (Just l)
_otherwise -> return Nothing
let source_modified | isNothing mb_linkable = SourceModified
| otherwise = SourceUnmodified
-- we can't determine stability here
-- compile doesn't change the session
hsc_env <- getSession
mod_info <- liftIO $ compileOne' (Just tcg) Nothing
hsc_env ms 1 1 Nothing mb_linkable
source_modified
modifySession $ \e -> e{ hsc_HPT = addToHpt (hsc_HPT e) mod mod_info }
return tcm
-- %************************************************************************
-- %* *
-- Dealing with Core
-- %* *
-- %************************************************************************
-- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for
-- the 'GHC.compileToCoreModule' interface.
data CoreModule
= CoreModule {
-- | Module name
cm_module :: !Module,
-- | Type environment for types declared in this module
cm_types :: !TypeEnv,
-- | Declarations
cm_binds :: CoreProgram,
-- | Safe Haskell mode
cm_safe :: SafeHaskellMode
}
instance Outputable CoreModule where
ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb,
cm_safe = sf})
= text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te
$$ vcat (map ppr cb)
-- | This is the way to get access to the Core bindings corresponding
-- to a module. 'compileToCore' parses, typechecks, and
-- desugars the module, then returns the resulting Core module (consisting of
-- the module name, type declarations, and function declarations) if
-- successful.
compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule
compileToCoreModule = compileCore False
-- | Like compileToCoreModule, but invokes the simplifier, so
-- as to return simplified and tidied Core.
compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule
compileToCoreSimplified = compileCore True
compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule
compileCore simplify fn = do
-- First, set the target to the desired filename
target <- guessTarget fn Nothing
addTarget target
_ <- load LoadAllTargets
-- Then find dependencies
modGraph <- depanal [] True
case find ((== fn) . msHsFilePath) modGraph of
Just modSummary -> do
-- Now we have the module name;
-- parse, typecheck and desugar the module
mod_guts <- coreModule `fmap`
-- TODO: space leaky: call hsc* directly?
(desugarModule =<< typecheckModule =<< parseModule modSummary)
liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $
if simplify
then do
-- If simplify is true: simplify (hscSimplify), then tidy
-- (tidyProgram).
hsc_env <- getSession
simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts
tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts
return $ Left tidy_guts
else
return $ Right mod_guts
Nothing -> panic "compileToCoreModule: target FilePath not found in\
module dependency graph"
where -- two versions, based on whether we simplify (thus run tidyProgram,
-- which returns a (CgGuts, ModDetails) pair, or not (in which case
-- we just have a ModGuts.
gutsToCoreModule :: SafeHaskellMode
-> Either (CgGuts, ModDetails) ModGuts
-> CoreModule
gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule {
cm_module = cg_module cg,
cm_types = md_types md,
cm_binds = cg_binds cg,
cm_safe = safe_mode
}
gutsToCoreModule safe_mode (Right mg) = CoreModule {
cm_module = mg_module mg,
cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg))
(mg_tcs mg)
(mg_fam_insts mg),
cm_binds = mg_binds mg,
cm_safe = safe_mode
}
-- %************************************************************************
-- %* *
-- Inspecting the session
-- %* *
-- %************************************************************************
-- | Get the module dependency graph.
getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary
getModuleGraph = liftM hsc_mod_graph getSession
-- | Determines whether a set of modules requires Template Haskell.
--
-- Note that if the session's 'DynFlags' enabled Template Haskell when
-- 'depanal' was called, then each module in the returned module graph will
-- have Template Haskell enabled whether it is actually needed or not.
needsTemplateHaskell :: ModuleGraph -> Bool
needsTemplateHaskell ms =
any (xopt LangExt.TemplateHaskell . ms_hspp_opts) ms
-- | Return @True@ <==> module is loaded.
isLoaded :: GhcMonad m => ModuleName -> m Bool
isLoaded m = withSession $ \hsc_env ->
return $! isJust (lookupHpt (hsc_HPT hsc_env) m)
-- | Return the bindings for the current interactive session.
getBindings :: GhcMonad m => m [TyThing]
getBindings = withSession $ \hsc_env ->
return $ icInScopeTTs $ hsc_IC hsc_env
-- | Return the instances for the current interactive session.
getInsts :: GhcMonad m => m ([ClsInst], [FamInst])
getInsts = withSession $ \hsc_env ->
return $ ic_instances (hsc_IC hsc_env)
getPrintUnqual :: GhcMonad m => m PrintUnqualified
getPrintUnqual = withSession $ \hsc_env ->
return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
-- | Container for information about a 'Module'.
data ModuleInfo = ModuleInfo {
minf_type_env :: TypeEnv,
minf_exports :: [AvailInfo],
minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
minf_instances :: [ClsInst],
minf_iface :: Maybe ModIface,
minf_safe :: SafeHaskellMode
#ifdef GHCI
,minf_modBreaks :: ModBreaks
#endif
}
-- We don't want HomeModInfo here, because a ModuleInfo applies
-- to package modules too.
-- | Request information about a loaded 'Module'
getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X
getModuleInfo mdl = withSession $ \hsc_env -> do
let mg = hsc_mod_graph hsc_env
if mdl `elem` map ms_mod mg
then liftIO $ getHomeModuleInfo hsc_env mdl
else do
{- if isHomeModule (hsc_dflags hsc_env) mdl
then return Nothing
else -} liftIO $ getPackageModuleInfo hsc_env mdl
-- ToDo: we don't understand what the following comment means.
-- (SDM, 19/7/2011)
-- getPackageModuleInfo will attempt to find the interface, so
-- we don't want to call it for a home module, just in case there
-- was a problem loading the module and the interface doesn't
-- exist... hence the isHomeModule test here. (ToDo: reinstate)
getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
#ifdef GHCI
getPackageModuleInfo hsc_env mdl
= do eps <- hscEPS hsc_env
iface <- hscGetModuleInterface hsc_env mdl
let
avails = mi_exports iface
pte = eps_PTE eps
tys = [ ty | name <- concatMap availNames avails,
Just ty <- [lookupTypeEnv pte name] ]
--
return (Just (ModuleInfo {
minf_type_env = mkTypeEnv tys,
minf_exports = avails,
minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails,
minf_instances = error "getModuleInfo: instances for package module unimplemented",
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface,
minf_modBreaks = emptyModBreaks
}))
#else
-- bogusly different for non-GHCI (ToDo)
getPackageModuleInfo _hsc_env _mdl = do
return Nothing
#endif
getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
getHomeModuleInfo hsc_env mdl =
case lookupHpt (hsc_HPT hsc_env) (moduleName mdl) of
Nothing -> return Nothing
Just hmi -> do
let details = hm_details hmi
iface = hm_iface hmi
return (Just (ModuleInfo {
minf_type_env = md_types details,
minf_exports = md_exports details,
minf_rdr_env = mi_globals $! hm_iface hmi,
minf_instances = md_insts details,
minf_iface = Just iface,
minf_safe = getSafeMode $ mi_trust iface
#ifdef GHCI
,minf_modBreaks = getModBreaks hmi
#endif
}))
-- | The list of top-level entities defined in a module
modInfoTyThings :: ModuleInfo -> [TyThing]
modInfoTyThings minf = typeEnvElts (minf_type_env minf)
modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
modInfoTopLevelScope minf
= fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
modInfoExports :: ModuleInfo -> [Name]
modInfoExports minf = concatMap availNames $! minf_exports minf
modInfoExportsWithSelectors :: ModuleInfo -> [Name]
modInfoExportsWithSelectors minf = concatMap availNamesWithSelectors $! minf_exports minf
-- | Returns the instances defined by the specified module.
-- Warning: currently unimplemented for package modules.
modInfoInstances :: ModuleInfo -> [ClsInst]
modInfoInstances = minf_instances
modInfoIsExportedName :: ModuleInfo -> Name -> Bool
modInfoIsExportedName minf name = elemNameSet name (availsToNameSet (minf_exports minf))
mkPrintUnqualifiedForModule :: GhcMonad m =>
ModuleInfo
-> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X
mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do
return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
modInfoLookupName :: GhcMonad m =>
ModuleInfo -> Name
-> m (Maybe TyThing) -- XXX: returns a Maybe X
modInfoLookupName minf name = withSession $ \hsc_env -> do
case lookupTypeEnv (minf_type_env minf) name of
Just tyThing -> return (Just tyThing)
Nothing -> do
eps <- liftIO $ readIORef (hsc_EPS hsc_env)
return $! lookupType (hsc_dflags hsc_env)
(hsc_HPT hsc_env) (eps_PTE eps) name
modInfoIface :: ModuleInfo -> Maybe ModIface
modInfoIface = minf_iface
-- | Retrieve module safe haskell mode
modInfoSafe :: ModuleInfo -> SafeHaskellMode
modInfoSafe = minf_safe
#ifdef GHCI
modInfoModBreaks :: ModuleInfo -> ModBreaks
modInfoModBreaks = minf_modBreaks
#endif
isDictonaryId :: Id -> Bool
isDictonaryId id
= case tcSplitSigmaTy (idType id) of {
(_tvs, _theta, tau) -> isDictTy tau }
-- | Looks up a global name: that is, any top-level name in any
-- visible module. Unlike 'lookupName', lookupGlobalName does not use
-- the interactive context, and therefore does not require a preceding
-- 'setContext'.
lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupGlobalName name = withSession $ \hsc_env -> do
liftIO $ lookupTypeHscEnv hsc_env name
findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a]
findGlobalAnns deserialize target = withSession $ \hsc_env -> do
ann_env <- liftIO $ prepareAnnotations hsc_env Nothing
return (findAnns deserialize ann_env target)
#ifdef GHCI
-- | get the GlobalRdrEnv for a session
getGRE :: GhcMonad m => m GlobalRdrEnv
getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
#endif
-- -----------------------------------------------------------------------------
{- ToDo: Move the primary logic here to compiler/main/Packages.hs
-- | Return all /external/ modules available in the package database.
-- Modules from the current session (i.e., from the 'HomePackageTable') are
-- not included. This includes module names which are reexported by packages.
packageDbModules :: GhcMonad m =>
Bool -- ^ Only consider exposed packages.
-> m [Module]
packageDbModules only_exposed = do
dflags <- getSessionDynFlags
let pkgs = eltsUFM (pkgIdMap (pkgState dflags))
return $
[ mkModule pid modname
| p <- pkgs
, not only_exposed || exposed p
, let pid = packageConfigId p
, modname <- exposedModules p
++ map exportName (reexportedModules p) ]
-}
-- -----------------------------------------------------------------------------
-- Misc exported utils
dataConType :: DataCon -> Type
dataConType dc = idType (dataConWrapId dc)
-- | print a 'NamedThing', adding parentheses if the name is an operator.
pprParenSymName :: NamedThing a => a -> SDoc
pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
-- ----------------------------------------------------------------------------
#if 0
-- ToDo:
-- - Data and Typeable instances for HsSyn.
-- ToDo: check for small transformations that happen to the syntax in
-- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
-- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
-- to get from TyCons, Ids etc. to TH syntax (reify).
-- :browse will use either lm_toplev or inspect lm_interface, depending
-- on whether the module is interpreted or not.
#endif
-- Extract the filename, stringbuffer content and dynflags associed to a module
--
-- XXX: Explain pre-conditions
getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags)
getModuleSourceAndFlags mod = do
m <- getModSummary (moduleName mod)
case ml_hs_file $ ms_location m of
Nothing -> do dflags <- getDynFlags
liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod)
Just sourceFile -> do
source <- liftIO $ hGetStringBuffer sourceFile
return (sourceFile, source, ms_hspp_opts m)
-- | Return module source as token stream, including comments.
--
-- The module must be in the module graph and its source must be available.
-- Throws a 'HscTypes.SourceError' on parse error.
getTokenStream :: GhcMonad m => Module -> m [Located Token]
getTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Give even more information on the source than 'getTokenStream'
-- This function allows reconstructing the source completely with
-- 'showRichTokenStream'.
getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)]
getRichTokenStream mod = do
(sourceFile, source, flags) <- getModuleSourceAndFlags mod
let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1
case lexTokenStream source startLoc flags of
POk _ ts -> return $ addSourceToTokens startLoc source ts
PFailed span err ->
do dflags <- getDynFlags
liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err)
-- | Given a source location and a StringBuffer corresponding to this
-- location, return a rich token stream with the source associated to the
-- tokens.
addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token]
-> [(Located Token, String)]
addSourceToTokens _ _ [] = []
addSourceToTokens loc buf (t@(L span _) : ts)
= case span of
UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts
RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts
where
(newLoc, newBuf, str) = go "" loc buf
start = realSrcSpanStart s
end = realSrcSpanEnd s
go acc loc buf | loc < start = go acc nLoc nBuf
| start <= loc && loc < end = go (ch:acc) nLoc nBuf
| otherwise = (loc, buf, reverse acc)
where (ch, nBuf) = nextChar buf
nLoc = advanceSrcLoc loc ch
-- | Take a rich token stream such as produced from 'getRichTokenStream' and
-- return source code almost identical to the original code (except for
-- insignificant whitespace.)
showRichTokenStream :: [(Located Token, String)] -> String
showRichTokenStream ts = go startLoc ts ""
where sourceFile = getFile $ map (getLoc . fst) ts
getFile [] = panic "showRichTokenStream: No source file found"
getFile (UnhelpfulSpan _ : xs) = getFile xs
getFile (RealSrcSpan s : _) = srcSpanFile s
startLoc = mkRealSrcLoc sourceFile 1 1
go _ [] = id
go loc ((L span _, str):ts)
= case span of
UnhelpfulSpan _ -> go loc ts
RealSrcSpan s
| locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++)
. (str ++)
. go tokEnd ts
| otherwise -> ((replicate (tokLine - locLine) '\n') ++)
. ((replicate (tokCol - 1) ' ') ++)
. (str ++)
. go tokEnd ts
where (locLine, locCol) = (srcLocLine loc, srcLocCol loc)
(tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s)
tokEnd = realSrcSpanEnd s
-- -----------------------------------------------------------------------------
-- Interactive evaluation
-- | Takes a 'ModuleName' and possibly a 'UnitId', and consults the
-- filesystem and package database to find the corresponding 'Module',
-- using the algorithm that is used for an @import@ declaration.
findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
findModule mod_name maybe_pkg = withSession $ \hsc_env -> do
let
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
--
case maybe_pkg of
Just pkg | fsToUnitId pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found _ m -> return m
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
_otherwise -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findImportedModule hsc_env mod_name maybe_pkg
case res of
Found loc m | moduleUnitId m /= this_pkg -> return m
| otherwise -> modNotLoadedError dflags m loc
err -> throwOneError $ noModError dflags noSrcSpan mod_name err
modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a
modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $
text "module is not loaded:" <+>
quotes (ppr (moduleName m)) <+>
parens (text (expectJust "modNotLoadedError" (ml_hs_file loc)))
-- | Like 'findModule', but differs slightly when the module refers to
-- a source file, and the file has not been loaded via 'load'. In
-- this case, 'findModule' will throw an error (module not loaded),
-- but 'lookupModule' will check to see whether the module can also be
-- found in a package, and if so, that package 'Module' will be
-- returned. If not, the usual module-not-found error will be thrown.
--
lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module
lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg)
lookupModule mod_name Nothing = withSession $ \hsc_env -> do
home <- lookupLoadedHomeModule mod_name
case home of
Just m -> return m
Nothing -> liftIO $ do
res <- findExposedPackageModule hsc_env mod_name Nothing
case res of
Found _ m -> return m
err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err
lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module)
lookupLoadedHomeModule mod_name = withSession $ \hsc_env ->
case lookupHpt (hsc_HPT hsc_env) mod_name of
Just mod_info -> return (Just (mi_module (hm_iface mod_info)))
_not_a_home_module -> return Nothing
#ifdef GHCI
-- | Check that a module is safe to import (according to Safe Haskell).
--
-- We return True to indicate the import is safe and False otherwise
-- although in the False case an error may be thrown first.
isModuleTrusted :: GhcMonad m => Module -> m Bool
isModuleTrusted m = withSession $ \hsc_env ->
liftIO $ hscCheckSafe hsc_env m noSrcSpan
-- | Return if a module is trusted and the pkgs it depends on to be trusted.
moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [InstalledUnitId])
moduleTrustReqs m = withSession $ \hsc_env ->
liftIO $ hscGetSafe hsc_env m noSrcSpan
-- | Set the monad GHCi lifts user statements into.
--
-- Checks that a type (in string form) is an instance of the
-- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is,
-- throws an error otherwise.
setGHCiMonad :: GhcMonad m => String -> m ()
setGHCiMonad name = withSession $ \hsc_env -> do
ty <- liftIO $ hscIsGHCiMonad hsc_env name
modifySession $ \s ->
let ic = (hsc_IC s) { ic_monad = ty }
in s { hsc_IC = ic }
-- | Get the monad GHCi lifts user statements into.
getGHCiMonad :: GhcMonad m => m Name
getGHCiMonad = fmap (ic_monad . hsc_IC) getSession
getHistorySpan :: GhcMonad m => History -> m SrcSpan
getHistorySpan h = withSession $ \hsc_env ->
return $ InteractiveEval.getHistorySpan hsc_env h
obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term
obtainTermFromVal bound force ty a = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a
obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term
obtainTermFromId bound force id = withSession $ \hsc_env ->
liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id
#endif
-- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
-- entity known to GHC, including 'Name's defined using 'runStmt'.
lookupName :: GhcMonad m => Name -> m (Maybe TyThing)
lookupName name =
withSession $ \hsc_env ->
liftIO $ hscTcRcLookupName hsc_env name
-- -----------------------------------------------------------------------------
-- Pure API
-- | A pure interface to the module parser.
--
parser :: String -- ^ Haskell module source text (full Unicode is supported)
-> DynFlags -- ^ the flags
-> FilePath -- ^ the filename (for source locations)
-> Either ErrorMessages (WarningMessages, Located (HsModule RdrName))
parser str dflags filename =
let
loc = mkRealSrcLoc (mkFastString filename) 1 1
buf = stringToStringBuffer str
in
case unP Parser.parseModule (mkPState dflags buf loc) of
PFailed span err ->
Left (unitBag (mkPlainErrMsg dflags span err))
POk pst rdr_module ->
let (warns,_) = getMessages pst dflags in
Right (warns, rdr_module)
| snoyberg/ghc | compiler/main/GHC.hs | bsd-3-clause | 56,788 | 4 | 28 | 15,369 | 10,140 | 5,462 | 4,678 | -1 | -1 |
module ParsecPos(module Text.ParserCombinators.Parsec.Pos) where
import Text.ParserCombinators.Parsec.Pos
| OS2World/DEV-UTIL-HUGS | oldlib/ParsecPos.hs | bsd-3-clause | 106 | 0 | 5 | 6 | 21 | 15 | 6 | 2 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.SMT.SMTLib
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Conversion of symbolic programs to SMTLib format
-----------------------------------------------------------------------------
{-# LANGUAGE NamedFieldPuns #-}
module Data.SBV.SMT.SMTLib (
SMTLibPgm
, toSMTLib
, toIncSMTLib
) where
import qualified Data.Set as Set (member, toList)
import Data.SBV.Core.Data
import Data.SBV.SMT.Utils
import qualified Data.SBV.SMT.SMTLib2 as SMT2
-- | Convert to SMT-Lib, in a full program context.
toSMTLib :: SMTConfig -> SMTLibConverter SMTLibPgm
toSMTLib SMTConfig{smtLibVersion} = case smtLibVersion of
SMTLib2 -> toSMTLib2
-- | Convert to SMT-Lib, in an incremental query context.
toIncSMTLib :: SMTConfig -> SMTLibIncConverter [String]
toIncSMTLib SMTConfig{smtLibVersion} = case smtLibVersion of
SMTLib2 -> toIncSMTLib2
-- | Convert to SMTLib-2 format
toSMTLib2 :: SMTLibConverter SMTLibPgm
toSMTLib2 = cvt SMTLib2
where cvt v kindInfo isSat comments qinps skolemMap consts tbls arrs uis axs asgnsSeq cstrs out config
| KUnbounded `Set.member` kindInfo && not (supportsUnboundedInts solverCaps)
= unsupported "unbounded integers"
| KReal `Set.member` kindInfo && not (supportsReals solverCaps)
= unsupported "algebraic reals"
| (needsFloats || needsDoubles) && not (supportsIEEE754 solverCaps)
= unsupported "floating-point numbers"
| needsQuantifiers && not (supportsQuantifiers solverCaps)
= unsupported "quantifiers"
| not (null sorts) && not (supportsUninterpretedSorts solverCaps)
= unsupported "uninterpreted sorts"
| True
= SMTLibPgm v pgm
where sorts = [s | KUserSort s _ <- Set.toList kindInfo]
solverCaps = capabilities (solver config)
unsupported w = error $ unlines [ "SBV: Given problem needs " ++ w
, "*** Which is not supported by SBV for the chosen solver: " ++ show (name (solver config))
]
converter = case v of
SMTLib2 -> SMT2.cvt
pgm = converter kindInfo isSat comments qinps skolemMap consts tbls arrs uis axs asgnsSeq cstrs out config
needsFloats = KFloat `Set.member` kindInfo
needsDoubles = KDouble `Set.member` kindInfo
needsQuantifiers
| isSat = ALL `elem` quantifiers
| True = EX `elem` quantifiers
where quantifiers = map fst (fst qinps)
-- | Convert to SMTLib-2 format
toIncSMTLib2 :: SMTLibIncConverter [String]
toIncSMTLib2 = cvt SMTLib2
where cvt SMTLib2 = SMT2.cvtInc
| josefs/sbv | Data/SBV/SMT/SMTLib.hs | bsd-3-clause | 3,020 | 0 | 17 | 879 | 615 | 326 | 289 | 46 | 1 |
{-#LANGUAGE ScopedTypeVariables#-}
module Main where
import Lib
import Misc
import Numeric.LinearAlgebra as NA
import Data.Foldable
import Data.Maybe
import Data.Default.Class
import Numeric.GSL.Minimization
import Optimise
import Data.Packed.Repa
import Data.Array.Repa (computeUnboxedP)
import Data.Array.Repa.IO.BMP
import Data.Word
import qualified Data.Array.Repa.Operators.Mapping as RM
printMas :: Show a => [a] -> IO ()
printMas [] = return ()
printMas (x:xs) = do
print x
printMas xs
insrt :: [a] -> Int -> a -> [a]
insrt m i e = (take i m) ++ [e] ++ (drop (i+1) m)
swap :: forall a. [a] -> Int -> Int -> [a]
swap x i j = insrt (insrt x i (x!!j)) j (x!!i)
main :: IO ()
main = do
d <- foldlM
(\acc fp -> do
el <- matrixFromCsv fp
return $ el:acc
) [] [ "data/data1.csv"
, "data/data2.csv"
, "data/data3.csv"
, "data/data4.csv"
, "data/data5.csv"
]
i_noisy <- matrixFromCsv "data/I_noisy.csv"
i_orig <- matrixFromCsv "data/I_orig.csv"
r <- matrixFromCsv "data/residual.csv"
let dr = catMaybes $ (\a -> case a of
Left _ -> Nothing
Right v -> Just v) <$> d
let c = zipMatrixWith (+) (matrix 3 [1.0..9.0]) (matrix 3 [1.0..9.0])
let Right r' = r
let Right i = i_orig
let a0 = [0,0,0,0,0]
let (s,p) = minimize NMSimplex2 1E-2 50 ((\_ -> 10) <$> a0) (costAbs dr r' i) a0
q <- computeUnboxedP $ RM.map dtg $ matrixToRepa i
print "ready to write"
writeImageToBMP "data/img.bmp" $ q
dtg :: Double -> (Word8,Word8,Word8)
dtg d = (w,w,w)
where w = fromInteger $ round $ d * 255
costAbs :: [Matrix Double] -> Matrix Double -> Matrix Double -> [Double] -> Double
costAbs d r o a = sum $ NA.toList $ flatten $ cmap (abs) $ o - ad + r
where
ad = foldl (+) (scalar 0.0) $ zipWith (\a d -> scalar a * d) a d | LeMarwin/bmt16 | app/Main.hs | bsd-3-clause | 1,906 | 0 | 17 | 509 | 818 | 428 | 390 | 55 | 2 |
-----------------------------------------------------------------------------
--
-- Code generation for profiling
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module StgCmmProf (
initCostCentres, ccType, ccsType,
mkCCostCentre, mkCCostCentreStack,
-- Cost-centre Profiling
dynProfHdr, profDynAlloc, profAlloc, staticProfHdr, initUpdFrameProf,
enterCostCentreThunk, enterCostCentreFun,
costCentreFrom,
curCCS, storeCurCCS,
emitSetCCC,
saveCurrentCostCentre, restoreCurrentCostCentre,
-- Lag/drag/void stuff
ldvEnter, ldvEnterClosure, ldvRecordCreate
) where
#include "HsVersions.h"
#include "../includes/MachDeps.h"
-- For WORD_SIZE_IN_BITS only.
#include "../includes/rts/Constants.h"
-- For LDV_CREATE_MASK, LDV_STATE_USE
-- which are StgWords
#include "../includes/dist-derivedconstants/header/DerivedConstants.h"
-- For REP_xxx constants, which are MachReps
import StgCmmClosure
import StgCmmUtils
import StgCmmMonad
import SMRep
import MkGraph
import Cmm
import CmmUtils
import CLabel
import qualified Module
import CostCentre
import DynFlags
import FastString
import Module
import Constants -- Lots of field offsets
import Outputable
import Control.Monad
import Data.Char (ord)
-----------------------------------------------------------------------------
--
-- Cost-centre-stack Profiling
--
-----------------------------------------------------------------------------
-- Expression representing the current cost centre stack
ccsType :: CmmType -- Type of a cost-centre stack
ccsType = bWord
ccType :: CmmType -- Type of a cost centre
ccType = bWord
curCCS :: CmmExpr
curCCS = CmmReg (CmmGlobal CCCS)
storeCurCCS :: CmmExpr -> CmmAGraph
storeCurCCS e = mkAssign (CmmGlobal CCCS) e
mkCCostCentre :: CostCentre -> CmmLit
mkCCostCentre cc = CmmLabel (mkCCLabel cc)
mkCCostCentreStack :: CostCentreStack -> CmmLit
mkCCostCentreStack ccs = CmmLabel (mkCCSLabel ccs)
costCentreFrom :: CmmExpr -- A closure pointer
-> CmmExpr -- The cost centre from that closure
costCentreFrom cl = CmmLoad (cmmOffsetB cl oFFSET_StgHeader_ccs) ccsType
staticProfHdr :: DynFlags -> CostCentreStack -> [CmmLit]
-- The profiling header words in a static closure
-- Was SET_STATIC_PROF_HDR
staticProfHdr dflags ccs
= ifProfilingL dflags [mkCCostCentreStack ccs, staticLdvInit]
dynProfHdr :: DynFlags -> CmmExpr -> [CmmExpr]
-- Profiling header words in a dynamic closure
dynProfHdr dflags ccs = ifProfilingL dflags [ccs, dynLdvInit]
initUpdFrameProf :: ByteOff -> FCode ()
-- Initialise the profiling field of an update frame
initUpdFrameProf frame_off
= ifProfiling $ -- frame->header.prof.ccs = CCCS
emitStore (CmmStackSlot Old (frame_off - oFFSET_StgHeader_ccs)) curCCS
-- frame->header.prof.hp.rs = NULL (or frame-header.prof.hp.ldvw = 0)
-- is unnecessary because it is not used anyhow.
---------------------------------------------------------------------------
-- Saving and restoring the current cost centre
---------------------------------------------------------------------------
{- Note [Saving the current cost centre]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The current cost centre is like a global register. Like other
global registers, it's a caller-saves one. But consider
case (f x) of (p,q) -> rhs
Since 'f' may set the cost centre, we must restore it
before resuming rhs. So we want code like this:
local_cc = CCC -- save
r = f( x )
CCC = local_cc -- restore
That is, we explicitly "save" the current cost centre in
a LocalReg, local_cc; and restore it after the call. The
C-- infrastructure will arrange to save local_cc across the
call.
The same goes for join points;
let j x = join-stuff
in blah-blah
We want this kind of code:
local_cc = CCC -- save
blah-blah
J:
CCC = local_cc -- restore
-}
saveCurrentCostCentre :: FCode (Maybe LocalReg)
-- Returns Nothing if profiling is off
saveCurrentCostCentre
= do dflags <- getDynFlags
if not (dopt Opt_SccProfilingOn dflags)
then return Nothing
else do local_cc <- newTemp ccType
emitAssign (CmmLocal local_cc) curCCS
return (Just local_cc)
restoreCurrentCostCentre :: Maybe LocalReg -> FCode ()
restoreCurrentCostCentre Nothing
= return ()
restoreCurrentCostCentre (Just local_cc)
= emit (storeCurCCS (CmmReg (CmmLocal local_cc)))
-------------------------------------------------------------------------------
-- Recording allocation in a cost centre
-------------------------------------------------------------------------------
-- | Record the allocation of a closure. The CmmExpr is the cost
-- centre stack to which to attribute the allocation.
profDynAlloc :: SMRep -> CmmExpr -> FCode ()
profDynAlloc rep ccs
= ifProfiling $
do dflags <- getDynFlags
profAlloc (CmmLit (mkIntCLit (heapClosureSize dflags rep))) ccs
-- | Record the allocation of a closure (size is given by a CmmExpr)
-- The size must be in words, because the allocation counter in a CCS counts
-- in words.
profAlloc :: CmmExpr -> CmmExpr -> FCode ()
profAlloc words ccs
= ifProfiling $
do dflags <- getDynFlags
emit (addToMemE alloc_rep
(cmmOffsetB ccs oFFSET_CostCentreStack_mem_alloc)
(CmmMachOp (MO_UU_Conv wordWidth (typeWidth alloc_rep)) $
[CmmMachOp mo_wordSub [words,
CmmLit (mkIntCLit (profHdrSize dflags))]]))
-- subtract the "profiling overhead", which is the
-- profiling header in a closure.
where
alloc_rep = REP_CostCentreStack_mem_alloc
-- -----------------------------------------------------------------------
-- Setting the current cost centre on entry to a closure
enterCostCentreThunk :: CmmExpr -> FCode ()
enterCostCentreThunk closure =
ifProfiling $ do
emit $ storeCurCCS (costCentreFrom closure)
enterCostCentreFun :: CostCentreStack -> CmmExpr -> FCode ()
enterCostCentreFun ccs closure =
ifProfiling $ do
if isCurrentCCS ccs
then emitRtsCall rtsPackageId (fsLit "enterFunCCS")
[(CmmReg (CmmGlobal BaseReg), AddrHint),
(costCentreFrom closure, AddrHint)] False
else return () -- top-level function, nothing to do
ifProfiling :: FCode () -> FCode ()
ifProfiling code
= do dflags <- getDynFlags
if dopt Opt_SccProfilingOn dflags
then code
else nopC
ifProfilingL :: DynFlags -> [a] -> [a]
ifProfilingL dflags xs
| dopt Opt_SccProfilingOn dflags = xs
| otherwise = []
---------------------------------------------------------------
-- Initialising Cost Centres & CCSs
---------------------------------------------------------------
initCostCentres :: CollectedCCs -> FCode ()
-- Emit the declarations
initCostCentres (local_CCs, ___extern_CCs, singleton_CCSs)
= do dflags <- getDynFlags
whenC (dopt Opt_SccProfilingOn dflags) $
do mapM_ emitCostCentreDecl local_CCs
mapM_ emitCostCentreStackDecl singleton_CCSs
emitCostCentreDecl :: CostCentre -> FCode ()
emitCostCentreDecl cc = do
-- NB. bytesFS: we want the UTF-8 bytes here (#5559)
{ label <- newByteStringCLit (bytesFS $ costCentreUserNameFS cc)
; modl <- newByteStringCLit (bytesFS $ Module.moduleNameFS
$ Module.moduleName
$ cc_mod cc)
; dflags <- getDynFlags
; loc <- newByteStringCLit $ bytesFS $ mkFastString $
showPpr dflags (costCentreSrcSpan cc)
-- XXX going via FastString to get UTF-8 encoding is silly
; let
lits = [ zero, -- StgInt ccID,
label, -- char *label,
modl, -- char *module,
loc, -- char *srcloc,
zero64, -- StgWord64 mem_alloc
zero, -- StgWord time_ticks
is_caf, -- StgInt is_caf
zero -- struct _CostCentre *link
]
; emitDataLits (mkCCLabel cc) lits
}
where
is_caf | isCafCC cc = mkIntCLit (ord 'c') -- 'c' == is a CAF
| otherwise = zero
emitCostCentreStackDecl :: CostCentreStack -> FCode ()
emitCostCentreStackDecl ccs
= case maybeSingletonCCS ccs of
Just cc -> emitDataLits (mkCCSLabel ccs) (mk_lits cc)
Nothing -> pprPanic "emitCostCentreStackDecl" (ppr ccs)
where
mk_lits cc = zero :
mkCCostCentre cc :
replicate (sizeof_ccs_words - 2) zero
-- Note: to avoid making any assumptions about how the
-- C compiler (that compiles the RTS, in particular) does
-- layouts of structs containing long-longs, simply
-- pad out the struct with zero words until we hit the
-- size of the overall struct (which we get via DerivedConstants.h)
zero :: CmmLit
zero = mkIntCLit 0
zero64 :: CmmLit
zero64 = CmmInt 0 W64
sizeof_ccs_words :: Int
sizeof_ccs_words
-- round up to the next word.
| ms == 0 = ws
| otherwise = ws + 1
where
(ws,ms) = SIZEOF_CostCentreStack `divMod` wORD_SIZE
-- ---------------------------------------------------------------------------
-- Set the current cost centre stack
emitSetCCC :: CostCentre -> Bool -> Bool -> FCode ()
emitSetCCC cc tick push
= do dflags <- getDynFlags
if not (dopt Opt_SccProfilingOn dflags)
then nopC
else do tmp <- newTemp ccsType -- TODO FIXME NOW
pushCostCentre tmp curCCS cc
when tick $ emit (bumpSccCount (CmmReg (CmmLocal tmp)))
when push $ emit (storeCurCCS (CmmReg (CmmLocal tmp)))
pushCostCentre :: LocalReg -> CmmExpr -> CostCentre -> FCode ()
pushCostCentre result ccs cc
= emitRtsCallWithResult result AddrHint
rtsPackageId
(fsLit "pushCostCentre") [(ccs,AddrHint),
(CmmLit (mkCCostCentre cc), AddrHint)]
False
bumpSccCount :: CmmExpr -> CmmAGraph
bumpSccCount ccs
= addToMem REP_CostCentreStack_scc_count
(cmmOffsetB ccs oFFSET_CostCentreStack_scc_count) 1
-----------------------------------------------------------------------------
--
-- Lag/drag/void stuff
--
-----------------------------------------------------------------------------
--
-- Initial value for the LDV field in a static closure
--
staticLdvInit :: CmmLit
staticLdvInit = zeroCLit
--
-- Initial value of the LDV field in a dynamic closure
--
dynLdvInit :: CmmExpr
dynLdvInit = -- (era << LDV_SHIFT) | LDV_STATE_CREATE
CmmMachOp mo_wordOr [
CmmMachOp mo_wordShl [loadEra, CmmLit (mkIntCLit lDV_SHIFT) ],
CmmLit (mkWordCLit lDV_STATE_CREATE)
]
--
-- Initialise the LDV word of a new closure
--
ldvRecordCreate :: CmmExpr -> FCode ()
ldvRecordCreate closure = emit $ mkStore (ldvWord closure) dynLdvInit
--
-- Called when a closure is entered, marks the closure as having been "used".
-- The closure is not an 'inherently used' one.
-- The closure is not IND or IND_OLDGEN because neither is considered for LDV
-- profiling.
--
ldvEnterClosure :: ClosureInfo -> FCode ()
ldvEnterClosure closure_info = ldvEnter (cmmOffsetB (CmmReg nodeReg) (-tag))
where tag = funTag closure_info
-- don't forget to substract node's tag
ldvEnter :: CmmExpr -> FCode ()
-- Argument is a closure pointer
ldvEnter cl_ptr
= ifProfiling $
-- if (era > 0) {
-- LDVW((c)) = (LDVW((c)) & LDV_CREATE_MASK) |
-- era | LDV_STATE_USE }
emit =<< mkCmmIfThenElse (CmmMachOp mo_wordUGt [loadEra, CmmLit zeroCLit])
(mkStore ldv_wd new_ldv_wd)
mkNop
where
-- don't forget to substract node's tag
ldv_wd = ldvWord cl_ptr
new_ldv_wd = cmmOrWord (cmmAndWord (CmmLoad ldv_wd bWord)
(CmmLit (mkWordCLit lDV_CREATE_MASK)))
(cmmOrWord loadEra (CmmLit (mkWordCLit lDV_STATE_USE)))
loadEra :: CmmExpr
loadEra = CmmMachOp (MO_UU_Conv cIntWidth wordWidth)
[CmmLoad (mkLblExpr (mkCmmDataLabel rtsPackageId (fsLit "era"))) cInt]
ldvWord :: CmmExpr -> CmmExpr
-- Takes the address of a closure, and returns
-- the address of the LDV word in the closure
ldvWord closure_ptr = cmmOffsetB closure_ptr oFFSET_StgHeader_ldvw
-- LDV constants, from ghc/includes/Constants.h
lDV_SHIFT :: Int
lDV_SHIFT = LDV_SHIFT
--lDV_STATE_MASK :: StgWord
--lDV_STATE_MASK = LDV_STATE_MASK
lDV_CREATE_MASK :: StgWord
lDV_CREATE_MASK = LDV_CREATE_MASK
--lDV_LAST_MASK :: StgWord
--lDV_LAST_MASK = LDV_LAST_MASK
lDV_STATE_CREATE :: StgWord
lDV_STATE_CREATE = LDV_STATE_CREATE
lDV_STATE_USE :: StgWord
lDV_STATE_USE = LDV_STATE_USE
| nomeata/ghc | compiler/codeGen/StgCmmProf.hs | bsd-3-clause | 12,996 | 35 | 21 | 2,739 | 2,244 | 1,198 | 1,046 | 201 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE LambdaCase #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.TreeSelect
-- Description : Display workspaces or actions in a tree-like format.
-- Copyright : (c) Tom Smeets <tom.tsmeets@gmail.com>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Tom Smeets <tom.tsmeets@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
--
-- TreeSelect displays your workspaces or actions in a Tree-like format.
-- You can select the desired workspace/action with the cursor or hjkl keys.
--
-- This module is fully configurable and very useful if you like to have a
-- lot of workspaces.
--
-- Only the nodes up to the currently selected are displayed.
-- This will be configurable in the near future by changing 'ts_hidechildren' to @False@, this is not yet implemented.
--
-- <<https://wiki.haskell.org/wikiupload/thumb/0/0b/Treeselect-Workspace.png/800px-Treeselect-Workspace.png>>
--
-----------------------------------------------------------------------------
module XMonad.Actions.TreeSelect
(
-- * Usage
-- $usage
treeselectWorkspace
, toWorkspaces
, treeselectAction
-- * Configuring
-- $config
, Pixel
-- $pixel
, TSConfig(..)
, tsDefaultConfig
, def
-- * Navigation
-- $navigation
, defaultNavigation
, select
, cancel
, moveParent
, moveChild
, moveNext
, movePrev
, moveHistBack
, moveHistForward
, moveTo
-- * Advanced usage
-- $advusage
, TSNode(..)
, treeselect
, treeselectAt
) where
import Control.Monad.Reader
import Control.Monad.State
import Data.Tree
import Foreign (shiftL, shiftR, (.&.))
import System.IO
import XMonad hiding (liftX)
import XMonad.Prelude
import XMonad.StackSet as W
import XMonad.Util.Font
import XMonad.Util.NamedWindows
import XMonad.Util.TreeZipper
import XMonad.Hooks.WorkspaceHistory
import qualified Data.Map as M
#ifdef XFT
import qualified Data.List.NonEmpty as NE
import Graphics.X11.Xrender
import Graphics.X11.Xft
#endif
-- $usage
--
-- These imports are used in the following example
--
-- > import Data.Tree
-- > import XMonad.Actions.TreeSelect
-- > import XMonad.Hooks.WorkspaceHistory
-- > import qualified XMonad.StackSet as W
--
-- For selecting Workspaces, you need to define them in a tree structure using 'Data.Tree.Node' instead of just a standard list
--
-- Here is an example workspace-tree
--
-- > myWorkspaces :: Forest String
-- > myWorkspaces = [ Node "Browser" [] -- a workspace for your browser
-- > , Node "Home" -- for everyday activity's
-- > [ Node "1" [] -- with 4 extra sub-workspaces, for even more activity's
-- > , Node "2" []
-- > , Node "3" []
-- > , Node "4" []
-- > ]
-- > , Node "Programming" -- for all your programming needs
-- > [ Node "Haskell" []
-- > , Node "Docs" [] -- documentation
-- > ]
-- > ]
--
-- Then add it to your 'XMonad.Core.workspaces' using the 'toWorkspaces' function.
--
-- Optionally, if you add 'workspaceHistoryHook' to your 'logHook' you can use the \'o\' and \'i\' keys to select from previously-visited workspaces
--
-- > xmonad $ def { ...
-- > , workspaces = toWorkspaces myWorkspaces
-- > , logHook = workspaceHistoryHook
-- > }
--
-- After that you still need to bind buttons to 'treeselectWorkspace' to start selecting a workspaces and moving windows
--
-- you could bind @Mod-f@ to switch workspace
--
-- > , ((modMask, xK_f), treeselectWorkspace myTreeConf myWorkspaces W.greedyView)
--
-- and bind @Mod-Shift-f@ to moving the focused windows to a workspace
--
-- > , ((modMask .|. shiftMask, xK_f), treeselectWorkspace myTreeConf myWorkspaces W.shift)
-- $config
-- The selection menu is very configurable, you can change the font, all colors and the sizes of the boxes.
--
-- The default config defined as 'def'
--
-- > def = TSConfig { ts_hidechildren = True
-- > , ts_background = 0xc0c0c0c0
-- > , ts_font = "xft:Sans-16"
-- > , ts_node = (0xff000000, 0xff50d0db)
-- > , ts_nodealt = (0xff000000, 0xff10b8d6)
-- > , ts_highlight = (0xffffffff, 0xffff0000)
-- > , ts_extra = 0xff000000
-- > , ts_node_width = 200
-- > , ts_node_height = 30
-- > , ts_originX = 0
-- > , ts_originY = 0
-- > , ts_indent = 80
-- > , ts_navigate = defaultNavigation
-- > }
-- $pixel
--
-- The 'Pixel' Color format is in the form of @0xaarrggbb@
--
-- Note that transparency is only supported if you have a window compositor running like <https://github.com/chjj/compton compton>
--
-- Some Examples:
--
-- @
-- white = 0xffffffff
-- black = 0xff000000
-- red = 0xffff0000
-- green = 0xff00ff00
-- blue = 0xff0000ff
-- transparent = 0x00000000
-- @
-- $navigation
--
-- Keybindings for navigations can also be modified
--
-- This is the definition of 'defaultNavigation'
--
-- > defaultNavigation :: M.Map (KeyMask, KeySym) (TreeSelect a (Maybe a))
-- > defaultNavigation = M.fromList
-- > [ ((0, xK_Escape), cancel)
-- > , ((0, xK_Return), select)
-- > , ((0, xK_space), select)
-- > , ((0, xK_Up), movePrev)
-- > , ((0, xK_Down), moveNext)
-- > , ((0, xK_Left), moveParent)
-- > , ((0, xK_Right), moveChild)
-- > , ((0, xK_k), movePrev)
-- > , ((0, xK_j), moveNext)
-- > , ((0, xK_h), moveParent)
-- > , ((0, xK_l), moveChild)
-- > , ((0, xK_o), moveHistBack)
-- > , ((0, xK_i), moveHistForward)
-- > ]
-- $advusage
-- This module can also be used to select any other action
-- | Extensive configuration for displaying the tree.
--
-- This class also has a 'Default' instance
data TSConfig a = TSConfig { ts_hidechildren :: Bool -- ^ when enabled, only the parents (and their first children) of the current node will be shown (This feature is not yet implemented!)
, ts_background :: Pixel -- ^ background color filling the entire screen.
, ts_font :: String -- ^ XMF font for drawing the node name extra text
, ts_node :: (Pixel, Pixel) -- ^ node foreground (text) and background color when not selected
, ts_nodealt :: (Pixel, Pixel) -- ^ every other node will use this color instead of 'ts_node'
, ts_highlight :: (Pixel, Pixel) -- ^ node foreground (text) and background color when selected
, ts_extra :: Pixel -- ^ extra text color
, ts_node_width :: Int -- ^ node width in pixels
, ts_node_height :: Int -- ^ node height in pixels
, ts_originX :: Int -- ^ tree X position on the screen in pixels
, ts_originY :: Int -- ^ tree Y position on the screen in pixels
, ts_indent :: Int -- ^ indentation amount for each level in pixels
, ts_navigate :: M.Map (KeyMask, KeySym) (TreeSelect a (Maybe a)) -- ^ key bindings for navigating the tree
}
instance Default (TSConfig a) where
def = TSConfig { ts_hidechildren = True
, ts_background = 0xc0c0c0c0
, ts_font = "xft:Sans-16"
, ts_node = (0xff000000, 0xff50d0db)
, ts_nodealt = (0xff000000, 0xff10b8d6)
, ts_highlight = (0xffffffff, 0xffff0000)
, ts_extra = 0xff000000
, ts_node_width = 200
, ts_node_height = 30
, ts_originX = 0
, ts_originY = 0
, ts_indent = 80
, ts_navigate = defaultNavigation
}
-- | Default navigation
--
-- * navigation using either arrow key or vi style hjkl
-- * Return or Space to confirm
-- * Escape or Backspace to cancel to
defaultNavigation :: M.Map (KeyMask, KeySym) (TreeSelect a (Maybe a))
defaultNavigation = M.fromList
[ ((0, xK_Escape), cancel)
, ((0, xK_Return), select)
, ((0, xK_space), select)
, ((0, xK_Up), movePrev)
, ((0, xK_Down), moveNext)
, ((0, xK_Left), moveParent)
, ((0, xK_Right), moveChild)
, ((0, xK_k), movePrev)
, ((0, xK_j), moveNext)
, ((0, xK_h), moveParent)
, ((0, xK_l), moveChild)
, ((0, xK_o), moveHistBack)
, ((0, xK_i), moveHistForward)
]
-- | Default configuration.
--
-- Using nice alternating blue nodes
tsDefaultConfig :: TSConfig a
tsDefaultConfig = def
{-# DEPRECATED tsDefaultConfig "Use def (from Data.Default, and re-exported by XMonad.Actions.TreeSelect) instead." #-}
-- | Tree Node With a name and extra text
data TSNode a = TSNode { tsn_name :: String
, tsn_extra :: String -- ^ extra text, displayed next to the node name
, tsn_value :: a -- ^ value to return when this node is selected
}
-- | State used by TreeSelect.
--
-- Contains all needed information such as the window, font and a zipper over the tree.
data TSState a = TSState { tss_tree :: TreeZipper (TSNode a)
, tss_window :: Window
, tss_display :: Display
, tss_size :: (Int, Int) -- ^ size of 'tz_window'
, tss_xfont :: XMonadFont
, tss_gc :: GC
, tss_visual :: Visual
, tss_colormap :: Colormap
, tss_history :: ([[String]], [[String]]) -- ^ history zipper, navigated with 'moveHistBack' and 'moveHistForward'
}
-- | State monad transformer using 'TSState'
newtype TreeSelect a b = TreeSelect { runTreeSelect :: ReaderT (TSConfig a) (StateT (TSState a) X) b }
deriving (Monad, Applicative, Functor, MonadState (TSState a), MonadReader (TSConfig a), MonadIO)
-- | Lift the 'X' action into the 'XMonad.Actions.TreeSelect.TreeSelect' monad
liftX :: X a -> TreeSelect b a
liftX = TreeSelect . lift . lift
-- | Run Treeselect with a given config and tree.
-- This can be used for selectiong anything
--
-- * for switching workspaces and moving windows use 'treeselectWorkspace'
-- * for selecting actions use 'treeselectAction'
treeselect :: TSConfig a -- ^ config file
-> Forest (TSNode a) -- ^ a list of 'Data.Tree.Tree's to select from.
-> X (Maybe a)
treeselect c t = treeselectAt c (fromForest t) []
-- | Same as 'treeselect' but ad a specific starting position
treeselectAt :: TSConfig a -- ^ config file
-> TreeZipper (TSNode a) -- ^ tree structure with a cursor position (starting node)
-> [[String]] -- ^ list of paths that can be navigated with 'moveHistBack' and 'moveHistForward' (bound to the 'o' and 'i' keys)
-> X (Maybe a)
treeselectAt conf@TSConfig{..} zipper hist = withDisplay $ \display -> do
-- create a window on the currently focused screen
rootw <- asks theRoot
Rectangle{..} <- gets $ screenRect . W.screenDetail . W.current . windowset
Just vinfo <- liftIO $ matchVisualInfo display (defaultScreen display) 32 4
colormap <- liftIO $ createColormap display rootw (visualInfo_visual vinfo) allocNone
win <- liftIO $ allocaSetWindowAttributes $ \attributes -> do
set_override_redirect attributes True
set_colormap attributes colormap
set_background_pixel attributes ts_background
set_border_pixel attributes 0
w <- createWindow display rootw rect_x rect_y rect_width rect_height 0 (visualInfo_depth vinfo) inputOutput (visualInfo_visual vinfo) (cWColormap .|. cWBorderPixel .|. cWBackPixel) attributes
setClassHint display w (ClassHint "xmonad-tree_select" "xmonad")
pure w
liftIO $ do
-- TODO: move below?
-- make the window visible
mapWindow display win
-- listen to key and mouse button events
selectInput display win (exposureMask .|. keyPressMask .|. buttonReleaseMask)
-- TODO: enable mouse select?
-- and mouse button 1
grabButton display button1 anyModifier win True buttonReleaseMask grabModeAsync grabModeAsync none none
-- grab the keyboard
status <- liftIO $ grabKeyboard display win True grabModeAsync grabModeAsync currentTime
r <- if status == grabSuccess
then do
-- load the XMF font
gc <- liftIO $ createGC display win
xfont <- initXMF ts_font
-- run the treeselect Monad
ret <- evalStateT (runReaderT (runTreeSelect (redraw >> navigate)) conf)
TSState{ tss_tree = zipper
, tss_window = win
, tss_display = display
, tss_xfont = xfont
, tss_size = (fromIntegral rect_width, fromIntegral rect_height)
, tss_gc = gc
, tss_visual = visualInfo_visual vinfo
, tss_colormap = colormap
, tss_history = ([], hist)
}
-- release the XMF font
releaseXMF xfont
liftIO $ freeGC display gc
return ret
else return Nothing
-- destroy the window
liftIO $ do
unmapWindow display win
destroyWindow display win
freeColormap display colormap
-- Flush the output buffer and wait for all the events to be processed
-- TODO: is this needed?
sync display False
return r
-- | Select a workspace and execute a \"view\" function from "XMonad.StackSet" on it.
treeselectWorkspace :: TSConfig WorkspaceId
-> Forest String -- ^ your tree of workspace-names
-> (WorkspaceId -> WindowSet -> WindowSet) -- ^ the \"view\" function.
-- Instances can be 'W.greedyView' for switching to a workspace
-- and/or 'W.shift' for moving the focused window to a selected workspace.
--
-- These actions can also be combined by doing
--
-- > \i -> W.greedyView i . W.shift i
-> X ()
treeselectWorkspace c xs f = do
-- get all defined workspaces
-- They have to be set with 'toWorkspaces'!
ws <- gets (W.workspaces . windowset)
-- check the 'XConfig.workspaces'
if all (`elem` map tag ws) (toWorkspaces xs)
then do
-- convert the 'Forest WorkspaceId' to 'Forest (TSNode WorkspaceId)'
wsf <- forMForest (mkPaths xs) $ \(n, i) -> maybe (return (TSNode n "Does not exist!" "")) (mkNode n) (find (\w -> i == tag w) ws)
-- get the current workspace path
me <- gets (W.tag . W.workspace . W.current . windowset)
hist <- workspaceHistory
treeselectAt c (fromJust $ followPath tsn_name (splitPath me) $ fromForest wsf) (map splitPath hist) >>= maybe (return ()) (windows . f)
else liftIO $ do
-- error!
let msg = unlines $ [ "Please add:"
, " workspaces = toWorkspaces myWorkspaces"
, "to your XMonad config!"
, ""
, "XConfig.workspaces: "
] ++ map tag ws
hPutStrLn stderr msg
xmessage msg
return ()
where
mkNode n w = do
-- find the focused window's name on this workspace
name <- maybe (return "") (fmap show . getName . W.focus) $ stack w
return $ TSNode n name (tag w)
-- | Convert the workspace-tree to a flat list of paths such that XMonad can use them
--
-- The Nodes will be separated by a dot (\'.\') character
toWorkspaces :: Forest String -> [WorkspaceId]
toWorkspaces = map snd . concatMap flatten . mkPaths
mkPaths :: Forest String -> Forest (String, WorkspaceId)
mkPaths = map (\(Node n ns) -> Node (n, n) (map (f n) ns))
where
f pth (Node x xs) = let pth' = pth ++ '.' : x
in Node (x, pth') (map (f pth') xs)
splitPath :: WorkspaceId -> [String]
splitPath i = case break (== '.') i of
(x, []) -> [x]
(x, _:xs) -> x : splitPath xs
-- | Select from a Tree of 'X' actions
--
-- <<https://wiki.haskell.org/wikiupload/thumb/9/9b/Treeselect-Action.png/800px-Treeselect-Action.png>>
--
-- Each of these actions have to be specified inside a 'TSNode'
--
-- Example
--
-- > treeselectAction myTreeConf
-- > [ Node (TSNode "Hello" "displays hello" (spawn "xmessage hello!")) []
-- > , Node (TSNode "Shutdown" "Poweroff the system" (spawn "shutdown")) []
-- > , Node (TSNode "Brightness" "Sets screen brightness using xbacklight" (return ()))
-- > [ Node (TSNode "Bright" "FULL POWER!!" (spawn "xbacklight -set 100")) []
-- > , Node (TSNode "Normal" "Normal Brightness (50%)" (spawn "xbacklight -set 50")) []
-- > , Node (TSNode "Dim" "Quite dark" (spawn "xbacklight -set 10")) []
-- > ]
-- > ]
treeselectAction :: TSConfig (X a) -> Forest (TSNode (X a)) -> X ()
treeselectAction c xs = treeselect c xs >>= \case
Just a -> void a
Nothing -> return ()
forMForest :: (Functor m, Applicative m, Monad m) => [Tree a] -> (a -> m b) -> m [Tree b]
forMForest x g = mapM (mapMTree g) x
mapMTree :: (Functor m, Applicative m, Monad m) => (a -> m b) -> Tree a -> m (Tree b)
mapMTree f (Node x xs) = Node <$> f x <*> mapM (mapMTree f) xs
-- | Quit returning the currently selected node
select :: TreeSelect a (Maybe a)
select = gets (Just . (tsn_value . cursor . tss_tree))
-- | Quit without returning anything
cancel :: TreeSelect a (Maybe a)
cancel = return Nothing
-- TODO: redraw only what is necessary.
-- Examples: redrawAboveCursor, redrawBelowCursor and redrawCursor
-- | Move the cursor to its parent node
moveParent :: TreeSelect a (Maybe a)
moveParent = moveWith parent >> redraw >> navigate
-- | Move the cursor one level down, highlighting its first child-node
moveChild :: TreeSelect a (Maybe a)
moveChild = moveWith children >> redraw >> navigate
-- | Move the cursor to the next child-node
moveNext :: TreeSelect a (Maybe a)
moveNext = moveWith nextChild >> redraw >> navigate
-- | Move the cursor to the previous child-node
movePrev :: TreeSelect a (Maybe a)
movePrev = moveWith previousChild >> redraw >> navigate
-- | Move backwards in history
moveHistBack :: TreeSelect a (Maybe a)
moveHistBack = do
s <- get
case tss_history s of
(xs, a:y:ys) -> do
put s{tss_history = (a:xs, y:ys)}
moveTo y
_ -> navigate
-- | Move forward in history
moveHistForward :: TreeSelect a (Maybe a)
moveHistForward = do
s <- get
case tss_history s of
(x:xs, ys) -> do
put s{tss_history = (xs, x:ys)}
moveTo x
_ -> navigate
-- | Move to a specific node
moveTo :: [String] -- ^ path, always starting from the top
-> TreeSelect a (Maybe a)
moveTo i = moveWith (followPath tsn_name i . rootNode) >> redraw >> navigate
-- | Apply a transformation on the internal 'XMonad.Util.TreeZipper.TreeZipper'.
moveWith :: (TreeZipper (TSNode a) -> Maybe (TreeZipper (TSNode a))) -> TreeSelect a ()
moveWith f = do
s <- get
case f (tss_tree s) of
-- TODO: redraw cursor only?
Just t -> put s{ tss_tree = t }
Nothing -> return ()
-- | wait for keys and run navigation
navigate :: TreeSelect a (Maybe a)
navigate = gets tss_display >>= \d -> join . liftIO . allocaXEvent $ \e -> do
maskEvent d (exposureMask .|. keyPressMask .|. buttonReleaseMask .|. buttonPressMask) e
ev <- getEvent e
if | ev_event_type ev == keyPress -> do
ks <- keycodeToKeysym d (ev_keycode ev) 0
return $ do
mask <- liftX $ cleanKeyMask <*> pure (ev_state ev)
f <- asks ts_navigate
fromMaybe navigate $ M.lookup (mask, ks) f
| ev_event_type ev == buttonPress -> do
-- See XMonad.Prompt Note [Allow ButtonEvents]
allowEvents d replayPointer currentTime
return navigate
| otherwise -> return navigate
-- | Request a full redraw
redraw :: TreeSelect a ()
redraw = do
win <- gets tss_window
dpy <- gets tss_display
-- clear window
-- TODO: not always needed!
liftIO $ clearWindow dpy win
t <- gets tss_tree
_ <- drawLayers 0 0 (reverse $ (tz_before t, cursor t, tz_after t) : tz_parents t)
return ()
drawLayers :: Int -- ^ indentation level
-> Int -- ^ height
-> [(Forest (TSNode a), TSNode a, Forest (TSNode a))] -- ^ node layers (from top to bottom!)
-> TreeSelect a Int
drawLayers _ yl [] = return yl
drawLayers xl yl ((bs, c, as):xs) = do
TSConfig{..} <- ask
let nodeColor y = if odd y then ts_node else ts_nodealt
-- draw nodes above
forM_ (zip [yl ..] (reverse bs)) $ \(y, Node n _) ->
drawNode xl y n (nodeColor y)
-- drawLayers (xl + 1) (y + 1) ns
-- TODO: draw rest? if not ts_hidechildren
-- drawLayers (xl + 1) (y + 1) ns
-- draw the current / parent node
-- if this is the last (currently focused) we use the 'ts_highlight' color
let current_level = yl + length bs
drawNode xl current_level c $
if null xs then ts_highlight
else nodeColor current_level
l2 <- drawLayers (xl + 1) (current_level + 1) xs
-- draw nodes below
forM_ (zip [l2 ..] as) $ \(y, Node n _) ->
drawNode xl y n (nodeColor y)
-- TODO: draw rest? if not ts_hidechildren
-- drawLayers (xl + 1) (y + 1) ns
return (l2 + length as)
-- | Draw a node at a given indentation and height level
drawNode :: Int -- ^ indentation level (not in pixels)
-> Int -- ^ height level (not in pixels)
-> TSNode a -- ^ node to draw
-> (Pixel, Pixel) -- ^ node foreground (font) and background color
-> TreeSelect a ()
drawNode ix iy TSNode{..} col = do
TSConfig{..} <- ask
window <- gets tss_window
display <- gets tss_display
font <- gets tss_xfont
gc <- gets tss_gc
colormap <- gets tss_colormap
visual <- gets tss_visual
liftIO $ drawWinBox window display visual colormap gc font col tsn_name ts_extra tsn_extra
(ix * ts_indent + ts_originX) (iy * ts_node_height + ts_originY)
ts_node_width ts_node_height
-- TODO: draw extra text (transparent background? or ts_background)
-- drawWinBox window fnt col2 nodeH (scW-x) (mes) (x+nodeW) y 8
-- | Draw a simple box with text
drawWinBox :: Window -> Display -> Visual -> Colormap -> GC -> XMonadFont -> (Pixel, Pixel) -> String -> Pixel -> String -> Int -> Int -> Int -> Int -> IO ()
drawWinBox win display visual colormap gc font (fg, bg) text fg2 text2 x y w h = do
-- draw box
setForeground display gc bg
fillRectangle display win gc (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h)
-- dreaw text
drawStringXMF display win visual colormap gc font fg
(fromIntegral $ x + 8)
(fromIntegral $ y + h - 8)
text
-- dreaw extra text
drawStringXMF display win visual colormap gc font fg2
(fromIntegral $ x + w + 8)
(fromIntegral $ y + h - 8)
text2
-- | Modified version of 'XMonad.Util.Font.printStringXMF' that uses 'Pixel' as color format
drawStringXMF :: Display -> Drawable -> Visual -> Colormap -> GC
-> XMonadFont -- ^ XMF Font
-> Pixel -- ^ font color
-> Position -- ^ x-position
-> Position -- ^ y-position
-> String -- ^ string text
-> IO ()
drawStringXMF display window visual colormap gc font col x y text = case font of
Core fnt -> do
setForeground display gc col
setFont display gc $ fontFromFontStruct fnt
drawImageString display window gc x y text
Utf8 fnt -> do
setForeground display gc col
wcDrawImageString display window fnt gc x y text
#ifdef XFT
Xft fnts -> do
withXftDraw display window visual colormap $
\ft_draw -> withXftColorValue display visual colormap (fromARGB col) $
#if MIN_VERSION_X11_xft(0, 3, 4)
\ft_color -> xftDrawStringFallback ft_draw ft_color (NE.toList fnts) (fi x) (fi y) text
#else
\ft_color -> xftDrawString ft_draw ft_color (NE.head fnts) x y text
#endif
-- | Convert 'Pixel' to 'XRenderColor'
--
-- Note that it uses short to represent its components
fromARGB :: Pixel -> XRenderColor
fromARGB x =
#if MIN_VERSION_X11_xft(0, 3, 3)
XRenderColor r g b a
#else
-- swapped green/blue as a workaround for the faulty Storable instance in X11-xft < 0.3.3
XRenderColor r b g a
#endif
where
r = fromIntegral $ 0xff00 .&. shiftR x 8
g = fromIntegral $ 0xff00 .&. x
b = fromIntegral $ 0xff00 .&. shiftL x 8
a = fromIntegral $ 0xff00 .&. shiftR x 16
#endif
| xmonad/xmonad-contrib | XMonad/Actions/TreeSelect.hs | bsd-3-clause | 26,109 | 0 | 22 | 8,040 | 4,863 | 2,651 | 2,212 | 314 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Prompt.Workspace
-- Copyright : (C) 2007 Andrea Rossato, David Roundy
-- License : BSD3
--
-- Maintainer :
-- Stability : unstable
-- Portability : unportable
--
-- A workspace prompt for XMonad
--
-----------------------------------------------------------------------------
module XMonad.Prompt.Workspace (
-- * Usage
-- $usage
workspacePrompt,
workspacePromptRecent,
-- * For developers
Wor(Wor),
) where
import XMonad hiding ( workspaces )
import XMonad.Prompt
import XMonad.StackSet ( workspaces, tag )
import XMonad.Util.WorkspaceCompare ( getSortByIndex )
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Prompt
-- > import XMonad.Prompt.Workspace
--
-- > , ((modm .|. shiftMask, xK_m ), workspacePrompt def (windows . W.shift))
--
-- For detailed instruction on editing the key binding see
-- "XMonad.Doc.Extending#Editing_key_bindings".
data Wor = Wor String
instance XPrompt Wor where
showXPrompt (Wor x) = x
-- Mine changes: updated select method: pop word bound matches
workspacePrompt :: XPConfig -> (String -> X ()) -> X ()
workspacePrompt c job = do ws <- gets (workspaces . windowset)
sort <- getSortByIndex
let ts = map tag $ sort ws
mkXPrompt (Wor "") c (mkComplFunPopWords' ts) job
-- my custom prompt with workspaces ordered by recency
workspacePromptRecent :: XPConfig -> (String -> X ()) -> X ()
workspacePromptRecent c job = do ws <- gets (recentWs . windowset)
let ts = map tag $ ws
mkXPrompt (Wor "") c (mkComplFunPopWords' ts) job
where recentWs w = tail (workspaces w) ++ [head (workspaces w)]
| eb-gh-cr/XMonadContrib1 | XMonad/Prompt/Workspace.hs | bsd-3-clause | 2,074 | 0 | 11 | 636 | 359 | 197 | 162 | 23 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
module DodgerBlue.IO
(evalDslIO,
newQueue,
writeQueue,
tryReadQueue,
readQueue)
where
import DodgerBlue.Types
import Control.Concurrent.Async
import Control.Concurrent.STM
import Control.Monad.Free.Church
import Control.Monad.IO.Class
newQueue :: (MonadIO m) => m (TQueue a)
newQueue = liftIO newTQueueIO
writeQueue :: (MonadIO m) => TQueue a -> a -> m ()
writeQueue q a = (liftIO . atomically) (writeTQueue q a)
tryReadQueue :: (MonadIO m) => TQueue a -> m (Maybe a)
tryReadQueue q = (liftIO . atomically) (tryReadTQueue q)
readQueue :: (MonadIO m) => TQueue a -> m a
readQueue q = (liftIO . atomically) (readTQueue q)
evalDslIO :: (MonadIO m) =>
(m () -> IO ()) ->
CustomCommandStep t m ->
F (CustomDsl TQueue t) a ->
m a
evalDslIO runChild stepCustomCommand p = iterM stepProgram p
where
stepProgram (DslBase (NewQueue' n)) =
newQueue >>= n
stepProgram (DslBase (WriteQueue' q a n)) =
writeQueue q a >> n
stepProgram (DslBase (TryReadQueue' q n)) =
tryReadQueue q >>= n
stepProgram (DslBase (ReadQueue' q n)) =
readQueue q >>= n
stepProgram (DslBase (ForkChild' _childName childProgram n)) = do
let runner = evalDslIO runChild stepCustomCommand childProgram
childAsync <- liftIO $ async (runChild runner)
liftIO $ link childAsync
n
stepProgram (DslBase (SetPulseStatus' _status n)) = n -- ignore for now
stepProgram (DslCustom cmd) =
stepCustomCommand cmd
| adbrowne/dodgerblue | src/DodgerBlue/IO.hs | bsd-3-clause | 1,583 | 0 | 13 | 375 | 558 | 283 | 275 | 43 | 7 |
{-# LANGUAGE ExistentialQuantification #-}
module Valkyrie.Resource(
createResourceManager,
attachResourceLocator,
attachLocator,
obtainResource,
releaseResource,
obtainResourceInternal,
releaseResourceInternal
) where
import Valkyrie.Types
import Valkyrie.Resource.Types
import Valkyrie.Valkyrie
import Control.Applicative
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Control.Lens
import Control.Monad
import Control.Monad.Trans
import Data.List (find)
import qualified Data.Map as M
import Data.Maybe (isJust)
import Data.Typeable
import Debug.Trace
instance (Monad m) => Functor (Load s m) where
fmap = liftM
instance (Monad m) => Applicative (Load s m) where
pure = return
(<*>) = ap
instance (Monad m) => Monad (Load s m) where
return x = Load $ \s -> return (x,s)
(>>=) x f = Load $ \s -> (runLoad x) s >>= \(v,s') -> runLoad (f v) s'
instance (MonadIO m) => MonadIO (Load s m) where
liftIO x = Load $ \s -> liftIO x >>= \v -> return (v,s)
createResourceManager :: IO ResourceManager
createResourceManager = atomically $ fmap (ResourceManager []) $ newTVar M.empty
attachResourceLocator :: ResourceLocator l => l -> ValkyrieM IO ()
attachResourceLocator l = modify $ \valk -> do
return $ valk & valkResourceManager %~ (attachLocator l)
attachLocator :: ResourceLocator l => l -> ResourceManager -> ResourceManager
attachLocator l (ResourceManager lx rx) = ResourceManager (RLB l:lx) rx
obtainResource :: (Resource r, Typeable r) => String -> ValkyrieM IO (Maybe r)
obtainResource path = do
rm <- fmap (view valkResourceManager) get
obtainResourceInternal path rm
obtainResourceInternal :: (MonadIO m, Resource r, Typeable r) => String -> ResourceManager -> m (Maybe r)
obtainResourceInternal path rm@(ResourceManager lx rx) = do
rmap <- liftIO . atomically $ readTVar rx
maybe (obtainNew path rm) (\(RB r) -> return $ cast r) $ M.lookup path rmap
releaseResource :: String -> ValkyrieM IO ()
releaseResource path = do
rm <- fmap (view valkResourceManager) get
releaseResourceInternal path rm
releaseResourceInternal :: MonadIO m => String -> ResourceManager -> m ()
releaseResourceInternal path (ResourceManager _ rx) = do
rmap <- liftIO . atomically $ readTVar rx
maybe (return ()) (\(RB r) -> release r) $ M.lookup path rmap
liftIO . atomically $ modifyTVar rx $ M.delete path
obtainNew :: (MonadIO m, Resource r, Typeable r) => String -> ResourceManager -> m (Maybe r)
obtainNew path rm@(ResourceManager [] rx) = return Nothing
obtainNew path rm@(ResourceManager ((RLB l):lx) rx) = do
mres <- resolve rm path l
case mres of
Nothing -> obtainNew path $ ResourceManager lx rx
Just r -> do
liftIO . atomically . modifyTVar rx $ insert path r
return mres
insert :: (Resource r, Typeable r) => String -> r -> ResourceMap -> ResourceMap
insert k v = M.insert k $ RB v
| Feeniks/valkyrie | src/Valkyrie/Resource.hs | bsd-3-clause | 3,000 | 0 | 14 | 623 | 1,117 | 570 | 547 | 68 | 2 |
{-# LANGUAGE TypeFamilies, RankNTypes, FlexibleContexts, OverloadedStrings #-}
module DirectedKeys.GenerateCfg where
-- import DirectedKeys
import DirectedKeys.GenerateCfg.Internal
import Control.Applicative
import Data.Aeson
import Data.List
import Database.Persist.Class
import Database.Persist.Types
import Persist.Mongo.Settings
import Control.Monad.IO.Class
import Control.Monad.Trans.Control
import Database.Persist.MongoDB
import qualified Data.Text as T
createAndMatchKeys :: (MonadBaseControl IO m, PersistEntity val, Ord a,
MonadIO m, PersistEntityBackend val ~ MongoBackend) =>
MongoDBConf -> (Entity val -> a) -> [b] -> m [(a, b)]
createAndMatchKeys mongoConf collToKey destList = do
collectionList <- runDBConf mongoConf $ selectList [] []
let keyList = sort $ collToKey <$> collectionList
return $ matchKeys keyList destList
getAllkeysTest :: (MonadBaseControl IO m, PersistEntity val, Ord a,
MonadIO m, PersistEntityBackend val ~ MongoBackend) =>
MongoDBConf -> (Entity val -> a) -> m [a]
getAllkeysTest mongoConf keyFcn = do
collectionList <- runDBConf mongoConf $ selectList [] []
return $ (keyFcn <$> collectionList)
matchKeys :: [a] -> [b] -> [(a,b)]
matchKeys aList bList =
let delta = ceiling $ (toRational . length $ aList) / (toRational . length $ bList) -- delta = quot ((length aList)) ((length bList))
groupedOnDelta = revLast . reverse $ groupUp delta aList
in createBoundsTuples ((map (!! 0) groupedOnDelta)) bList
createBoundsTuples :: [a] -> [b] -> [(a,b)]
createBoundsTuples al bl = zipWith (\a b -> (a,b)) al bl
revLast :: [[a]] -> [[a]]
revLast (x:[]) = [reverse x]
revLast (x:xs) = x:(revLast xs)
mConf :: MongoDBConf
mConf = MongoDBConf "127.0.0.1" "onping_production" 27017 | plow-technologies/dkrouter-generator | src/DirectedKeys/GenerateCfg.hs | bsd-3-clause | 1,840 | 0 | 13 | 359 | 602 | 326 | 276 | 38 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.API.Subledger.Types
( AccountingValue(..)
, Action(..)
, BalanceValue(..)
, CreditValue(..)
, DebitValue(..)
, WrappedBalanceValue(..)
, EffectiveAt(..)
, fromUTCTime
, ResourceState(..)
, Reference(..)
, Void
) where
import Prelude hiding (print)
import Control.Arrow ((***))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import qualified Data.ByteString.Char8 as B
import qualified Data.Scientific as S
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Textual
import Data.Time.Clock (DiffTime, UTCTime(..))
import Data.Time.ISO8601 (parseISO8601, formatISO8601Millis)
import Data.Typeable (Typeable)
import qualified Data.Void as V
import GHC.Generics (Generic)
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types.Method as M
-- ResourceState
data ResourceState
= Active
| Archived
deriving (Bounded, Enum, Eq, Show)
-- EffectiveAt
newtype EffectiveAt = EffectiveAt { toUTCTime :: UTCTime }
deriving (Eq, Show)
instance A.FromJSON EffectiveAt where
parseJSON = A.withText "ISO8601" (outer . parseISO8601 . T.unpack)
where outer = maybe mempty (pure . EffectiveAt)
instance Printable EffectiveAt where
print = print . formatISO8601Millis . toUTCTime
instance A.ToJSON EffectiveAt where
toJSON = A.String . toText
fromUTCTime :: UTCTime -> EffectiveAt
fromUTCTime = EffectiveAt . roundUTCTimeToMillis
roundUTCTimeToMillis :: UTCTime -> UTCTime
roundUTCTimeToMillis (UTCTime day dayTime) =
UTCTime day $ roundDiffToMillis dayTime
where roundDiffToMillis = (/1000) . fromInt . truncate . (*1000)
fromInt = fromIntegral :: Int -> DiffTime
-- AccountingAmount
newtype AccountingAmount = AccountingAmount { toScientific :: S.Scientific }
deriving (Eq, Show)
instance A.FromJSON AccountingAmount where
parseJSON = A.withText "numeric string" (pure . AccountingAmount . read . reqZero . T.uncons)
where reqZero (Just ('.', t)) = '0':'.':(T.unpack t)
reqZero (Just (c, t)) = c:(T.unpack t)
reqZero Nothing = error "empty string for amount"
instance A.ToJSON AccountingAmount where
toJSON = A.String . T.pack . S.formatScientific S.Fixed Nothing . toScientific
-- | AccountingValue
data AccountingValue = AccountingDebitValue S.Scientific
| AccountingCreditValue S.Scientific
| AccountingZeroValue
deriving (Eq, Generic, Show)
instance A.FromJSON AccountingValue where
parseJSON = A.withObject "value object" $ \v -> do
t <- v A..: "type" :: A.Parser Text
case t of
"debit" -> AccountingDebitValue . toScientific <$> v A..: "amount"
"credit"-> AccountingCreditValue . toScientific <$> v A..: "amount"
"zero" -> pure AccountingZeroValue
_ -> error "Accounting values must have a type of debit, credit, or zero."
valueObject :: Text -> S.Scientific -> A.Value
valueObject t a = A.object [ "type" A..= A.String t
, "amount" A..= AccountingAmount a
]
instance A.ToJSON AccountingValue where
toJSON (AccountingDebitValue s) = valueObject "debit" s
toJSON (AccountingCreditValue s) = valueObject "credit" s
toJSON AccountingZeroValue = valueObject "zero" 0
-- | BalanceValue
data BalanceValue = BalanceValue DebitValue CreditValue AccountingValue
deriving (Eq, Show)
instance A.FromJSON BalanceValue where
parseJSON = A.withObject "balance value object" $ \v ->
BalanceValue <$> v A..: "debit_value"
<*> v A..: "credit_value"
<*> v A..: "value"
instance A.ToJSON BalanceValue where
toJSON (BalanceValue d c a) = A.object
[ "debit_value" A..= d
, "credit_value" A..= c
, "value" A..= a
]
-- | DebitValue
data DebitValue = DebitValue S.Scientific
| DebitZeroValue
deriving (Eq, Show)
instance A.FromJSON DebitValue where
parseJSON = A.withObject "debit value" $ \v -> do
t <- v A..: "type" :: A.Parser Text
case t of
"debit" -> DebitValue . toScientific <$> v A..: "amount"
"zero" -> pure DebitZeroValue
_ -> error "Debit values must have a type of debit or zero."
instance A.ToJSON DebitValue where
toJSON (DebitValue s) = valueObject "debit" s
toJSON DebitZeroValue = valueObject "zero" 0
-- | CreditValue
data CreditValue = CreditValue S.Scientific
| CreditZeroValue
deriving (Eq, Show)
instance A.FromJSON CreditValue where
parseJSON = A.withObject "credit value" $ \v -> do
t <- v A..: "type" :: A.Parser Text
case t of
"credit" -> CreditValue . toScientific <$> v A..: "amount"
"zero" -> pure CreditZeroValue
_ -> error "Credit values must have a type of credit or zero."
instance A.ToJSON CreditValue where
toJSON (CreditValue s) = valueObject "credit" s
toJSON CreditZeroValue = valueObject "zero" 0
-- | WrappedBalanceValue
newtype WrappedBalanceValue = WrappedBalanceValue
{ unwrapBalanceValue :: BalanceValue }
deriving (Eq, Show)
instance A.FromJSON WrappedBalanceValue where
parseJSON = A.withObject "wrapped balance value objecT" $ \v ->
WrappedBalanceValue <$> v A..: "balance"
instance A.ToJSON WrappedBalanceValue where
toJSON (WrappedBalanceValue b) = A.object ["balance" A..= b]
-- | Reference
newtype Reference = Reference
{ uri :: Text
} deriving (Eq, Show, Typeable)
instance A.FromJSON Reference where
parseJSON = A.withText "Data.API.Subledger.Types.Reference" (return . Reference)
instance A.ToJSON Reference where
toJSON = A.String . uri
-- Action
class A.ToJSON a => Action q a r | q -> a r where
toMethod :: q -> M.Method
toMethod = const M.methodGet
toPathPieces :: q -> [Text]
toPath :: q -> B.ByteString
toPath = B.concat . ("v2":) . map (B.cons '/' . encodeUtf8) . toPathPieces
toQueryParams :: q -> [(Text, Maybe Text)]
toQueryParams = const []
toQueryString :: q -> [(B.ByteString, Maybe B.ByteString)]
toQueryString = map (encodeUtf8 *** (encodeUtf8 <$>)) . toQueryParams
toBodyObject :: A.ToJSON a => q -> Maybe a
toBodyObject = const Nothing
toBody :: q -> HTTP.RequestBody
toBody = maybe (HTTP.RequestBodyBS "") (HTTP.RequestBodyLBS . A.encode) . toBodyObject
toRequest :: q -> HTTP.Request
toRequest q = HTTP.setQueryString (toQueryString q) $ HTTP.defaultRequest
{ HTTP.method = toMethod q
, HTTP.path = toPath q
, HTTP.requestBody = toBody q
}
-- Void
newtype Void = Void V.Void deriving (Eq, Show)
instance A.ToJSON Void where
toJSON = error "the void is uninhabited"
| whittle/subledger | subledger-core/src/Data/API/Subledger/Types.hs | bsd-3-clause | 7,063 | 0 | 15 | 1,671 | 1,982 | 1,081 | 901 | 156 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Hmm… so not all functions really need to get the client passed in, but for consistency's (and safety's on some level) sake, they all do in the module
{- |
Client interface to Neo4j over REST. Here's a simple example (never mind the cavalier pattern matching):
> import Database.Neo4j
>
> main = do
> let client = mkClient "192.168.56.101" defaultPort
> Right n <- createNode client [("name", "Neo"), ("quote", "Whoa.")]
> Right m <- createNode client [("name", "Trinity"), ("quote", "Dodge this.")]
> Right r <- createRelationship client n m "LOVES"
> indexNodeByAllProperties client n
> nodes <- findNodes client "name" "name" "Neo"
-}
module Database.Neo4j (
-- * Connecting to Neo4j
Client, mkClient, defaultClient, defaultPort,
-- * Working with Nodes
Node(), createNode, nodeProperties, nodeURI, getNodeID, getNode, getNodes,
lookupNode, deleteNode,
-- * Working with Relationships
Relationship(), relationshipFrom, relationshipTo, relationshipType,
relationshipProperties, createRelationship, updateRelationshipProperties,
deleteRelationship, getRelationship, getRelationships,
incomingRelationships,
outgoingRelationships, allRelationships, typedRelationships,
-- * Working with Indexes
indexNode, indexNodeByProperty, indexNodeByAllProperties, findNodes,
-- * Data Types
Properties, RelationshipType, IndexName, RelationshipRetrievalType(..),
NodeID,
-- * Traversals
TraversalOption, TraversalOptions, TraversalReturnType(..),
TraversalOrder(..), TraverseRelationships(..), TraverseRelationship(..),
Language(..), TraversalUniqueness(..),
TraversalReturnFilter(..), TraversalPruneEvaluator(..), PathWithURIs(..),
Path(..), pathTraversalURIs, pathTraversal,
-- ** Setting Traversal Options
set, order, uniqueness, returnFilter, maxDepth, pruneEvaluator,
relationships, defaultBFSOptions
) where
-- module Database.Neo4j where
import Control.Monad
import Text.Printf
import qualified Data.HashMap.Lazy as Map
import qualified Data.Vector as V
import Data.Either.Unwrap
import Data.Aeson
import Data.Aeson.Parser
import Data.Attoparsec.Number (Number (I))
import qualified Data.Attoparsec as Attoparsec
import Database.Neo4j.Node
import Database.Neo4j.Relationship
import Database.Neo4j.Types
import Database.Neo4j.Internal
import Database.Neo4j.Traversal
import Network.HTTP
import Network.URI
import Data.String
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy.Char8 as BLC
import Data.Either.Unwrap
import Control.Applicative
import Debug.Trace
import Data.Maybe
-- | Get relationships of a specified type
typedRelationships :: Client -> RelationshipType -> Node -> IO (Either String [Relationship])
typedRelationships client relType =
getRelationships client (RetrieveTyped relType)
createNodeIndex :: Client -> IndexName -> IO (Either String ())
createNodeIndex client indexName = do
let uri = serviceRootURI client `appendToPath` "index" `appendToPath`
"node"
let request = buildPost uri $ toStrictByteString $ encode $
object [("name", toJSON indexName)]
result <- simpleHTTP request
return $ case result of
Right response -> case rspCode response of
(2, 0, 1) -> Right ()
_ -> Left ("Index not created. Actual response: " ++
(show response))
Left err -> Left (show err)
-- | If a node has a specific property, add the property to the given index.
indexNodeByProperty :: Client -> IndexName -> Text -> Node -> IO (Either String ())
indexNodeByProperty client indexName propertyName node@(Node nodeURI properties) =
case lookup propertyName properties of
Just propertyValue -> indexNode client indexName node propertyName
propertyValue
Nothing -> return $ Left $ printf "Property %s not in node %s"
(Text.unpack propertyName) (show node)
-- | Add all properties of a given node to indices, each of which is named the same as the property key
indexNodeByAllProperties :: Client -> Node -> IO (Either String ())
indexNodeByAllProperties client node@(Node _ properties) = let keys = map fst properties in do
rs <- mapM (\key -> indexNodeByProperty client (Text.unpack key) key node)
keys
return $ sequence_ rs
-- | Add a node to the given index, specifying your own key and value
indexNode :: Client -> IndexName -> Node -> Text -> Value -> IO (Either String ())
indexNode client indexName node@(Node nodeURI _) key value =
case valueAsString of
Just value' -> do
let uri = serviceRootURI client `appendToPath`
"index" `appendToPath`
"node" `appendToPath` indexName `appendToPath`
(Text.unpack key) `appendToPath` value'
result <- simpleHTTP $ buildPost uri $
toStrictByteString $
encode $ toJSON $ show nodeURI
return $ case fmap rspCode result of
Right (2, 0, 1) -> Right ()
Left err -> Left $ show err
_ ->
Left $ printf "Node not indexed.\
\ Actual response: %s" (show result)
Nothing -> return $ Left $
printf "I can't convert your value %s automatically\
\ into a sane indexable string. Convert it to a string\
\ the way you want first." (show value)
where
valueAsString = case value of
String text -> Just $ Text.unpack text
Number (I int) -> Just $ show int
_ -> Nothing
-- | The new way in > 1.5 MILESTONE (https://github.com/neo4j/community/issues/25;cid=1317413794432-668)
indexNodeNew :: (ToJSON a) => Client -> IndexName -> Node -> Text -> a -> IO (Either String ())
indexNodeNew client indexName node@(Node nodeURI _) key value = do
let uri = serviceRootURI client `appendToPath` "index" `appendToPath` "node" `appendToPath`
indexName
print uri
result <- simpleHTTP $ buildPost uri $ toStrictByteString $ encode $
object [("uri", toJSON $ show nodeURI), ("key", toJSON key),
("value", toJSON value)]
return $ case fmap rspCode result of
Right (2, 0, 1) -> Right ()
Left err -> Left $ show err
_ ->
Left $
printf "Node not indexed for some reason. Actual response: %s"
(show result)
-- | Search the given index for nodes whose keys have the specified value
findNodes :: Client -> IndexName -> Text -> String -> IO (Either String [Node])
findNodes client indexName key value = do
let uri = serviceRootURI client `appendToPath` "index" `appendToPath`
"node" `appendToPath` indexName `appendToPath`
(Text.unpack key) `appendToPath` value
result <- simpleHTTP $ mkRequest GET uri
let node = case result of
Right response -> case rspCode response of
(2, 0, 0) -> let body = rspBody response in
case Attoparsec.parse json body of
Attoparsec.Done _ (Array v) -> Right $
forM (V.toList v) $ \n ->
case n of
Object o -> extractNode o
_ -> Nothing
_ -> Left "findNode: Node parse error"
_ -> Left ("Node probably doesn't exist. Response code "
++ (show $ rspCode response))
Left err -> Left $ show err
return $ case node of
Right (Just n) -> Right n
Right Nothing ->
Left "Some weird node parse error deep in the code..."
Left err -> Left err
where
extractNode o = do
selfURIFromJSON <- fmap fromJSON $ Map.lookup "self" o
selfURI <- case selfURIFromJSON of
(Success possibleURI) -> parseURI possibleURI
_ -> Nothing
nodePropertiesFromJSON <- fmap fromJSON $ Map.lookup "data" o
nodeProperties <- case nodePropertiesFromJSON of
(Success (Object propMap)) -> Just $ Map.toList propMap
_ -> Nothing
return $ Node selfURI nodeProperties
| ThoughtLeadr/neo4j-haskell-http-client | src/Database/Neo4j.hs | bsd-3-clause | 8,765 | 0 | 26 | 2,607 | 1,967 | 1,048 | 919 | 151 | 9 |
module Model where
import Prelude
import Yesod
import Data.Text (Text)
import Database.Persist.Quasi
import Data.Typeable (Typeable)
import Hitweb.Identity
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlOnlySettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
| NicolasDP/hitweb | Model.hs | bsd-3-clause | 469 | 0 | 8 | 61 | 74 | 43 | 31 | -1 | -1 |
module Performer where
import System.Process
import Control.Concurrent
import Control.Monad
import Types
boxsize = 24
ctopleft = (122, 26)
cbotleft1_1 = (122, 290)
cbotleft1_2 = (122, 321)
cbotleft2_1 = (274, 290)
chua = (689, 26)
czhong = (600, 50)
cfa = (600, 140)
cbai = (600, 220)
voffset = snd cbotleft1_2 - snd cbotleft1_1
hoffset = fst cbotleft2_1 - fst cbotleft1_1
getmouselocation :: IO (Int, Int)
getmouselocation = do
str <- readProcess "xdotool" ["getmouselocation", "--shell"] []
let [x, y] = take 2 $ lines str
return (read $ drop 2 x, read $ drop 2 y)
speed :: Double
speed = 18
-- move mouse to coordinate at speed sp
mousemove :: (Int, Int) -> Double -> IO ()
mousemove (x, y) sp = do
(x', y') <- getmouselocation
let (dx, dy) = (x - x', y' - y)
r = sqrt . fromIntegral $ dx ^ 2 + dy ^ 2
theta = tanh (fromIntegral dy / fromIntegral dx) * 180 / pi
interval = floor (r / sp)
forM_ [1..interval] $ \_ -> do
readProcess "xdotool" ["mousemove_relative", "--polar", "--",
show (90 - theta), show sp] []
threadDelay 10000
void $ readProcess "xdotool" ["mousemove", show x, show y] []
mousemove' :: (Int, Int) -> IO ()
mousemove' = flip mousemove speed
mousemove'' :: (Int, Int) -> IO ()
mousemove'' (x, y) = void $ readProcess "xdotool"
["mousemove", show x, show y] []
mousedown :: IO ()
mousedown = void $ readProcess "xdotool" ["mousedown", "1"] []
mouseclick :: IO ()
mouseclick = void $ readProcess "xdotool" ["click", "1"] []
mouseup :: IO ()
mouseup = void $ readProcess "xdotool" ["mouseup", "1"] []
coord :: Position -> (Int, Int)
coord (PMain x y) =
let (a, b) = cbotleft1_1 in (a + hoffset * x, b + voffset * y)
coord (PTL i) =
let (a, b) = ctopleft in (a + hoffset * i, b)
coord (PTR i) =
let (a, b) = ctopleft in (a + hoffset * (i + 5), b)
coord PHua = chua
performOperation :: Operation -> IO ()
{- performOperation (Move p1 (PTR i)) = do -}
{- let (cx, cy) = coord p1 -}
{- mousemove'' (cx, min (cy + 210) 690) -}
{- threadDelay 150000 -}
{- mousedown -}
{- threadDelay 150000 -}
{- let (dx, dy) = coord (PTR i) -}
{- mousemove'' (dx, dy + 210) -}
{- threadDelay 150000 -}
{- mouseup -}
{- threadDelay 100000 -}
performOperation (Move p1 p2) = do
mousemove'' (coord p1)
threadDelay 150000
mousedown
threadDelay 150000
mousemove'' (coord p2)
threadDelay 150000
mouseup
threadDelay 200000
performOperation (Slay Zhong) = do
mousemove'' czhong
threadDelay 200000
mousedown
threadDelay 100000
mouseup
threadDelay 1000000
performOperation (Slay Fa) = do
mousemove'' cfa
threadDelay 200000
mousedown
threadDelay 100000
mouseup
threadDelay 1000000
performOperation (Slay Bai) = do
mousemove'' cbai
threadDelay 200000
mousedown
threadDelay 100000
mouseup
threadDelay 1000000
| Frefreak/solitaire-solver | src/Performer.hs | bsd-3-clause | 2,947 | 0 | 15 | 727 | 1,101 | 564 | 537 | 85 | 1 |
{-# LANGUAGE OverloadedStrings, RecursiveDo, ScopedTypeVariables, FlexibleContexts, TypeFamilies, ConstraintKinds #-}
module Frontend.Properties.DDB
(
dbProperties
) where
import Prelude hiding (mapM, mapM_, all, sequence)
import qualified Data.Map as Map
import Data.Monoid ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import Reflex
import Reflex.Dom.Core
------
import AWSFunction
--------------------------------------------------------------------------
-- DynamoDB Properties
-------
calcDBData :: Text -> Int -> Text
calcDBData cmv ckey = toText $
case ckey of
1 -> calcDB' $ readDouble cmv
_ -> calcDB' $ 1000 * (readDouble cmv)
where
calcDB' cmv'
| cmv' <= 25 = 0
| otherwise = price * (cmv' - 25)
price = 0.285
--------------------
dbProperties :: (Reflex t, MonadWidget t m) => Dynamic t (Map.Map T.Text T.Text) -> m (Dynamic t Text)
dbProperties dynAttrs = do
rec
result <- elDynAttr "div" ((constDyn $ idAttrs CF) <> dynAttrs <> rightClassAttrs) $ do
rec
dbDts <- dbDataSet evReset
evReset <- button "Reset"
return $ dbDts
return $ result
dbDataSet :: (Reflex t, MonadWidget t m) => Event t a -> m (Dynamic t Text)
dbDataSet evReset = do
rec
let
resultDBData = calcDBData <$> (value dbDataSize)
<*> (value ddDBDataSize)
el "h4" $ text "Data Transfer Out: "
el "p" $ text "Monthly Volume:"
dbDataSize <- textInput $ def & textInputConfig_inputType .~ "number"
& textInputConfig_initialValue .~ "0"
& setValue .~ (leftmost ["0" <$ evReset])
ddDBDataSize <- dropdown 1 (constDyn ddDataSet) def
return $ resultDBData | Rizary/awspi | Lib/Frontend/Properties/DDB.hs | bsd-3-clause | 1,807 | 3 | 18 | 492 | 520 | 267 | 253 | 43 | 2 |
{-# LANGUAGE ForeignFunctionInterface #-}
module CRF.LogMath
( logIsZero
, logAdd
, logSum
) where
import Data.List (sort)
foreign import ccall unsafe "math.h log1p"
log1p :: Double -> Double
inf :: RealFloat a => a
inf = (1/0)
m_inf :: RealFloat a => a
m_inf = -(1/0)
logIsZero :: Double -> Bool
logIsZero x = x == m_inf
logAdd :: Double -> Double -> Double
logAdd x y
| logIsZero x = y
| x > y = x + log1p(exp(y - x))
| otherwise = y + log1p(exp(x - y))
logSub :: Double -> Double -> Double
logSub x y
| logIsZero x = y
| x > y = x + log1p(exp(y - x))
| otherwise = y + log1p(exp(x - y))
--TODO: Which version to use ?
logSum :: [Double] -> Double
--logSum l = foldl (\acc x -> logAdd acc x) m_inf $ sort l
logSum l = foldl (\acc x -> logAdd acc x) m_inf l
| kawu/tagger | src/CRF/LogMath.hs | bsd-3-clause | 824 | 0 | 11 | 225 | 349 | 180 | 169 | 26 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE GADTs #-}
-- |
-- Module : Pact.Native.Db
-- Copyright : (C) 2016 Stuart Popejoy
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Stuart Popejoy <stuart@kadena.io>
--
-- Builtins for database access.
--
module Pact.Native.Db
(dbDefs)
where
import Bound
import Control.Arrow hiding (app)
import Control.Lens hiding ((.=))
import Control.Monad
import Control.Monad.Reader (ask)
import Data.Default
import qualified Data.HashSet as HS
import qualified Data.Map.Strict as M
import Data.Foldable (foldlM)
import qualified Data.Vector as V
import Data.Text (pack)
import Pact.Eval
import Pact.Runtime.Typecheck
import Pact.Runtime.Utils
import Pact.Native.Internal
import Pact.Types.Pretty
import Pact.Types.RowData
import Pact.Types.Runtime
import Pact.Types.PactValue
class Readable a where
readable :: a -> ReadValue
instance Readable RowData where
readable = ReadData
instance Readable RowKey where
readable = ReadKey
instance Readable TxId where
readable = const ReadTxId
instance Readable (TxLog RowData) where
readable = ReadData . _txValue
instance Readable (TxId, TxLog RowData) where
readable = ReadData . _txValue . snd
-- | Parameterize calls to 'guardTable' with op.
data GuardTableOp
= GtRead
| GtSelect
| GtWithRead
| GtWithDefaultRead
| GtKeys
| GtTxIds
| GtTxLog
| GtKeyLog
| GtWrite
| GtCreateTable
dbDefs :: NativeModule
dbDefs =
let writeArgs part = funType tTyString
[("table",tableTy),("key",tTyString),
("object",TySchema TyObject rt part)]
writeDocs s = "Write entry in TABLE for KEY of OBJECT column data" <> s
rt = mkSchemaVar "row"
tableTy = TySchema TyTable rt def
rowTy = TySchema TyObject rt def
bindTy = TySchema TyBinding rt def
partialize = set tySchemaPartial AnySubschema
a = mkTyVar "a" []
b = mkTyVar "b" []
in ("Database",
[setTopLevelOnly $ defGasRNative "create-table" createTable'
(funType tTyString [("table",tableTy)])
[LitExample "(create-table accounts)"] "Create table TABLE."
,defNative (specialForm WithRead) withRead
(funType a [("table",tableTy),("key",tTyString),("bindings",bindTy)])
[ LitExample "(with-read accounts id { \"balance\":= bal, \"ccy\":= ccy }\n\
\ (format \"Balance for {} is {} {}\" [id bal ccy]))"
]
"Special form to read row from TABLE for KEY and bind columns per BINDINGS over subsequent body statements."
,defNative (specialForm WithDefaultRead) withDefaultRead
(funType a
[("table",tableTy),("key",tTyString),("defaults",partialize rowTy),("bindings",partialize bindTy)])
[ LitExample "(with-default-read accounts id { \"balance\": 0, \"ccy\": \"USD\" } { \"balance\":= bal, \"ccy\":= ccy }\n\
\ (format \"Balance for {} is {} {}\" [id bal ccy]))"
]
"Special form to read row from TABLE for KEY and bind columns per BINDINGS over subsequent body statements. \
\If row not found, read columns from DEFAULTS, an object with matching key names."
,defGasRNative "read" read'
(funType rowTy [("table",tableTy),("key",tTyString)] <>
funType rowTy [("table",tableTy),("key",tTyString),("columns",TyList tTyString)])
[LitExample "(read accounts id ['balance 'ccy])"]
"Read row from TABLE for KEY, returning database record object, or just COLUMNS if specified."
,defNative (specialForm Select) select
(funType (TyList rowTy) [("table",tableTy),("where",TyFun $ funType' tTyBool [("row",rowTy)])] <>
funType (TyList rowTy) [("table",tableTy),("columns",TyList tTyString),("where",TyFun $ funType' tTyBool [("row",rowTy)])])
[ LitExample "(select people ['firstName,'lastName] (where 'name (= \"Fatima\")))"
, LitExample "(select people (where 'age (> 30)))?"
]
"Select full rows or COLUMNS from table by applying WHERE to each row to get a boolean determining inclusion."
,defGasRNative "keys" keys'
(funType (TyList tTyString) [("table",tableTy)])
[LitExample "(keys accounts)"] "Return all keys in TABLE."
,defNative "fold-db" foldDB'
(funType (TyList b)
[ ("table", tableTy)
, ("qry", TyFun (funType' (TyPrim TyBool) [("a", TyPrim TyString), ("b", rowTy)] ))
, ("consumer", TyFun (funType' b [("a", TyPrim TyString), ("b", rowTy)]))])
[LitExample "(let* \n\
\ ((qry (lambda (k obj) true)) ;; select all rows\n\
\ (f (lambda (x) [(at 'firstName x), (at 'b x)]))\n\
\ )\n\
\ (fold-db people (qry) (f))\n\
\)"]
"Select rows from TABLE using QRY as a predicate with both key and value, and then accumulate results of the query \
\in CONSUMER. Output is sorted by the ordering of keys."
,defGasRNative "txids" txids'
(funType (TyList tTyInteger) [("table",tableTy),("txid",tTyInteger)])
[LitExample "(txids accounts 123849535)"] "Return all txid values greater than or equal to TXID in TABLE."
,defNative "write" (write Write FullSchema) (writeArgs FullSchema)
[LitExample "(write accounts id { \"balance\": 100.0 })"] (writeDocs ".")
,defNative "insert" (write Insert FullSchema) (writeArgs FullSchema)
[LitExample "(insert accounts id { \"balance\": 0.0, \"note\": \"Created account.\" })"]
(writeDocs ", failing if data already exists for KEY.")
,defNative "update" (write Update AnySubschema) (writeArgs AnySubschema)
[LitExample "(update accounts id { \"balance\": (+ bal amount), \"change\": amount, \"note\": \"credit\" })"]
(writeDocs ", failing if data does not exist for KEY.")
,defGasRNative "txlog" txlog
(funType (TyList tTyObjectAny) [("table",tableTy),("txid",tTyInteger)])
[LitExample "(txlog accounts 123485945)"] "Return all updates to TABLE performed in transaction TXID."
,defGasRNative "keylog" keylog
(funType (TyList (tTyObject TyAny)) [("table",tableTy),("key",tTyString),("txid",tTyInteger)])
[LitExample "(keylog accounts \"Alice\" 123485945)"] "Return updates to TABLE for a KEY in transactions at or after TXID, in a list of objects \
\indexed by txid."
,setTopLevelOnly $ defRNative "describe-table" descTable
(funType tTyObjectAny [("table",tableTy)])
[LitExample "(describe-table accounts)"]
"Get metadata for TABLE. Returns an object with 'name', 'hash', 'blessed', 'code', and 'keyset' fields."
,setTopLevelOnly $ defGasRNative "describe-keyset" descKeySet
(funType tTyObjectAny [("keyset",tTyString)]) [] "Get metadata for KEYSET."
,setTopLevelOnly $ defRNative "describe-module" descModule
(funType tTyObjectAny [("module",tTyString)])
[LitExample "(describe-module 'my-module)"]
"Get metadata for MODULE. Returns an object with 'name', 'hash', 'blessed', 'code', and 'keyset' fields."
])
descTable :: RNativeFun e
descTable _ [TTable {..}] = return $ toTObject TyAny def [
("name",tStr $ asString _tTableName),
("module", tStr $ asString _tModuleName),
("type", toTerm $ pack $ showPretty _tTableType)]
descTable i as = argsError i as
descKeySet :: GasRNativeFun e
descKeySet g i [TLitString t] = do
r <- readRow (_faInfo i) KeySets (KeySetName t)
case r of
Just v -> computeGas' g i (GPostRead (ReadKeySet (KeySetName t) v)) $
return $ toTerm v
Nothing -> evalError' i $ "Keyset not found: " <> pretty t
descKeySet _ i as = argsError i as
descModule :: RNativeFun e
descModule i [TLitString t] = do
mods <- lookupModule i (ModuleName t Nothing)
case _mdModule <$> mods of
Just m ->
case m of
MDModule Module{..} ->
return $ toTObject TyAny def
[ ("name" , tStr $ asString _mName)
, ("hash" , tStr $ asString _mHash)
, ("keyset" , tStr $ pack $ show _mGovernance)
, ("blessed" , toTList tTyString def $ map (tStr . asString) (HS.toList _mBlessed))
, ("code" , tStr $ asString _mCode)
, ("interfaces", toTList tTyString def $ (tStr . asString) <$> _mInterfaces)
]
MDInterface Interface{..} ->
return $ toTObject TyAny def
[ ("name", tStr $ asString _interfaceName)
, ("code", tStr $ asString _interfaceCode)
]
Nothing -> evalError' i $ "Module not found: " <> pretty t
descModule i as = argsError i as
-- | unsafe function to create domain from TTable.
userTable :: Show n => Term n -> Domain RowKey RowData
userTable = UserTables . userTable'
-- | unsafe function to create TableName from TTable.
userTable' :: Show n => Term n -> TableName
userTable' TTable {..} = TableName $ asString _tModuleName <> "_" <> asString _tTableName
userTable' t = error $ "creating user table from non-TTable: " ++ show t
read' :: GasRNativeFun e
read' g0 i as@(table@TTable {}:TLitString key:rest) = do
cols <- case rest of
[] -> return []
[l] -> colsToList (argsError i as) l
_ -> argsError i as
guardTable i table GtRead
mrow <- readRow (_faInfo i) (userTable table) (RowKey key)
case mrow of
Nothing -> failTx (_faInfo i) $ "read: row not found: " <> pretty key
Just cs -> do
g <- gasPostRead i g0 cs
fmap (g,) $ case cols of
[] -> return $ columnsToObject (_tTableType table) cs
_ -> columnsToObject' (_tTableType table) cols cs
read' _ i as = argsError i as
foldDB' :: NativeFun e
foldDB' i [tbl, tLamToApp -> TApp qry _, tLamToApp -> TApp consumer _] = do
table <- reduce tbl >>= \case
t@TTable{} -> return t
t -> evalError' i $ "Expected table as first argument to foldDB, got: " <> pretty t
!g0 <- computeGas (Right i) (GUnreduced [])
!g1 <- computeGas (Right i) GFoldDB
ks <- getKeys table
(!g2, xs) <- foldlM (fdb table) (g0+g1, []) ks
pure (g2, TList (V.fromList (reverse xs)) TyAny def)
where
asBool (TLiteral (LBool satisfies) _) = return satisfies
asBool t = evalError' i $ "Unexpected return value from fold-db query condition " <> pretty t
getKeys table = do
guardTable i table GtKeys
keys (_faInfo i) (userTable table)
fdb table (!g0, acc) key = do
mrow <- readRow (_faInfo i) (userTable table) key
case mrow of
Just row -> do
g1 <- gasPostRead i g0 row
let obj = columnsToObject (_tTableType table) row
let key' = toTerm key
cond <- asBool =<< apply qry [key', obj]
if cond then do
r' <- apply consumer [key', obj]
pure (g1, r':acc)
else pure (g1, acc)
Nothing -> evalError (_faInfo i) $ "foldDb: unexpected error, key: "
<> pretty key <> " not found in table: " <> pretty table
foldDB' i as = argsError' i as
gasPostRead :: Readable r => FunApp -> Gas -> r -> Eval e Gas
gasPostRead i g0 row = (g0 +) <$> computeGas (Right i) (GPostRead $ readable row)
gasPostRead' :: Readable r => FunApp -> Gas -> r -> Eval e a -> Eval e (Gas,a)
gasPostRead' i g0 row action = gasPostRead i g0 row >>= \g -> (g,) <$> action
-- | TODO improve post-streaming
gasPostReads :: Readable r => FunApp -> Gas -> ([r] -> a) -> Eval e [r] -> Eval e (Gas,a)
gasPostReads i g0 postProcess action = do
rs <- action
(,postProcess rs) <$> foldM (gasPostRead i) g0 rs
columnsToObject :: Type (Term Name) -> RowData -> Term Name
columnsToObject ty m = TObject (Object (fmap (fromPactValue . rowDataToPactValue) (_rdData m)) ty def def) def
columnsToObject' :: Type (Term Name) -> [(Info,FieldKey)] ->
RowData -> Eval m (Term Name)
columnsToObject' ty cols (RowData _ (ObjectMap m)) = do
ps <- forM cols $ \(ci,col) ->
case M.lookup col m of
Nothing -> evalError ci $ "read: invalid column: " <> pretty col
Just v -> return (col, fromPactValue $ rowDataToPactValue v)
return $ TObject (Object (ObjectMap (M.fromList ps)) ty def def) def
select :: NativeFun e
select i as@[tbl',cols',app] = do
cols <- reduce cols' >>= colsToList (argsError' i as)
reduce tbl' >>= select' i as (Just cols) app
select i as@[tbl',app] = reduce tbl' >>= select' i as Nothing app
select i as = argsError' i as
select' :: FunApp -> [Term Ref] -> Maybe [(Info,FieldKey)] ->
Term Ref -> Term Name -> Eval e (Gas,Term Name)
select' i _ cols' app@TApp{} tbl@TTable{} = do
g0 <- computeGas (Right i) (GUnreduced [])
g1 <- computeGas (Right i) $ GSelect cols'
guardTable i tbl GtSelect
let fi = _faInfo i
tblTy = _tTableType tbl
ks <- keys fi (userTable tbl)
fmap (second (\b -> TList (V.fromList (reverse b)) tblTy def)) $
(\f -> foldM f (g0 + g1, []) ks) $ \(gPrev,rs) k -> do
mrow <- readRow fi (userTable tbl) k
case mrow of
Nothing -> evalError fi $ "select: unexpected error, key not found in select: "
<> pretty k <> ", table: " <> pretty tbl
Just row -> do
g <- gasPostRead i gPrev row
let obj = columnsToObject tblTy row
result <- apply (_tApp app) [obj]
fmap (g,) $ case result of
(TLiteral (LBool include) _)
| include -> case cols' of
Nothing -> return (obj:rs)
Just cols -> (:rs) <$> columnsToObject' tblTy cols row
| otherwise -> return rs
t -> evalError (_tInfo app) $ "select: filter returned non-boolean value: "
<> pretty t
select' i as _ _ _ = argsError' i as
withDefaultRead :: NativeFun e
withDefaultRead fi as@[table',key',defaultRow',b@(TBinding ps bd (BindSchema _) _)] = do
let argsToReduce = [table',key',defaultRow']
(!g0,!tkd) <- gasUnreduced fi argsToReduce (mapM reduce argsToReduce)
case tkd of
[table@TTable {}, TLitString key, TObject (Object defaultRow _ _ _) _] -> do
guardTable fi table GtWithDefaultRead
mrow <- readRow (_faInfo fi) (userTable table) (RowKey key)
case mrow of
Nothing -> (g0,) <$> (bindToRow ps bd b =<< enforcePactValue' defaultRow)
(Just row) -> gasPostRead' fi g0 row $ bindToRow ps bd b (rowDataToPactValue <$> _rdData row)
_ -> argsError' fi as
withDefaultRead fi as = argsError' fi as
withRead :: NativeFun e
withRead fi as@[table',key',b@(TBinding ps bd (BindSchema _) _)] = do
let argsToReduce = [table',key']
(!g0,!tk) <- gasUnreduced fi argsToReduce (mapM reduce argsToReduce)
case tk of
[table@TTable {},TLitString key] -> do
guardTable fi table GtWithRead
mrow <- readRow (_faInfo fi) (userTable table) (RowKey key)
case mrow of
Nothing -> failTx (_faInfo fi) $ "with-read: row not found: " <> pretty key
(Just row) -> gasPostRead' fi g0 row $ bindToRow ps bd b (rowDataToPactValue <$> _rdData row)
_ -> argsError' fi as
withRead fi as = argsError' fi as
bindToRow :: [BindPair (Term Ref)] ->
Scope Int Term Ref -> Term Ref -> ObjectMap PactValue -> Eval e (Term Name)
bindToRow ps bd b (ObjectMap row) =
bindReduce ps bd (_tInfo b) (\s -> fromPactValue <$> M.lookup (FieldKey s) row)
keys' :: GasRNativeFun e
keys' g i [table@TTable {}] = do
gasPostReads i g
((\b -> TList (V.fromList b) tTyString def) . map toTerm) $ do
guardTable i table GtKeys
keys (_faInfo i) (userTable table)
keys' _ i as = argsError i as
txids' :: GasRNativeFun e
txids' g i [table@TTable {},TLitInteger key] = do
checkNonLocalAllowed i
gasPostReads i g
((\b -> TList (V.fromList b) tTyInteger def) . map toTerm) $ do
guardTable i table GtTxIds
txids (_faInfo i) (userTable' table) (fromIntegral key)
txids' _ i as = argsError i as
txlog :: GasRNativeFun e
txlog g i [table@TTable {},TLitInteger tid] = do
checkNonLocalAllowed i
gasPostReads i g (toTList TyAny def . map txlogToObj) $ do
guardTable i table GtTxLog
getTxLog (_faInfo i) (userTable table) (fromIntegral tid)
txlog _ i as = argsError i as
txlogToObj :: TxLog RowData -> Term Name
txlogToObj TxLog{..} = toTObject TyAny def
[ ("table", toTerm _txDomain)
, ("key", toTerm _txKey)
, ("value", toTObjectMap TyAny def (fmap (fromPactValue . rowDataToPactValue) (_rdData _txValue)))
]
checkNonLocalAllowed :: HasInfo i => i -> Eval e ()
checkNonLocalAllowed i = do
env <- ask
disabledInTx <- isExecutionFlagSet FlagDisableHistoryInTransactionalMode
let mode = view eeMode env
when (mode == Transactional && disabledInTx) $ evalError' i $
"Operation only permitted in local execution mode"
keylog :: GasRNativeFun e
keylog g i [table@TTable {..},TLitString key,TLitInteger utid] = do
checkNonLocalAllowed i
let postProc = toTList TyAny def . map toTxidObj
where toTxidObj (t,r) =
toTObject TyAny def [("txid", toTerm t),("value",columnsToObject _tTableType (_txValue r))]
gasPostReads i g postProc $ do
guardTable i table GtKeyLog
tids <- txids (_faInfo i) (userTable' table) (fromIntegral utid)
logs <- fmap concat $ forM tids $ \tid -> map (tid,) <$> getTxLog (_faInfo i) (userTable table) tid
return $ filter (\(_,TxLog {..}) -> _txKey == key) logs
keylog _ i as = argsError i as
write :: WriteType -> SchemaPartial -> NativeFun e
write wt partial i as = do
ts <- mapM reduce as
case ts of
[table@TTable {..},TLitString key,(TObject (Object ps _ _ _) _)] -> do
ps' <- enforcePactValue' ps
cost0 <- computeGas (Right i) (GUnreduced [])
cost1 <- computeGas (Right i) (GPreWrite (WriteData wt (asString key) ps'))
guardTable i table GtWrite
case _tTableType of
TyAny -> return ()
TyVar {} -> return ()
tty -> void $ checkUserType partial (_faInfo i) ps tty
rdv <- ifExecutionFlagSet' FlagDisablePact420 RDV0 RDV1
r <- success "Write succeeded" $ writeRow (_faInfo i) wt (userTable table) (RowKey key) $
RowData rdv (pactValueToRowData <$> ps')
return (cost0 + cost1, r)
_ -> argsError i ts
createTable' :: GasRNativeFun e
createTable' g i [t@TTable {..}] = do
guardTable i t GtCreateTable
let (UserTables tn) = userTable t
computeGas' g i (GPreWrite (WriteTable (asString tn))) $
success "TableCreated" $ createUserTable (_faInfo i) tn _tModuleName
createTable' _ i as = argsError i as
guardTable :: Pretty n => FunApp -> Term n -> GuardTableOp -> Eval e ()
guardTable i TTable {..} dbop =
checkLocalBypass $
guardForModuleCall (_faInfo i) _tModuleName $
enforceBlessedHashes i _tModuleName _tHash
where checkLocalBypass notBypassed = do
localBypassEnabled <- isExecutionFlagSet FlagAllowReadInLocal
case dbop of
GtWrite -> notBypassed
GtCreateTable -> notBypassed
_ | localBypassEnabled -> return ()
| otherwise -> notBypassed
guardTable i t _ = evalError' i $ "Internal error: guardTable called with non-table term: " <> pretty t
enforceBlessedHashes :: FunApp -> ModuleName -> ModuleHash -> Eval e ()
enforceBlessedHashes i mn h = getModule i mn >>= \m -> case (_mdModule m) of
MDModule Module{..}
| h == _mHash -> return () -- current version ok
| h `HS.member` _mBlessed -> return () -- hash is blessed
| otherwise -> evalError' i $
"Execution aborted, hash not blessed for module " <> pretty mn <> ": " <> pretty h
_ -> evalError' i $ "Internal error: expected module reference " <> pretty mn
| kadena-io/pact | src/Pact/Native/Db.hs | bsd-3-clause | 19,739 | 0 | 26 | 4,627 | 6,523 | 3,284 | 3,239 | 388 | 5 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Robot
( Bearing ( East
, North
, South
, West
)
, bearing
, coordinates
, mkRobot
, simulate
, turnLeft
, turnRight
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "robot-simulator" $ do
-- Test cases adapted from `exercism/x-common/robot-simulator.json`
-- on 2016-08-02. Some deviations exist and are noted in comments.
describe "mkRobot" $ do
-- The function described by the reference file
-- as `create` is called `mkRobot` in this track.
it "A robot is created with a position and a direction" $ do
let robot = mkRobot North (0, 0)
coordinates robot `shouldBe` (0, 0)
bearing robot `shouldBe` North
it "Negative positions are allowed" $ do
let robot = mkRobot South (-1, -1)
coordinates robot `shouldBe` (-1, -1)
bearing robot `shouldBe` South
-- The reference tests for `turnLeft` and `turnRight` describe
-- functions that are applied to robots positioned at (0, 0).
-- In this track, they are functions over directions, so those
-- test cases cannot be completely implemented.
describe "turnRight" $ do
it "turn from North" $ turnRight North `shouldBe` East
it "turn from East" $ turnRight East `shouldBe` South
it "turn from South" $ turnRight South `shouldBe` West
it "turn from West" $ turnRight West `shouldBe` North
describe "turnLeft" $ do
it "turn from North" $ turnLeft North `shouldBe` West
it "turn from West" $ turnLeft West `shouldBe` South
it "turn from South" $ turnLeft South `shouldBe` East
it "turn from East" $ turnLeft East `shouldBe` North
describe "simulate advance" $ do
-- The function described by the reference file as `advance`
-- doesn't exist in this track, so we test `simulate` with "A".
let dir `from` pos = simulate (mkRobot dir pos) "A"
it "does not change the direction" $
bearing (North `from` (0, 0)) `shouldBe` North
it "increases the y coordinate one when facing north" $
coordinates (North `from` (0, 0)) `shouldBe` (0, 1)
it "decreases the y coordinate by one when facing south" $
coordinates (South `from` (0, 0)) `shouldBe` (0, -1)
it "increases the x coordinate by one when facing east" $
coordinates (East `from` (0, 0)) `shouldBe` (1, 0)
it "decreases the x coordinate by one when facing west" $
coordinates (West `from` (0, 0)) `shouldBe `(-1, 0)
describe "simulate" $ do
-- The function described by the reference file as
-- `instructions` is called `simulate` in this track.
let simulation pos dir = simulate (mkRobot dir pos)
it "instructions to move west and north" $ do
let robot = simulation (0, 0) North "LAAARALA"
coordinates robot `shouldBe` (-4, 1)
bearing robot `shouldBe` West
it "instructions to move west and south" $ do
let robot = simulation (2, -7) East "RRAAAAALA"
coordinates robot `shouldBe` (-3, -8)
bearing robot `shouldBe` South
it "instructions to move east and north" $ do
let robot = simulation (8, 4) South "LAAARRRALLLL"
coordinates robot `shouldBe` (11, 5)
bearing robot `shouldBe` North
| vaibhav276/exercism_haskell | robot-simulator/test/Tests.hs | mit | 3,575 | 0 | 19 | 979 | 908 | 477 | 431 | 63 | 1 |
module MultipleInnerEntriesRemoved where
import Language.Haskell.Exts (Exp(Var,Con,Lit))
foo = Con
| serokell/importify | test/test-data/haskell-src-exts@constructors/06-MultipleInnerEntriesRemoved.hs | mit | 101 | 0 | 6 | 11 | 28 | 20 | 8 | 3 | 1 |
{-# LANGUAGE FlexibleContexts, OverloadedStrings #-}
-- | Module : Network.MPD.Commands.Parse
-- Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2010
-- License : MIT (see LICENSE)
-- Maintainer : Joachim Fasting <joachim.fasting@gmail.com>
-- Stability : alpha
--
-- Parsers for MPD data types.
module Network.MPD.Commands.Parse where
import Network.MPD.Commands.Types
import Control.Applicative
import Control.Monad.Error
import Data.Maybe (fromMaybe)
import Network.MPD.Util
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.UTF8 as UTF8
-- | Builds a 'Count' instance from an assoc. list.
parseCount :: [ByteString] -> Either String Count
parseCount = foldM f def . toAssocList
where f :: Count -> (ByteString, ByteString) -> Either String Count
f a ("songs", x) = return $ parse parseNum
(\x' -> a { cSongs = x'}) a x
f a ("playtime", x) = return $ parse parseNum
(\x' -> a { cPlaytime = x' }) a x
f _ x = Left $ show x
-- | Builds a list of 'Device' instances from an assoc. list
parseOutputs :: [ByteString] -> Either String [Device]
parseOutputs = mapM (foldM f def)
. splitGroups ["outputid"]
. toAssocList
where f a ("outputid", x) = return $ parse parseNum
(\x' -> a { dOutputID = x' }) a x
f a ("outputname", x) = return a { dOutputName = UTF8.toString x }
f a ("outputenabled", x) = return $ parse parseBool
(\x' -> a { dOutputEnabled = x'}) a x
f _ x = Left $ show x
-- | Builds a 'Stats' instance from an assoc. list.
parseStats :: [ByteString] -> Either String Stats
parseStats = foldM f def . toAssocList
where
f a ("artists", x) = return $ parse parseNum
(\x' -> a { stsArtists = x' }) a x
f a ("albums", x) = return $ parse parseNum
(\x' -> a { stsAlbums = x' }) a x
f a ("songs", x) = return $ parse parseNum
(\x' -> a { stsSongs = x' }) a x
f a ("uptime", x) = return $ parse parseNum
(\x' -> a { stsUptime = x' }) a x
f a ("playtime", x) = return $ parse parseNum
(\x' -> a { stsPlaytime = x' }) a x
f a ("db_playtime", x) = return $ parse parseNum
(\x' -> a { stsDbPlaytime = x' }) a x
f a ("db_update", x) = return $ parse parseNum
(\x' -> a { stsDbUpdate = x' }) a x
f _ x = Left $ show x
parseMaybeSong :: [ByteString] -> Either String (Maybe Song)
parseMaybeSong xs | null xs = Right Nothing
| otherwise = Just <$> (parseSong . toAssocList) xs
-- | Builds a 'Song' instance from an assoc. list.
parseSong :: [(ByteString, ByteString)] -> Either String Song
parseSong xs = case xs of
("file", path):ys -> foldM f (defaultSong (Path path)) ys
_ -> Left "Got a song without a file path! This indicates a bug in either libmpd-haskell or MPD itself!"
where
f :: Song -> (ByteString, ByteString) -> Either String Song
f s ("Last-Modified", v) =
return s { sgLastModified = parseIso8601 v }
f s ("Time", v) =
return s { sgLength = fromMaybe 0 $ parseNum v }
f s ("Id", v) =
return $ parse parseNum (\v' -> s { sgId = Just $ Id v' }) s v
f s ("Pos", v) =
maybe (return $ parse parseNum
(\v' -> s { sgIndex = Just v' }) s v)
(const $ return s)
(sgIndex s)
f s (k, v) = return . maybe s (\m -> sgAddTag m (Value v) s) $
readMeta k
-- Custom-made Read instance
readMeta "ArtistSort" = Just ArtistSort
readMeta "Artist" = Just Artist
readMeta "Album" = Just Album
readMeta "AlbumArtist" = Just AlbumArtist
readMeta "AlbumArtistSort" = Just AlbumArtistSort
readMeta "Title" = Just Title
readMeta "Genre" = Just Genre
readMeta "Name" = Just Name
readMeta "Composer" = Just Composer
readMeta "Performer" = Just Performer
readMeta "Comment" = Just Comment
readMeta "Date" = Just Date
readMeta "Track" = Just Track
readMeta "Disc" = Just Disc
readMeta "MUSICBRAINZ_ARTISTID" = Just MUSICBRAINZ_ARTISTID
readMeta "MUSICBRAINZ_ALBUMID" = Just MUSICBRAINZ_ALBUMID
readMeta "MUSICBRAINZ_ALBUMARTISTID" = Just MUSICBRAINZ_ALBUMARTISTID
readMeta "MUSICBRAINZ_TRACKID" = Just MUSICBRAINZ_TRACKID
readMeta _ = Nothing
-- | A helper that runs a parser on a string and, depending on the
-- outcome, either returns the result of some command applied to the
-- result, or a default value. Used when building structures.
parse :: (ByteString -> Maybe a) -> (a -> b) -> b -> ByteString -> b
parse parser f x = maybe x f . parser
-- | A helper for running a parser returning Maybe on a pair of strings.
-- Returns Just if both strings where parsed successfully, Nothing otherwise.
pair :: (ByteString -> Maybe a) -> (ByteString, ByteString) -> Maybe (a, a)
pair p (x, y) = case (p x, p y) of
(Just a, Just b) -> Just (a, b)
_ -> Nothing
| beni55/libmpd-haskell | src/Network/MPD/Commands/Parse.hs | mit | 5,618 | 0 | 15 | 1,961 | 1,585 | 844 | 741 | 90 | 24 |
{-| Module : TS_Compile
License : GPL
Maintainer : bastiaan@cs.uu.nl
Stability : experimental
Portability : portable
Compile a .type file.
(directives based on "Scripting the Type Inference Process", ICFP 2003)
-}
module Helium.StaticAnalysis.Directives.TS_Compile where
import Helium.StaticAnalysis.Directives.TS_CoreSyntax
import Helium.ModuleSystem.ImportEnvironment
import Helium.StaticAnalysis.Directives.TS_ToCore (typingStrategyToCore)
import System.Exit (exitWith, ExitCode(..) )
import System.Directory (doesFileExist)
import Helium.StaticAnalysis.Directives.TS_Parser (parseTypingStrategies)
import Helium.Parser.Lexer (strategiesLexer)
import Helium.StaticAnalysis.Directives.TS_Analyse (analyseTypingStrategies)
import Helium.StaticAnalysis.Messages.HeliumMessages (sortAndShowMessages)
import Control.Monad (unless, when)
import qualified Helium.Main.Args as Args
import Helium.Parser.ParseMessage ()
import Helium.CodeGeneration.CoreUtils
import Lvm.Core.Expr
readTypingStrategiesFromFile :: [Args.Option] -> String -> ImportEnvironment ->
IO (Core_TypingStrategies, [CoreDecl])
readTypingStrategiesFromFile options filename importEnvironment =
doesFileExist filename >>=
\exists -> if not exists then return ([], []) else
do fileContent <- readFile filename
case strategiesLexer options filename fileContent of
Left lexError -> do
putStrLn "Parse error in typing strategy: "
putStr . sortAndShowMessages $ [lexError]
exitWith (ExitFailure 1)
Right (tokens, _) ->
case parseTypingStrategies (operatorTable importEnvironment) filename tokens of
Left parseError -> do
putStrLn "Parse error in typing strategy: "
putStr . sortAndShowMessages $ [parseError]
exitWith (ExitFailure 1)
Right strategies ->
do let (errors, warnings) = analyseTypingStrategies strategies importEnvironment
unless (null errors) $
do putStr . sortAndShowMessages $ errors
exitWith (ExitFailure 1)
unless (Args.NoWarnings `elem` options || null warnings) $
do putStrLn "\nWarnings in typing strategies:"
putStrLn . sortAndShowMessages $ warnings
let number = length strategies
when (Args.Verbose `elem` options && number > 0) $
putStrLn (" (" ++
(if number == 1
then "1 strategy is included)"
else show number ++ " strategies are included)"))
let coreTypingStrategies = map (typingStrategyToCore importEnvironment) strategies
when (Args.DumpTypeDebug `elem` options) $
do putStrLn "Core typing strategies:"
mapM_ print coreTypingStrategies
return ( coreTypingStrategies, [ customStrategy (show coreTypingStrategies) ] )
| roberth/uu-helium | src/Helium/StaticAnalysis/Directives/TS_Compile.hs | gpl-3.0 | 3,359 | 0 | 25 | 1,127 | 637 | 333 | 304 | 51 | 5 |
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving, Rank2Types,
RecordWildCards #-}
-- |
-- Module: Data.Aeson.Types.Internal
-- Copyright: (c) 2011-2015 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
--
-- Types for working with JSON data.
module Data.Aeson.Types.Internal
(
-- * Core JSON types
Value(..)
, Encoding(..)
, Series(..)
, Array
, emptyArray, isEmptyArray
, Pair
, Object
, emptyObject
-- * Type conversion
, Parser
, Result(..)
, IResult(..)
, JSONPathElement(..)
, JSONPath
, iparse
, parse
, parseEither
, parseMaybe
, modifyFailure
, formatError
, (<?>)
-- * Constructors and accessors
, object
-- * Generic and TH encoding configuration
, Options(..)
, SumEncoding(..)
, defaultOptions
, defaultTaggedObject
-- * Used for changing CamelCase names into something else.
, camelTo
, camelTo2
-- * Other types
, DotNetTime(..)
) where
import Control.Applicative
import Control.Monad
import Control.DeepSeq (NFData(..))
import Data.ByteString.Builder (Builder, char7, toLazyByteString)
import Data.Char (toLower, isUpper, isLower)
import Data.Scientific (Scientific)
import Data.Foldable (Foldable(..))
import Data.Hashable (Hashable(..))
import Data.Data (Data)
import Data.HashMap.Strict (HashMap)
import Data.Monoid (Monoid(..), (<>))
import Data.String (IsString(..))
import Data.Text (Text, pack, unpack)
import Data.Time (UTCTime)
import Data.Time.Format (FormatTime)
import Data.Traversable (Traversable(..))
import Data.Typeable (Typeable)
import Data.Vector (Vector)
import qualified Data.HashMap.Strict as H
import qualified Data.Vector as V
-- | Elements of a JSON path used to describe the location of an
-- error.
data JSONPathElement = Key Text
-- ^ JSON path element of a key into an object,
-- \"object.key\".
| Index {-# UNPACK #-} !Int
-- ^ JSON path element of an index into an
-- array, \"array[index]\".
deriving (Eq, Show, Typeable)
type JSONPath = [JSONPathElement]
-- | The internal result of running a 'Parser'.
data IResult a = IError JSONPath String
| ISuccess a
deriving (Eq, Show, Typeable)
-- | The result of running a 'Parser'.
data Result a = Error String
| Success a
deriving (Eq, Show, Typeable)
instance NFData JSONPathElement where
rnf (Key t) = rnf t
rnf (Index i) = rnf i
instance (NFData a) => NFData (IResult a) where
rnf (ISuccess a) = rnf a
rnf (IError path err) = rnf path `seq` rnf err
instance (NFData a) => NFData (Result a) where
rnf (Success a) = rnf a
rnf (Error err) = rnf err
instance Functor IResult where
fmap f (ISuccess a) = ISuccess (f a)
fmap _ (IError path err) = IError path err
{-# INLINE fmap #-}
instance Functor Result where
fmap f (Success a) = Success (f a)
fmap _ (Error err) = Error err
{-# INLINE fmap #-}
instance Monad IResult where
return = ISuccess
{-# INLINE return #-}
ISuccess a >>= k = k a
IError path err >>= _ = IError path err
{-# INLINE (>>=) #-}
fail err = IError [] err
{-# INLINE fail #-}
instance Monad Result where
return = Success
{-# INLINE return #-}
Success a >>= k = k a
Error err >>= _ = Error err
{-# INLINE (>>=) #-}
fail err = Error err
{-# INLINE fail #-}
instance Applicative IResult where
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance Applicative Result where
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance MonadPlus IResult where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a@(ISuccess _) _ = a
mplus _ b = b
{-# INLINE mplus #-}
instance MonadPlus Result where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a@(Success _) _ = a
mplus _ b = b
{-# INLINE mplus #-}
instance Alternative IResult where
empty = mzero
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance Alternative Result where
empty = mzero
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance Monoid (IResult a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
instance Monoid (Result a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
instance Foldable IResult where
foldMap _ (IError _ _) = mempty
foldMap f (ISuccess y) = f y
{-# INLINE foldMap #-}
foldr _ z (IError _ _) = z
foldr f z (ISuccess y) = f y z
{-# INLINE foldr #-}
instance Foldable Result where
foldMap _ (Error _) = mempty
foldMap f (Success y) = f y
{-# INLINE foldMap #-}
foldr _ z (Error _) = z
foldr f z (Success y) = f y z
{-# INLINE foldr #-}
instance Traversable IResult where
traverse _ (IError path err) = pure (IError path err)
traverse f (ISuccess a) = ISuccess <$> f a
{-# INLINE traverse #-}
instance Traversable Result where
traverse _ (Error err) = pure (Error err)
traverse f (Success a) = Success <$> f a
{-# INLINE traverse #-}
-- | Failure continuation.
type Failure f r = JSONPath -> String -> f r
-- | Success continuation.
type Success a f r = a -> f r
-- | A JSON parser.
newtype Parser a = Parser {
runParser :: forall f r.
JSONPath
-> Failure f r
-> Success a f r
-> f r
}
instance Monad Parser where
m >>= g = Parser $ \path kf ks -> let ks' a = runParser (g a) path kf ks
in runParser m path kf ks'
{-# INLINE (>>=) #-}
return a = Parser $ \_path _kf ks -> ks a
{-# INLINE return #-}
fail msg = Parser $ \path kf _ks -> kf (reverse path) msg
{-# INLINE fail #-}
instance Functor Parser where
fmap f m = Parser $ \path kf ks -> let ks' a = ks (f a)
in runParser m path kf ks'
{-# INLINE fmap #-}
instance Applicative Parser where
pure = return
{-# INLINE pure #-}
(<*>) = apP
{-# INLINE (<*>) #-}
instance Alternative Parser where
empty = fail "empty"
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
instance MonadPlus Parser where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a b = Parser $ \path kf ks -> let kf' _ _ = runParser b path kf ks
in runParser a path kf' ks
{-# INLINE mplus #-}
instance Monoid (Parser a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
apP :: Parser (a -> b) -> Parser a -> Parser b
apP d e = do
b <- d
a <- e
return (b a)
{-# INLINE apP #-}
-- | A JSON \"object\" (key\/value map).
type Object = HashMap Text Value
-- | A JSON \"array\" (sequence).
type Array = Vector Value
-- | A JSON value represented as a Haskell value.
data Value = Object !Object
| Array !Array
| String !Text
| Number !Scientific
| Bool !Bool
| Null
deriving (Eq, Read, Show, Typeable, Data)
-- | An encoding of a JSON value.
newtype Encoding = Encoding {
fromEncoding :: Builder
-- ^ Acquire the underlying bytestring builder.
} deriving (Monoid)
instance Show Encoding where
show (Encoding e) = show (toLazyByteString e)
instance Eq Encoding where
Encoding a == Encoding b = toLazyByteString a == toLazyByteString b
instance Ord Encoding where
compare (Encoding a) (Encoding b) =
compare (toLazyByteString a) (toLazyByteString b)
-- | A series of values that, when encoded, should be separated by commas.
data Series = Empty
| Value Encoding
deriving (Typeable)
instance Monoid Series where
mempty = Empty
mappend Empty a = a
mappend (Value a) b =
Value $
a <> case b of
Empty -> mempty
Value c -> Encoding (char7 ',') <> c
-- | A newtype wrapper for 'UTCTime' that uses the same non-standard
-- serialization format as Microsoft .NET, whose
-- <https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx System.DateTime>
-- type is by default serialized to JSON as in the following example:
--
-- > /Date(1302547608878)/
--
-- The number represents milliseconds since the Unix epoch.
newtype DotNetTime = DotNetTime {
fromDotNetTime :: UTCTime
-- ^ Acquire the underlying value.
} deriving (Eq, Ord, Read, Show, Typeable, FormatTime)
instance NFData Value where
rnf (Object o) = rnf o
rnf (Array a) = V.foldl' (\x y -> rnf y `seq` x) () a
rnf (String s) = rnf s
rnf (Number n) = rnf n
rnf (Bool b) = rnf b
rnf Null = ()
instance IsString Value where
fromString = String . pack
{-# INLINE fromString #-}
hashValue :: Int -> Value -> Int
hashValue s (Object o) = H.foldl' hashWithSalt
(s `hashWithSalt` (0::Int)) o
hashValue s (Array a) = V.foldl' hashWithSalt
(s `hashWithSalt` (1::Int)) a
hashValue s (String str) = s `hashWithSalt` (2::Int) `hashWithSalt` str
hashValue s (Number n) = s `hashWithSalt` (3::Int) `hashWithSalt` n
hashValue s (Bool b) = s `hashWithSalt` (4::Int) `hashWithSalt` b
hashValue s Null = s `hashWithSalt` (5::Int)
instance Hashable Value where
hashWithSalt = hashValue
-- | The empty array.
emptyArray :: Value
emptyArray = Array V.empty
-- | Determines if the 'Value' is an empty 'Array'.
-- Note that: @isEmptyArray 'emptyArray'@.
isEmptyArray :: Value -> Bool
isEmptyArray (Array arr) = V.null arr
isEmptyArray _ = False
-- | The empty object.
emptyObject :: Value
emptyObject = Object H.empty
-- | Run a 'Parser'.
parse :: (a -> Parser b) -> a -> Result b
parse m v = runParser (m v) [] (const Error) Success
{-# INLINE parse #-}
-- | Run a 'Parser'.
iparse :: (a -> Parser b) -> a -> IResult b
iparse m v = runParser (m v) [] IError ISuccess
{-# INLINE iparse #-}
-- | Run a 'Parser' with a 'Maybe' result type.
parseMaybe :: (a -> Parser b) -> a -> Maybe b
parseMaybe m v = runParser (m v) [] (\_ _ -> Nothing) Just
{-# INLINE parseMaybe #-}
-- | Run a 'Parser' with an 'Either' result type. If the parse fails,
-- the 'Left' payload will contain an error message.
parseEither :: (a -> Parser b) -> a -> Either String b
parseEither m v = runParser (m v) [] onError Right
where onError path msg = Left (formatError path msg)
{-# INLINE parseEither #-}
-- | Annotate an error message with a
-- <http://goessner.net/articles/JsonPath/ JSONPath> error location.
formatError :: JSONPath -> String -> String
formatError path msg = "Error in " ++ (format "$" path) ++ ": " ++ msg
where
format pfx [] = pfx
format pfx (Index idx:parts) = format (pfx ++ "[" ++ show idx ++ "]") parts
format pfx (Key key:parts) = format (pfx ++ "." ++ unpack key) parts
-- | A key\/value pair for an 'Object'.
type Pair = (Text, Value)
-- | Create a 'Value' from a list of name\/value 'Pair's. If duplicate
-- keys arise, earlier keys and their associated values win.
object :: [Pair] -> Value
object = Object . H.fromList
{-# INLINE object #-}
-- | Add JSON Path context to a parser
--
-- When parsing complex structure it helps to annotate (sub)parsers
-- with context so that if error occurs you can find it's location.
--
-- > withObject "Person" $ \o ->
-- > Person
-- > <$> o .: "name" <?> Key "name"
-- > <*> o .: "age" <?> Key "age"
--
-- (except for standard methods like '(.:)' already do that)
--
-- After that in case of error you will get a JSON Path location of that error.
--
-- Since 0.9
(<?>) :: Parser a -> JSONPathElement -> Parser a
p <?> pathElem = Parser $ \path kf ks -> runParser p (pathElem:path) kf ks
-- | If the inner @Parser@ failed, modify the failure message using the
-- provided function. This allows you to create more descriptive error messages.
-- For example:
--
-- > parseJSON (Object o) = modifyFailure
-- > ("Parsing of the Foo value failed: " ++)
-- > (Foo <$> o .: "someField")
--
-- Since 0.6.2.0
modifyFailure :: (String -> String) -> Parser a -> Parser a
modifyFailure f (Parser p) = Parser $ \path kf ks -> p path (\p' m -> kf p' (f m)) ks
--------------------------------------------------------------------------------
-- Generic and TH encoding configuration
--------------------------------------------------------------------------------
-- | Options that specify how to encode\/decode your datatype to\/from JSON.
data Options = Options
{ fieldLabelModifier :: String -> String
-- ^ Function applied to field labels.
-- Handy for removing common record prefixes for example.
, constructorTagModifier :: String -> String
-- ^ Function applied to constructor tags which could be handy
-- for lower-casing them for example.
, allNullaryToStringTag :: Bool
-- ^ If 'True' the constructors of a datatype, with /all/
-- nullary constructors, will be encoded to just a string with
-- the constructor tag. If 'False' the encoding will always
-- follow the `sumEncoding`.
, omitNothingFields :: Bool
-- ^ If 'True' record fields with a 'Nothing' value will be
-- omitted from the resulting object. If 'False' the resulting
-- object will include those fields mapping to @null@.
, sumEncoding :: SumEncoding
-- ^ Specifies how to encode constructors of a sum datatype.
, unwrapUnaryRecords :: Bool
-- ^ Hide the field name when a record constructor has only one
-- field, like a newtype.
}
instance Show Options where
show Options{..} = "Options {" ++
"fieldLabelModifier =~ " ++
show (fieldLabelModifier "exampleField") ++ ", " ++
"constructorTagModifier =~ " ++
show (constructorTagModifier "ExampleConstructor") ++ ", " ++
"allNullaryToStringTag = " ++ show allNullaryToStringTag ++ ", " ++
"omitNothingFields = " ++ show omitNothingFields ++ ", " ++
"sumEncoding = " ++ show sumEncoding ++ ", " ++
"unwrapUnaryRecords = " ++ show unwrapUnaryRecords ++
"}"
-- | Specifies how to encode constructors of a sum datatype.
data SumEncoding =
TaggedObject { tagFieldName :: String
, contentsFieldName :: String
}
-- ^ A constructor will be encoded to an object with a field
-- 'tagFieldName' which specifies the constructor tag (modified by
-- the 'constructorTagModifier'). If the constructor is a record
-- the encoded record fields will be unpacked into this object. So
-- make sure that your record doesn't have a field with the same
-- label as the 'tagFieldName'. Otherwise the tag gets overwritten
-- by the encoded value of that field! If the constructor is not a
-- record the encoded constructor contents will be stored under
-- the 'contentsFieldName' field.
| ObjectWithSingleField
-- ^ A constructor will be encoded to an object with a single
-- field named after the constructor tag (modified by the
-- 'constructorTagModifier') which maps to the encoded contents of
-- the constructor.
| TwoElemArray
-- ^ A constructor will be encoded to a 2-element array where the
-- first element is the tag of the constructor (modified by the
-- 'constructorTagModifier') and the second element the encoded
-- contents of the constructor.
deriving (Eq, Show)
-- | Default encoding 'Options':
--
-- @
-- 'Options'
-- { 'fieldLabelModifier' = id
-- , 'constructorTagModifier' = id
-- , 'allNullaryToStringTag' = True
-- , 'omitNothingFields' = False
-- , 'sumEncoding' = 'defaultTaggedObject'
-- }
-- @
defaultOptions :: Options
defaultOptions = Options
{ fieldLabelModifier = id
, constructorTagModifier = id
, allNullaryToStringTag = True
, omitNothingFields = False
, sumEncoding = defaultTaggedObject
, unwrapUnaryRecords = False
}
-- | Default 'TaggedObject' 'SumEncoding' options:
--
-- @
-- defaultTaggedObject = 'TaggedObject'
-- { 'tagFieldName' = \"tag\"
-- , 'contentsFieldName' = \"contents\"
-- }
-- @
defaultTaggedObject :: SumEncoding
defaultTaggedObject = TaggedObject
{ tagFieldName = "tag"
, contentsFieldName = "contents"
}
-- | Converts from CamelCase to another lower case, interspersing
-- the character between all capital letters and their previous
-- entries, except those capital letters that appear together,
-- like 'API'.
--
-- For use by Aeson template haskell calls.
--
-- > camelTo '_' 'CamelCaseAPI' == "camel_case_api"
camelTo :: Char -> String -> String
{-# DEPRECATED camelTo "Use camelTo2 for better results" #-}
camelTo c = lastWasCap True
where
lastWasCap :: Bool -- ^ Previous was a capital letter
-> String -- ^ The remaining string
-> String
lastWasCap _ [] = []
lastWasCap prev (x : xs) = if isUpper x
then if prev
then toLower x : lastWasCap True xs
else c : toLower x : lastWasCap True xs
else x : lastWasCap False xs
-- | Better version of 'camelTo'. Example where it works better:
--
-- > camelTo '_' 'CamelAPICase' == "camel_apicase"
-- > camelTo2 '_' 'CamelAPICase' == "camel_api_case"
camelTo2 :: Char -> String -> String
camelTo2 c = map toLower . go2 . go1
where go1 "" = ""
go1 (x:u:l:xs) | isUpper u && isLower l = x : c : u : l : go1 xs
go1 (x:xs) = x : go1 xs
go2 "" = ""
go2 (l:u:xs) | isLower l && isUpper u = l : c : u : go2 xs
go2 (x:xs) = x : go2 xs
| abbradar/aeson | Data/Aeson/Types/Internal.hs | bsd-3-clause | 18,503 | 0 | 25 | 5,208 | 4,044 | 2,226 | 1,818 | 359 | 5 |
{-# LANGUAGE OverloadedStrings, TypeFamilies, CPP #-}
-- | Events relating to mouse keyboard input.
module Haste.Events.KeyEvents (KeyEvent (..), KeyData (..), mkKeyData) where
import Haste.Any
import Haste.Events.Core
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
-- | Event data for keyboard events.
data KeyData = KeyData {
keyCode :: !Int,
keyCtrl :: !Bool,
keyAlt :: !Bool,
keyShift :: !Bool,
keyMeta :: !Bool
} deriving (Show, Eq)
-- | Build a 'KeyData' object for the given key, without any modifier keys
-- pressed.
mkKeyData :: Int -> KeyData
mkKeyData n = KeyData {
keyCode = fromIntegral n,
keyCtrl = False,
keyAlt = False,
keyShift = False,
keyMeta = False
}
-- | Num instance for KeyData to enable pattern matching against numeric
-- key codes.
instance Num KeyData where
fromInteger = mkKeyData . fromInteger
a + b = a {keyCode = keyCode a + keyCode b}
a * b = a {keyCode = keyCode a * keyCode b}
a - b = a {keyCode = keyCode a - keyCode b}
negate a = a {keyCode = negate $ keyCode a}
signum a = a {keyCode = signum $ keyCode a}
abs a = a {keyCode = abs $ keyCode a}
data KeyEvent
= KeyPress
| KeyUp
| KeyDown
instance Event KeyEvent where
type EventData KeyEvent = KeyData
eventName KeyPress = "keypress"
eventName KeyUp = "keyup"
eventName KeyDown = "keydown"
eventData _ e =
KeyData <$> get e "keyCode"
<*> get e "ctrlKey"
<*> get e "altKey"
<*> get e "shiftKey"
<*> get e "metaKey"
| akru/haste-compiler | libraries/haste-lib/src/Haste/Events/KeyEvents.hs | bsd-3-clause | 1,585 | 0 | 11 | 418 | 440 | 240 | 200 | 52 | 1 |
{-# Language TypeInType #-}
{-# Language TypeOperators, DataKinds, PolyKinds, GADTs #-}
module T14555 where
import Data.Kind
import GHC.Types (TYPE)
data Exp :: [TYPE rep] -> TYPE rep -> Type where
--data Exp (x :: [TYPE rep]) (y :: TYPE rep) where
--data Exp (x :: [TYPE rep]) y where
Lam :: Exp (a:xs) b -> Exp xs (a -> b)
| shlevy/ghc | testsuite/tests/polykinds/T14555.hs | bsd-3-clause | 330 | 0 | 9 | 65 | 80 | 46 | 34 | 7 | 0 |
module Handler.Feed where
import Import
import Model.UserComment
import Text.Blaze.Html (toMarkup)
import Yesod.RssFeed
getFeedR :: SiteId -> Handler RepRss
getFeedR siteId = do
site <- runDB $ get404 siteId
comments <- runDB $ findRecentUserComments siteId
feedFromComments (Entity siteId site) comments
feedFromComments :: Entity Site -> [UserComment] -> Handler RepRss
feedFromComments (Entity siteId site) comments = do
updated <- getUpdated comments
entries <- mapM commentToRssEntry comments
render <- getUrlRender
rssFeedText Feed
{ feedAuthor = siteName site
, feedTitle = "Comments on " <> siteName site
, feedDescription = toHtml $ "Comments on " <> siteName site
, feedLanguage = siteLanguage site
, feedLinkSelf = render $ FeedR siteId
, feedLinkHome = siteBaseUrl site
, feedUpdated = updated
, feedEntries = entries
}
where
getUpdated :: [UserComment] -> Handler UTCTime
getUpdated [] = liftIO $ getCurrentTime
getUpdated (userComment:_) = return $ userCommentCreated $ userComment
commentToRssEntry :: UserComment -> Handler (FeedEntry Text)
commentToRssEntry userComment = return FeedEntry
{ feedEntryLink = siteBaseUrl site <> "/" <> commentArticleURL comment
, feedEntryUpdated = commentCreated comment
, feedEntryTitle = "New comment from "
<> userName user
<> " on " <> commentArticleTitle comment
<> " by " <> commentArticleAuthor comment
, feedEntryContent = toMarkup $ commentBody comment
}
where
comment = entityVal $ userCommentComment userComment
site = entityVal $ userCommentSite userComment
user = entityVal $ userCommentUser userComment
| vaporware/carnival | Handler/Feed.hs | mit | 1,790 | 0 | 13 | 442 | 453 | 230 | 223 | 39 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SES.VerifyEmailAddress
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Verifies an email address. This action causes a confirmation email message to
-- be sent to the specified address.
--
-- The VerifyEmailAddress action is deprecated as of the May 15, 2012 release
-- of Domain Verification. The VerifyEmailIdentity action is now preferred. This
-- action is throttled at one request per second.
--
-- <http://docs.aws.amazon.com/ses/latest/APIReference/API_VerifyEmailAddress.html>
module Network.AWS.SES.VerifyEmailAddress
(
-- * Request
VerifyEmailAddress
-- ** Request constructor
, verifyEmailAddress
-- ** Request lenses
, veaEmailAddress
-- * Response
, VerifyEmailAddressResponse
-- ** Response constructor
, verifyEmailAddressResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.SES.Types
import qualified GHC.Exts
newtype VerifyEmailAddress = VerifyEmailAddress
{ _veaEmailAddress :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'VerifyEmailAddress' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'veaEmailAddress' @::@ 'Text'
--
verifyEmailAddress :: Text -- ^ 'veaEmailAddress'
-> VerifyEmailAddress
verifyEmailAddress p1 = VerifyEmailAddress
{ _veaEmailAddress = p1
}
-- | The email address to be verified.
veaEmailAddress :: Lens' VerifyEmailAddress Text
veaEmailAddress = lens _veaEmailAddress (\s a -> s { _veaEmailAddress = a })
data VerifyEmailAddressResponse = VerifyEmailAddressResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'VerifyEmailAddressResponse' constructor.
verifyEmailAddressResponse :: VerifyEmailAddressResponse
verifyEmailAddressResponse = VerifyEmailAddressResponse
instance ToPath VerifyEmailAddress where
toPath = const "/"
instance ToQuery VerifyEmailAddress where
toQuery VerifyEmailAddress{..} = mconcat
[ "EmailAddress" =? _veaEmailAddress
]
instance ToHeaders VerifyEmailAddress
instance AWSRequest VerifyEmailAddress where
type Sv VerifyEmailAddress = SES
type Rs VerifyEmailAddress = VerifyEmailAddressResponse
request = post "VerifyEmailAddress"
response = nullResponse VerifyEmailAddressResponse
| kim/amazonka | amazonka-ses/gen/Network/AWS/SES/VerifyEmailAddress.hs | mpl-2.0 | 3,256 | 0 | 9 | 672 | 334 | 207 | 127 | 45 | 1 |
{-
(c) The University of Glasgow 2006-2008
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-}
{-# LANGUAGE CPP, NondecreasingIndentation #-}
-- | Module for constructing @ModIface@ values (interface files),
-- writing them to disk and comparing two versions to see if
-- recompilation is required.
module MkIface (
mkUsedNames,
mkDependencies,
mkIface, -- Build a ModIface from a ModGuts,
-- including computing version information
mkIfaceTc,
writeIfaceFile, -- Write the interface file
checkOldIface, -- See if recompilation is required, by
-- comparing version information
RecompileRequired(..), recompileRequired,
tyThingToIfaceDecl -- Converting things to their Iface equivalents
) where
{-
-----------------------------------------------
Recompilation checking
-----------------------------------------------
A complete description of how recompilation checking works can be
found in the wiki commentary:
http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
Please read the above page for a top-down description of how this all
works. Notes below cover specific issues related to the implementation.
Basic idea:
* In the mi_usages information in an interface, we record the
fingerprint of each free variable of the module
* In mkIface, we compute the fingerprint of each exported thing A.f.
For each external thing that A.f refers to, we include the fingerprint
of the external reference when computing the fingerprint of A.f. So
if anything that A.f depends on changes, then A.f's fingerprint will
change.
Also record any dependent files added with
* addDependentFile
* #include
* -optP-include
* In checkOldIface we compare the mi_usages for the module with
the actual fingerprint for all each thing recorded in mi_usages
-}
#include "HsVersions.h"
import IfaceSyn
import LoadIface
import FlagChecker
import Id
import IdInfo
import Demand
import Coercion( tidyCo )
import Annotations
import CoreSyn
import CoreFVs
import Class
import Kind
import TyCon
import CoAxiom
import ConLike
import DataCon
import PatSyn
import Type
import TcType
import TysPrim ( alphaTyVars )
import InstEnv
import FamInstEnv
import TcRnMonad
import HsSyn
import HscTypes
import Finder
import DynFlags
import VarEnv
import VarSet
import Var
import Name
import Avail
import RdrName
import NameEnv
import NameSet
import Module
import BinIface
import ErrUtils
import Digraph
import SrcLoc
import Outputable
import BasicTypes hiding ( SuccessFlag(..) )
import UniqFM
import Unique
import Util hiding ( eqListBy )
import FastString
import Maybes
import ListSetOps
import Binary
import Fingerprint
import Bag
import Exception
import Control.Monad
import Data.Function
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Ord
import Data.IORef
import System.Directory
import System.FilePath
{-
************************************************************************
* *
\subsection{Completing an interface}
* *
************************************************************************
-}
mkIface :: HscEnv
-> Maybe Fingerprint -- The old fingerprint, if we have it
-> ModDetails -- The trimmed, tidied interface
-> ModGuts -- Usages, deprecations, etc
-> IO (Messages,
Maybe (ModIface, -- The new one
Bool)) -- True <=> there was an old Iface, and the
-- new one is identical, so no need
-- to write it
mkIface hsc_env maybe_old_fingerprint mod_details
ModGuts{ mg_module = this_mod,
mg_boot = is_boot,
mg_used_names = used_names,
mg_used_th = used_th,
mg_deps = deps,
mg_dir_imps = dir_imp_mods,
mg_rdr_env = rdr_env,
mg_fix_env = fix_env,
mg_warns = warns,
mg_hpc_info = hpc_info,
mg_safe_haskell = safe_mode,
mg_trust_pkg = self_trust,
mg_dependent_files = dependent_files
}
= mkIface_ hsc_env maybe_old_fingerprint
this_mod is_boot used_names used_th deps rdr_env fix_env
warns hpc_info dir_imp_mods self_trust dependent_files
safe_mode mod_details
-- | make an interface from the results of typechecking only. Useful
-- for non-optimising compilation, or where we aren't generating any
-- object code at all ('HscNothing').
mkIfaceTc :: HscEnv
-> Maybe Fingerprint -- The old fingerprint, if we have it
-> SafeHaskellMode -- The safe haskell mode
-> ModDetails -- gotten from mkBootModDetails, probably
-> TcGblEnv -- Usages, deprecations, etc
-> IO (Messages, Maybe (ModIface, Bool))
mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details
tc_result@TcGblEnv{ tcg_mod = this_mod,
tcg_src = hsc_src,
tcg_imports = imports,
tcg_rdr_env = rdr_env,
tcg_fix_env = fix_env,
tcg_warns = warns,
tcg_hpc = other_hpc_info,
tcg_th_splice_used = tc_splice_used,
tcg_dependent_files = dependent_files
}
= do
let used_names = mkUsedNames tc_result
deps <- mkDependencies tc_result
let hpc_info = emptyHpcInfo other_hpc_info
used_th <- readIORef tc_splice_used
dep_files <- (readIORef dependent_files)
mkIface_ hsc_env maybe_old_fingerprint
this_mod (hsc_src == HsBootFile) used_names
used_th deps rdr_env
fix_env warns hpc_info (imp_mods imports)
(imp_trust_own_pkg imports) dep_files safe_mode mod_details
mkUsedNames :: TcGblEnv -> NameSet
mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
-- | Extract information from the rename and typecheck phases to produce
-- a dependencies information for the module being compiled.
mkDependencies :: TcGblEnv -> IO Dependencies
mkDependencies
TcGblEnv{ tcg_mod = mod,
tcg_imports = imports,
tcg_th_used = th_var
}
= do
-- Template Haskell used?
th_used <- readIORef th_var
let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
-- M.hi-boot can be in the imp_dep_mods, but we must remove
-- it before recording the modules on which this one depends!
-- (We want to retain M.hi-boot in imp_dep_mods so that
-- loadHiBootInterface can see if M's direct imports depend
-- on M.hi-boot, and hence that we should do the hi-boot consistency
-- check.)
pkgs | th_used = insertList thPackageKey (imp_dep_pkgs imports)
| otherwise = imp_dep_pkgs imports
-- Set the packages required to be Safe according to Safe Haskell.
-- See Note [RnNames . Tracking Trust Transitively]
sorted_pkgs = sortBy stablePackageKeyCmp pkgs
trust_pkgs = imp_trust_pkgs imports
dep_pkgs' = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
dep_pkgs = dep_pkgs',
dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
-- sort to get into canonical order
-- NB. remember to use lexicographic ordering
mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> IsBootInterface
-> NameSet -> Bool -> Dependencies -> GlobalRdrEnv
-> NameEnv FixItem -> Warnings -> HpcInfo
-> ImportedMods -> Bool
-> [FilePath]
-> SafeHaskellMode
-> ModDetails
-> IO (Messages, Maybe (ModIface, Bool))
mkIface_ hsc_env maybe_old_fingerprint
this_mod is_boot used_names used_th deps rdr_env fix_env src_warns
hpc_info dir_imp_mods pkg_trust_req dependent_files safe_mode
ModDetails{ md_insts = insts,
md_fam_insts = fam_insts,
md_rules = rules,
md_anns = anns,
md_vect_info = vect_info,
md_types = type_env,
md_exports = exports }
-- NB: notice that mkIface does not look at the bindings
-- only at the TypeEnv. The previous Tidy phase has
-- put exactly the info into the TypeEnv that we want
-- to expose in the interface
= do
usages <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
let entities = typeEnvElts type_env
decls = [ tyThingToIfaceDecl entity
| entity <- entities,
let name = getName entity,
not (isImplicitTyThing entity),
-- No implicit Ids and class tycons in the interface file
not (isWiredInName name),
-- Nor wired-in things; the compiler knows about them anyhow
nameIsLocalOrFrom this_mod name ]
-- Sigh: see Note [Root-main Id] in TcRnDriver
fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
warns = src_warns
iface_rules = map (coreRuleToIfaceRule this_mod) rules
iface_insts = map instanceToIfaceInst insts
iface_fam_insts = map famInstToIfaceFamInst fam_insts
iface_vect_info = flattenVectInfo vect_info
trust_info = setSafeMode safe_mode
annotations = map mkIfaceAnnotation anns
sig_of = getSigOf dflags (moduleName this_mod)
intermediate_iface = ModIface {
mi_module = this_mod,
mi_sig_of = sig_of,
mi_boot = is_boot,
mi_deps = deps,
mi_usages = usages,
mi_exports = mkIfaceExports exports,
-- Sort these lexicographically, so that
-- the result is stable across compilations
mi_insts = sortBy cmp_inst iface_insts,
mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts,
mi_rules = sortBy cmp_rule iface_rules,
mi_vect_info = iface_vect_info,
mi_fixities = fixities,
mi_warns = warns,
mi_anns = annotations,
mi_globals = maybeGlobalRdrEnv rdr_env,
-- Left out deliberately: filled in by addFingerprints
mi_iface_hash = fingerprint0,
mi_mod_hash = fingerprint0,
mi_flag_hash = fingerprint0,
mi_exp_hash = fingerprint0,
mi_used_th = used_th,
mi_orphan_hash = fingerprint0,
mi_orphan = False, -- Always set by addFingerprints, but
-- it's a strict field, so we can't omit it.
mi_finsts = False, -- Ditto
mi_decls = deliberatelyOmitted "decls",
mi_hash_fn = deliberatelyOmitted "hash_fn",
mi_hpc = isHpcUsed hpc_info,
mi_trust = trust_info,
mi_trust_pkg = pkg_trust_req,
-- And build the cached values
mi_warn_fn = mkIfaceWarnCache warns,
mi_fix_fn = mkIfaceFixCache fixities }
(new_iface, no_change_at_all)
<- {-# SCC "versioninfo" #-}
addFingerprints hsc_env maybe_old_fingerprint
intermediate_iface decls
-- Warn about orphans
-- See Note [Orphans and auto-generated rules]
let warn_orphs = wopt Opt_WarnOrphans dflags
warn_auto_orphs = wopt Opt_WarnAutoOrphans dflags
orph_warnings --- Laziness means no work done unless -fwarn-orphans
| warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
| otherwise = emptyBag
errs_and_warns = (orph_warnings, emptyBag)
unqual = mkPrintUnqualified dflags rdr_env
inst_warns = listToBag [ instOrphWarn dflags unqual d
| (d,i) <- insts `zip` iface_insts
, isOrphan (ifInstOrph i) ]
rule_warns = listToBag [ ruleOrphWarn dflags unqual this_mod r
| r <- iface_rules
, isOrphan (ifRuleOrph r)
, if ifRuleAuto r then warn_auto_orphs
else warn_orphs ]
if errorsFound dflags errs_and_warns
then return ( errs_and_warns, Nothing )
else do
-- Debug printing
dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
(pprModIface new_iface)
-- bug #1617: on reload we weren't updating the PrintUnqualified
-- correctly. This stems from the fact that the interface had
-- not changed, so addFingerprints returns the old ModIface
-- with the old GlobalRdrEnv (mi_globals).
let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env }
return (errs_and_warns, Just (final_iface, no_change_at_all))
where
cmp_rule = comparing ifRuleName
-- Compare these lexicographically by OccName, *not* by unique,
-- because the latter is not stable across compilations:
cmp_inst = comparing (nameOccName . ifDFun)
cmp_fam_inst = comparing (nameOccName . ifFamInstTcName)
dflags = hsc_dflags hsc_env
-- We only fill in mi_globals if the module was compiled to byte
-- code. Otherwise, the compiler may not have retained all the
-- top-level bindings and they won't be in the TypeEnv (see
-- Desugar.addExportFlagsAndRules). The mi_globals field is used
-- by GHCi to decide whether the module has its full top-level
-- scope available. (#5534)
maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv
maybeGlobalRdrEnv rdr_env
| targetRetainsAllBindings (hscTarget dflags) = Just rdr_env
| otherwise = Nothing
deliberatelyOmitted :: String -> a
deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
ifFamInstTcName = ifFamInstFam
flattenVectInfo (VectInfo { vectInfoVar = vVar
, vectInfoTyCon = vTyCon
, vectInfoParallelVars = vParallelVars
, vectInfoParallelTyCons = vParallelTyCons
}) =
IfaceVectInfo
{ ifaceVectInfoVar = [Var.varName v | (v, _ ) <- varEnvElts vVar]
, ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
, ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
, ifaceVectInfoParallelVars = [Var.varName v | v <- varSetElems vParallelVars]
, ifaceVectInfoParallelTyCons = nameSetElems vParallelTyCons
}
-----------------------------
writeIfaceFile :: DynFlags -> FilePath -> ModIface -> IO ()
writeIfaceFile dflags hi_file_path new_iface
= do createDirectoryIfMissing True (takeDirectory hi_file_path)
writeBinIface dflags hi_file_path new_iface
-- -----------------------------------------------------------------------------
-- Look up parents and versions of Names
-- This is like a global version of the mi_hash_fn field in each ModIface.
-- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
-- the parent and version info.
mkHashFun
:: HscEnv -- needed to look up versions
-> ExternalPackageState -- ditto
-> (Name -> Fingerprint)
mkHashFun hsc_env eps
= \name ->
let
mod = ASSERT2( isExternalName name, ppr name ) nameModule name
occ = nameOccName name
iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
pprPanic "lookupVers2" (ppr mod <+> ppr occ)
in
snd (mi_hash_fn iface occ `orElse`
pprPanic "lookupVers1" (ppr mod <+> ppr occ))
where
hpt = hsc_HPT hsc_env
pit = eps_PIT eps
-- ---------------------------------------------------------------------------
-- Compute fingerprints for the interface
addFingerprints
:: HscEnv
-> Maybe Fingerprint -- the old fingerprint, if any
-> ModIface -- The new interface (lacking decls)
-> [IfaceDecl] -- The new decls
-> IO (ModIface, -- Updated interface
Bool) -- True <=> no changes at all;
-- no need to write Iface
addFingerprints hsc_env mb_old_fingerprint iface0 new_decls
= do
eps <- hscEPS hsc_env
let
-- The ABI of a declaration represents everything that is made
-- visible about the declaration that a client can depend on.
-- see IfaceDeclABI below.
declABI :: IfaceDecl -> IfaceDeclABI
declABI decl = (this_mod, decl, extras)
where extras = declExtras fix_fn ann_fn non_orph_rules non_orph_insts
non_orph_fis decl
edges :: [(IfaceDeclABI, Unique, [Unique])]
edges = [ (abi, getUnique (ifName decl), out)
| decl <- new_decls
, let abi = declABI decl
, let out = localOccs $ freeNamesDeclABI abi
]
name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
localOccs = map (getUnique . getParent . getOccName)
. filter ((== this_mod) . name_module)
. nameSetElems
where getParent occ = lookupOccEnv parent_map occ `orElse` occ
-- maps OccNames to their parents in the current module.
-- e.g. a reference to a constructor must be turned into a reference
-- to the TyCon for the purposes of calculating dependencies.
parent_map :: OccEnv OccName
parent_map = foldr extend emptyOccEnv new_decls
where extend d env =
extendOccEnvList env [ (b,n) | b <- ifaceDeclImplicitBndrs d ]
where n = ifName d
-- strongly-connected groups of declarations, in dependency order
groups = stronglyConnCompFromEdgedVertices edges
global_hash_fn = mkHashFun hsc_env eps
-- how to output Names when generating the data to fingerprint.
-- Here we want to output the fingerprint for each top-level
-- Name, whether it comes from the current module or another
-- module. In this way, the fingerprint for a declaration will
-- change if the fingerprint for anything it refers to (transitively)
-- changes.
mk_put_name :: (OccEnv (OccName,Fingerprint))
-> BinHandle -> Name -> IO ()
mk_put_name local_env bh name
| isWiredInName name = putNameLiterally bh name
-- wired-in names don't have fingerprints
| otherwise
= ASSERT2( isExternalName name, ppr name )
let hash | nameModule name /= this_mod = global_hash_fn name
| otherwise = snd (lookupOccEnv local_env (getOccName name)
`orElse` pprPanic "urk! lookup local fingerprint"
(ppr name)) -- (undefined,fingerprint0))
-- This panic indicates that we got the dependency
-- analysis wrong, because we needed a fingerprint for
-- an entity that wasn't in the environment. To debug
-- it, turn the panic into a trace, uncomment the
-- pprTraces below, run the compile again, and inspect
-- the output and the generated .hi file with
-- --show-iface.
in put_ bh hash
-- take a strongly-connected group of declarations and compute
-- its fingerprint.
fingerprint_group :: (OccEnv (OccName,Fingerprint),
[(Fingerprint,IfaceDecl)])
-> SCC IfaceDeclABI
-> IO (OccEnv (OccName,Fingerprint),
[(Fingerprint,IfaceDecl)])
fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
= do let hash_fn = mk_put_name local_env
decl = abiDecl abi
-- pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
hash <- computeFingerprint hash_fn abi
env' <- extend_hash_env local_env (hash,decl)
return (env', (hash,decl) : decls_w_hashes)
fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
= do let decls = map abiDecl abis
local_env1 <- foldM extend_hash_env local_env
(zip (repeat fingerprint0) decls)
let hash_fn = mk_put_name local_env1
-- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
let stable_abis = sortBy cmp_abiNames abis
-- put the cycle in a canonical order
hash <- computeFingerprint hash_fn stable_abis
let pairs = zip (repeat hash) decls
local_env2 <- foldM extend_hash_env local_env pairs
return (local_env2, pairs ++ decls_w_hashes)
-- we have fingerprinted the whole declaration, but we now need
-- to assign fingerprints to all the OccNames that it binds, to
-- use when referencing those OccNames in later declarations.
--
extend_hash_env :: OccEnv (OccName,Fingerprint)
-> (Fingerprint,IfaceDecl)
-> IO (OccEnv (OccName,Fingerprint))
extend_hash_env env0 (hash,d) = do
return (foldr (\(b,fp) env -> extendOccEnv env b (b,fp)) env0
(ifaceDeclFingerprints hash d))
--
(local_env, decls_w_hashes) <-
foldM fingerprint_group (emptyOccEnv, []) groups
-- when calculating fingerprints, we always need to use canonical
-- ordering for lists of things. In particular, the mi_deps has various
-- lists of modules and suchlike, so put these all in canonical order:
let sorted_deps = sortDependencies (mi_deps iface0)
-- the export hash of a module depends on the orphan hashes of the
-- orphan modules below us in the dependency tree. This is the way
-- that changes in orphans get propagated all the way up the
-- dependency tree. We only care about orphan modules in the current
-- package, because changes to orphans outside this package will be
-- tracked by the usage on the ABI hash of package modules that we import.
let orph_mods = filter ((== this_pkg) . modulePackageKey)
$ dep_orphs sorted_deps
dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods
orphan_hash <- computeFingerprint (mk_put_name local_env)
(map ifDFun orph_insts, orph_rules, orph_fis)
-- the export list hash doesn't depend on the fingerprints of
-- the Names it mentions, only the Names themselves, hence putNameLiterally.
export_hash <- computeFingerprint putNameLiterally
(mi_exports iface0,
orphan_hash,
dep_orphan_hashes,
dep_pkgs (mi_deps iface0),
-- dep_pkgs: see "Package Version Changes" on
-- wiki/Commentary/Compiler/RecompilationAvoidance
mi_trust iface0)
-- Make sure change of Safe Haskell mode causes recomp.
-- put the declarations in a canonical order, sorted by OccName
let sorted_decls = Map.elems $ Map.fromList $
[(ifName d, e) | e@(_, d) <- decls_w_hashes]
-- the flag hash depends on:
-- - (some of) dflags
-- it returns two hashes, one that shouldn't change
-- the abi hash and one that should
flag_hash <- fingerprintDynFlags dflags this_mod putNameLiterally
-- the ABI hash depends on:
-- - decls
-- - export list
-- - orphans
-- - deprecations
-- - vect info
-- - flag abi hash
mod_hash <- computeFingerprint putNameLiterally
(map fst sorted_decls,
export_hash, -- includes orphan_hash
mi_warns iface0,
mi_vect_info iface0)
-- The interface hash depends on:
-- - the ABI hash, plus
-- - the module level annotations,
-- - usages
-- - deps (home and external packages, dependent files)
-- - hpc
iface_hash <- computeFingerprint putNameLiterally
(mod_hash,
ann_fn (mkVarOcc "module"), -- See mkIfaceAnnCache
mi_usages iface0,
sorted_deps,
mi_hpc iface0)
let
no_change_at_all = Just iface_hash == mb_old_fingerprint
final_iface = iface0 {
mi_mod_hash = mod_hash,
mi_iface_hash = iface_hash,
mi_exp_hash = export_hash,
mi_orphan_hash = orphan_hash,
mi_flag_hash = flag_hash,
mi_orphan = not ( all ifRuleAuto orph_rules
-- See Note [Orphans and auto-generated rules]
&& null orph_insts
&& null orph_fis
&& isNoIfaceVectInfo (mi_vect_info iface0)),
mi_finsts = not . null $ mi_fam_insts iface0,
mi_decls = sorted_decls,
mi_hash_fn = lookupOccEnv local_env }
--
return (final_iface, no_change_at_all)
where
this_mod = mi_module iface0
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
(non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
(non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
(non_orph_fis, orph_fis) = mkOrphMap ifFamInstOrph (mi_fam_insts iface0)
fix_fn = mi_fix_fn iface0
ann_fn = mkIfaceAnnCache (mi_anns iface0)
getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
getOrphanHashes hsc_env mods = do
eps <- hscEPS hsc_env
let
hpt = hsc_HPT hsc_env
pit = eps_PIT eps
dflags = hsc_dflags hsc_env
get_orph_hash mod =
case lookupIfaceByModule dflags hpt pit mod of
Nothing -> pprPanic "moduleOrphanHash" (ppr mod)
Just iface -> mi_orphan_hash iface
--
return (map get_orph_hash mods)
sortDependencies :: Dependencies -> Dependencies
sortDependencies d
= Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
dep_pkgs = sortBy (stablePackageKeyCmp `on` fst) (dep_pkgs d),
dep_orphs = sortBy stableModuleCmp (dep_orphs d),
dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
-- | Creates cached lookup for the 'mi_anns' field of ModIface
-- Hackily, we use "module" as the OccName for any module-level annotations
mkIfaceAnnCache :: [IfaceAnnotation] -> OccName -> [AnnPayload]
mkIfaceAnnCache anns
= \n -> lookupOccEnv env n `orElse` []
where
pair (IfaceAnnotation target value) =
(case target of
NamedTarget occn -> occn
ModuleTarget _ -> mkVarOcc "module"
, [value])
-- flipping (++), so the first argument is always short
env = mkOccEnv_C (flip (++)) (map pair anns)
{-
Note [Orphans and auto-generated rules]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we specialise an INLINEABLE function, or when we have
-fspecialise-aggressively, we auto-generate RULES that are orphans.
We don't want to warn about these, at least not by default, or we'd
generate a lot of warnings. Hence -fwarn-auto-orphans.
Indeed, we don't even treat the module as an oprhan module if it has
auto-generated *rule* orphans. Orphan modules are read every time we
compile, so they are pretty obtrusive and slow down every compilation,
even non-optimised ones. (Reason: for type class instances it's a
type correctness issue.) But specialisation rules are strictly for
*optimisation* only so it's fine not to read the interface.
What this means is that a SPEC rules from auto-specialisation in
module M will be used in other modules only if M.hi has been read for
some other reason, which is actually pretty likely.
************************************************************************
* *
The ABI of an IfaceDecl
* *
************************************************************************
Note [The ABI of an IfaceDecl]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ABI of a declaration consists of:
(a) the full name of the identifier (inc. module and package,
because these are used to construct the symbol name by which
the identifier is known externally).
(b) the declaration itself, as exposed to clients. That is, the
definition of an Id is included in the fingerprint only if
it is made available as an unfolding in the interface.
(c) the fixity of the identifier
(d) for Ids: rules
(e) for classes: instances, fixity & rules for methods
(f) for datatypes: instances, fixity & rules for constrs
Items (c)-(f) are not stored in the IfaceDecl, but instead appear
elsewhere in the interface file. But they are *fingerprinted* with
the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
and fingerprinting that as part of the declaration.
-}
type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)
data IfaceDeclExtras
= IfaceIdExtras IfaceIdExtras
| IfaceDataExtras
Fixity -- Fixity of the tycon itself
[IfaceInstABI] -- Local class and family instances of this tycon
-- See Note [Orphans] in InstEnv
[AnnPayload] -- Annotations of the type itself
[IfaceIdExtras] -- For each constructor: fixity, RULES and annotations
| IfaceClassExtras
Fixity -- Fixity of the class itself
[IfaceInstABI] -- Local instances of this class *or*
-- of its associated data types
-- See Note [Orphans] in InstEnv
[AnnPayload] -- Annotations of the type itself
[IfaceIdExtras] -- For each class method: fixity, RULES and annotations
| IfaceSynonymExtras Fixity [AnnPayload]
| IfaceFamilyExtras Fixity [IfaceInstABI] [AnnPayload]
| IfaceOtherDeclExtras
data IfaceIdExtras
= IdExtras
Fixity -- Fixity of the Id
[IfaceRule] -- Rules for the Id
[AnnPayload] -- Annotations for the Id
-- When hashing a class or family instance, we hash only the
-- DFunId or CoAxiom, because that depends on all the
-- information about the instance.
--
type IfaceInstABI = IfExtName -- Name of DFunId or CoAxiom that is evidence for the instance
abiDecl :: IfaceDeclABI -> IfaceDecl
abiDecl (_, decl, _) = decl
cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare`
ifName (abiDecl abi2)
freeNamesDeclABI :: IfaceDeclABI -> NameSet
freeNamesDeclABI (_mod, decl, extras) =
freeNamesIfDecl decl `unionNameSet` freeNamesDeclExtras extras
freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
freeNamesDeclExtras (IfaceIdExtras id_extras)
= freeNamesIdExtras id_extras
freeNamesDeclExtras (IfaceDataExtras _ insts _ subs)
= unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
freeNamesDeclExtras (IfaceClassExtras _ insts _ subs)
= unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
freeNamesDeclExtras (IfaceSynonymExtras _ _)
= emptyNameSet
freeNamesDeclExtras (IfaceFamilyExtras _ insts _)
= mkNameSet insts
freeNamesDeclExtras IfaceOtherDeclExtras
= emptyNameSet
freeNamesIdExtras :: IfaceIdExtras -> NameSet
freeNamesIdExtras (IdExtras _ rules _) = unionNameSets (map freeNamesIfRule rules)
instance Outputable IfaceDeclExtras where
ppr IfaceOtherDeclExtras = Outputable.empty
ppr (IfaceIdExtras extras) = ppr_id_extras extras
ppr (IfaceSynonymExtras fix anns) = vcat [ppr fix, ppr anns]
ppr (IfaceFamilyExtras fix finsts anns) = vcat [ppr fix, ppr finsts, ppr anns]
ppr (IfaceDataExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
ppr_id_extras_s stuff]
ppr (IfaceClassExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
ppr_id_extras_s stuff]
ppr_insts :: [IfaceInstABI] -> SDoc
ppr_insts _ = ptext (sLit "<insts>")
ppr_id_extras_s :: [IfaceIdExtras] -> SDoc
ppr_id_extras_s stuff = vcat (map ppr_id_extras stuff)
ppr_id_extras :: IfaceIdExtras -> SDoc
ppr_id_extras (IdExtras fix rules anns) = ppr fix $$ vcat (map ppr rules) $$ vcat (map ppr anns)
-- This instance is used only to compute fingerprints
instance Binary IfaceDeclExtras where
get _bh = panic "no get for IfaceDeclExtras"
put_ bh (IfaceIdExtras extras) = do
putByte bh 1; put_ bh extras
put_ bh (IfaceDataExtras fix insts anns cons) = do
putByte bh 2; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh cons
put_ bh (IfaceClassExtras fix insts anns methods) = do
putByte bh 3; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh methods
put_ bh (IfaceSynonymExtras fix anns) = do
putByte bh 4; put_ bh fix; put_ bh anns
put_ bh (IfaceFamilyExtras fix finsts anns) = do
putByte bh 5; put_ bh fix; put_ bh finsts; put_ bh anns
put_ bh IfaceOtherDeclExtras = putByte bh 6
instance Binary IfaceIdExtras where
get _bh = panic "no get for IfaceIdExtras"
put_ bh (IdExtras fix rules anns)= do { put_ bh fix; put_ bh rules; put_ bh anns }
declExtras :: (OccName -> Fixity)
-> (OccName -> [AnnPayload])
-> OccEnv [IfaceRule]
-> OccEnv [IfaceClsInst]
-> OccEnv [IfaceFamInst]
-> IfaceDecl
-> IfaceDeclExtras
declExtras fix_fn ann_fn rule_env inst_env fi_env decl
= case decl of
IfaceId{} -> IfaceIdExtras (id_extras n)
IfaceData{ifCons=cons} ->
IfaceDataExtras (fix_fn n)
(map ifFamInstAxiom (lookupOccEnvL fi_env n) ++
map ifDFun (lookupOccEnvL inst_env n))
(ann_fn n)
(map (id_extras . ifConOcc) (visibleIfConDecls cons))
IfaceClass{ifSigs=sigs, ifATs=ats} ->
IfaceClassExtras (fix_fn n)
(map ifDFun $ (concatMap at_extras ats)
++ lookupOccEnvL inst_env n)
-- Include instances of the associated types
-- as well as instances of the class (Trac #5147)
(ann_fn n)
[id_extras op | IfaceClassOp op _ _ <- sigs]
IfaceSynonym{} -> IfaceSynonymExtras (fix_fn n)
(ann_fn n)
IfaceFamily{} -> IfaceFamilyExtras (fix_fn n)
(map ifFamInstAxiom (lookupOccEnvL fi_env n))
(ann_fn n)
_other -> IfaceOtherDeclExtras
where
n = ifName decl
id_extras occ = IdExtras (fix_fn occ) (lookupOccEnvL rule_env occ) (ann_fn occ)
at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl)
lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
lookupOccEnvL env k = lookupOccEnv env k `orElse` []
-- used when we want to fingerprint a structure without depending on the
-- fingerprints of external Names that it refers to.
putNameLiterally :: BinHandle -> Name -> IO ()
putNameLiterally bh name = ASSERT( isExternalName name )
do
put_ bh $! nameModule name
put_ bh $! nameOccName name
{-
-- for testing: use the md5sum command to generate fingerprints and
-- compare the results against our built-in version.
fp' <- oldMD5 dflags bh
if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
else return fp
oldMD5 dflags bh = do
tmp <- newTempName dflags "bin"
writeBinMem bh tmp
tmp2 <- newTempName dflags "md5"
let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
r <- system cmd
case r of
ExitFailure _ -> throwGhcExceptionIO (PhaseFailed cmd r)
ExitSuccess -> do
hash_str <- readFile tmp2
return $! readHexFingerprint hash_str
-}
instOrphWarn :: DynFlags -> PrintUnqualified -> ClsInst -> WarnMsg
instOrphWarn dflags unqual inst
= mkWarnMsg dflags (getSrcSpan inst) unqual $
hang (ptext (sLit "Orphan instance:")) 2 (pprInstanceHdr inst)
$$ text "To avoid this"
$$ nest 4 (vcat possibilities)
where
possibilities =
text "move the instance declaration to the module of the class or of the type, or" :
text "wrap the type with a newtype and declare the instance on the new type." :
[]
ruleOrphWarn :: DynFlags -> PrintUnqualified -> Module -> IfaceRule -> WarnMsg
ruleOrphWarn dflags unqual mod rule
= mkWarnMsg dflags silly_loc unqual $
ptext (sLit "Orphan rule:") <+> ppr rule
where
silly_loc = srcLocSpan (mkSrcLoc (moduleNameFS (moduleName mod)) 1 1)
-- We don't have a decent SrcSpan for a Rule, not even the CoreRule
-- Could readily be fixed by adding a SrcSpan to CoreRule, if we wanted to
----------------------
-- mkOrphMap partitions instance decls or rules into
-- (a) an OccEnv for ones that are not orphans,
-- mapping the local OccName to a list of its decls
-- (b) a list of orphan decls
mkOrphMap :: (decl -> IsOrphan) -- Extract orphan status from decl
-> [decl] -- Sorted into canonical order
-> (OccEnv [decl], -- Non-orphan decls associated with their key;
-- each sublist in canonical order
[decl]) -- Orphan decls; in canonical order
mkOrphMap get_key decls
= foldl go (emptyOccEnv, []) decls
where
go (non_orphs, orphs) d
| NotOrphan occ <- get_key d
= (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
| otherwise = (non_orphs, d:orphs)
{-
************************************************************************
* *
Keeping track of what we've slurped, and fingerprints
* *
************************************************************************
-}
mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> [FilePath] -> IO [Usage]
mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
= do
eps <- hscEPS hsc_env
hashes <- mapM getFileHash dependent_files
let mod_usages = mk_mod_usage_info (eps_PIT eps) hsc_env this_mod
dir_imp_mods used_names
let usages = mod_usages ++ [ UsageFile { usg_file_path = f
, usg_file_hash = hash }
| (f, hash) <- zip dependent_files hashes ]
usages `seqList` return usages
-- seq the list of Usages returned: occasionally these
-- don't get evaluated for a while and we can end up hanging on to
-- the entire collection of Ifaces.
mk_mod_usage_info :: PackageIfaceTable
-> HscEnv
-> Module
-> ImportedMods
-> NameSet
-> [Usage]
mk_mod_usage_info pit hsc_env this_mod direct_imports used_names
= mapMaybe mkUsage usage_mods
where
hpt = hsc_HPT hsc_env
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
used_mods = moduleEnvKeys ent_map
dir_imp_mods = moduleEnvKeys direct_imports
all_mods = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
usage_mods = sortBy stableModuleCmp all_mods
-- canonical order is imported, to avoid interface-file
-- wobblage.
-- ent_map groups together all the things imported and used
-- from a particular module
ent_map :: ModuleEnv [OccName]
ent_map = foldNameSet add_mv emptyModuleEnv used_names
where
add_mv name mv_map
| isWiredInName name = mv_map -- ignore wired-in names
| otherwise
= case nameModule_maybe name of
Nothing -> ASSERT2( isSystemName name, ppr name ) mv_map
-- See Note [Internal used_names]
Just mod -> -- This lambda function is really just a
-- specialised (++); originally came about to
-- avoid quadratic behaviour (trac #2680)
extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
where occ = nameOccName name
-- We want to create a Usage for a home module if
-- a) we used something from it; has something in used_names
-- b) we imported it, even if we used nothing from it
-- (need to recompile if its export list changes: export_fprint)
mkUsage :: Module -> Maybe Usage
mkUsage mod
| isNothing maybe_iface -- We can't depend on it if we didn't
-- load its interface.
|| mod == this_mod -- We don't care about usages of
-- things in *this* module
= Nothing
| modulePackageKey mod /= this_pkg
= Just UsagePackageModule{ usg_mod = mod,
usg_mod_hash = mod_hash,
usg_safe = imp_safe }
-- for package modules, we record the module hash only
| (null used_occs
&& isNothing export_hash
&& not is_direct_import
&& not finsts_mod)
= Nothing -- Record no usage info
-- for directly-imported modules, we always want to record a usage
-- on the orphan hash. This is what triggers a recompilation if
-- an orphan is added or removed somewhere below us in the future.
| otherwise
= Just UsageHomeModule {
usg_mod_name = moduleName mod,
usg_mod_hash = mod_hash,
usg_exports = export_hash,
usg_entities = Map.toList ent_hashs,
usg_safe = imp_safe }
where
maybe_iface = lookupIfaceByModule dflags hpt pit mod
-- In one-shot mode, the interfaces for home-package
-- modules accumulate in the PIT not HPT. Sigh.
Just iface = maybe_iface
finsts_mod = mi_finsts iface
hash_env = mi_hash_fn iface
mod_hash = mi_mod_hash iface
export_hash | depend_on_exports = Just (mi_exp_hash iface)
| otherwise = Nothing
(is_direct_import, imp_safe)
= case lookupModuleEnv direct_imports mod of
Just ((_,_,_,safe):_xs) -> (True, safe)
Just _ -> pprPanic "mkUsage: empty direct import" Outputable.empty
Nothing -> (False, safeImplicitImpsReq dflags)
-- Nothing case is for implicit imports like 'System.IO' when 'putStrLn'
-- is used in the source code. We require them to be safe in Safe Haskell
used_occs = lookupModuleEnv ent_map mod `orElse` []
-- Making a Map here ensures that (a) we remove duplicates
-- when we have usages on several subordinates of a single parent,
-- and (b) that the usages emerge in a canonical order, which
-- is why we use Map rather than OccEnv: Map works
-- using Ord on the OccNames, which is a lexicographic ordering.
ent_hashs :: Map OccName Fingerprint
ent_hashs = Map.fromList (map lookup_occ used_occs)
lookup_occ occ =
case hash_env occ of
Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
Just r -> r
depend_on_exports = is_direct_import
{- True
Even if we used 'import M ()', we have to register a
usage on the export list because we are sensitive to
changes in orphan instances/rules.
False
In GHC 6.8.x we always returned true, and in
fact it recorded a dependency on *all* the
modules underneath in the dependency tree. This
happens to make orphans work right, but is too
expensive: it'll read too many interface files.
The 'isNothing maybe_iface' check above saved us
from generating many of these usages (at least in
one-shot mode), but that's even more bogus!
-}
mkIfaceAnnotation :: Annotation -> IfaceAnnotation
mkIfaceAnnotation (Annotation { ann_target = target, ann_value = payload })
= IfaceAnnotation {
ifAnnotatedTarget = fmap nameOccName target,
ifAnnotatedValue = payload
}
mkIfaceExports :: [AvailInfo] -> [IfaceExport] -- Sort to make canonical
mkIfaceExports exports
= sortBy stableAvailCmp (map sort_subs exports)
where
sort_subs :: AvailInfo -> AvailInfo
sort_subs (Avail n) = Avail n
sort_subs (AvailTC n []) = AvailTC n []
sort_subs (AvailTC n (m:ms))
| n==m = AvailTC n (m:sortBy stableNameCmp ms)
| otherwise = AvailTC n (sortBy stableNameCmp (m:ms))
-- Maintain the AvailTC Invariant
{-
Note [Orignal module]
~~~~~~~~~~~~~~~~~~~~~
Consider this:
module X where { data family T }
module Y( T(..) ) where { import X; data instance T Int = MkT Int }
The exported Avail from Y will look like
X.T{X.T, Y.MkT}
That is, in Y,
- only MkT is brought into scope by the data instance;
- but the parent (used for grouping and naming in T(..) exports) is X.T
- and in this case we export X.T too
In the result of MkIfaceExports, the names are grouped by defining module,
so we may need to split up a single Avail into multiple ones.
Note [Internal used_names]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Most of the used_names are External Names, but we can have Internal
Names too: see Note [Binders in Template Haskell] in Convert, and
Trac #5362 for an example. Such Names are always
- Such Names are always for locally-defined things, for which we
don't gather usage info, so we can just ignore them in ent_map
- They are always System Names, hence the assert, just as a double check.
************************************************************************
* *
Load the old interface file for this module (unless
we have it already), and check whether it is up to date
* *
************************************************************************
-}
data RecompileRequired
= UpToDate
-- ^ everything is up to date, recompilation is not required
| MustCompile
-- ^ The .hs file has been touched, or the .o/.hi file does not exist
| RecompBecause String
-- ^ The .o/.hi files are up to date, but something else has changed
-- to force recompilation; the String says what (one-line summary)
deriving Eq
recompileRequired :: RecompileRequired -> Bool
recompileRequired UpToDate = False
recompileRequired _ = True
-- | Top level function to check if the version of an old interface file
-- is equivalent to the current source file the user asked us to compile.
-- If the same, we can avoid recompilation. We return a tuple where the
-- first element is a bool saying if we should recompile the object file
-- and the second is maybe the interface file, where Nothng means to
-- rebuild the interface file not use the exisitng one.
checkOldIface
:: HscEnv
-> ModSummary
-> SourceModified
-> Maybe ModIface -- Old interface from compilation manager, if any
-> IO (RecompileRequired, Maybe ModIface)
checkOldIface hsc_env mod_summary source_modified maybe_iface
= do let dflags = hsc_dflags hsc_env
showPass dflags $
"Checking old interface for " ++
(showPpr dflags $ ms_mod mod_summary)
initIfaceCheck hsc_env $
check_old_iface hsc_env mod_summary source_modified maybe_iface
check_old_iface
:: HscEnv
-> ModSummary
-> SourceModified
-> Maybe ModIface
-> IfG (RecompileRequired, Maybe ModIface)
check_old_iface hsc_env mod_summary src_modified maybe_iface
= let dflags = hsc_dflags hsc_env
getIface =
case maybe_iface of
Just _ -> do
traceIf (text "We already have the old interface for" <+>
ppr (ms_mod mod_summary))
return maybe_iface
Nothing -> loadIface
loadIface = do
let iface_path = msHiFilePath mod_summary
read_result <- readIface (ms_mod mod_summary) iface_path
case read_result of
Failed err -> do
traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err)
return Nothing
Succeeded iface -> do
traceIf (text "Read the interface file" <+> text iface_path)
return $ Just iface
src_changed
| gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True
| SourceModified <- src_modified = True
| otherwise = False
in do
when src_changed $
traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")
case src_changed of
-- If the source has changed and we're in interactive mode,
-- avoid reading an interface; just return the one we might
-- have been supplied with.
True | not (isObjectTarget $ hscTarget dflags) ->
return (MustCompile, maybe_iface)
-- Try and read the old interface for the current module
-- from the .hi file left from the last time we compiled it
True -> do
maybe_iface' <- getIface
return (MustCompile, maybe_iface')
False -> do
maybe_iface' <- getIface
case maybe_iface' of
-- We can't retrieve the iface
Nothing -> return (MustCompile, Nothing)
-- We have got the old iface; check its versions
-- even in the SourceUnmodifiedAndStable case we
-- should check versions because some packages
-- might have changed or gone away.
Just iface -> checkVersions hsc_env mod_summary iface
-- | Check if a module is still the same 'version'.
--
-- This function is called in the recompilation checker after we have
-- determined that the module M being checked hasn't had any changes
-- to its source file since we last compiled M. So at this point in general
-- two things may have changed that mean we should recompile M:
-- * The interface export by a dependency of M has changed.
-- * The compiler flags specified this time for M have changed
-- in a manner that is significant for recompilaiton.
-- We return not just if we should recompile the object file but also
-- if we should rebuild the interface file.
checkVersions :: HscEnv
-> ModSummary
-> ModIface -- Old interface
-> IfG (RecompileRequired, Maybe ModIface)
checkVersions hsc_env mod_summary iface
= do { traceHiDiffs (text "Considering whether compilation is required for" <+>
ppr (mi_module iface) <> colon)
; recomp <- checkFlagHash hsc_env iface
; if recompileRequired recomp then return (recomp, Nothing) else do {
; if getSigOf (hsc_dflags hsc_env) (moduleName (mi_module iface))
/= mi_sig_of iface
then return (RecompBecause "sig-of changed", Nothing) else do {
; recomp <- checkDependencies hsc_env mod_summary iface
; if recompileRequired recomp then return (recomp, Just iface) else do {
-- Source code unchanged and no errors yet... carry on
--
-- First put the dependent-module info, read from the old
-- interface, into the envt, so that when we look for
-- interfaces we look for the right one (.hi or .hi-boot)
--
-- It's just temporary because either the usage check will succeed
-- (in which case we are done with this module) or it'll fail (in which
-- case we'll compile the module from scratch anyhow).
--
-- We do this regardless of compilation mode, although in --make mode
-- all the dependent modules should be in the HPT already, so it's
-- quite redundant
; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
; recomp <- checkList [checkModUsage this_pkg u | u <- mi_usages iface]
; return (recomp, Just iface)
}}}}
where
this_pkg = thisPackage (hsc_dflags hsc_env)
-- This is a bit of a hack really
mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
mod_deps = mkModDeps (dep_mods (mi_deps iface))
-- | Check the flags haven't changed
checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired
checkFlagHash hsc_env iface = do
let old_hash = mi_flag_hash iface
new_hash <- liftIO $ fingerprintDynFlags (hsc_dflags hsc_env)
(mi_module iface)
putNameLiterally
case old_hash == new_hash of
True -> up_to_date (ptext $ sLit "Module flags unchanged")
False -> out_of_date_hash "flags changed"
(ptext $ sLit " Module flags have changed")
old_hash new_hash
-- If the direct imports of this module are resolved to targets that
-- are not among the dependencies of the previous interface file,
-- then we definitely need to recompile. This catches cases like
-- - an exposed package has been upgraded
-- - we are compiling with different package flags
-- - a home module that was shadowing a package module has been removed
-- - a new home module has been added that shadows a package module
-- See bug #1372.
--
-- Returns True if recompilation is required.
checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
checkDependencies hsc_env summary iface
= checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary))
where
prev_dep_mods = dep_mods (mi_deps iface)
prev_dep_pkgs = dep_pkgs (mi_deps iface)
this_pkg = thisPackage (hsc_dflags hsc_env)
dep_missing (L _ (ImportDecl { ideclName = L _ mod, ideclPkgQual = pkg })) = do
find_res <- liftIO $ findImportedModule hsc_env mod pkg
let reason = moduleNameString mod ++ " changed"
case find_res of
Found _ mod
| pkg == this_pkg
-> if moduleName mod `notElem` map fst prev_dep_mods
then do traceHiDiffs $
text "imported module " <> quotes (ppr mod) <>
text " not among previous dependencies"
return (RecompBecause reason)
else
return UpToDate
| otherwise
-> if pkg `notElem` (map fst prev_dep_pkgs)
then do traceHiDiffs $
text "imported module " <> quotes (ppr mod) <>
text " is from package " <> quotes (ppr pkg) <>
text ", which is not among previous dependencies"
return (RecompBecause reason)
else
return UpToDate
where pkg = modulePackageKey mod
_otherwise -> return (RecompBecause reason)
needInterface :: Module -> (ModIface -> IfG RecompileRequired)
-> IfG RecompileRequired
needInterface mod continue
= do -- Load the imported interface if possible
let doc_str = sep [ptext (sLit "need version info for"), ppr mod]
traceHiDiffs (text "Checking usages for module" <+> ppr mod)
mb_iface <- loadInterface doc_str mod ImportBySystem
-- Load the interface, but don't complain on failure;
-- Instead, get an Either back which we can test
case mb_iface of
Failed _ -> do
traceHiDiffs (sep [ptext (sLit "Couldn't load interface for module"),
ppr mod])
return MustCompile
-- Couldn't find or parse a module mentioned in the
-- old interface file. Don't complain: it might
-- just be that the current module doesn't need that
-- import and it's been deleted
Succeeded iface -> continue iface
-- | Given the usage information extracted from the old
-- M.hi file for the module being compiled, figure out
-- whether M needs to be recompiled.
checkModUsage :: PackageKey -> Usage -> IfG RecompileRequired
checkModUsage _this_pkg UsagePackageModule{
usg_mod = mod,
usg_mod_hash = old_mod_hash }
= needInterface mod $ \iface -> do
let reason = moduleNameString (moduleName mod) ++ " changed"
checkModuleFingerprint reason old_mod_hash (mi_mod_hash iface)
-- We only track the ABI hash of package modules, rather than
-- individual entity usages, so if the ABI hash changes we must
-- recompile. This is safe but may entail more recompilation when
-- a dependent package has changed.
checkModUsage this_pkg UsageHomeModule{
usg_mod_name = mod_name,
usg_mod_hash = old_mod_hash,
usg_exports = maybe_old_export_hash,
usg_entities = old_decl_hash }
= do
let mod = mkModule this_pkg mod_name
needInterface mod $ \iface -> do
let
new_mod_hash = mi_mod_hash iface
new_decl_hash = mi_hash_fn iface
new_export_hash = mi_exp_hash iface
reason = moduleNameString mod_name ++ " changed"
-- CHECK MODULE
recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash
if not (recompileRequired recompile)
then return UpToDate
else do
-- CHECK EXPORT LIST
checkMaybeHash reason maybe_old_export_hash new_export_hash
(ptext (sLit " Export list changed")) $ do
-- CHECK ITEMS ONE BY ONE
recompile <- checkList [ checkEntityUsage reason new_decl_hash u
| u <- old_decl_hash]
if recompileRequired recompile
then return recompile -- This one failed, so just bail out now
else up_to_date (ptext (sLit " Great! The bits I use are up to date"))
checkModUsage _this_pkg UsageFile{ usg_file_path = file,
usg_file_hash = old_hash } =
liftIO $
handleIO handle $ do
new_hash <- getFileHash file
if (old_hash /= new_hash)
then return recomp
else return UpToDate
where
recomp = RecompBecause (file ++ " changed")
handle =
#ifdef DEBUG
\e -> pprTrace "UsageFile" (text (show e)) $ return recomp
#else
\_ -> return recomp -- if we can't find the file, just recompile, don't fail
#endif
------------------------
checkModuleFingerprint :: String -> Fingerprint -> Fingerprint
-> IfG RecompileRequired
checkModuleFingerprint reason old_mod_hash new_mod_hash
| new_mod_hash == old_mod_hash
= up_to_date (ptext (sLit "Module fingerprint unchanged"))
| otherwise
= out_of_date_hash reason (ptext (sLit " Module fingerprint has changed"))
old_mod_hash new_mod_hash
------------------------
checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc
-> IfG RecompileRequired -> IfG RecompileRequired
checkMaybeHash reason maybe_old_hash new_hash doc continue
| Just hash <- maybe_old_hash, hash /= new_hash
= out_of_date_hash reason doc hash new_hash
| otherwise
= continue
------------------------
checkEntityUsage :: String
-> (OccName -> Maybe (OccName, Fingerprint))
-> (OccName, Fingerprint)
-> IfG RecompileRequired
checkEntityUsage reason new_hash (name,old_hash)
= case new_hash name of
Nothing -> -- We used it before, but it ain't there now
out_of_date reason (sep [ptext (sLit "No longer exported:"), ppr name])
Just (_, new_hash) -- It's there, but is it up to date?
| new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))
return UpToDate
| otherwise -> out_of_date_hash reason (ptext (sLit " Out of date:") <+> ppr name)
old_hash new_hash
up_to_date :: SDoc -> IfG RecompileRequired
up_to_date msg = traceHiDiffs msg >> return UpToDate
out_of_date :: String -> SDoc -> IfG RecompileRequired
out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason)
out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired
out_of_date_hash reason msg old_hash new_hash
= out_of_date reason (hsep [msg, ppr old_hash, ptext (sLit "->"), ppr new_hash])
----------------------
checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
-- This helper is used in two places
checkList [] = return UpToDate
checkList (check:checks) = do recompile <- check
if recompileRequired recompile
then return recompile
else checkList checks
{-
************************************************************************
* *
Converting things to their Iface equivalents
* *
************************************************************************
-}
tyThingToIfaceDecl :: TyThing -> IfaceDecl
tyThingToIfaceDecl (AnId id) = idToIfaceDecl id
tyThingToIfaceDecl (ATyCon tycon) = snd (tyConToIfaceDecl emptyTidyEnv tycon)
tyThingToIfaceDecl (ACoAxiom ax) = coAxiomToIfaceDecl ax
tyThingToIfaceDecl (AConLike cl) = case cl of
RealDataCon dc -> dataConToIfaceDecl dc -- for ppr purposes only
PatSynCon ps -> patSynToIfaceDecl ps
--------------------------
idToIfaceDecl :: Id -> IfaceDecl
-- The Id is already tidied, so that locally-bound names
-- (lambdas, for-alls) already have non-clashing OccNames
-- We can't tidy it here, locally, because it may have
-- free variables in its type or IdInfo
idToIfaceDecl id
= IfaceId { ifName = getOccName id,
ifType = toIfaceType (idType id),
ifIdDetails = toIfaceIdDetails (idDetails id),
ifIdInfo = toIfaceIdInfo (idInfo id) }
--------------------------
dataConToIfaceDecl :: DataCon -> IfaceDecl
dataConToIfaceDecl dataCon
= IfaceId { ifName = getOccName dataCon,
ifType = toIfaceType (dataConUserType dataCon),
ifIdDetails = IfVanillaId,
ifIdInfo = NoInfo }
--------------------------
patSynToIfaceDecl :: PatSyn -> IfaceDecl
patSynToIfaceDecl ps
= IfacePatSyn { ifName = getOccName . getName $ ps
, ifPatMatcher = to_if_pr (patSynMatcher ps)
, ifPatBuilder = fmap to_if_pr (patSynBuilder ps)
, ifPatIsInfix = patSynIsInfix ps
, ifPatUnivTvs = toIfaceTvBndrs univ_tvs'
, ifPatExTvs = toIfaceTvBndrs ex_tvs'
, ifPatProvCtxt = tidyToIfaceContext env2 prov_theta
, ifPatReqCtxt = tidyToIfaceContext env2 req_theta
, ifPatArgs = map (tidyToIfaceType env2) args
, ifPatTy = tidyToIfaceType env2 rhs_ty
}
where
(univ_tvs, ex_tvs, prov_theta, req_theta, args, rhs_ty) = patSynSig ps
(env1, univ_tvs') = tidyTyVarBndrs emptyTidyEnv univ_tvs
(env2, ex_tvs') = tidyTyVarBndrs env1 ex_tvs
to_if_pr (id, needs_dummy) = (idName id, needs_dummy)
--------------------------
coAxiomToIfaceDecl :: CoAxiom br -> IfaceDecl
-- We *do* tidy Axioms, because they are not (and cannot
-- conveniently be) built in tidy form
coAxiomToIfaceDecl ax@(CoAxiom { co_ax_tc = tycon, co_ax_branches = branches
, co_ax_role = role })
= IfaceAxiom { ifName = name
, ifTyCon = toIfaceTyCon tycon
, ifRole = role
, ifAxBranches = brListMap (coAxBranchToIfaceBranch tycon
(brListMap coAxBranchLHS branches))
branches }
where
name = getOccName ax
-- 2nd parameter is the list of branch LHSs, for conversion from incompatible branches
-- to incompatible indices
-- See Note [Storing compatibility] in CoAxiom
coAxBranchToIfaceBranch :: TyCon -> [[Type]] -> CoAxBranch -> IfaceAxBranch
coAxBranchToIfaceBranch tc lhs_s
branch@(CoAxBranch { cab_incomps = incomps })
= (coAxBranchToIfaceBranch' tc branch) { ifaxbIncomps = iface_incomps }
where
iface_incomps = map (expectJust "iface_incomps"
. (flip findIndex lhs_s
. eqTypes)
. coAxBranchLHS) incomps
-- use this one for standalone branches without incompatibles
coAxBranchToIfaceBranch' :: TyCon -> CoAxBranch -> IfaceAxBranch
coAxBranchToIfaceBranch' tc (CoAxBranch { cab_tvs = tvs, cab_lhs = lhs
, cab_roles = roles, cab_rhs = rhs })
= IfaceAxBranch { ifaxbTyVars = toIfaceTvBndrs tv_bndrs
, ifaxbLHS = tidyToIfaceTcArgs env1 tc lhs
, ifaxbRoles = roles
, ifaxbRHS = tidyToIfaceType env1 rhs
, ifaxbIncomps = [] }
where
(env1, tv_bndrs) = tidyTyClTyVarBndrs emptyTidyEnv tvs
-- Don't re-bind in-scope tyvars
-- See Note [CoAxBranch type variables] in CoAxiom
-----------------
tyConToIfaceDecl :: TidyEnv -> TyCon -> (TidyEnv, IfaceDecl)
-- We *do* tidy TyCons, because they are not (and cannot
-- conveniently be) built in tidy form
-- The returned TidyEnv is the one after tidying the tyConTyVars
tyConToIfaceDecl env tycon
| Just clas <- tyConClass_maybe tycon
= classToIfaceDecl env clas
| Just syn_rhs <- synTyConRhs_maybe tycon
= ( tc_env1
, IfaceSynonym { ifName = getOccName tycon,
ifTyVars = if_tc_tyvars,
ifRoles = tyConRoles tycon,
ifSynRhs = if_syn_type syn_rhs,
ifSynKind = tidyToIfaceType tc_env1 (synTyConResKind tycon)
})
| Just fam_flav <- famTyConFlav_maybe tycon
= ( tc_env1
, IfaceFamily { ifName = getOccName tycon,
ifTyVars = if_tc_tyvars,
ifFamFlav = to_if_fam_flav fam_flav,
ifFamKind = tidyToIfaceType tc_env1 (synTyConResKind tycon)
})
| isAlgTyCon tycon
= ( tc_env1
, IfaceData { ifName = getOccName tycon,
ifCType = tyConCType tycon,
ifTyVars = if_tc_tyvars,
ifRoles = tyConRoles tycon,
ifCtxt = tidyToIfaceContext tc_env1 (tyConStupidTheta tycon),
ifCons = ifaceConDecls (algTyConRhs tycon),
ifRec = boolToRecFlag (isRecursiveTyCon tycon),
ifGadtSyntax = isGadtSyntaxTyCon tycon,
ifPromotable = isJust (promotableTyCon_maybe tycon),
ifParent = parent })
| otherwise -- FunTyCon, PrimTyCon, promoted TyCon/DataCon
-- For pretty printing purposes only.
= ( env
, IfaceData { ifName = getOccName tycon,
ifCType = Nothing,
ifTyVars = funAndPrimTyVars,
ifRoles = tyConRoles tycon,
ifCtxt = [],
ifCons = IfDataTyCon [],
ifRec = boolToRecFlag False,
ifGadtSyntax = False,
ifPromotable = False,
ifParent = IfNoParent })
where
(tc_env1, tc_tyvars) = tidyTyClTyVarBndrs env (tyConTyVars tycon)
if_tc_tyvars = toIfaceTvBndrs tc_tyvars
if_syn_type ty = tidyToIfaceType tc_env1 ty
funAndPrimTyVars = toIfaceTvBndrs $ take (tyConArity tycon) alphaTyVars
parent = case tyConFamInstSig_maybe tycon of
Just (tc, ty, ax) -> IfDataInstance (coAxiomName ax)
(toIfaceTyCon tc)
(tidyToIfaceTcArgs tc_env1 tc ty)
Nothing -> IfNoParent
to_if_fam_flav OpenSynFamilyTyCon = IfaceOpenSynFamilyTyCon
to_if_fam_flav (ClosedSynFamilyTyCon ax) = IfaceClosedSynFamilyTyCon axn ibr
where defs = fromBranchList $ coAxiomBranches ax
ibr = map (coAxBranchToIfaceBranch' tycon) defs
axn = coAxiomName ax
to_if_fam_flav AbstractClosedSynFamilyTyCon
= IfaceAbstractClosedSynFamilyTyCon
to_if_fam_flav (BuiltInSynFamTyCon {})
= IfaceBuiltInSynFamTyCon
ifaceConDecls (NewTyCon { data_con = con }) = IfNewTyCon (ifaceConDecl con)
ifaceConDecls (DataTyCon { data_cons = cons }) = IfDataTyCon (map ifaceConDecl cons)
ifaceConDecls (DataFamilyTyCon {}) = IfDataFamTyCon
ifaceConDecls (AbstractTyCon distinct) = IfAbstractTyCon distinct
-- The last case happens when a TyCon has been trimmed during tidying
-- Furthermore, tyThingToIfaceDecl is also used
-- in TcRnDriver for GHCi, when browsing a module, in which case the
-- AbstractTyCon case is perfectly sensible.
ifaceConDecl data_con
= IfCon { ifConOcc = getOccName (dataConName data_con),
ifConInfix = dataConIsInfix data_con,
ifConWrapper = isJust (dataConWrapId_maybe data_con),
ifConExTvs = toIfaceTvBndrs ex_tvs',
ifConEqSpec = map to_eq_spec eq_spec,
ifConCtxt = tidyToIfaceContext con_env2 theta,
ifConArgTys = map (tidyToIfaceType con_env2) arg_tys,
ifConFields = map getOccName
(dataConFieldLabels data_con),
ifConStricts = map (toIfaceBang con_env2) (dataConImplBangs data_con) }
where
(univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con
-- Tidy the univ_tvs of the data constructor to be identical
-- to the tyConTyVars of the type constructor. This means
-- (a) we don't need to redundantly put them into the interface file
-- (b) when pretty-printing an Iface data declaration in H98-style syntax,
-- we know that the type variables will line up
-- The latter (b) is important because we pretty-print type construtors
-- by converting to IfaceSyn and pretty-printing that
con_env1 = (fst tc_env1, mkVarEnv (zipEqual "ifaceConDecl" univ_tvs tc_tyvars))
-- A bit grimy, perhaps, but it's simple!
(con_env2, ex_tvs') = tidyTyVarBndrs con_env1 ex_tvs
to_eq_spec (tv,ty) = (toIfaceTyVar (tidyTyVar con_env2 tv), tidyToIfaceType con_env2 ty)
toIfaceBang :: TidyEnv -> HsImplBang -> IfaceBang
toIfaceBang _ HsNoBang = IfNoBang
toIfaceBang _ (HsUnpack Nothing) = IfUnpack
toIfaceBang env (HsUnpack (Just co)) = IfUnpackCo (toIfaceCoercion (tidyCo env co))
toIfaceBang _ HsStrict = IfStrict
toIfaceBang _ (HsSrcBang {}) = panic "toIfaceBang"
classToIfaceDecl :: TidyEnv -> Class -> (TidyEnv, IfaceDecl)
classToIfaceDecl env clas
= ( env1
, IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta,
ifName = getOccName (classTyCon clas),
ifTyVars = toIfaceTvBndrs clas_tyvars',
ifRoles = tyConRoles (classTyCon clas),
ifFDs = map toIfaceFD clas_fds,
ifATs = map toIfaceAT clas_ats,
ifSigs = map toIfaceClassOp op_stuff,
ifMinDef = fmap getFS (classMinimalDef clas),
ifRec = boolToRecFlag (isRecursiveTyCon tycon) })
where
(clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
= classExtraBigSig clas
tycon = classTyCon clas
(env1, clas_tyvars') = tidyTyVarBndrs env clas_tyvars
toIfaceAT :: ClassATItem -> IfaceAT
toIfaceAT (ATI tc def)
= IfaceAT if_decl (fmap (tidyToIfaceType env2) def)
where
(env2, if_decl) = tyConToIfaceDecl env1 tc
toIfaceClassOp (sel_id, def_meth)
= ASSERT(sel_tyvars == clas_tyvars)
IfaceClassOp (getOccName sel_id) (toDmSpec def_meth)
(tidyToIfaceType env1 op_ty)
where
-- Be careful when splitting the type, because of things
-- like class Foo a where
-- op :: (?x :: String) => a -> a
-- and class Baz a where
-- op :: (Ord a) => a -> a
(sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
op_ty = funResultTy rho_ty
toDmSpec NoDefMeth = NoDM
toDmSpec (GenDefMeth _) = GenericDM
toDmSpec (DefMeth _) = VanillaDM
toIfaceFD (tvs1, tvs2) = (map (getFS . tidyTyVar env1) tvs1,
map (getFS . tidyTyVar env1) tvs2)
--------------------------
tidyToIfaceType :: TidyEnv -> Type -> IfaceType
tidyToIfaceType env ty = toIfaceType (tidyType env ty)
tidyToIfaceTcArgs :: TidyEnv -> TyCon -> [Type] -> IfaceTcArgs
tidyToIfaceTcArgs env tc tys = toIfaceTcArgs tc (tidyTypes env tys)
tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext
tidyToIfaceContext env theta = map (tidyToIfaceType env) theta
tidyTyClTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyTyClTyVarBndrs env tvs = mapAccumL tidyTyClTyVarBndr env tvs
tidyTyClTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- If the type variable "binder" is in scope, don't re-bind it
-- In a class decl, for example, the ATD binders mention
-- (amd must mention) the class tyvars
tidyTyClTyVarBndr env@(_, subst) tv
| Just tv' <- lookupVarEnv subst tv = (env, tv')
| otherwise = tidyTyVarBndr env tv
tidyTyVar :: TidyEnv -> TyVar -> TyVar
tidyTyVar (_, subst) tv = lookupVarEnv subst tv `orElse` tv
-- TcType.tidyTyVarOcc messes around with FlatSkols
getFS :: NamedThing a => a -> FastString
getFS x = occNameFS (getOccName x)
--------------------------
instanceToIfaceInst :: ClsInst -> IfaceClsInst
instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag
, is_cls_nm = cls_name, is_cls = cls
, is_tcs = mb_tcs
, is_orphan = orph })
= ASSERT( cls_name == className cls )
IfaceClsInst { ifDFun = dfun_name,
ifOFlag = oflag,
ifInstCls = cls_name,
ifInstTys = map do_rough mb_tcs,
ifInstOrph = orph }
where
do_rough Nothing = Nothing
do_rough (Just n) = Just (toIfaceTyCon_name n)
dfun_name = idName dfun_id
--------------------------
famInstToIfaceFamInst :: FamInst -> IfaceFamInst
famInstToIfaceFamInst (FamInst { fi_axiom = axiom,
fi_fam = fam,
fi_tcs = roughs })
= IfaceFamInst { ifFamInstAxiom = coAxiomName axiom
, ifFamInstFam = fam
, ifFamInstTys = map do_rough roughs
, ifFamInstOrph = orph }
where
do_rough Nothing = Nothing
do_rough (Just n) = Just (toIfaceTyCon_name n)
fam_decl = tyConName $ coAxiomTyCon axiom
mod = ASSERT( isExternalName (coAxiomName axiom) )
nameModule (coAxiomName axiom)
is_local name = nameIsLocalOrFrom mod name
lhs_names = filterNameSet is_local (orphNamesOfCoCon axiom)
orph | is_local fam_decl
= NotOrphan (nameOccName fam_decl)
| not (isEmptyNameSet lhs_names)
= NotOrphan (nameOccName (head (nameSetElems lhs_names)))
| otherwise
= IsOrphan
--------------------------
toIfaceLetBndr :: Id -> IfaceLetBndr
toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
(toIfaceType (idType id))
(toIfaceIdInfo (idInfo id))
-- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr
-- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn
--------------------------
toIfaceIdDetails :: IdDetails -> IfaceIdDetails
toIfaceIdDetails VanillaId = IfVanillaId
toIfaceIdDetails (DFunId {}) = IfDFunId
toIfaceIdDetails (RecSelId { sel_naughty = n
, sel_tycon = tc }) = IfRecSelId (toIfaceTyCon tc) n
toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other)
IfVanillaId -- Unexpected
toIfaceIdInfo :: IdInfo -> IfaceIdInfo
toIfaceIdInfo id_info
= case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
inline_hsinfo, unfold_hsinfo] of
[] -> NoInfo
infos -> HasInfo infos
-- NB: strictness and arity must appear in the list before unfolding
-- See TcIface.tcUnfolding
where
------------ Arity --------------
arity_info = arityInfo id_info
arity_hsinfo | arity_info == 0 = Nothing
| otherwise = Just (HsArity arity_info)
------------ Caf Info --------------
caf_info = cafInfo id_info
caf_hsinfo = case caf_info of
NoCafRefs -> Just HsNoCafRefs
_other -> Nothing
------------ Strictness --------------
-- No point in explicitly exporting TopSig
sig_info = strictnessInfo id_info
strict_hsinfo | not (isNopSig sig_info) = Just (HsStrictness sig_info)
| otherwise = Nothing
------------ Unfolding --------------
unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info)
loop_breaker = isStrongLoopBreaker (occInfo id_info)
------------ Inline prag --------------
inline_prag = inlinePragInfo id_info
inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing
| otherwise = Just (HsInline inline_prag)
--------------------------
toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem
toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs
, uf_src = src
, uf_guidance = guidance })
= Just $ HsUnfold lb $
case src of
InlineStable
-> case guidance of
UnfWhen {ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
-> IfInlineRule arity unsat_ok boring_ok if_rhs
_other -> IfCoreUnfold True if_rhs
InlineCompulsory -> IfCompulsory if_rhs
InlineRhs -> IfCoreUnfold False if_rhs
-- Yes, even if guidance is UnfNever, expose the unfolding
-- If we didn't want to expose the unfolding, TidyPgm would
-- have stuck in NoUnfolding. For supercompilation we want
-- to see that unfolding!
where
if_rhs = toIfaceExpr rhs
toIfUnfolding lb (DFunUnfolding { df_bndrs = bndrs, df_args = args })
= Just (HsUnfold lb (IfDFunUnfold (map toIfaceBndr bndrs) (map toIfaceExpr args)))
-- No need to serialise the data constructor;
-- we can recover it from the type of the dfun
toIfUnfolding _ _
= Nothing
--------------------------
coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
coreRuleToIfaceRule _ (BuiltinRule { ru_fn = fn})
= pprTrace "toHsRule: builtin" (ppr fn) $
bogusIfaceRule fn
coreRuleToIfaceRule mod rule@(Rule { ru_name = name, ru_fn = fn,
ru_act = act, ru_bndrs = bndrs,
ru_args = args, ru_rhs = rhs,
ru_auto = auto })
= IfaceRule { ifRuleName = name, ifActivation = act,
ifRuleBndrs = map toIfaceBndr bndrs,
ifRuleHead = fn,
ifRuleArgs = map do_arg args,
ifRuleRhs = toIfaceExpr rhs,
ifRuleAuto = auto,
ifRuleOrph = orph }
where
-- For type args we must remove synonyms from the outermost
-- level. Reason: so that when we read it back in we'll
-- construct the same ru_rough field as we have right now;
-- see tcIfaceRule
do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
do_arg (Coercion co) = IfaceCo (toIfaceCoercion co)
do_arg arg = toIfaceExpr arg
-- Compute orphanhood. See Note [Orphans] in InstEnv
-- A rule is an orphan only if none of the variables
-- mentioned on its left-hand side are locally defined
lhs_names = nameSetElems (ruleLhsOrphNames rule)
orph = case filter (nameIsLocalOrFrom mod) lhs_names of
(n : _) -> NotOrphan (nameOccName n)
[] -> IsOrphan
bogusIfaceRule :: Name -> IfaceRule
bogusIfaceRule id_name
= IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
ifRuleRhs = IfaceExt id_name, ifRuleOrph = IsOrphan,
ifRuleAuto = True }
---------------------
toIfaceExpr :: CoreExpr -> IfaceExpr
toIfaceExpr (Var v) = toIfaceVar v
toIfaceExpr (Lit l) = IfaceLit l
toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
toIfaceExpr (Coercion co) = IfaceCo (toIfaceCoercion co)
toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x, toIfaceOneShot x) (toIfaceExpr b)
toIfaceExpr (App f a) = toIfaceApp f [a]
toIfaceExpr (Case s x ty as)
| null as = IfaceECase (toIfaceExpr s) (toIfaceType ty)
| otherwise = IfaceCase (toIfaceExpr s) (getFS x) (map toIfaceAlt as)
toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceCoercion co)
toIfaceExpr (Tick t e)
| Just t' <- toIfaceTickish t = IfaceTick t' (toIfaceExpr e)
| otherwise = toIfaceExpr e
toIfaceOneShot :: Id -> IfaceOneShot
toIfaceOneShot id | isId id
, OneShotLam <- oneShotInfo (idInfo id)
= IfaceOneShot
| otherwise
= IfaceNoOneShot
---------------------
toIfaceTickish :: Tickish Id -> Maybe IfaceTickish
toIfaceTickish (ProfNote cc tick push) = Just (IfaceSCC cc tick push)
toIfaceTickish (HpcTick modl ix) = Just (IfaceHpcTick modl ix)
toIfaceTickish (SourceNote src names) = Just (IfaceSource src names)
toIfaceTickish (Breakpoint {}) = Nothing
-- Ignore breakpoints, since they are relevant only to GHCi, and
-- should not be serialised (Trac #8333)
---------------------
toIfaceBind :: Bind Id -> IfaceBinding
toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
---------------------
toIfaceAlt :: (AltCon, [Var], CoreExpr)
-> (IfaceConAlt, [FastString], IfaceExpr)
toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
---------------------
toIfaceCon :: AltCon -> IfaceConAlt
toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc)
toIfaceCon (LitAlt l) = IfaceLitAlt l
toIfaceCon DEFAULT = IfaceDefault
---------------------
toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
toIfaceApp (App f a) as = toIfaceApp f (a:as)
toIfaceApp (Var v) as
= case isDataConWorkId_maybe v of
-- We convert the *worker* for tuples into IfaceTuples
Just dc | isTupleTyCon tc && saturated
-> IfaceTuple (tupleTyConSort tc) tup_args
where
val_args = dropWhile isTypeArg as
saturated = val_args `lengthIs` idArity v
tup_args = map toIfaceExpr val_args
tc = dataConTyCon dc
_ -> mkIfaceApps (toIfaceVar v) as
toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
---------------------
toIfaceVar :: Id -> IfaceExpr
toIfaceVar v
| Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
-- Foreign calls have special syntax
| isExternalName name = IfaceExt name
| otherwise = IfaceLcl (getFS name)
where name = idName v
| green-haskell/ghc | compiler/iface/MkIface.hs | bsd-3-clause | 87,030 | 3 | 24 | 27,759 | 15,437 | 8,096 | 7,341 | -1 | -1 |
module ResolvePred (myFold) where
{-@ data L [llen] = C (h :: Int) (t :: L) | N @-}
{-@ invariant {v:L | (llen v) >= 0} @-}
data L = C Int L | N
{-@ myFold :: forall <q :: L -> b -> Prop>.
(as:L -> a:Int -> b<q as> -> b<q (C a as)>)
-> b<q N>
-> l:L
-> b<q l>
@-}
myFold f z = go
where
go N = z
go (C a as) = f as a (go as)
{-@ measure llen :: L -> Int
llen (N) = 0
llen (C x xs) = 1 + (llen xs)
@-}
{-@ qualif PappL(v:a, p:Pred a L , a:int, as:L ):
papp2(p, v, C(a, as))
@-}
| ssaavedra/liquidhaskell | tests/pos/ResolvePred.hs | bsd-3-clause | 571 | 0 | 9 | 218 | 77 | 43 | 34 | 5 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main (main) where
import Prelude
import Data.Default
#if __GLASGOW_HASKELL__ == 704
import qualified Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable
#endif
import Data.Vector.Unboxed.Base (Unbox)
import Data.Vector.Unboxed.Deriving
derivingUnbox "Maybe"
[t| ∀ a. (Default a, Unbox a) ⇒ Maybe a → (Bool, a) |]
[| maybe (False, def) (\ x → (True, x)) |]
[| \ (b, x) → if b then Just x else Nothing |]
main ∷ IO ()
main = return ()
| liyang/vector-th-unbox | tests/sanity.hs | bsd-3-clause | 702 | 0 | 6 | 116 | 102 | 69 | 33 | 18 | 1 |
{-# LANGUAGE BangPatterns #-}
foo = case v of !1 -> x
| bitemyapp/apply-refact | tests/examples/Structure20.hs | bsd-3-clause | 54 | 1 | 8 | 12 | 21 | 9 | 12 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : CSH.Eval.Config
Description : Configuration utilities
Copyright : Stephen Demos, Matt Gambogi, Travis Whitaker, Computer Science House 2015
License : MIT
Maintainer : pvals@csh.rit.edu
Stability : Provisional
Portability : POSIX
Provides functionality for reading config values.
-}
module CSH.Eval.Config (
evalConfig
, cxCfgSettings
, poolCfgSettings
, module Data.Configurator
, Command (..)
, ServerCmd (..)
, DBInitCmd (..)
) where
import Data.Configurator
import Data.Configurator.Types
import Data.Word (Word16)
import Hasql
import Hasql.Postgres
import System.Environment
import qualified Data.ByteString.Char8 as C
-- | Toplevel 'csh-eval' command configuration type.
data Command = Members ServerCmd -- ^ Members only site configuration type
| Intro ServerCmd -- ^ Freshman site configuration type
| InitDB DBInitCmd -- ^ DB initialization command configuation type
-- | Configuation type for launching either site
data ServerCmd = ServerCmd { withTLS :: Bool -- ^ Launch with TLS support
, port :: Int -- ^ Which port to launch on
}
-- | Configuration type for running the db initialization script
data DBInitCmd = DBInitCmd
{ dbHost :: C.ByteString -- ^ Database hostname
, dbPort :: Word16 -- ^ Database port
, dbUser :: C.ByteString -- ^ Database username
, dbName :: C.ByteString -- ^ Database name
}
-- | Load a config from the path given by the 'CSH_EVAL_CONFIG' environment
-- variable, or default to 'config/csh-eval.rc'
evalConfig :: IO Config
evalConfig = lookupEnv "CSH_EVAL_CONFIG"
>>= maybe (load [Required "config/csh-eval.rc"])
(\x -> load [Required x])
-- | Derive hasql postgres connection settings from configuration.
cxCfgSettings :: Config -> IO Settings
cxCfgSettings cfg = ParamSettings
<$> (lookupDefault "localhost" cfg "db.host")
<*> (lookupDefault 5432 cfg "db.port")
<*> (lookupDefault "" cfg "db.user")
<*> (lookupDefault "" cfg "db.password")
<*> (lookupDefault "" cfg "db.dbname")
-- | Derive hasql pool settings from configuration.
poolCfgSettings :: Config -> IO PoolSettings
poolCfgSettings cfg = do
max_con <- (lookupDefault 1 cfg "db.pool.max_con")
idle_timeout <- (lookupDefault 10 cfg "db.pool.idle_timeout")
case poolSettings max_con idle_timeout of
Just x -> pure x
Nothing -> fail ("Bad pool settings config:\n db.pool.max_con = "
++ (show max_con)
++ "\n db.pool.idle_timeout: "
++ (show idle_timeout))
| robgssp/csh-eval | src/CSH/Eval/Config.hs | mit | 2,824 | 0 | 16 | 765 | 443 | 251 | 192 | 47 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.GHC.IPI641
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
module Distribution.Simple.GHC.IPI641 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (depends, installedPackageId)
import Distribution.Text (display)
import Distribution.Simple.GHC.IPI642
( PackageIdentifier, convertPackageId
, License, convertLicense, convertModuleName )
-- | This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1.
--
-- It's here purely for the 'Read' instance so that we can read the package
-- database used by those ghc versions. It is a little hacky to read the
-- package db directly, but we do need the info and until ghc-6.9 there was
-- no better method.
--
-- In ghc-6.4.2 the format changed a bit. See "Distribution.Simple.GHC.IPI642"
--
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
mkInstalledPackageId :: Current.PackageIdentifier -> Current.InstalledPackageId
mkInstalledPackageId = Current.InstalledPackageId . display
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing Nothing
in Current.InstalledPackageInfo {
Current.installedPackageId = mkInstalledPackageId (convertPackageId (package ipi)),
Current.sourcePackageId = pid,
Current.packageKey = Current.OldPackageKey pid,
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.instantiatedWith = [],
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = [],
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (mkInstalledPackageId.convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
| DavidAlphaFox/ghc | libraries/Cabal/Cabal/Distribution/Simple/GHC/IPI641.hs | bsd-3-clause | 4,347 | 0 | 13 | 1,160 | 831 | 497 | 334 | 79 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Util.WorkspaceCompare
-- Copyright : (c) Spencer Janssen <spencerjanssen@gmail.com>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Spencer Janssen <spencerjanssen@gmail.com>
-- Stability : unstable
-- Portability : unportable
--
-----------------------------------------------------------------------------
module XMonad.Util.WorkspaceCompare ( WorkspaceCompare, WorkspaceSort
, getWsIndex
, getWsCompare
, getWsCompareByTag
, getXineramaPhysicalWsCompare
, getXineramaWsCompare
, mkWsSort
, getSortByIndex
, getSortByTag
, getSortByXineramaPhysicalRule
, getSortByXineramaRule ) where
import XMonad
import qualified XMonad.StackSet as S
import Data.List
import Data.Monoid
import Data.Ord
import Data.Maybe
import Data.Function
type WorkspaceCompare = WorkspaceId -> WorkspaceId -> Ordering
type WorkspaceSort = [WindowSpace] -> [WindowSpace]
-- | Lookup the index of a workspace id in the user's config, return Nothing
-- if that workspace does not exist in the config.
getWsIndex :: X (WorkspaceId -> Maybe Int)
getWsIndex = do
spaces <- asks (workspaces . config)
return $ flip elemIndex spaces
-- | A comparison function for WorkspaceId, based on the index of the
-- tags in the user's config.
getWsCompare :: X WorkspaceCompare
getWsCompare = do
wsIndex <- getWsIndex
return $ mconcat [compare `on` wsIndex, compare]
-- | A simple comparison function that orders workspaces
-- lexicographically by tag.
getWsCompareByTag :: X WorkspaceCompare
getWsCompareByTag = return compare
-- | A comparison function for Xinerama based on visibility, workspace
-- and screen id. It produces the same ordering as
-- 'XMonad.Hooks.DynamicLog.pprWindowSetXinerama'.
getXineramaWsCompare :: X WorkspaceCompare
getXineramaWsCompare = getXineramaWsCompare' False
-- | A comparison function like 'getXineramaWsCompare', but uses physical locations for screens.
getXineramaPhysicalWsCompare :: X WorkspaceCompare
getXineramaPhysicalWsCompare = getXineramaWsCompare' True
getXineramaWsCompare' :: Bool -> X WorkspaceCompare
getXineramaWsCompare' phy = do
w <- gets windowset
return $ \ a b -> case (isOnScreen a w, isOnScreen b w) of
(True, True) -> cmpPosition phy w a b
(False, False) -> compare a b
(True, False) -> LT
(False, True) -> GT
where
onScreen w = S.current w : S.visible w
isOnScreen a w = a `elem` map (S.tag . S.workspace) (onScreen w)
tagToSid s x = S.screen $ fromJust $ find ((== x) . S.tag . S.workspace) s
cmpPosition False w a b = comparing (tagToSid $ onScreen w) a b
cmpPosition True w a b = comparing (rect.(tagToSid $ onScreen w)) a b
where rect i = let (Rectangle x y _ _) = screens !! fromIntegral i in (y,x)
screens = map (screenRect . S.screenDetail) $ sortBy (comparing S.screen) $ S.current w : S.visible w
-- | Create a workspace sorting function from a workspace comparison
-- function.
mkWsSort :: X WorkspaceCompare -> X WorkspaceSort
mkWsSort cmpX = do
cmp <- cmpX
return $ sortBy (\a b -> cmp (S.tag a) (S.tag b))
-- | Sort several workspaces according to their tags' indices in the
-- user's config.
getSortByIndex :: X WorkspaceSort
getSortByIndex = mkWsSort getWsCompare
-- | Sort workspaces lexicographically by tag.
getSortByTag :: X WorkspaceSort
getSortByTag = mkWsSort getWsCompareByTag
-- | Sort serveral workspaces for xinerama displays, in the same order
-- produced by 'XMonad.Hooks.DynamicLog.pprWindowSetXinerama': first
-- visible workspaces, sorted by screen, then hidden workspaces,
-- sorted by tag.
getSortByXineramaRule :: X WorkspaceSort
getSortByXineramaRule = mkWsSort getXineramaWsCompare
-- | Like 'getSortByXineramaRule', but uses physical locations for screens.
getSortByXineramaPhysicalRule :: X WorkspaceSort
getSortByXineramaPhysicalRule = mkWsSort getXineramaPhysicalWsCompare
| markus1189/xmonad-contrib-710 | XMonad/Util/WorkspaceCompare.hs | bsd-3-clause | 4,362 | 1 | 15 | 1,047 | 817 | 439 | 378 | 61 | 5 |
-- Programatica Front-End, level 2, see README.html
module PFE2(
PFE2MT,runPFE2,clean2,
getSt2ext,updSt2ext,setSt2ext,
getAllExports,getExports,getModuleExports,getModuleExportsTime,getModuleTime
) where
import Prelude hiding (readFile,putStrLn)
import Data.Maybe(isJust,isNothing,fromJust)
import Data.List(nub,intersect,(\\))
import HsModule
import WorkModule(analyzeSCM,expRel,ExpRel,readRel,showRel)
import Relations(Rel)
--import Ents(Ent)
import PFE0
import PrettyPrint(pp,fsep,(<+>))
import MUtils
import StateMT(getSt,updSt_)
import AbstractIO
import FileUtils
import DirUtils(optCreateDirectory,getModificationTimeMaybe,rmR)
type Exports n = [(ModuleName,(ClockTime,ExpRel n))]
type PFE2Info n = Exports n
pfe2info0 = []::PFE2Info n
type PFE2MT n i ds ext m = PFE0MT n i ds (PFE2Info n,ext) m
runPFE2 ext = runPFE0 (pfe2info0,ext)
getSt2 :: Monad m => PFE2MT n i ds ext m (PFE2Info n)
updSt2 :: Monad m => Upd (PFE2Info n)->PFE2MT n i ds ext m ()
getSt2ext :: Monad m => PFE2MT n i ds ext m ext
updSt2ext :: Monad m => Upd ext->PFE2MT n i ds ext m ()
getSt2 = fst # getSt0ext
updSt2 = updSt0ext . apFst
setSt2 = updSt2 . const
getSt2ext = snd # getSt0ext
updSt2ext = updSt0ext . apSnd
setSt2ext = updSt2ext . const
-- The latest time at which the module or one of its imports was modified:
getModuleTime m =
do (path,(_,imports)) <- findNode m
srct <- getModificationTime path
expts <- mapM getModuleExportsTime imports
return (maximum (srct:expts))
getModuleExportsTime m = fst # getModuleExports m
getModuleExports m =
maybe (fail $ pp $ "Unknown module:"<+>m) return . lookup m
=<< getExports (Just [m])
getAllExports = getExports Nothing
getExports optms =
do oldExports <- getSt2
ms <- maybe allModules return optms
b <- batchMode
if b && haveAll oldExports ms
then return oldExports
else do exports <- analyzeModules' oldExports optms
setSt2 exports
return exports
where
haveAll old ms = null (nub ms\\map fst old)
-- Compute the WorkModules for all modules in the project:
--analyzeModules = analyzeModules' pfe2info0 Nothing
-- Compute the WorkModules for a selected set of modules in the project:
analyzeModules' oldExports optms =
do optCreateDirectory `projPath` scopedir
g <- sortCurrentModuleGraph
exports <- scopeScms [] [] (optSubGraph g optms)
let newms = map fst exports
oldexports = [oe|oe@(m,_)<-oldExports,m `notElem` newms]
return (exports++oldexports)
where
scopeScms exports updated [] = return exports
scopeScms exports updated (scm:scms) =
do (exports',updated') <- scopeScm exports updated scm
scopeScms (exports'++exports) (updated'++updated) scms
scopeScm exports updated scm =
do es <- mapM getOldExport scm
let imps = imports scm
updimps = imps `intersect` updated -- updated imports
case mapM id es of
Just exports' | null updimps ->
do let ms = map (fst.snd) scm
return (zip ms exports',[])
_ -> do epput $ "Analyzing:" <+>fsep (map fst scm)
a <- analyzeSCM (mapSnd snd exports) # preparseSCM scm
case a of
Left err -> fail (pp err)
Right wms' ->
do (unchanged,ts) <- unzip # mapM updateWorkModule wms'
let updated' = [m|((m,_),False)<-zip wms' unchanged]
exports' = zipWith f ts wms'
f t (m,wm) = (m,(t,expRel wm))
return (exports',updated')
imports scm = nub [i|(f,(m,is))<-scm,i<-is]
preparseSCM = mapM (preparseSourceFile.fst)
getOldExport (f,(m,_)) =
do let opt_oexp = lookup m oldExports
oexpt = fmap fst opt_oexp
-- Is the export relation in the internal cache present and fresh?
b <- batchMode
srct <- if b then return undefined else getModificationTime f
if if b then isNothing oexpt else srct `newerThan` oexpt
then do optdir <- projectDir
case optdir of
Nothing -> return Nothing -- no external cache
Just dir ->
do let expf = exportsFile dir m
expt <- getModificationTimeMaybe expf
srct <- if b
then getModificationTime f
else return srct
--Ditto for the export relation in the external cache?
if srct `newerThan` expt
then return Nothing
else maybeM (((,) (fromJust expt) . readRel)
# readFileNow expf)
else return opt_oexp
--fromJust' = fromMaybe (error "PFE2.getOldExport")
--getInscope (_,(m,_)) = read # readFile (inscopeFile m)
updateWorkModule (m,wm) =
do optdir <- projectDir
case optdir of
Nothing ->
do --No access to the old exports here, so we have to assume
--they have changed!! (This should be easy to improve.)
t <- getClockTime
return (True,t)
Just dir ->
do --updateFile (inscopeFile dir m) (show (inscpRel wm))
let expf = exportsFile dir m
updated <- updateFile' expf (showRel (expRel wm))
t <- getModificationTime expf
return (updated,t)
--------------------------------------------------------------------------------
clean2 = withProjectDir clean
where
clean dir = do rmR [scopedir dir]
clean0
--------------------------------------------------------------------------------
scopedir dir=dir++"scope/"
exportsFile dir m = scopedir dir++moduleInfoPath m++".exports"
--inscopeFile dir (Module s) = scopedir dir++s++".inscope"
--------------------------------------------------------------------------------
| kmate/HaRe | old/tools/pfe/PFE2.hs | bsd-3-clause | 5,580 | 73 | 20 | 1,303 | 1,347 | 779 | 568 | 121 | 11 |
{-# LANGUAGE OverloadedStrings #-}
module CreateIssue where
import qualified Github.Issues as Github
main = do
let auth = Github.GithubBasicAuth "user" "password"
newiss = (Github.newIssue "A new issue") {
Github.newIssueBody = Just "Issue description text goes here"
}
possibleIssue <- Github.createIssue auth "thoughtbot" "paperclip" newiss
putStrLn $ either (\e -> "Error: " ++ show e)
formatIssue
possibleIssue
formatIssue issue =
(Github.githubOwnerLogin $ Github.issueUser issue) ++
" opened this issue " ++
(show $ Github.fromGithubDate $ Github.issueCreatedAt issue) ++ "\n" ++
(Github.issueState issue) ++ " with " ++
(show $ Github.issueComments issue) ++ " comments" ++ "\n\n" ++
(Github.issueTitle issue)
| mavenraven/github | samples/Issues/CreateIssue.hs | bsd-3-clause | 810 | 0 | 17 | 191 | 211 | 108 | 103 | 18 | 1 |
module TiRhs where
--import HasBaseStruct
import BaseSyntaxStruct
import TI
--import TiPrelude(tBool)
import MUtils
--import PrettyPrint -- debug
instance (--Printable i, -- debug
TypeCon i,Fresh i,TypeCheck i e (Typed i e'),HasTypeAnnot i e')
=> TypeCheck i (HsRhs e) (Typed i (HsRhs e')) where
tc = tcRhs
tcRhs rhs =
case rhs of
HsBody e -> emap HsBody # tc e
HsGuard gds -> emap HsGuard # tcGds gds
tcGds gds =
do gds':>:ts' <- unzipTyped # mapM tcGd gds
t <- allSame ts'
gds'>:t
tcGd (s,e1,e2) =
posContext s $
do e1':>:t1' <- tc e1
tBool <- getBoolType
t1'=:=tBool
e2':>:t2' <- tc e2
(s,e1',typeAnnot e2' t2')>:t2'
| forste/haReFork | tools/base/TI/TiRhs.hs | bsd-3-clause | 688 | 0 | 10 | 173 | 277 | 137 | 140 | -1 | -1 |
{-# LANGUAGE KindSignatures, TypeFamilies, GADTs, DataKinds #-}
module T12444a where
type family F a :: *
type instance F (Maybe x) = Maybe (F x)
foo :: a -> Maybe (F a)
foo = undefined
-- bad :: (F (Maybe t) ~ t) => Maybe t -> [Maybe t]
bad x = [x, foo x]
| olsner/ghc | testsuite/tests/indexed-types/should_compile/T12444a.hs | bsd-3-clause | 261 | 0 | 8 | 59 | 80 | 45 | 35 | 7 | 1 |
module Prim where
map2 f [] = []
map2 f (x:xs) = f x : map2 f xs
zipWith2 f [] [] = []
zipWith2 f (a:x) (b:y) = (f a b):zipWith2 f x y
| ezyang/ghc | testsuite/tests/arityanal/prim.hs | bsd-3-clause | 137 | 0 | 7 | 37 | 110 | 56 | 54 | 5 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
module Examples.WithTVar where
import Control.Concurrent.STM
import Control.Applicative
import Data.Time
import System.IO
import Database.EventSafe
import Examples.Shared
-- Naive simple program prompting the user allowing him/her
-- to add new events and get resources
-- (horrible piece of code but it's just an example)
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
events <- emptyPoolM
handleQuery events
handleQuery :: ESTVar [] Event -> IO ()
handleQuery events = do
putStr "(1) New event\n(2) Get resource\nYour choice: "
choice <- getLine
case choice of
"1" -> newEvent events
"2" -> getRes events
_ -> putStrLn "Unrecognized sequence."
handleQuery events
newEvent :: ESTVar [] Event -> IO ()
newEvent events = do
putStr "(1) New user\n(2) Change password\n(3) New post\nYour choice: "
choice <- getLine
case choice of
"1" -> do
putStr "Email: "
email <- getLine
putStr "Password: "
pwd <- getLine
time <- show <$> getCurrentTime
addEventM events $ UserCreation time (Email email) pwd
putStrLn "User created."
"2" -> do
putStr "Email: "
email <- getLine
putStr "Password: "
pwd <- getLine
time <- show <$> getCurrentTime
addEventM events $ UserChangePassword time (Email email) pwd
putStrLn "Password changed."
"3" -> do
putStr "Id (number please): "
postIdStr <- getLine
putStr "Author e-mail: "
email <- getLine
putStr "Title: "
title <- getLine
time <- show <$> getCurrentTime
addEventM events $ PostCreation time (PostId . read $ postIdStr) (Email email) title
putStrLn "Post created."
_ -> putStrLn "Unrecognized sequence."
getRes :: ESTVar [] Event -> IO ()
getRes events = do
putStr "(1) Get a user\n(2) Get a post\nYour choice: "
choice <- getLine
case choice of
"1" -> do
putStr "Email: "
email <- getLine
mres <- getResourceM events (Email email) :: IO (Maybe User)
print mres
"2" -> do
putStr "Post Id (number please): "
postIdStr <- getLine
mres <- getResourceM events (PostId . read $ postIdStr) :: IO (Maybe Post)
print mres
_ -> putStrLn "Unrecognized sequence."
| thoferon/eventsafe | Examples/WithTVar.hs | mit | 2,332 | 0 | 16 | 589 | 633 | 285 | 348 | 71 | 4 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.HTMLFormControlsCollection
(get, get_, getUnsafe, getUnchecked, namedItem, namedItem_,
namedItemUnsafe, namedItemUnchecked,
HTMLFormControlsCollection(..), gTypeHTMLFormControlsCollection)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.get Mozilla HTMLFormControlsCollection.get documentation>
get ::
(MonadDOM m) =>
HTMLFormControlsCollection -> Word -> m (Maybe HTMLElement)
get self index
= liftDOM ((self ^. jsf "get" [toJSVal index]) >>= fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.get Mozilla HTMLFormControlsCollection.get documentation>
get_ :: (MonadDOM m) => HTMLFormControlsCollection -> Word -> m ()
get_ self index
= liftDOM (void (self ^. jsf "get" [toJSVal index]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.get Mozilla HTMLFormControlsCollection.get documentation>
getUnsafe ::
(MonadDOM m, HasCallStack) =>
HTMLFormControlsCollection -> Word -> m HTMLElement
getUnsafe self index
= liftDOM
(((self ^. jsf "get" [toJSVal index]) >>= fromJSVal) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.get Mozilla HTMLFormControlsCollection.get documentation>
getUnchecked ::
(MonadDOM m) => HTMLFormControlsCollection -> Word -> m HTMLElement
getUnchecked self index
= liftDOM
((self ^. jsf "get" [toJSVal index]) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.namedItem Mozilla HTMLFormControlsCollection.namedItem documentation>
namedItem ::
(MonadDOM m, ToJSString name) =>
HTMLFormControlsCollection ->
name -> m (Maybe RadioNodeListOrElement)
namedItem self name = liftDOM ((self ! name) >>= fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.namedItem Mozilla HTMLFormControlsCollection.namedItem documentation>
namedItem_ ::
(MonadDOM m, ToJSString name) =>
HTMLFormControlsCollection -> name -> m ()
namedItem_ self name = liftDOM (void (self ! name))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.namedItem Mozilla HTMLFormControlsCollection.namedItem documentation>
namedItemUnsafe ::
(MonadDOM m, ToJSString name, HasCallStack) =>
HTMLFormControlsCollection -> name -> m RadioNodeListOrElement
namedItemUnsafe self name
= liftDOM
(((self ! name) >>= fromJSVal) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection.namedItem Mozilla HTMLFormControlsCollection.namedItem documentation>
namedItemUnchecked ::
(MonadDOM m, ToJSString name) =>
HTMLFormControlsCollection -> name -> m RadioNodeListOrElement
namedItemUnchecked self name
= liftDOM ((self ! name) >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/HTMLFormControlsCollection.hs | mit | 4,046 | 0 | 14 | 634 | 870 | 498 | 372 | -1 | -1 |
module Classifier
(
) where
| Yukits/classyou | src/Classifier.hs | mit | 36 | 0 | 3 | 13 | 7 | 5 | 2 | 2 | 0 |
module Main where
foo a | even (fst a) = False
| True = True
boo = any foo [(2,2), (6,3), (7,4)]
main = print $ boo
| NickolayStorm/usatu-learning | Functional programming/lab3/1st.hs | mit | 120 | 0 | 10 | 31 | 82 | 45 | 37 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Simple model for slides
module Slides where
import Control.Lens hiding (children)
import Data.Foldable (foldl')
import Data.Maybe (listToMaybe)
import qualified Data.Text as T
import VirtualHom.Element
import VirtualHom.View(View, renderUI, specialise)
import VirtualHom.Html (h1, h2, h3, h4, p, div)
import VirtualHom.Rendering(renderingOptions, onElementChanged)
import Prelude hiding (div)
import SemanticUI
import MathJax
-- | State = View that can be navigated to
-- | Slide = pointer to a specific view
data Slide = Slide {
_section :: T.Text,
_subsection :: T.Text,
_contents :: View Identity () }
makeLenses ''Slide
-- | Create a slide
slide :: T.Text -> T.Text -> View Identity () -> Slide
slide = Slide
data SlideShowData = SlideShowData {
_title :: T.Text,
_author :: T.Text,
_date :: T.Text,
_subtitle :: T.Text
}
makeLenses ''SlideShowData
slideShowData :: SlideShowData
slideShowData = SlideShowData "" "" "" ""
data SlideShow = SlideShow {
_metadata :: SlideShowData,
_current :: Slide,
_previous :: Maybe SlideShow,
_next :: Maybe SlideShow
}
makeLenses ''SlideShow
slideDeck :: SlideShowData -> [Slide] -> SlideShow
slideDeck dt slides = slideDeck' dt [] slides firstSlide where
firstSlide = slide "" "" (const [div & children .~ [h1 $ dt^.title, h2 $ dt^.subtitle, h4 $ dt^.author, h4 $ dt^.date]])
slideDeck' :: SlideShowData -> [Slide] -> [Slide] -> Slide -> SlideShow
slideDeck' dt left right cur = SlideShow dt cur pr nxt where
pr = fmap (sd (tail left) (cur:right)) $ listToMaybe left
nxt = fmap (sd (cur:left) (tail right)) $ listToMaybe right
sd = slideDeck' dt
-- | Render a slide show in a given div
renderSlideShow :: T.Text -> SlideShow -> IO ()
renderSlideShow target shw = do
let options = onElementChanged updateMathJax $ renderingOptions target
let interp = return . runIdentity
renderUI options showSlide interp shw
showSlide :: View Identity SlideShow
showSlide ss = [container &
children .~ [
menu & children .~ [
container & children .~ [
headerItem & content .~ ss^.metadata.title
],
rightMenu & children .~ buttons
],
div & attributes . at "class" ?~ "main-div" & children .~ [
div & children .~[
h2 $ ss^.current.section,
h3 $ ss^.current.subsection,
div & children .~ (specialise united (ss^.current.contents) ss)
]]
]
] where
buttons = (maybe leftDisabled leftBtn $ ss^.previous) ++ (maybe rightDisabled rightBtn $ ss^.next)
moveLeft s = return $ maybe s id (s^.previous)
moveRight s = return $ maybe s id (s^.next)
leftDisabled = [item & children .~ [disabledButton & content .~ "<"]]
leftBtn sls = [item & children .~ [button &
content .~ "<" &
callbacks . click ?~ (const moveLeft)]]
rightDisabled = [item & children .~ [disabledButton & content .~ ">"]]
rightBtn sls = [item & children .~ [button &
content .~ ">" &
callbacks . click ?~ (const moveRight)]]
onKeyDown args = moveRight
| j-mueller/talks | 2016-05-laf/src/Slides.hs | mit | 3,143 | 0 | 17 | 698 | 1,061 | 571 | 490 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Text.IO as Text
main = Text.putStrLn "Hello"
| yamadapc/stack-run-auto | test-files/Test2.hs | mit | 93 | 0 | 6 | 13 | 20 | 12 | 8 | 3 | 1 |
module Main (main) where
import MuchAdo
import NoAdo
import Criterion.Main
import Control.DeepSeq
import GHC.TypeLits
import Numeric.Sized.WordOfSize
instance KnownNat n => NFData (WordOfSize n)
main :: IO ()
main =
defaultMain
[ env (pure ([1 .. 6], 8)) $
\ ~(xs,n) ->
bgroup
"probabilistic inference map"
[ bench "Applicative rewriting, Final encoding" $ whnf (diceAdoFinal n) xs
, bench "Applicative rewriting, Initial encoding" $ whnf (diceAdoInitial n) xs
, bench "Applicative rewriting, Constrained encoding" $ whnf (diceAdoConstrained n) xs
, bench "Applicative rewriting, Codensity encoding" $ whnf (diceAdoCodensity n) xs
, bench "No rewriting" $ whnf (diceNoAdo n) xs]
, env (pure [1 .. 5]) $
\xs ->
bgroup
"set"
[ bench "Applicative rewriting, Final encoding" $ whnf sumThriceAdoFinal xs
, bench "Applicative rewriting, Initial encoding" $ whnf sumThriceAdoInitial xs
, bench "Applicative rewriting, Constrained encoding" $ whnf sumThriceAdoConstrained xs
, bench "Applicative rewriting, Codensity encoding" $ whnf sumThriceAdoCodensity xs
, bench "No rewriting" $ whnf sumThriceNoAdo xs]
, env (pure ([1 .. 5], 30)) $
\ ~(xs,n) ->
bgroup
"probabilistic inference vect"
[ bench "Applicative rewriting, Initial encoding" $ whnf (diceVectAdoInitial n) xs
, bench "Applicative rewriting Codensity encoding" $ whnf (diceVectAdoCodensity n) xs
, bench "No rewriting" $ whnf (diceVectNoAdo n) xs]]
| oisdk/constrained-monads | bench/bench.hs | mit | 1,983 | 0 | 14 | 783 | 439 | 223 | 216 | 36 | 1 |
{-#LANGUAGE EmptyDataDecls, CPP #-}
module Melchior.Data.String (
JSString
, jsStringToString
, stringToJSString
) where
#ifdef __UHC_TARGET_JS__
import Language.UHC.JScript.ECMA.String (JSString, stringToJSString, jsStringToString)
instance Show JSString where
show h = jsStringToString h
#else
data JSString
stringToJSString = undefined
jsStringToString = undefined
instance Show JSString where
show = undefined
#endif
| kjgorman/melchior | Melchior/Data/String.hs | mit | 440 | 0 | 6 | 66 | 60 | 38 | 22 | -1 | -1 |
import Data.List --sort und reverse
hIndex :: (Num a, Ord a) => [a] -> a
hIndex l = helper (reverse (sort l)) 0
where helper [] acc = acc
helper (z:ls) acc
| z > acc = helper ls (acc + 1)
| otherwise = acc
-- Alternativ
hindex1 = length . takeWhile id .
zipWith (<=) [1..] . reverse . sort
hindex2 = length . takeWhile (\(i, n) -> n >= i) .
zip [1..] . reverse . sort | MartinThoma/LaTeX-examples | documents/Programmierparadigmen/scripts/haskell/hirsch-index.hs | mit | 431 | 0 | 12 | 143 | 204 | 106 | 98 | 11 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | The @Client@ monad type.
module Haste.App.Client.Type
( MonadError (..), MonadConc (..), MonadEvent (..), MonadIO (..)
, Client, ClientError (..)
, runClient
) where
import Haste.Concurrent (MonadConc (..), CIO, concurrent)
import Control.Monad.IO.Class (MonadIO)
import Haste.Events (MonadEvent (..))
import Control.Exception
import Control.Monad.Error
import Data.Typeable
data ClientError = ClientError String
deriving (Typeable, Show)
instance Error ClientError where
strMsg = ClientError
instance (Error e, MonadConc m) => MonadConc (ErrorT e m) where
liftCIO = lift . liftCIO
fork m = lift $ fork $ do
Right x <- runErrorT m
return x
instance MonadEvent Client where
mkHandler f = return $ \x -> concurrent $ do
void $ runClient $ f x
runClient :: Client a -> CIO a
runClient (Client m) = do
res <- runErrorT m
case res of
Right x -> pure x
Left (ClientError e) -> error e
-- | A client program running in the browser.
newtype Client a = Client {unClient :: ErrorT ClientError CIO a}
deriving (Functor, Applicative, Monad, MonadIO, MonadConc, MonadError ClientError)
| valderman/haste-app | src/Haste/App/Client/Type.hs | mit | 1,187 | 0 | 12 | 237 | 393 | 216 | 177 | 31 | 2 |
module Network.BitFunctor2.Platform.Blockchain.Forging where
| BitFunctor/bitfunctor | src/Network/BitFunctor2/Platform/Blockchain/Forging.hs | mit | 62 | 0 | 3 | 4 | 9 | 7 | 2 | 1 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-|
Module : PostgREST.Auth
Description : PostgREST authorization functions.
This module provides functions to deal with the JWT authorization (http://jwt.io).
It also can be used to define other authorization functions,
in the future Oauth, LDAP and similar integrations can be coded here.
Authentication should always be implemented in an external service.
In the test suite there is an example of simple login function that can be used for a
very simple authentication system inside the PostgreSQL database.
-}
module PostgREST.Auth (
containsRole
, jwtClaims
, JWTAttempt(..)
, parseSecret
) where
import qualified Crypto.JOSE.Types as JOSE.Types
import qualified Data.Aeson as JSON
import qualified Data.HashMap.Strict as M
import Data.Vector as V
import Control.Lens (set)
import Data.Time.Clock (UTCTime)
import Control.Lens.Operators
import Crypto.JWT
import PostgREST.Types
import Protolude
{-|
Possible situations encountered with client JWTs
-}
data JWTAttempt = JWTInvalid JWTError
| JWTMissingSecret
| JWTClaims (M.HashMap Text JSON.Value)
deriving (Eq, Show)
{-|
Receives the JWT secret and audience (from config) and a JWT and returns a map
of JWT claims.
-}
jwtClaims :: Maybe JWKSet -> Maybe StringOrURI -> LByteString -> UTCTime -> Maybe JSPath -> IO JWTAttempt
jwtClaims _ _ "" _ _ = return $ JWTClaims M.empty
jwtClaims secret audience payload time jspath =
case secret of
Nothing -> return JWTMissingSecret
Just s -> do
let validation = set allowedSkew 1 $ defaultJWTValidationSettings (maybe (const True) (==) audience)
eJwt <- runExceptT $ do
jwt <- decodeCompact payload
verifyClaimsAt validation s time jwt
return $ case eJwt of
Left e -> JWTInvalid e
Right jwt -> JWTClaims $ claims2map jwt jspath
{-|
Turn JWT ClaimSet into something easier to work with,
also here the jspath is applied to put the "role" in the map
-}
claims2map :: ClaimsSet -> Maybe JSPath -> M.HashMap Text JSON.Value
claims2map claims jspath = (\case
val@(JSON.Object o) ->
let role = maybe M.empty (M.singleton "role") $
walkJSPath (Just val) =<< jspath in
M.delete "role" o `M.union` role -- mutating the map
_ -> M.empty
) $ JSON.toJSON claims
walkJSPath :: Maybe JSON.Value -> JSPath -> Maybe JSON.Value
walkJSPath x [] = x
walkJSPath (Just (JSON.Object o)) (JSPKey key:rest) = walkJSPath (M.lookup key o) rest
walkJSPath (Just (JSON.Array ar)) (JSPIdx idx:rest) = walkJSPath (ar V.!? idx) rest
walkJSPath _ _ = Nothing
{-|
Whether a response from jwtClaims contains a role claim
-}
containsRole :: JWTAttempt -> Bool
containsRole (JWTClaims claims) = M.member "role" claims
containsRole _ = False
{-|
Parse `jwt-secret` configuration option and turn into a JWKSet.
There are three ways to specify `jwt-secret`: text secret, JSON Web Key
(JWK), or JSON Web Key Set (JWKS). The first two are converted into a JWKSet
with one key and the last is converted as is.
-}
parseSecret :: ByteString -> JWKSet
parseSecret str =
fromMaybe (maybe secret (\jwk' -> JWKSet [jwk']) maybeJWK)
maybeJWKSet
where
maybeJWKSet = JSON.decode (toS str) :: Maybe JWKSet
maybeJWK = JSON.decode (toS str) :: Maybe JWK
secret = JWKSet [jwkFromSecret str]
{-|
Internal helper to generate a symmetric HMAC-SHA256 JWK from a text secret.
-}
jwkFromSecret :: ByteString -> JWK
jwkFromSecret key =
fromKeyMaterial km
& jwkUse ?~ Sig
& jwkAlg ?~ JWSAlg HS256
where
km = OctKeyMaterial (OctKeyParameters (JOSE.Types.Base64Octets key))
| diogob/postgrest | src/PostgREST/Auth.hs | mit | 3,823 | 0 | 19 | 891 | 844 | 437 | 407 | 63 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module HXSDL (mainLoop) where
import Graphics.UI.SDL
import Control.Concurrent
mainLoop :: Renderer -> IO ()
mainLoop renderer = do
putStrLn "mainloop"
renderClear renderer
putStrLn "clear renderer"
setRenderDrawColor renderer maxBound maxBound maxBound maxBound
putStrLn "set color"
renderPresent renderer
threadDelay (10^6 * 2)
return ()
| EDeijl/HXSDL | src/HXSDL.hs | mit | 447 | 0 | 10 | 118 | 112 | 52 | 60 | 14 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Types.GraphAnnotationSpec where
import Control.Monad (forM_)
import Data.Aeson (decode, encode, Value(..))
import Data.Aeson.QQ
import qualified Data.HashMap.Lazy as HM
import Test.Hspec
import Web.Mackerel.Types.GraphAnnotation
spec :: Spec
spec = do
let graphAnnotation = GraphAnnotation {
graphAnnotationId = Just $ GraphAnnotationId "abcde",
graphAnnotationTitle = "Deploy application #123",
graphAnnotationDescription = "Deploy link: https://example.com/123",
graphAnnotationFrom = 1485000000,
graphAnnotationTo = 1485000060,
graphAnnotationService = "ExampleService",
graphAnnotationRoles = Just [ "ExampleRole1", "ExampleRole2" ]
}
let json = [aesonQQ|
{
"id": "abcde",
"title": "Deploy application #123",
"description": "Deploy link: https://example.com/123",
"from": 1485000000,
"to": 1485000060,
"service": "ExampleService",
"roles": [ "ExampleRole1", "ExampleRole2" ]
}
|]
describe "GraphAnnotation FromJSON" $ do
it "should parse a json" $
decode (encode json) `shouldBe` Just graphAnnotation
it "should reject an invalid json" $ do
decode "{}" `shouldBe` (Nothing :: Maybe GraphAnnotation)
let (Object hm) = json
forM_ ["title", "description", "from", "to", "service"] $ \key ->
decode (encode (Object (HM.delete key hm))) `shouldBe` (Nothing :: Maybe GraphAnnotation)
describe "GraphAnnotation ToJSON" $
it "should encode into a json" $
decode (encode graphAnnotation) `shouldBe` Just json
| itchyny/mackerel-client-hs | test/Types/GraphAnnotationSpec.hs | mit | 1,639 | 0 | 23 | 353 | 346 | 191 | 155 | 30 | 1 |
--
--
--
------------------
-- Exercise 12.37.
------------------
--
--
--
module E'12'37 where
| pascal-knodel/haskell-craft | _/links/E'12'37.hs | mit | 106 | 0 | 2 | 24 | 13 | 12 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html
module Stratosphere.Resources.EMRStep where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EMRStepHadoopJarStepConfig
-- | Full data type definition for EMRStep. See 'emrStep' for a more
-- convenient constructor.
data EMRStep =
EMRStep
{ _eMRStepActionOnFailure :: Val Text
, _eMRStepHadoopJarStep :: EMRStepHadoopJarStepConfig
, _eMRStepJobFlowId :: Val Text
, _eMRStepName :: Val Text
} deriving (Show, Eq)
instance ToResourceProperties EMRStep where
toResourceProperties EMRStep{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::EMR::Step"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("ActionOnFailure",) . toJSON) _eMRStepActionOnFailure
, (Just . ("HadoopJarStep",) . toJSON) _eMRStepHadoopJarStep
, (Just . ("JobFlowId",) . toJSON) _eMRStepJobFlowId
, (Just . ("Name",) . toJSON) _eMRStepName
]
}
-- | Constructor for 'EMRStep' containing required fields as arguments.
emrStep
:: Val Text -- ^ 'emrsActionOnFailure'
-> EMRStepHadoopJarStepConfig -- ^ 'emrsHadoopJarStep'
-> Val Text -- ^ 'emrsJobFlowId'
-> Val Text -- ^ 'emrsName'
-> EMRStep
emrStep actionOnFailurearg hadoopJarSteparg jobFlowIdarg namearg =
EMRStep
{ _eMRStepActionOnFailure = actionOnFailurearg
, _eMRStepHadoopJarStep = hadoopJarSteparg
, _eMRStepJobFlowId = jobFlowIdarg
, _eMRStepName = namearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-actiononfailure
emrsActionOnFailure :: Lens' EMRStep (Val Text)
emrsActionOnFailure = lens _eMRStepActionOnFailure (\s a -> s { _eMRStepActionOnFailure = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-hadoopjarstep
emrsHadoopJarStep :: Lens' EMRStep EMRStepHadoopJarStepConfig
emrsHadoopJarStep = lens _eMRStepHadoopJarStep (\s a -> s { _eMRStepHadoopJarStep = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-jobflowid
emrsJobFlowId :: Lens' EMRStep (Val Text)
emrsJobFlowId = lens _eMRStepJobFlowId (\s a -> s { _eMRStepJobFlowId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-name
emrsName :: Lens' EMRStep (Val Text)
emrsName = lens _eMRStepName (\s a -> s { _eMRStepName = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/EMRStep.hs | mit | 2,708 | 0 | 15 | 374 | 454 | 260 | 194 | 44 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module Doppler.Html.SyntaxSpec where
import Test.Hspec
import Doppler.Html.Types
import qualified Doppler.Css.Types as Css
import Doppler.Html.Syntax
import Language.Haskell.TH.Syntax (lift)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Tags" $ do
it "parses short closed root element" $
parseHtmlFromString "<html/>" `shouldBe`
Html (ShortTag "html" [])
it "parses short closed spaced root element" $
parseHtmlFromString " <html/> " `shouldBe`
Html (ShortTag "html" [])
it "parses spaced short closed root element" $
parseHtmlFromString "<html />" `shouldBe`
Html (ShortTag "html" [])
it "parses dangling root element" $
parseHtmlFromString "<html>" `shouldBe`
Html (DanglingTag "html" [])
it "parses empty root element" $
parseHtmlFromString "<html></html>" `shouldBe`
Html (FullTag "html" [] [])
it "parses element with one short closed children" $
parseHtmlFromString "<html><br /></html>" `shouldBe`
Html (FullTag "html" [] [ShortTag "br" []])
it "parses element with dangling children" $
parseHtmlFromString "<html><br></html>" `shouldBe`
Html (FullTag "html" [] [DanglingTag "br" []])
it "parses element with full children" $
parseHtmlFromString "<html><b></b></html>" `shouldBe`
Html (FullTag "html" [] [FullTag "b" [] []])
it "parses element with mixed children" $
parseHtmlFromString "<html><br><p><br></p><br></html>" `shouldBe`
Html (FullTag "html" [] [DanglingTag "br" [], FullTag "p" [] [DanglingTag "br" []], DanglingTag "br" []])
describe "Attributes" $ do
it "parses unquoted attribute for short closed root element" $
parseHtmlFromString "<html key=value />" `shouldBe`
Html (ShortTag "html" [("key", AttributeValues [Value "value"])])
it "parses unquoted attribute for dangling root element" $
parseHtmlFromString "<html key=value/>" `shouldBe`
Html (DanglingTag "html" [("key", AttributeValues [Value "value/"])])
it "parses single quoted attribute for short closed root element" $
parseHtmlFromString "<html key='value\"s' />" `shouldBe`
Html (ShortTag "html" [("key", AttributeValues [Value "value\"s"])])
it "parses double quoted attribute for spaced short closed root element" $
parseHtmlFromString "<html key=\"value's\" />" `shouldBe`
Html (ShortTag "html" [("key", AttributeValues [Value "value's"])])
it "parses empty attribute for spaced short closed root element" $
parseHtmlFromString "<html key />" `shouldBe`
Html (ShortTag "html" [("key", mempty)])
it "parses multiple unquoted attribute for short closed root element" $
parseHtmlFromString "<html key1=value1 key2=value2 />" `shouldBe`
Html (ShortTag "html" [("key1", AttributeValues [Value "value1"]), ("key2", AttributeValues [Value "value2"])])
it "parses unquoted attribute for root element" $
parseHtmlFromString "<html key=value></html>" `shouldBe`
Html (FullTag "html" [("key", AttributeValues [Value "value"])] [])
it "parses single quoted attribute for root element" $
parseHtmlFromString "<html key='value'></html>" `shouldBe`
Html (FullTag "html" [("key", AttributeValues [Value "value"])] [])
it "parses double quoted attribute for root element" $
parseHtmlFromString "<html key=\"value\"></html>" `shouldBe`
Html (FullTag "html" [("key", AttributeValues [Value "value"])] [])
it "parses single quoted empty attribute for root element" $
parseHtmlFromString "<html key=''></html>" `shouldBe`
Html (FullTag "html" [("key", mempty)] [])
it "parses double quoted empty attribute for root element" $
parseHtmlFromString "<html key=\"\"></html>" `shouldBe`
Html (FullTag "html" [("key", mempty)] [])
it "parses unquoted attribute interpolation for short closed root element" $
parseHtmlFromString "<html key=${foo} />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift ""))])
it "parses unquoted attribute interpolation and values (post) for short closed root element" $
parseHtmlFromString "<html key=${foo}bar />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift ""))])
it "parses unquoted attribute interpolation and values (pre) for short closed root element" $
parseHtmlFromString "<html key=bar${foo} />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift ""))])
it "parses unquoted attribute interpolation and does not mix it with values for short closed root element" $
parseHtmlFromString "<html key=${foo} bar />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift "")), ("bar", mempty)])
it "parses single quoted interpolation attribute for short closed root element" $
parseHtmlFromString "<html key='hello ${name}' />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift ""))])
it "parses double quoted interpolation attribute for spaced short closed root element" $
parseHtmlFromString "<html key=\"hello ${name}\" />" `shouldBe`
Html (ShortTag "html" [("key", InterpolationAttribute (lift ""))])
describe "CSS integration" $ do
it "parses CSS in style double quoted attribute for root element" $
parseHtmlFromString "<html style=\"text-align: center;\" />" `shouldBe`
Html (ShortTag "html" [("style", AttributeValues [StyleValue $ Css.CssProperty ("text-align", [Css.Value "center"])])])
it "parses CSS in style single quoted attribute for root element" $
parseHtmlFromString "<html style='text-align: center;' />" `shouldBe`
Html (ShortTag "html" [("style", AttributeValues [StyleValue $ Css.CssProperty ("text-align", [Css.Value "center"])])])
it "parses CSS style tag" $
parseHtmlFromString "<style>div { text-align: center; }</style>" `shouldBe`
Html (FullTag "style" [] [Content $ Style [Css.Block ["div"] [Css.CssProperty ("text-align", [Css.Value "center"])]]])
describe "Content" $ do
it "parses root element with text content" $
parseHtmlFromString "<html>text content</html>" `shouldBe`
Html (FullTag "html" [] [Content $ Plain "text", Content BreakingSpace, Content $ Plain "content"])
it "parses root element with spaced text content" $
parseHtmlFromString "<html> text content </html>" `shouldBe`
Html (FullTag "html" [] [Content BreakingSpace, Content $ Plain "text", Content BreakingSpace, Content $ Plain "content", Content BreakingSpace])
it "parses root element with multi-spaced text content to be equal with one spaced" $
parseHtmlFromString "<html> text content </html>" `shouldBe`
Html (FullTag "html" [] [Content BreakingSpace, Content $ Plain "text", Content BreakingSpace, Content $ Plain "content", Content BreakingSpace])
it "parses root element with text and element content" $
parseHtmlFromString "<html>text <b>content</b></html>" `shouldBe`
Html (FullTag "html" [] [Content $ Plain "text", Content BreakingSpace, FullTag "b" [] [Content $ Plain "content"]])
it "parses root element with text and element content with spaces" $
parseHtmlFromString "<html> text <b> content </b> </html>" `shouldBe`
Html (FullTag "html" [] [Content BreakingSpace, Content $ Plain "text", Content BreakingSpace, FullTag "b" [] [Content BreakingSpace, Content $ Plain "content", Content BreakingSpace], Content BreakingSpace])
it "parses root element with text and dangling element content" $
parseHtmlFromString "<html>text <br>more</html>" `shouldBe`
Html (FullTag "html" [] [Content $ Plain "text", Content BreakingSpace, DanglingTag "br" [], Content $ Plain "more"])
it "parses interpolation inside root element" $
parseHtmlFromString "<html>${interpolation}</html>" `shouldBe`
Html (FullTag "html" [] [Content $ Interpolation (lift "")])
it "parses interpolation within text inside root element" $
parseHtmlFromString "<html>Hello, ${interpolation}!</html>" `shouldBe`
Html (FullTag "html" [] [Content $ Plain "Hello,", Content BreakingSpace, Content $ Interpolation (lift ""), Content $ Plain "!"])
it "parses interpolation within text with space at the end inside root element" $
parseHtmlFromString "<html>Hello, ${interpolation} mate!</html>" `shouldBe`
Html (FullTag "html" [] [Content $ Plain "Hello,", Content BreakingSpace, Content $ Interpolation (lift ""), Content BreakingSpace, Content $ Plain "mate!"])
describe "Quasiquotes" $ do
it "applies string interpolation inside root element" $
let foo = "bar" in ([html|<html>${foo}</html>|] :: Html) `shouldBe`
Html (FullTag "html" [] [Content $ Plain "bar"])
it "applies string interpolation inside root element and quotes html" $
let foo = "eskimo < ben & jerry's" in ([html|<html>${foo}</html>|] :: Html) `shouldBe`
Html (FullTag "html" [] [Content $ Plain "eskimo < ben & jerry's"])
it "applies string interpolation within text inside root element" $
let name = "Maija" in ([html|<html>Hello ${name}!</html>|] :: Html) `shouldBe`
Html (FullTag "html" [] [Content $ Plain "Hello", Content BreakingSpace, Content $ Plain "Maija", Content $ Plain "!"])
it "applies string interpolation within text inside root element" $
let name = "Maija" in ([html|<html>Hello ${name}!</html>|] :: Html) `shouldBe`
Html (FullTag "html" [] [Content $ Plain "Hello", Content BreakingSpace, Content $ Plain "Maija", Content $ Plain "!"])
it "applies integer interpolation inside root element" $
let foo = 42 :: Int in ([html|<html>${foo}</html>|] :: Html) `shouldBe`
Html (FullTag "html" [] [Content $ Plain "42"])
it "applies string interpolation for root element attribute" $
let bar = "bar" in ([html|<html attr=foo${bar} />|] :: Html) `shouldBe`
Html (ShortTag "html" [("attr", AttributeValues [Value "foobar"])])
it "applies string interpolation for root element attribute and quotes single quotes" $
let bar = "bar's" in ([html|<html attr='${bar}' />|] :: Html) `shouldBe`
Html (ShortTag "html" [("attr", AttributeValues [Value "bar's"])])
it "applies string interpolation for root element attribute and quotes double quotes" $
let bar = "he said \"get over it\"" in ([html|<html attr="${bar}" />|] :: Html) `shouldBe`
Html (ShortTag "html" [("attr", AttributeValues [Value "he said "get over it""])])
it "applies style interpolation for root element unquoted style attribute" $
let bar = StyleValue (Css.CssProperty ("font-size", [Css.Value "12px"])) in ([html|<html style=${bar} />|] :: Html) `shouldBe`
Html (ShortTag "html" [("style", AttributeValues [StyleValue $ Css.CssProperty ("font-size", [Css.Value "12px"])])])
it "applies multiple style interpolation for root element unquoted style attribute" $
let stylesheet = [Css.CssProperty ("font-size", [Css.Value "12px"]), Css.CssProperty ("text-align", [Css.Value "center"])] in ([html|<html style=${stylesheet} />|] :: Html) `shouldBe`
Html (ShortTag "html" [("style", AttributeValues [StyleValue $ Css.CssProperty ("font-size", [Css.Value "12px"]), StyleValue $ Css.CssProperty ("text-align", [Css.Value "center"])])])
it "applies multiline interpolation" $
let content = "foobar" in ([html|
<body>
${content}
</body>
|] :: Html) `shouldBe`
Html (FullTag "body" [] [Content BreakingSpace, Content $ Plain "foobar", Content BreakingSpace])
| oinuar/doppler-html | test/Doppler/Html/SyntaxSpec.hs | mit | 12,289 | 0 | 26 | 2,818 | 3,105 | 1,579 | 1,526 | 164 | 1 |
module Trainer where
import Numeric.LinearAlgebra
import Models
import Layer
import Optimization
import Data.Foldable
import Control.Monad.IO.Class
import Utils
data TrainConfig = TrainConfig {
trainConfigRowNum :: Int,
trainConfigColNum :: Int,
trainConfigLearningRate :: Double,
trainConfigMomentum :: Double,
trainConfigDecay :: Double,
trainConfigEpsilon :: Double,
trainConfigBatchSize :: Double,
trainConfigOptimization:: String
}
trainSingleData :: Model VLayer -> TrainConfig -> Matrix R -> IO ()
trainSingleData (Model []) _ _ = print "No models !" >> return ()
trainSingleData neuModel trainConfig inputData =
let r = trainConfigRowNum trainConfig
c = trainConfigColNum trainConfig
paramsList = genParamsList neuModel
gparamsList = genGParamsList neuModel
accGradList = accMatrixInit paramsList
accDeltaList = accMatrixInit paramsList
optimize = Adadelta {
adaDecay = trainConfigDecay trainConfig,
adaEpsilon = trainConfigEpsilon trainConfig,
adaBatchSize = (trainConfigBatchSize trainConfig),
adaParams = paramsList,
adaGparams = gparamsList,
adaAccGrad = accGradList,
adaAccDelta = accDeltaList
} in
-- begin to train
forM_ [1..10000] $ \idx -> do
--print idx
let output = forward inputData neuModel in
--print "backpropagate the model" >>
let neuModel = backward "mse" output inputData neuModel in
--print "neumodel" >>
let gparamsList = updateGParamsList neuModel gparamsList in
--print "continue" >>
if mod idx 100 == 0 && idx >= 100 then
-- update the params in optimize
-- update the params in model
let optimize = paramUpdate optimize
paramsList = adaParams optimize
neuModel = updateModelParams neuModel paramsList in
print (getAverageMat output) >>
return()
else return()
| neutronest/vortex | vortex/Trainer.hs | mit | 2,040 | 0 | 23 | 570 | 436 | 234 | 202 | 45 | 2 |
module Server where
import Network (listenOn, withSocketsDo, accept, PortID(..), Socket{-, HostName, PortNumber-})
import System.IO (hSetBuffering, hGetLine, hPutStrLn, hPrint, BufferMode(..), Handle)
import Control.Concurrent --(forkIO, newEmptyMVar, MVar)
import qualified Data.Map as Map
import DataTypes
run :: String -> MVar Connections -> IO ()
run port connections = withSocketsDo $ do
let p = fromIntegral $ (read port :: Int)
sock <- listenOn $ (PortNumber p)
putStrLn $ "Listening on " ++ show p
sockHandler sock connections
sockHandler :: Socket -> MVar Connections -> IO ()
sockHandler sock connections = do
(handle, host, port) <- accept sock
hSetBuffering handle NoBuffering
let connection = (host, port)
_ <- forkIO $ do
conns <- takeMVar connections -- Add new connection
putMVar connections (Map.insert (host, port) (PlayerState Login "", Account "" "" "", handle) conns)
handleMainMenu handle connection connections
commandProcessor handle (host, port) connections
sockHandler sock connections
-- menuState = [(Login, [("New account", LoginNewAccount),
-- ("Login", LoginLogin),
-- ("Quit", Logout)]),
-- (LoginNewAccount, [("Enter your username", LoginNewAccountEmail),
-- ("Back", Login)]),
-- (LoginNewAccountEmail, [("Enter your email", LoginNewAccountPassword),
-- ("Back", LoginNewAccountEmail),
-- ("Cancel", Login)]),
-- (LoginNewAccountPassword, [("Enter your password", LoginNewAccountPasswordVerify),
-- ("Back", LoginNewAccountPassword),
-- ("Cancel", Login)]),
-- (LoginNewAccountPasswordVerify, [("Enter your password again", LoginNewAccountComplete),
-- ("Back", LoginNewAccountPassword),
-- ("Cancel", Login)])
-- ]
printMenu :: Handle -> Connection -> MVar Connections -> IO ()
printMenu h _ _ = do
hPutStrLn h "Welcome to Pokemon Arena!"
router :: [(RoomState, Handle -> Connection -> MVar Connections -> IO ())]
router = [(Login, handleMainMenu),
(LoginNewAccount, handleNewAccount)
--,(LoginLogin, handleLogin)
]
handleMainMenu :: Handle -> Connection -> MVar Connections -> IO ()
handleMainMenu h c cs = do
let menuItems = [("New account", LoginNewAccount)
,("Login", LoginLogin)
,("Quit", Logout)]
localLoop h c cs menuItems
where localLoop :: Handle -> Connection -> MVar Connections -> [(String, RoomState)] -> IO ()
localLoop _ _ _ menu = do
_ <- mapM (\(i, x) -> hPutStrLn h (((show (i :: Int)) :: String) ++ ". " ++ (show x))) (zip [0..] menu)
line <- hGetLine h
let cmd = words line
let choice = lookup (read (head cmd) :: Int) (zip [0..] menu)
case choice of
Just (_, j) -> case (lookup j router) of
Just y -> y h c cs
Nothing -> hPutStrLn h "What? Please try again!" >> localLoop h c cs menu
Nothing -> hPutStrLn h "What? Please try again!" >> localLoop h c cs menu
handleNewAccount :: Handle -> Connection -> MVar Connections -> IO ()
handleNewAccount h c cs = do
let menuItems = [("Cancel", Login)]
localLoop h c cs menuItems
where localLoop :: Handle -> Connection -> MVar Connections -> [(String, RoomState)] -> IO ()
localLoop _ _ _ menu = do
_ <- mapM (\(i, x) -> hPutStrLn h ((show (i :: Int)) ++ ". " ++ (show x))) (zip [0..] menu)
handleUsername
handleUsername = do
hPutStrLn h "What is your username? "
line <- hGetLine h
verifyUsernameAndHandleEmail $ words line
verifyUsernameAndHandleEmail :: [String] -> IO ()
verifyUsernameAndHandleEmail input
| length input == 1 = do
hPutStrLn h "Enter your email:"
l <- hGetLine h
verifyEmailAndHandlePassword (words l) input
| otherwise = do
hPutStrLn h "Sorry, only a one word names please. Try again."
line <- hGetLine h
verifyUsernameAndHandleEmail (words line)
verifyEmailAndHandlePassword :: [String] -> [String] -> IO ()
verifyEmailAndHandlePassword line input
| length line == 1 = do
hPutStrLn h "Enter your password please: "
l <- hGetLine h
verifyPasswordAndHandlePasswordRepeat l (head line:input)
| otherwise = do
hPutStrLn h "Sorry, a valid email contains no spaces. Try again."
l <- hGetLine h
verifyEmailAndHandlePassword (words l) input
verifyPasswordAndHandlePasswordRepeat :: String -> [String] -> IO ()
verifyPasswordAndHandlePasswordRepeat pass input = do
hPutStrLn h "Okay. Next password please."
nextPass <- hGetLine h
verifyPasswordRepeatAndLogin pass nextPass input
verifyPasswordRepeatAndLogin :: String -> String -> [String] -> IO ()
verifyPasswordRepeatAndLogin pass1 pass2 input
| pass1 == pass2 = do
hPutStrLn h "Account created."
let inp = reverse input
conns <- takeMVar cs
let insertPlayer = Map.insert c (PlayerState {currentRoom = Town, lastCommand=""},
Account { username = (inp !! 0)
, password = pass1
, email = (inp !! 1)
},
h) conns
putMVar cs insertPlayer
putStrLn $ "Player created: " ++ (show insertPlayer)
commandProcessor h c cs
| otherwise = do
hPutStrLn h "Passwords didn't match. Please re-enter both passwords."
verifyEmailAndHandlePassword (drop 1 input) (tail input)
commandProcessor :: Handle -> Connection -> MVar Connections -> IO ()
commandProcessor handle con connections = do
line <- hGetLine handle
let cmd = words line
conns <- takeMVar connections
let updatedState = updateLastCommand conns con (head cmd)
putMVar connections updatedState
putStrLn (show updatedState)
case (head cmd) of
("echo") -> echoCommand handle cmd
("add") -> addCommand handle cmd
_ -> hPutStrLn handle "Unknown command"
commandProcessor handle con connections
updateLastCommand :: Connections -> Connection -> String -> Connections
updateLastCommand conns con cmd =
Map.adjust (\(playerstate, a, h) -> (PlayerState { currentRoom=(currentRoom playerstate)
, lastCommand=cmd},
a,
h)) con conns
echoCommand :: Handle -> [String] -> IO ()
echoCommand handle cmd = do
hPutStrLn handle (unwords $ tail cmd)
addCommand :: Handle -> [String] -> IO ()
addCommand handle cmd =
hPrint handle $ (read $ cmd !! 1 :: Int) + (read $ cmd !! 2 :: Int)
| Zolomon/PokemonArena | src/Server.hs | mit | 7,651 | 0 | 20 | 2,739 | 1,963 | 982 | 981 | 125 | 3 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Graph.Weighted.Data where
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Set
import Autolib.Hash
import Data.Typeable
data ( Ord v ) => Kante v w =
Kante { von :: v, nach :: v, gewicht :: w }
deriving ( Typeable )
instance ( Ord v, Hash v, Hash w ) => Hash ( Kante v w ) where
hash k = hash ( von k, nach k, gewicht k )
-- | das Gewicht wird beim Vergleich der Kanten ignoriert.
-- Das ist eventuell keine gute Idee.
-- Damit kann man z. B. keine Automaten darstellen,
-- dort kann es mehrere Kanten mit verschiedenem Gewicht (Labels)
-- zwischen zwei Knoten geben.
-- außerdem versteckt sich hier die Entscheidung,
-- ob Kanten gerichtet oder ungerichtet sind.
instance Ord v => Eq ( Kante v w ) where
k == l = von k == von l && nach k == nach l
instance Ord v => Ord ( Kante v w ) where
compare k l = compare ( von k, nach k ) ( von l, nach l )
data ( Ord v ) => Graph v w =
Graph { knoten :: Set v
, kanten :: Set ( Kante v w )
}
deriving ( Typeable, Eq )
instance (Ord v, Hash v, Hash w) => Hash ( Graph v w ) where
hash g = hash ( knoten g, kanten g )
$(derives [makeReader, makeToDoc] [''Kante, ''Graph]) | Erdwolf/autotool-bonn | src/Graph/Weighted/Data.hs | gpl-2.0 | 1,258 | 0 | 11 | 318 | 416 | 222 | 194 | 23 | 0 |
import Prelude hiding (map)
import Hiding2 hiding (x, y)
--TODO: statische error bij verbergen show functie
x, y :: Int
x = 3
y = 4
map :: Num a => [a] -> a
map xs = sum xs
main :: (Int, String)
main = ( map [x,y,z] -- should be 307
, show X -- show functions, types and constructors may not be hidden
)
| Helium4Haskell/helium | test/make/Hiding1.hs | gpl-3.0 | 321 | 0 | 7 | 83 | 109 | 65 | 44 | 10 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | A modifier that can contain exactly one out of multiple modifiers of different types.
module Data.VPlan.Modifier.Enum (
(:><:)(R,L)
, enumSchedule
, enumItem
, scheduleItem
, EnumContains(enumValue, castEnum)
, EnumApply(enumApply)
, CFunc(..)
, enumv
, BothInstance
, BothInstance1
, BothInstance2
, C
) where
import Control.Applicative
import Data.Aeson.Types
import Data.Maybe
import GHC.Exts
import Data.Foldable (Foldable(..))
import Control.Lens
import Control.Monad
import Data.Data
import qualified Data.VPlan.At as A
import Data.VPlan.Builder
import Data.VPlan.Class
import qualified Data.Text as T
import Data.VPlan.Schedule
import Data.VPlan.TH
import Control.Lens.Aeson
import GHC.Generics hiding (C)
-- | An Either for types with one type argument (which is passed to both sides)
data (:><:) a b (s :: * -> * -> * -> *) c i v = L (a s c i v) | R (b s c i v) deriving (Eq, Generic)
infixr 2 :><:
makeModifier ''(:><:)
deriving instance (BothInstance Show a b s c i v) => Show (C a b s c i v)
deriving instance (BothInstance Read a b s c i v) => Read (C a b s c i v)
deriving instance (Typeable v, Typeable i, Typeable c, BothInstance Data a b s c i v, Typeable3 (C a b s)) => Data ((:><:) a b s c i v)
-- | Shorter alias
type C = (:><:)
-- | Require that a type enum can contain the given value
class EnumContains a b where
-- | Create an enum with the given value.
enumValue :: a s c i v -> b (s :: * -> * -> * -> *) c i v
-- | Try to access the value of the requested type in the enum. Returns Nothing if a value of another type
-- is currently stored in the enum.
castEnum :: b (s :: * -> * -> * -> *) c i v -> Maybe (a s c i v)
instance EnumContains a a where
enumValue = id
castEnum = Just
instance EnumContains a (C a b) where
enumValue = L
castEnum = preview $ enumEither . _Left
instance EnumContains b (C a b) where
enumValue = R
castEnum = preview $ enumEither . _Right
instance (EnumContains c b) => EnumContains c (C a b) where
enumValue = R . enumValue
castEnum = preview (enumEither . _Right) >=> castEnum
type BothInstance (c :: * -> Constraint) a b (s :: * -> * -> * -> *) c' i v = (c (a s c' i v), c (b s c' i v))
type BothInstance1 (c :: (* -> *) -> Constraint) a b (s :: * -> * -> * -> *) c' i = (c (a s c' i), c (b s c' i))
type BothInstance2 (c :: (* -> * -> *) -> Constraint) a b (s :: * -> * -> * -> *) c' = (c (a s c'), c (b s c'))
type BothInstance3 (c :: (* -> * -> * -> *) -> Constraint) a b (s :: * -> * -> * -> *) = (c (a s), c (b s))
type BothSame f a b s c i v = (f (C a b (s :: * -> * -> * -> *) c i v) ~ f (a s c i v), f (C a b s c i v) ~ f (b s c i v))
instance (BothInstance (A.Contains f) a b s c i v, BothSame Index a b s c i v, Functor f) => A.Contains f (C a b s c i v) where
contains i f (L x) = L <$> A.contains i f x
contains i f (R x) = R <$> A.contains i f x
instance (Functor f, BothInstance (A.Ixed f) a b s c i v, BothSame Index a b s c i v, BothSame IxValue a b s c i v) => A.Ixed f (C a b s c i v) where
ix i f (L x) = L <$> A.ix i f x
ix i f (R x) = R <$> A.ix i f x
instance (BothInstance Periodic a b s c i v, BothSame Index a b s c i v) => Periodic (C a b s c i v) where
interval (L a) = interval a
interval (R a) = interval a
instance (BothInstance Limited a b s c i v, BothSame Index a b s c i v) => Limited (C a b s c i v) where
imin (L a) = imin a
imin (R a) = imin a
imax (L a) = imax a
imax (R a) = imax a
instance BothInstance1 Functor a b s c i => Functor (C a b s c i) where
fmap f (L x) = L $ fmap f x
fmap f (R x) = R $ fmap f x
instance BothInstance2 Bifunctor a b s c => Bifunctor (C a b s c) where
bimap f g (L x) = L $ bimap f g x
bimap f g (R x) = R $ bimap f g x
instance BothInstance2 Profunctor a b s c => Profunctor (C a b s c) where
dimap l r (L x) = L $ dimap l r x
dimap l r (R x) = R $ dimap l r x
instance BothInstance1 Contravariant a b s c i => Contravariant (C a b s c i) where
contramap f (L x) = L $ contramap f x
contramap f (R x) = R $ contramap f x
instance BothInstance1 Foldable a b s c i => Foldable (C a b s c i) where
foldMap f (L x) = foldMap f x
foldMap f (R x) = foldMap f x
instance (BothInstance1 Traversable a b s c i) => Traversable (C a b s c i) where
traverse f (L x) = L <$> traverse f x
traverse f (R x) = R <$> traverse f x
-- | Unwrap one constructor application in a TypeRep
unapply :: TypeRep -> TypeRep
unapply t = typeRepTyCon t `mkTyConApp` dropEnd 1 (typeRepArgs t)
-- | Select a the given element of an association list, failing with the default given.
caseOf :: (Eq k) => (k -> a) -> [(k,a)] -> k -> a
caseOf def assoc k = fromMaybe (def k) $ assoc ^? traversed . filtered ((==k) . fst) . _2
instance (BothInstance FromJSON a (C b c) s c' i v, Typeable3 (a s)) => FromJSON (C a (C b c) s c' i v) where
parseJSON (Object o)
| o ^? ix "modifier" . _String == Just (T.pack $ show typL) = L <$> parseJSON (Object $ sans "modifier" o)
| otherwise = R <$> parseJSON (Object o)
where typL = unapply $ typeOf3 (undefined :: a s c' () ())
parseJSON v = typeMismatch "Object" v
instance (BothInstance FromJSON a b s c i v, BothInstance3 Typeable3 a b s) => FromJSON (C a b s c i v) where
parseJSON (Object o) = o .: "modifier" >>= caseOf failure
[ (show typL, L <$> parseJSON (Object $ sans "modifier" o))
, (show typR, R <$> parseJSON (Object $ sans "modifier" o))
]
where failure m = fail $ "Unknown modifier: " ++ m
typL = unapply $ typeOf3 (undefined :: a s c () ())
typR = unapply $ typeOf3 (undefined :: b s c () ())
parseJSON v = typeMismatch "Object" v
instance (BothInstance ToJSON a (C b c) s c' i v, Typeable3 (a s)) => ToJSON (C a (C b c) s c' i v) where
toJSON (L x) = let (Object o) = toJSON x in Object $ o & at "modifier" ?~ String (T.pack $ show $ unapply $ typeOf3 (undefined :: a s c' () ()))
toJSON (R x) = toJSON x
instance (BothInstance ToJSON a b s c i v, BothInstance3 Typeable3 a b s) => ToJSON (C a b s c i v) where
toJSON (L x) = let (Object o) = toJSON x in Object $ o & at "modifier" ?~ String (T.pack $ show $ unapply $ typeOf3 (undefined :: a s c () ()))
toJSON (R x) = let (Object o) = toJSON x in Object $ o & at "modifier" ?~ String (T.pack $ show $ unapply $ typeOf3 (undefined :: b s c () ()))
-- | A polymorphic, constrained function returning some type r.
data CFunc ctx r = CFunc
{ cfunc :: (forall a. ctx a => a -> r)
}
-- | Class to which allows to apply functions to the values in an Enum
class EnumApply ctx e where
enumApply :: CFunc ctx b -> e -> b
instance (ctx (l s c i v), EnumApply ctx (r s c i v)) => EnumApply ctx (C l r s c i v) where
enumApply f (L a) = cfunc f a
enumApply f (R a) = enumApply f a
instance (ctx a) => EnumApply ctx a where
enumApply f a = cfunc f a
-- | Build a value as a schedule containing an enum.
enumSchedule :: (EnumContains a s) => a (Schedule s) c i v -> Schedule s c i v
enumSchedule = view schedule . enumValue
-- | Build an enum value as a single item.
enumItem :: (EnumContains a e) => a (Schedule s) c i v -> Builder (e (Schedule s) c i v) ()
enumItem = item . enumValue
-- | Build an enum value as a single schedule item.
scheduleItem :: (EnumContains a s) => a (Schedule s) c i v -> Builder (Schedule s c i v) ()
scheduleItem = item . enumSchedule
instance (EnumContains m s) => Supported m (Schedule s) where new = enumSchedule
-- | Convert an Enum to/from an Either
enumEither :: Iso (C a b s c i v) (C a' b' s' c' i' v') (Either (a s c i v) (b s c i v)) (Either (a' s' c' i' v') (b' s' c' i' v'))
enumEither = iso ?? either L R $ \e -> case e of
L x -> Left x
R x -> Right x
-- | A prism that focuses the element at the given type in an enum. The v stands for "value", it's there because the name
-- enum is already taken by lens.
enumv :: (EnumApply Typeable (e s c i v), EnumContains a e, EnumContains b e) => Prism (e s c i v) (e s c i v) (a s c i v) (b s c i v)
enumv = prism enumValue (\e -> maybe (Left e) Right $ castEnum e)
| bennofs/vplan | src/Data/VPlan/Modifier/Enum.hs | gpl-3.0 | 8,851 | 0 | 15 | 2,303 | 3,953 | 2,060 | 1,893 | -1 | -1 |
ssa :: State s (State s a)
runState ssa :: s -> (State s a, s) | hmemcpy/milewski-ctfp-pdf | src/content/3.6/code/haskell/snippet24.hs | gpl-3.0 | 62 | 1 | 8 | 15 | 42 | 21 | 21 | -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.CloudFront.ListDistributions
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List distributions.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/ListDistributions.html AWS API Reference> for ListDistributions.
--
-- This operation returns paginated results.
module Network.AWS.CloudFront.ListDistributions
(
-- * Creating a Request
listDistributions
, ListDistributions
-- * Request Lenses
, ldMarker
, ldMaxItems
-- * Destructuring the Response
, listDistributionsResponse
, ListDistributionsResponse
-- * Response Lenses
, ldrsResponseStatus
, ldrsDistributionList
) where
import Network.AWS.CloudFront.Types
import Network.AWS.CloudFront.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The request to list your distributions.
--
-- /See:/ 'listDistributions' smart constructor.
data ListDistributions = ListDistributions'
{ _ldMarker :: !(Maybe Text)
, _ldMaxItems :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListDistributions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldMarker'
--
-- * 'ldMaxItems'
listDistributions
:: ListDistributions
listDistributions =
ListDistributions'
{ _ldMarker = Nothing
, _ldMaxItems = Nothing
}
-- | Use this when paginating results to indicate where to begin in your list
-- of distributions. The results include distributions in the list that
-- occur after the marker. To get the next page of results, set the Marker
-- to the value of the NextMarker from the current page\'s response (which
-- is also the ID of the last distribution on that page).
ldMarker :: Lens' ListDistributions (Maybe Text)
ldMarker = lens _ldMarker (\ s a -> s{_ldMarker = a});
-- | The maximum number of distributions you want in the response body.
ldMaxItems :: Lens' ListDistributions (Maybe Text)
ldMaxItems = lens _ldMaxItems (\ s a -> s{_ldMaxItems = a});
instance AWSPager ListDistributions where
page rq rs
| stop (rs ^. ldrsDistributionList . dlIsTruncated) =
Nothing
| isNothing
(rs ^? ldrsDistributionList . dlNextMarker . _Just)
= Nothing
| otherwise =
Just $ rq &
ldMarker .~
rs ^? ldrsDistributionList . dlNextMarker . _Just
instance AWSRequest ListDistributions where
type Rs ListDistributions = ListDistributionsResponse
request = get cloudFront
response
= receiveXML
(\ s h x ->
ListDistributionsResponse' <$>
(pure (fromEnum s)) <*> (parseXML x))
instance ToHeaders ListDistributions where
toHeaders = const mempty
instance ToPath ListDistributions where
toPath = const "/2015-04-17/distribution"
instance ToQuery ListDistributions where
toQuery ListDistributions'{..}
= mconcat
["Marker" =: _ldMarker, "MaxItems" =: _ldMaxItems]
-- | The returned result of the corresponding request.
--
-- /See:/ 'listDistributionsResponse' smart constructor.
data ListDistributionsResponse = ListDistributionsResponse'
{ _ldrsResponseStatus :: !Int
, _ldrsDistributionList :: !DistributionList
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListDistributionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ldrsResponseStatus'
--
-- * 'ldrsDistributionList'
listDistributionsResponse
:: Int -- ^ 'ldrsResponseStatus'
-> DistributionList -- ^ 'ldrsDistributionList'
-> ListDistributionsResponse
listDistributionsResponse pResponseStatus_ pDistributionList_ =
ListDistributionsResponse'
{ _ldrsResponseStatus = pResponseStatus_
, _ldrsDistributionList = pDistributionList_
}
-- | The response status code.
ldrsResponseStatus :: Lens' ListDistributionsResponse Int
ldrsResponseStatus = lens _ldrsResponseStatus (\ s a -> s{_ldrsResponseStatus = a});
-- | The DistributionList type.
ldrsDistributionList :: Lens' ListDistributionsResponse DistributionList
ldrsDistributionList = lens _ldrsDistributionList (\ s a -> s{_ldrsDistributionList = a});
| olorin/amazonka | amazonka-cloudfront/gen/Network/AWS/CloudFront/ListDistributions.hs | mpl-2.0 | 5,092 | 0 | 14 | 1,079 | 710 | 416 | 294 | -1 | -1 |
-- | Parsing of Enums.
module Data.GI.GIR.Enum
( Enumeration(..)
, parseEnum
) where
import Data.Int (Int64)
import Data.Text (Text)
import Foreign.C (CInt(..))
import Data.GI.GIR.Parser
data Enumeration = Enumeration {
enumValues :: [(Text, Int64)],
errorDomain :: Maybe Text,
enumTypeInit :: Maybe Text,
enumStorageBytes :: Int, -- ^ Bytes used for storage of this struct.
enumDeprecated :: Maybe DeprecationInfo }
deriving Show
-- | Parse a struct member.
parseEnumMember :: Parser (Text, Int64)
parseEnumMember = do
name <- getAttr "name"
value <- getAttr "value" >>= parseIntegral
return (name, value)
foreign import ccall "_gi_get_enum_storage_bytes" get_storage_bytes ::
Int64 -> Int64 -> CInt
-- | Return the number of bytes that should be allocated for storage
-- of the given values in an enum.
extractEnumStorageBytes :: [Int64] -> Int
extractEnumStorageBytes values =
fromIntegral $ get_storage_bytes (minimum values) (maximum values)
-- | Parse an "enumeration" element from the GIR file.
parseEnum :: Parser (Name, Enumeration)
parseEnum = do
name <- parseName
deprecated <- parseDeprecation
errorDomain <- queryAttrWithNamespace GLibGIRNS "error-domain"
typeInit <- queryAttrWithNamespace GLibGIRNS "get-type"
values <- parseChildrenWithLocalName "member" parseEnumMember
return (name,
Enumeration {
enumValues = values
, errorDomain = errorDomain
, enumTypeInit = typeInit
, enumStorageBytes = extractEnumStorageBytes (map snd values)
, enumDeprecated = deprecated
})
| hamishmack/haskell-gi | lib/Data/GI/GIR/Enum.hs | lgpl-2.1 | 1,625 | 0 | 13 | 341 | 367 | 205 | 162 | 38 | 1 |
-- -*-haskell-*-
-- GIMP Toolkit (GTK) CellRenderer TreeView
--
-- Author : Axel Simon
--
-- Created: 23 May 2001
--
-- Copyright (C) 1999-2005 Axel Simon
--
-- 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.
--
-- |
-- Maintainer : gtk2hs-users@lists.sourceforge.net
-- Stability : provisional
-- Portability : portable (depends on GHC)
--
-- A 'CellRenderer' is an object that determines how the cell of a
-- 'TreeView' widget is displayed.
--
-- * Each 'TreeViewColumn' has exactly one accociated 'CellRenderer'.
-- The data supply for a cell is contained in a 'TreeStore' or a
-- 'ListStore' (both subclasses of 'TreeModel'). Each 'CellRenderer'
-- may have several attributes. Each 'Attribute' is associated with
-- one column of the 'TreeModel' database. Thus several columns of a
-- 'TreeModel' may be the supply for one 'TreeViewColumn'.
--
module Graphics.UI.Gtk.TreeList.CellRenderer (
-- * Detail
--
-- | The 'CellRenderer' is a base class of a set of objects used for rendering
-- a cell to a 'Drawable'. These objects are used primarily by the 'TreeView'
-- widget, though they aren't tied to them in any specific way. It is worth
-- noting that 'CellRenderer' is not a 'Widget' and cannot be treated as such.
--
-- The primary use of a 'CellRenderer' is for drawing a certain graphical
-- elements on a 'Drawable'. Typically, one cell renderer is used to draw many
-- cells on the screen. To this extent, it isn't expected that a CellRenderer
-- keep any permanent state around. Instead, any state is set just prior to use
-- using 'GObject's property system. Then, the cell is measured using
-- 'cellRendererGetSize'. Finally, the cell is rendered in the correct location
-- using 'cellRendererRender'.
--
-- Beyond merely rendering a cell, cell renderers can optionally provide
-- active user interface elements. A cell renderer can be activatable like
-- 'CellRendererToggle', which toggles when it gets activated by a mouse click,
-- or it can be editable like 'CellRendererText', which allows the user to edit
-- the text using a 'Entry'.
-- * Class Hierarchy
-- |
-- @
-- | 'GObject'
-- | +----'Object'
-- | +----CellRenderer
-- | +----'CellRendererText'
-- | +----'CellRendererPixbuf'
-- | +----'CellRendererProgress'
-- | +----'CellRendererToggle'
-- @
-- * Types
CellRenderer,
CellRendererClass,
castToCellRenderer,
toCellRenderer,
Attribute(..),
-- * Methods
cellRendererSet,
cellRendererGet
) where
import Control.Monad (zipWithM)
import Graphics.UI.Gtk.Types
import System.Glib.StoreValue (GenericValue, TMType,
valueSetGenericValue, valueGetGenericValue)
import System.Glib.Properties (objectSetPropertyInternal,
objectGetPropertyInternal)
-- | Definition of the 'Attribute' data type.
--
-- * Each 'CellRenderer' defines a set of attributes. They are used
-- by the Mogul layer to generate columns in a 'TreeStore' or
-- 'ListStore'.
--
data CellRendererClass cr => Attribute cr a = Attribute [String] [TMType]
(a -> IO [GenericValue])
([GenericValue] -> IO a)
-- | Set a property statically.
--
-- * Instead of using a 'TreeStore' or 'ListStore' to set
-- properties of a 'CellRenderer' this method allows to set such
-- a property for the whole column.
--
cellRendererSet :: CellRendererClass cr =>
cr -> Attribute cr val -> val -> IO ()
cellRendererSet cr (Attribute names types write _) val = do
values <- write val
sequence_ $ zipWith3 (\name tmtype value ->
objectSetPropertyInternal
(fromIntegral $ fromEnum tmtype)
valueSetGenericValue name cr value)
names types values
-- | Get a static property.
--
-- * See 'cellRendererSet'. Note that calling this function on a
-- property of a 'CellRenderer' object which retrieves its values
-- from a 'ListStore' or 'TreeStore' will result in an
-- abitrary value.
--
cellRendererGet :: CellRendererClass cr =>
cr -> Attribute cr val -> IO val
cellRendererGet cr (Attribute names types _ read) = do
values <- zipWithM (\name tmtype ->
objectGetPropertyInternal
(fromIntegral $ fromEnum tmtype)
valueGetGenericValue name cr)
names types
read values
| thiagoarrais/gtk2hs | gtk/Graphics/UI/Gtk/TreeList/CellRenderer.hs | lgpl-2.1 | 4,931 | 12 | 14 | 1,147 | 457 | 284 | 173 | 35 | 1 |
{-# LANGUAGE InstanceSigs #-}
module MoiState where
newtype Moi s a =
Moi { runMoi :: s -> (a, s) }
instance Functor (Moi s) where
fmap :: (a -> b) -> Moi s a -> Moi s b
fmap f (Moi g) = Moi $ (\(a,s) -> (f a, s)) . g
instance Applicative (Moi s) where
pure :: a -> Moi s a
pure a = Moi $ \s -> (a, s)
(<*>) :: Moi s (a -> b) -> Moi s a -> Moi s b
(Moi f) <*> (Moi g) = Moi $ (\(a, s) -> ((fst $ f s) a, s)) . g
instance Monad (Moi s) where
return = pure
(>>=) :: Moi s a -> (a -> Moi s b) -> Moi s b
(>>=) (Moi f) g = Moi $ \s -> (runMoi $ (g . fst . f) s) s
{-(>>) :: Moi s a -> Moi s b -> Moi s b-}
{-(>>) (Moi f) (Moi g) = Moi $ \s -> (g,s)-}
| thewoolleyman/haskellbook | 23/08/haskell-club/MoiState.hs | unlicense | 676 | 0 | 14 | 202 | 382 | 207 | 175 | 16 | 0 |
{-
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
-}
isPythTriple :: (Integral a) => a -> a -> a -> Bool
isPythTriple a b c = a^2 + b^2 == c^2
findTriple1000 :: Integer
findTriple1000 = find 1 1 where
find 998 two = find 1 (two+1)
find one two = if isPythTriple one two three
then one*two*three
else find (one+1) two
where three = 1000 - one - two
| m3mitsuppe/haskell | projecteuler/pr009.hs | unlicense | 578 | 4 | 10 | 166 | 163 | 84 | 79 | 9 | 3 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
import Data.FileEmbed
import Test.HUnit ((@?=))
import System.FilePath ((</>))
main :: IO ()
main = do
let received = $(embedDir "test/sample")
received @?=
[ ("foo", "foo\r\n")
, ("bar" </> "baz", "baz\r\n")
]
| phadej/file-embed | test/main.hs | bsd-2-clause | 313 | 0 | 12 | 73 | 92 | 53 | 39 | 11 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGraphicsSimpleTextItem_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:26
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QGraphicsSimpleTextItem_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QGraphicsItem
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QGraphicsSimpleTextItem ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGraphicsSimpleTextItem_unSetUserMethod" qtc_QGraphicsSimpleTextItem_unSetUserMethod :: Ptr (TQGraphicsSimpleTextItem a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGraphicsSimpleTextItemSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsSimpleTextItem ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGraphicsSimpleTextItemSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsSimpleTextItem ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGraphicsSimpleTextItemSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGraphicsSimpleTextItem_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsSimpleTextItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsSimpleTextItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsSimpleTextItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setUserMethod" qtc_QGraphicsSimpleTextItem_setUserMethod :: Ptr (TQGraphicsSimpleTextItem a) -> CInt -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsSimpleTextItem :: (Ptr (TQGraphicsSimpleTextItem x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsSimpleTextItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGraphicsSimpleTextItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGraphicsSimpleTextItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsSimpleTextItem_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsSimpleTextItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsSimpleTextItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsSimpleTextItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setUserMethodVariant" qtc_QGraphicsSimpleTextItem_setUserMethodVariant :: Ptr (TQGraphicsSimpleTextItem a) -> CInt -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsSimpleTextItem :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsSimpleTextItem_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGraphicsSimpleTextItem setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGraphicsSimpleTextItem_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGraphicsSimpleTextItem_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsSimpleTextItem_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGraphicsSimpleTextItem_unSetHandler" qtc_QGraphicsSimpleTextItem_unSetHandler :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> IO (CBool)
instance QunSetHandler (QGraphicsSimpleTextItemSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGraphicsSimpleTextItem_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler1" qtc_QGraphicsSimpleTextItem_setHandler1 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem1 :: (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQRectF t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> IO (QRectF t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_boundingRect cobj_x0
foreign import ccall "qtc_QGraphicsSimpleTextItem_boundingRect" qtc_QGraphicsSimpleTextItem_boundingRect :: Ptr (TQGraphicsSimpleTextItem a) -> IO (Ptr (TQRectF ()))
instance QqqboundingRect_h (QGraphicsSimpleTextItemSc a) (()) where
qqboundingRect_h x0 ()
= withQRectFResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_boundingRect cobj_x0
instance QqboundingRect_h (QGraphicsSimpleTextItem ()) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
foreign import ccall "qtc_QGraphicsSimpleTextItem_boundingRect_qth" qtc_QGraphicsSimpleTextItem_boundingRect_qth :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO ()
instance QqboundingRect_h (QGraphicsSimpleTextItemSc a) (()) where
qboundingRect_h x0 ()
= withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler2" qtc_QGraphicsSimpleTextItem_setHandler2 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem2 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPointF t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QPointF t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsSimpleTextItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
foreign import ccall "qtc_QGraphicsSimpleTextItem_contains_qth" qtc_QGraphicsSimpleTextItem_contains_qth :: Ptr (TQGraphicsSimpleTextItem a) -> CDouble -> CDouble -> IO CBool
instance Qqcontains_h (QGraphicsSimpleTextItemSc a) ((PointF)) where
qcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPointF x1 $ \cpointf_x1_x cpointf_x1_y ->
qtc_QGraphicsSimpleTextItem_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y
instance Qqqcontains_h (QGraphicsSimpleTextItem ()) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_contains cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_contains" qtc_QGraphicsSimpleTextItem_contains :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQPointF t1) -> IO CBool
instance Qqqcontains_h (QGraphicsSimpleTextItemSc a) ((QPointF t1)) where
qqcontains_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_contains cobj_x0 cobj_x1
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler3" qtc_QGraphicsSimpleTextItem_setHandler3 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem3 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler4" qtc_QGraphicsSimpleTextItem_setHandler4 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem4 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QObject t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_isObscuredBy cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_isObscuredBy" qtc_QGraphicsSimpleTextItem_isObscuredBy :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsSimpleTextItemSc a) ((QGraphicsItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_isObscuredBy cobj_x0 cobj_x1
instance QisObscuredBy_h (QGraphicsSimpleTextItem ()) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_isObscuredBy_graphicstextitem" qtc_QGraphicsSimpleTextItem_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QisObscuredBy_h (QGraphicsSimpleTextItemSc a) ((QGraphicsTextItem t1)) where
isObscuredBy_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_isObscuredBy_graphicstextitem cobj_x0 cobj_x1
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler5" qtc_QGraphicsSimpleTextItem_setHandler5 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem5 :: (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (Ptr (TQPainterPath t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> IO (QPainterPath t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_opaqueArea cobj_x0
foreign import ccall "qtc_QGraphicsSimpleTextItem_opaqueArea" qtc_QGraphicsSimpleTextItem_opaqueArea :: Ptr (TQGraphicsSimpleTextItem a) -> IO (Ptr (TQPainterPath ()))
instance QopaqueArea_h (QGraphicsSimpleTextItemSc a) (()) where
opaqueArea_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_opaqueArea cobj_x0
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler6" qtc_QGraphicsSimpleTextItem_setHandler6 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem6 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((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_QGraphicsSimpleTextItem_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QGraphicsSimpleTextItem_paint" qtc_QGraphicsSimpleTextItem_paint :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO ()
instance Qpaint_h (QGraphicsSimpleTextItemSc 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_QGraphicsSimpleTextItem_paint cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance Qshape_h (QGraphicsSimpleTextItem ()) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_shape cobj_x0
foreign import ccall "qtc_QGraphicsSimpleTextItem_shape" qtc_QGraphicsSimpleTextItem_shape :: Ptr (TQGraphicsSimpleTextItem a) -> IO (Ptr (TQPainterPath ()))
instance Qshape_h (QGraphicsSimpleTextItemSc a) (()) where
shape_h x0 ()
= withQPainterPathResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_shape cobj_x0
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler7" qtc_QGraphicsSimpleTextItem_setHandler7 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem7 :: (Ptr (TQGraphicsSimpleTextItem x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_type cobj_x0
foreign import ccall "qtc_QGraphicsSimpleTextItem_type" qtc_QGraphicsSimpleTextItem_type :: Ptr (TQGraphicsSimpleTextItem a) -> IO CInt
instance Qqtype_h (QGraphicsSimpleTextItemSc a) (()) where
qtype_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_type cobj_x0
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler8" qtc_QGraphicsSimpleTextItem_setHandler8 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem8 :: (Ptr (TQGraphicsSimpleTextItem x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_advance cobj_x0 (toCInt x1)
foreign import ccall "qtc_QGraphicsSimpleTextItem_advance" qtc_QGraphicsSimpleTextItem_advance :: Ptr (TQGraphicsSimpleTextItem a) -> CInt -> IO ()
instance Qadvance_h (QGraphicsSimpleTextItemSc a) ((Int)) where
advance_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_advance cobj_x0 (toCInt x1)
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler9" qtc_QGraphicsSimpleTextItem_setHandler9 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem9 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler10" qtc_QGraphicsSimpleTextItem_setHandler10 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem10 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithItem" qtc_QGraphicsSimpleTextItem_collidesWithItem :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsSimpleTextItemSc a) ((QGraphicsItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsSimpleTextItem ()) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithItem1" qtc_QGraphicsSimpleTextItem_collidesWithItem1 :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsSimpleTextItemSc a) ((QGraphicsItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QcollidesWithItem_h (QGraphicsSimpleTextItem ()) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithItem_graphicstextitem" qtc_QGraphicsSimpleTextItem_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool
instance QcollidesWithItem_h (QGraphicsSimpleTextItemSc a) ((QGraphicsTextItem t1)) where
collidesWithItem_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem_graphicstextitem cobj_x0 cobj_x1
instance QcollidesWithItem_h (QGraphicsSimpleTextItem ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithItem1_graphicstextitem" qtc_QGraphicsSimpleTextItem_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool
instance QcollidesWithItem_h (QGraphicsSimpleTextItemSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where
collidesWithItem_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler11" qtc_QGraphicsSimpleTextItem_setHandler11 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem11 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QPainterPath t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler12" qtc_QGraphicsSimpleTextItem_setHandler12 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem12 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithPath cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithPath" qtc_QGraphicsSimpleTextItem_collidesWithPath :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQPainterPath t1) -> IO CBool
instance QcollidesWithPath_h (QGraphicsSimpleTextItemSc a) ((QPainterPath t1)) where
collidesWithPath_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithPath cobj_x0 cobj_x1
instance QcollidesWithPath_h (QGraphicsSimpleTextItem ()) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QGraphicsSimpleTextItem_collidesWithPath1" qtc_QGraphicsSimpleTextItem_collidesWithPath1 :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool
instance QcollidesWithPath_h (QGraphicsSimpleTextItemSc a) ((QPainterPath t1, ItemSelectionMode)) where
collidesWithPath_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler13" qtc_QGraphicsSimpleTextItem_setHandler13 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem13 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_contextMenuEvent" qtc_QGraphicsSimpleTextItem_contextMenuEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_contextMenuEvent cobj_x0 cobj_x1
instance QdragEnterEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_dragEnterEvent" qtc_QGraphicsSimpleTextItem_dragEnterEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragEnterEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_dragLeaveEvent" qtc_QGraphicsSimpleTextItem_dragLeaveEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragLeaveEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_dragMoveEvent" qtc_QGraphicsSimpleTextItem_dragMoveEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdragMoveEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_dropEvent" qtc_QGraphicsSimpleTextItem_dropEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO ()
instance QdropEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneDragDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_dropEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QGraphicsSimpleTextItem ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_focusInEvent" qtc_QGraphicsSimpleTextItem_focusInEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QGraphicsSimpleTextItemSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QGraphicsSimpleTextItem ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_focusOutEvent" qtc_QGraphicsSimpleTextItem_focusOutEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QGraphicsSimpleTextItemSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_focusOutEvent cobj_x0 cobj_x1
instance QhoverEnterEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_hoverEnterEvent" qtc_QGraphicsSimpleTextItem_hoverEnterEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverEnterEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverEnterEvent cobj_x0 cobj_x1
instance QhoverLeaveEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_hoverLeaveEvent" qtc_QGraphicsSimpleTextItem_hoverLeaveEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverLeaveEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverLeaveEvent cobj_x0 cobj_x1
instance QhoverMoveEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_hoverMoveEvent" qtc_QGraphicsSimpleTextItem_hoverMoveEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO ()
instance QhoverMoveEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneHoverEvent t1)) where
hoverMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_hoverMoveEvent cobj_x0 cobj_x1
instance QinputMethodEvent_h (QGraphicsSimpleTextItem ()) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_inputMethodEvent" qtc_QGraphicsSimpleTextItem_inputMethodEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent_h (QGraphicsSimpleTextItemSc a) ((QInputMethodEvent t1)) where
inputMethodEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_inputMethodEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler14" qtc_QGraphicsSimpleTextItem_setHandler14 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem14 :: (Ptr (TQGraphicsSimpleTextItem x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QGraphicsSimpleTextItem_inputMethodQuery" qtc_QGraphicsSimpleTextItem_inputMethodQuery :: Ptr (TQGraphicsSimpleTextItem a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QGraphicsSimpleTextItemSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGraphicsSimpleTextItem_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler15" qtc_QGraphicsSimpleTextItem_setHandler15 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem15 :: (Ptr (TQGraphicsSimpleTextItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsSimpleTextItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
foreign import ccall "qtc_QGraphicsSimpleTextItem_itemChange" qtc_QGraphicsSimpleTextItem_itemChange :: Ptr (TQGraphicsSimpleTextItem a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ()))
instance QitemChange_h (QGraphicsSimpleTextItemSc a) ((GraphicsItemChange, QVariant t2)) where
itemChange_h x0 (x1, x2)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsSimpleTextItem_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2
instance QkeyPressEvent_h (QGraphicsSimpleTextItem ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_keyPressEvent" qtc_QGraphicsSimpleTextItem_keyPressEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QGraphicsSimpleTextItemSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_keyPressEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QGraphicsSimpleTextItem ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_keyReleaseEvent" qtc_QGraphicsSimpleTextItem_keyReleaseEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QGraphicsSimpleTextItemSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_keyReleaseEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_mouseDoubleClickEvent" qtc_QGraphicsSimpleTextItem_mouseDoubleClickEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_mouseMoveEvent" qtc_QGraphicsSimpleTextItem_mouseMoveEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_mousePressEvent" qtc_QGraphicsSimpleTextItem_mousePressEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_mouseReleaseEvent" qtc_QGraphicsSimpleTextItem_mouseReleaseEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler16" qtc_QGraphicsSimpleTextItem_setHandler16 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem16 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_sceneEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_sceneEvent" qtc_QGraphicsSimpleTextItem_sceneEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQEvent t1) -> IO CBool
instance QsceneEvent_h (QGraphicsSimpleTextItemSc a) ((QEvent t1)) where
sceneEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_sceneEvent cobj_x0 cobj_x1
instance QsetHandler (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler17" qtc_QGraphicsSimpleTextItem_setHandler17 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem17 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) (QGraphicsSimpleTextItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem_setHandler18" qtc_QGraphicsSimpleTextItem_setHandler18 :: Ptr (TQGraphicsSimpleTextItem a) -> CWString -> Ptr (Ptr (TQGraphicsSimpleTextItem 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_QGraphicsSimpleTextItem18 :: (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsSimpleTextItem x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGraphicsSimpleTextItem18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGraphicsSimpleTextItemSc a) (QGraphicsSimpleTextItem x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGraphicsSimpleTextItem18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGraphicsSimpleTextItem18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGraphicsSimpleTextItem_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGraphicsSimpleTextItem 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 (QGraphicsSimpleTextItem ()) ((QGraphicsItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsSimpleTextItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsSimpleTextItem_sceneEventFilter" qtc_QGraphicsSimpleTextItem_sceneEventFilter :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsSimpleTextItemSc 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_QGraphicsSimpleTextItem_sceneEventFilter cobj_x0 cobj_x1 cobj_x2
instance QsceneEventFilter_h (QGraphicsSimpleTextItem ()) ((QGraphicsTextItem t1, QEvent t2)) where
sceneEventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QGraphicsSimpleTextItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QGraphicsSimpleTextItem_sceneEventFilter_graphicstextitem" qtc_QGraphicsSimpleTextItem_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool
instance QsceneEventFilter_h (QGraphicsSimpleTextItemSc 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_QGraphicsSimpleTextItem_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2
instance QwheelEvent_h (QGraphicsSimpleTextItem ()) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QGraphicsSimpleTextItem_wheelEvent" qtc_QGraphicsSimpleTextItem_wheelEvent :: Ptr (TQGraphicsSimpleTextItem a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO ()
instance QwheelEvent_h (QGraphicsSimpleTextItemSc a) ((QGraphicsSceneWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGraphicsSimpleTextItem_wheelEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QGraphicsSimpleTextItem_h.hs | bsd-2-clause | 102,263 | 0 | 18 | 20,812 | 30,664 | 14,671 | 15,993 | -1 | -1 |
module Propellor.Property.DnsSec where
import Propellor.Base
import qualified Propellor.Property.File as File
-- | Puts the DNSSEC key files in place from PrivData.
--
-- signedPrimary uses this, so this property does not normally need to be
-- used directly.
keysInstalled :: Domain -> RevertableProperty HasInfo
keysInstalled domain = setup <!> cleanup
where
setup = propertyList "DNSSEC keys installed" $
map installkey keys
cleanup = propertyList "DNSSEC keys removed" $
map (File.notPresent . keyFn domain) keys
installkey k = writer (keysrc k) (keyFn domain k) (Context domain)
where
writer
| isPublic k = File.hasPrivContentExposedFrom
| otherwise = File.hasPrivContentFrom
keys = [ PubZSK, PrivZSK, PubKSK, PrivKSK ]
keysrc k = PrivDataSource (DnsSec k) $ unwords
[ "The file with extension"
, keyExt k
, "created by running:"
, if isZoneSigningKey k
then "dnssec-keygen -a RSASHA256 -b 2048 -n ZONE " ++ domain
else "dnssec-keygen -f KSK -a RSASHA256 -b 4096 -n ZONE " ++ domain
]
-- | Uses dnssec-signzone to sign a domain's zone file.
--
-- signedPrimary uses this, so this property does not normally need to be
-- used directly.
zoneSigned :: Domain -> FilePath -> RevertableProperty HasInfo
zoneSigned domain zonefile = setup <!> cleanup
where
setup = check needupdate (forceZoneSigned domain zonefile)
`requires` keysInstalled domain
cleanup = File.notPresent (signedZoneFile zonefile)
`before` File.notPresent dssetfile
`before` revert (keysInstalled domain)
dssetfile = dir </> "-" ++ domain ++ "."
dir = takeDirectory zonefile
-- Need to update the signed zone file if the zone file or
-- any of the keys have a newer timestamp.
needupdate = do
v <- catchMaybeIO $ getModificationTime (signedZoneFile zonefile)
case v of
Nothing -> return True
Just t1 -> anyM (newerthan t1) $
zonefile : map (keyFn domain) [minBound..maxBound]
newerthan t1 f = do
t2 <- getModificationTime f
return (t2 >= t1)
forceZoneSigned :: Domain -> FilePath -> Property NoInfo
forceZoneSigned domain zonefile = property ("zone signed for " ++ domain) $ liftIO $ do
salt <- take 16 <$> saltSha1
let p = proc "dnssec-signzone"
[ "-A"
, "-3", salt
-- The serial number needs to be increased each time the
-- zone is resigned, even if there are no other changes,
-- so that it will propagate to secondaries. So, use the
-- unixtime serial format.
, "-N", "unixtime"
, "-o", domain
, zonefile
-- the ordering of these key files does not matter
, keyFn domain PubZSK
, keyFn domain PubKSK
]
-- Run in the same directory as the zonefile, so it will
-- write the dsset file there.
(_, _, _, h) <- createProcess $
p { cwd = Just (takeDirectory zonefile) }
ifM (checkSuccessProcess h)
( return MadeChange
, return FailedChange
)
saltSha1 :: IO String
saltSha1 = readProcess "sh"
[ "-c"
, "head -c 1024 /dev/urandom | sha1sum | cut -d ' ' -f 1"
]
-- | The file used for a given key.
keyFn :: Domain -> DnsSecKey -> FilePath
keyFn domain k = "/etc/bind/propellor/dnssec" </> concat
[ "K" ++ domain ++ "."
, if isZoneSigningKey k then "ZSK" else "KSK"
, keyExt k
]
-- | These are the extensions that dnssec-keygen looks for.
keyExt :: DnsSecKey -> String
keyExt k
| isPublic k = ".key"
| otherwise = ".private"
isPublic :: DnsSecKey -> Bool
isPublic k = k `elem` [PubZSK, PubKSK]
isZoneSigningKey :: DnsSecKey -> Bool
isZoneSigningKey k = k `elem` [PubZSK, PrivZSK]
-- | dnssec-signzone makes a .signed file
signedZoneFile :: FilePath -> FilePath
signedZoneFile zonefile = zonefile ++ ".signed"
| np/propellor | src/Propellor/Property/DnsSec.hs | bsd-2-clause | 3,620 | 83 | 16 | 723 | 916 | 486 | 430 | 74 | 2 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett and Dan Doel 2012-2014
-- License : BSD3
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
-- General-purpose utilities for pretty printing.
--------------------------------------------------------------------
module Ermine.Pretty
( module Text.PrettyPrint.ANSI.Leijen
, names
, parensIf
, hyph
, prePunctuate
, prePunctuate'
, block
, say
, sayLn
, chooseNames
) where
import Control.Applicative
import Control.Monad.IO.Class
import Control.Lens
import Data.Bifunctor
import Data.Maybe
import Data.Semigroup
import Data.Text (unpack)
import Ermine.Syntax.Hint
import Numeric.Lens
import System.IO
import Text.Hyphenation
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (<>))
import Text.Trifecta.Delta () -- for Text.Trifecta.Instances
-- | This is an infinitely large free variable supply you can trim your used variables out of.
names :: [String]
names = map pure az
++ [ i : review (base 36) j | j <- [1..], i <- az ] where
az = ['a'..'z']
-- | Pretty print parentheses
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
-- | Hyphenate a word using standard TeX-style 'english_US' hyphenation.
hyph :: String -> Doc
hyph t = column $ \k -> columns $ \mn ->
let n = fromMaybe 80 mn
(pr,sf) = bimap (fmap fst) (fmap fst) $ span (\ (_,d) -> k + d < n) $ zip xs ls
ls = tail $ scanl (\a b -> a + length b) 0 xs
xs = hyphenate english_US t
in if null pr
then text (concat sf)
else if null sf
then text (concat pr)
else vsep [text (concat pr) <> char '-', text (concat sf)]
prePunctuate :: Doc -> [Doc] -> [Doc]
prePunctuate _ [ ] = []
prePunctuate p (d:ds) = d : map (p <+>) ds
prePunctuate' :: Doc -> Doc -> [Doc] -> [Doc]
prePunctuate' _ _ [ ] = []
prePunctuate' fp p (d:ds) = (fp <+> d) : map (p <+>) ds
-- | Format a layout block in explicit style.
block :: [Doc] -> Doc
block [ ] = text "{}"
block (d:ds) = sep (lbrace <+> d : map (semi <+>) ds) <> line <> rbrace
-- | Pretty print to 'stdout'
say :: MonadIO m => Doc -> m ()
say = liftIO . displayIO stdout . renderPretty 0.8 80
-- | Pretty print to 'stdout' with a 'linebreak' after.
sayLn :: MonadIO m => Doc -> m ()
sayLn d = say (d <> linebreak)
chooseNames :: (String -> Bool) -> [Hinted v] -> [String] -> ([String], [String])
chooseNames p ahs = go p ahs . filter (\n -> n `notElem` avoid && not (p n))
where
avoid = [ unpack h | Hinted h _ <- ahs ]
go _ [] supply = ([], supply)
go taken (Unhinted _ : hs) (n:supply) = (n:) `first` go taken hs supply
go taken (Hinted h _ : hs) supply@(n:ns)
| taken h' = (n:) `first` go taken hs ns
| otherwise = (h':) `first` go (\x -> x == h' || taken x) hs supply
where h' = unpack h
go _ _ _ = error "PANIC: chooseNames: ran out of names"
| ekmett/ermine | src/Ermine/Pretty.hs | bsd-2-clause | 2,999 | 0 | 19 | 647 | 1,099 | 599 | 500 | 66 | 4 |
{-|
Module : Network.NSFW.Firewall.Packet
Description : Defines the Packet data type.
-}
module Network.NSFW.Firewall.Packet
( IpAddress
, Protocol
, Packet(..)
) where
import Data.Int (Int8, Int16)
type IpAddress = String
type Protocol = String
data Packet = Packet {
getProtocol :: Protocol,
getTtl :: Int8,
getSourceIpAddress :: IpAddress,
getSourcePort :: Int16,
getDestinationIpAddress :: IpAddress,
getDestinationPort :: Int16,
getDestinationService :: String
} deriving (Eq, Read, Show)
| m-renaud/NSFW | src/Network/NSFW/Firewall/Packet.hs | bsd-2-clause | 597 | 0 | 8 | 168 | 115 | 74 | 41 | 16 | 0 |
-- %%%%%%%%%%%%%%%%%%%%%%%%%%
-- WARNING
-- File not actually used in drasil.cabal for GamePhysics
-- so it is not actually 'plugged in'. The definitions in here
-- may not type check anymore!
-- %%%%%%%%%%%%%%%%%%%%%%%%%%
module Drasil.GamePhysics.GDefs (genDefs) where
import Language.Drasil
import Utils.Drasil
import Data.Drasil.Concepts.Physics (rigidBody)
import Data.Drasil.Quantities.PhysicalProperties (mass)
----- General Models -----
genDefs :: [RelationConcept]
--genDefs = []
impulseGDef :: RelationConcept
impulseGDef = makeRC "impulse" (nounPhraseSP "Impulse")
impulseDesc impulseRel
impulseRel :: Relation
impulseRel = C impulseS := Integral C force -- replace with proper Expr
impulseDesc :: Sentence
impulseDesc = foldlSent [S "An", phrase impulseS, getS impulseS,
S "occurs when a", phrase force, getS force,
S "acts over an interval of", phrase time]
--[impulseS, force, changeInMomentum, mass, changeInVelocity]
impulseDeriv :: Sentence
impulseDeriv = foldlSent [S "Newton's second law of motion (ref to T1)",
S "states" +: S "(expr1)",
S "rearranging" +: S "(expr2)",
S "Integrating the right side" +: S "(expr3)"
]
conservationOfMomentGDef :: RelationConcept
conservationOfMomentGDef = makeRC "conservOfMoment" (nounPhraseSP "Conservation of Momentum")
conservationOfMomentDesc conservationOfMomentRel
conservationOfMomentRel :: Relation
conservationOfMomentRel = UnaryOp $ Summation Nothing
C massI
conservationOfMomentDesc :: Sentence
conservationOfMomentDesc = foldlSent [S "In an isolated system,",
S "where the sum of external", phrase impulseS, S "acting on the system is zero,",
S "the total momentum of the bodies is constant (conserved)"
]
--[mass, initialVelocity, finalVelocity]
conservationOfMomentDeriv :: Sentence
conservationOfMomentDeriv = foldlSent [S "When bodies collide, they exert",
S "an equal (force) on each other in opposite directions" +:+.
S "This is Newton's third law:",
S "(expr1)",
S "The objects collide with each other for the exact same amount of",
phrase time, getS time,
S "The above equation is equal to the", phrase impulseS,
S "(GD1 ref)",
S "(expr2)",
S "The", phrase impulseS, S "is equal to the change in momentum:",
S "(expr3)",
S "Substituting 2*ref to 2* into 1*ref to 1* yields:",
S "(expr4)",
S "Expanding and rearranging the above formula gives",
S "(expr5)",
S "Generalizing for multiple (k) colliding objects:",
S "(expr6)"
]
accelerationDueToGravityGDef :: RelationConcept
accelerationDueToGravityGDef = makeRC "accelDueToGrav"
(nounPhraseSP "Acceleration due to gravity")
accelerationDueToGravityDesc accelerationDueToGravityRel
accelerationDueToGravityRel :: Relation
accelerationDueToGravityRel = FCall (C thFluxVect) [C QP.time] := C htTransCoeff :*
FCall (C temp_diff) [C QP.time] -- replace with proper Expr
accelerationDueToGravityDesc :: Sentence
accelerationDueToGravityDesc = foldlSent [S ""]
-- [gravitationalAccel, mass, gravitationalConst]
accelerationDueToGravityDeriv :: Sentence
accelerationDueToGravityDeriv = foldlSent [S "From Newton's law of universal",
S "gravitation (T3 ref), we have:",
S "(expr1)",
S "Equation 3 **ref to 3** governs the gravitational attraction between two",
S "bodies. Suppose that one of the bodies is significantly more massive than",
S "other, so that we concern ourselves with the force the massive body exerts",
S "on the lighter body" +:+. S "Further suppose that the coordinate system is",
S "chosen such that this force acts on a line which lies along one of the",
S "principle axes (A2 ref)" +:+. S "Then our unit vector", S "(expr2)", S "for",
S "the x or y axes (A3 ref), respectively"
S "Given the above assumptions, let M and m be the", phrase mass,
S "of the massive and",
S "light body, respectively" +:+. S "Using 3 **ref to 3** and equating this",
S "with Newton's second law (T1 ref) for the force experienced by the light",
S "body, we get:",
S "(expr3)",
S "where", getS gravitationalConst, S "is", phrase gravitationalAccel,
S "Dividing 4 **ref to 4**",
S "by m, and resolving this into separate x and y components:",
S "(expr4)",
S "(expr5)",
S "Thus:",
S "(expr6)"
]
relativeVelocityInCollisionsGDef :: RelationConcept
relativeVelocityInCollisionsGDef = makeRC "relVeloInColl"
(nounPhraseSP "Relative velocity in collision")
relativeVelocityInCollisionsDesc relativeVelocityInCollisionsRel
relativeVelocityInCollisionsDesc :: Sentence
relativeVelocityInCollisionsDesc = foldlSent [S "In a collision, the",
phrase velocity, S "of", S "rigid body A",
S "colliding with another body B relative to that",
S "body, (symbol vAB), is the difference between the", plural velocity,
S "of A", S "and B at point P"
]
--[velocityAB, collisionPoint, velocityAP, velocityBP]
relativeVelocityInCollisionsRel :: Relation
relativeVelocityInCollisionsRel = FCall (C thFluxVect) [C QP.time] := C htTransCoeff :*
FCall (C temp_diff) [C QP.time] -- replace with proper Expr
coefficientOfRestitutionGDef :: RelationConcept
coefficientOfRestitutionGDef = makeRC "coeffOfRest"
(nounPhraseSP "Coefficient of restitution")
coefficientOfRestitutionDesc coefficientOfRestitutionRel
coefficientOfRestitutionDesc :: Sentence
coefficientOfRestitutionDesc = foldlSent [S "The", phrase restitutionCoef,
getS restitutionCoef, S "is",
S "a unitless, dimensionless quantity that determines the elasticity of a",
S "collision between two bodies. (symbol/expr)[CR = 1] results in an elastic",
S "collision, while (symbol/expr)[CR < 1] results in an inelastic collision,",
S "and (symbol/expr)[CR = 0] results in a totally inelastic collision"
]
--[restitutionCoef, normCollisionVect, initRelativeVelocityAB, finalRelativeVelocityAB]
coefficientOfRestitutionRel :: Relation
coefficientOfRestitutionRel = FCall (C thFluxVect) [C QP.time] := C htTransCoeff :*
FCall (C temp_diff) [C QP.time] -- replace with proper Expr
torqueGDef :: RelationConcept
torqueGDef = makeRC "torque"
(nounPhraseSP "Torque")
torqueDesc torqueRel
torqueDesc :: Sentence
torqueDesc = foldlSent [S "The", phrase torque, getS torque,
S "on a body measures the", S "the tendency of a", phrase force,
S "to rotate the body around an axis or pivot"
]
--[torque, force, position]
torqueRel :: Relation
torqueRel = FCall (C thFluxVect) [C QP.time] := C htTransCoeff :*
FCall (C temp_diff) [C QP.time] -- replace with proper Expr
momentOfInertiaGDef :: RelationConcept
momentOfInertiaGDef = makeRC "momentOfInertia"
(nounPhraseSP "Moment of Inertia")
momentOfInertiaDesc momentOfInertiaRel
momentOfInertiaDesc :: Sentence
momentOfInertiaDesc = foldlSent []
--[momentOfInertia, numOfParticles, massI, distanceBtwParticleI]
momentOfInertiaRel :: Relation
momentOfInertiaRel = FCall (C thFluxVect) [C QP.time] := C htTransCoeff :*
FCall (C temp_diff) [C QP.time] -- replace with proper Expr
| JacquesCarette/literate-scientific-software | code/drasil-example/Drasil/GamePhysics/GDef.hs | bsd-2-clause | 6,973 | 0 | 10 | 1,106 | 1,313 | 678 | 635 | 128 | 1 |
module Pokemon.Experience where
data ExpCurve = Slow | MediumSlow | Medium | Fast
deriving (Eq, Show, Ord)
lowestExpForLevel :: ExpCurve -> Integer -> Integer
lowestExpForLevel curve n =
case curve of
Slow -> 5 * n^3 `div` 4
MediumSlow -> 6 * n^3 `div` 5 - 15 * n^2 + 100 * n - 140
Medium -> n^3
Fast -> 4 * n^3 `div` 5
| bhamrick/RouteNeo | Pokemon/Experience.hs | bsd-3-clause | 362 | 0 | 16 | 107 | 158 | 86 | 72 | 10 | 4 |
{-# LANGUAGE TypeFamilies #-}
module EFA.Test.Arithmetic where
import qualified EFA.Equation.Arithmetic as Arith
import EFA.Equation.Arithmetic
(Sum, (~+), (~-),
Product, (~*), (~/),
Constant, zero,
Integrate, Scalar, integrate)
import Control.Applicative (Applicative, pure, (<*>), liftA2, liftA3)
import qualified Test.QuickCheck as QC
data Triple a = Triple a a a
deriving (Show, Eq)
instance Functor Triple where
fmap f (Triple x y z) = Triple (f x) (f y) (f z)
instance Applicative Triple where
pure x = Triple x x x
(Triple fx fy fz) <*> (Triple x y z) =
Triple (fx x) (fy y) (fz z)
instance (Sum a) => Sum (Triple a) where
(~+) = liftA2 (~+)
(~-) = liftA2 (~-)
negate = fmap Arith.negate
instance (Product a) => Product (Triple a) where
(~*) = liftA2 (~*)
(~/) = liftA2 (~/)
recip = fmap Arith.recip
constOne = fmap Arith.constOne
instance (Constant a) => Constant (Triple a) where
zero = pure zero
fromInteger = pure . Arith.fromInteger
fromRational = pure . Arith.fromRational
instance (Sum a) => Integrate (Triple a) where
type Scalar (Triple a) = a
integrate (Triple x y z) = x ~+ y ~+ z
instance QC.Arbitrary a => QC.Arbitrary (Triple a) where
arbitrary = liftA3 Triple QC.arbitrary QC.arbitrary QC.arbitrary
| energyflowanalysis/efa-2.1 | test/EFA/Test/Arithmetic.hs | bsd-3-clause | 1,336 | 0 | 8 | 315 | 541 | 302 | 239 | 36 | 0 |
module Main where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (poll)
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Monad (forever, forM_)
import Data.Monoid ((<>))
import Data.Set (fromList, toList)
import Data.Oddjob.Worker
lockedPutStrLn :: MVar () -> String -> IO ()
lockedPutStrLn lock str =
withMVar lock (\_ -> putStrLn str)
worker :: MVar () -> Integer -> IO ()
worker lock job = do
lockedPutStrLn lock ("Starting job: " <> show job)
forever $ do
lockedPutStrLn lock ("Worker: " <> show job)
threadDelay halfSecond
halfSecond :: Int
halfSecond = 500000
oneSecond :: Int
oneSecond = 1000000
main :: IO ()
main = do
lock <- newMVar ()
service <- startWorkerService (worker lock) (Just print)
let jobsOverTime = map fromList [ [1..2]
, [1..3]
, [2..3]
, [1..4]
, [1..5]
, [2..5]
, [1..6]
]
forM_ jobsOverTime $ \j -> do
lockedPutStrLn lock ("Settings new jobs: " <> show (toList j))
setJobs service j
threadDelay oneSecond
threadDelay (2 * oneSecond)
getState service >>= print
poll (_asyncHandle service) >>= print
| helium/oddjob | app/Main.hs | bsd-3-clause | 1,413 | 0 | 16 | 503 | 450 | 233 | 217 | 39 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-unused-binds #-}
module Ling.Layout where
import Ling.Lex
import Data.Maybe (isNothing, fromJust)
-- Generated by the BNF Converter
-- local parameters
topLayout :: Bool
topLayout = True
layoutWords, layoutStopWords :: [String]
layoutWords = ["of"]
layoutStopWords = []
-- layout separators
layoutOpen, layoutClose, layoutSep :: String
layoutOpen = "{"
layoutClose = "}"
layoutSep = ","
-- | Replace layout syntax with explicit layout tokens.
resolveLayout :: Bool -- ^ Whether to use top-level layout.
-> [Token] -> [Token]
resolveLayout tp = res Nothing [if tl then Implicit 1 else Explicit]
where
-- Do top-level layout if the function parameter and the grammar say so.
tl = tp && topLayout
res :: Maybe Token -- ^ The previous token, if any.
-> [Block] -- ^ A stack of layout blocks.
-> [Token] -> [Token]
-- The stack should never be empty.
res _ [] ts = error $ "Layout error: stack empty. Tokens: " ++ show ts
res _ st (t0:ts)
-- We found an open brace in the input,
-- put an explicit layout block on the stack.
-- This is done even if there was no layout word,
-- to keep opening and closing braces.
| isLayoutOpen t0 = moveAlong (Explicit:st) [t0] ts
-- We are in an implicit layout block
res pt st@(Implicit n:ns) (t0:ts)
-- End of implicit block by a layout stop word
| isStop t0 =
-- Exit the current block and all implicit blocks
-- more indented than the current token
let (ebs,ns') = span (`moreIndent` column t0) ns
moreIndent (Implicit x) y = x > y
moreIndent Explicit _ = False
-- the number of blocks exited
b = 1 + length ebs
bs = replicate b layoutClose
-- Insert closing braces after the previous token.
(ts1,ts2) = splitAt (1+b) $ addTokens (afterPrev pt) bs (t0:ts)
in moveAlong ns' ts1 ts2
-- End of an implicit layout block
| newLine pt t0 && column t0 < n =
-- Insert a closing brace after the previous token.
let b:t0':ts' = addToken (afterPrev pt) layoutClose (t0:ts)
-- Repeat, with the current block removed from the stack
in moveAlong ns [b] (t0':ts')
res pt st (t0:ts)
-- Start a new layout block if the first token is a layout word
| isLayout t0 =
case ts of
-- Explicit layout, just move on. The case above
-- will push an explicit layout block.
t1:_ | isLayoutOpen t1 -> moveAlong st [t0] ts
-- at end of file, the start column doesn't matter
_ -> let col = if null ts then column t0 else column (head ts)
-- insert an open brace after the layout word
b:ts' = addToken (nextPos t0) layoutOpen ts
-- save the start column
st' = Implicit col:st
in -- Do we have to insert an extra layoutSep?
case st of
Implicit n:_
| newLine pt t0 && column t0 == n
&& not (isNothing pt ||
isTokenIn [layoutSep,layoutOpen] (fromJust pt)) ->
let b':t0':b'':ts'' =
addToken (afterPrev pt) layoutSep (t0:b:ts')
in moveAlong st' [b',t0',b''] ts'
_ -> moveAlong st' [t0,b] ts'
-- If we encounter a closing brace, exit the first explicit layout block.
| isLayoutClose t0 =
let st' = drop 1 (dropWhile isImplicit st)
in if null st'
then error $ "Layout error: Found " ++ layoutClose ++ " at ("
++ show (line t0) ++ "," ++ show (column t0)
++ ") without an explicit layout block."
else moveAlong st' [t0] ts
-- Insert separator if necessary.
res pt st@(Implicit n:ns) (t0:ts)
-- Encounted a new line in an implicit layout block.
| newLine pt t0 && column t0 == n =
-- Insert a semicolon after the previous token.
-- unless we are the beginning of the file,
-- or the previous token is a semicolon or open brace.
if isNothing pt || isTokenIn [layoutSep,layoutOpen] (fromJust pt)
then moveAlong st [t0] ts
else let b:t0':ts' = addToken (afterPrev pt) layoutSep (t0:ts)
in moveAlong st [b,t0'] ts'
-- Nothing to see here, move along.
res _ st (t:ts) = moveAlong st [t] ts
-- At EOF: skip explicit blocks.
res (Just t) (Explicit:bs) [] | null bs = []
| otherwise = res (Just t) bs []
-- If we are using top-level layout, insert a semicolon after
-- the last token, if there isn't one already
res (Just t) [Implicit _n] []
| isTokenIn [layoutSep] t = []
| otherwise = addToken (nextPos t) layoutSep []
-- At EOF in an implicit, non-top-level block: close the block
res (Just t) (Implicit _n:bs) [] =
let c = addToken (nextPos t) layoutClose []
in moveAlong bs c []
-- This should only happen if the input is empty.
res Nothing _st [] = []
-- | Move on to the next token.
moveAlong :: [Block] -- ^ The layout stack.
-> [Token] -- ^ Any tokens just processed.
-> [Token] -- ^ the rest of the tokens.
-> [Token]
moveAlong _ [] _ = error $ "Layout error: moveAlong got [] as old tokens"
moveAlong st ot ts = ot ++ res (Just $ last ot) st ts
newLine :: Maybe Token -> Token -> Bool
newLine pt t0 = case pt of
Nothing -> True
Just t -> line t /= line t0
data Block = Implicit Int -- ^ An implicit layout block with its start column.
| Explicit
deriving Show
type Position = Posn
-- | Check if s block is implicit.
isImplicit :: Block -> Bool
isImplicit (Implicit _) = True
isImplicit _ = False
-- | Insert a number of tokens at the begninning of a list of tokens.
addTokens :: Position -- ^ Position of the first new token.
-> [String] -- ^ Token symbols.
-> [Token] -- ^ The rest of the tokens. These will have their
-- positions updated to make room for the new tokens .
-> [Token]
addTokens p ss ts = foldr (addToken p) ts ss
-- | Insert a new symbol token at the begninning of a list of tokens.
addToken :: Position -- ^ Position of the new token.
-> String -- ^ Symbol in the new token.
-> [Token] -- ^ The rest of the tokens. These will have their
-- positions updated to make room for the new token.
-> [Token]
addToken p s ts = sToken p s : map (incrGlobal p (length s)) ts
-- | Get the position immediately to the right of the given token.
-- If no token is given, gets the first position in the file.
afterPrev :: Maybe Token -> Position
afterPrev = maybe (Pn 0 1 1) nextPos
-- | Get the position immediately to the right of the given token.
nextPos :: Token -> Position
nextPos t = Pn (g + s) l (c + s + 1)
where Pn g l c = position t
s = tokenLength t
-- | Add to the global and column positions of a token.
-- The column position is only changed if the token is on
-- the same line as the given position.
incrGlobal :: Position -- ^ If the token is on the same line
-- as this position, update the column position.
-> Int -- ^ Number of characters to add to the position.
-> Token -> Token
incrGlobal (Pn _ l0 _) i (PT (Pn g l c) t) =
if l /= l0 then PT (Pn (g + i) l c) t
else PT (Pn (g + i) l (c + i)) t
incrGlobal _ _ p = error $ "cannot add token at " ++ show p
-- | Create a symbol token.
sToken :: Position -> String -> Token
sToken p s = PT p (TS s i)
where
i = case s of
"!" -> 1
"(" -> 2
")" -> 3
"**" -> 4
"," -> 5
"->" -> 6
"-o" -> 7
"." -> 8
":" -> 9
":*" -> 10
":]" -> 11
";" -> 12
"<" -> 13
"<-" -> 14
"<=" -> 15
"=" -> 16
">" -> 17
"?" -> 18
"@" -> 19
"Type" -> 20
"[" -> 21
"[:" -> 22
"\\" -> 23
"]" -> 24
"^" -> 25
"`" -> 26
"as" -> 27
"assert" -> 28
"case" -> 29
"data" -> 30
"end" -> 31
"fwd" -> 32
"in" -> 33
"let" -> 34
"new" -> 35
"new/" -> 36
"of" -> 37
"parallel" -> 38
"proc" -> 39
"recv" -> 40
"send" -> 41
"sequence" -> 42
"split" -> 43
"with" -> 44
"{" -> 45
"|" -> 46
"}" -> 47
"~" -> 48
_ -> error $ "not a reserved word: " ++ show s
-- | Get the position of a token.
position :: Token -> Position
position t = case t of
PT p _ -> p
Err p -> p
-- | Get the line number of a token.
line :: Token -> Int
line t = case position t of Pn _ l _ -> l
-- | Get the column number of a token.
column :: Token -> Int
column t = case position t of Pn _ _ c -> c
-- | Check if a token is one of the given symbols.
isTokenIn :: [String] -> Token -> Bool
isTokenIn ts t = case t of
PT _ (TS r _) | elem r ts -> True
_ -> False
-- | Check if a word is a layout start token.
isLayout :: Token -> Bool
isLayout = isTokenIn layoutWords
-- | Check if a token is a layout stop token.
isStop :: Token -> Bool
isStop = isTokenIn layoutStopWords
-- | Check if a token is the layout open token.
isLayoutOpen :: Token -> Bool
isLayoutOpen = isTokenIn [layoutOpen]
-- | Check if a token is the layout close token.
isLayoutClose :: Token -> Bool
isLayoutClose = isTokenIn [layoutClose]
-- | Get the number of characters in the token.
tokenLength :: Token -> Int
tokenLength t = length $ prToken t
| np/ling | Ling/Layout.hs | bsd-3-clause | 9,793 | 0 | 25 | 3,206 | 2,533 | 1,312 | 1,221 | 188 | 49 |
{-# Language RecordWildCards, GADTs, TupleSections, MultiParamTypeClasses #-}
module Analysis.Types.Annotation where
import qualified Analysis.Types.Sorts as S
import qualified Data.Set as D
import Analysis.Common
import qualified Data.Map as M
import Data.Maybe
import Control.Monad.Identity
import Control.Monad.State
import qualified Analysis.Types.Common as C
import Control.Applicative
data Annotation =
Var Int
| App Annotation Annotation
| Union Annotation Annotation
| Abs S.FlowVariable Annotation
| Label String
| Empty
| Set (D.Set Annotation)
-- Apparently the GHC derived Eq and Ord work well enough
-- such that normalizing equivalent terms will reduce
-- in equal terms
-- For that property to hold, elements that have equal
-- structure up to alpha renameing should be considered
-- adjecent to the other acording to the Ord instance
deriving (Show,Read,Eq,Ord)
instance C.Fold Annotation Algebra where
foldM = foldAnnM
byId = annById
baseAlgebra = algebra
groupAlgebra =
Algebra{
fvar = \_ _ -> return C.void,
fabs = \_ _ s -> return s,
fapp = \_ s1 s2 -> return $ s1 C.<+> s2,
flabel = \_ _ -> return C.void,
funion = \_ a b -> return $ a C.<+> b,
fempty = const $ return C.void
}
instance C.WithAbstraction Annotation Algebra where
abst (Abs v e) = Just (v,e)
abst _ = Nothing
abstC = Abs
increment = increment
baseAbstAlgebra alg abst = alg{fabs=abst}
groupAbstAlgebra alg abst = alg{fabs=abst}
vars = vars
lambdaDepths = depths
instance C.LambdaCalculus Annotation Algebra where
app (App a1 a2) = Just (a1,a2)
app _ = Nothing
appC = App
var (Var i) = Just i
var _ = Nothing
varC = Var
baseCalcAlgebra alg var app =
alg{fvar=var,fapp=app}
groupCalcAlgebra alg var app = alg{fvar=var,fapp=app}
instance C.WithSets Annotation Algebra where
unionM (Union a1 a2) = Just (a1,a2)
unionM _ = Nothing
unionC = Union
setM (Set a) = Just a
setM _ = Nothing
setC = Set
emptyM Empty = Just ()
emptyM _ = Nothing
emptyC = Empty
unionAlgebra alg un empty = alg{funion=un,fempty=empty}
data Algebra m t a =
Algebra {
fvar :: Int -> Int -> m a,
fabs :: Int -> S.FlowVariable -> a -> m a,
flabel :: Int -> String -> m a,
funion :: Int -> a -> a -> m a,
fapp :: Int -> a -> a -> m a,
fempty :: Int -> m a
}
maxIx ann = maximum $ D.toList $ D.map fst $ vars ann
data ReduceContext = ReduceContext{
freshIx :: Int
}
algebra :: Monad m => Algebra m Annotation Annotation
algebra = Algebra{
fvar = \_ x -> return $ Var x,
fabs = \_ v s -> return $ Abs v s,
flabel = \_ l -> return $ Label l,
funion = \_ a b -> return $ Union a b,
fapp = \_ a b -> return $ App a b,
fempty = const (return Empty)
}
fresh :: Monad m => StateT ReduceContext m Int
fresh = do
ctx <- get
put $ ctx{freshIx = freshIx ctx + 1}
return $ freshIx ctx
foldAnnM f@Algebra{..} a0 = evalStateT (foldAnnM' undefined a0) 0
where
foldAnnM' s a = do
i <- get
put (i+1)
let
go fn a1 a2 = do
a1' <- (foldAnnM' s a1)
a2' <- (foldAnnM' s a2)
lift $ fn i a1' a2'
case a of
App a1 a2 -> go fapp a1 a2
Union a1 a2 -> go funion a1 a2
-- Sets are treated as if they were unions
Set as -> foldAnnM' s $ C.setFold as
Var v -> lift $ fvar i v
Abs v a1 -> (foldAnnM' s a1) >>= (lift . (fabs i v))
Label l -> lift $ flabel i l
Empty -> lift $ fempty i
depths = runIdentity . (foldAnnM alg)
where
alg = Algebra {
fapp = un,
funion = un,
fabs = \i _ m -> return $ M.insert i 0 $ M.map (+1) m,
flabel = sing,
fvar = sing,
fempty = const (return M.empty)
}
sing i _ = return $ M.insert i 0 M.empty
un i ma mb = return $ M.insert i 0 $ M.union ma mb
vars :: Annotation -> D.Set (Int, C.Boundness)
vars = runIdentity . C.foldM alg
where
-- alg :: Monad m => Algebra (StateT (D.Set (Int,C.Boundness)) m) Annotation (D.Set (Int,C.Boundness))
alg = C.baseVarsAlg
renameByLambdasOffset base offset obj = calcReplacements >>= mkReplacements
where
calcReplacements =
M.map (M.map fst) <$> foldAnnM (C.baseRepAlg base offset obj :: Algebra Identity Annotation (M.Map Int (M.Map Int (Int,Bool)))) obj
mkReplacements rep = foldAnnM (C.baseSubAlg rep) obj
renameByLambdas :: Annotation -> Annotation
renameByLambdas obj = runIdentity $ renameByLambdasOffset M.empty 0 obj
subAppAnn cons obj rep i s ann = do
let offset' = fromJust $ M.lookup i $ C.lambdaDepths obj
ann' <- renameByLambdasOffset (fromJust $ M.lookup i rep) offset' ann
return $ cons s ann'
rename ren = runIdentity . (foldAnnM alg)
where
alg = algebra{
fvar = const fvar,
fabs = const fabs
}
fvar v = return $ Var $ M.findWithDefault v v ren
fabs v s = return $ Abs v{S.name=M.findWithDefault (S.name v) (S.name v) ren} s
replaceFree rep ann = runIdentity $ foldAnnM alg ann
where
alg = C.baseReplaceAlg rep ann
-- Increase or decrease the `depth` of all bound variables in the expression
incrementWithBase base i ann = runIdentity $ foldAnnM alg ann
where
alg = C.baseIncAlg i $ D.map fst $ D.filter C.bound $ D.union base $ vars ann
increment = incrementWithBase D.empty
application fun@(Abs _ a1) a2 = increment (-1) $ runIdentity $ C.foldM (C.baseAppAlg fun a2) a1
application a1 a2 = App a1 a2
reduce' = runIdentity . (foldAnnM alg >=> foldAnnM C.baseRedUnionAlg)
where
alg = algebra{
fapp = \i a1 a2 -> return $ application a1 a2
}
reduce e = go e (reduce' e)
where
go x x'
| x == x' = x
| otherwise = go x' (reduce x')
unionGen empty singleton unions e =
case e of
Empty -> empty
Union a1 a2 -> unions [(union' a1),(union' a2)]
a -> singleton a
where
union' = unionGen empty singleton unions
union = unionGen D.empty D.singleton D.unions
unions e =
case e of
Union a1 a2 -> Set $ D.map unions (union e)
App a1 a2 -> App (unions a1) (unions a2)
Abs v a -> Abs v $ unions a
Var v -> Var v
Label s -> Set (D.singleton $ Label s)
Empty -> Set (D.empty)
a -> a
normalize :: Annotation -> Annotation
normalize ann =
-- The second `renameByLambdas` is there only to ensure that all
-- terms are equal to alpha renaming of the free variables
C.unions $ reduce $ renameByLambdas ann
annById i ann = execState (foldAnnM alg ann) Nothing
where
labelF i' l = do
unless (i /= i') $ put $ Just $ Label l
return $ Label l
alg = (C.byIdSetAlgebra i){flabel=labelF}
isConstant = runIdentity . (foldAnnM alg)
where
alg = Algebra{
fvar = \_ _ -> return False,
fabs = \_ _ s -> return s,
fapp = \_ s1 s2 -> return $ s1 && s2,
flabel = \_ _ -> return True,
funion = \_ a b -> return $ a && b,
fempty = const $ return True
}
| netogallo/polyvariant | src/Analysis/Types/Annotation.hs | bsd-3-clause | 6,992 | 0 | 16 | 1,875 | 2,691 | 1,390 | 1,301 | 178 | 7 |
{-# LANGUAGE UndecidableInstances, MultiParamTypeClasses #-}
-- Copyright (c) 2012 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS''
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
-- | This module provides a monad class representing a simple symbol
-- table interface.
module Control.Monad.Symtab.Class(
MonadSymtab(..),
) where
import Data.Symbol
import Prelude(Maybe, Monad)
-- | This class represents a simple symbol table interface.
class Monad m => MonadSymtab a m where
-- | Insert a symbol into the table
insert :: Symbol -> a -> m (Maybe a)
-- | Look up a symbol
lookup :: Symbol -> m (Maybe a)
-- | List all symbols
list :: m [(Symbol,a)]
| emc2/proglang-util | Control/Monad/Symtab/Class.hs | bsd-3-clause | 2,105 | 0 | 11 | 380 | 142 | 94 | 48 | 9 | 0 |
{-# LANGUAGE PatternGuards, RecordWildCards #-}
module Website where
import Data.Char (toLower)
import Data.Function (on)
import Data.List (find, groupBy, nub, sort)
import Data.Version (showVersion, versionBranch)
import Development.Shake
import Text.Hastache
import Text.Hastache.Context
import Dirs
import Paths
import PlatformDB
import Releases
import ReleaseFiles
import Templates
import Types
websiteRules :: FilePath -> Rules ()
websiteRules templateSite = do
websiteDir %/> \dst -> do
bcCtx <- buildConfigContext
let rlsCtx = releasesCtx
ctx = ctxConcat [rlsCtx, historyCtx, bcCtx, errorCtx]
copyExpandedDir ctx templateSite dst
fileCtx :: (Monad m) => FileInfo -> MuContext m
fileCtx (dist, url, mHash) = mkStrContext ctx
where
ctx "osNameAndArch" = MuVariable $ distName dist
ctx "url" = MuVariable url
ctx "mHash" = maybe (MuBool False) MuVariable mHash
ctx "archBits"
| DistBinary _ arch <- dist = MuVariable $ archBits arch
| otherwise = MuNothing
ctx "isOSX" = MuBool $ distIsFor OsOSX dist
ctx "isWindows" = MuBool $ distIsFor OsWindows dist
ctx "isLinux" = MuBool $ distIsFor OsLinux dist
ctx "isSource" = MuBool $ dist == DistSource
ctx _ = MuNothing
releaseCtx :: (Monad m) => ReleaseFiles -> MuContext m
releaseCtx (ver, (month, year), files) = mkStrContext ctx
where
ctx "version" = MuVariable ver
ctx "year" = MuVariable $ show year
ctx "month" = MuVariable $ monthName month
ctx "files" = mapListContext fileCtx files
ctx _ = MuNothing
releasesCtx :: (Monad m) => MuContext m
releasesCtx = mkStrContext ctx
where
ctx "years" = mapListStrContext yearCtx years
ctx "current" = MuList [releaseCtx currentFiles]
ctx _ = MuNothing
yearCtx [] _ = MuBool False
yearCtx (r0:_) "year" = MuVariable $ show $ releaseYear r0
yearCtx rs "releases" = mapListContext releaseCtx rs
yearCtx _ _ = MuNothing
years = groupBy ((==) `on` releaseYear) priorFiles
releaseYear :: ReleaseFiles -> Int
releaseYear (_ver, (_month, year), _files) = year
monthName :: Int -> String
monthName i = maybe (show i) id $ lookup i monthNames
where
monthNames = zip [1..] $
words "January Feburary March April May June \
\July August September October November December"
historyCtx :: (Monad m) => MuContext m
historyCtx = mkStrContext outerCtx
where
outerCtx "history" = MuList [mkStrContext ctx]
outerCtx _ = MuNothing
ctx "hpReleases" = mapListStrContext rlsCtx releasesNewToOld
ctx "ncols" = MuVariable $ length releasesNewToOld + 1
ctx "sections" = MuList
[ sectionCtx "Compiler" [isGhc, not . isLib]
, sectionCtx "Core Libraries, provided with GHC" [isGhc, isLib]
, sectionCtx "Additional Platform Libraries" [not . isGhc, isLib]
, sectionCtx "Programs and Tools" [isTool]
]
ctx _ = MuNothing
rlsCtx rls "hpVersion" = MuVariable . showVersion . hpVersion . relVersion $ rls
rlsCtx _ _ = MuNothing
sectionCtx :: (Monad m) => String -> [IncludeType -> Bool] -> MuContext m
sectionCtx name tests = mkStrContext ctx
where
ctx "name" = MuVariable name
ctx "components" = mapListStrContext pCtx packages
ctx _ = MuNothing
packages = sortOnLower . nub . map pkgName . concat $
map (packagesByIncludeFilter $ \i -> all ($i) tests)
releasesNewToOld
sortOnLower = map snd . sort . map (\s -> (map toLower s, s))
pCtx pName "package" = MuVariable pName
pCtx pName "hackageUrl" =
MuVariable $ "http://hackage.haskell.org/package/" ++ pName
pCtx pName "releases" = mapListStrContext pvCtx $ packageVersionInfo pName
pCtx _ _ = MuNothing
pvCtx (c, _) "class" = MuVariable c
pvCtx (_, v) "version" = MuVariable v
pvCtx _ _ = MuNothing
packageVersionInfo :: String -> [(String, String)]
packageVersionInfo pName = curr $ zipWith comp vers (drop 1 vers ++ [Nothing])
where
comp Nothing _ = ("missing", "—")
comp (Just v) Nothing = ("update", showVersion v)
comp (Just v) (Just w) | maj v == maj w = ("same", showVersion v)
| otherwise = ("update", showVersion v)
maj = take 3 . versionBranch
curr ((c, v) : cvs) = (c ++ " current", v) : cvs
curr [] = []
vers = map (fmap pkgVersion . find ((==pName) . pkgName) . map snd . relIncludes)
releasesNewToOld
releasesNewToOld :: [Release]
releasesNewToOld = reverse releases
| ardumont/haskell-platform | hptool/src/Website.hs | bsd-3-clause | 4,647 | 0 | 15 | 1,189 | 1,488 | 765 | 723 | 103 | 9 |
-- | Reacts to changes in the selection in the diagram
module Controller.Conditions.Selection
(installHandlers)
where
-- External imports
import Control.Monad
import Data.Maybe
import Graphics.UI.Gtk
import Hails.MVC.Model.ProtectedModel.Reactive
-- Internal imports
import CombinedEnvironment
import Model.Model
import Model.SystemStatus
import View
import Graphics.UI.Gtk.Display.SoOSiMState
-- | Handles changes in the box selection in the diagram
installHandlers :: CEnv -> IO()
installHandlers cenv = void $ do
onEvent (model cenv) SimStateChanged $ conditionShowPage cenv
soosimOnSelectionChanged soosim $ conditionUpdateSelection cenv
where vw = view cenv
soosim = soosimView vw
-- | Shows component info only when a component is selected
conditionShowPage :: CEnv -> IO()
conditionShowPage cenv = onViewAsync $ do
stM <- getter simStateField (model cenv) -- readCBMVar $ mcs $ view cenv
let hasSelection = maybe False (not . null . selection . simGLSystemStatus) stM
notebook <- infoNotebook vw
-- Show notebook page
let newPage = if hasSelection then 1 else 0
notebookSetCurrentPage notebook newPage
where vw = view cenv
soosim = soosimView vw
-- | Shows component info only when a component is selected
conditionUpdateSelection :: CEnv -> IO()
conditionUpdateSelection cenv = onViewAsync $ do
selection <- soosimGetSelection soosim
stM <- getter simStateField (model cenv)
when (isJust stM) $ do
let selection' = fromMaybe [] selection
stM' = fromJust stM
status = simGLSystemStatus stM'
status' = status { selection = selection' }
stM'' = stM' { simGLSystemStatus = status' }
setter simStateField (model cenv) (Just stM'')
where vw = view cenv
soosim = soosimView vw
| ivanperez-keera/SoOSiM-ui | src/Controller/Conditions/Selection.hs | bsd-3-clause | 1,798 | 0 | 15 | 361 | 442 | 227 | 215 | 39 | 2 |
{-# LANGUAGE CPP, MagicHash, NondecreasingIndentation, UnboxedTuples #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------
module InteractiveEval (
#ifdef GHCI
RunResult(..), Status(..), Resume(..), History(..),
runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
parseImportDecl, SingleStep(..),
resume,
abandon, abandonAll,
getResumeContext,
getHistorySpan,
getModBreaks,
getHistoryModule,
back, forward,
setContext, getContext,
availsToGlobalRdrEnv,
getNamesInScope,
getRdrNamesInScope,
moduleIsInterpreted,
getInfo,
exprType,
typeKind,
parseName,
showModule,
isModuleInterpreted,
compileExpr, dynCompileExpr,
Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
#endif
) where
#ifdef GHCI
#include "HsVersions.h"
import InteractiveEvalTypes
import GhcMonad
import HscMain
import HsSyn
import HscTypes
import BasicTypes ( HValue )
import InstEnv
import FamInstEnv ( FamInst, orphNamesOfFamInst )
import TyCon
import Type hiding( typeKind )
import TcType hiding( typeKind )
import Var
import Id
import Name hiding ( varName )
import NameSet
import Avail
import RdrName
import VarSet
import VarEnv
import ByteCodeInstr
import Linker
import DynFlags
import Unique
import UniqSupply
import Module
import Panic
import UniqFM
import Maybes
import ErrUtils
import SrcLoc
import BreakArray
import RtClosureInspect
import Outputable
import FastString
import MonadUtils
import System.Mem.Weak
import System.Directory
import Data.Dynamic
import Data.Either
import Data.List (find)
import Control.Monad
#if __GLASGOW_HASKELL__ >= 709
import Foreign
#else
import Foreign.Safe
#endif
import Foreign.C
import GHC.Exts
import Data.Array
import Exception
import Control.Concurrent
import System.IO.Unsafe
-- -----------------------------------------------------------------------------
-- running a statement interactively
getResumeContext :: GhcMonad m => m [Resume]
getResumeContext = withSession (return . ic_resume . hsc_IC)
data SingleStep
= RunToCompletion
| SingleStep
| RunAndLogSteps
isStep :: SingleStep -> Bool
isStep RunToCompletion = False
isStep _ = True
mkHistory :: HscEnv -> HValue -> BreakInfo -> History
mkHistory hsc_env hval bi = let
decls = findEnclosingDecls hsc_env bi
in History hval bi decls
getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo
getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env hist =
let inf = historyBreakInfo hist
num = breakInfo_number inf
in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
_ -> panic "getHistorySpan"
getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
| Just linkable <- hm_linkable hmi,
[BCOs _ modBreaks] <- linkableUnlinked linkable
= modBreaks
| otherwise
= emptyModBreaks -- probably object code
{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
findEnclosingDecls hsc_env inf =
let hmi = expectJust "findEnclosingDecls" $
lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
mb = getModBreaks hmi
in modBreaks_decls mb ! breakInfo_number inf
-- | Update fixity environment in the current interactive context.
updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
updateFixityEnv fix_env = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
-- | Run a statement in the current interactive context. Statement
-- may bind multple values.
runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
runStmt = runStmtWithLocation "<interactive>" 1
-- | Run a statement in the current interactive context. Passing debug information
-- Statement may bind multple values.
runStmtWithLocation :: GhcMonad m => String -> Int ->
String -> SingleStep -> m RunResult
runStmtWithLocation source linenumber expr step =
do
hsc_env <- getSession
breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
-- Turn off -fwarn-unused-bindings when running a statement, to hide
-- warnings about the implicit bindings we introduce.
let ic = hsc_IC hsc_env -- use the interactive dflags
idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedBinds
hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
-- compile to value (IO [HValue]), don't run
r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
case r of
-- empty statement / comment
Nothing -> return (RunOk [])
Just (tyThings, hval, fix_env) -> do
updateFixityEnv fix_env
status <-
withVirtualCWD $
withBreakAction (isStep step) idflags' breakMVar statusMVar $ do
liftIO $ sandboxIO idflags' statusMVar hval
let ic = hsc_IC hsc_env
bindings = (ic_tythings ic, ic_rn_gbl_env ic)
size = ghciHistSize idflags'
handleRunStatus step expr bindings tyThings
breakMVar statusMVar status (emptyHistory size)
runDecls :: GhcMonad m => String -> m [Name]
runDecls = runDeclsWithLocation "<interactive>" 1
runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
runDeclsWithLocation source linenumber expr =
do
hsc_env <- getSession
(tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
setSession $ hsc_env { hsc_IC = ic }
hsc_env <- getSession
hsc_env' <- liftIO $ rttiEnvironment hsc_env
modifySession (\_ -> hsc_env')
return (map getName tyThings)
withVirtualCWD :: GhcMonad m => m a -> m a
withVirtualCWD m = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
let set_cwd = do
dir <- liftIO $ getCurrentDirectory
case ic_cwd ic of
Just dir -> liftIO $ setCurrentDirectory dir
Nothing -> return ()
return dir
reset_cwd orig_dir = do
virt_dir <- liftIO $ getCurrentDirectory
hsc_env <- getSession
let old_IC = hsc_IC hsc_env
setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
liftIO $ setCurrentDirectory orig_dir
gbracket set_cwd reset_cwd $ \_ -> m
parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
emptyHistory :: Int -> BoundedList History
emptyHistory size = nilBL size
handleRunStatus :: GhcMonad m
=> SingleStep -> String-> ([TyThing],GlobalRdrEnv) -> [Id]
-> MVar () -> MVar Status -> Status -> BoundedList History
-> m RunResult
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status history
| RunAndLogSteps <- step = tracing
| otherwise = not_tracing
where
tracing
| Break is_exception apStack info tid <- status
, not is_exception
= do
hsc_env <- getSession
b <- liftIO $ isBreakEnabled hsc_env info
if b
then not_tracing
-- This breakpoint is explicitly enabled; we want to stop
-- instead of just logging it.
else do
let history' = mkHistory hsc_env apStack info `consBL` history
-- probably better make history strict here, otherwise
-- our BoundedList will be pointless.
_ <- liftIO $ evaluate history'
status <- withBreakAction True (hsc_dflags hsc_env)
breakMVar statusMVar $ do
liftIO $ mask_ $ do
putMVar breakMVar () -- awaken the stopped thread
redirectInterrupts tid $
takeMVar statusMVar -- and wait for the result
handleRunStatus RunAndLogSteps expr bindings final_ids
breakMVar statusMVar status history'
| otherwise
= not_tracing
not_tracing
-- Hit a breakpoint
| Break is_exception apStack info tid <- status
= do
hsc_env <- getSession
let mb_info | is_exception = Nothing
| otherwise = Just info
(hsc_env1, names, span) <- liftIO $
bindLocalsAtBreakpoint hsc_env apStack mb_info
let
resume = Resume
{ resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = mb_info
, resumeSpan = span, resumeHistory = toListBL history
, resumeHistoryIx = 0 }
hsc_env2 = pushResume hsc_env1 resume
modifySession (\_ -> hsc_env2)
return (RunBreak tid names mb_info)
-- Completed with an exception
| Complete (Left e) <- status
= return (RunException e)
-- Completed successfully
| Complete (Right hvals) <- status
= do hsc_env <- getSession
let final_ic = extendInteractiveContextWithIds (hsc_IC hsc_env) final_ids
final_names = map getName final_ids
liftIO $ Linker.extendLinkEnv (zip final_names hvals)
hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
modifySession (\_ -> hsc_env')
return (RunOk final_names)
| otherwise
= panic "handleRunStatus" -- The above cases are in fact exhaustive
isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
isBreakEnabled hsc_env inf =
case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
Just hmi -> do
w <- getBreak (hsc_dflags hsc_env)
(modBreaks_flags (getModBreaks hmi))
(breakInfo_number inf)
case w of Just n -> return (n /= 0); _other -> return False
_ ->
return False
foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
setStepFlag :: IO ()
setStepFlag = poke stepFlag 1
resetStepFlag :: IO ()
resetStepFlag = poke stepFlag 0
-- this points to the IO action that is executed when a breakpoint is hit
foreign import ccall "&rts_breakpoint_io_action"
breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
-- When running a computation, we redirect ^C exceptions to the running
-- thread. ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
--
-- Careful here: there may be ^C exceptions flying around, so we start the new
-- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
-- only while we execute the user's code. We can't afford to lose the final
-- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
sandboxIO dflags statusMVar thing =
mask $ \restore -> -- fork starts blocked
let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
in if gopt Opt_GhciSandbox dflags
then do tid <- forkIO $ do res <- runIt
putMVar statusMVar res -- empty: can't block
redirectInterrupts tid $
takeMVar statusMVar
else -- GLUT on OS X needs to run on the main thread. If you
-- try to use it from another thread then you just get a
-- white rectangle rendered. For this, or anything else
-- with such restrictions, you can turn the GHCi sandbox off
-- and things will be run in the main thread.
--
-- BUT, note that the debugging features (breakpoints,
-- tracing, etc.) need the expression to be running in a
-- separate thread, so debugging is only enabled when
-- using the sandbox.
runIt
--
-- While we're waiting for the sandbox thread to return a result, if
-- the current thread receives an asynchronous exception we re-throw
-- it at the sandbox thread and continue to wait.
--
-- This is for two reasons:
--
-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
-- computation to run its exception handlers before returning the
-- exception result to the caller of runStmt.
--
-- * clients of the GHC API can terminate a runStmt in progress
-- without knowing the ThreadId of the sandbox thread (#1381)
--
-- NB. use a weak pointer to the thread, so that the thread can still
-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
-- exception. A symptom of getting this wrong is that conc033(ghci)
-- will hang.
--
redirectInterrupts :: ThreadId -> IO a -> IO a
redirectInterrupts target wait
= do wtid <- mkWeakThreadId target
wait `catch` \e -> do
m <- deRefWeak wtid
case m of
Nothing -> wait
Just target -> do throwTo target (e :: SomeException); wait
-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break. Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange). So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: DynFlags -> IO a -> IO a
rethrow dflags io = Exception.catch io $ \se -> do
-- If -fbreak-on-error, we break unconditionally,
-- but with care of not breaking twice
if gopt Opt_BreakOnError dflags &&
not (gopt Opt_BreakOnException dflags)
then poke exceptionFlag 1
else case fromException se of
-- If it is a "UserInterrupt" exception, we allow
-- a possible break by way of -fbreak-on-exception
Just UserInterrupt -> return ()
-- In any other case, we don't want to break
_ -> poke exceptionFlag 0
Exception.throwIO se
-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running. This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction :: (ExceptionMonad m, MonadIO m) =>
Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
withBreakAction step dflags breakMVar statusMVar act
= gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
where
setBreakAction = do
stablePtr <- newStablePtr onBreak
poke breakPointIOAction stablePtr
when (gopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
when step $ setStepFlag
return stablePtr
-- Breaking on exceptions is not enabled by default, since it
-- might be a bit surprising. The exception flag is turned off
-- as soon as it is hit, or in resetBreakAction below.
onBreak is_exception info apStack = do
tid <- myThreadId
putMVar statusMVar (Break is_exception apStack info tid)
takeMVar breakMVar
resetBreakAction stablePtr = do
poke breakPointIOAction noBreakStablePtr
poke exceptionFlag 0
resetStepFlag
freeStablePtr stablePtr
noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
noBreakAction True _ _ = return () -- exception: just continue
resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
resume canLogSpan step
= do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
-- unbind the temporary locals by restoring the TypeEnv from
-- before the breakpoint, and drop this Resume from the
-- InteractiveContext.
let (resume_tmp_te,resume_rdr_env) = resumeBindings r
ic' = ic { ic_tythings = resume_tmp_te,
ic_rn_gbl_env = resume_rdr_env,
ic_resume = rs }
modifySession (\_ -> hsc_env{ hsc_IC = ic' })
-- remove any bindings created since the breakpoint from the
-- linker's environment
let new_names = map getName (filter (`notElem` resume_tmp_te)
(ic_tythings ic))
liftIO $ Linker.deleteFromLinkEnv new_names
when (isStep step) $ liftIO setStepFlag
case r of
Resume { resumeStmt = expr, resumeThreadId = tid
, resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
, resumeBindings = bindings, resumeFinalIds = final_ids
, resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
, resumeHistory = hist } -> do
withVirtualCWD $ do
withBreakAction (isStep step) (hsc_dflags hsc_env)
breakMVar statusMVar $ do
status <- liftIO $ mask_ $ do
putMVar breakMVar ()
-- this awakens the stopped thread...
redirectInterrupts tid $
takeMVar statusMVar
-- and wait for the result
let prevHistoryLst = fromListBL 50 hist
hist' = case info of
Nothing -> prevHistoryLst
Just i
| not $canLogSpan span -> prevHistoryLst
| otherwise -> mkHistory hsc_env apStack i `consBL`
fromListBL 50 hist
handleRunStatus step expr bindings final_ids
breakMVar statusMVar status hist'
back :: GhcMonad m => m ([Name], Int, SrcSpan)
back = moveHist (+1)
forward :: GhcMonad m => m ([Name], Int, SrcSpan)
forward = moveHist (subtract 1)
moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
moveHist fn = do
hsc_env <- getSession
case ic_resume (hsc_IC hsc_env) of
[] -> liftIO $
throwGhcExceptionIO (ProgramError "not stopped at a breakpoint")
(r:rs) -> do
let ix = resumeHistoryIx r
history = resumeHistory r
new_ix = fn ix
--
when (new_ix > length history) $ liftIO $
throwGhcExceptionIO (ProgramError "no more logged breakpoints")
when (new_ix < 0) $ liftIO $
throwGhcExceptionIO (ProgramError "already at the beginning of the history")
let
update_ic apStack mb_info = do
(hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
apStack mb_info
let ic = hsc_IC hsc_env1
r' = r { resumeHistoryIx = new_ix }
ic' = ic { ic_resume = r':rs }
modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
return (names, new_ix, span)
-- careful: we want apStack to be the AP_STACK itself, not a thunk
-- around it, hence the cases are carefully constructed below to
-- make this the case. ToDo: this is v. fragile, do something better.
if new_ix == 0
then case r of
Resume { resumeApStack = apStack,
resumeBreakInfo = mb_info } ->
update_ic apStack mb_info
else case history !! (new_ix - 1) of
History apStack info _ ->
update_ic apStack (Just info)
-- -----------------------------------------------------------------------------
-- After stopping at a breakpoint, add free variables to the environment
result_fs :: FastString
result_fs = fsLit "_result"
bindLocalsAtBreakpoint
:: HscEnv
-> HValue
-> Maybe BreakInfo
-> IO (HscEnv, [Name], SrcSpan)
-- Nothing case: we stopped when an exception was raised, not at a
-- breakpoint. We have no location information or local variables to
-- bind, all we can do is bind a local variable to the exception
-- value.
bindLocalsAtBreakpoint hsc_env apStack Nothing = do
let exn_fs = fsLit "_exception"
exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
e_fs = fsLit "e"
e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
exn_id = Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 [exn_id]
span = mkGeneralSrcSpan (fsLit "<exception thrown>")
--
Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
-- Just case: we stopped at a breakpoint, we have information about the location
-- of the breakpoint and the free variables of the expression.
bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
let
mod_name = moduleName (breakInfo_module info)
hmi = expectJust "bindLocalsAtBreakpoint" $
lookupUFM (hsc_HPT hsc_env) mod_name
breaks = getModBreaks hmi
index = breakInfo_number info
vars = breakInfo_vars info
result_ty = breakInfo_resty info
occs = modBreaks_vars breaks ! index
span = modBreaks_locs breaks ! index
-- Filter out any unboxed ids;
-- we can't bind these at the prompt
pointers = filter (\(id,_) -> isPointer id) vars
isPointer id | UnaryRep ty <- repType (idType id)
, PtrRep <- typePrimRep ty = True
| otherwise = False
(ids, offsets) = unzip pointers
free_tvs = mapUnionVarSet (tyVarsOfType . idType) ids
`unionVarSet` tyVarsOfType result_ty
-- It might be that getIdValFromApStack fails, because the AP_STACK
-- has been accidentally evaluated, or something else has gone wrong.
-- So that we don't fall over in a heap when this happens, just don't
-- bind any free variables instead, and we emit a warning.
mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
when (any isNothing mb_hValues) $
debugTraceMsg (hsc_dflags hsc_env) 1 $
text "Warning: _result has been evaluated, some bindings have been lost"
us <- mkSplitUniqSupply 'I'
let (us1, us2) = splitUniqSupply us
tv_subst = newTyVars us1 free_tvs
new_ids = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
names = map idName new_ids
-- make an Id for _result. We use the Unique of the FastString "_result";
-- we don't care about uniqueness here, because there will only be one
-- _result in scope at any time.
let result_name = mkInternalName (getUnique result_fs)
(mkVarOccFS result_fs) span
result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
-- for each Id we're about to bind in the local envt:
-- - tidy the type variables
-- - globalise the Id (Ids are supposed to be Global, apparently).
--
let result_ok = isPointer result_id
all_ids | result_ok = result_id : new_ids
| otherwise = new_ids
id_tys = map idType all_ids
(_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
final_ids = zipWith setIdType all_ids tidy_tys
ictxt0 = hsc_IC hsc_env
ictxt1 = extendInteractiveContextWithIds ictxt0 final_ids
Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
return (hsc_env1, if result_ok then result_name:names else names, span)
where
-- We need a fresh Unique for each Id we bind, because the linker
-- state is single-threaded and otherwise we'd spam old bindings
-- whenever we stop at a breakpoint. The InteractveContext is properly
-- saved/restored, but not the linker state. See #1743, test break026.
mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
mkNewId tv_subst occ id uniq
= Id.mkVanillaGlobalWithInfo name ty (idInfo id)
where
loc = nameSrcSpan (idName id)
name = mkInternalName uniq occ loc
ty = substTy tv_subst (idType id)
newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
-- Similarly, clone the type variables mentioned in the types
-- we have here, *and* make them all RuntimeUnk tyars
newTyVars us tvs
= mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
| (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
, let name = setNameUnique (tyVarName tv) uniq ]
rttiEnvironment :: HscEnv -> IO HscEnv
rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
incompletelyTypedIds =
[id | id <- tmp_ids
, not $ noSkolems id
, (occNameFS.nameOccName.idName) id /= result_fs]
hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
return hsc_env'
where
noSkolems = isEmptyVarSet . tyVarsOfType . idType
improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
let tmp_ids = [id | AnId id <- ic_tythings ic]
Just id = find (\i -> idName i == name) tmp_ids
if noSkolems id
then return hsc_env
else do
mb_new_ty <- reconstructType hsc_env 10 id
let old_ty = idType id
case mb_new_ty of
Nothing -> return hsc_env
Just new_ty -> do
case improveRTTIType hsc_env old_ty new_ty of
Nothing -> return $
WARN(True, text (":print failed to calculate the "
++ "improvement for a type")) hsc_env
Just subst -> do
let dflags = hsc_dflags hsc_env
when (dopt Opt_D_dump_rtti dflags) $
printInfoForUser dflags alwaysQualify $
fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
let ic' = substInteractiveContext ic subst
return hsc_env{hsc_IC=ic'}
getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
getIdValFromApStack apStack (I# stackDepth) = do
case getApStackVal# apStack (stackDepth +# 1#) of
-- The +1 is magic! I don't know where it comes
-- from, but this makes things line up. --SDM
(# ok, result #) ->
case ok of
0# -> return Nothing -- AP_STACK not found
_ -> return (Just (unsafeCoerce# result))
pushResume :: HscEnv -> Resume -> HscEnv
pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
where
ictxt0 = hsc_IC hsc_env
ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
-- -----------------------------------------------------------------------------
-- Abandoning a resume context
abandon :: GhcMonad m => m Bool
abandon = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
r:rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
liftIO $ abandon_ r
return True
abandonAll :: GhcMonad m => m Bool
abandonAll = do
hsc_env <- getSession
let ic = hsc_IC hsc_env
resume = ic_resume ic
case resume of
[] -> return False
rs -> do
modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
liftIO $ mapM_ abandon_ rs
return True
-- when abandoning a computation we have to
-- (a) kill the thread with an async exception, so that the
-- computation itself is stopped, and
-- (b) fill in the MVar. This step is necessary because any
-- thunks that were under evaluation will now be updated
-- with the partial computation, which still ends in takeMVar,
-- so any attempt to evaluate one of these thunks will block
-- unless we fill in the MVar.
-- (c) wait for the thread to terminate by taking its status MVar. This
-- step is necessary to prevent race conditions with
-- -fbreak-on-exception (see #5975).
-- See test break010.
abandon_ :: Resume -> IO ()
abandon_ r = do
killThread (resumeThreadId r)
putMVar (resumeBreakMVar r) ()
_ <- takeMVar (resumeStatMVar r)
return ()
-- -----------------------------------------------------------------------------
-- Bounded list, optimised for repeated cons
data BoundedList a = BL
{-# UNPACK #-} !Int -- length
{-# UNPACK #-} !Int -- bound
[a] -- left
[a] -- right, list is (left ++ reverse right)
nilBL :: Int -> BoundedList a
nilBL bound = BL 0 bound [] []
consBL :: a -> BoundedList a -> BoundedList a
consBL a (BL len bound left right)
| len < bound = BL (len+1) bound (a:left) right
| null right = BL len bound [a] $! tail (reverse left)
| otherwise = BL len bound (a:left) $! tail right
toListBL :: BoundedList a -> [a]
toListBL (BL _ _ left right) = left ++ reverse right
fromListBL :: Int -> [a] -> BoundedList a
fromListBL bound l = BL (length l) bound l []
-- lenBL (BL len _ _ _) = len
-- -----------------------------------------------------------------------------
-- | Set the interactive evaluation context.
--
-- (setContext imports) sets the ic_imports field (which in turn
-- determines what is in scope at the prompt) to 'imports', and
-- constructs the ic_rn_glb_env environment to reflect it.
--
-- We retain in scope all the things defined at the prompt, and kept
-- in ic_tythings. (Indeed, they shadow stuff from ic_imports.)
setContext :: GhcMonad m => [InteractiveImport] -> m ()
setContext imports
= do { hsc_env <- getSession
; let dflags = hsc_dflags hsc_env
; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
; case all_env_err of
Left (mod, err) ->
liftIO $ throwGhcExceptionIO (formatError dflags mod err)
Right all_env -> do {
; let old_ic = hsc_IC hsc_env
final_rdr_env = all_env `icExtendGblRdrEnv` ic_tythings old_ic
; modifySession $ \_ ->
hsc_env{ hsc_IC = old_ic { ic_imports = imports
, ic_rn_gbl_env = final_rdr_env }}}}
where
formatError dflags mod err = ProgramError . showSDoc dflags $
text "Cannot add module" <+> ppr mod <+>
text "to context:" <+> text err
findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
-> IO (Either (ModuleName, String) GlobalRdrEnv)
-- Compute the GlobalRdrEnv for the interactive context
findGlobalRdrEnv hsc_env imports
= do { idecls_env <- hscRnImportDecls hsc_env idecls
-- This call also loads any orphan modules
; return $ case partitionEithers (map mkEnv imods) of
([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
(err : _, _) -> Left err }
where
idecls :: [LImportDecl RdrName]
idecls = [noLoc d | IIDecl d <- imports]
imods :: [ModuleName]
imods = [m | IIModule m <- imports]
mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
Left err -> Left (mod, err)
Right env -> Right env
availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
availsToGlobalRdrEnv mod_name avails
= mkGlobalRdrEnv (gresFromAvails imp_prov avails)
where
-- We're building a GlobalRdrEnv as if the user imported
-- all the specified modules into the global interactive module
imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
is_qual = False,
is_dloc = srcLocSpan interactiveSrcLoc }
mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
mkTopLevEnv hpt modl
= case lookupUFM hpt modl of
Nothing -> Left "not a home module"
Just details ->
case mi_globals (hm_iface details) of
Nothing -> Left "not interpreted"
Just env -> Right env
-- | Get the interactive evaluation context, consisting of a pair of the
-- set of modules from which we take the full top-level scope, and the set
-- of modules from which we take just the exports respectively.
getContext :: GhcMonad m => m [InteractiveImport]
getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
return (ic_imports ic)
-- | Returns @True@ if the specified module is interpreted, and hence has
-- its full top-level scope available.
moduleIsInterpreted :: GhcMonad m => Module -> m Bool
moduleIsInterpreted modl = withSession $ \h ->
if modulePackageKey modl /= thisPackage (hsc_dflags h)
then return False
else case lookupUFM (hsc_HPT h) (moduleName modl) of
Just details -> return (isJust (mi_globals (hm_iface details)))
_not_a_home_module -> return False
-- | Looks up an identifier in the current interactive context (for :info)
-- Filter the instances by the ones whose tycons (or clases resp)
-- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
-- The exact choice of which ones to show, and which to hide, is a judgement call.
-- (see Trac #1581)
getInfo :: GhcMonad m => Bool -> Name -> m (Maybe (TyThing,Fixity,[ClsInst],[FamInst]))
getInfo allInfo name
= withSession $ \hsc_env ->
do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
case mb_stuff of
Nothing -> return Nothing
Just (thing, fixity, cls_insts, fam_insts) -> do
let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
-- Filter the instances based on whether the constituent names of their
-- instance heads are all in scope.
let cls_insts' = filter (plausible rdr_env . orphNamesOfClsInst) cls_insts
fam_insts' = filter (plausible rdr_env . orphNamesOfFamInst) fam_insts
return (Just (thing, fixity, cls_insts', fam_insts'))
where
plausible rdr_env names
-- Dfun involving only names that are in ic_rn_glb_env
= allInfo
|| all ok (nameSetElems names)
where -- A name is ok if it's in the rdr_env,
-- whether qualified or not
ok n | n == name = True -- The one we looked for in the first place!
| isBuiltInSyntax n = True
| isExternalName n = any ((== n) . gre_name)
(lookupGRE_Name rdr_env n)
| otherwise = True
-- | Returns all names in scope in the current interactive context
getNamesInScope :: GhcMonad m => m [Name]
getNamesInScope = withSession $ \hsc_env -> do
return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
getRdrNamesInScope :: GhcMonad m => m [RdrName]
getRdrNamesInScope = withSession $ \hsc_env -> do
let
ic = hsc_IC hsc_env
gbl_rdrenv = ic_rn_gbl_env ic
gbl_names = concatMap greToRdrNames $ globalRdrEnvElts gbl_rdrenv
return gbl_names
-- ToDo: move to RdrName
greToRdrNames :: GlobalRdrElt -> [RdrName]
greToRdrNames GRE{ gre_name = name, gre_prov = prov }
= case prov of
LocalDef -> [unqual]
Imported specs -> concat (map do_spec (map is_decl specs))
where
occ = nameOccName name
unqual = Unqual occ
do_spec decl_spec
| is_qual decl_spec = [qual]
| otherwise = [unqual,qual]
where qual = Qual (is_as decl_spec) occ
-- | Parses a string as an identifier, and returns the list of 'Name's that
-- the identifier can refer to in the current interactive context.
parseName :: GhcMonad m => String -> m [Name]
parseName str = withSession $ \hsc_env -> do
(L _ rdr_name) <- liftIO $ hscParseIdentifier hsc_env str
liftIO $ hscTcRnLookupRdrName hsc_env rdr_name
-- -----------------------------------------------------------------------------
-- Getting the type of an expression
-- | Get the type of an expression
-- Returns its most general type
exprType :: GhcMonad m => String -> m Type
exprType expr = withSession $ \hsc_env -> do
ty <- liftIO $ hscTcExpr hsc_env expr
return $ tidyType emptyTidyEnv ty
-- -----------------------------------------------------------------------------
-- Getting the kind of a type
-- | Get the kind of a type
typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
typeKind normalise str = withSession $ \hsc_env -> do
liftIO $ hscKcType hsc_env normalise str
-----------------------------------------------------------------------------
-- Compile an expression, run it and deliver the resulting HValue
compileExpr :: GhcMonad m => String -> m HValue
compileExpr expr = withSession $ \hsc_env -> do
Just (ids, hval, fix_env) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
updateFixityEnv fix_env
hvals <- liftIO hval
case (ids,hvals) of
([_],[hv]) -> return hv
_ -> panic "compileExpr"
-- -----------------------------------------------------------------------------
-- Compile an expression, run it and return the result as a dynamic
dynCompileExpr :: GhcMonad m => String -> m Dynamic
dynCompileExpr expr = do
iis <- getContext
let importDecl = ImportDecl {
ideclName = noLoc (mkModuleName "Data.Dynamic"),
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False,
ideclQualified = True,
ideclImplicit = False,
ideclAs = Nothing,
ideclHiding = Nothing
}
setContext (IIDecl importDecl : iis)
let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
Just (ids, hvals, fix_env) <- withSession $ \hsc_env ->
liftIO $ hscStmt hsc_env stmt
setContext iis
updateFixityEnv fix_env
vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
case (ids,vals) of
(_:[], v:[]) -> return v
_ -> panic "dynCompileExpr"
-----------------------------------------------------------------------------
-- show a module and it's source/object filenames
showModule :: GhcMonad m => ModSummary -> m String
showModule mod_summary =
withSession $ \hsc_env -> do
interpreted <- isModuleInterpreted mod_summary
let dflags = hsc_dflags hsc_env
return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
isModuleInterpreted mod_summary = withSession $ \hsc_env ->
case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
Nothing -> panic "missing linkable"
Just mod_info -> return (not obj_linkable)
where
obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
----------------------------------------------------------------------------
-- RTTI primitives
obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
obtainTermFromVal hsc_env bound force ty x =
cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
obtainTermFromId hsc_env bound force id = do
hv <- Linker.getHValue hsc_env (varName id)
cvObtainTerm hsc_env bound force (idType id) hv
-- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
reconstructType hsc_env bound id = do
hv <- Linker.getHValue hsc_env (varName id)
cvReconstructType hsc_env bound (idType id) hv
mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
#endif /* GHCI */
| bitemyapp/ghc | compiler/main/InteractiveEval.hs | bsd-3-clause | 41,677 | 19 | 36 | 11,816 | 8,984 | 4,588 | 4,396 | 2 | 0 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module IRTS.Cil.UnreachableCodeRemoval
(removeUnreachable) where
import Data.Graph
import Language.Cil hiding (entryPoint)
removeUnreachable :: [MethodDef] -> [MethodDef]
removeUnreachable defs = let (graph, fromVertex, toVertex) = callGraph defs
(Just entryPoint) = toVertex "'runMain0'"
in map (def . fromVertex) (reachable graph entryPoint)
where def (d, _, _) = d
callGraph :: [MethodDef]
-> (Graph, Vertex -> (MethodDef, MethodName, [MethodName]), MethodName -> Maybe Vertex)
callGraph methods = graphFromEdges $ map toEdge methods
where toEdge m@(Method _ _ name _ body) = (m, name, callees body)
callees (OpCode (Tailcall c) : rest) = callees (OpCode c : rest)
callees (OpCode Call{..} : rest) = methodName : callees rest
callees (_ : rest) = callees rest
callees [] = []
| BartAdv/idris-cil | src/IRTS/Cil/UnreachableCodeRemoval.hs | bsd-3-clause | 1,004 | 0 | 12 | 291 | 328 | 175 | 153 | 18 | 4 |
{-# LANGUAGE PatternGuards, ViewPatterns, RecordWildCards #-}
module Settings(
Severity(..), Classify(..), HintRule(..), Note(..), showNotes, Setting(..),
defaultHintName, isUnifyVar,
findSettings, readSettings,
readSettings2, readPragma, findSettings2
) where
import HSE.All
import Data.Char
import Data.List
import Data.Monoid
import System.FilePath
import Util
defaultHintName :: String
defaultHintName = "Use alternative"
-- | How severe an issue is.
data Severity
= Ignore -- ^ The issue has been explicitly ignored and will usually be hidden (pass @--show@ on the command line to see ignored ideas).
| Warning -- ^ Warnings are things that some people may consider improvements, but some may not.
| Error -- ^ Errors are suggestions that are nearly always a good idea to apply.
deriving (Eq,Ord,Show,Read,Bounded,Enum)
getSeverity :: String -> Maybe Severity
getSeverity "ignore" = Just Ignore
getSeverity "warn" = Just Warning
getSeverity "warning" = Just Warning
getSeverity "error" = Just Error
getSeverity "hint" = Just Error
getSeverity _ = Nothing
-- Any 1-letter variable names are assumed to be unification variables
isUnifyVar :: String -> Bool
isUnifyVar [x] = x == '?' || isAlpha x
isUnifyVar _ = False
addInfix = parseFlagsAddFixities $ infix_ (-1) ["==>"]
---------------------------------------------------------------------
-- TYPE
-- | A note describing the impact of the replacement.
data Note
= IncreasesLaziness -- ^ The replacement is increases laziness, for example replacing @reverse (reverse x)@ with @x@ makes the code lazier.
| DecreasesLaziness -- ^ The replacement is decreases laziness, for example replacing @(fst x, snd x)@ with @x@ makes the code stricter.
| RemovesError String -- ^ The replacement removes errors, for example replacing @foldr1 (+)@ with @sum@ removes an error on @[]@, and might contain the text @\"on []\"@.
| ValidInstance String String -- ^ The replacement assumes standard type class lemmas, a hint with the note @ValidInstance \"Eq\" \"x\"@ might only be valid if
-- the @x@ variable has a reflexive @Eq@ instance.
| Note String -- ^ An arbitrary note.
deriving (Eq,Ord)
instance Show Note where
show IncreasesLaziness = "increases laziness"
show DecreasesLaziness = "decreases laziness"
show (RemovesError x) = "removes error " ++ x
show (ValidInstance x y) = "requires a valid " ++ x ++ " instance for " ++ y
show (Note x) = x
showNotes :: [Note] -> String
showNotes = intercalate ", " . map show . filter use
where use ValidInstance{} = False -- Not important enough to tell an end user
use _ = True
-- | How to classify an 'Idea'. If any matching field is @\"\"@ then it matches everything.
data Classify = Classify
{classifySeverity :: Severity -- ^ Severity to set the 'Idea' to.
,classifyHint :: String -- ^ 'ideaHint'.
,classifyModule :: String -- ^ 'ideaModule'.
,classifyDecl :: String -- ^ 'ideaDecl'.
}
deriving Show
-- | A @LHS ==> RHS@ style hint rule.
data HintRule = HintRule
{hintRuleSeverity :: Severity -- ^ Default severity for the hint.
,hintRuleName :: String -- ^ Name for the hint.
,hintRuleScope :: Scope -- ^ Module scope in which the hint operates.
,hintRuleLHS :: Exp SrcSpanInfo -- ^ LHS
,hintRuleRHS :: Exp SrcSpanInfo -- ^ RHS
,hintRuleSide :: Maybe (Exp SrcSpanInfo) -- ^ Side condition, typically specified with @where _ = ...@.
,hintRuleNotes :: [Note] -- ^ Notes about application of the hint.
}
deriving Show
data Setting
= SettingClassify Classify
| SettingMatchExp HintRule
| Builtin String -- use a builtin hint set
| Infix Fixity
deriving Show
---------------------------------------------------------------------
-- READ A SETTINGS FILE
-- Given a list of hint files to start from
-- Return the list of settings commands
readSettings2 :: FilePath -> [FilePath] -> [String] -> IO [Setting]
readSettings2 dataDir files hints = do
(builtin,mods) <- fmap unzipEither $ concatMapM (readHints dataDir) $ map Right files ++ map Left hints
return $ map Builtin builtin ++ concatMap moduleSettings_ mods
moduleSettings_ :: Module SrcSpanInfo -> [Setting]
moduleSettings_ m = concatMap (readSetting $ scopeCreate m) $ concatMap getEquations $
[AnnPragma l x | AnnModulePragma l x <- modulePragmas m] ++ moduleDecls m
-- | Given a module containing HLint settings information return the 'Classify' rules and the 'HintRule' expressions.
-- Any fixity declarations will be discarded, but any other unrecognised elements will result in an exception.
readSettings :: Module SrcSpanInfo -> ([Classify], [HintRule])
readSettings m = ([x | SettingClassify x <- xs], [x | SettingMatchExp x <- xs])
where xs = moduleSettings_ m
readHints :: FilePath -> Either String FilePath -> IO [Either String Module_]
readHints datadir x = do
(builtin,ms) <- case x of
Left src -> findSettings datadir "CommandLine" (Just src)
Right file -> findSettings datadir file Nothing
return $ map Left builtin ++ map Right ms
-- | Given the data directory (where the @hlint@ data files reside, see 'getHLintDataDir'),
-- and a filename to read, and optionally that file's contents, produce a pair containing:
--
-- 1. Builtin hints to use, e.g. @"List"@, which should be resolved using 'builtinHints'.
--
-- 1. A list of modules containing hints, suitable for processing with 'readSettings'.
--
-- Any parse failures will result in an exception.
findSettings :: FilePath -> FilePath -> Maybe String -> IO ([String], [Module SrcSpanInfo])
findSettings dataDir file contents = do
let flags = addInfix defaultParseFlags
res <- parseModuleEx flags file contents
case res of
Left (ParseError sl msg err) -> exitMessage $ "Parse failure at " ++ showSrcLoc sl ++ ": " ++ msg ++ "\n" ++ err
Right m -> do
ys <- sequence [f $ fromNamed $ importModule i | i <- moduleImports m, importPkg i `elem` [Just "hint", Just "hlint"]]
return $ concat2 $ ([],[m]) : ys
where
f x | Just x <- "HLint.Builtin." `stripPrefix` x = return ([x],[])
| Just x <- "HLint." `stripPrefix` x = findSettings dataDir (dataDir </> x <.> "hs") Nothing
| otherwise = findSettings dataDir (x <.> "hs") Nothing
readSetting :: Scope -> Decl_ -> [Setting]
readSetting s (FunBind _ [Match _ (Ident _ (getSeverity -> Just severity)) pats (UnGuardedRhs _ bod) bind])
| InfixApp _ lhs op rhs <- bod, opExp op ~= "==>" =
let (a,b) = readSide $ childrenBi bind in
[SettingMatchExp $ HintRule severity (headDef defaultHintName names) s (fromParen lhs) (fromParen rhs) a b]
| otherwise = [SettingClassify $ Classify severity n a b | n <- names2, (a,b) <- readFuncs bod]
where
names = filter notNull $ getNames pats bod
names2 = ["" | null names] ++ names
readSetting s x | "test" `isPrefixOf` map toLower (fromNamed x) = []
readSetting s (AnnPragma _ x) | Just y <- readPragma x = [SettingClassify y]
readSetting s (PatBind an (PVar _ name) _ bod bind) = readSetting s $ FunBind an [Match an name [] bod bind]
readSetting s (FunBind an xs) | length xs /= 1 = concatMap (readSetting s . FunBind an . return) xs
readSetting s (SpliceDecl an (App _ (Var _ x) (Lit _ y))) = readSetting s $ FunBind an [Match an (toNamed $ fromNamed x) [PLit an y] (UnGuardedRhs an $ Lit an $ String an "" "") Nothing]
readSetting s x@InfixDecl{} = map Infix $ getFixity x
readSetting s x = errorOn x "bad hint"
-- return Nothing if it is not an HLint pragma, otherwise all the settings
readPragma :: Annotation S -> Maybe Classify
readPragma o = case o of
Ann _ name x -> f (fromNamed name) x
TypeAnn _ name x -> f (fromNamed name) x
ModuleAnn _ x -> f "" x
where
f name (Lit _ (String _ s _)) | "hlint:" `isPrefixOf` map toLower s =
case getSeverity a of
Nothing -> errorOn o "bad classify pragma"
Just severity -> Just $ Classify severity (ltrim b) "" name
where (a,b) = break isSpace $ ltrim $ drop 6 s
f name (Paren _ x) = f name x
f name (ExpTypeSig _ x _) = f name x
f _ _ = Nothing
readSide :: [Decl_] -> (Maybe Exp_, [Note])
readSide = foldl f (Nothing,[])
where f (Nothing,notes) (PatBind _ PWildCard{} Nothing (UnGuardedRhs _ side) Nothing) = (Just side, notes)
f (Nothing,notes) (PatBind _ (fromNamed -> "side") Nothing (UnGuardedRhs _ side) Nothing) = (Just side, notes)
f (side,[]) (PatBind _ (fromNamed -> "note") Nothing (UnGuardedRhs _ note) Nothing) = (side,g note)
f _ x = errorOn x "bad side condition"
g (Lit _ (String _ x _)) = [Note x]
g (List _ xs) = concatMap g xs
g x = case fromApps x of
[con -> Just "IncreasesLaziness"] -> [IncreasesLaziness]
[con -> Just "DecreasesLaziness"] -> [DecreasesLaziness]
[con -> Just "RemovesError",str -> Just a] -> [RemovesError a]
[con -> Just "ValidInstance",str -> Just a,var -> Just b] -> [ValidInstance a b]
_ -> errorOn x "bad note"
con :: Exp_ -> Maybe String
con c@Con{} = Just $ prettyPrint c; con _ = Nothing
var c@Var{} = Just $ prettyPrint c; var _ = Nothing
str c = if isString c then Just $ fromString c else Nothing
-- Note: Foo may be ("","Foo") or ("Foo",""), return both
readFuncs :: Exp_ -> [(String, String)]
readFuncs (App _ x y) = readFuncs x ++ readFuncs y
readFuncs (Lit _ (String _ "" _)) = [("","")]
readFuncs (Var _ (UnQual _ name)) = [("",fromNamed name)]
readFuncs (Var _ (Qual _ (ModuleName _ mod) name)) = [(mod, fromNamed name)]
readFuncs (Con _ (UnQual _ name)) = [(fromNamed name,""),("",fromNamed name)]
readFuncs (Con _ (Qual _ (ModuleName _ mod) name)) = [(mod ++ "." ++ fromNamed name,""),(mod,fromNamed name)]
readFuncs x = errorOn x "bad classification rule"
getNames :: [Pat_] -> Exp_ -> [String]
getNames ps _ | ps /= [] && all isPString ps = map fromPString ps
getNames [] (InfixApp _ lhs op rhs) | opExp op ~= "==>" = map ("Use "++) names
where
lnames = map f $ childrenS lhs
rnames = map f $ childrenS rhs
names = filter (not . isUnifyVar) $ (rnames \\ lnames) ++ rnames
f (Ident _ x) = x
f (Symbol _ x) = x
getNames _ _ = []
errorOn :: (Annotated ast, Pretty (ast S)) => ast S -> String -> b
errorOn val msg = exitMessage $
showSrcLoc (getPointLoc $ ann val) ++
": Error while reading hint file, " ++ msg ++ "\n" ++
prettyPrint val
---------------------------------------------------------------------
-- FIND SETTINGS IN A SOURCE FILE
-- find definitions in a source file
findSettings2 :: ParseFlags -> FilePath -> IO (String, [Setting])
findSettings2 flags file = do
x <- parseModuleEx flags file Nothing
case x of
Left (ParseError sl msg _) ->
return ("-- Parse error " ++ showSrcLoc sl ++ ": " ++ msg, [])
Right m -> do
let xs = concatMap (findSetting $ UnQual an) (moduleDecls m)
s = unlines $ ["-- hints found in " ++ file] ++ map prettyPrint xs ++ ["-- no hints found" | null xs]
r = concatMap (readSetting mempty) xs
return (s,r)
findSetting :: (Name S -> QName S) -> Decl_ -> [Decl_]
findSetting qual (InstDecl _ _ _ (Just xs)) = concatMap (findSetting qual) [x | InsDecl _ x <- xs]
findSetting qual (PatBind _ (PVar _ name) Nothing (UnGuardedRhs _ bod) Nothing) = findExp (qual name) [] bod
findSetting qual (FunBind _ [InfixMatch _ p1 name ps rhs bind]) = findSetting qual $ FunBind an [Match an name (p1:ps) rhs bind]
findSetting qual (FunBind _ [Match _ name ps (UnGuardedRhs _ bod) Nothing]) = findExp (qual name) [] $ Lambda an ps bod
findSetting _ x@InfixDecl{} = [x]
findSetting _ _ = []
-- given a result function name, a list of variables, a body expression, give some hints
findExp :: QName S -> [String] -> Exp_ -> [Decl_]
findExp name vs (Lambda _ ps bod) | length ps2 == length ps = findExp name (vs++ps2) bod
| otherwise = []
where ps2 = [x | PVar_ x <- map view ps]
findExp name vs Var{} = []
findExp name vs (InfixApp _ x dot y) | isDot dot = findExp name (vs++["_hlint"]) $ App an x $ Paren an $ App an y (toNamed "_hlint")
findExp name vs bod = [PatBind an (toNamed "warn") Nothing (UnGuardedRhs an $ InfixApp an lhs (toNamed "==>") rhs) Nothing]
where
lhs = g $ transform f bod
rhs = apps $ Var an name : map snd rep
rep = zip vs $ map (toNamed . return) ['a'..]
f xx | Var_ x <- view xx, Just y <- lookup x rep = y
f (InfixApp _ x dol y) | isDol dol = App an x (paren y)
f x = x
g o@(InfixApp _ _ _ x) | isAnyApp x || isAtom x = o
g o@App{} = o
g o = paren o
| bergmark/hlint | src/Settings.hs | bsd-3-clause | 13,005 | 0 | 19 | 3,113 | 4,317 | 2,195 | 2,122 | 198 | 13 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Dimitri Sabadie
-- License : BSD3
--
-- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- OpenGL log committer.
----------------------------------------------------------------------------
module Quaazar.Render.GL.Log (
-- * OpenGL logs
gllog
) where
import Quaazar.Utils.Log ( LogCommitter(BackendLog) )
-- |OpenGL 'LogCommitter'.
gllog :: LogCommitter
gllog = BackendLog "gl"
| phaazon/quaazar | src/Quaazar/Render/GL/Log.hs | bsd-3-clause | 592 | 0 | 6 | 100 | 54 | 39 | 15 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Afftrack.API.Brand.Merchant
( addBrowserLanguageBlocked
, createMerchant
, getMerchant
, getMerchantBlacklist
)
where
import GHC.Generics
import Data.Aeson
import Control.Applicative
import Network.HTTP.Client
import qualified Data.ByteString.Char8 as BS
import Data.Text
import Afftrack.API.Common
--------------------------------------------------------------------------------
addBrowserLanguageBlocked =
Call "mer_merchant"
"addMerchantBlacklist"
"POST"
[ Param "affiliate_id" True "" -- Required
, Param "merchant_id" True "" -- Required
]
createMerchant =
Call "mer_merchant"
"createMerchant"
"POST"
[ Param "added_by" True "" -- Required
, Param "admin_id" True "" -- Required
, Param "billing_company" True "" -- Required
, Param "billing_email" True "" -- Required
, Param "company" True "" -- Required
, Param "email" True "" -- Required
, Param "address" False ""
, Param "address2" False ""
, Param "aim" False ""
, Param "billing_address" False ""
, Param "billing_address2" False ""
, Param "billing_aim" False ""
, Param "billing_cell" False ""
, Param "billing_city" False ""
, Param "billing_contact" False ""
, Param "billing_country" False ""
, Param "billing_fax" False ""
, Param "billing_phone" False ""
, Param "billing_postal" False ""
, Param "billing_skype" False ""
, Param "billing_state" False ""
, Param "cell" False ""
, Param "city" False ""
, Param "contact" False ""
, Param "country" False ""
, Param "fax" False ""
, Param "mailing_address" False ""
, Param "mailing_address2" False ""
, Param "mailing_city" False ""
, Param "mailing_country" False ""
, Param "mailing_postal" False ""
, Param "mailing_state" False ""
, Param "phone" False ""
, Param "portal_notes" False ""
, Param "portal_notes2" False ""
, Param "portal_notes3" False ""
, Param "portal_password" False ""
, Param "portal_password2" False ""
, Param "portal_password3" False ""
, Param "portal_url" False ""
, Param "portal_url2" False ""
, Param "portal_url3" False ""
, Param "portal_username" False ""
, Param "portal_username2" False ""
, Param "portal_username3" False ""
, Param "postal" False ""
, Param "skype" False ""
, Param "state" False ""
]
getMerchant =
Call "mer_merchant"
"getMerchant"
"GET"
[ Param "limit" False ""
, Param "merchant_id" False ""
, Param "orderby" False ""
, Param "page" False ""
, Param "sort" False ""
, Param "status" False ""
]
getMerchantBlacklist =
Call "mer_merchant"
"getMerchant"
"GET"
[ Param "merchant_id" True "" ]
| kelecorix/api-afftrack | src/Afftrack/API/Brand/Merchant.hs | bsd-3-clause | 3,404 | 0 | 7 | 1,254 | 699 | 365 | 334 | 86 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module LLVM.General.Quote.Test.InlineAssembly where
import Test.Tasty
import Test.Tasty.HUnit
import Test.HUnit
import LLVM.General.Quote.LLVM
import LLVM.General.AST
import LLVM.General.AST.InlineAssembly as IA
import qualified LLVM.General.AST.Linkage as L
import qualified LLVM.General.AST.Visibility as V
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Global as G
tests = testGroup "InlineAssembly" [
testCase "expression" $ do
let ast = Module "<string>" Nothing Nothing [
GlobalDefinition $
functionDefaults {
G.returnType = IntegerType 32,
G.name = Name "foo",
G.parameters = ([Parameter (IntegerType 32) (Name "x") []],False),
G.basicBlocks = [
BasicBlock (Name "entry") [
UnName 0 := Call {
isTailCall = False,
callingConvention = CC.C,
returnAttributes = [],
function = Left $ InlineAssembly {
IA.type' = FunctionType (IntegerType 32) [IntegerType 32] False,
assembly = "bswap $0",
constraints = "=r,r",
hasSideEffects = False,
alignStack = False,
dialect = ATTDialect
},
arguments = [
(LocalReference (Name "x"), [])
],
functionAttributes = [],
metadata = []
}
] (
Do $ Ret (Just (LocalReference (UnName 0))) []
)
]
}
]
s = [llmod|; ModuleID = '<string>'
define i32 @foo(i32 %x) {
entry:
%0 = call i32 asm "bswap $0", "=r,r"(i32 %x)
ret i32 %0
}|]
s @?= ast,
testCase "module" $ do
let ast = Module "<string>" Nothing Nothing [
ModuleInlineAssembly "foo",
ModuleInlineAssembly "bar",
GlobalDefinition $ globalVariableDefaults {
G.name = UnName 0,
G.type' = IntegerType 32
}
]
s = [llmod|; ModuleID = '<string>'
module asm "foo"
module asm "bar"
@0 = external global i32|]
s @?= ast
] | tvh/llvm-general-quote | test/LLVM/General/Quote/Test/InlineAssembly.hs | bsd-3-clause | 2,795 | 0 | 29 | 1,321 | 509 | 301 | 208 | 51 | 1 |
{-
(c) The AQUA Project, Glasgow University, 1993-1998
\section{Common subexpression}
-}
{-# LANGUAGE CPP #-}
module CSE (cseProgram) where
#include "HsVersions.h"
import CoreSubst
import Var ( Var )
import Id ( Id, idType, idInlineActivation, zapIdOccInfo, zapIdUsageInfo )
import CoreUtils ( mkAltExpr
, exprIsTrivial
, stripTicksE, stripTicksT, stripTicksTopE, mkTick, mkTicks )
import Type ( tyConAppArgs )
import CoreSyn
import Outputable
import BasicTypes ( isAlwaysActive )
import TrieMap
import Data.List
{-
Simple common sub-expression
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we see
x1 = C a b
x2 = C x1 b
we build up a reverse mapping: C a b -> x1
C x1 b -> x2
and apply that to the rest of the program.
When we then see
y1 = C a b
y2 = C y1 b
we replace the C a b with x1. But then we *dont* want to
add x1 -> y1 to the mapping. Rather, we want the reverse, y1 -> x1
so that a subsequent binding
y2 = C y1 b
will get transformed to C x1 b, and then to x2.
So we carry an extra var->var substitution which we apply *before* looking up in the
reverse mapping.
Note [Shadowing]
~~~~~~~~~~~~~~~~
We have to be careful about shadowing.
For example, consider
f = \x -> let y = x+x in
h = \x -> x+x
in ...
Here we must *not* do CSE on the inner x+x! The simplifier used to guarantee no
shadowing, but it doesn't any more (it proved too hard), so we clone as we go.
We can simply add clones to the substitution already described.
Note [Case binders 1]
~~~~~~~~~~~~~~~~~~~~~~
Consider
f = \x -> case x of wild {
(a:as) -> case a of wild1 {
(p,q) -> ...(wild1:as)...
Here, (wild1:as) is morally the same as (a:as) and hence equal to wild.
But that's not quite obvious. In general we want to keep it as (wild1:as),
but for CSE purpose that's a bad idea.
So we add the binding (wild1 -> a) to the extra var->var mapping.
Notice this is exactly backwards to what the simplifier does, which is
to try to replaces uses of 'a' with uses of 'wild1'
Note [Case binders 2]
~~~~~~~~~~~~~~~~~~~~~~
Consider
case (h x) of y -> ...(h x)...
We'd like to replace (h x) in the alternative, by y. But because of
the preceding [Note: case binders 1], we only want to add the mapping
scrutinee -> case binder
to the reverse CSE mapping if the scrutinee is a non-trivial expression.
(If the scrutinee is a simple variable we want to add the mapping
case binder -> scrutinee
to the substitution
Note [CSE for INLINE and NOINLINE]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are some subtle interactions of CSE with functions that the user
has marked as INLINE or NOINLINE. (Examples from Roman Leshchinskiy.)
Consider
yes :: Int {-# NOINLINE yes #-}
yes = undefined
no :: Int {-# NOINLINE no #-}
no = undefined
foo :: Int -> Int -> Int {-# NOINLINE foo #-}
foo m n = n
{-# RULES "foo/no" foo no = id #-}
bar :: Int -> Int
bar = foo yes
We do not expect the rule to fire. But if we do CSE, then we risk
getting yes=no, and the rule does fire. Actually, it won't because
NOINLINE means that 'yes' will never be inlined, not even if we have
yes=no. So that's fine (now; perhaps in the olden days, yes=no would
have substituted even if 'yes' was NOINLINE.
But we do need to take care. Consider
{-# NOINLINE bar #-}
bar = <rhs> -- Same rhs as foo
foo = <rhs>
If CSE produces
foo = bar
then foo will never be inlined to <rhs> (when it should be, if <rhs>
is small). The conclusion here is this:
We should not add
<rhs> :-> bar
to the CSEnv if 'bar' has any constraints on when it can inline;
that is, if its 'activation' not always active. Otherwise we
might replace <rhs> by 'bar', and then later be unable to see that it
really was <rhs>.
Note that we do not (currently) do CSE on the unfolding stored inside
an Id, even if is a 'stable' unfolding. That means that when an
unfolding happens, it is always faithful to what the stable unfolding
originally was.
Note [CSE for case expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
case f x of y { pat -> ...let y = f x in ... }
Then we can CSE the inner (f x) to y. In fact 'case' is like a strict
let-binding, and we can use cseRhs for dealing with the scrutinee.
************************************************************************
* *
\section{Common subexpression}
* *
************************************************************************
-}
cseProgram :: CoreProgram -> CoreProgram
cseProgram binds = snd (mapAccumL cseBind emptyCSEnv binds)
cseBind :: CSEnv -> CoreBind -> (CSEnv, CoreBind)
cseBind env (NonRec b e)
= (env2, NonRec b'' e')
where
(env1, b') = addBinder env b
(env2, (b'', e')) = cseRhs env1 (b',e)
cseBind env (Rec pairs)
= (env2, Rec pairs')
where
(bs,es) = unzip pairs
(env1, bs') = addRecBinders env bs
(env2, pairs') = mapAccumL cseRhs env1 (bs' `zip` es)
cseRhs :: CSEnv -> (OutBndr, InExpr) -> (CSEnv, (OutBndr, OutExpr))
cseRhs env (id',rhs)
= case lookupCSEnv env rhs'' of
Nothing
| always_active -> (extendCSEnv env rhs' id', (zapped_id, rhs'))
| otherwise -> (env, (id', rhs'))
Just id
| always_active -> (extendCSSubst env id' id, (id', mkTicks ticks $ Var id))
| otherwise -> (env, (id', mkTicks ticks $ Var id))
-- In the Just case, we have
-- x = rhs
-- ...
-- x' = rhs
-- We are replacing the second binding with x'=x
-- and so must record that in the substitution so
-- that subsequent uses of x' are replaced with x,
-- See Trac #5996
where
zapped_id = zapIdUsageInfo id'
-- Putting the Id into the environment makes it possible that
-- it'll become shared more than it is now, which would
-- invalidate (the usage part of) its demand info. This caused
-- Trac #100218.
-- Easiest thing is to zap the usage info; subsequently
-- performing late demand-analysis will restore it. Don't zap
-- the strictness info; it's not necessary to do so, and losing
-- it is bad for performance if you don't do late demand
-- analysis
rhs' = cseExpr env rhs
ticks = stripTicksT tickishFloatable rhs'
rhs'' = stripTicksE tickishFloatable rhs'
-- We don't want to lose the source notes when a common sub
-- expression gets eliminated. Hence we push all (!) of them on
-- top of the replaced sub-expression. This is probably not too
-- useful in practice, but upholds our semantics.
always_active = isAlwaysActive (idInlineActivation id')
-- See Note [CSE for INLINE and NOINLINE]
tryForCSE :: CSEnv -> InExpr -> OutExpr
tryForCSE env expr
| exprIsTrivial expr' = expr' -- No point
| Just smaller <- lookupCSEnv env expr'' = foldr mkTick (Var smaller) ticks
| otherwise = expr'
where
expr' = cseExpr env expr
expr'' = stripTicksE tickishFloatable expr'
ticks = stripTicksT tickishFloatable expr'
cseExpr :: CSEnv -> InExpr -> OutExpr
cseExpr env (Type t) = Type (substTy (csEnvSubst env) t)
cseExpr env (Coercion c) = Coercion (substCo (csEnvSubst env) c)
cseExpr _ (Lit lit) = Lit lit
cseExpr env (Var v) = lookupSubst env v
cseExpr env (App f a) = App (cseExpr env f) (tryForCSE env a)
cseExpr env (Tick t e) = Tick t (cseExpr env e)
cseExpr env (Cast e co) = Cast (cseExpr env e) (substCo (csEnvSubst env) co)
cseExpr env (Lam b e) = let (env', b') = addBinder env b
in Lam b' (cseExpr env' e)
cseExpr env (Let bind e) = let (env', bind') = cseBind env bind
in Let bind' (cseExpr env' e)
cseExpr env (Case scrut bndr ty alts) = Case scrut' bndr''' ty alts'
where
alts' = cseAlts env2 scrut' bndr bndr'' alts
(env1, bndr') = addBinder env bndr
bndr'' = zapIdOccInfo bndr'
-- The swizzling from Note [Case binders 2] may
-- cause a dead case binder to be alive, so we
-- play safe here and bring them all to life
(env2, (bndr''', scrut')) = cseRhs env1 (bndr'', scrut)
-- Note [CSE for case expressions]
cseAlts :: CSEnv -> OutExpr -> InBndr -> InBndr -> [InAlt] -> [OutAlt]
cseAlts env scrut' bndr bndr' alts
= map cse_alt alts
where
scrut'' = stripTicksTopE tickishFloatable scrut'
(con_target, alt_env)
= case scrut'' of
Var v' -> (v', extendCSSubst env bndr v') -- See Note [Case binders 1]
-- map: bndr -> v'
_ -> (bndr', extendCSEnv env scrut' bndr') -- See Note [Case binders 2]
-- map: scrut' -> bndr'
arg_tys = tyConAppArgs (idType bndr)
cse_alt (DataAlt con, args, rhs)
| not (null args)
-- Don't try CSE if there are no args; it just increases the number
-- of live vars. E.g.
-- case x of { True -> ....True.... }
-- Don't replace True by x!
-- Hence the 'null args', which also deal with literals and DEFAULT
= (DataAlt con, args', tryForCSE new_env rhs)
where
(env', args') = addBinders alt_env args
new_env = extendCSEnv env' con_expr con_target
con_expr = mkAltExpr (DataAlt con) args' arg_tys
cse_alt (con, args, rhs)
= (con, args', tryForCSE env' rhs)
where
(env', args') = addBinders alt_env args
{-
************************************************************************
* *
\section{The CSE envt}
* *
************************************************************************
-}
type InExpr = CoreExpr -- Pre-cloning
type InBndr = CoreBndr
type InAlt = CoreAlt
type OutExpr = CoreExpr -- Post-cloning
type OutBndr = CoreBndr
type OutAlt = CoreAlt
data CSEnv = CS { cs_map :: CoreMap (OutExpr, Id) -- Key, value
, cs_subst :: Subst }
emptyCSEnv :: CSEnv
emptyCSEnv = CS { cs_map = emptyCoreMap, cs_subst = emptySubst }
lookupCSEnv :: CSEnv -> OutExpr -> Maybe Id
lookupCSEnv (CS { cs_map = csmap }) expr
= case lookupCoreMap csmap expr of
Just (_,e) -> Just e
Nothing -> Nothing
extendCSEnv :: CSEnv -> OutExpr -> Id -> CSEnv
extendCSEnv cse expr id
= cse { cs_map = extendCoreMap (cs_map cse) sexpr (sexpr,id) }
where sexpr = stripTicksE tickishFloatable expr
csEnvSubst :: CSEnv -> Subst
csEnvSubst = cs_subst
lookupSubst :: CSEnv -> Id -> OutExpr
lookupSubst (CS { cs_subst = sub}) x = lookupIdSubst (text "CSE.lookupSubst") sub x
extendCSSubst :: CSEnv -> Id -> Id -> CSEnv
extendCSSubst cse x y = cse { cs_subst = extendIdSubst (cs_subst cse) x (Var y) }
addBinder :: CSEnv -> Var -> (CSEnv, Var)
addBinder cse v = (cse { cs_subst = sub' }, v')
where
(sub', v') = substBndr (cs_subst cse) v
addBinders :: CSEnv -> [Var] -> (CSEnv, [Var])
addBinders cse vs = (cse { cs_subst = sub' }, vs')
where
(sub', vs') = substBndrs (cs_subst cse) vs
addRecBinders :: CSEnv -> [Id] -> (CSEnv, [Id])
addRecBinders cse vs = (cse { cs_subst = sub' }, vs')
where
(sub', vs') = substRecBndrs (cs_subst cse) vs
| forked-upstream-packages-for-ghcjs/ghc | compiler/simplCore/CSE.hs | bsd-3-clause | 12,445 | 0 | 12 | 4,082 | 1,991 | 1,077 | 914 | 117 | 3 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE LiberalTypeSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# OPTIONS_GHC -Wall -fno-warn-missing-signatures #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Edward Kmett 2014
-- License : BSD3
-- Maintainer: Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
--------------------------------------------------------------------
module Hask.Foldable where
import qualified Control.Applicative as Base
import qualified Data.Foldable as Base
import qualified Data.Functor as Base
import qualified Data.Monoid as Base
import qualified Data.Traversable as Base
import Hask.Core
import Hask.Power
-- * Foldable
class Functor f => Foldable (f :: i -> j) where
foldMap :: Monoid (m :: j) => (a ⋔ m) ~> (f a ⋔ m)
newtype WrapMonoid m = WrapMonoid { runWrapMonoid :: m }
instance Monoid m => Base.Monoid (WrapMonoid m) where
mempty = WrapMonoid (one ())
mappend (WrapMonoid a) (WrapMonoid b) = WrapMonoid (mult (a, b))
foldMapHask :: (Base.Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMapHask f = runWrapMonoid . Base.foldMap (WrapMonoid . f)
instance Foldable [] where foldMap = foldMapHask
instance Foldable Maybe where foldMap = foldMapHask
instance Foldable (,) where
foldMap = Nat $ \f -> Lift $ runPower f . fst
instance Foldable ((,) e) where foldMap = lmap snd
instance Foldable Either where
foldMap = Nat $ \f -> Lift $ (runPower f ||| \ _ -> transport one (Const ()))
instance Foldable (Either a) where foldMap = foldMapHask
instance Foldable ((&) e) where foldMap = lmap snd
-- TODO: instance Foldable (Lift1 (,))
instance Foldable (Lift1 (,) e) where foldMap = lmap snd
-- TODO: instance Foldable (Lift2 (Lift1 (,)))
instance Foldable (Lift2 (Lift1 (,)) e) where foldMap = lmap snd
-- TODO: instance Foldable (Lift1 Either)
instance Foldable (Lift1 Either e) where
foldMap = Nat $ \ f -> Lift $ \case
Lift (Left _) -> transport one (Const ())
Lift (Right e) -> lower f e
-- TODO: instance Foldable (Lift2 (Lift1 Either))
instance Foldable (Lift2 (Lift1 Either) e) where
foldMap = nat2 $ \ (Lift2 (Lift f)) -> Lift2 $ Lift $ \case
Lift2 (Lift (Left _)) -> transport2 one (Const2 (Const ()))
Lift2 (Lift (Right e)) -> f e
-- TODO: instance Foldable Compose1 -- we don't have sufficient Power levels
-- * Traversable
class Functor f => Traversable f where
-- (Rel a ~> m b) -> f a ~> m (f b) ?
traverse :: Monoidal m => (a ~> m b) -> f a ~> m (f b)
newtype WrapMonoidal f a = WrapMonoidal { runWrapMonoidal :: f a }
_WrapMonoidal = dimap runWrapMonoidal WrapMonoidal
instance Functor f => Base.Functor (WrapMonoidal f) where
fmap f (WrapMonoidal m) = WrapMonoidal (fmap f m)
instance Monoidal f => Base.Applicative (WrapMonoidal f) where
pure a = WrapMonoidal (return a)
WrapMonoidal f <*> WrapMonoidal g = WrapMonoidal $ ap f g
fmapDefault f = get _Id . traverse (beget _Id . f)
foldMapDefault f = get _Const . traverse (beget _Const . f)
traverseHask :: (Base.Traversable f, Monoidal m) => (a -> m b) -> f a -> m (f b)
traverseHask f = runWrapMonoidal . Base.traverse (WrapMonoidal . f)
instance Traversable [] where traverse = traverseHask
instance Traversable Maybe where traverse = traverseHask
instance Traversable (Either a) where traverse = traverseHask
instance Traversable ((,) e) where traverse = traverseHask
| ekmett/hask | old/src/Hask/Foldable.hs | bsd-3-clause | 3,968 | 0 | 17 | 688 | 1,167 | 621 | 546 | 72 | 1 |
module Network.Protocol.Uri.Chars
( unreserved
, genDelims
, subDelims
) where
import Data.Char
-- 2.3. Unreserved Characters
unreserved :: Char -> Bool
unreserved c = isAlphaNum c || elem c "-._~"
-- 2.2. Reserved Characters
genDelims :: Char -> Bool
genDelims = flip elem ":/?#[]@"
subDelims :: Char -> Bool
subDelims = flip elem "!$&'()*+,;="
| sebastiaanvisser/salvia-protocol | src/Network/Protocol/Uri/Chars.hs | bsd-3-clause | 361 | 0 | 6 | 69 | 93 | 52 | 41 | 11 | 1 |
{-# OPTIONS_JHC -fno-prelude #-}
module Data.Ix ( Ix(range, index, inRange, rangeSize) ) where
import Jhc.Int
import Jhc.Enum
import Jhc.Order
import Jhc.Basics
import Jhc.Num
import Jhc.Tuples
import Jhc.IO
class Ord a => Ix a where
range :: (a,a) -> [a]
index :: (a,a) -> a -> Int
inRange :: (a,a) -> a -> Bool
rangeSize :: (a,a) -> Int
rangeSize b@(l,h) = case range b of
[] -> zero
_ -> index b h `plus` one
-- NB: replacing "null (range b)" by "not (l <= h)"
-- fails if the bounds are tuples. For example,
-- (1,2) <= (2,1)
-- but the range is nevertheless empty
-- range ((1,2),(2,1)) = []
instance Ix Char where
range (m,n) = [m..n]
index b@(c,c') ci
| inRange b ci = fromEnum ci `minus` fromEnum c
| otherwise = error "Ix.index: Index out of range."
inRange (c,c') i = c <= i && i <= c'
instance Ix Int where
range (m,n) = [m..n]
index b@(m,n) i
| inRange b i = i `minus` m
| otherwise = error "Ix.index: Index out of range."
inRange (m,n) i = m <= i && i <= n
instance (Ix a, Ix b) => Ix (a,b) where
range ((l,l'),(u,u')) = [(i,i') | i <- range (l,u), i' <- range (l',u')]
index ((l,l'),(u,u')) (i,i') = index (l,u) i * rangeSize (l',u') + index (l',u') i'
inRange ((l,l'),(u,u')) (i,i') = inRange (l,u) i && inRange (l',u') i'
--instance Ix Integer where
-- range (m,n) = [m..n]
-- index b@(m,n) i
-- | inRange b i = fromInteger (i - m)
-- | otherwise = error "Ix.index: Index out of range."
-- inRange (m,n) i = m <= i && i <= n
instance Ix Bool where
range (m,n) = [m..n]
index b@(c,c') ci
| inRange b ci = fromEnum ci `minus` fromEnum c
| otherwise = error "Ix.index: 'Bool' Index out of range."
inRange (c,c') i = c <= i && i <= c'
instance Ix Ordering where
range (m,n) = [m..n]
index b@(c,c') ci
| inRange b ci = fromEnum ci `minus` fromEnum c
| otherwise = error "Ix.index: 'Ordering' Index out of range."
inRange (c,c') i = c <= i && i <= c'
-- instance (Ix a,Ix b) => Ix (a, b) -- as derived, for all tuples
-- instance Ix Bool -- as derived
-- instance Ix Ordering -- as derived
-- instance Ix () -- as derived
| dec9ue/jhc_copygc | lib/haskell-extras/Data/Ix.hs | gpl-2.0 | 2,388 | 8 | 11 | 759 | 877 | 487 | 390 | 48 | 0 |
predecessor n :: Int -> Int
predecessor n
| n>0 = n-1
| n==0 = 0
{- predecessor n :: Num a => a -> a -}
| roberth/uu-helium | test/thompson/Thompson18.hs | gpl-3.0 | 116 | 2 | 8 | 39 | 49 | 23 | 26 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, NamedFieldPuns,
DeriveDataTypeable, FlexibleInstances, ScopedTypeVariables #-}
module Graphics.Qt.CPPWrapper (
-- * globale
qtVersion,
qtOpenUrl,
-- * QApplication
QApplication,
withQApplication,
execQApplication,
processEventsQApplication,
quitQApplication,
-- * MainWindow
MainWindow,
paintEngineTypeMainWindow,
withMainWindow,
setWindowTitle,
setWindowIcon,
setFullscreenMainWindow,
showMainWindow,
resizeMainWindow,
updateMainWindow,
setDrawingCallbackMainWindow,
setKeyCallbackMainWindow,
setArrowAutoRepeat,
setRenderingLooped,
-- * QPainter
QPainter,
newQPainter,
destroyQPainter,
sizeQPainter,
resetMatrix,
withClearCompositionMode,
translate,
rotate,
scale,
setPenColor,
withClipRect,
fillRect,
drawCircle,
drawLine,
drawText,
drawPixmap,
drawPixmapInMemory,
drawPixmapFragments,
drawPoint,
drawRect,
-- * QTransform
QTransform,
withMatrix,
setMatrix,
withQIcon,
addFileQIcon,
-- * QPixmap
QPixmap,
newQPixmap,
newQPixmapEmpty,
saveQPixmap,
sizeQPixmap,
toImageQPixmap,
copyQPixmap,
-- * QImage
QImage,
destroyQImage,
saveQImage,
sizeQImage,
colorCountQImage,
colorQImage,
setColorQImage,
pixelQImage,
setPixelQImage,
fromImageQPixmap,
-- * QRgb
QRgb,
qRgbToColor,
colorToQRgb,
-- * QClipboard
textQClipboard,
-- * GUI-thread
postGUI,
postGUIBlocking,
) where
import Data.Data
import Data.Abelian
import Data.Set (Set)
import Data.Maybe
import qualified Data.ByteString as SBS
import qualified Data.ByteString.Unsafe as SBS
import Text.Logging
import Text.Printf
import Control.Monad.CatchIO
import Control.Monad.State (evalStateT, get, put)
import Control.Concurrent.MVar
import Foreign (Ptr, nullPtr, FunPtr, freeHaskellFunPtr)
import Foreign.C.String
import Foreign.C.Types
import Foreign.ForeignPtr
import qualified Foreign.Concurrent (newForeignPtr)
import System.Directory
import System.Environment
import System.IO.Unsafe
import Graphics.Qt.Types
import Graphics.Qt.Events
import Utils
-- ** Globals
qtVersion :: IO String
qtVersion = cppQtVersion >>= peekCString
foreign import ccall "qtVersion" cppQtVersion :: IO CString
qtOpenUrl :: String -> IO Bool
qtOpenUrl s = withCString s cppQtOpenUrl
foreign import ccall "qtOpenUrl" cppQtOpenUrl :: CString -> IO Bool
-- ** Objects
-- * QApplication
data QApplication
foreign import ccall "newQApplication" cppNewQApplication :: CString -> IO (Ptr QApplication)
newQApplication :: IO (Ptr QApplication)
newQApplication = do
progName <- getProgName
cs <- newCString progName
cppNewQApplication cs
foreign import ccall destroyQApplication :: Ptr QApplication -> IO ()
withQApplication :: MonadCatchIO m => (Ptr QApplication -> m a) -> m a
withQApplication = bracket (io newQApplication) (io . destroyQApplication)
foreign import ccall execQApplication :: Ptr QApplication -> IO QtInt
foreign import ccall quitQApplication :: IO ()
foreign import ccall processEventsQApplication :: Ptr QApplication -> IO ()
setApplicationName :: Ptr QApplication -> String -> IO ()
setApplicationName ptr s = withCString s (cppSetApplicationName ptr)
foreign import ccall "setApplicationName" cppSetApplicationName :: Ptr QApplication -> CString -> IO ()
-- * MainWindow
data MainWindow
newMainWindow :: Int -> Int -> Int -> IO (Ptr MainWindow)
newMainWindow swapInterval width height = do
r <- cppNewMainWindow swapInterval width height
putMVar _mainWindowRef r
cCallback <- wrapDrawingCallback _stdDrawingCallback
cppSetDrawingCallbackMainWindow r cCallback
return r
foreign import ccall "newMainWindow" cppNewMainWindow ::
Int -> Int -> Int -> IO (Ptr MainWindow)
foreign import ccall destroyMainWindow :: Ptr MainWindow -> IO ()
withMainWindow :: MonadCatchIO m => Int -> Int -> Int -> (Ptr MainWindow -> m a) -> m a
withMainWindow swapInterval width height =
bracket (io $ newMainWindow swapInterval width height) (io . destroyMainWindow)
foreign import ccall setWindowIcon :: Ptr MainWindow -> Ptr QIcon -> IO ()
foreign import ccall setRenderingLooped :: Ptr MainWindow -> Bool -> IO ()
foreign import ccall setArrowAutoRepeat :: Ptr MainWindow -> Bool -> IO ()
foreign import ccall updateMainWindow :: Ptr MainWindow -> IO ()
-- | sets the MainWindow fullscreen mode.
-- In fullscreen mode the mouse cursor is hidden
foreign import ccall setFullscreenMainWindow :: Ptr MainWindow -> Bool -> IO ()
foreign import ccall resizeMainWindow :: Ptr MainWindow -> QtInt -> QtInt -> IO ()
foreign import ccall "setWindowTitle" cppSetWindowTitle ::
Ptr MainWindow -> CString -> IO ()
setWindowTitle :: Ptr MainWindow -> String -> IO ()
setWindowTitle ptr t = withCString t (cppSetWindowTitle ptr)
foreign import ccall showMainWindow :: Ptr MainWindow -> IO ()
foreign import ccall hideMainWindow :: Ptr MainWindow -> IO ()
foreign import ccall directRenderingMainWindow :: Ptr MainWindow -> IO Bool
paintEngineTypeMainWindow :: Ptr MainWindow -> IO PaintEngineType
paintEngineTypeMainWindow ptr = do
i <- cppPaintEngineTypeMainWindow ptr
return $ int2PaintEngineType i
foreign import ccall "paintEngineTypeMainWindow" cppPaintEngineTypeMainWindow ::
Ptr MainWindow -> IO QtInt
data PaintEngineType
= X11
| CoreGraphics
| OpenGL
| OpenGL2
| UnknownPaintEngine QtInt
deriving Show
int2PaintEngineType :: QtInt -> PaintEngineType
int2PaintEngineType 0 = X11
-- int2PaintEngineType 1 = Windows
int2PaintEngineType 3 = CoreGraphics
int2PaintEngineType 7 = OpenGL
int2PaintEngineType 14 = OpenGL2
int2PaintEngineType x = UnknownPaintEngine x
-- drawing callbacks (MainWindow)
foreign import ccall "setDrawingCallbackMainWindow" cppSetDrawingCallbackMainWindow ::
Ptr MainWindow -> FunPtr (Ptr QPainter -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapDrawingCallback ::
(Ptr QPainter -> IO ()) -> IO (FunPtr (Ptr QPainter -> IO ()))
-- | Sets the drawing callback.
setDrawingCallbackMainWindow ::
Ptr MainWindow -> Maybe (Ptr QPainter -> IO ()) -> IO ()
setDrawingCallbackMainWindow ptr cb = do
ignore $ swapMVar _drawingCallback $ toCB cb
updateMainWindow ptr
where
toCB :: Maybe (Ptr QPainter -> IO ()) -> (Ptr QPainter -> IO ())
toCB = fromMaybe (const $ return ())
_drawingCallback :: MVar (Ptr QPainter -> IO ())
_drawingCallback = unsafePerformIO $ newMVar (const $ return ())
_stdDrawingCallback :: Ptr QPainter -> IO ()
_stdDrawingCallback ptr = do
callback <- readMVar _drawingCallback
callback ptr
-- event callbacks
foreign import ccall "setKeyCallbackMainWindow" cppSetKeyCallbackMainWindow ::
Ptr MainWindow -> FunPtr (Int -> Ptr QKeyEvent -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapKeyCallback ::
(Int -> Ptr QKeyEvent -> IO ()) -> IO (FunPtr (Int -> Ptr QKeyEvent -> IO ()))
-- int being an event code:
-- 0 - press key event (with the QKeyEvent)
-- 1 - release key event (with the QKeyEvent)
-- 2 - focus out of window event
-- 3 - window close event (from the window manager)
setKeyCallbackMainWindow :: Ptr MainWindow -> (QtEvent -> IO ()) -> IO ()
setKeyCallbackMainWindow ptr cmd =
wrapKeyCallback preWrap >>=
cppSetKeyCallbackMainWindow ptr
where
preWrap :: (Int -> Ptr QKeyEvent -> IO ())
preWrap n ptr = case n of
0 -> do
(key, text, modifiers) <- peekQKeyEvent
cmd $ KeyPress key text modifiers
1 -> do
(key, text, modifiers) <- peekQKeyEvent
cmd $ KeyRelease key text modifiers
2 -> cmd FocusOut
3 -> cmd CloseWindow
where
peekQKeyEvent :: IO (Key, String, Set QKeyboardModifier)
peekQKeyEvent = do
key <- keyQKeyEvent ptr
text <- textQKeyEvent ptr
modifierFlags <- modifiersQKeyEvent ptr
return (translateQtKey key, text, marshallKeyboardModifiers modifierFlags)
-- * QPainter
data QPainter
deriving Typeable
-- | for rendering into pixmaps.
newQPainter :: ForeignPtr QPixmap -> IO (Ptr QPainter)
newQPainter fp = withForeignPtr fp cppNewQPainter
foreign import ccall "newQPainter" cppNewQPainter :: Ptr QPixmap -> IO (Ptr QPainter)
foreign import ccall destroyQPainter :: Ptr QPainter -> IO ()
foreign import ccall "fillRect" cppEraseRect ::
Ptr QPainter -> QtReal -> QtReal -> QtReal -> QtReal -> QtInt -> QtInt -> QtInt -> QtInt -> IO ()
fillRect :: Ptr QPainter -> Position QtReal -> Size QtReal -> Color -> IO ()
fillRect ptr (Position x y) (Size w h) (QtColor r g b a) =
cppEraseRect
ptr x y w h r g b a
foreign import ccall resetMatrix :: Ptr QPainter -> IO ()
-- | seems to be buggy on some systems...
withClearCompositionMode :: Ptr QPainter -> IO a -> IO a
withClearCompositionMode ptr cmd = do
bracket start (const stop) (const $ cmd)
where
start = setCompositionModeClear ptr
stop = setCompositionModeDefault ptr
foreign import ccall setCompositionModeDefault :: Ptr QPainter -> IO ()
foreign import ccall setCompositionModeClear :: Ptr QPainter -> IO ()
foreign import ccall rotate :: Ptr QPainter -> QtReal -> IO ()
translate :: Ptr QPainter -> Position QtReal -> IO ()
translate ptr (Position x y) =
cppTranslate ptr x y
foreign import ccall "translate" cppTranslate :: Ptr QPainter -> QtReal -> QtReal -> IO ()
foreign import ccall scale :: Ptr QPainter -> QtReal -> QtReal -> IO ()
drawPixmap :: Ptr QPainter -> Position QtReal -> ForeignPtr QPixmap -> IO ()
drawPixmap ptr (Position x y) fp =
withForeignPtr fp $ cppDrawPixmap ptr x y
foreign import ccall "drawPixmap" cppDrawPixmap :: Ptr QPainter -> QtReal -> QtReal -> Ptr QPixmap -> IO ()
drawPixmapInMemory :: Ptr QPainter -> Position QtReal -> ForeignPtr QPixmap -> IO ()
drawPixmapInMemory ptr (Position x y) fp =
withForeignPtr fp $ cppDrawPixmapInMemory ptr x y
foreign import ccall "drawPixmapInMemory" cppDrawPixmapInMemory :: Ptr QPainter -> QtReal -> QtReal -> Ptr QPixmap -> IO ()
drawPoint :: Ptr QPainter -> Position QtInt -> IO ()
drawPoint ptr (Position x y) =
cppDrawPoint ptr x y
foreign import ccall "drawPoint" cppDrawPoint :: Ptr QPainter -> QtInt -> QtInt -> IO ()
-- | sets the pen color and thickness
setPenColor :: Ptr QPainter -> Color -> QtInt -> IO ()
setPenColor ptr (QtColor r g b a) thickness =
cppSetPenColor ptr r g b a thickness
foreign import ccall "setPenColor" cppSetPenColor :: Ptr QPainter -> QtInt -> QtInt -> QtInt -> QtInt -> QtInt -> IO ()
setClipRect :: Ptr QPainter -> Position Double -> Size Double -> IO ()
setClipRect ptr (Position x y) (Size w h) =
cppSetClipRect ptr x y w h
foreign import ccall "setClipRect" cppSetClipRect :: Ptr QPainter ->
QtReal -> QtReal -> QtReal -> QtReal -> IO ()
foreign import ccall setClipping :: Ptr QPainter -> Bool -> IO ()
withClipRect :: Ptr QPainter -> Position Double -> Size Double -> IO a -> IO a
withClipRect ptr pos size cmd =
bracket start (const stop) (const cmd)
where
start = setClipRect ptr pos size
stop = setClipping ptr False
foreign import ccall setFontSize :: Ptr QPainter -> QtInt -> IO ()
drawRect :: Ptr QPainter -> Position QtReal -> Size QtReal -> IO ()
drawRect ptr (Position x y) (Size w h) = cppDrawRect ptr x y w h
foreign import ccall "drawRect" cppDrawRect :: Ptr QPainter -> QtReal -> QtReal -> QtReal -> QtReal -> IO ()
drawLine :: Ptr QPainter -> Position QtReal -> Position QtReal -> IO ()
drawLine ptr (Position a b) (Position x y) =
cppDrawLine ptr a b x y
foreign import ccall "drawLine" cppDrawLine :: Ptr QPainter -> QtReal -> QtReal -> QtReal -> QtReal -> IO ()
-- | draws a circle using drawEllipse
drawCircle :: Ptr QPainter -> Position QtReal -> QtReal -> IO ()
drawCircle ptr center radius =
drawEllipse ptr p s
where
p = center -~ Position radius radius
s = fmap (* 2) $ Size radius radius
drawEllipse :: Ptr QPainter -> Position QtReal -> Size QtReal -> IO ()
drawEllipse ptr (Position x y) (Size w h) =
cppDrawEllipse ptr x y w h
foreign import ccall "drawEllipse" cppDrawEllipse :: Ptr QPainter -> QtReal -> QtReal -> QtReal -> QtReal -> IO ()
drawText :: Ptr QPainter -> Position QtReal -> Bool -> String -> IO ()
drawText ptr (Position x y) highlighted s =
withCString s $
cppDrawText ptr x y highlighted
foreign import ccall "drawText" cppDrawText :: Ptr QPainter -> QtReal -> QtReal -> Bool -> CString -> IO ()
sizeQPainter :: Ptr QPainter -> IO (Size QtReal)
sizeQPainter ptr = do
width <- widthQPainter ptr
height <- heightQPainter ptr
return $ fmap fromIntegral (Size width height)
foreign import ccall widthQPainter :: Ptr QPainter -> IO QtInt
foreign import ccall heightQPainter :: Ptr QPainter -> IO QtInt
-- * drawPixmapFragment
drawPixmapFragments :: Ptr QPainter -> [(Position QtReal, QtReal)]
-> Ptr QPixmap -> IO ()
drawPixmapFragments ptr fragments pixmap = flip evalStateT 0 $ do
forM_ fragments $ \ ((Position x y), angle) -> do
i <- get
io $ writePixmapFragmentArray i x y angle pixmap
put (succ i)
n <- get
io $ do
resetMatrix ptr
cppDrawPixmapFragments ptr n pixmap
foreign import ccall writePixmapFragmentArray :: Int -> QtReal -> QtReal -> QtReal
-> Ptr QPixmap -> IO ()
foreign import ccall "drawPixmapFragments" cppDrawPixmapFragments :: Ptr QPainter -> Int -> Ptr QPixmap -> IO ()
-- * QTransform
data QTransform
foreign import ccall "&destroyQTransform" destroyQTransform :: FinalizerPtr QTransform
withMatrix :: Ptr QPainter -> (Ptr QTransform -> IO a) -> IO a
withMatrix ptr action = do
matrix <- cppGetMatrix ptr
foreignPtr <- newForeignPtr destroyQTransform matrix
withForeignPtr foreignPtr action
foreign import ccall "getMatrix" cppGetMatrix :: Ptr QPainter -> IO (Ptr QTransform)
foreign import ccall "setMatrix" setMatrix :: Ptr QPainter -> Ptr QTransform -> IO ()
-- * QPixmap
data QPixmap
deriving (Typeable)
-- | loads a new pixmap. Canonicalizes the path first.
newQPixmap :: FilePath -> IO (ForeignPtr QPixmap)
newQPixmap file_ = do
file <- canonicalizePath file_
exists <- doesFileExist file
when (not exists) $
error ("file does not exist: " ++ file)
-- ~ ptr <- withCString file cppNewQPixmap
ptr <- newQPixmapFromPNGData file
when (ptr == nullPtr) $
error ("could not load image file: " ++ file)
newForeignQPixmap ptr
newQPixmapFromPNGData :: FilePath -> IO (Ptr QPixmap)
newQPixmapFromPNGData file = do
bytes <- SBS.readFile file
SBS.unsafeUseAsCString bytes $ \ arrayPtr ->
cppNewQPixmapFromPNGData arrayPtr (SBS.length bytes)
newQPixmapEmpty :: Size QtInt -> IO (ForeignPtr QPixmap)
newQPixmapEmpty (Size x y) = do
when veryBig $
logg Warning (printf
"creating very large QPixmap: %.0fKB" kb)
ptr <- cppNewQPixmapEmpty x y
newForeignQPixmap ptr
where
veryBig = bytes > 8 * 1024 ^ 2
bytes :: QtInt
bytes = x * y * 4
kb :: Double = fromIntegral bytes / 1024
foreign import ccall "newQPixmapEmpty" cppNewQPixmapEmpty ::
QtInt -> QtInt -> IO (Ptr QPixmap)
foreign import ccall "newQPixmap" cppNewQPixmap :: CString -> IO (Ptr QPixmap)
foreign import ccall "newQPixmapFromPNGData" cppNewQPixmapFromPNGData :: Ptr CChar -> Int -> IO (Ptr QPixmap)
foreign import ccall "destroyQPixmap" destroyQPixmap :: Ptr QPixmap -> IO ()
newForeignQPixmap :: Ptr QPixmap -> IO (ForeignPtr QPixmap)
newForeignQPixmap ptr =
Foreign.Concurrent.newForeignPtr ptr (ignore $ postGUIBlocking $ destroyQPixmap ptr)
saveQPixmap :: ForeignPtr QPixmap -> String -> QtInt -> IO ()
saveQPixmap fp file quality =
withForeignPtr fp $ \ ptr ->
withCString file $ \ cfile ->
cppSaveQPixmap ptr cfile quality
foreign import ccall "saveQPixmap" cppSaveQPixmap ::
Ptr QPixmap -> CString -> QtInt -> IO ()
copyQPixmap :: ForeignPtr QPixmap -> IO (ForeignPtr QPixmap)
copyQPixmap originalFp =
withForeignPtr originalFp $ \ original -> do
copy <- cppCopyQPixmap original
newForeignQPixmap copy
foreign import ccall "copyQPixmap" cppCopyQPixmap :: Ptr QPixmap -> IO (Ptr QPixmap)
foreign import ccall widthQPixmap :: Ptr QPixmap -> IO QtInt
foreign import ccall heightQPixmap :: Ptr QPixmap -> IO QtInt
sizeQPixmap :: ForeignPtr QPixmap -> IO (Size QtInt)
sizeQPixmap fp =
withForeignPtr fp $ \ ptr ->
(Size <$> widthQPixmap ptr <*> heightQPixmap ptr)
-- | Bool parameter controls, if Indexed8 is forced as a format.
toImageQPixmap :: ForeignPtr QPixmap -> Bool -> IO (Ptr QImage)
toImageQPixmap fp indexed8 =
withForeignPtr fp $ \ ptr ->
cppToImageQPixmap ptr indexed8
foreign import ccall "toImageQPixmap" cppToImageQPixmap
:: Ptr QPixmap -> Bool -> IO (Ptr QImage)
fromImageQPixmap :: Ptr QImage -> IO (ForeignPtr QPixmap)
fromImageQPixmap image =
newForeignQPixmap =<< cppFromImageQPixmap image
foreign import ccall "fromImageQPixmap" cppFromImageQPixmap :: Ptr QImage -> IO (Ptr QPixmap)
-- * QImage
data QImage
foreign import ccall destroyQImage :: Ptr QImage -> IO ()
saveQImage :: Ptr QImage -> FilePath -> IO ()
saveQImage image filename =
withCString filename $ \ cfile ->
cppSaveQImage image cfile
foreign import ccall "saveQImage" cppSaveQImage :: Ptr QImage -> CString -> IO ()
foreign import ccall widthQImage :: Ptr QImage -> IO QtInt
foreign import ccall heightQImage :: Ptr QImage -> IO QtInt
sizeQImage :: Ptr QImage -> IO (Size QtInt)
sizeQImage ptr = Size <$> widthQImage ptr <*> heightQImage ptr
foreign import ccall colorCountQImage :: Ptr QImage -> IO Int
foreign import ccall colorQImage :: Ptr QImage -> Int -> IO QRgb
foreign import ccall setColorQImage :: Ptr QImage -> Int -> QRgb -> IO ()
pixelQImage :: Ptr QImage -> (QtInt, QtInt) -> IO QRgb
pixelQImage ptr (x, y) = cppPixelQImage ptr x y
foreign import ccall "pixelQImage" cppPixelQImage ::
Ptr QImage -> QtInt -> QtInt -> IO QRgb
setPixelQImage :: Ptr QImage -> (QtInt, QtInt) -> QRgb -> IO ()
setPixelQImage ptr (x, y) color =
cppSetPixelQImage ptr x y color
foreign import ccall "setPixelQImage" cppSetPixelQImage ::
Ptr QImage -> QtInt -> QtInt -> QRgb -> IO ()
-- * QRgb
type QRgb = CUInt
qRgbToColor :: QRgb -> IO Color
qRgbToColor qrgb =
QtColor <$> c_qRed qrgb <*> c_qGreen qrgb <*> c_qBlue qrgb <*> c_qAlpha qrgb
colorToQRgb :: Color -> IO QRgb
colorToQRgb (QtColor r g b a) = c_qRgba r g b a
foreign import ccall c_qRed :: QRgb -> IO QtInt
foreign import ccall c_qGreen :: QRgb -> IO QtInt
foreign import ccall c_qBlue :: QRgb -> IO QtInt
foreign import ccall c_qAlpha :: QRgb -> IO QtInt
foreign import ccall c_qRgba :: QtInt -> QtInt -> QtInt -> QtInt -> IO QRgb
-- * QIcon
data QIcon
foreign import ccall newQIcon :: IO (Ptr QIcon)
foreign import ccall destroyQIcon :: Ptr QIcon -> IO ()
withQIcon :: MonadCatchIO m => (Ptr QIcon -> m a) -> m a
withQIcon = bracket (io newQIcon) (io . destroyQIcon)
addFileQIcon :: Ptr QIcon -> FilePath -> IO ()
addFileQIcon ptr s = withCString s (cppAddFileQIcon ptr)
foreign import ccall "addFileQIcon" cppAddFileQIcon :: Ptr QIcon -> CString -> IO ()
-- * QKeyEvent
-- type declaration in Qt.Types, because it's needed in Qt.Events
foreign import ccall keyQKeyEvent :: Ptr QKeyEvent -> IO QtInt
foreign import ccall "textQKeyEvent" cppTextQKeyEvent :: Ptr QKeyEvent -> IO (Ptr QByteArray)
textQKeyEvent :: Ptr QKeyEvent -> IO String
textQKeyEvent ptr = do
byteArray <- cppTextQKeyEvent ptr
r <- stringQByteArray byteArray
destroyQByteArray byteArray
return r
foreign import ccall modifiersQKeyEvent :: Ptr QKeyEvent -> IO QtInt
-- * QByteArray
data QByteArray
foreign import ccall destroyQByteArray :: Ptr QByteArray -> IO ()
foreign import ccall dataQByteArray :: Ptr QByteArray -> IO CString
stringQByteArray :: Ptr QByteArray -> IO String
stringQByteArray ptr =
peekCString =<< dataQByteArray ptr
-- * QClipboard
textQClipboard :: IO String
textQClipboard = postGUIBlocking $ do
byteArray <- cppTextQClipboard
r <- stringQByteArray byteArray
destroyQByteArray byteArray
return r
foreign import ccall "textQClipboard" cppTextQClipboard :: IO (Ptr QByteArray)
-- * Execute IO-operations in the GUI-thread
-- | Non-blocking operation, that gets the gui thread to perform the given action.
-- (cpp has to call 'freePostGUIFunPtr' after performing the action.)
postGUI :: IO () -> IO ()
postGUI action = do
mm <- tryReadMVar _mainWindowRef
case mm of
Nothing -> error "initialize _mainWindowRef before calling postGUI or postGUIBlocking!"
Just window ->
cppPostGUI window =<< wrapGuiAction action
{-# noinline _mainWindowRef #-}
_mainWindowRef :: MVar (Ptr MainWindow)
_mainWindowRef = unsafePerformIO newEmptyMVar
foreign import ccall "postGUI" cppPostGUI :: Ptr MainWindow -> FunPtr (IO ()) -> IO ()
foreign import ccall "wrapper" wrapGuiAction ::
IO () -> IO (FunPtr (IO ()))
-- | Blocking operation, that gets the gui thread to perform a given action and
-- returns its result.
postGUIBlocking :: IO a -> IO a
postGUIBlocking a = do
ref <- newEmptyMVar
postGUI (a >>= putMVar ref)
takeMVar ref
foreign export ccall freePostGUIFunPtr :: FunPtr (IO ()) -> IO ()
freePostGUIFunPtr :: FunPtr (IO ()) -> IO ()
freePostGUIFunPtr = freeHaskellFunPtr
| geocurnoff/nikki | src/Graphics/Qt/CPPWrapper.hs | lgpl-3.0 | 21,607 | 0 | 16 | 4,376 | 6,564 | 3,274 | 3,290 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Test.IO.Ambiata.Cli.Processing where
import Ambiata.Cli.Data
import Ambiata.Cli.Incoming
import Ambiata.Cli.Processing
import P
import Test.QuickCheck
import System.Directory
import System.FilePath ((</>))
import System.IO
import System.IO.Temp
import Control.Monad.IO.Class (liftIO)
import Data.List (nub, sort)
import Data.String
import Data.Text (unpack)
import Disorder.Core.IO
import Mismi
import Mismi.S3
import Test.Ambiata.Cli.Arbitrary ()
import Test.IO.Ambiata.Cli.Util
import qualified Test.Mismi.S3 as S3
import Test.Mismi.S3
import X.Control.Monad.Trans.Either
prop_available_files :: String -> [ProcessingFile] -> Property
prop_available_files junk files' = testIO . withSystemTempDirectory "prop_available_files" $ \dir' -> testAmbiata $ do
let xfiles = nub files'
let dir = IncomingDir dir'
let working = toWorkingPath dir Processing
prepareDir dir
ls <- liftIO $ availableFiles dir
liftIO $ mapM_ (\p -> writeFile (working </> (unpack $ unProcessingFile p)) $ junk) xfiles
ls' <- liftIO $ availableFiles dir
pure $ (ls, length ls', sort ls') === ([], length xfiles, sort (xfiles))
prop_move_to_archive :: String -> ProcessingFile -> Property
prop_move_to_archive junk f@(ProcessingFile name) = testIO . withSystemTempDirectory "prop_move_to_archive" $ \dir' -> testAmbiata $ do
let dir = IncomingDir dir'
let working = toWorkingPath dir Processing
prepareDir dir
liftIO $ writeFile (working </> (unpack $ name)) junk
(ArchivedFile archivedName) <- liftIO $ moveToArchive dir f
ls <- liftIO $ getDirectoryContents (toWorkingPath dir Archive)
pure $ (elem (unpack name) ls, name) === (True, archivedName)
prop_upload :: String -> ProcessingFile -> Property
prop_upload junk f@(ProcessingFile name) = withLocalAWS $ \p a -> do
let dir = IncomingDir p
void $ liftIO $ runEitherT $ prepareDir dir
let working = toWorkingPath dir Processing
liftIO $ writeFile (working </> (unpack $ name)) junk
archivedFiles <- processReady dir a
ls <- liftIO $ availableFiles dir
let d = (p </> unpack name)
downloadOrFail (fileAddress f a) d
c <- liftIO $ readFile d
pure $ (length archivedFiles, length ls, c) === (1,0,junk)
-- check it leaves files in processing
prop_upload_broken :: String -> ProcessingFile -> TemporaryAccess -> Property
prop_upload_broken junk (ProcessingFile name) creds' = testIO . withSystemTempDirectory "prop_upload_broken" $ \dir' -> runOrFail $ do
let dir = IncomingDir dir'
let working = toWorkingPath dir Processing
creds <- liftIO $ useTestBucket creds'
void $ liftIO $ runEitherT $ prepareDir dir
liftIO $ writeFile (working </> (unpack $ name)) junk
ls <- liftIO $ availableFiles dir
-- this should actually fail
_ <- expectLeft "Not valid creds" $ uploadReady dir Sydney (UploadAccess creds)
-- and leave the file in the processing dir:
ls' <- liftIO $ availableFiles dir
pure $ (ls, length ls) === (ls', 1)
--
-- | some neat combinators to make tests a bit nicer:
--
withLocalAWS :: Testable a => (FilePath -> Address -> AWS a) -> Property
withLocalAWS x = S3.testAWS $
join $ x <$> S3.newFilePath <*> S3.newAddress
runOrFail :: (Monad m) => EitherT Text m a -> m a
runOrFail = (=<<) (either (fail . unpack) return) . runEitherT
expectLeft :: Functor m => f -> EitherT b m e -> EitherT f m b
expectLeft err e = bimapEitherT (const err) id $ swapEitherT e
useTestBucket :: TemporaryAccess -> IO TemporaryAccess
useTestBucket (TemporaryAccess creds (Address _ k)) = do
b' <- testBucket
return $ TemporaryAccess creds (Address b' k)
swapEitherT :: Functor m => EitherT a m b -> EitherT b m a
swapEitherT =
newEitherT . fmap (either Right Left) . runEitherT
return []
tests :: IO Bool
tests = $forAllProperties $ quickCheckWithResult (stdArgs { maxSuccess = 10 })
| ambiata/tatooine-cli | test/Test/IO/Ambiata/Cli/Processing.hs | apache-2.0 | 4,164 | 0 | 20 | 923 | 1,342 | 682 | 660 | 84 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.