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
{-# OPTIONS_GHC -fno-warn-orphans #-} module Unison.Hash.Extra where import Data.Bytes.Serial import Data.List import Unison.Hash import qualified Crypto.Hash as CH import qualified Data.ByteArray as BA import qualified Data.ByteString as B import qualified Data.Bytes.Put as Put import qualified Data.Bytes.VarInt as VarInt import qualified Unison.Hashable as H instance H.Accumulate Hash where accumulate = fromBytes . BA.convert . CH.hashFinalize . foldl' step CH.hashInit where step :: CH.Context CH.SHA3_512 -> H.Token Hash -> CH.Context CH.SHA3_512 step acc (H.Tag b) = CH.hashUpdate acc (B.singleton b) step acc (H.Bytes bs) = CH.hashUpdate acc bs step acc (H.VarInt i) = CH.hashUpdate acc (Put.runPutS $ serialize (VarInt.VarInt i)) step acc (H.Text txt) = CH.hashUpdate acc (Put.runPutS $ serialize txt) step acc (H.Double d) = CH.hashUpdate acc (Put.runPutS $ serialize d) step acc (H.Hashed h) = CH.hashUpdate acc (toBytes h) fromBytes = Unison.Hash.fromBytes toBytes = Unison.Hash.toBytes instance Serial Hash where serialize h = serialize (toBytes h) deserialize = fromBytes <$> deserialize
nightscape/platform
node/src/Unison/Hash/Extra.hs
mit
1,146
0
14
192
404
217
187
25
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ScopedTypeVariables #-} module Symmetry.IL.AST where import Prelude hiding (concatMap, mapM, foldl, concat) import Data.Traversable import Data.Foldable import Control.Monad.State hiding (mapM) import Data.Typeable import Data.Generics import Data.List (nub, isPrefixOf, (\\)) import qualified Data.Map.Strict as M import qualified Data.IntMap as I import Text.PrettyPrint.Leijen as P hiding ((<$>)) setSize :: Int setSize = 1 infty :: Int infty = 2 data Set = S { setName :: String } | SV Var | SInts Int deriving (Ord, Eq, Read, Show, Typeable, Data) data Var = V String -- Local Var | GV String -- Global Var | VPtrR Type -- Special Variable (read ptr for type) | VPtrW Type -- Special Variable (read ptr for type) | VRef Pid String -- Reference another process's variable (for ghost state) deriving (Ord, Eq, Read, Show, Typeable, Data) data LVar = LV { unlv :: String } deriving (Ord, Eq, Read, Show, Typeable, Data) newtype MTyCon = MTyCon { untycon :: String } deriving (Ord, Eq, Read, Show, Typeable, Data) data Pid = PConc Int | PAbs { absVar :: Var, absSet :: Set } {- These do not appear in configurations: -} | PUnfold Var Set Int | PVar Var deriving (Ord, Eq, Read, Show, Typeable, Data) type PidMap = M.Map Pid (Int, Int) type Channel = (Pid, Pid, MTyCon) isUnfold :: Pid -> Bool isUnfold PUnfold{} = True isUnfold _ = False isAbs :: Pid -> Bool isAbs (PAbs _ _) = True isAbs _ = False isBounded :: [SetBound] -> Pid -> Bool isBounded bs (PAbs _ s) = s `elem` [ s' | Known s' _ <- bs ] isBounded _ _ = False data Label = LL | RL | VL Var deriving (Ord, Eq, Read, Show, Typeable, Data) data Type = TUnit | TInt | TString | TPid | TPidMulti | TProd Type Type | TSum Type Type | TLift String Type deriving (Ord, Eq, Read, Show, Typeable, Data) data Pat = PUnit | PInt Var | PPid Var | PProd Pat Pat | PSum Pat Pat deriving (Ord, Eq, Read, Show, Typeable, Data) data Pred = ILBop Op ILExpr ILExpr | ILAnd Pred Pred | ILOr Pred Pred | ILNot Pred | ILPTrue deriving (Ord, Eq, Read, Show, Typeable, Data) data Op = Eq | Lt | Le | Gt | Ge deriving (Ord, Eq, Read, Show, Typeable, Data) -- Predicates (Can we move to fixpoint refts? Or paramaterize over these?) pTrue :: Pred pTrue = ILPTrue pFalse :: Pred pFalse = ILBop Eq (EInt 0) (EInt 1) pAnd :: Pred -> Pred -> Pred pAnd p1 p2 = pSimplify (ILAnd p1 p2) pSimplify :: Pred -> Pred pSimplify (ILAnd ILPTrue p) = pSimplify p pSimplify (ILAnd p ILPTrue) = pSimplify p pSimplify (ILOr ILPTrue _) = pTrue pSimplify (ILOr _ ILPTrue) = pTrue pSimplify (ILNot p) = ILNot (pSimplify p) pSimplify p = p data ILExpr = EUnit | EInt Int | EString | EPid Pid | ESet Set | EVar Var | ELift String ILExpr | ELeft ILExpr | ERight ILExpr | EPair ILExpr ILExpr | EPlus ILExpr ILExpr | EProj1 ILExpr | EProj2 ILExpr deriving (Ord, Eq, Read, Show, Typeable, Data) -- send(p, EPid p) data MConstr = MTApp { tycon :: MTyCon, tyargs :: [Pid] } | MCaseL Label MConstr | MCaseR Label MConstr -- | MTSum MConstr MConstr | MTProd { proj1 :: MConstr, proj2 :: MConstr } deriving (Ord, Eq, Read, Show, Typeable, Data) eqConstr :: MConstr -> MConstr -> Bool eqConstr (MCaseL _ c) (MCaseL _ c') = eqConstr c c' eqConstr (MCaseR _ c) (MCaseR _ c') = eqConstr c c' eqConstr (MTProd p1 p2) (MTProd p1' p2') = eqConstr p1 p1' && eqConstr p2 p2' eqConstr a1@(MTApp{}) a2@MTApp{} = tycon a1 == tycon a2 && length (tyargs a1) == length (tyargs a2) eqConstr _ _ = False lookupConstr :: MType -> MConstr -> Maybe CId lookupConstr m c = M.foldlWithKey go Nothing m where go Nothing i c' = if eqConstr c c' then Just i else Nothing go a _ _ = a lookupType :: MTypeEnv -> MType -> Maybe TId lookupType m t = M.foldlWithKey go Nothing m where go Nothing i t' = if t == t' then Just i else Nothing go a _ _ = a type TId = Int type CId = Int type VId = Int type MType = M.Map CId MConstr type MValMap = M.Map MConstr VId -- No variables type MTypeEnv = M.Map TId MType class Eq a => Identable a where ident :: a -> Int instance Identable Int where ident = id instance Identable a => Identable (Stmt a) where ident = ident . annot data PredAnnot a = PredAnnot { annotPred :: Pred, annotId :: a } deriving (Ord, Eq, Read, Show, Data, Typeable) instance Identable a => Identable (PredAnnot a) where ident = ident . annotId data Stmt a = Skip { annot :: a } | Block { blkBody :: [Stmt a] , annot :: a } | Send { sndPid :: ILExpr -- Pid , sndMsg :: (Type, ILExpr) , annot :: a } | Recv { rcvMsg :: (Type, Var) , annot :: a } | Iter { iterVar :: Var , iterSet :: Set , iterBody :: Stmt a , annot :: a } | Loop { loopVar :: LVar , loopBody :: Stmt a , annot :: a } | Goto { varVar :: LVar , annot :: a } | Choose { chooseVar :: Var , chooseSet :: Set , chooseBody :: Stmt a , annot :: a } | Assert { assertPred :: Pred , annot :: a } -- x := p1 == p2; | Compare { compareVar :: Var , compareLhs :: Pid , compareRhs :: Pid , annot :: a } | Case { caseVar :: Var , caseLPat :: Var , caseRPat :: Var , caseLeft :: Stmt a , caseRight :: Stmt a , annot :: a } | NonDet { nonDetBody :: [Stmt a] , annot :: a } | Assign { assignLhs :: Var , assignRhs :: ILExpr , annot :: a } | Die { annot :: a } {- These do not appear in the source: -} | Null { annot :: a } -- | GotoDecl Var a -- | STest Var a deriving (Ord, Eq, Read, Show, Functor, Foldable, Data, Typeable) data SetBound = Known Set Int | Unknown Set Var deriving (Eq, Read, Show, Data, Typeable) type Process a = (Pid, Stmt a) data Unfold = Conc Set Int deriving (Eq, Read, Show, Data, Typeable) data Config a = Config { cTypes :: MTypeEnv , cGlobals :: [(Var, Type)] , cGlobalSets :: [Set] , cSetBounds :: [SetBound] , cUnfold :: [Unfold] , cProcs :: [Process a] } deriving (Eq, Read, Show, Data, Typeable) unboundVars :: forall a. Data a => Stmt a -> [Var] unboundVars s = allvars \\ (bound ++ absIdx) where allvars = nub $ listify (const True :: Var -> Bool) s bound = nub $ everything (++) (mkQ [] go) s absIdx = nub $ everything (++) (mkQ [] goAbs) s go :: Data a => Stmt a -> [Var] go (Recv (_,x) _) = [x] go (i@Iter {}) = [iterVar i] go (i@Choose {}) = [chooseVar i] go (i@Case {}) = [caseLPat i, caseRPat i] go _ = [] goAbs :: Pid -> [Var] goAbs (PAbs v _) = [v] goAbs _ = [] unboundSets :: forall a. Data a => Stmt a -> [Set] unboundSets s = allSetVars \\ boundSetVars where allSetVars = nub $ listify isSetVar s isSetVar (S _) = True isSetVar (SV _) = True isSetVar _ = False boundSetVars = nub $ everything (++) (mkQ [] go) s go :: Data a => Stmt a -> [Set] go (Recv (_, V x) _)= [S x] -- TODO go _ = [] endLabels :: (Data a, Typeable a) => Stmt a -> [LVar] endLabels = nub . listify (isPrefixOf "end" . unlv) isBound :: Set -> [SetBound] -> Bool isBound s = any p where p (Known s' _) = s == s' p _ = False boundAbs :: Config a -> Config a boundAbs c@(Config {cProcs = ps, cSetBounds = bs}) = c { cUnfold = us } where us = [ Conc s n | (PAbs _ s, _) <- ps , Known s' n <- bs , s == s'] vars :: Pat -> [Var] vars = nub . listify (const True) -- | Typeclass tomfoolery instance Traversable Stmt where traverse f (Skip a) = Skip <$> f a traverse f (Send p ms a) = Send p ms <$> f a traverse f (Recv ms a) = Recv ms <$> f a traverse f (Iter v s ss a) = flip (Iter v s) <$> f a <*> traverse f ss traverse f (Loop v ss a) = flip (Loop v) <$> f a <*> traverse f ss traverse f (Choose v s ss a) = flip (Choose v s) <$> f a <*> traverse f ss traverse f (Goto v a) = Goto v <$> f a traverse f (Compare v p1 p2 a) = Compare v p1 p2 <$> f a traverse f (Die a) = Die <$> f a traverse f (Block ss a) = flip Block <$> f a <*> traverse (traverse f) ss traverse f (Case v pl pr sl sr a) = mkCase <$> f a <*> traverse f sl <*> traverse f sr where mkCase a' l r = Case v pl pr l r a' traverse f (NonDet ss a) = flip NonDet <$> f a <*> traverse (traverse f) ss traverse f (Assign v e a) = Assign v e <$> f a traverse f (Assert p a) = Assert p <$> f a traverse _ _ = error "traverse undefined for non-source stmts" joinMaps :: Eq a => I.IntMap [a] -> I.IntMap [a] -> I.IntMap [a] joinMaps m m' = I.unionWith (foldl' go) m m' where go is i = if i `elem` is then is else i:is stmt :: (TId, [(CId, MConstr)], Stmt a) -> Stmt a stmt (_,_,s) = s lastStmts :: Stmt a -> [Stmt a] lastStmts s@(Skip _) = [s] lastStmts s@(Goto _ _) = [s] lastStmts s@(Compare _ _ _ _) = [s] lastStmts (Block ss _) = [last ss] lastStmts s@(Send _ _ _) = [s] lastStmts s@(Recv _ _) = [s] lastStmts (NonDet ss _) = concatMap lastStmts ss lastStmts (Choose _ _ s _) = lastStmts s lastStmts s@(Iter _ _ _ _) = [s] lastStmts (Loop _ s _) = lastStmts s lastStmts (Case _ _ _ sl sr _) = lastStmts sl ++ lastStmts sr lastStmts s@(Die _) = [s] lastStmts s@Assert{} = [s] lastStmts _ = error "lastStmts: TBD" buildCfg :: (Data a, Identable a) => Stmt a -> I.IntMap [Int] buildCfg s = I.map (fmap ident) $ buildStmtCfg s buildStmtCfg :: (Data a, Identable a) => Stmt a -> I.IntMap [Stmt a] buildStmtCfg = nextStmts 0 singleton :: Identable a => Int -> Stmt a -> I.IntMap [Stmt a] singleton i j | i == ident j = I.empty | otherwise = I.fromList [(i, [j])] nextStmts :: forall a. (Typeable a, Data a, Identable a) => Int -> Stmt a -> I.IntMap [Stmt a] nextStmts toMe s@(NonDet ss i) = foldl' (\m -> joinMaps m . nextStmts (ident i)) (I.fromList [(toMe, [s])]) ss -- Blocks shouldn't be nested nextStmts toMe s@Block { blkBody = ss } = singleton toMe s `joinMaps` snd nexts where nexts = foldl' go ([ident s], I.empty) ss go (ins, m) s' = (annots s', foldl' joinMaps m (doMaps s' <$> ins)) doMaps s' i = nextStmts i s' annots (NonDet ts _) = [ ident i | i <- concatMap lastStmts ts ] annots s'@Case {} = ident <$> lastStmts s' annots s'@Choose{} = ident <$> lastStmts s' annots s'@Loop{} = ident <$> [ s'' | s'' <- lastStmts s', notGoto s''] annots s' = [ident s'] notGoto Goto{} = False notGoto _ = True nextStmts toMe s@(Iter _ _ t _) = singleton toMe s `joinMaps` I.fromList [(ident j, [s]) | j <- lastStmts t] `joinMaps` nextStmts (ident s) t nextStmts toMe me@(Loop v s _) = singleton toMe me `joinMaps` I.fromList [(j, [me]) | j <- js ] `joinMaps` nextStmts (ident me) s where js = everything (++) (mkQ [] go) s go :: Stmt a -> [Int] go s'@Goto{} | varVar s' == v = [ident s'] go _ = [] nextStmts toMe me@(Choose _ _ s _) = singleton toMe me `joinMaps` nextStmts (ident me) s nextStmts toMe me@(Case _ _ _ sl sr _) = singleton toMe me `joinMaps` nextStmts (ident me) sl `joinMaps` nextStmts (ident me) sr nextStmts toMe s = singleton toMe s -- | Operations freshId :: forall a b. (Int -> a -> b) -> Stmt a -> State Int (Stmt b) freshId f s = mapM fr s where fr :: a -> State Int b fr a = do n <- get put (n + 1) return (f n a) freshStmtIds :: (Int -> a -> b) -> Stmt a -> Stmt b freshStmtIds f s = evalState (freshId f s) 0 freshIds :: Config a -> (Int -> a -> b) -> Config b freshIds (c @ Config { cProcs = ps }) f = c { cProcs = evalState (mapM (mapM (freshId f)) ps) 1 } instance Pretty Var where pretty (V x) = text x pretty (GV x) = text x pretty (VPtrR t) = text "Rd[" <> pretty t <> text "]" pretty (VPtrW t) = text "Wr[" <> pretty t <> text "]" pretty (VRef p v) = pretty v <> text "@" <> pretty p instance Pretty Set where pretty (S x) = text x pretty (SV x) = pretty x pretty (SInts n) = brackets (int 1 <+> text ".." <+> int n) instance Pretty Pid where pretty (PConc x) = text "pid" <> parens (int x) pretty (PAbs v vs) = text "pid" <> parens (pretty vs <> brackets (pretty v)) pretty (PVar v) = text "pid" <> parens (pretty v) pretty (PUnfold _ s i) = text "pid" <> parens (pretty s <> brackets (int i)) ($$) :: Doc -> Doc -> Doc x $$ y = (x <> line <> y) instance Pretty Label where pretty LL = text "inl" pretty RL = text "inr" pretty (VL x) = pretty x instance Pretty MConstr where pretty (MTApp tc []) = text (untycon tc) pretty (MTApp tc args) = text (untycon tc) <> pretty args pretty (MCaseL l t) = pretty l <+> pretty t pretty (MCaseR l t) = pretty l <+> pretty t pretty (MTProd t1 t2) = parens (pretty t1 <> text ", " <> pretty t2) instance Pretty ILExpr where pretty EUnit = text "()" pretty EString = text "<str>" pretty (EInt i) = int i pretty (EVar v) = pretty v pretty (EPid p) = pretty p pretty (ESet p) = pretty p pretty (ELeft e) = text "inl" <> parens (pretty e) pretty (ERight e) = text "inr" <> parens (pretty e) pretty (EPair e1 e2) = tupled [pretty e1, pretty e2] pretty (EPlus e1 e2) = pretty e1 <+> text "+" <+> pretty e2 pretty (EProj1 e) = text "π₁" <> parens (pretty e) pretty (EProj2 e) = text "π₂" <> parens (pretty e) instance Pretty Pat where pretty (PUnit ) = text "()" pretty (PInt v) = text "int" <+> pretty v pretty (PPid v) = text "pid" <+> pretty v pretty (PSum p1 p2) = parens (pretty p1 <+> text "+" <+> pretty p2) pretty (PProd p1 p2) = parens (pretty p1 <+> text "*" <+> pretty p2) instance Pretty Type where pretty TUnit = text "()" pretty TInt = text "int" pretty TString = text "string" pretty TPid = text "pid" pretty TPidMulti = text "pid set" pretty (TLift n t) = parens (text n <+> pretty t) pretty (TSum p1 p2) = parens (pretty p1 <+> text "+" <+> pretty p2) pretty (TProd p1 p2) = parens (pretty p1 <+> text "*" <+> pretty p2) instance Pretty Op where pretty Eq = text "=" pretty Lt = text "<" pretty Le = text "≤" pretty Gt = text ">" pretty Ge = text "≥" instance Pretty Pred where pretty (ILBop o e1 e2) = parens (pretty e1 <+> pretty o <+> pretty e2) pretty (ILAnd p1 p2) = parens (pretty p1 <+> text "&&" <+> pretty p2) pretty (ILOr p1 p2) = parens (pretty p1 <+> text "||" <+> pretty p2) pretty (ILNot p) = parens (text "~" <> pretty p) pretty (ILPTrue) = text "T" instance Pretty a => Pretty (PredAnnot a) where pretty PredAnnot { annotId = i, annotPred = ILPTrue } = text "/*" <+> pretty i <+> text "*/" pretty PredAnnot { annotId = i, annotPred = p } = text "/*" <+> pretty i <+> text "{" <+> pretty p <> text "} */" instance Pretty a => Pretty (Stmt a) where pretty (Skip a) = text "<skip>" <+> pretty a pretty (Assert e a) = text "assert" <+> pretty e <+> pretty a pretty (Assign v e a) = pretty v <+> text ":=" <+> pretty e <+> pretty a pretty (Send p (t,e) a) = text "send" <+> pretty p <+> parens (pretty e <+> text "::" <+> pretty t) <+> pretty a pretty (Recv (t,x) a) = text "recv" <+> parens (pretty x <+> text "::" <+> pretty t) <+> pretty a pretty (Iter x xs s a) = pretty x <+> text ":=" <+> int 0 $$ text "while" <+> parens (pretty x <+> langle <+> text "|" <> pretty xs <> text "|") <+> pretty a $$ (indent 2 $ pretty s) pretty (Goto (LV v) a) = text "goto" <+> pretty v <+> pretty a pretty (Loop (LV v) s a) = pretty v <> colon <+> parens (pretty s) <+> pretty a pretty (Case l pl pr sl sr a) = text "match" <+> pretty l <+> text "with" <+> pretty a $$ indent 2 (align (vcat [text "| InL" <+> pretty pl <+> text "->" <+> pretty sl, text "| InR" <+> pretty pr <+> text "->" <+> pretty sr])) pretty (Choose v r s a) = text "select" <+> pretty v <+> text "from" <+> pretty r <+> text "in" <+> pretty a $$ indent 2 (align (pretty s)) pretty (Die a) = text "CRASH" <+> pretty a pretty (Block ss a) = braces (pretty a <> line <> indent 2 (vcat $ punctuate semi (map pretty ss)) <> line) pretty (Compare v p1 p2 _) = pretty v <+> colon <> equals <+> pretty p1 <+> equals <> equals <+> pretty p2 pretty (NonDet ss a) = pretty ss <+> pretty a pretty (Null a) = text "<null>" <+> pretty a prettyMsg :: (TId, CId, MConstr) -> Doc prettyMsg (t, c, v) = text "T" <> int t <> text "@" <> text "C" <> int c <> parens (pretty v) instance Pretty a => Pretty (Config a) where pretty (Config {cProcs = ps, cSetBounds = bs, cGlobals = gs, cGlobalSets = gsets}) = vsep (map goGlob gs ++ map goGlobS gsets ++ map goB bs ++ map go ps) where goGlob (v, t) = text "Global" <+> pretty v <+> text "::" <+> pretty t goGlobS s = text "Global" <+> pretty s goB (Known s n) = text "|" <> pretty s <> text "|" <+> equals <+> int n goB (Unknown s v) = text "|" <> pretty s <> text "|" <+> equals <+> pretty v go (pid, s) = processName pid <> colon <$$> indent 2 (pretty s) processName (PConc n) = text "P" <> text "r" <> int n processName (PAbs _ s) = braces (text "P" <> pretty s) processName p = pretty p recvVars :: forall a. (Data a, Typeable a) => Stmt a -> [Var] recvVars s = everything (++) (mkQ [] go) s where go :: Stmt a -> [Var] go (Recv t _) = listify (const True) t go _ = [] patVars :: forall a. (Data a, Typeable a) => Stmt a -> [Var] patVars s = nub $ everything (++) (mkQ [] go) s where go :: Stmt a -> [Var] go (Case _ x y _ _ _) = [x, y] go _ = [] ------------------------ -- Remove explicit Assertions ------------------------ annotAsserts :: Data a => Config a -> Config (PredAnnot a) annotAsserts c = c { cProcs = [ (p, squashAsserts s) | (p, s) <- cProcs c ] } truePred :: a -> PredAnnot a truePred a = PredAnnot { annotPred = ILPTrue , annotId = a } meetPred :: PredAnnot a -> PredAnnot a -> PredAnnot a meetPred p1 p2 = p2 { annotPred = pAnd (annotPred p1) (annotPred p2) } squashAsserts :: forall a. Data a => Stmt a -> Stmt (PredAnnot a) squashAsserts s@Block { blkBody = [a@Assert{}] } = s { blkBody = [fmap truePred a] , annot = truePred (annot s) } squashAsserts s@Block { blkBody = (a@Assert{}):s1:body } = annotFirst ann $ squashAsserts s { blkBody = s1:body } where ann = PredAnnot { annotPred = assertPred a , annotId = annot a } squashAsserts s@Block { blkBody = b:body } = s { blkBody = b' `joinStmts` body' , annot = truePred (annot s) } where b' = fmap truePred b body' = squashAsserts s { blkBody = body } joinStmts s1 s2@Block{} = s1 : blkBody s2 joinStmts s1 s2 = [s1, s2] squashAsserts s = fmap truePred s annotFirst :: PredAnnot a -> Stmt (PredAnnot a) -> Stmt (PredAnnot a) annotFirst a s@Block{ blkBody = b:body } = s { blkBody = b { annot = meetPred a (annot b) } : body } annotFirst a s = s { annot = meetPred a (annot s) }
abakst/symmetry
checker/src/Symmetry/IL/AST.hs
mit
21,181
1
16
7,118
9,007
4,614
4,393
511
7
{-# LANGUAGE FlexibleInstances, BangPatterns #-} -- | Field operations module FieldElt where class Show a => FieldElt a where zero :: a -- | Add all elements. (~+~) :: a -> a -> a -- | Subtract elements from second from first. (~-~) :: a -> a -> a -- | Multiply all elements. (~*~) :: a -> Float -> a -- | Divide first elemends by the second. (~/~) :: a -> Float -> a -- | Negate all mambers. negate :: a -> a -- | Masked addition. addIf :: Bool -> a -> a -> a -- | Masked filter, members with their corresponding flags set -- to False get zero. useIf :: Bool -> a -> a instance FieldElt Float where zero = 0 {-# INLINE zero #-} (~+~) a b = a + b {-# INLINE (~+~) #-} (~-~) a b = a - b {-# INLINE (~-~) #-} (~*~) a b = a * b {-# INLINE (~*~) #-} (~/~) a b = a / b {-# INLINE (~/~) #-} negate a = 0 ~-~ a {-# INLINE negate #-} addIf True a b = a + b addIf False _ b = b {-# INLINE addIf #-} useIf True a = a useIf False _ = 0 {-# INLINE useIf #-} instance FieldElt (Float, Float) where zero = (0, 0) {-# INLINE zero #-} (~+~) (a1, a2) (b1, b2) = (c1, c2) where !c1 = a1 + b1 !c2 = a2 + b2 {-# INLINE (~+~) #-} (~-~) (a1, a2) (b1, b2) = (c1, c2) where !c1 = a1 - b1 !c2 = a2 - b2 {-# INLINE (~-~) #-} (~*~) (a1, a2) b = (c1, c2) where !c1 = a1 * b !c2 = a2 * b {-# INLINE (~*~) #-} (~/~) (a1, a2) b = (c1, c2) where !c1 = a1 / b !c2 = a2 / b {-# INLINE (~/~) #-} addIf True a b = a ~+~ b addIf False _ b = b {-# INLINE addIf #-} useIf True a = a useIf False _ = (0, 0) {-# INLINE useIf #-} negate (a1, a2) = (~-~) (0, 0) (a1, a2) {-# INLINE negate #-}
gscalzo/HaskellTheHardWay
gloss-try/gloss-master/gloss-examples/raster/Fluid/src-repa/FieldElt.hs
mit
2,210
0
9
1,027
603
344
259
58
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE BangPatterns #-} import Hypervisor.DomainInfo import Hypervisor.XenStore import Hypervisor.Debug import Data.List import Control.Monad import Control.Applicative import Control.Distributed.Process import Control.Distributed.Process.Node import Network.Transport.IVC (createTransport, waitForDoms, waitForKey) import Data.Binary import Data.Typeable data SizedList a = SizedList { size :: Int , elems :: [a] } deriving (Typeable) instance Binary a => Binary (SizedList a) where put (SizedList sz xs) = put sz >> mapM_ put xs get = do sz <- get xs <- getMany sz return (SizedList sz xs) -- Copied from Data.Binary getMany :: Binary a => Int -> Get [a] getMany = go [] where go xs 0 = return $! reverse xs go xs i = do x <- get x `seq` go (x:xs) (i-1) {-# INLINE getMany #-} nats :: Int -> SizedList Int nats = \n -> SizedList n (aux n) where aux 0 = [] aux n = n : aux (n - 1) counter :: Process () counter = go 0 where go :: Int -> Process () go !n = receiveWait [ match $ \xs -> go (n + size (xs :: SizedList Int)) , match $ \them -> send them n >> go 0 ] count :: (Int, Int) -> ProcessId -> Process () count (packets, sz) them = do us <- getSelfPid replicateM_ packets $ send them (nats sz) send them us n' <- expect liftIO $ writeDebugConsole $ (show (packets * sz, n' == packets * sz)) ++ "\n" initialProcess :: XenStore -> String -> Process () initialProcess xs "SERVER" = do us <- getSelfPid liftIO $ xsWrite xs "/process/counter-pid" (show (encode us)) counter initialProcess xs "CLIENT" = do them <- liftIO $ decode . read <$> waitForKey xs "/process/counter-pid" count (10, 10) them main :: IO () main = do xs <- initXenStore Right transport <- createTransport xs doms <- sort <$> waitForDoms xs 2 me <- xsGetDomId xs let role = if me == head doms then "SERVER" else "CLIENT" node <- newLocalNode transport initRemoteTable runProcess node $ initialProcess xs role
hackern/network-transport-ivc
benchmarks/Throughput/Main.hs
mit
2,060
0
16
476
805
404
401
62
2
import Data.Char -- Exercise 1 -- putStr' :: String -> IO () putStr' [] = return () putStr' (x:xs) = putChar x >> putStr' xs -- Exersice 2 -- putStrLn' :: String -> IO () putStrLn' [] = putChar '\n' putStrLn' xs = putStr' xs >> putStrLn' "" -- OK --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putChar '\n' -- OK --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >>= \ x -> putChar '\n' -- NOK (does not compile) --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> \ x -> putChar '\n' -- OK --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putStr' "\n" -- NOK (does not terminate) --putStrLn' [] = putChar '\n' --putStrLn' xs = putStr' xs >> putStrLn' "\n" -- NOK (does not terminate) --putStrLn' [] = return "" --putStrLn' xs = putStrLn' xs >> putStr' "\n" -- NOK (does not compile) --putStrLn' [] = putChar "\n" --putStrLn' xs = putStr' xs >> \ x -> putChar '\n' -- Exercise 3 -- getLine' :: IO String getLine' = get [] get :: String -> IO String get xs = do x <- getChar case x of '\n' -> return xs _ -> get (xs ++ [x]) -- Exercise 4 -- interact' :: (String -> String) -> IO () interact' f = do input <- getLine' putStrLn' (f input) toUpperCase :: String -> String toUpperCase xs = [toUpper x | x <- xs] toLowerCase :: String -> String toLowerCase xs = [toLower x | x <- xs] -- Exercise 5 -- sequence_' :: Monad m => [m a] -> m () sequence_' ms = foldr (>>) (return ()) ms -- NOK (does not compile) --sequence_' [] = return [] --sequence_' (m : ms) = m >> \ _ -> sequence_' ms -- OK --sequence_' [] = return () --sequence_' (m : ms) = (foldl (>>) m ms) >> return () -- NOK (does not compile) --sequence_' ms = foldl (>>) (return ()) ms -- OK --sequence_' [] = return () --sequence_' (m : ms) = m >> sequence_' ms -- OK --sequence_' [] = return () --sequence_' (m : ms) = m >>= \ _ -> sequence_' ms -- NOK (does not compile) --sequence_' ms = foldr (>>=) (return()) ms -- OK --sequence_' ms = foldr (>>) (return()) ms -- NOK (does not compile) --sequence_' ms = foldr (>>) (return []) ms -- Exercise 6 -- sequence' :: Monad m => [m a] -> m [a] sequence' [] = return [] sequence' (m : ms) = do a <- m as <- sequence' ms return (a : as) -- OK --sequence' [] = return [] --sequence' (m : ms) = m >>= \ a -> -- do as <- sequence' ms -- return (a : as) -- NOK (does not compile) --sequence' ms = foldr func (return ()) ms -- where -- func :: (Monad m) => m a -> m [a] -> m [a] -- func m acc = do x <- m -- xs <- acc -- return (x : xs) -- NOK (does not compile) --sequence' ms = foldr func (return []) ms -- where -- func :: (Monad m) => m a -> m [a] -> m [a] -- func m acc = m : acc -- NOK (does not compile) --sequence' [] = return [] --sequence' (m : ms) = return (a : as) -- where -- a <- m -- as <- sequence' ms -- OK --sequence' ms = foldr func (return []) ms -- where -- func :: (Monad m) => m a -> m [a] -> m [a] -- func m acc = do x <- m -- xs <- acc -- return (x : xs) -- NOK (does not compile) --sequence' [] = return [] --sequence' (m : ms) = m >> -- \ a -> -- do as <- sequence' ms -- return (a : as) -- NOK (does not compile) --sequence' [] = return [] --sequence' (m : ms) = m >>= \ a -> -- as <- sequence' ms -- return (a : as) -- Exercise 7 -- mapM' :: Monad m => (a -> m b) -> [a] -> m [b] mapM' f as = sequence' (map f as) -- OK --mapM' f as = sequence' (map f as) -- OK --mapM' [] = return [] --mapM' f (a : as) -- = f a >>= \ b -> mapM' f as >>= \ bs -> return (b : bs) -- NOK (does not compile) --mapM' f as = sequence_' (map f as) -- NOK (does not compile) --mapM' f [] = return [] --mapM' f (a : as) = -- do -- f a -> b -- mapM' f as -> bs -- return (b : bs) -- OK --mapM' f [] = return [] --mapM' f (a : as) -- = do b <- f a -- bs <- mapM' f as -- return (b : bs) -- OK --mapM' f [] = return [] --mapM' f (a : as) -- = f a >>= -- \ b -> -- do bs <- mapM' f as -- return (b : bs) -- NOK (reverses results) --mapM' f [] = return [] --mapM' f (a : as) -- = f a >>= -- \ b -> -- do bs <- mapM' f as -- return (bs ++ [b]) just a = Just a none a = Nothing singleton a = [a] empty a = [] -- Exercise 8 -- filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM' _ [] = return [] filterM' p (x : xs) = do flag <- p x ys <- filterM' p xs if flag then return (x : ys) else return ys maybeEven :: Int -> Maybe Bool maybeEven i = if (i `mod` 2 == 0) then Just True else Just False -- Exercise 9 -- foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a foldLeftM f a [] = return a foldLeftM f a (x:xs) = f a x >>= \z -> foldLeftM f z xs testFLM = foldLeftM (\a b -> putChar b >> return (b : a ++ [b])) [] "haskell" >>= \r -> putStrLn r -- Exercise 10 -- With help from: http://stackoverflow.com/questions/17055527/lifting-foldr-to-monad -- foldRightM :: Monad m => (a -> b -> m b) -> b -> [a] -> m b foldRightM f b [] = return b foldRightM f b (x:xs) = (\z -> f x z) <<= foldRightM f b xs where (<<=) = flip (>>=) testFRM = foldRightM (\a b -> putChar a >> return (a : b)) [] (show [1,3..10]) >>= \r -> putStrLn r -- Exersize 11 -- liftM :: Monad m => (a -> b) -> m a -> m b liftM f m = do x <- m return (f x) -- OK --liftM f m = do x <- m -- return (f x) -- NOK (does not compile) --liftM f m = m >>= \ a -> f a -- OK --liftM f m = m >>= \ a -> return (f a) -- NOK (does not compile) --liftM f m = return (f m) -- NOK (does not compile) --liftM f m = m >>= \ a -> m >> \ b -> return (f a) -- NOK (does not compile) --liftM f m = m >>= \ a -> m >> \ b -> return (f b) -- NOK (does not compile) --liftM f m = mapM f [m] -- NOK (does not compile) --liftM f m = m >> \ a -> return (f a) testLM = liftM toUpper (Just 'a')
anwb/fp-one-on-one
lecture-08-hw.hs
mit
6,376
1
13
2,097
1,279
715
564
56
2
module Sync.MerkleTree.Client where import Codec.Compression.GZip import Control.Monad import Control.Monad.IO.Class import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BL import qualified Data.Foldable as F import Data.Function import Data.IORef import Data.List import qualified Data.Map as M import Data.Monoid (Sum (..)) import Data.Ratio import Data.Set (Set) import qualified Data.Set as S import Data.String.Interpolate.IsString import qualified Data.Text as T import Data.Time.Clock import Foreign.C.Types import Sync.MerkleTree.CommTypes import Sync.MerkleTree.Trie import Sync.MerkleTree.Types import Sync.MerkleTree.Util.Progress import System.Directory import System.IO import System.PosixCompat.Files data Diff a = Diff (Set a) (Set a) instance Ord a => Semigroup (Diff a) where (<>) (Diff x1 y1) (Diff x2 y2) = Diff (x1 `S.union` x2) (y1 `S.union` y2) instance Ord a => Monoid (Diff a) where mempty = Diff S.empty S.empty showText :: (Show a) => a -> T.Text showText = T.pack . show dataSize :: (F.Foldable f) => f Entry -> FileSize dataSize s = getSum $ F.foldMap sizeOf s where sizeOf (FileEntry f) = Sum $ f_size f sizeOf (DirectoryEntry _) = Sum $ FileSize 0 dataSizeText :: (F.Foldable f) => f Entry -> T.Text dataSizeText s = T.concat [showText $ unFileSize $ dataSize s, " bytes"] logClient :: (Protocol m, MonadFail m) => T.Text -> m () logClient t = do True <- logReq t return () data SimpleEntry = FileSimpleEntry Path | DirectorySimpleEntry Path deriving (Eq, Ord) analyseEntries :: Diff Entry -> ([Entry], [Entry], [Entry]) analyseEntries (Diff obsoleteEntries newEntries) = (M.elems deleteMap, M.elems changeMap, M.elems newMap) where deleteMap = M.difference obsMap updMap changeMap = M.intersection updMap obsMap newMap = M.difference updMap obsMap obsMap = M.fromList $ S.toList $ S.map keyValue obsoleteEntries updMap = M.fromList $ S.toList $ S.map keyValue newEntries keyValue x = (name x, x) name (FileEntry f) = FileSimpleEntry $ f_name f name (DirectoryEntry f) = DirectorySimpleEntry f data Cost = Cost { c_fileCount :: Int, c_dataSize :: FileSize } instance Semigroup Cost where (<>) x y = Cost { c_fileCount = c_fileCount x + c_fileCount y, c_dataSize = c_dataSize x + c_dataSize y } instance Monoid Cost where mempty = Cost 0 0 checkClockDiff :: (MonadIO m, Protocol m, ?clientServerOptions :: ClientServerOptions) => m (Maybe T.Text) checkClockDiff | Just (realToFrac -> treshold, realToFrac -> skew) <- compareClocks = do t0 <- liftIO getCurrentTime t1 <- liftM (addUTCTime skew) queryTime t2 <- liftIO getCurrentTime case (and [diffUTCTime t0 t1 < treshold, diffUTCTime t1 t2 < treshold]) of False -> return $ Just $ [i|Warning: Server and client clocks drift by at least #{treshold} seconds!|] True -> return Nothing | otherwise = return Nothing abstractClient :: (MonadIO m, Protocol m, MonadFail m, ?clientServerOptions :: ClientServerOptions) => FilePath -> Trie Entry -> m (Maybe T.Text) abstractClient fp trie = do drift <- checkClockDiff case drift of Nothing -> syncClient fp trie Just msg -> do True <- terminateReq (Just msg) return (Just msg) syncClient :: (MonadIO m, Protocol m, MonadFail m, ?clientServerOptions :: ClientServerOptions) => FilePath -> Trie Entry -> m (Maybe T.Text) syncClient fp trie = do logClient $ [i|Hash of destination directory: #{t_hash trie} \n|] Diff oent nent <- nodeReq (rootLocation, trie) let (delEntries, changedEntries, newEntries) = analyseEntries (Diff oent nent) logClient $ T.concat [ [i|Client has #{length delEntries} superfluos files of size |], [i|#{dataSizeText delEntries}, #{length changedEntries} changed files of size |], [i|#{dataSizeText changedEntries} and #{length newEntries} missing files of size |], [i|#{dataSizeText newEntries}.\n|] ] when shouldDelete $ forM_ (reverse $ sort delEntries) $ \e -> case e of FileEntry f -> liftIO $ removeFile $ toFilePath fp $ f_name f DirectoryEntry p -> liftIO $ removeDirectoryRecursive $ toFilePath fp p let updateEntries = [e | shouldAdd, e <- newEntries] ++ [e | shouldUpdate, e <- changedEntries] progressLast <- liftIO $ getCurrentTime >>= newIORef runProgress (showProgess progressLast) $ F.traverse_ (syncNewOrChangedEntries fp) $ groupBy ((==) `on` levelOf) $ sort $ updateEntries logClient "Done. \n" True <- terminateReq Nothing return Nothing syncNewOrChangedEntries :: (MonadIO m, MonadFail m, Protocol m, HasProgress Cost m) => FilePath -> [Entry] -> m () syncNewOrChangedEntries fp entries = F.traverse_ (synchronizeNewOrChangedEntry fp) entries showProgess :: (MonadIO m, MonadFail m, Protocol m) => IORef UTCTime -> ProgressState Cost -> m () showProgess progressLast c = do t <- liftIO getCurrentTime l <- liftIO $ readIORef progressLast when (diffUTCTime t l > fromRational (1 % 2)) $ do logClient $ T.concat [ [i|Transfering: #{render c_fileCount} files, |], [i|#{render (unFileSize . c_dataSize)} bytes. \r|] ] t2 <- liftIO getCurrentTime liftIO $ writeIORef progressLast t2 where render :: (Show a) => (Cost -> a) -> T.Text render f = [i|#{f (ps_completed c)}/#{f (ps_planned c)}|] synchronizeNewOrChangedEntry :: (MonadIO m, MonadFail m, Protocol m, HasProgress Cost m) => FilePath -> Entry -> m () synchronizeNewOrChangedEntry fp entry = case entry of FileEntry f -> do progressPlanned $ Cost {c_fileCount = 1, c_dataSize = f_size f} firstResult <- queryFileReq (f_name f) h <- liftIO $ openFile (toFilePath fp $ f_name f) WriteMode let loop result = case result of Final -> return () ToBeContinued content contHandle -> do let bs = BL.toStrict $ decompress $ BL.fromStrict content liftIO $ BS.hPut h $ bs progressCompleted $ mempty {c_dataSize = fromIntegral $ BS.length bs} queryFileContReq contHandle >>= loop loop firstResult liftIO $ hClose h let modTime = (CTime $ fromIntegral $ unModTime $ f_modtime f) liftIO $ setFileTimes (toFilePath fp $ f_name f) modTime modTime progressCompleted $ mempty {c_fileCount = 1} DirectoryEntry p -> do progress $ mempty {c_fileCount = 1} liftIO $ createDirectory $ toFilePath fp p nodeReq :: (MonadIO m, Protocol m, MonadFail m) => (TrieLocation, Trie Entry) -> m (Diff Entry) nodeReq (loc, trie) = do fp <- queryHashReq loc if | fp == toFingerprint trie -> return mempty | Node arr <- t_node trie, NodeType == f_nodeType fp -> fmap (foldl1 (<>)) $ traverse nodeReq (expand loc arr) | otherwise -> do s' <- querySetReq loc let s = getAll trie return $ Diff (s `S.difference` s') (s' `S.difference` s)
ekarayel/sync-mht
src/Sync/MerkleTree/Client.hs
mit
7,418
0
23
1,949
2,430
1,246
1,184
-1
-1
module Main where import Grammar import Tokens import Data.List data Satisfiability = SAT | UNSAT deriving (Eq, Show) type Literal = Int type Variable = Int type Clause = [Literal] type VariableAssignement = (Int,Bool) --extract variable from literal exv :: Literal -> Variable exv l | l > 0 = l | l < 0 = -l exvWithValue:: Literal -> VariableAssignement exvWithValue l | l > 0 = (l,True) | l < 0 = (-l,False) assignTrueFor :: [Clause] -> Variable -> [Clause] (assignTrueFor) cnf literal = [ (- literal) `delete` clause | clause <- cnf, (not $ literal `elem` clause)] hasConflict = (elem) [] dpll :: ([Variable], [Clause]) -> [VariableAssignement] ->(Satisfiability,[VariableAssignement]) dpll (vss@(x:vs),cnf) as | hasConflict cnf = (UNSAT,[]) | let (result,list) = enterDecisionLevelWAL x, result == SAT = (result,list) | otherwise = enterDecisionLevelWAL (-x) -- enterDecisionLevelWAL: enter Decision Level With Assigned Literal where enterDecisionLevelWAL theVariable = do_up_and_ple (vs, (cnf `assignTrueFor` theVariable)) (exvWithValue theVariable:as) dpll ([],_) as = (SAT,as) -- do_up_and_ple: do unit propagation && pure literal elmination do_up_and_ple :: ([Variable], [Clause]) -> [VariableAssignement] ->(Satisfiability,[VariableAssignement]) do_up_and_ple (vs,cnf) as = dpll (vs',cnf') as' where ((vs',cnf'),as') = up_and_ple ((vs,cnf),as) up_and_ple x = check_if_ple_gets_same_result (ple x') x' where x' = (up (ple x)) check_if_ple_gets_same_result x previous | x == previous = x | otherwise = up_and_ple x -- pure literal elmination ple ((vs,cnf),as) | length pls == 0 = ((vs,cnf),as) | otherwise = up ((vs',cnf'),as') where cnf' = foldl (assignTrueFor) cnf pls vs' = vs \\ (fmap exv pls) as' = as ++ (fmap exvWithValue pls) pls = nubBy (==) $ find_pure_literals literals [] literals = concat cnf find_pure_literals (x:xs) o = find_pure_literals xs o' where o' | (x `elem` literals) && ( -x `elem` literals) = o | (-x `elem` literals) = -x:o | otherwise = x:o find_pure_literals [] o = o -- unit propagation up ((vs,cnf),as) | length ucs == 0 = ((vs,cnf),as) | otherwise = up ((vs',cnf'),as') where cnf' = foldl (assignTrueFor) cnf ucs as' = as ++ (fmap exvWithValue ucs) vs' = vs \\ (fmap exv ucs) ucs = [ x | (x:xs) <- cnf, xs == []] dpllStart :: ([Variable], [Clause]) ->(Satisfiability,[VariableAssignement]) dpllStart (vs,cnf) = do_up_and_ple (vs, cnf) [] readyForDPLL :: Exp -> ([Variable], [Clause]) readyForDPLL (WholeFormula a _ b) = ([1..a], makeCNF b) makeCNF :: Exp -> [Clause] makeCNF (SubFormula a b) = [makeClause a, makeClause b] makeCNF (SubFormulaJoined a xs) = makeClause a : makeCNF xs makeClause :: Exp -> Clause makeClause (WholeClause a) = makeClause a makeClause (WholeUnitClause a) = [l a] makeClause (SubClause a b) = [l a, l b] makeClause (SubClauseJoined a xs) = l a : makeClause xs l :: Exp -> Int l (Negative (Literal x)) = -x l (Literal x) = x main :: IO () main = do s <- getContents print $ dpllStart ( readyForDPLL $ parseCNF (scanTokens s) )
0a-/Haskell-DPLL-SAT-Solver
src/Main.hs
mit
3,349
0
15
828
1,406
760
646
76
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} module WhatIsThisGame.Rendering (performRender) where -------------------- -- Global Imports -- import Graphics.Rendering.OpenGL hiding ( Shader , Color ) import Data.Foldable hiding (foldl1, mapM_) import Graphics.Rendering.FTGL import Control.Applicative import Graphics.VinylGL import Graphics.GLUtil import Data.Vinyl import Linear.V2 ------------------- -- Local Imports -- import WhatIsThisGame.Input import WhatIsThisGame.Data ---------- -- Code -- -- | Scaling a coordinate to the window size. scaleCoord :: (Real a, Fractional b) => V2 a -> IO (V2 b) scaleCoord (V2 x y) = do (V2 w h) <- ioRenderSize return $ V2 (realToFrac x / w) (realToFrac y / h) -- | Generating a list of vertices for a quad based on a position and a size. generateVertices :: (Real a, Fractional b) => V2 a -> V2 a -> IO [V2 b] generateVertices p s = do (V2 x y) <- scaleCoord p (V2 w h) <- scaleCoord s return $ V2 <$> [x, x + w] <*> [y, y + h] -- | Calculating the number of indices required for a list. calcIndices :: (Enum b, Num b) => Int -> [b] calcIndices n = take (6 * n) $ foldMap (flip map [0, 1, 2, 2, 1, 3] . (+)) [0, 4..] -- | Computing the texture coordinate for each input coordinate. tileTex :: [[V2 GLfloat]] -> [PlainFieldRec [VertexCoord, TextureCoord]] tileTex = foldMap (flip (zipWith (<+>)) (cycle coords) . map (vertexCoord =:)) where coords = map (textureCoord =:) $ V2 <$> [0, 1] <*> [1, 0] -- | Rendering a set of @'Sprite'@s contained within a list of @'Render'@ -- calls. actuallyPerformRender :: CamMatrix -> Shader -> SpriteBatch -> IO () actuallyPerformRender cm (Shader sp) (SpriteBatch rs) = do loadIdentity let tos = map (\(SpriteRender (Sprite a) _ _) -> a) rs ps = map (\(SpriteRender _ a _) -> a) rs ss = map (\(SpriteRender _ _ a) -> a) rs len = length rs verts <- mapM (uncurry generateVertices) (zip ps ss) >>= bufferVertices . tileTex eb <- bufferIndices $ calcIndices len vao <- makeVAO $ do enableVertices' sp verts bindVertices verts bindBuffer ElementArrayBuffer $= Just eb currentProgram $= Just (program sp) setUniforms sp cm withVAO vao . withTextures2D tos $ drawIndexedTris (2 * fromIntegral len) currentProgram $= Nothing deleteVertices verts deleteObjectName eb deleteVAO vao -- | Rendering a @'SpriteBatch'@. renderSpriteBatch :: CamMatrix -> Shader -> SpriteBatch -> IO () renderSpriteBatch = actuallyPerformRender -- | Rendering a @'TextRender'@. renderText :: CamMatrix -> Shader -> TextRender -> IO () renderText _ _ (TextRender font string (V2 x y) size) = do loadIdentity (V2 w h) <- ioRenderSize :: IO (V2 Float) ortho 0 (realToFrac w) 0 (realToFrac h) (-1) 1 translate $ (Vector3 (realToFrac x) (realToFrac y) 0 :: Vector3 GLfloat) color (Color3 1 1 1 :: Color3 GLfloat) setFontFaceSize font size (size * 2) renderFont font string All -- | Performing a bunch of @'Renders'@. performRender :: CamMatrix -> (Shader, Shader) -> Renders -> IO () performRender _ _ [] = return () performRender cm sp@(ss, ts) (r:rs) = do case r of (RenderSprite sr) -> renderSpriteBatch cm ss $ SpriteBatch [sr] (RenderSprites sb) -> renderSpriteBatch cm ss sb (RenderText tr) -> renderText cm ts tr performRender cm sp rs
crockeo/whatisthisgame
src/WhatIsThisGame/Rendering.hs
mit
3,449
0
16
789
1,223
624
599
69
3
{-# LANGUAGE RecursiveDo #-} module Main where import Control.Monad import Control.Monad.Tardis print_tardis_example :: IO () print_tardis_example = print $ runTardis tardis_example (0,0) tardis_example = do x <- getFuture sendFuture 234 sendPast 123 y <- getPast return (x + y)
sordina/tardistest
src/Examples.hs
mit
296
0
9
56
90
46
44
12
1
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./Maude/Symbol.hs Description : Maude Symbols Copyright : (c) Martin Kuehl, Uni Bremen 2008-2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable Definition of symbols for Maude. -} module Maude.Symbol ( {- * Types The Symbol type -} Symbol (..), -- ** Auxiliary types Symbols, SymbolSet, SymbolMap, SymbolRel, kindSym2sortSym, -- * Conversion toId, qualify, asSort, asKind, toType, toOperator, -- * Construction mkOpTotal, mkOpPartial, -- * Testing sameKind, ) where import Maude.AS_Maude import Maude.Meta.HasName import Data.Data import Data.Set (Set) import Data.Map (Map) import Common.Lib.Rel (Rel) import qualified Data.Set as Set import qualified Common.Lib.Rel as Rel import Common.Id (Id, mkId, mkSimpleId, GetRange, getRange, nullRange) import Common.Doc import Common.DocUtils (Pretty (..)) import Data.Maybe (fromJust) -- * Types {- ** The Symbol type A 'Sort', 'Kind', 'Label', or 'Operator'. -} data Symbol = Sort Qid -- ^ A 'Sort' Symbol | Kind Qid -- ^ A 'Kind' Symbol | Labl Qid -- ^ A 'Label' Symbol | Operator Qid Symbols Symbol -- ^ A qualified 'Operator' Symbol | OpWildcard Qid -- ^ A wildcard 'Operator' Symbol deriving (Show, Read, Ord, Eq, Typeable) -- ** Auxiliary types type Symbols = [Symbol] type SymbolSet = Set Symbol type SymbolMap = Map Symbol Symbol type SymbolRel = Rel Symbol -- ** Symbol instances instance HasName Symbol where getName symb = case symb of Sort qid -> qid Kind qid -> qid Labl qid -> qid OpWildcard qid -> qid Operator qid _ _ -> qid mapName mp symb = case symb of Sort qid -> Sort $ mapName mp qid Kind qid -> Kind $ mapName mp qid Labl qid -> Labl $ mapName mp qid OpWildcard qid -> OpWildcard $ mapName mp qid Operator qid dom cod -> Operator (mapName mp qid) dom cod instance Pretty Symbol where pretty symb = case symb of Sort qid -> pretty qid Kind qid -> brackets $ pretty qid Labl qid -> pretty qid OpWildcard qid -> pretty qid Operator qid dom cod -> hsep [pretty qid, colon, hsep $ map pretty dom, funArrow, pretty cod] instance GetRange Symbol where getRange _ = nullRange -- * Conversion -- | Convert 'Symbol' to 'Id'. toId :: Symbol -> Id toId = mkId . return . getName -- | Qualify the 'Symbol' name with a 'Qid'. qualify :: Qid -> Symbol -> Symbol qualify qid = let prepend sym = mkSimpleId $ concat [show qid, "$", show sym] in mapName $ prepend . getName -- | Convert 'Symbol' to 'Symbol', changing 'Kind's to 'Sort's. asSort :: Symbol -> Symbol asSort symb = case symb of Kind qid -> Sort qid _ -> symb -- | Convert 'Symbol' to 'Symbol', changing 'Sort's to 'Kind's. asKind :: Symbol -> Symbol asKind symb = case symb of Sort qid -> Kind qid _ -> symb -- | True iff the argument is a 'Sort' or 'Kind'. isType :: Symbol -> Bool isType symb = case symb of Sort _ -> True Kind _ -> True _ -> False toTypeMaybe :: Symbol -> Maybe Type toTypeMaybe symb = case symb of Sort qid -> Just . TypeSort . SortId $ qid Kind qid -> Just . TypeKind . KindId $ qid _ -> Nothing -- | Convert 'Symbol' to 'Type', if possible. toType :: Symbol -> Type toType = fromJust . toTypeMaybe -- | True iff the argument is a wildcard 'Operator'. isOpWildcard :: Symbol -> Bool isOpWildcard symb = case symb of OpWildcard _ -> True _ -> False -- | True iff the argument is a qualified 'Operator'. isOperator :: Symbol -> Bool isOperator symb = case symb of Operator {} -> True _ -> False toOperatorMaybe :: Symbol -> Maybe Operator toOperatorMaybe symb = case symb of Operator qid dom cod -> Just $ Op (OpId qid) (map toType dom) (toType cod) [] _ -> Nothing -- | Convert 'Symbol' to 'Operator', if possible. toOperator :: Symbol -> Operator toOperator = fromJust . toOperatorMaybe -- * Construction -- | Create a total 'Operator' 'Symbol' with the given profile. mkOpTotal :: Qid -> [Qid] -> Qid -> Symbol mkOpTotal qid dom cod = Operator qid (map Sort dom) (Sort cod) -- | Create a partial 'Operator' 'Symbol' with the given profile. mkOpPartial :: Qid -> [Qid] -> Qid -> Symbol mkOpPartial qid dom cod = Operator qid (map Sort dom) (Kind cod) -- * Testing {- | True iff both 'Symbol's are of the same 'Kind' in the given 'SymbolRel'. The 'isType' predicate is assumed to hold for both 'Symbol's; this precondition is /not/ checked. -} typeSameKind :: SymbolRel -> Symbol -> Symbol -> Bool typeSameKind rel s1 s2 = let preds1 = Rel.predecessors rel s1 preds2 = Rel.predecessors rel s2 succs1 = Rel.succs rel s1 succs2 = Rel.succs rel s2 psect = Set.intersection preds1 preds2 ssect = Set.intersection succs1 succs2 in or [ s1 == s2 , Set.member s2 preds1 , Set.member s1 preds2 , Set.member s2 succs1 , Set.member s1 succs2 , not $ Set.null psect , not $ Set.null ssect ] {- | True iff the 'Symbol's of both lists are pairwise of the same 'Kind' in the given 'SymbolRel'. -} zipSameKind :: SymbolRel -> Symbols -> Symbols -> Bool zipSameKind rel s1 s2 = and $ zipWith (sameKind rel) s1 s2 -- | True iff both 'Symbol's are of the same 'Kind' in the given 'SymbolRel'. sameKind :: SymbolRel -> Symbol -> Symbol -> Bool sameKind rel s1 s2 | isOpWildcard s1 && isOperator s2 = True | isOperator s1 && isOpWildcard s2 = True | all isType [s1, s2] = typeSameKind rel (kindSym2sortSym s1) (kindSym2sortSym s2) | all isOperator [s1, s2] = let Operator _ dom1 _ = s1 Operator _ dom2 _ = s2 in zipSameKind rel dom1 dom2 | otherwise = False kindSym2sortSym :: Symbol -> Symbol kindSym2sortSym (Kind q) = Sort q kindSym2sortSym s = s
gnn/Hets
Maude/Symbol.hs
gpl-2.0
6,146
0
12
1,630
1,627
845
782
136
3
{-| Module : $Header$ Copyright : (c) 2014 Edward O'Callaghan License : GPL-2 Maintainer : [email protected] Stability : provisional Portability : portable This module covers L1 FEC, L2 and L3 message translation. -} module BTS.GSMCommon where import Data.Maybe import Data.Tuple -- | Call states based on GSM 04.08 5 and ITU-T Q.931 data CallState = NullState | Paging | AnsweredPaging | MOCInitiated | MOCProceeding | MTCConfirmed | CallReceived | CallPresent | ConnectIndication | Active | DisconnectIndication | ReleaseRequest | SMSDelivering | SMSSubmitting | HandoverInbound | HandoverProgress | HandoverOutbound | BusyReject deriving (Enum) instance Show CallState where show NullState = "null" show Paging = "paging" show AnsweredPaging = "answered-paging" show MOCInitiated = "MOC-initiated" show MOCProceeding = "MOC-proceeding" show MTCConfirmed = "MTC-confirmed" show CallReceived = "call-received" show CallPresent = "call-present" show ConnectIndication = "connect-indication" show Active = "active" show DisconnectIndication = "disconnect-indication" show ReleaseRequest = "release-request" show SMSDelivering = "SMS-delivery" show SMSSubmitting = "SMS-submission" show HandoverInbound = "HANDOVER Inbound" show HandoverProgress = "HANDOVER Progress" show HandoverOutbound = "HANDOVER Outbound" show BusyReject = "Busy Reject" -- | GSM 04.08 Table 10.5.118 and GSM 03.40 9.1.2.5 data TypeOfNumber = UnknownTypeOfNumber | InternationalNumber | NationalNumber | NetworkSpecificNumber | ShortCodeNumber | AlphanumericNumber | AbbreviatedNumber deriving (Eq) instance Enum TypeOfNumber where fromEnum = fromJust . flip lookup tyofno toEnum = fromJust . flip lookup (map swap tyofno) tyofno = [ (UnknownTypeOfNumber, 0) , (InternationalNumber, 1) , (NationalNumber, 2) , (NetworkSpecificNumber, 3) , (ShortCodeNumber, 4) , (AlphanumericNumber, 5) , (AbbreviatedNumber, 6) ] instance Show TypeOfNumber where show UnknownTypeOfNumber = "unknown" show InternationalNumber = "international" show NationalNumber = "national" show NetworkSpecificNumber = "network-specific" show ShortCodeNumber = "short code" -- | GSM 04.08 Table 10.5.118 and GSM 03.40 9.1.2.5 data NumberingPlan = UnknownPlan | E164Plan | X121Plan | F69Plan | NationalPlan | PrivatePlan | ERMESPlan deriving (Eq) instance Enum NumberingPlan where fromEnum = fromJust . flip lookup noplans toEnum = fromJust . flip lookup (map swap noplans) noplans = [ (UnknownPlan, 0) , (E164Plan, 1) , (X121Plan, 3) , (F69Plan, 4) , (NationalPlan, 8) , (PrivatePlan, 9) , (ERMESPlan, 10) ] instance Show NumberingPlan where show UnknownPlan = "unknown" show E164Plan = "E.164/ISDN" show X121Plan = "X.121/data" show F69Plan = "F.69/Telex" show NationalPlan = "national" show PrivatePlan = "private" -- | Codes for GSM band types, GSM 05.05 2. data GSMBand = GSM850 -- ^ US cellular | EGSM900 -- ^ extended GSM | DCS1800 -- ^ worldwide DCS band | PCS1900 -- ^ US PCS band deriving (Eq) instance Enum GSMBand where fromEnum = fromJust . flip lookup gsmbands toEnum = fromJust . flip lookup (map swap gsmbands) gsmbands = [ (GSM850, 850) , (EGSM900, 900) , (DCS1800, 1800) , (PCS1900, 1900) ] -- | Codes for logical channel types. data ChannelType = -- | Non-dedicated control channels. SCHType -- ^ sync | FCCHType -- ^ frequency correction | BCCHType -- ^ broadcast control | CCCHType -- ^ common control, a combination of several sub-types | RACHType -- ^ random access | SACCHType -- ^ slow associated control (acutally dedicated, but...) | CBCHType -- ^ cell broadcast channel -- | Dedicated control channels (DCCHs). | SDCCHType -- ^ standalone dedicated control | FACCHType -- ^ fast associated control -- | Traffic channels | TCHFType -- ^ full-rate traffic | TCHHType -- ^ half-rate traffic | AnyTCHType -- ^ any TCH type -- | Packet channels for GPRS. | PDTCHCS1Type | PDTCHCS2Type | PDTCHCS3Type | PDTCHCS4Type -- | Packet CHANNEL REQUEST responses -- These are used only as return value from decodeChannelNeeded(), and do not correspond -- to any logical channels. | PSingleBlock1PhaseType | PSingleBlock2PhaseType -- | Special internal channel types. | LoopbackFullType -- ^ loopback testing | LoopbackHalfType -- ^ loopback testing | AnyDCCHType -- ^ any dedicated control channel | UndefinedCHType -- ^ undefined instance Show ChannelType where show UndefinedCHType = "undefined" show SCHType = "SCH" show FCCHType = "FCCH" show BCCHType = "BCCH" show RACHType = "RACH" show SDCCHType = "SDCCH" show FACCHType = "FACCH" show CCCHType = "CCCH" show SACCHType = "SACCH" show TCHFType = "TCH/F" show TCHHType = "TCH/H" show AnyTCHType = "any TCH" show LoopbackFullType = "Loopback Full" show LoopbackHalfType = "Loopback Half" show PDTCHCS1Type = "PDTCHCS1" show PDTCHCS2Type = "PDTCHCS2" show PDTCHCS3Type = "PDTCHCS3" show PDTCHCS4Type = "PDTCHCS4" show PSingleBlock1PhaseType = "GPRS_SingleBlock1Phase" show PSingleBlock2PhaseType = "GPRS_SingleBlock2Phase" show AnyDCCHType = "any DCCH" -- | Mobile identity types, GSM 04.08 10.5.1.4 data MobileIDType = NoIDType | IMSIType | IMEIType | IMEISVType | TMSIType deriving (Eq) instance Enum MobileIDType where fromEnum = fromJust . flip lookup mobidty toEnum = fromJust . flip lookup (map swap mobidty) mobidty = [ (NoIDType, 0) , (IMSIType, 1) , (IMEIType, 2) , (IMEISVType, 3) , (TMSIType, 4) ] instance Show MobileIDType where show NoIDType = "None" show IMSIType = "IMSI" show IMEIType = "IMEI" show TMSIType = "TMSI" show IMEISVType = "IMEISV" -- | Type and TDMA offset of a logical channel, from GSM 04.08 10.5.2.5 data TypeAndOffset = TDMA_MISC | TCHF_0 -- | .. | TCHH_0 | TCHH_1 -- | .. | SDCCH_4_0 | SDCCH_4_1 | SDCCH_4_2 | SDCCH_4_3 -- | .. | SDCCH_8_0 | SDCCH_8_1 | SDCCH_8_2 | SDCCH_8_3 -- | .. | SDCCH_8_4 | SDCCH_8_5 | SDCCH_8_6 | SDCCH_8_7 -- | Some extra ones for our internal use. | TDMA_BEACON_BCCH | TDMA_BEACON_CCCH | TDMA_BEACON | TDMA_PDTCHF -- ^ packet data traffic logical channel, full speed. | TDMA_PDCH -- ^ packet data channel, inclusive | TDMA_PACCH -- ^ packet control channel, shared with data but distinguished in MAC header. | TDMA_PTCCH -- ^ packet data timing advance logical channel | TDMA_PDIDLE -- ^ Handles the packet channel idle frames. deriving (Eq) instance Enum TypeAndOffset where fromEnum = fromJust . flip lookup tyoffset toEnum = fromJust . flip lookup (map swap tyoffset) tyoffset = [ (TDMA_MISC, 0) , (TCHF_0, 1) , (TCHH_0, 2), (TCHH_1, 3) , (SDCCH_4_0, 4), (SDCCH_4_1, 5), (SDCCH_4_2, 6), (SDCCH_4_3, 7) , (SDCCH_8_0, 8), (SDCCH_8_1, 9), (SDCCH_8_2, 10), (SDCCH_8_3, 11) , (SDCCH_8_4, 12), (SDCCH_8_5, 13), (SDCCH_8_6, 14), (SDCCH_8_7, 15) , (TDMA_BEACON_BCCH, 253) , (TDMA_BEACON_CCCH, 252) , (TDMA_BEACON, 255) , (TDMA_PDTCHF, 256) , (TDMA_PDCH, 257) , (TDMA_PACCH, 258) , (TDMA_PTCCH, 259) , (TDMA_PDIDLE, 260) ] instance Show TypeAndOffset where show TDMA_MISC = "(misc)" show TCHF_0 = "TCH/F" show TCHH_0 = "TCH/H-0" show TCHH_1 = "TCH/H-1" show SDCCH_4_0 = "SDCCH/4-0" show SDCCH_4_1 = "SDCCH/4-1" show SDCCH_4_2 = "SDCCH/4-2" show SDCCH_4_3 = "SDCCH/4-3" show SDCCH_8_0 = "SDCCH/8-0" show SDCCH_8_1 = "SDCCH/8-1" show SDCCH_8_2 = "SDCCH/8-2" show SDCCH_8_3 = "SDCCH/8-3" show SDCCH_8_4 = "SDCCH/8-4" show SDCCH_8_5 = "SDCCH/8-5" show SDCCH_8_6 = "SDCCH/8-6" show SDCCH_8_7 = "SDCCH/8-7" show TDMA_BEACON = "BCH" show TDMA_BEACON_BCCH = "BCCH" show TDMA_BEACON_CCCH = "CCCH" show TDMA_PDCH = "PDCH" show TDMA_PACCH = "PACCH" show TDMA_PTCCH = "PTCCH" show TDMA_PDIDLE = "PDIDLE" -- | L3 Protocol Discriminator, GSM 04.08 10.2, GSM 04.07 11.2.3.1.1. data L3PD = L3GroupCallControlPD | L3BroadcastCallControlPD | L3PDSS1PD | L3CallControlPD | L3PDSS2PD | L3MobilityManagementPD | L3RadioResourcePD | L3GPRSMobilityManagementPD | L3SMSPD | L3GPRSSessionManagementPD | L3NonCallSSPD | L3LocationPD | L3ExtendedPD | L3TestProcedurePD | L3UndefinedPD deriving (Eq) instance Enum L3PD where fromEnum = fromJust . flip lookup l3pd toEnum = fromJust . flip lookup (map swap l3pd) l3pd = [ (L3GroupCallControlPD, 0x00) , (L3BroadcastCallControlPD, 0x01) , (L3PDSS1PD, 0x02) , (L3CallControlPD, 0x03) , (L3PDSS2PD, 0x04) , (L3MobilityManagementPD, 0x05) , (L3RadioResourcePD, 0x06) , (L3GPRSMobilityManagementPD, 0x08) , (L3SMSPD, 0x09) , (L3GPRSSessionManagementPD, 0x0a) , (L3NonCallSSPD, 0x0b) , (L3LocationPD, 0x0c) , (L3ExtendedPD, 0x0e) , (L3TestProcedurePD, 0x0f) , (L3UndefinedPD, -1) ] instance Show L3PD where show L3CallControlPD = "Call Control" show L3MobilityManagementPD = "Mobility Management" show L3RadioResourcePD = "Radio Resource" -- | .. uplinkOffsetKHz :: GSMBand -> Int uplinkOffsetKHz b = case b of GSM850 -> 45000 EGSM900 -> 45000 DCS1800 -> 95000 PCS1900 -> 80000 -- | XXX ARFCN should not be a Int rather its own type -- NOTES.. for each band the following inequalities should hold: -- assert((ARFCN>=128)&&(ARFCN<=251)); -- assert((ARFCN>=975)&&(ARFCN<=1023)); -- assert((ARFCN>=512)&&(ARFCN<=885)); -- assert((ARFCN>=512)&&(ARFCN<=810)); uplinkFreqKHz :: GSMBand -> Int -> Int uplinkFreqKHz b arfcn = case b of GSM850 -> 824200+200*(arfcn-128) EGSM900 -> if arfcn <= 124 then 890000+200*arfcn else 890000+200*(arfcn-1024) DCS1800 -> 1710200+200*(arfcn-512) PCS1900 -> 1850200+200*(arfcn-512) -- | ?? downlinkFreqKHz :: GSMBand -- ^ GSM band -> Int -- ^ ARFCN -> Int downlinkFreqKHz band arfcn = uplinkFreqKHz band arfcn + uplinkOffsetKHz band -- | Modulus operations for frame numbers. -- The GSM hyperframe is largest time period in the GSM system, GSM 05.02 4.3.3. -- It is 2715648 hyperframe = 2048 * 26 * 51 -- | Get a clock difference, within the modulus, v1-v2. fnDelta :: Int -> Int -> Int fnDelta u v = if delta >= halfModulus then delta - hyperframe else delta + hyperframe where delta = u - v halfModulus = hyperframe `div` 2 -- | Compare two frame clock values. -- return 1 if v1>v2, -1 if v1<v2, 0 if v1==v2 fnCompare :: Int -> Int -> Int fnCompare u v | fnDelta u v > 0 = 1 | fnDelta u v < 0 = -1 | otherwise = 0 -- | GSM frame clock value. GSM 05.02 4.3 -- No internal thread sync. data Time = Time { fn :: Int -- ^ frame number in the hyperframe , tn :: Int -- ^ timeslot number } deriving (Eq) instance Ord Time where t < t' | fn t == fn t' = tn t < tn t' | otherwise = fnCompare (fn t) (fn t') < 0 t > t' | fn t == fn t' = tn t > tn t' | otherwise = fnCompare (fn t) (fn t') > 0 t <= t' | fn t == fn t' = tn t <= tn t' | otherwise = fnCompare (fn t) (fn t') <= 0 t >= t' | fn t == fn t' = tn t >= tn t' | otherwise = fnCompare (fn t) (fn t') >= 0 instance Show Time where show t = show (tn t) ++ ":" ++ show (fn t) -- | Arithmetic. inc :: Time -> Time inc (Time fn tn) = Time ((fn+1) `mod` hyperframe) tn -- .. -- assert(step<=8); decTN :: Time -> Int -- ^ step -> Time decTN (Time fn tn) s = Time fn' tn' where (fn', tn') | tnx >= 0 = (fn, tnx) | otherwise = (fnx + (if fnx < 0 then hyperframe else 0), tnx + 8) tnx = tn - s fnx = fn - 1 -- .. -- assert(step<=8); incTN :: Time -> Int -- ^ step -> Time incTN (Time fn tn) s = Time fn' tn' where (fn', tn') | tnx <= 7 = (fn, tnx) | otherwise = (fnx `mod` hyperframe, tnx - 8) tnx = tn + s fnx = fn + 1 -- | Standard derivations. sfn, t1, t2, t3, t3p, tc, t1p, t1r :: Time -> Int -- GSM 05.02 3.3.2.2.1 sfn t = fn t `div` (26*51) -- GSM 05.02 3.3.2.2.1 t1 t = sfn t `mod` 2048 -- GSM 05.02 3.3.2.2.1 t2 t = fn t `mod` 26 -- GSM 05.02 3.3.2.2.1 t3 t = fn t `mod` 51 -- GSM 05.02 3.3.2.2.1. t3p t = (t3 t - 1) `div` 10 -- GSM 05.02 6.3.1.3. tc t = (fn t `div` 51) `mod` 8 -- GSM 04.08 10.5.2.30. t1p t = sfn t `mod` 32 -- GSM 05.02 6.2.3 t1r t = t1 t `mod` 64
victoredwardocallaghan/hbts
src/BTS/GSMCommon.hs
gpl-2.0
15,413
0
12
5,770
3,205
1,809
1,396
342
5
{-# LANGUAGE OverloadedStrings #-} module ImageFileNotify where import Control.Concurrent import Control.Monad (forever) import DBus import DBus.Client import Filesystem.Path import Filesystem.Path.CurrentOS import System.FSNotify -- import Prelude hiding (FilePath) actpred :: Event -> Bool actpred (Added _ _) = True actpred _ = False workChan :: Client -> Chan Event -> IO () workChan cli chan = forever $ do ev <- readChan chan case ev of Added fp _ -> do case (toText fp) of Right txt -> emit cli (signal "/image" "org.ianwookim.hoodle" "filepath") { signalBody = [toVariant txt] } _ -> return () _ -> return () -- act = print startImageFileNotify :: Chan Event -> FilePath -> IO () startImageFileNotify chan fp = do withManager $ \wm -> do putStrLn "watching start" watchTreeChan wm fp actpred chan forever getLine
wavewave/hoodle-daemon
exe/ImageFileNotify.hs
gpl-2.0
904
0
20
213
291
147
144
29
3
{-# LANGUAGE TypeSynonymInstances, FlexibleContexts #-} {- | Module : ./CSL/InteractiveTests.hs Description : Test environment for CSL Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : non-portable (uses type-expression in type contexts) This file is for experimenting with the Interpreter instances and general static analysis tools -} module CSL.InteractiveTests where {- import CSL.ReduceInterpreter import CSL.Reduce_Interface import CSL.Transformation import CSL.BoolBasic import CSL.TreePO import CSL.ExtendedParameter import Common.IOS import Common.Result (diags, printDiags, resultToMaybe) import Common.ResultT import Common.Lexer as Lexer import Common.Parsec import qualified Common.Lib.Rel as Rel import Text.ParserCombinators.Parsec import Control.Monad.Trans (MonadIO (..), lift) import Control.Monad (liftM) -- the process communication interface -} import Interfaces.Process as PC import Control.Monad.State (StateT (..)) import Control.Monad.Error (MonadError (..)) import Static.SpecLoader (getSigSensComplete, SigSens (..)) import Foreign.C.Types import CSL.MathematicaInterpreter import CSL.MapleInterpreter import CSL.Interpreter import CSL.Logic_CSL import CSL.Analysis import CSL.AS_BASIC_CSL import CSL.Sign import CSL.Parse_AS_Basic import CSL.Verification import Common.Utils (getEnvDef) import Common.DocUtils import Common.Doc import Common.AS_Annotation import Common.MathLink as ML import Driver.Options import Control.Monad.State.Class import Control.Monad.Reader import Data.Char import Data.Maybe import Data.Time.Clock import qualified CSL.SMTComparison as CMP import CSL.EPRelation import System.IO import System.Directory import qualified Data.Map as Map import qualified Data.Set as Set import Data.List {- MAIN TESTING FUNCTIONS: test 64 assStoreAndProgSimple test 44 assStoreAndProgElim test 45 loadAssignmentStore testResult 54 (depClosure ["F_G"]) (mit, _) <- testWithMaple 4 0.8 stepProg 3 (mit, _) <- testWithMaple 4 0.8 verifyProg 3 ncl <- sens 56 inDefinition (undef ncl) ncl For engineering of the specification (to see how to fix missing constants): sens 56 >>= (\ ncl -> inDefinition (undef ncl) ncl) >>= mapM putStrLn >>= return . length Verification Condition Testing: (as, prog) <- testResult 102 assStoreAndProgSimple let gr = assDepGraphFromDescList (const $ const True) as or short: gr <- fmap (assDepGraphFromDescList (const $ const True) . fst)testResult 102 assStoreAndProgSimple DEACTIVATED: interesting i's: 44, 46 udefC i == show all undefined constants of spec i elimDefs i == ep-eliminated AS for spec i prettyEDefs i == pretty output for elimDefs testElim i == raw elimination proc for spec i prepareAS i == the assignment store after extraction from spec i and further analysis testSMT i == returns the length of elimDefs-output and measures time, good for testing of smt comparison -} help :: IO () help = do s <- readFile "CSL/InteractiveTests.hs" let l = lines s startP = ("MAIN TESTING FUNCTIONS:" /=) endP = ("-}" /=) putStrLn $ unlines $ takeWhile endP $ dropWhile startP l instance Pretty Bool where pretty = text . show data CAS = Maple | Mathematica deriving (Show, Read, Eq) data CASState = MapleState MITrans | MathematicaState MathState -- ------------------------- Shortcuts -------------------------- initFlags :: (StepDebugger m, SymbolicEvaluator m) => Bool -> Bool -> m () initFlags sm dm = do setSymbolicMode sm setDebugMode dm evalWithVerification :: Bool -- ^ auto-close connection -> CAS -> Maybe FilePath -> Maybe String -> Bool -> Bool -> DTime -> Int -> String -> String -> IO CASState evalWithVerification cl c mFp mN smode dmode to v lb sp = let {- exitWhen s = null s || s == "q" || take 4 s == "quit" || take 4 s == "exit" program for initialization -} p prog = do prettyInfo $ text "" prettyInfo $ text "****************** Assignment store loaded ******************" prettyInfo $ text "" mE <- verifyProg prog when (isJust mE) $ prettyInfo $ pretty $ fromJust mE -- readEvalPrintLoop stdin stdout ">" exitWhen in case c of Maple -> do (mit, _) <- testWithMapleGen v to (initFlags smode dmode) p lb sp when cl $ mapleExit mit >> return () return $ MapleState mit Mathematica -> do (mst, _) <- testWithMathematicaGen v mFp mN (initFlags smode dmode) p lb sp when cl $ mathematicaExit mst return $ MathematicaState mst {- mapleLoop :: MITrans -> IO () mapleLoop mit = do x <- getLine if x == "q" then mapleExit mit >> return () else mapleDirect False mit x >>= putStrLn >> mapleLoop mit -} {- ---------------------------------------------------------------------- Gluing the Analysis and Evaluation together ---------------------------------------------------------------------- -} test :: (Pretty a, MonadIO m) => Int -> ([Named CMD] -> m a) -> m () test i f = testResult i f >>= liftIO . print . pretty testResult :: (Pretty a, MonadIO m) => Int -> ([Named CMD] -> m a) -> m a testResult i f = liftIO (sens i) >>= f -- | Returns sorted assignment store and program after EP elimination assStoreAndProgElim :: [Named CMD] -> IO ([(ConstantName, AssDefinition)], [Named CMD]) assStoreAndProgElim ncl = do let (asss, prog) = splitAS ncl gm = fmap analyzeGuarded asss sgl = dependencySortAS gm ve = CMP.VarEnv { CMP.varmap = Map.fromList $ zip ["I", "F"] [1 ..] , CMP.vartypes = Map.empty , CMP.loghandle = Just stdout -- , CMP.loghandle = Nothing } -- ve = emptyVarEnv $ Just stdout el <- execSMTTester' ve $ epElimination sgl return (getElimAS el, prog) -- | Returns sorted assignment store and program without EP elimination assStoreAndProgSimple :: [Named CMD] -> IO ([(ConstantName, AssDefinition)], [Named CMD]) assStoreAndProgSimple ncl = do let (asss, prog) = splitAS ncl gm = fmap analyzeGuarded asss sgl = dependencySortAS gm return (getSimpleAS sgl, prog) loadAssignmentStore :: (MonadState (ASState st) m, AssignmentStore m, MonadIO m) => Bool -> [Named CMD] -> m ([(ConstantName, AssDefinition)], [Named CMD]) loadAssignmentStore b ncl = do let f = if b then assStoreAndProgElim else assStoreAndProgSimple res@(asss, _) <- liftIO $ f ncl loadAS asss return res stepProg :: (MessagePrinter m, MonadIO m, MonadError ASError m) => [Named CMD] -> m (Maybe ASError) stepProg ncl = stepwiseSafe interactiveStepper $ Sequence $ map sentence ncl verifyProg :: (MessagePrinter m, StepDebugger m, VCGenerator m, MonadIO m, MonadError ASError m) => [Named CMD] -> m (Maybe ASError) verifyProg ncl = stepwiseSafe verifyingStepper $ Sequence $ map sentence ncl testWithMapleGen :: Int -> DTime -> MapleIO b -> ([Named CMD] -> MapleIO a) -> String -> String -> IO (MITrans, a) testWithMapleGen v to = testWithCASGen rf where rf adg = runWithMaple adg v to [ "EnCLFunctions" -- , "intpakX" -- Problems with the min,max functions, they are remapped by this package! ] testWithMathematicaGen :: Int -> Maybe FilePath -> Maybe String -> MathematicaIO b -> ([Named CMD] -> MathematicaIO a) -> String -> String -> IO (MathState, a) testWithMathematicaGen v mFp mN = testWithCASGen rf where rf adg = runWithMathematica adg v mFp mN [ "/home/ewaryst/Hets/CSL/CAS/Mathematica.m" ] {- testWithMapleGen :: Int -> DTime -> ([Named CMD] -> MapleIO a) -> String -> String -> IO (MITrans, a) testWithMapleGen verb to f lb sp = do ncl <- fmap sigsensNamedSentences $ sigsensGen lb sp -- get ordered assignment store and program (as, prog) <- assStoreAndProgSimple ncl vchdl <- openFile "/tmp/vc.out" WriteMode -- build the dependency graph let gr = assDepGraphFromDescList (const $ const ()) as -- make sure that the assignment store is loaded into maple before -- the execution of f g x = loadAS as >> modify (\ mit -> mit {vericondOut = Just vchdl}) >> f x -- start maple and run g res <- runWithMaple gr verb to [ "EnCLFunctions" -- , "intpakX" -- Problems with the min,max functions, they are remapped by this package! ] $ g prog hClose vchdl return res -} testWithMaple :: Int -> DTime -> ([Named CMD] -> MapleIO a) -> Int -> IO (MITrans, a) testWithMaple verb to f = uncurry (testWithMapleGen verb to (return ()) f) . libFP getMathState :: Maybe CASState -> MathState getMathState (Just (MathematicaState mst)) = mst getMathState _ = error "getMathState: no MathState" getMapleState :: Maybe CASState -> MITrans getMapleState (Just (MapleState mst)) = mst getMapleState _ = error "getMapleState: no Maple state" testWithCASGen :: ( AssignmentStore as, MonadState (ASState st) as, MonadIO as) => (AssignmentDepGraph () -> as a -> IO (ASState st, a)) -> as b -> ([Named CMD] -> as a) -> String -> String -> IO (ASState st, a) testWithCASGen rf ip f lb sp = do ncl <- fmap sigsensNamedSentences $ sigsensGen lb sp -- get ordered assignment store and program (as, prog) <- assStoreAndProgSimple ncl vchdl <- openFile "/tmp/vc.out" WriteMode -- build the dependency graph let gr = assDepGraphFromDescList (const $ const ()) as {- make sure that the assignment store is loaded into maple before the execution of f -} g x = ip >> loadAS as >> modify (\ mit -> mit {vericondOut = Just vchdl}) >> f x -- start maple and run g res <- rf gr $ (withLogFile "/tmp/evalWV.txt" . g) prog hClose vchdl return res {- ---------------------------------------------------------------------- Temp tools ---------------------------------------------------------------------- -} -- | Returns all constants where the given constants depend on depClosure :: [String] -> [Named CMD] -> IO [[String]] depClosure l ncl = do let (asss, _) = splitAS ncl gm = fmap analyzeGuarded asss dr = getDependencyRelation gm return $ relLayer dr l -- | mark final markFinal :: [String] -> [Named CMD] -> IO [String] markFinal l ncl = do let (asss, _) = splitAS ncl gm = fmap analyzeGuarded asss dr = getDependencyRelation gm f x = case Map.lookup x dr of Just s -> if Set.null s then x ++ " *" else x _ -> x ++ " *" return $ map f l -- | definedIn definedIn :: [String] -> [Named CMD] -> IO [String] definedIn l ncl = return $ map g l where g s = intercalate ", " (mapMaybe (f s) ncl) ++ ":" ++ s f s nc = case sentence nc of Ass (Op oi _ _ _) _ -> if simpleName oi == s then Just $ senAttr nc else Nothing _ -> Nothing inDefinition :: [String] -> [Named CMD] -> IO [String] inDefinition l ncl = let (asss, _) = splitAS ncl gm = fmap analyzeGuarded asss dr = getDependencyRelation gm allDefs = allDefinitions ncl br = Map.filterWithKey (\ k _ -> elem k l) $ getBackRef dr f m = map (g m) g m x = Map.findWithDefault "" x m h = f allDefs f' (x, y) = x ++ ": " ++ intercalate ", " y in return $ map f' $ Map.toList $ fmap h br allDefinitions :: [Named CMD] -> Map.Map String String allDefinitions ncl = Map.fromList $ mapMaybe f ncl where f nc = case sentence nc of Ass (Op oi _ _ _) _ -> Just (simpleName oi, senAttr nc) _ -> Nothing undef :: [Named CMD] -> [String] undef ncl = Set.toList $ undefinedConstants $ fst $ splitAS ncl -- printSetMap Common.Doc.empty Common.Doc.empty dr relLayer :: Ord a => Rel2 a -> [a] -> [[a]] relLayer _ [] = [] relLayer r l = l : relLayer r succs where succs = Set.toList $ Set.unions $ mapMaybe (`Map.lookup` r) l {- emptyVarEnv execSMTComparer :: VarEnv -> SmtComparer a -> IO a splitAS :: [Named CMD] -> (GuardedMap [EXTPARAM], [Named CMD]) getElimAS :: [(String, Guarded EPRange)] -> [(ConstantName, AssDefinition)] dependencySortAS :: GuardedMap EPRange -> [(String, Guarded EPRange)] epElimination :: CompareIO m => [(String, Guarded EPRange)] -> m [(String, Guarded EPRange)] -} casConst :: ASState a -> String -> String casConst mit s = fromMaybe "" $ rolookup (getBMap mit) $ SimpleConstant s enclConst :: ASState a -> String -> OPID enclConst mit s = fromMaybe (error $ "enclConst: no mapping for " ++ s) $ revlookup (getBMap mit) s {- ---------------------------------------------------------------------- general test functions ---------------------------------------------------------------------- -} -- Testing of keyboard-input charInfo :: IO () charInfo = do c <- getChar {- when (c /= 'e') $ putStrLn "" >> putStrLn (c:[]) >> putStrLn (show $ ord c) >> charInfo Escape-button = 27 -} when (ord c /= 27) $ putStrLn "" >> putStrLn [c] >> print $ ord c >> charInfo testspecs :: [(Int, (String, String))] testspecs = [ (44, ("EnCL/EN1591.het", "EN1591")) , (45, ("EnCL/flange.het", "Flange")) , (46, ("EnCL/flange.het", "FlangeComplete")) , (54, ("EnCL/EN1591S.het", "EN1591")) , (55, ("EnCL/flangeS.het", "Flange")) , (56, ("EnCL/flangeS.het", "FlangeComplete")) , (65, ("EnCL/flangeDefault.het", "FlangeDefault")) , (66, ("EnCL/flangeExported.het", "FlangeComplete")) ] sigsensGen :: String -> String -> IO (SigSens Sign CMD) sigsensGen lb sp = do hlib <- getEnvDef "HETS_LIB" $ error "Missing HETS_LIB environment variable" b <- doesFileExist lb let fp = if b then lb else hlib ++ "/" ++ lb ho = defaultHetcatsOpts { libdirs = [hlib] , verbose = 0 } res <- getSigSensComplete True ho CSL fp sp putStrLn "\n" return res siggy :: Int -> IO (SigSens Sign CMD) siggy = uncurry sigsensGen . libFP libFP :: Int -> (String, String) libFP i = fromMaybe (if i >= 0 then ("EnCL/Tests.het", "Test" ++ show i) else ("EnCL/ExtParamExamples.het", 'E' : show (- i))) $ Prelude.lookup i testspecs sigsens :: Int -> IO (Sign, [Named CMD]) sigsens i = do res <- siggy i return ( sigsensSignature res, sigsensNamedSentences res ) sig :: Int -> IO Sign sig = fmap fst . sigsens -- Check if the order is broken or not! sens :: Int -> IO [Named CMD] sens = fmap snd . sigsens cmds :: Int -> IO [CMD] cmds = fmap (map sentence) . sens -- time measurement, pendant of the time shell command time :: MonadIO m => m a -> m a time p = do t <- liftIO getCurrentTime res <- p t' <- liftIO getCurrentTime liftIO $ print $ diffUTCTime t' t return res toE :: String -> EXPRESSION toE = fromJust . parseExpression operatorInfoMap toCmd :: String -> CMD toCmd = fromJust . parseCommand {- ---------------------------------------------------------------------- Smt testing instances ---------------------------------------------------------------------- -} data TestEnv = TestEnv { counter :: Int , varenv :: CMP.VarEnv , loghdl :: Handle } logf :: FilePath logf = "/tmp/CSL.log" teFromVE :: CMP.VarEnv -> IO TestEnv teFromVE ve = do hdl <- openFile logf WriteMode let ve' = ve { CMP.loghandle = Just hdl } return TestEnv { counter = 0, varenv = ve', loghdl = hdl } type SmtTester = StateT TestEnv IO execSMTTester :: CMP.VarEnv -> SmtTester a -> IO (a, Int) execSMTTester ve smt = do (x, s) <- teFromVE ve >>= runStateT smt hClose $ loghdl s return (x, counter s) execSMTTester' :: CMP.VarEnv -> SmtTester a -> IO a execSMTTester' ve smt = do (x, i) <- execSMTTester ve smt putStrLn $ "SMT-Checks: " ++ show i return x instance CompareIO SmtTester where logMessage x = do hdl <- gets loghdl liftIO $ hPutStrLn hdl x rangeFullCmp r1 r2 = do env <- get let f x = x {counter = counter x + 1} ve = varenv env vm = CMP.varmap ve hdl = loghdl env modify f lift $ writeRangesToLog hdl r1 r2 liftIO $ hPutStrLn hdl "" res <- lift $ CMP.smtCompare ve (boolRange vm r1) $ boolRange vm r2 lift $ writeRangesToLog hdl r1 r2 >> hPutStrLn hdl ('=' : show res) return res writeRangesToLog :: Handle -> EPRange -> EPRange -> IO () writeRangesToLog hdl r1 r2 = do let [d1, d2] = map diagnoseEPRange [r1, r2] hPutStr hdl $ show $ text "Cmp" <> parens (d1 <> comma <+> d2) {- ---------------------------------------------------------------------- Smt testing instances ---------------------------------------------------------------------- -} {- show guarded assignments: :m +CSL.Analysis sl <- sens 3 fst $ splitAS s -} {- -- ---------------------------------------------------------------------- -- * calculator test functions -- ---------------------------------------------------------------------- runTest :: ResultT (IOS b) a -> b -> IO a runTest cmd r = fmap fromJust $ runTestM cmd r runTestM :: ResultT (IOS b) a -> b -> IO (Maybe a) runTestM cmd r = fmap (resultToMaybe . fst) $ runIOS r $ runResultT cmd runTest_ :: ResultT (IOS b) a -> b -> IO (a, b) runTest_ cmd r = do (res, r') <- runIOS r $ runResultT cmd return (fromJust $ resultToMaybe res, r') evalL :: AssignmentStore (ResultT (IOS b)) => b -> Int -- ^ Test-spec -> IO b evalL s i = do cl <- cmds i (_, s') <- runIOS s (runResultT $ evaluateList cl) return s' -- ---------------------------------------------------------------------- -- * different parser -- ---------------------------------------------------------------------- -- parses a single extparam range such as: "I>0, F=1" toEP :: String -> [EXTPARAM] toEP [] = [] toEP s = case runParser (Lexer.separatedBy extparam pComma >-> fst) "" "" s of Left e -> error $ show e Right s' -> s' -- parses lists of extparam ranges such as: "I>0, F=1; ....; I=10, F=1" toEPL :: String -> [[EXTPARAM]] toEPL [] = [] toEPL s = case runParser (Lexer.separatedBy (Lexer.separatedBy extparam pComma >-> fst) pSemi >-> fst) "" "" s of Left e -> error $ show e Right s' -> s' toEP1 :: String -> EPExp toEP1 s = case runParser extparam "" "" s of Left e -> error $ show e Right s' -> snd $ fromJust $ toEPExp s' toEPs :: String -> EPExps toEPs = toEPExps . toEP toEPLs :: String -> [EPExps] toEPLs = map toEPExps . toEPL -- ---------------------------------------------------------------------- -- * Extended Parameter tests -- ---------------------------------------------------------------------- {- smtEQScript vMap (boolRange vMap $ epList!!0) (boolRange vMap $ epList!!1) test for smt-export let m = varMapFromList ["I", "J", "F"] let be = boolExps m $ toEPs "I=0" smtBoolExp be compare-check for yices let l2 = [(x,y) | x <- epList, y <- epList] let l3 = map (\ (x, y) -> smtCompareUnsafe vEnv (boolRange vMap x) (boolRange vMap y)) l2 putStrLn $ unlines $ map show $ zip l3 l2 :l CSL/InteractiveTests.hs :m +CSL.Analysis sl <- sens (-82) let grdm = fst $ splitAS sl let sgm = dependencySortAS grdm let grdd = snd $ Map.elemAt 0 grdm let sgm = dependencySortAS grdm getDependencyRelation grdm :l CSL/InteractiveTests.hs :m +CSL.Analysis gm <- fmap grddMap $ sens (-3) let (_, xg) = Map.elemAt 1 gm let (_, yg) = Map.elemAt 2 gm let f grd = (grd, toEPExps $ range grd) let frst = forestFromEPs f $ guards xg putStrLn $ showEPForest show frst foldForest (\ x y z -> x ++ [(y, length z)]) [] frst -} -- undefinedConstants :: GuardedMap a -> Set.Set String -- getElimAS :: [(String, Guarded EPRange)] -> [(ConstantName, AssDefinition)] -- Use this Constant printer for test output instance ConstantPrinter (Reader (ConstantName -> Doc)) where printConstant c = asks ($ c) ppConst :: ConstantName -> Doc ppConst (SimpleConstant s) = text s ppConst (ElimConstant s i) = text s <> text (show $ 1+i) prettyEXP e = runReader (printExpression e) ppConst testSMT = time . fmap length . elimDefs udefC = liftM (undefinedConstants . fst . splitAS) . sens elimDefs = liftM getElimAS . testElim elimConsts = liftM elimConstants . testElim prettyEConsts i = elimConsts i >>= mapM_ f where f (_, m) = mapM_ g $ Map.toList m g (c, er) = putStrLn $ (show $ ppConst c) ++ " :: " ++ show (prettyEPRange er) prettyEDefs i = liftM (unlines . map f) (elimDefs i) >>= putStrLn where f (c, assdef) = concat [ show $ ppConst c, g $ getArguments assdef, " := " , show $ prettyEXP $ getDefiniens assdef] g [] = "" g l = show $ parens $ sepByCommas $ map text l -- irreflexive triangle of a list l: for i < j . (l_i, l_j) irrTriang :: [a] -> [(a,a)] irrTriang [] = [] irrTriang (x:l) = map ((,) x) l ++ irrTriang l -- * Model Generation frmAround "" = "" frmAround s = let l = lines s hd = "--" ++ map (const '-') (head l) in unlines $ hd : map (('|':) . (++"|")) l ++ [hd] modelRg1 :: Map.Map String (Int, Int) modelRg1 = Map.fromList [("I", (-5, 5))] modelRg2 :: Map.Map String (Int, Int) modelRg2 = Map.fromList [("I", (-5, 5)), ("F", (-5, 5))] modelRg3 :: Map.Map String (Int, Int) modelRg3 = Map.fromList [("I", (-5, 5)), ("J", (-5, 5)), ("F", (-5, 5))] printModel :: Map.Map String (Int, Int) -> EPRange -> String printModel x y = modelToString boolModelChar $ modelOf x y pM1::EPRange -> IO () pM2::EPRange -> IO () pM1s::[EPRange] -> IO () pM2s::[EPRange] -> IO () pM2 = putStr . frmAround . printModel modelRg2 pM1 = putStr . frmAround . printModel modelRg1 pM1s = mapM_ pM1 pM2s = mapM_ pM2 toEPR :: String -> EPRange toEPR = Atom . toEPs -- Test for partitioning taken from E82 in CSL/ExtParamExamples.het el11 :: [EPRange] el11 = let x1 = toEPR "I>=0" in [x1, Complement x1] el12 :: [EPRange] el12 = let l = map toEPR ["I=1", "I>1"] in Complement (Union l) : l el13 :: [EPRange] el13 = let x1 = toEPR "I>0" in [x1, Complement x1] el21 :: [EPRange] el21 = let x1 = toEPR "I>=0" in [x1, Complement x1] el22 :: [EPRange] el22 = let l = map toEPR ["I>=0, F>=0", "I<4, F<=4"] inter = Intersection l uni = Union l in uni : inter : Intersection [uni, Complement inter] : l el23 :: [EPRange] el23 = let x1 = toEPR "I>0" in [x1, Complement x1] -- * Partition tests checkForPartition :: [EPRange] -> IO Bool checkForPartition l = execSMTTester' vEnv1 $ f g l where f a [] = return True f a (x:l') = do res <- mapM (a x) l' res' <- f a l' return $ and $ res' : res g x y = fmap (Incomparable Disjoint ==) $ rangeCmp x y part1 :: Partition Int part1 = AllPartition 10 part2 :: Partition Int part2 = Partition $ zip el11 [33 ..] part3 :: Partition Int part3 = Partition $ zip el12 [1 ..] part4 :: Partition Int part4 = Partition $ zip el13 [91 ..] parts = [part1, part2, part3, part4] refinePart a b = execSMTTester' vEnv1 $ refinePartition a b allRefin = do m1 <- mapM (uncurry refinePart) $ irrTriang parts m2 <- mapM (uncurry refinePart) $ irrTriang m1 return (m1, m2) allRShow = do (a, b) <- allRefin showPart1s a putStrLn "==============================================" showPart1s b allRCmp = do (a, b) <- allRefin cmpRg1s a putStrLn "==============================================" cmpRg1s b showPart1s :: Show a => [Partition a] -> IO () showPart1s = let f x = showPart1 x >> putStrLn "===" in mapM_ f showPartX :: Show a => (EPRange -> IO ()) -> Partition a -> IO () showPart1 :: Show a => Partition a -> IO () showPart2 :: Show a => Partition a -> IO () showPartX _ (AllPartition x) = do putStrLn $ show x putStrLn "All\n\n" showPartX fM (Partition l) = let f (re, x) = do putStrLn $ show x fM re putStrLn "\n" in mapM_ f l showPart1 = showPartX pM1 showPart2 = showPartX pM2 class HasRanges a where getRanges :: a -> [EPRange] instance HasRanges (Partition a) where getRanges (AllPartition x) = [] getRanges (Partition l) = map fst l instance HasRanges a => HasRanges [a] where getRanges = concatMap getRanges instance HasRanges (Guarded EPRange) where getRanges = map range . guards instance HasRanges (String, Guarded EPRange) where getRanges = map range . guards . snd cmpRg1 :: HasRanges a => a -> IO () cmpRg1 = putStrLn . concat . map (printModel modelRg1) . getRanges cmpRg1s :: HasRanges a => [a] -> IO () cmpRg1s = let f = putStrLn . concat . map (printModel modelRg1) . getRanges g x = f x >> putStrLn "===" in mapM_ g -- * elim proc testing {- :l CSL/InteractiveTests.hs :m +CSL.Analysis sl <- sens (-82) let grdm = fst $ splitAS sl let sgm = dependencySortAS grdm -} -- elimTestInit :: Int -> [(String, Guarded EPRange)] -> IO [Guard EPRange] elimTestInit i gl = do let grd = (guards $ snd $ head gl)!!i execSMTTester' vEnv $ eliminateGuard Map.empty grd pgX :: (EPRange -> IO a) -> Guard EPRange -> IO () pgX fM grd = do fM $ range grd putStr "Def: " putStrLn $ show $ pretty $ definition grd putStrLn "" pg1 :: Guard EPRange -> IO () pg1 = pgX pM1 pg2 :: Guard EPRange -> IO () pg2 = pgX pM2 pgrddX :: (EPRange -> IO a) -> Guarded EPRange -> IO () pgrddX fM grdd = mapM_ (pgX fM) $ guards grdd pgrdd2 :: Guarded EPRange -> IO () pgrdd2 = pgrddX pM2 printASX :: (EPRange -> IO a) -> [(String, Guarded EPRange)] -> IO () printASX fM l = mapM_ f l where f (s, grdd) = do putStr s putStrLn ":" pgrddX fM grdd putStrLn "" printAS1 :: [(String, Guarded EPRange)] -> IO () printAS1 = printASX pM1 printAS2 :: [(String, Guarded EPRange)] -> IO () printAS2 = printASX pM2 testElim :: Int -> IO [(String, Guarded EPRange)] testElim i = prepareAS i >>= elimEPs prepareAS :: Int -> IO [(String, Guarded EPRange)] prepareAS = liftM (dependencySortAS . fmap analyzeGuarded . fst . splitAS) . sens prepareProg :: Int -> IO [Named CMD] prepareProg = liftM (snd . splitAS) . sens progAssignments :: Int -> IO [(EXPRESSION, EXPRESSION)] progAssignments = liftM subAss . prepareProg -- get the first guarded-entry from the AS -- grdd <- fmap (snd . head) $ getAS (-821) getAS :: Int -> IO [(String, Guarded [EXTPARAM])] getAS = liftM (Map.toList . fst . splitAS) . sens getASana :: Int -> IO [(String, Guarded EPRange)] getASana = liftM (Map.toList . fmap analyzeGuarded . fst . splitAS) . sens elimEPs :: [(String, Guarded EPRange)] -> IO [(String, Guarded EPRange)] elimEPs l = do -- execSMTComparer vEnv $ epElimination l execSMTTester' vEnv $ epElimination l grddMap :: [Named CMD] -> GuardedMap [EXTPARAM] grddMap = foldr (uncurry $ addAssignment "?") Map.empty . assignments assignments :: [Named CMD] -> [(EXPRESSION, EXPRESSION)] assignments = assignments' . map sentence assignments' :: [CMD] -> [(EXPRESSION, EXPRESSION)] assignments' = mapMaybe getAss subAss :: [Named CMD] -> [(EXPRESSION, EXPRESSION)] subAss = concatMap subAssignments . map sentence getAss (Ass c def) = Just (c,def) getAss _ = Nothing varEnvFromList :: [String] -> VarEnv varEnvFromList l = error "" -- | Generates from a list of Extended Parameter names an id-mapping varMapFromList :: [String] -> VarMap varMapFromList l = Map.fromList $ zip l $ [1 .. length l] -- | Generates from a list of Extended Parameter names an id-mapping varMapFromSet :: Set.Set String -> VarMap varMapFromSet = varMapFromList . Set.toList epList :: [EPRange] epList = let l = map (Atom . toEPs) ["", "I=1,F=0", "I=0,F=0", "I=0", "I=1", "F=0", "I>0", "I>2", "I>0,F>2"] in Intersection l : Union l : l epDomain :: [(String, EPExps)] epDomain = zip ["I", "F"] $ map toEPs ["I>= -1", "F>=0"] vMap :: Map.Map String Int vMap = varMapFromSet $ namesInList epList -- vTypes = Map.map (const Nothing) vMap vTypes = Map.fromList $ map (\ (x,y) -> (x, boolExps vMap y)) epDomain vEnvX = VarEnv { varmap = vMap, vartypes = Map.empty, loghandle = Nothing } vEnv1 = VarEnv { varmap = Map.fromList [("I", 1)], vartypes = Map.empty, loghandle = Nothing } --vEnv = VarEnv { varmap = vMap, vartypes = vTypes, loghandle = Nothing } vEnv = vEnvX printOrdEPs :: String -> IO () printOrdEPs s = let ft = forestFromEPs ((,) ()) $ toEPLs s in putStrLn $ showEPForest show ft --forestFromEPs :: (a -> EPTree b) -> [a] -> EPForest b compareEPgen :: Show a => (String -> a) -> (a -> a -> SetOrdering) -> String -> String -> IO SetOrdering compareEPgen p c a b = let epA = p a epB = p b in do putStrLn $ show epA putStrLn $ show epB return $ c epA epB compareEP' = compareEPgen toEP1 compareEP compareEPs' = compareEPgen toEPs compareEPs -- ---------------------------------------------------------------------- -- * MAPLE INTERPRETER -- ---------------------------------------------------------------------- -- just call the methods in MapleInterpreter: mapleInit, mapleExit, mapleDirect -- , the CS-interface functions and evalL -- ---------------------------------------------------------------------- -- * FIRST REDUCE INTERPRETER -- ---------------------------------------------------------------------- -- first reduce interpreter reds :: Int -- ^ Test-spec -> IO ReduceInterpreter reds i = do r <- redsInit sendToReduce r "on rounded; precision 30;" evalL r i -- use "redsExit r" to disconnect where "r <- red" {- -- many instances (connection/disconnection tests) l <- mapM (const reds 1) [1..20] mapM redsExit l -- BA-test: (l, r) <- redsBA 2 'l' is a list of response values for each sentence in spec Test2 'r' is the reduce connection -} -- ---------------------------------------------------------------------- -- * SECOND REDUCE INTERPRETER -- ---------------------------------------------------------------------- -- run the assignments from the spec redc :: Int -- ^ verbosity level -> Int -- ^ Test-spec -> IO RITrans redc v i = do r <- redcInit v evalL r i redcNames :: RITrans -> IO [ConstantName] redcNames = runTest $ liftM toList names redcValues :: RITrans -> IO [(ConstantName, EXPRESSION)] redcValues = runTest values -- run the assignments from the spec redcCont :: Int -- ^ Test-spec -> RITrans -> IO RITrans redcCont i r = do cl <- cmds i (res, r') <- runIOS r (runResultT $ evaluateList cl) printDiags (PC.verbosity $ getRI r') (diags res) return r' --- Testing with many instances {- -- c-variant lc <- time $ mapM (const $ redc 1 1) [1..20] mapM redcExit lc -- to communicate directly with reduce use: let r = head lc OR r <- redc x y let ri = getRI r redcDirect ri "some command;" -} -- ---------------------------------------------------------------------- -- * TRANSFORMATION TESTS -- ---------------------------------------------------------------------- data WithAB a b c = WithAB a b c instance Show c => Show (WithAB a b c) where show (WithAB _ _ c) = show c getA (WithAB a _ _) = a getB (WithAB _ b _) = b getC (WithAB _ _ c) = c -- tt = transformation tests (normally Calculationsystem monad result) -- tte = tt with evaluation (normally gets a cs-state and has IO-result) runTT c s vcc = do (res, s') <- runIOS s $ runResultT $ runStateT c vcc let (r, vcc') = fromJust $ resultToMaybe res return $ WithAB vcc' s' r runTTi c s = do (res, s') <- runIOS s (runResultT $ runStateT c emptyVCCache) let (r, vcc') = fromJust $ resultToMaybe res return $ WithAB vcc' s' r --s -> t -> t1 -> IO (Common.Result.Result a, s) -- ttesd :: ( VarGen (ResultT (IOS s)) -- , VariableContainer a VarRange -- , AssignmentStore (ResultT (IOS s)) -- , Cache (ResultT (IOS s)) a String EXPRESSION) => -- EXPRESSION -> s -> a -> IO (WithAB a s EXPRESSION) ttesd e = runTT (substituteDefined e) ttesdi e = runTTi (substituteDefined e) -- -- substituteDefined with init --ttesdi s e = ttesd s vc e {- r <- mapleInit 1 r <- redcInit 3 r' <- evalL r 3 let e = toE "sin(x) + 2*cos(y) + x^2" w <- ttesdi e r' let vss = getA w -- show value for const x runTest (CSL.Interpreter.lookup "x") r' >>= return . pretty runTest (CSL.Interpreter.eval $ toE "cos(x-x)") r' >>= return . pretty w' <- ttesd e r' vss w' <- ttesd e r' vss mapleExit r y <- fmap fromJust $ runTest (CSL.Interpreter.lookup "y") r' runTest (verificationCondition y $ toE "cos(x)") r' pretty it r <- mapleInit 4 r <- redcInit 4 r' <- evalL r 301 let t = toE "cos(z)^2 + cos(z ^2) + sin(y) + sin(z)^2" t' <- runTest (eval t) r' vc <- runTest (verificationCondition t' t) r' pretty vc -} {- -- exampleRun r <- mapleInit 4 let t = toE "factor(x^5-15*x^4+85*x^3-225*x^2+274*x-120)" t' <- runTest (eval t) r vc <- runTest (verificationCondition t' t) r pretty vc -- exampleRun2 r <- mapleInit 4 r' <- evalL r 1011 let t = toE "factor(x^5-z4*x^4+z3*x^3-z2*x^2+z1*x-z0)" t' <- runTest (eval t) r' vc <- runTest (verificationCondition t' t) r' pretty vc let l = ["z4+z3+20", "z2 + 3*z4 + 4", "3 * z3 - 30", "5 * z4 + 10", "15"] let tl = map toE l tl' <- mapM (\x -> runTest (eval x) r') tl vcl <- mapM (\ (x, y) -> runTest (verificationCondition x y) r') $ zip tl' tl mapM_ putStrLn $ map pretty vcl -} -- ---------------------------------------------------------------------- -- * Utilities -- ---------------------------------------------------------------------- -- ---------------------------------------------------------------------- -- ** Operator extraction -- ---------------------------------------------------------------------- addOp :: Map.Map String Int -> String -> Map.Map String Int addOp mp s = Map.insertWith (+) s 1 mp class OpExtractor a where extr :: Map.Map String Int -> a -> Map.Map String Int instance OpExtractor EXPRESSION where extr m (Op op _ l _) = extr (addOp m $ show op) l extr m (Interval _ _ _) = addOp m "!Interval" extr m (Int _ _) = addOp m "!Int" extr m (Double _ _) = addOp m "!Double" extr m (List l _) = extr (addOp m "!List") l extr m (Var _) = addOp m "!Var" instance OpExtractor [EXPRESSION] where extr = foldl extr instance OpExtractor (EXPRESSION, [CMD]) where extr m (e,l) = extr (extr m e) l instance OpExtractor CMD where extr m (Ass c def) = extr m [c, def] extr m (Cmd _ l) = extr m l extr m (Sequence l) = extr m l extr m (Cond l) = foldl extr m l extr m (Repeat e l) = extr m (e,l) instance OpExtractor [CMD] where extr = foldl extr extractOps :: OpExtractor a => a -> Map.Map String Int extractOps = extr Map.empty -- -- ---------------------------------------------------------------------- -- -- ** Assignment extraction -- -- ---------------------------------------------------------------------- -- addOp :: Map.Map String Int -> String -> Map.Map String Int -- addOp mp s = Map.insertWith (+) s 1 mp -- class OpExtractor a where -- extr :: Map.Map String Int -> a -> Map.Map String Int -- instance OpExtractor EXPRESSION where -- extr m (Op op _ l _) = extr (addOp m op) l -- extr m (Interval _ _ _) = addOp m "!Interval" -- extr m (Int _ _) = addOp m "!Int" -- extr m (Double _ _) = addOp m "!Double" -- extr m (List l _) = extr (addOp m "!List") l -- extr m (Var _) = addOp m "!Var" -- instance OpExtractor [EXPRESSION] where -- extr = foldl extr -- instance OpExtractor (EXPRESSION, [CMD]) where -- extr m (e,l) = extr (extr m e) l -- instance OpExtractor CMD where -- extr m (Cmd _ l) = extr m l -- extr m (Sequence l) = extr m l -- extr m (Cond l) = foldl extr m l -- extr m (Repeat e l) = extr m (e,l) -- instance OpExtractor [CMD] where -- extr = foldl extr -- extractOps :: OpExtractor a => a -> Map.Map String Int -- extractOps = extr Map.empty -- -- ---------------------------------------------------------------------- -- -- * static analysis functions -- -- ---------------------------------------------------------------------- -- arithmetic operators opsArith = [ OP_mult, OP_div, OP_plus, OP_minus, OP_neg, OP_pow ] -- roots, trigonometric and other operators opsReal = [ OP_fthrt, OP_sqrt, OP_abs, OP_max, OP_min, OP_sign , OP_cos, OP_sin, OP_tan, OP_Pi ] -- special CAS operators opsCas = [ OP_maximize, OP_factor , OP_divide, OP_factorize, OP_int, OP_rlqe, OP_simplify, OP_solve ] -- comparison predicates opsCmp = [ OP_neq, OP_lt, OP_leq, OP_eq, OP_gt, OP_geq, OP_convergence ] -- boolean constants and connectives opsBool = [ OP_false, OP_true, OP_not, OP_and, OP_or, OP_impl ] -- quantifiers opsQuant = [ OP_ex, OP_all ] -} {- ---------------------------------------------------------------------- MathLink stuff ---------------------------------------------------------------------- -} readAndPrintOutput :: ML () readAndPrintOutput = do exptype <- mlGetNext let pr | exptype == dfMLTKSYM = readAndPrintML "Symbol: " mlGetSymbol | exptype == dfMLTKSTR = readAndPrintML "String: " mlGetString | exptype == dfMLTKINT = readAndPrintML "Int: " mlGetInteger | exptype == dfMLTKREAL = readAndPrintML "Real: " mlGetReal | exptype == dfMLTKFUNC = do len <- mlGetArgCount if len == 0 then mlProcError else do let f i = readAndPrintOutput >> when (i < len) $ userMessage ", " readAndPrintOutput userMessage "[" forM_ [1 .. len] f userMessage "]" | exptype == dfMLTKERROR = userMessageLn "readAndPrintOutput-error" >> mlProcError | otherwise = userMessageLn ("readAndPrintOutput-error" ++ show exptype) >> mlProcError pr userMessage :: String -> ML () userMessage s = ML.verbMsgMLLn 2 s >> liftIO (putStr s) userMessageLn :: String -> ML () userMessageLn s = ML.verbMsgMLLn 2 s >> liftIO (putStrLn s) class MLShow a where mlshow :: a -> String instance MLShow String where mlshow s = s instance MLShow CDouble where mlshow = show instance MLShow CInt where mlshow = show readAndPrintML :: MLShow a => String -> ML a -> ML () readAndPrintML _ pr = pr >>= userMessage . mlshow -- * Test functionality sendPlus :: CInt -> CInt -> CInt -> ML () sendPlus i j k = do mlPutFunction "EvaluatePacket" 1 mlPutFunction "Plus" 3 mlPutInteger i mlPutInteger j mlPutInteger k mlEndPacket userMessageLn "Sent" sendFormula :: CInt -> CInt -> CInt -> ML () sendFormula i j k = do mlPutFunction "EvaluatePacket" 1 mlPutFunction "Plus" 2 mlPutFunction "Times" 2 mlPutInteger i mlPutInteger j mlPutFunction "Times" 3 mlPutInteger k mlPutInteger k mlPutSymbol "xsymb" mlEndPacket userMessageLn "Sent" {- ---------------------------------------------------------------------- MathLink Tests ---------------------------------------------------------------------- -} mathP3 :: MathState -> String -> IO () mathP3 mst s = mlMathEnv mst $ mlP3 s 0 mlMathEnv :: MathState -> ML a -> IO a mlMathEnv mst prog = liftM snd $ withMathematica mst $ liftML prog mlTestEnv :: Pretty a => String -> ML a -> IO a mlTestEnv s act = do let mN = if null s then Nothing else Just s eRes <- runLink (Just "/tmp/mi.txt") 2 mN act case eRes of Left eid -> putStrLn ("Error " ++ show eid) >> error "ml-test" Right res -> putStrLn ("OK: " ++ show (pretty res)) >> return res mlP1 :: CInt -> CInt -> CInt -> ML () mlP1 i j k = forM_ [1 .. k] $ sendFormula i j >=> const (waitForAnswer >> readAndPrintOutput >> userMessageLn "") mlTest :: [String] -> IO () mlTest argv = do let (k, i, j) = (read $ head argv, read $ argv !! 1, read $ argv !! 2) s = if length argv > 3 then argv !! 3 else "" mlTestEnv s $ mlP1 i j k mlP2 :: Int -> EXPRESSION -> ML [EXPRESSION] mlP2 k e = forM [1 .. (k :: Int)] $ const $ sendEvalPacket (sendExpression True e) >> waitForAnswer >> receiveExpression mlTest2 :: [String] -> IO [EXPRESSION] mlTest2 argv = do let k = read $ head argv e = toE $ argv !! 1 s = if length argv > 2 then argv !! 2 else "" mlTestEnv s $ mlP2 k e -- a good interactive stepper through the mathlink interface mlP3 :: String -> Int -> ML () mlP3 es k = do let pr j = liftIO $ putStrLn $ "Entering level " ++ show j prog i j s | null s = pr j >> prog2 j | i == 1 = pr j >> sendTextPacket s >> prog2 j | i == 2 = pr j >> sendTextResultPacket s >> prog2 j | i == 10 = pr j >> sendTextPacket' s >> prog2 j | i == 3 = pr j >> sendTextPacket'' s >> prog2 j | i == 4 = pr j >> sendTextPacket3 s >> prog2 j | i == 0 = pr j >> sendEvalPacket (sendExpression True $ toE s) >> prog2 j | otherwise = pr j >> sendTextPacket4 s >> prog2 j gt g | g == dfMLTKSYM = "Symbol" | g == dfMLTKSTR = "String" | g == dfMLTKINT = "Int" | g == dfMLTKREAL = "Real" | otherwise = "" prog2 j = do let exitP2 = return $ -1 c <- liftIO getChar i <- case c of 'x' -> mlNextPacket 'n' -> mlNewPacket 'G' -> mlGetNext 'r' -> mlReady 'g' -> do g <- mlGetNext liftIO $ putStrLn $ "getnext -> " ++ gt g return g 'y' -> liftIO (putStr " -> ") >> readAndPrintML "Symbol: " mlGetSymbol >> liftIO (putStrLn "") >> return 0 's' -> liftIO (putStr " -> ") >> readAndPrintML "String: " mlGetString >> liftIO (putStrLn "") >> return 0 'i' -> liftIO (putStr " -> ") >> readAndPrintML "Int: " mlGetInteger >> liftIO (putStrLn "") >> return 0 'd' -> liftIO (putStr " -> ") >> readAndPrintML "Real: " mlGetReal >> liftIO (putStrLn "") >> return 0 '0' -> liftIO (putStr ">" >> getLine) >>= prog 0 (j + 1) >> exitP2 '1' -> liftIO (putStr ">" >> getLine) >>= prog 1 (j + 1) >> exitP2 '2' -> liftIO (putStr ">" >> getLine) >>= prog 2 (j + 1) >> exitP2 '3' -> liftIO (putStr ">" >> getLine) >>= prog 3 (j + 1) >> exitP2 '4' -> liftIO (putStr ">" >> getLine) >>= prog 4 (j + 1) >> exitP2 '5' -> liftIO (putStr ">" >> getLine) >>= prog 5 (j + 1) >> exitP2 _ -> exitP2 when (i >= 0) $ do liftIO $ putStrLn $ c : (": " ++ show i) prog2 j -- mlTestEnv cn $ prog k (0::Int) es prog k (0 :: Int) es mlTest3 :: String -> String -> Int -> IO () mlTest3 cn es k = mlTestEnv cn $ mlP3 es k mlTest4 :: String -> [String] -> IO () mlTest4 cn = mlTest5 cn . map Right mlTest5 :: String -> [Either String String] -> IO () mlTest5 cn el = do let prog [] = return () prog (e : l) = do case e of Right s -> sendEvalPacket (sendExpression True $ toE s) Left s -> sendEvalPacket (sendExpressionString s) waitForAnswer e' <- receiveExpression liftIO $ putStrLn $ show e ++ ": " ++ show (pretty e') prog l mlTestEnv cn $ prog el
gnn/Hets
CSL/InteractiveTests.hs
gpl-2.0
43,779
0
23
10,621
6,822
3,369
3,453
431
16
-- | input: on stdin, a list of file names, e.g. -- /space/autotool/done/196/2020/8644/OK/5837.input -- /space/autotool/done/196/2020/8644/OK/latest.input {-# language PatternSignatures #-} import Scorer.Einsendung import Operate.Recommon import Operate.Store ( location, load, store ) import Operate.Bank ( logline ) -- import Inter.Boiler ( boiler ) -- import Inter.Collector import Operate.Common import Operate.Types -- import Inter.Types -- import Inter.Evaluate -- import qualified Inter.Param as P import qualified Control.Stud_Aufg as SA import qualified Control.Aufgabe as A import qualified Control.Student as S import qualified Control.Schule as U import qualified Control.Vorlesung as V import Control.Types import qualified Gateway.CGI as G import Util.Datei import Autolib.ToDoc import Autolib.Reporter import Autolib.Timer import Control.Monad ( guard, forM, void ) import Control.Exception import Data.Maybe ( isJust ) import System.Environment (getArgs) import System.IO ( hPutStrLn, stderr ) patience :: Int patience = 60 -- seconds main :: IO () main = do input <- getContents forM_ (lines input) rescore_for_line rescore_for_line fname = do let ws = words $ map ( \ c -> if c == '/' then ' ' else c) fname hPutStrLn stderr $ show ws case ws of [ "space", "autotool", "done", vnr, anr, mnr, okno, file ] -> do [ vor ] <- V.get_this $ VNr $ read vnr [ auf ] <- A.get_this $ ANr $ read anr [ stud ] <- S.get_unr_mnr ( V.unr vor , MNr mnr ) void $ G.runForm $ Operate.Recommon.recompute_for_student fname auf stud _ -> hPutStrLn stderr $ "cannot handle " ++ fname
marcellussiegburg/autotool
db/src/Operate/Rescore.hs
gpl-2.0
1,702
0
16
361
441
251
190
40
3
import Graphics.Gloss main :: IO () main = display (InWindow "Dibujo" (800,300) (20,20)) white texto texto :: Picture texto = Text "Figura"
jaalonso/I1M-Cod-Temas
src/Tema_25/texto.hs
gpl-2.0
142
0
8
24
63
34
29
5
1
module Handler.Devices where import Data.Aeson (withObject, (.:?)) import Data.Time.Clock (getCurrentTime) import Handler.Extension import Import data CreateDeviceRequest = CreateDeviceRequest Text ByteString (Maybe ByteString) (Maybe Text) instance FromJSON CreateDeviceRequest where parseJSON = withObject "device request" $ \o -> CreateDeviceRequest <$> o .: "deviceToken" <*> o .: "keyFingerprint" <*> o .:? "apnDeviceToken" <*> o .:? "preferredLocalization" postDevicesR :: Handler Value postDevicesR = do now <- liftIO getCurrentTime CreateDeviceRequest deviceToken keyFingerprint mApnToken mPreferredLocalization <- requireJsonBody _ <- runDB $ upsertBy (UniqueDeviceToken deviceToken) (Device deviceToken keyFingerprint mApnToken (Just now) mPreferredLocalization) [ DeviceKeyFingerprint =. keyFingerprint , DeviceApnToken =. mApnToken , DeviceUpdated =. Just now , DevicePreferredLocalization =. mPreferredLocalization ] sendResponseStatus status201 emptyResponse data DeleteDeviceRequest = DeleteDeviceRequest Text [Text] instance FromJSON DeleteDeviceRequest where parseJSON = withObject "delete device request" $ \o -> DeleteDeviceRequest <$> o .: "deviceToken" <*> o .: "recordingUIDs" deleteDevicesR :: Handler Value deleteDevicesR = do DeleteDeviceRequest deviceToken recordingUIDs <- requireJsonBody mapM_ (runDB . deleteWhere . (:[]) . (==.) PlaybackGrantRecordingUID) recordingUIDs mapM_ (runDB . deleteWhere . (:[]) . (==.) PerpetualGrantRecordingUID) recordingUIDs runDB $ deleteBy $ UniqueDeviceToken deviceToken sendResponseStatus status204 ()
rumuki/rumuki-server
src/Handler/Devices.hs
gpl-3.0
1,746
0
15
355
418
215
203
42
1
{- Symbols & Symbol Table This file is part of AEx. Copyright (C) 2016 Jeffrey Sharp AEx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AEx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AEx. If not, see <http://www.gnu.org/licenses/>. -} module Aex.Symbols where data Symbol = Symbol Text Type Pos
sharpjs/haskell-learning
src/Aex/Symbols.hs
gpl-3.0
832
0
6
226
20
12
8
5
0
module Chap03.Exercise05 where import Chap03.Data.BinomialHeap.Ranked import Chap03.Data.BinomialTree.Ranked findMin :: Ord a => BinomialHeap a -> Maybe a findMin (BH []) = Nothing findMin (BH (t:ts)) = myMin (root t) (findMin $ BH ts) where myMin :: Ord a => a -> Maybe a -> Maybe a myMin a Nothing = Just a myMin a (Just b) = Just (min a b)
stappit/okasaki-pfds
src/Chap03/Exercise05.hs
gpl-3.0
366
0
10
84
168
85
83
9
2
{-# 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.DataPipeline.ListPipelines -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the pipeline identifiers for all active pipelines that you have -- permission to access. -- -- /See:/ <http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_ListPipelines.html AWS API Reference> for ListPipelines. -- -- This operation returns paginated results. module Network.AWS.DataPipeline.ListPipelines ( -- * Creating a Request listPipelines , ListPipelines -- * Request Lenses , lpMarker -- * Destructuring the Response , listPipelinesResponse , ListPipelinesResponse -- * Response Lenses , lprsHasMoreResults , lprsMarker , lprsResponseStatus , lprsPipelineIdList ) where import Network.AWS.DataPipeline.Types import Network.AWS.DataPipeline.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Contains the parameters for ListPipelines. -- -- /See:/ 'listPipelines' smart constructor. newtype ListPipelines = ListPipelines' { _lpMarker :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListPipelines' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lpMarker' listPipelines :: ListPipelines listPipelines = ListPipelines' { _lpMarker = Nothing } -- | The starting point for the results to be returned. For the first call, -- this value should be empty. As long as there are more results, continue -- to call 'ListPipelines' with the marker value from the previous call to -- retrieve the next set of results. lpMarker :: Lens' ListPipelines (Maybe Text) lpMarker = lens _lpMarker (\ s a -> s{_lpMarker = a}); instance AWSPager ListPipelines where page rq rs | stop (rs ^. lprsMarker) = Nothing | stop (rs ^. lprsPipelineIdList) = Nothing | otherwise = Just $ rq & lpMarker .~ rs ^. lprsMarker instance AWSRequest ListPipelines where type Rs ListPipelines = ListPipelinesResponse request = postJSON dataPipeline response = receiveJSON (\ s h x -> ListPipelinesResponse' <$> (x .?> "hasMoreResults") <*> (x .?> "marker") <*> (pure (fromEnum s)) <*> (x .?> "pipelineIdList" .!@ mempty)) instance ToHeaders ListPipelines where toHeaders = const (mconcat ["X-Amz-Target" =# ("DataPipeline.ListPipelines" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON ListPipelines where toJSON ListPipelines'{..} = object (catMaybes [("marker" .=) <$> _lpMarker]) instance ToPath ListPipelines where toPath = const "/" instance ToQuery ListPipelines where toQuery = const mempty -- | Contains the output of ListPipelines. -- -- /See:/ 'listPipelinesResponse' smart constructor. data ListPipelinesResponse = ListPipelinesResponse' { _lprsHasMoreResults :: !(Maybe Bool) , _lprsMarker :: !(Maybe Text) , _lprsResponseStatus :: !Int , _lprsPipelineIdList :: ![PipelineIdName] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListPipelinesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprsHasMoreResults' -- -- * 'lprsMarker' -- -- * 'lprsResponseStatus' -- -- * 'lprsPipelineIdList' listPipelinesResponse :: Int -- ^ 'lprsResponseStatus' -> ListPipelinesResponse listPipelinesResponse pResponseStatus_ = ListPipelinesResponse' { _lprsHasMoreResults = Nothing , _lprsMarker = Nothing , _lprsResponseStatus = pResponseStatus_ , _lprsPipelineIdList = mempty } -- | Indicates whether there are more results that can be obtained by a -- subsequent call. lprsHasMoreResults :: Lens' ListPipelinesResponse (Maybe Bool) lprsHasMoreResults = lens _lprsHasMoreResults (\ s a -> s{_lprsHasMoreResults = a}); -- | The starting point for the next page of results. To view the next page -- of results, call 'ListPipelinesOutput' again with this marker value. If -- the value is null, there are no more results. lprsMarker :: Lens' ListPipelinesResponse (Maybe Text) lprsMarker = lens _lprsMarker (\ s a -> s{_lprsMarker = a}); -- | The response status code. lprsResponseStatus :: Lens' ListPipelinesResponse Int lprsResponseStatus = lens _lprsResponseStatus (\ s a -> s{_lprsResponseStatus = a}); -- | The pipeline identifiers. If you require additional information about -- the pipelines, you can use these identifiers to call DescribePipelines -- and GetPipelineDefinition. lprsPipelineIdList :: Lens' ListPipelinesResponse [PipelineIdName] lprsPipelineIdList = lens _lprsPipelineIdList (\ s a -> s{_lprsPipelineIdList = a}) . _Coerce;
fmapfmapfmap/amazonka
amazonka-datapipeline/gen/Network/AWS/DataPipeline/ListPipelines.hs
mpl-2.0
5,712
0
14
1,260
840
496
344
97
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.FirebaseDynamicLinks -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Programmatically creates and manages Firebase Dynamic Links. -- -- /See:/ <https://firebase.google.com/docs/dynamic-links/ Firebase Dynamic Links API Reference> module Network.Google.FirebaseDynamicLinks ( -- * Service Configuration firebaseDynamicLinksService -- * OAuth Scopes , firebaseScope -- * API Declaration , FirebaseDynamicLinksAPI -- * Resources -- ** firebasedynamiclinks.getLinkStats , module Network.Google.Resource.FirebaseDynamicLinks.GetLinkStats -- ** firebasedynamiclinks.installAttribution , module Network.Google.Resource.FirebaseDynamicLinks.InstallAttribution -- ** firebasedynamiclinks.managedShortLinks.create , module Network.Google.Resource.FirebaseDynamicLinks.ManagedShortLinks.Create -- ** firebasedynamiclinks.reopenAttribution , module Network.Google.Resource.FirebaseDynamicLinks.ReopenAttribution -- ** firebasedynamiclinks.shortLinks.create , module Network.Google.Resource.FirebaseDynamicLinks.ShortLinks.Create -- * Types -- ** NavigationInfo , NavigationInfo , navigationInfo , niEnableForcedRedirect -- ** DesktopInfo , DesktopInfo , desktopInfo , diDesktopFallbackLink -- ** DynamicLinkEventStatPlatform , DynamicLinkEventStatPlatform (..) -- ** Suffix , Suffix , suffix , sCustomSuffix , sOption -- ** DynamicLinkWarning , DynamicLinkWarning , dynamicLinkWarning , dlwWarningCode , dlwWarningDocumentLink , dlwWarningMessage -- ** ManagedShortLink , ManagedShortLink , managedShortLink , mslCreationTime , mslLink , mslVisibility , mslLinkName , mslFlaggedAttribute , mslInfo -- ** CreateShortDynamicLinkRequest , CreateShortDynamicLinkRequest , createShortDynamicLinkRequest , csdlrLongDynamicLink , csdlrSuffix , csdlrDynamicLinkInfo , csdlrSdkVersion -- ** SocialMetaTagInfo , SocialMetaTagInfo , socialMetaTagInfo , smtiSocialImageLink , smtiSocialDescription , smtiSocialTitle -- ** CreateShortDynamicLinkResponse , CreateShortDynamicLinkResponse , createShortDynamicLinkResponse , csdlrPreviewLink , csdlrWarning , csdlrShortLink -- ** DynamicLinkEventStat , DynamicLinkEventStat , dynamicLinkEventStat , dlesEvent , dlesPlatform , dlesCount -- ** IosInfo , IosInfo , iosInfo , iiIosBundleId , iiIosIPadBundleId , iiIosAppStoreId , iiIosMinimumVersion , iiIosIPadFallbackLink , iiIosCustomScheme , iiIosFallbackLink -- ** DynamicLinkInfo , DynamicLinkInfo , dynamicLinkInfo , dliNavigationInfo , dliDesktopInfo , dliSocialMetaTagInfo , dliDynamicLinkDomain , dliLink , dliIosInfo , dliDomainURIPrefix , dliAndroidInfo , dliAnalyticsInfo -- ** GetIosPostInstallAttributionRequestVisualStyle , GetIosPostInstallAttributionRequestVisualStyle (..) -- ** DynamicLinkStats , DynamicLinkStats , dynamicLinkStats , dlsLinkEventStats -- ** SuffixOption , SuffixOption (..) -- ** ManagedShortLinkFlaggedAttributeItem , ManagedShortLinkFlaggedAttributeItem (..) -- ** DynamicLinkEventStatEvent , DynamicLinkEventStatEvent (..) -- ** CreateManagedShortLinkRequest , CreateManagedShortLinkRequest , createManagedShortLinkRequest , cmslrLongDynamicLink , cmslrSuffix , cmslrDynamicLinkInfo , cmslrSdkVersion , cmslrName -- ** GetIosReopenAttributionResponse , GetIosReopenAttributionResponse , getIosReopenAttributionResponse , girarIosMinAppVersion , girarDeepLink , girarUtmContent , girarResolvedLink , girarUtmMedium , girarInvitationId , girarUtmTerm , girarUtmCampaign , girarUtmSource -- ** GetIosPostInstallAttributionResponseRequestIPVersion , GetIosPostInstallAttributionResponseRequestIPVersion (..) -- ** GetIosPostInstallAttributionRequest , GetIosPostInstallAttributionRequest , getIosPostInstallAttributionRequest , gipiarIosVersion , gipiarUniqueMatchLinkToCheck , gipiarAppInstallationTime , gipiarDevice , gipiarSdkVersion , gipiarBundleId , gipiarRetrievalMethod , gipiarVisualStyle -- ** Xgafv , Xgafv (..) -- ** GetIosPostInstallAttributionResponseAttributionConfidence , GetIosPostInstallAttributionResponseAttributionConfidence (..) -- ** AndroidInfo , AndroidInfo , androidInfo , aiAndroidMinPackageVersionCode , aiAndroidFallbackLink , aiAndroidLink , aiAndroidPackageName -- ** DynamicLinkWarningWarningCode , DynamicLinkWarningWarningCode (..) -- ** AnalyticsInfo , AnalyticsInfo , analyticsInfo , aiItunesConnectAnalytics , aiGooglePlayAnalytics -- ** ITunesConnectAnalytics , ITunesConnectAnalytics , iTunesConnectAnalytics , itcaAt , itcaMt , itcaPt , itcaCt -- ** GetIosPostInstallAttributionResponse , GetIosPostInstallAttributionResponse , getIosPostInstallAttributionResponse , gipiarDeepLink , gipiarRequestIPVersion , gipiarAppMinimumVersion , gipiarAttributionConfidence , gipiarExternalBrowserDestinationLink , gipiarUtmContent , gipiarResolvedLink , gipiarRequestedLink , gipiarUtmMedium , gipiarFallbackLink , gipiarInvitationId , gipiarIsStrongMatchExecutable , gipiarUtmTerm , gipiarUtmCampaign , gipiarMatchMessage , gipiarUtmSource -- ** CreateManagedShortLinkResponse , CreateManagedShortLinkResponse , createManagedShortLinkResponse , cmslrManagedShortLink , cmslrPreviewLink , cmslrWarning -- ** GetIosReopenAttributionRequest , GetIosReopenAttributionRequest , getIosReopenAttributionRequest , girarRequestedLink , girarSdkVersion , girarBundleId -- ** GooglePlayAnalytics , GooglePlayAnalytics , googlePlayAnalytics , gpaUtmContent , gpaUtmMedium , gpaUtmTerm , gpaUtmCampaign , gpaGclid , gpaUtmSource -- ** GetIosPostInstallAttributionRequestRetrievalMethod , GetIosPostInstallAttributionRequestRetrievalMethod (..) -- ** DeviceInfo , DeviceInfo , deviceInfo , diLanguageCodeFromWebview , diScreenResolutionWidth , diLanguageCode , diDeviceModelName , diScreenResolutionHeight , diLanguageCodeRaw , diTimezone -- ** ManagedShortLinkVisibility , ManagedShortLinkVisibility (..) ) where import Network.Google.Prelude import Network.Google.FirebaseDynamicLinks.Types import Network.Google.Resource.FirebaseDynamicLinks.GetLinkStats import Network.Google.Resource.FirebaseDynamicLinks.InstallAttribution import Network.Google.Resource.FirebaseDynamicLinks.ManagedShortLinks.Create import Network.Google.Resource.FirebaseDynamicLinks.ReopenAttribution import Network.Google.Resource.FirebaseDynamicLinks.ShortLinks.Create {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Firebase Dynamic Links API service. type FirebaseDynamicLinksAPI = ManagedShortLinksCreateResource :<|> InstallAttributionResource :<|> GetLinkStatsResource :<|> ReopenAttributionResource :<|> ShortLinksCreateResource
brendanhay/gogol
gogol-firebase-dynamiclinks/gen/Network/Google/FirebaseDynamicLinks.hs
mpl-2.0
7,875
0
8
1,624
749
531
218
195
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Storage.Buckets.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a bucket. Changes to the bucket will be readable immediately -- after writing, but configuration changes may take time to propagate. -- -- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.buckets.update@. module Network.Google.Resource.Storage.Buckets.Update ( -- * REST Resource BucketsUpdateResource -- * Creating a Request , bucketsUpdate , BucketsUpdate -- * Request Lenses , buIfMetagenerationMatch , buPredefinedACL , buBucket , buPayload , buPredefinedDefaultObjectACL , buIfMetagenerationNotMatch , buProjection ) where import Network.Google.Prelude import Network.Google.Storage.Types -- | A resource alias for @storage.buckets.update@ method which the -- 'BucketsUpdate' request conforms to. type BucketsUpdateResource = "storage" :> "v1" :> "b" :> Capture "bucket" Text :> QueryParam "ifMetagenerationMatch" (Textual Int64) :> QueryParam "predefinedAcl" BucketsUpdatePredefinedACL :> QueryParam "predefinedDefaultObjectAcl" BucketsUpdatePredefinedDefaultObjectACL :> QueryParam "ifMetagenerationNotMatch" (Textual Int64) :> QueryParam "projection" BucketsUpdateProjection :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Bucket :> Put '[JSON] Bucket -- | Updates a bucket. Changes to the bucket will be readable immediately -- after writing, but configuration changes may take time to propagate. -- -- /See:/ 'bucketsUpdate' smart constructor. data BucketsUpdate = BucketsUpdate' { _buIfMetagenerationMatch :: !(Maybe (Textual Int64)) , _buPredefinedACL :: !(Maybe BucketsUpdatePredefinedACL) , _buBucket :: !Text , _buPayload :: !Bucket , _buPredefinedDefaultObjectACL :: !(Maybe BucketsUpdatePredefinedDefaultObjectACL) , _buIfMetagenerationNotMatch :: !(Maybe (Textual Int64)) , _buProjection :: !(Maybe BucketsUpdateProjection) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BucketsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'buIfMetagenerationMatch' -- -- * 'buPredefinedACL' -- -- * 'buBucket' -- -- * 'buPayload' -- -- * 'buPredefinedDefaultObjectACL' -- -- * 'buIfMetagenerationNotMatch' -- -- * 'buProjection' bucketsUpdate :: Text -- ^ 'buBucket' -> Bucket -- ^ 'buPayload' -> BucketsUpdate bucketsUpdate pBuBucket_ pBuPayload_ = BucketsUpdate' { _buIfMetagenerationMatch = Nothing , _buPredefinedACL = Nothing , _buBucket = pBuBucket_ , _buPayload = pBuPayload_ , _buPredefinedDefaultObjectACL = Nothing , _buIfMetagenerationNotMatch = Nothing , _buProjection = Nothing } -- | Makes the return of the bucket metadata conditional on whether the -- bucket\'s current metageneration matches the given value. buIfMetagenerationMatch :: Lens' BucketsUpdate (Maybe Int64) buIfMetagenerationMatch = lens _buIfMetagenerationMatch (\ s a -> s{_buIfMetagenerationMatch = a}) . mapping _Coerce -- | Apply a predefined set of access controls to this bucket. buPredefinedACL :: Lens' BucketsUpdate (Maybe BucketsUpdatePredefinedACL) buPredefinedACL = lens _buPredefinedACL (\ s a -> s{_buPredefinedACL = a}) -- | Name of a bucket. buBucket :: Lens' BucketsUpdate Text buBucket = lens _buBucket (\ s a -> s{_buBucket = a}) -- | Multipart request metadata. buPayload :: Lens' BucketsUpdate Bucket buPayload = lens _buPayload (\ s a -> s{_buPayload = a}) -- | Apply a predefined set of default object access controls to this bucket. buPredefinedDefaultObjectACL :: Lens' BucketsUpdate (Maybe BucketsUpdatePredefinedDefaultObjectACL) buPredefinedDefaultObjectACL = lens _buPredefinedDefaultObjectACL (\ s a -> s{_buPredefinedDefaultObjectACL = a}) -- | Makes the return of the bucket metadata conditional on whether the -- bucket\'s current metageneration does not match the given value. buIfMetagenerationNotMatch :: Lens' BucketsUpdate (Maybe Int64) buIfMetagenerationNotMatch = lens _buIfMetagenerationNotMatch (\ s a -> s{_buIfMetagenerationNotMatch = a}) . mapping _Coerce -- | Set of properties to return. Defaults to full. buProjection :: Lens' BucketsUpdate (Maybe BucketsUpdateProjection) buProjection = lens _buProjection (\ s a -> s{_buProjection = a}) instance GoogleRequest BucketsUpdate where type Rs BucketsUpdate = Bucket type Scopes BucketsUpdate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/devstorage.full_control"] requestClient BucketsUpdate'{..} = go _buBucket _buIfMetagenerationMatch _buPredefinedACL _buPredefinedDefaultObjectACL _buIfMetagenerationNotMatch _buProjection (Just AltJSON) _buPayload storageService where go = buildClient (Proxy :: Proxy BucketsUpdateResource) mempty
rueshyna/gogol
gogol-storage/gen/Network/Google/Resource/Storage/Buckets/Update.hs
mpl-2.0
6,159
0
18
1,456
827
479
348
121
1
module Main where import Sound.MIDI import Pipes import qualified Pipes.Prelude as P import qualified Pipes.ByteString as B import Pipes.Attoparsec import System.IO import System.Environment main :: IO () main = do [fp] <- getArgs fd <- openFile fp ReadMode runEffect $ void (parsed midiParser (B.fromHandle fd)) >-> P.map show >-> P.stdoutLn return ()
tsahyt/midi-simple
example/MidiDump.hs
lgpl-3.0
383
0
15
82
129
69
60
15
1
module Data.Wavelet.Internal.BitOps where import Data.Bits import Data.Vector.Storable (Vector) import qualified Data.Vector.Storable as VS import Data.Word (Word64) {- Count the number of 1-bits in vector of word64s, in the bit range x[0..n] -} rnk1Vector64 :: Int -> Vector Word64 -> Int rnk1Vector64 n vec = let (wordsToCheck, bitsToCheck) = n `divMod` 64 wordParts = VS.sum . VS.map popCount . VS.take wordsToCheck $ vec bitParts = rnk1Word64 bitsToCheck . VS.head . VS.drop wordsToCheck $ vec in wordParts + bitParts where {- Count the number of 1-bits in one word64, in the bit range x[0..n'] -} rnk1Word64 :: Int -> Word64 -> Int rnk1Word64 n' x = let mask = (1 `shiftL` n') - 1 in popCount (mask .&. x) {-# INLINE rnk1Word64 #-}
jahaynes/waveletto
src/Data/Wavelet/Internal/BitOps.hs
lgpl-3.0
859
0
13
243
215
118
97
16
1
import Data.List sum' [] [] = [] sum' (x:xs) (y:ys) = (x+y):(sum' xs ys) sumup' s [] = s sumup' s (x:xs) = sumup' (sum' s x) xs sumup (x:xs) = sumup' x xs ans' :: [[Int]] -> [Int] ans' x = let s = sumup x z = zip [1..] s s'= sortBy (\(a,b) (c,d) -> compare d b) z in map fst s' ans [] = [] ans ([0,0]:_) = [] ans ([n,m]:x) = let d = take n x r = drop n x in (ans' d):(ans r) main = do c <- getContents let i = map (map read) $ map words $ lines c :: [[Int]] o = ans i mapM_ putStrLn $ map unwords $ map (map show) o
a143753/AOJ
0505.hs
apache-2.0
569
0
14
178
409
209
200
23
1
module Kernel.CPU.Hogbom where import Foreign.Ptr import Foreign.C import Data import Vector foreign import ccall deconvolve :: Ptr Double -- Model -> Ptr Double -- Dirty image -> Ptr Double -- Psf -> CInt -- Height -> CInt -- Pitch -> CInt -- Max number of iterations -> Double -- Gain -> Double -- Threshold -> IO () -- Trivial cleanPrepare :: CleanPar -> Image -> IO Image cleanPrepare _ psf = return psf cleanKernel :: CleanPar -> Image -> Image -> IO (Image, Image) cleanKernel (CleanPar iter gain thresh) res@(Image gp _ (CVector _ dirtyp)) (Image _ _ (CVector _ psfp)) = do mdl@(CVector _ modp) <- allocCVector (2 * imageSize gp) deconvolve modp dirtyp psfp (fi $ gridHeight gp) (fi $ gridPitch gp) (fi iter) gain thresh return (res, Image gp 0 mdl) where fi = fromIntegral cleanKernel _ _ _ = error "Wrong image or psf location for CPU clean kernel"
SKA-ScienceDataProcessor/RC
MS4/dna-programs/Kernel/CPU/Hogbom.hs
apache-2.0
925
0
15
220
322
167
155
24
1
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, KindSignatures, NoMonomorphismRestriction, TupleSections, OverloadedStrings, ScopedTypeVariables, FlexibleContexts, GeneralizedNewtypeDeriving, LambdaCase, ViewPatterns #-} {-# OPTIONS_GHC -Wall #-} import Bound import Bound.Name import Bound.Scope -- import Bound.Var import Control.Comonad import Control.Monad import Control.Monad.Except -- import Control.Monad.Trans.Maybe import Data.Bifunctor import Data.List import Data.String import Prelude.Extras import qualified Data.Set -- import Debug.Trace newtype Eval a = Eval { runEval :: (Except String a) } deriving (Functor, Applicative, Monad, MonadError String) doEval :: Show a => Eval a -> IO () doEval t = case runExcept $ runEval t of Left s -> putStrLn s Right a -> print a data Term n a = Var (Annotation (Term n a)) !a | Type | Q !(Binder n (Term n a)) (Scope (Name n ()) (Term n) a) | Let !Int (Prog n a) (Scope (Name n Int) (Term n) a) | App !(Term n a) !(Term n a) | Pair !(Term n a) !(Term n a) (Annotation (Term n a)) | Split !(Term n a) !(n,n) (Scope (Name n Tup) (Term n) a) (Annotation (Term n a)) | Enum [n] | Label n (Annotation (Term n a)) | Case !(Term n a) [(n,Term n a)] (Annotation (Term n a)) | Lift !(Term n a) | Box !(Term n a) | Force !(Term n a) | Require (Term n a) (Scope (Name n ()) (Term n) a, Scope (Name n ()) (Term n) a) | BelieveMe (Annotation (Term n a)) | Impossible (Annotation (Term n a)) deriving (Eq,Ord,Show,Functor,Foldable,Traversable) type Type = Term data Binder n f = Pi n f | Lam n (Annotation f) | Sigma n f deriving (Eq,Ord,Show,Functor,Foldable,Traversable) newtype Annotation f = Ann { unAnn :: Maybe f } deriving (Eq,Ord,Show,Functor,Foldable,Traversable) type Prog n a = [Name n ( Scope (Name n Int) (Type n) a , Scope (Name n Int) (Term n) a)] data Tup = Fst | Snd deriving (Eq,Ord,Show) instance Eq n => Eq1 (Term n) instance Ord n => Ord1 (Term n) instance Show n => Show1 (Term n) instance Applicative (Term n) where pure = Var noAnn (<*>) = ap instance Monad (Term n) where return = Var noAnn (>>=) = bindTerm bindTerm :: Term n a -> (a -> Term n b) -> Term n b bindTerm (Var _ x) f = f x bindTerm Type _ = Type bindTerm (Q b s) f = Q (fmap (`bindTerm` f) b) (s >>>= f) bindTerm (Let n p s) f = Let n (bindProg p f) (s >>>= f) bindTerm (App e u) f = App (bindTerm e f) (bindTerm u f) bindTerm (Pair l r an) f = Pair (bindTerm l f) (bindTerm r f) (fmap (`bindTerm` f) an) bindTerm (Split t (x,y) s an) f = Split (bindTerm t f) (x,y) (s >>>= f) (fmap (`bindTerm` f) an) bindTerm (Enum ns) _ = Enum ns bindTerm (Label n an) f = Label n (fmap (`bindTerm` f) an) bindTerm (Case t alts an) f = Case (bindTerm t f) (map (second (`bindTerm` f)) alts) (fmap (`bindTerm` f) an) bindTerm (Lift t) f = Lift (bindTerm t f) bindTerm (Box t) f = Box (bindTerm t f) bindTerm (Force t) f = Force (bindTerm t f) bindTerm (Require t (l,r)) f = Require (bindTerm t f) (l >>>= f, r >>>= f) bindTerm (BelieveMe an) f = BelieveMe (fmap (`bindTerm` f) an) bindTerm (Impossible an) f = Impossible (fmap (`bindTerm` f) an) bindProg :: Prog n a -> (a -> Term n b) -> Prog n b bindProg ps f = map (fmap (bimap (>>>= f) (>>>= f))) ps instance IsString a => IsString (Term n a) where fromString = Var noAnn . fromString data Env f g a = Env { ctx :: a -> f a , def :: a -> g a , constraints :: Maybe [Constraint] } data Constraint = Constraint data EnvEntry f a = Cloj (f a) | Id a deriving Functor type EnvEntry' n = EnvEntry (Term n) type Env' n = Env (Term n) (EnvEntry' n) emptyEnv :: Show a => Env f g a emptyEnv = Env (\x -> error ("No declaration for: " ++ show x)) (\x -> error ("No definition for: " ++ show x)) (Just []) noAnn :: Annotation a noAnn = Ann Nothing ann :: a -> Annotation a ann = Ann . Just inferType :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Term n a -> Eval (Term n a,Type n a) inferType env tm = tcTerm env tm Nothing checkType :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Term n a -> Type n a -> Eval (Term n a,Type n a) checkType env tm ty = tcTerm env tm (Just ty) tcTerm :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Term n a -> Maybe (Type n a) -> Eval (Term n a,Type n a) tcTerm env (Var (Ann ma) a) Nothing = do ty <- maybe (return (ctx env a)) return ma return (Var (ann ty) a,ty) tcTerm _ t@Type Nothing = return (t,Type) tcTerm env (Q (Pi n tyA) tyB) Nothing = do atyA <- tcType env tyA let env' = extendEnvQ env atyA atyB <- tcType env' (fromScope tyB) return (Q (Pi n atyA) (toScope atyB), Type) tcTerm env (Q (Lam n (Ann tmM)) s) Nothing = do tyA <- maybe (throwError "Must annotate lambda") return tmM atyA <- tcType env tyA let env' = extendEnvQ env atyA (ebody,atyB) <- inferType env' (fromScope s) return (Q (Lam n (ann atyA)) (toScope ebody) ,Q (Pi n atyA) (toScope atyB) ) tcTerm env (Q (Lam n (Ann ma)) body) (Just x) = eval env x >>= \case VQ (Pi m tyA) tyB -> do maybe (return ()) (eq env tyA) ma let env' = extendEnvQ env tyA (ebody,_) <- checkType env' (fromScope body) (fromScope tyB) return (Q (Lam n (ann tyA)) (toScope ebody) ,Q (Pi m tyA) tyB ) ty' -> throwError ("check': expected pi: " ++ show (quote ty')) tcTerm env (Q (Sigma n tyA) tyB) Nothing = do atyA <- tcType env tyA let env' = extendEnvQ env atyA atyB <- tcType env' (fromScope tyB) return (Q (Sigma n atyA) (toScope atyB),Type) tcTerm env (Let n prog body) an = do (env',prog') <- checkProg env prog (abody,ty) <- tcTerm env' (fromScope body) (fmap (fmap F) an) return (Let n prog' (toScope abody),Let n prog' (toScope ty)) tcTerm env (App t u) Nothing = do (at,atty) <- inferType env t eval env atty >>= \case VQ (Pi _ tyA) tyB -> do (au,_) <- checkType env u tyA return (App at au,instantiate1Name au tyB) _ -> throwError "tcTerm: expected pi" tcTerm env t@(Pair l r an1) an2 = do ty <- matchAnnots env t an1 an2 eval env ty >>= \case VQ (Sigma _ tyA) tyB -> do (al,_) <- checkType env l tyA let tyB' = instantiate1Name l tyB (ar,_) <- checkType env r tyB' return (Pair al ar (ann ty), ty) _ -> throwError "tcTerm: expected sigma" tcTerm _ t@(Enum ls) Nothing = if nub ls /= ls then throwError "tcTerm: duplicate labels" else return (t,Type) tcTerm env t@(Label l an1) an2 = do ty <- matchAnnots env t an1 an2 eval env ty >>= \case VEnum ls | l `elem` ls -> return (Label l (ann ty),Enum ls) | otherwise -> throwError "tcTerm: label not of enum" _ -> throwError "tcTerm: expected enum" tcTerm env t@(Split p (x,y) body ann1) ann2 = do ty <- matchAnnots env t ann1 ann2 (apr,pty) <- inferType env p sigmab <- eval env pty case sigmab of VQ (Sigma _ tyA) tyB -> do let env' = extendEnvSplit env tyA tyB x y apr (abody,_) <- checkType env' (fromScope body) (F <$> ty) return (Split apr (x,y) (toScope abody) (ann ty),ty) _ -> throwError "tcTerm: split: expected sigma" tcTerm env t@(Case scrut alts ann1) ann2 = do ty <- matchAnnots env t ann1 ann2 (ascrut,sty) <- inferType env scrut enum <- eval env sty case enum of VEnum ls -> let ls' = map fst alts in if (Data.Set.fromList ls) /= (Data.Set.fromList ls') then throwError ("tcTerm: labels don't match: " ++ show (ls,ls')) else do alts' <- mapM (\(l,u) -> do let env' = extendEnvCase env ascrut l (au,_) <- checkType env' u ty return (l,au)) alts return (Case ascrut alts' (ann ty),ty) _ -> throwError "tcTerm: case: expected enum" tcTerm env (Lift ty) Nothing = do aty <- tcType env ty return (Lift aty,Type) tcTerm env (Box t) Nothing = do (at,aty) <- inferType env t return (Box at, Lift aty) tcTerm env (Box t) (Just ty) = do eval env ty >>= \case VLift ty' -> do (at,_) <- checkType env t ty' return (Box at,Lift ty') _ -> throwError "tcTerm: Box: expected lift" tcTerm env (Force t) Nothing = do (at,aty) <- inferType env t eval env aty >>= \case VLift ty' -> return (Force at,ty') _ -> throwError "tcTerm: Force: expected lift" tcTerm env (Force t) (Just ty) = checkType env t (Lift ty) tcTerm _ (Require ty (l,r)) Nothing = do -- TODO: check context validity -- |- Gamma,x:sigma,t==p return (Require ty (l,r),Type) tcTerm env t@(BelieveMe ann1) ann2 = do expectedTy <- matchAnnots env t ann1 ann2 return (BelieveMe (ann expectedTy), expectedTy) tcTerm env t@(Impossible ann1) ann2 = do expectedTy <- matchAnnots env t ann1 ann2 case constraints env of Nothing -> return (Impossible (ann expectedTy),expectedTy) _ -> throwError "tcTerm: consistent context" tcTerm env tm (Just (Require ty (l,r))) = do eq env (instantiate1Name tm l) (instantiate1Name tm r) checkType env tm ty tcTerm env tm (Just ty) = do (atm,ty') <- inferType env tm case ty' of Require ty'' (l,r) -> do eq env (instantiate1Name tm l) (instantiate1Name tm r) eq env ty'' ty _ -> eq env ty' ty return (atm,ty) tcType :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Type n a -> Eval (Type n a) tcType env tm = do (atm,_) <- checkType env tm Type return atm checkProg :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Prog n a -> Eval (Env' n (Var (Name n Int) a), Prog n a) checkProg env p = do let env' = extendEnvLet env p p' <- mapM (checkProg' env' . fmap (bimap fromScope fromScope)) p return (env',map (fmap (bimap toScope toScope)) p') checkProg' :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Name n (Type n a, Term n a) -> Eval (Name n (Type n a, Term n a)) checkProg' env (Name n (ty,tm)) = do aty <- tcType env ty (atm,_) <- checkType env tm aty return (Name n (aty,atm)) extendEnvQ :: Env' n a -> Term n a -> Env' n (Var (Name n ()) a) extendEnvQ (Env ctxOld defOld cs) tm = Env ctx' def' cs where ctx' (B _) = F <$> tm ctx' (F tm') = F <$> ctxOld tm' def' x@(B _) = Id x def' (F tm') = F <$> defOld tm' extendEnvLet :: Env' n a -> Prog n a -> Env' n (Var (Name n Int) a) extendEnvLet (Env ctxOld defOld cs) ps = Env ctx' def' cs where ctx' (B x) = fromScope . fst . extract . (ps!!) $ extract x ctx' (F tm) = F <$> ctxOld tm def' (B x) = Cloj . fromScope . snd . extract . (ps!!) $ extract x def' (F tm) = F <$> defOld tm extendEnvConstraint :: Env' n a -> Term n a -> Term n a -> Env' n a extendEnvConstraint = undefined extendEnvSplit :: Eq a => Env' n a -> Type n a -> Scope (Name n ()) (Type n) a -> n -> n -> Term n a -> Env' n (Var (Name n Tup) a) extendEnvSplit (Env ctxOld defOld cs) tyA tyB x y p = extendEnvConstraint (Env ctx' def' cs) (F <$> p) (Pair (Var noAnn (B (Name x Fst))) (Var noAnn (B (Name y Snd))) noAnn) where ctx' (B (Name _ Fst)) = F <$> tyA ctx' (B (Name _ Snd)) = fromScope (mapBound (const (Name x Fst)) tyB) ctx' (F tm') = F <$> ctxOld tm' def' b@(B _) = Id b def' (F tm') = F <$> defOld tm' extendEnvCase :: Eq a => Env' n a -> Term n a -> n -> Env' n a extendEnvCase env tm l = extendEnvConstraint env tm (Label l noAnn) data Value n a = Neutral (Neutral n a) | VType | VQ (Binder n (Term n a)) (Scope (Name n ()) (Term n) a) | VPair (Term n a) (Term n a) | VEnum [n] | VLabel n | VLift (Type n a) | VBox (Boxed n a) | VRequire (Term n a) (Scope (Name n ()) (Term n) a, Scope (Name n ()) (Term n) a) | VBelieveMe | VImpossibe deriving (Eq,Ord,Show,Functor,Foldable,Traversable) newtype Boxed n a = Boxed { unBoxed :: Term n a } deriving (Eq,Ord,Show,Functor,Foldable,Traversable) data Neutral n a = NVar a | NApp (Neutral n a) (Term n a) | NSplit (Neutral n a) (n,n) (Scope (Name n Tup) (Term n) a) | NCase (Neutral n a) [(n,Term n a)] | NForce (Neutral n a) deriving (Eq,Ord,Show,Functor,Foldable,Traversable) instance Eq n => Eq1 (Value n) instance Ord n => Ord1 (Value n) instance Show n => Show1 (Value n) eval :: (MonadError String m, Eq n) => Env' n a -> Term n a -> m (Value n a) eval env (Var _ x) = case def env x of Cloj tm -> eval env tm Id v -> return (Neutral (NVar v)) eval _ Type = return VType eval _ (Q b s) = return (VQ b s) eval env (Let _ p s) = let inst = instantiateName es es = inst . defs p in eval env (inst s) eval env (App t u) = flip (evalApp env) u =<< eval env t eval _ (Pair l r _) = return (VPair l r) eval env (Split t xy s _) = flip (evalSplit env xy) s =<< eval env t eval _ (Enum ls) = return (VEnum ls) eval _ (Label l _) = return (VLabel l) eval env (Case t as _) = flip (evalCase env) as =<< eval env t eval _ (Lift t) = return (VLift t) eval _ (Box t) = return (VBox (Boxed t)) eval env (Force t) = force env =<< eval env t eval _ (Require t (l,r)) = return (VRequire t (l,r)) eval _ (BelieveMe _) = return VBelieveMe eval _ (Impossible _) = return VImpossibe evalApp :: (MonadError String m, Eq n) => Env' n a -> Value n a -> Term n a -> m (Value n a) evalApp env (VQ (Lam _ _) s) u = eval env (instantiate1Name u s) evalApp _ (Neutral t) u = return (Neutral (NApp t u)) evalApp _ _ _ = throwError ("evalApp: function expected") evalSplit :: (MonadError String m, Eq n) => Env' n a -> (n,n) -> Value n a -> Scope (Name n Tup) (Term n) a -> m (Value n a) evalSplit env _ (VPair l r) s = do eval env (instantiateName (\case {Fst -> l;Snd -> r}) s) evalSplit _ xy (Neutral n) s = return (Neutral (NSplit n xy s)) evalSplit _ _ _ _ = throwError "evalSplit: Pair expected" evalCase :: (MonadError String m, Eq n) => Env' n a -> Value n a -> [(n,Term n a)] -> m (Value n a) evalCase env (VLabel l) as = case lookup l as of Just t -> eval env t Nothing -> throwError "evalCase: case not matched" evalCase _ (Neutral n) as = return (Neutral (NCase n as)) evalCase _ _ _ = throwError "evalCase: Label expected" force :: (MonadError String m, Eq n) => Env' n a -> Value n a -> m (Value n a) force env (VBox (Boxed c)) = eval env c force _ (Neutral n) = return (Neutral (NForce n)) force _ _ = throwError "force: Box expected" defs :: Prog n a -> Int -> Scope (Name n Int) (Term n) a defs ps i = snd . extract $ (ps!!i) quote :: Value n a -> Term n a quote = undefined class Equal f where eq :: (MonadError String m, Eq a, Eq n, Show n, Show a) => Env' n a -> f n a -> f n a -> m () instance Equal Term where eq = undefined matchAnnots :: (Eq a, Eq n, Ord n, Show n, Show a) => Env' n a -> Term n a -> Annotation (Term n a) -> Maybe (Type n a) -> Eval (Type n a) matchAnnots _ e (Ann Nothing) Nothing = throwError (show e ++ " requires annotation") matchAnnots _ _ (Ann Nothing) (Just ty) = return ty matchAnnots env _ (Ann (Just ty)) Nothing = do aty <- tcType env ty return aty matchAnnots env _ (Ann (Just ty1)) (Just ty2) = do aty1 <- tcType env ty1 eq env aty1 ty2 return aty1
christiaanb/DepCore
Test2.hs
bsd-2-clause
16,436
0
24
5,123
8,094
4,020
4,074
437
13
{-# LANGUAGE BangPatterns #-} module Main where import Criterion.Main import System.Event.IntMap (IntMap) import qualified System.Event.IntMap as IM main = defaultMain [ bench "insert10k" $ whnf ascFrom n ] where -- Number of elements n = 10000 -- | Create an integer map with keys in ascending order starting at 0 -- and ending at @max@ (exclusive.) ascFrom :: Int -> IntMap Int ascFrom max = go 0 IM.empty where go :: Int -> IntMap Int -> IntMap Int go n !mp | n >= max = mp | otherwise = let (_, !mp') = IM.insertWith const n n mp in go (n + 1) mp'
tibbe/event
benchmarks/IntMap.hs
bsd-2-clause
622
0
13
175
183
95
88
15
1
-- http://www.codewars.com/kata/53ad7224454985e4e8000eaa module DragonCurve where dragon :: Int -> String dragon n | n < 0 = "" | otherwise = filter (\x -> x/='a' && x/='b') $ iterate (concatMap f) "Fa" !! n where f 'a' = "aRbFR" f 'b' = "LFaLb" f x = [x]
Bodigrim/katas
src/haskell/6-Dragons-Curve.hs
bsd-2-clause
274
0
13
65
112
57
55
8
3
module CLasH.Utils where -- Standard Imports import qualified Maybe import Data.Accessor import qualified Data.Accessor.Monad.Trans.StrictState as MonadState import qualified Data.Map as Map import qualified Control.Monad as Monad import qualified Control.Monad.Trans.State.Strict as State import qualified Debug.Trace as Trace -- Make a caching version of a stateful computatation. makeCached :: (Monad m, Ord k) => k -- ^ The key to use for the cache -> Accessor s (Map.Map k v) -- ^ The accessor to get at the cache -> State.StateT s m v -- ^ How to compute the value to cache? -> State.StateT s m v -- ^ The resulting value, from the cache or freshly -- computed. makeCached key accessor create = do cache <- MonadState.get accessor case Map.lookup key cache of -- Found in cache, just return Just value -> return value -- Not found, compute it and put it in the cache Nothing -> do value <- create MonadState.modify accessor (Map.insert key value) return value unzipM :: (Monad m) => m [(a, b)] -> m ([a], [b]) unzipM = Monad.liftM unzip catMaybesM :: (Monad m) => m [Maybe a] -> m [a] catMaybesM = Monad.liftM Maybe.catMaybes concatM :: (Monad m) => m [[a]] -> m [a] concatM = Monad.liftM concat isJustM :: (Monad m) => m (Maybe a) -> m Bool isJustM = Monad.liftM Maybe.isJust andM, orM :: (Monad m) => m [Bool] -> m Bool andM = Monad.liftM and orM = Monad.liftM or -- | Monadic versions of any and all. We reimplement them, since there -- is no ready-made lifting function for them. allM, anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool allM f = andM . (mapM f) anyM f = orM . (mapM f) mapAccumLM :: (Monad m) => (acc -> x -> m (acc, y)) -> acc -> [x] -> m (acc, [y]) mapAccumLM _ s [] = return (s, []) mapAccumLM f s (x:xs) = do (s', y ) <- f s x (s'', ys) <- mapAccumLM f s' xs return (s'', y:ys) -- Trace the given string if the given bool is True, do nothing -- otherwise. traceIf :: Bool -> String -> a -> a traceIf True = Trace.trace traceIf False = flip const
christiaanb/clash
clash/CLasH/Utils.hs
bsd-3-clause
2,093
0
15
486
735
397
338
50
2
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Servant.Router where import qualified Data.ByteString.Char8 as BS import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding import GHC.TypeLits import Network.HTTP.Types (decodePathSegments) import Servant.API hiding (URI(..)) import URI.ByteString import Web.HttpApiData -- | Router terminator. -- The 'HasRouter' instance for 'View' finalizes the router. -- -- Example: -- -- > type MyApi = "books" :> Capture "bookId" Int :> View data View instance HasLink View where type MkLink View = MkLink (Get '[] ()) toLink _ = toLink (Proxy :: Proxy (Get '[] ())) -- | When routing, the router may fail to match a location. -- Either this is an unrecoverable failure, -- such as failing to parse a query parameter, -- or it is recoverable by trying another path. data RoutingError = Fail | FailFatal deriving (Show, Eq, Ord) -- | A 'Router' contains the information necessary to execute a handler. data Router m a where RChoice :: Router m a -> Router m a -> Router m a RCapture :: FromHttpApiData x => (x -> Router m a) -> Router m a RQueryParam :: (FromHttpApiData x, KnownSymbol sym) => Proxy sym -> (Maybe x -> Router m a) -> Router m a RQueryParams :: (FromHttpApiData x, KnownSymbol sym) => Proxy sym -> ([x] -> Router m a) -> Router m a RQueryFlag :: KnownSymbol sym => Proxy sym -> (Bool -> Router m a) -> Router m a RPath :: KnownSymbol sym => Proxy sym -> Router m a -> Router m a RPage :: m a -> Router m a -- | Transform a layout by replacing 'View' with another type type family ViewTransform layout view where ViewTransform (a :<|> b) view = ViewTransform a view :<|> ViewTransform b view ViewTransform (a :> b) view = a :> ViewTransform b view ViewTransform View view = view -- | This is similar to the @HasServer@ class from @servant-server@. -- It is the class responsible for making API combinators routable. -- 'RuoteT' is used to build up the handler types. -- 'Router' is returned, to be interpretted by 'routeLoc'. class HasRouter layout where -- | A route handler. type RouteT layout (m :: * -> *) a :: * -- | Create a constant route handler that returns @a@ constHandler :: Monad m => Proxy layout -> Proxy m -> a -> RouteT layout m a -- | Transform a route handler into a 'Router'. route :: Proxy layout -> Proxy m -> Proxy a -> RouteT layout m a -> Router m a -- | Create a 'Router' from a constant. routeConst :: Monad m => Proxy layout -> Proxy m -> a -> Router m a routeConst l m a = route l m (Proxy :: Proxy a) (constHandler l m a) instance (HasRouter x, HasRouter y) => HasRouter (x :<|> y) where type RouteT (x :<|> y) m a = RouteT x m a :<|> RouteT y m a constHandler _ m a = constHandler (Proxy :: Proxy x) m a :<|> constHandler (Proxy :: Proxy y) m a route _ (m :: Proxy m) (a :: Proxy a) ((x :: RouteT x m a) :<|> (y :: RouteT y m a)) = RChoice (route (Proxy :: Proxy x) m a x) (route (Proxy :: Proxy y) m a y) instance (HasRouter sublayout, FromHttpApiData x) => HasRouter (Capture sym x :> sublayout) where type RouteT (Capture sym x :> sublayout) m a = x -> RouteT sublayout m a constHandler _ m a _ = constHandler (Proxy :: Proxy sublayout) m a route _ m a f = RCapture (route (Proxy :: Proxy sublayout) m a . f) instance (HasRouter sublayout, FromHttpApiData x, KnownSymbol sym) => HasRouter (QueryParam sym x :> sublayout) where type RouteT (QueryParam sym x :> sublayout) m a = Maybe x -> RouteT sublayout m a constHandler _ m a _ = constHandler (Proxy :: Proxy sublayout) m a route _ m a f = RQueryParam (Proxy :: Proxy sym) (route (Proxy :: Proxy sublayout) m a . f) instance (HasRouter sublayout, FromHttpApiData x, KnownSymbol sym) => HasRouter (QueryParams sym x :> sublayout) where type RouteT (QueryParams sym x :> sublayout) m a = [x] -> RouteT sublayout m a constHandler _ m a _ = constHandler (Proxy :: Proxy sublayout) m a route _ m a f = RQueryParams (Proxy :: Proxy sym) (route (Proxy :: Proxy sublayout) m a . f) instance (HasRouter sublayout, KnownSymbol sym) => HasRouter (QueryFlag sym :> sublayout) where type RouteT (QueryFlag sym :> sublayout) m a = Bool -> RouteT sublayout m a constHandler _ m a _ = constHandler (Proxy :: Proxy sublayout) m a route _ m a f = RQueryFlag (Proxy :: Proxy sym) (route (Proxy :: Proxy sublayout) m a . f) instance (HasRouter sublayout, KnownSymbol path) => HasRouter (path :> sublayout) where type RouteT (path :> sublayout) m a = RouteT sublayout m a constHandler _ = constHandler (Proxy :: Proxy sublayout) route _ m a page = RPath (Proxy :: Proxy path) (route (Proxy :: Proxy sublayout) m a page) instance HasRouter View where type RouteT View m a = m a constHandler _ _ = return route _ _ _ = RPage -- | Use a handler to route a 'URIRef'. routeURI :: (HasRouter layout, Monad m) => Proxy layout -> RouteT layout m a -> URIRef uri -> m (Either RoutingError a) routeURI layout page uri = let routing = route layout Proxy Proxy page toMaybeQuery (k, v) = if BS.null v then (k, Nothing) else (k, Just v) (path, query) = case uri of URI{} -> (uriPath uri, uriQuery uri) RelativeRef{} -> (rrPath uri, rrQuery uri) in routeQueryAndPath (toMaybeQuery <$> queryPairs query) (decodePathSegments path) routing -- | Use a computed 'Router' to route a path and query. Generally, -- you should use 'routeURI'. routeQueryAndPath :: Monad m => [(BS.ByteString, Maybe BS.ByteString)] -> [Text] -> Router m a -> m (Either RoutingError a) routeQueryAndPath queries pathSegs r = case r of RChoice a b -> do result <- routeQueryAndPath queries pathSegs a case result of Left Fail -> routeQueryAndPath queries pathSegs b Left FailFatal -> return $ Left FailFatal Right x -> return $ Right x RCapture f -> case pathSegs of [] -> return $ Left Fail capture:paths -> maybe (return $ Left FailFatal) (routeQueryAndPath queries paths) (f <$> parseUrlPieceMaybe capture) RQueryParam sym f -> case lookup (BS.pack $ symbolVal sym) queries of Nothing -> routeQueryAndPath queries pathSegs $ f Nothing Just Nothing -> return $ Left FailFatal Just (Just text) -> case parseQueryParamMaybe (decodeUtf8 text) of Nothing -> return $ Left FailFatal Just x -> routeQueryAndPath queries pathSegs $ f (Just x) RQueryParams sym f -> maybe (return $ Left FailFatal) (routeQueryAndPath queries pathSegs . f) $ do ps <- sequence $ snd <$> filter (\(k, _) -> k == BS.pack (symbolVal sym)) queries sequence $ (parseQueryParamMaybe . decodeUtf8) <$> ps RQueryFlag sym f -> case lookup (BS.pack $ symbolVal sym) queries of Nothing -> routeQueryAndPath queries pathSegs $ f False Just Nothing -> routeQueryAndPath queries pathSegs $ f True Just (Just _) -> return $ Left FailFatal RPath sym a -> case pathSegs of [] -> return $ Left Fail p:paths -> if p == T.pack (symbolVal sym) then routeQueryAndPath queries paths a else return $ Left Fail RPage a -> case pathSegs of [] -> Right <$> a _ -> return $ Left Fail
ElvishJerricco/servant-router
servant-router/src/Servant/Router.hs
bsd-3-clause
7,796
0
19
1,941
2,637
1,337
1,300
-1
-1
{-# LANGUAGE Rank2Types #-} -- | Paragon parsing module. Parser is written using Parsec. module Language.Java.Paragon.Parser ( parse , runParser , parseError ) where import Prelude hiding (exp) import Control.Applicative ((<$>)) import Control.Monad (when, void) import Data.Maybe (catMaybes, fromJust) import Data.List (find) import Text.ParserCombinators.Parsec hiding (parse, runParser) import qualified Text.ParserCombinators.Parsec as Parsec (runParser) import Language.Java.Paragon.Annotation import Language.Java.Paragon.Error import Language.Java.Paragon.Lexer import Language.Java.Paragon.Syntax import Language.Java.Paragon.SrcPos import Language.Java.Paragon.Parser.Names import Language.Java.Paragon.Parser.Types import Language.Java.Paragon.Parser.Statements import Language.Java.Paragon.Parser.Expressions import Language.Java.Paragon.Parser.Modifiers import Language.Java.Paragon.Parser.Symbols import Language.Java.Paragon.Parser.Helpers -- | Top-level parsing function. Takes a string to parse and a file name. parse :: String -> String -> Either ParseError AST parse = runParser compilationUnit -- | Runner for different parsers. Takes a parser, a string to parse and a file name. runParser :: P a -> String -> String -> Either ParseError a runParser p input fileName = Parsec.runParser (p >>= \r -> eof >> return r) initState fileName toks where initState = SrcPos fileName 1 1 toks = lexer input -- | Convert parse error to Paragon error. parseError :: ParseError -> MkError parseError pe = mkError $ defaultError { pretty = show pe } -- Parser building blocks. They almost follow the syntax tree structure. -- | Parser for the top-level syntax node. compilationUnit :: P CompilationUnit compilationUnit = do startPos <- getStartPos pkgDecl <- opt packageDecl impDecls <- list importDecl typeDecls <- fmap catMaybes (list typeDecl) endPos <- getEndPos return $ CompilationUnit (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) pkgDecl impDecls typeDecls packageDecl :: P PackageDecl packageDecl = do startPos <- getStartPos keyword KW_Package pName <- name pkgName <?> "package name" semiColon endPos <- getEndPos return $ PackageDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) pName <?> "package declaration" importDecl :: P ImportDecl importDecl = do startPos <- getStartPos keyword KW_Import isStatic <- bopt $ keyword KW_Static pkgTypeName <- name ambigName <?> "package/type name" hasStar <- bopt $ dot >> (tok Op_Star <?> "* or identifier") semiColon endPos <- getEndPos return $ mkImportDecl isStatic hasStar (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) pkgTypeName <?> "import declaration" where mkImportDecl False False sp n = SingleTypeImport sp (qualifiedTypeName $ flattenName n) mkImportDecl False True sp n = TypeImportOnDemand sp (pkgOrTypeName $ flattenName n) mkImportDecl True False sp n = SingleStaticImport sp (mkSingleStaticImport n) mkImportDecl True True sp n = StaticImportOnDemand sp (qualifiedTypeName $ flattenName n) mkSingleStaticImport n = let flName = flattenName n (lastI, initN) = (last flName, init flName) in Name (nameAnn n) lastI (nameType n) (if null initN then Nothing else (Just $ typeName initN)) typeDecl :: P (Maybe TypeDecl) typeDecl = Just <$> classOrInterfaceDecl <|> const Nothing <$> semiColon <?> "type declaration" classOrInterfaceDecl :: P TypeDecl classOrInterfaceDecl = withModifiers $ (do cdModsFun <- classDeclModsFun return $ \mods -> ClassTypeDecl (cdModsFun mods)) <|> (do intdModsFun <- interfaceDeclModsFun return $ \mods -> InterfaceTypeDecl (intdModsFun mods)) classDeclModsFun :: P (ModifiersFun ClassDecl) classDeclModsFun = normalClassDeclModsFun normalClassDeclModsFun :: P (ModifiersFun ClassDecl) normalClassDeclModsFun = do startPos <- getStartPos keyword KW_Class classId <- ident <?> "class name" body <- classBody endPos <- getEndPos return $ \mods -> let startPos' = getModifiersStartPos mods startPos in ClassDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos' endPos) mods classId [] Nothing [] body interfaceDeclModsFun :: P (ModifiersFun InterfaceDecl) interfaceDeclModsFun = do startPos <- getStartPos keyword KW_Interface iId <- ident <?> "interface name" openCurly closeCurly endPos <- getEndPos return $ \mods -> let startPos' = getModifiersStartPos mods startPos in InterfaceDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos' endPos) mods iId [] [] IB classBody :: P ClassBody classBody = do startPos <- getStartPos decls <- braces classBodyDecls endPos <- getEndPos return $ ClassBody (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) decls <?> "class body" classBodyDecls :: P [ClassBodyDecl] classBodyDecls = list classBodyDecl classBodyDecl :: P (ClassBodyDecl) classBodyDecl = withModifiers (do membDeclModsFun <- memberDeclModsFun return $ \mods -> MemberDecl (membDeclModsFun mods)) <?> "class body declaration" memberDeclModsFun :: P (ModifiersFun MemberDecl) memberDeclModsFun = do startPos <- getStartPos retT <- returnType -- parse the most general type case returnTypeToType retT of Just t -> do -- member can be either field or method -- continue with identifier idStartPos <- getStartPos i <- ident <?> "field/method name" fieldDeclAfterTypeIdModsFun t startPos i idStartPos (varDecl "field") <|> methodDeclAfterTypeIdModsFun retT startPos i -- member can only be method (void or lock return type) Nothing -> methodDeclAfterTypeModsFun retT startPos -- | Continues to parse field declaration after type and first identifier have been parsed. fieldDeclAfterTypeIdModsFun :: Type -> SrcPos -> Id -> SrcPos -> P VarDecl -> P (ModifiersFun MemberDecl) fieldDeclAfterTypeIdModsFun t startPos varId varStartPos varDeclFun = do -- continue to parse first VarDecl vInit <- opt $ tok Op_Assign >> varInit varEndPos <- getEndPos let varD = VarDecl (srcSpanToAnn $ mkSrcSpanFromPos varStartPos varEndPos) varId vInit -- try other VarDecls hasComma <- bopt comma varDs <- if hasComma then varDecls varDeclFun else return [] semiColon endPos <- getEndPos return $ \mods -> let startPos' = getModifiersStartPos mods startPos in FieldDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos' endPos) mods t (varD:varDs) -- | Continues to parse method declaration after return type has been parsed. methodDeclAfterTypeModsFun :: ReturnType -> SrcPos -> P (ModifiersFun MemberDecl) methodDeclAfterTypeModsFun retT startPos = do mId <- ident <?> "method name" methodDeclAfterTypeIdModsFun retT startPos mId -- | Continues to parse method declaration after return type and method identifier have been parsed. methodDeclAfterTypeIdModsFun :: ReturnType -> SrcPos -> Id -> P (ModifiersFun MemberDecl) methodDeclAfterTypeIdModsFun retT startPos mId = do (formalPs, isValid) <- parens $ formalParams -- See comment on formalParams about failing when (not isValid) $ do -- Very, very, very ugly hack to get the desired position in the error message -- See http://haskell.1045720.n5.nabble.com/Parsec-Custom-Fail-td3131949.html setPosition (srcPosToParsec $ srcSpanToStartPos $ annSrcSpan $ ann $ fromJust $ find formalParamVarArity formalPs) -- should not fail void anyToken fail "Only the last formal parameter may be of variable arity" body <- methodBody endPos <- getEndPos return $ \mods -> let startPos' = getModifiersStartPos mods startPos in MethodDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos' endPos) mods [] retT mId formalPs body -- | Takes 'VarDecl' parser to handle restrictions on field declarations in interfaces -- (required presence of initializer). varDecls :: P VarDecl -> P [VarDecl] varDecls varDeclFun = varDeclFun `sepBy1` comma varDecl :: String -> P VarDecl varDecl desc = do startPos <- getStartPos varId <- ident <?> desc ++ " name" vInit <- opt $ tok Op_Assign >> varInit endPos <- getEndPos return $ VarDecl (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) varId vInit -- | Parses formal parameters and returns them as a list together with validity -- indicator (whether parameter of variable arity is the last one). This is -- done in this way (returning a flag and not failing right here) for better -- error message. formalParams :: P ([FormalParam], Bool) formalParams = do formalPs <- seplist formalParam comma return (formalPs, validateFormalParams formalPs) where validateFormalParams :: [FormalParam] -> Bool validateFormalParams [] = True validateFormalParams [_] = True validateFormalParams (FormalParam { formalParamVarArity = varArity } : fps) = not varArity && validateFormalParams fps formalParam :: P (FormalParam) formalParam = withModifiers (do startPos <- getStartPos paramType <- ttype <?> "formal parameter type" varArity <- bopt ellipsis paramId <- ident <?> "formal parameter name" endPos <- getEndPos return $ \mods -> let startPos' = getModifiersStartPos mods startPos in FormalParam (srcSpanToAnn $ mkSrcSpanFromPos startPos' endPos) [] paramType varArity paramId) <?> "formal parameter" methodBody :: P MethodBody methodBody = do startPos <- getStartPos mBlock <- const Nothing <$> semiColon <|> Just <$> block endPos <- getEndPos return $ MethodBody (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) mBlock varInit :: P VarInit varInit = InitExp <$> exp block :: P Block block = do startPos <- getStartPos blStmts <- braces $ list blockStmt endPos <- getEndPos return $ Block (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) blStmts blockStmt :: P BlockStmt blockStmt = do startPos <- getStartPos mods <- list modifier <?> "local variable declaration" -- fixing error message if not (null mods) then localVarDecl startPos mods else try (localVarDecl startPos mods) <|> BlockStmt <$> stmt <?> "statement" localVarDecl :: SrcPos -> [Modifier] -> P BlockStmt localVarDecl startPos mods = do t <- ttype varDs <- varDecls (varDecl "variable") semiColon endPos <- getEndPos return $ LocalVars (srcSpanToAnn $ mkSrcSpanFromPos startPos endPos) mods t varDs <?> "local variable declaration"
bvdelft/paragon
src/Language/Java/Paragon/Parser.hs
bsd-3-clause
10,682
0
17
2,197
2,631
1,309
1,322
227
5
import AI.Classification import AI.Supervised.AdaBoost as AdaBoost import AI.Supervised.NaiveBayes as NaiveBayes import Criterion.Config import Criterion.Main import Database.HDBC import Control.Monad.Random import Control.Monad.Writer -- import System.Random myConfig = defaultConfig { -- cfgPerformGC = ljust True -- , cfgSamples = ljust 3 -- , cfgReport = ljust "perf.txt" cfgSummaryFile = ljust "perf.csv" -- , cfgResamples = ljust 0 -- , cfgVerbosity = ljust Quiet } main = defaultMainWith myConfig (return ()) [ bench ("BinaryNaiveBayes ex="++show ex++" dim="++show dim) $ runTest ex dim | ex <- map (*10) [1..5] , dim <- map (*5) [1..5] ] runTest ex dim = do bds <- evalRandIO $ createData ex dim [] putStrLn $ show $ NaiveBayes.train bds {- let bnb = {-toBinaryClassifier "1" $-} NaiveBayes.classify -- (NaiveBayes.train ds) let bnbc = NaiveBayes.classify (NaiveBayes.train bds) let (ada,out) = (runWriter $ AdaBoost.trainM NaiveBayes.train bnb bds) let adac= AdaBoost.classify ada return $ (out,eval bnbc bds)-} createData :: (RandomGen g) => Int -> Int -> [(Bool,DataPoint)] -> Rand g [(Bool,DataPoint)] createData 0 dim xs = return xs createData ex dim xs = do dp <- createDataPoint dim [] r <- getRandomR (0,100) let label=(r::Double)<50 createData (ex-1) dim ((label,dp):xs) createDataPoint :: (RandomGen g) => Int -> DataPoint -> Rand g DataPoint createDataPoint 0 xs = return xs createDataPoint n xs = do r <- getRandomR (1,100) createDataPoint (n-1) ((toSql (r::Double)):xs)
mikeizbicki/Classification
src/Performance.hs
bsd-3-clause
1,683
0
12
410
474
252
222
29
1
-- | Allows Feat properties to be used with the test-framework package. -- -- For an example of how to use test-framework, please see -- <http://github.com/batterseapower/test-framework/raw/master/example/Test/Framework/Example.lhs> {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TupleSections #-} module Test.Framework.Providers.Feat (testFeat) where import Test.Framework.Providers.API import Test.Feat (values, Enumerable) import Control.Arrow (second) import Data.Typeable import Debug.Trace -- | Create a 'Test' for a Feat property testFeat :: (Enumerable a, Show a) => TestName -> (a -> Bool) -> Test testFeat name = Test name . Property -- | Used to document numbers which we expect to be intermediate -- test counts from running properties -- I don't think I am using this in any meaningful way type PropertyTestCount = Int instance TestResultlike PropertyTestCount PropertyStatus where testSucceeded = propertySucceeded data PropertyStatus = PropertyOK -- ^ The property is true as far as we could check it | PropertyFalsifiable String -- ^ The property was not true. The strings -- are the reason and the output. deriving(Eq) instance Show PropertyStatus where show PropertyOK = "Property OK" show (PropertyFalsifiable x) = "Property failed with " ++ x propertySucceeded :: PropertyStatus -> Bool propertySucceeded s = case s of PropertyOK -> True _ -> False data Property = forall a. (Enumerable a, Show a) => Property { unProperty :: a -> Bool } deriving Typeable instance Testlike PropertyTestCount PropertyStatus Property where runTest topts (Property testable) = runProperty topts testable testTypeName _ = "Properties" traceIt x = trace (show x) x runProperty :: (Enumerable a, Show a) => CompleteTestOptions -> (a -> Bool) -> IO (PropertyTestCount :~> PropertyStatus, IO ()) runProperty topts test = do let K count = topt_maximum_generated_tests topts --This is just to help things type check toValues :: (Enumerable a, Show a) => (a -> Bool) -> [(Integer, [a])] -> [(Integer, [a])] toValues _ xs = xs --There is probably a better way to get it to typecheck values' = toValues test values samples = take count . concatMap (\(i, xs) -> zip (repeat i) xs) . take count $ values' results = map (second test) samples case map fst . filter ((==False) . snd . snd) . zip samples $ results of [] -> return (Finished PropertyOK, return ()) -- I could easily return all the results that sort was overwhelming x:_ -> return . (, return ()) . Finished . PropertyFalsifiable . show $ x
jfischoff/test-framework-testing-feat
src/Test/Framework/Providers/Feat.hs
bsd-3-clause
3,016
0
18
778
664
361
303
47
2
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType41 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get import Protocol.ROC.Float import Protocol.ROC.Utils data PointType41 = PointType41 { pointType41PointTag :: !PointType41PointTag ,pointType41ATMPress :: !PointType41ATMPress ,pointType41CalcMethodII :: !PointType41CalcMethodII ,pointType41NotUse1 :: !PointType41NotUse1 ,pointType41PipeRefTemp :: !PointType41PipeRefTemp ,pointType41PipeMaterial :: !PointType41PipeMaterial ,pointType41NotUse2 :: !PointType41NotUse2 ,pointType41MtrTypeOrCdTbFtm :: !PointType41MtrTypeOrCdTbFtm ,pointType41FrOrReynoldsNum :: !PointType41FrOrReynoldsNum ,pointType41OrExpFactorTbFpm :: !PointType41OrExpFactorTbFpm ,pointType41FpbFactor :: !PointType41FpbFactor ,pointType41FtpFactor :: !PointType41FtpFactor ,pointType41FtfFactor :: !PointType41FtfFactor ,pointType41FgrFactor :: !PointType41FgrFactor ,pointType41FpvFactor :: !PointType41FpvFactor ,pointType41HistPnt1 :: !PointType41HistPnt1 ,pointType41RollUp1 :: !PointType41RollUp1 ,pointType41TLPParamArchived1 :: !PointType41TLPParamArchived1 ,pointType41ConvRollUp1 :: !PointType41ConvRollUp1 ,pointType41HistPnt2 :: !PointType41HistPnt2 ,pointType41RollUp2 :: !PointType41RollUp2 ,pointType41TLPParamArchived2 :: !PointType41TLPParamArchived2 ,pointType41ConvRollUp2 :: !PointType41ConvRollUp2 ,pointType41HistPnt3 :: !PointType41HistPnt3 ,pointType41RollUp3 :: !PointType41RollUp3 ,pointType41TLPParamArchived3 :: !PointType41TLPParamArchived3 ,pointType41ConvRollUp3 :: !PointType41ConvRollUp3 ,pointType41HistPnt4 :: !PointType41HistPnt4 ,pointType41RollUp4 :: !PointType41RollUp4 ,pointType41TLPParamArchived4 :: !PointType41TLPParamArchived4 ,pointType41ConvRollUp4 :: !PointType41ConvRollUp4 ,pointType41HistPnt5 :: !PointType41HistPnt5 ,pointType41RollUp5 :: !PointType41RollUp5 ,pointType41TLPParamArchived5 :: !PointType41TLPParamArchived5 ,pointType41ConvRollUp5 :: !PointType41ConvRollUp5 ,pointType41HistPnt6 :: !PointType41HistPnt6 ,pointType41RollUp6 :: !PointType41RollUp6 ,pointType41TLPParamArchived6 :: !PointType41TLPParamArchived6 ,pointType41ConvRollUp6 :: !PointType41ConvRollUp6 ,pointType41HistPnt7 :: !PointType41HistPnt7 ,pointType41RollUp7 :: !PointType41RollUp7 ,pointType41TLPParamArchived7 :: !PointType41TLPParamArchived7 ,pointType41ConvRollUp7 :: !PointType41ConvRollUp7 ,pointType41HistPnt8 :: !PointType41HistPnt8 ,pointType41RollUp8 :: !PointType41RollUp8 ,pointType41TLPParamArchived8 :: !PointType41TLPParamArchived8 ,pointType41ConvRollUp8 :: !PointType41ConvRollUp8 ,pointType41HistPnt9 :: !PointType41HistPnt9 ,pointType41RollUp9 :: !PointType41RollUp9 ,pointType41TLPParamArchived9 :: !PointType41TLPParamArchived9 ,pointType41ConvRollUp9 :: !PointType41ConvRollUp9 ,pointType41HistPnt10 :: !PointType41HistPnt10 ,pointType41RollUp10 :: !PointType41RollUp10 ,pointType41TLPParamArchived10 :: !PointType41TLPParamArchived10 ,pointType41ConvRollUp10 :: !PointType41ConvRollUp10 --,pointType41HistPnt11 :: !PointType41HistPnt11 --,pointType41RollUp11 :: !PointType41RollUp11 --,pointType41TLPParamArchived11 :: !PointType41TLPParamArchived11 --,pointType41ConvRollUp11 :: !PointType41ConvRollUp11 --,pointType41HistPnt12 :: !PointType41HistPnt12 --,pointType41RollUp12 :: !PointType41RollUp12 --,pointType41TLPParamArchived12 :: !PointType41TLPParamArchived12 --,pointType41ConvRollUp12 :: !PointType41ConvRollUp12 --,pointType41HistPnt13 :: !PointType41HistPnt13 --,pointType41RollUp13 :: !PointType41RollUp13 --,pointType41TLPParamArchived13 :: !PointType41TLPParamArchived13 --,pointType41ConvRollUp13 :: !PointType41ConvRollUp13 --,pointType41HistPnt14 :: !PointType41HistPnt14 --,pointType41RollUp14 :: !PointType41RollUp14 --,pointType41TLPParamArchived14 :: !PointType41TLPParamArchived14 --,pointType41ConvRollUp14 :: !PointType41ConvRollUp14 --,pointType41HistPnt15 :: !PointType41HistPnt15 --,pointType41RollUp15 :: !PointType41RollUp15 --,pointType41TLPParamArchived15 :: !PointType41TLPParamArchived15 --,pointType41ConvRollUp15 :: !PointType41ConvRollUp15 --,pointType41HistPnt16 :: !PointType41HistPnt16 --,pointType41RollUp16 :: !PointType41RollUp16 --,pointType41TLPParamArchived16 :: !PointType41TLPParamArchived16 --,pointType41ConvRollUp16 :: !PointType41ConvRollUp16 } deriving (Read,Eq, Show, Generic) type PointType41PointTag = BS.ByteString type PointType41ATMPress = Float type PointType41CalcMethodII = Word8 type PointType41NotUse1 = [Word8] type PointType41PipeRefTemp = Float type PointType41PipeMaterial = Word8 type PointType41NotUse2 = Word8 type PointType41MtrTypeOrCdTbFtm = Float type PointType41FrOrReynoldsNum = Float type PointType41OrExpFactorTbFpm = Float type PointType41FpbFactor = Float type PointType41FtpFactor = Float type PointType41FtfFactor = Float type PointType41FgrFactor = Float type PointType41FpvFactor = Float type PointType41HistPnt1 = Word8 type PointType41RollUp1 = Word8 type PointType41TLPParamArchived1 = [Word8] type PointType41ConvRollUp1 = Float type PointType41HistPnt2 = Word8 type PointType41RollUp2 = Word8 type PointType41TLPParamArchived2 = [Word8] type PointType41ConvRollUp2 = Float type PointType41HistPnt3 = Word8 type PointType41RollUp3 = Word8 type PointType41TLPParamArchived3 = [Word8] type PointType41ConvRollUp3 = Float type PointType41HistPnt4 = Word8 type PointType41RollUp4 = Word8 type PointType41TLPParamArchived4 = [Word8] type PointType41ConvRollUp4 = Float type PointType41HistPnt5 = Word8 type PointType41RollUp5 = Word8 type PointType41TLPParamArchived5 = [Word8] type PointType41ConvRollUp5 = Float type PointType41HistPnt6 = Word8 type PointType41RollUp6 = Word8 type PointType41TLPParamArchived6 = [Word8] type PointType41ConvRollUp6 = Float type PointType41HistPnt7 = Word8 type PointType41RollUp7 = Word8 type PointType41TLPParamArchived7 = [Word8] type PointType41ConvRollUp7 = Float type PointType41HistPnt8 = Word8 type PointType41RollUp8 = Word8 type PointType41TLPParamArchived8 = [Word8] type PointType41ConvRollUp8 = Float type PointType41HistPnt9 = Word8 type PointType41RollUp9 = Word8 type PointType41TLPParamArchived9 = [Word8] type PointType41ConvRollUp9 = Float type PointType41HistPnt10 = Word8 type PointType41RollUp10 = Word8 type PointType41TLPParamArchived10 = [Word8] type PointType41ConvRollUp10 = Float --type PointType41HistPnt11 = Word8 --type PointType41RollUp11 = Word8 --type PointType41TLPParamArchived11 = [Word8] --type PointType41ConvRollUp11 = Float --type PointType41HistPnt12 = Word8 --type PointType41RollUp12 = Word8 --type PointType41TLPParamArchived12 = [Word8] --type PointType41ConvRollUp12 = Float --type PointType41HistPnt13 = Word8 --type PointType41RollUp13 = Word8 --type PointType41TLPParamArchived13 = [Word8] --type PointType41ConvRollUp13 = Float --type PointType41HistPnt14 = Word8 --type PointType41RollUp14 = Word8 --type PointType41TLPParamArchived14 = [Word8] --type PointType41ConvRollUp14 = Float --type PointType41HistPnt15 = Word8 --type PointType41RollUp15 = Word8 --type PointType41TLPParamArchived15 = [Word8] --type PointType41ConvRollUp15 = Float --type PointType41HistPnt16 = Word8 --type PointType41RollUp16 = Word8 --type PointType41TLPParamArchived16 = [Word8] --type PointType41ConvRollUp16 = Float pointType41Parser :: Get PointType41 pointType41Parser = do pointTag <- getByteString 10 aTMPress <- getIeeeFloat32 calcMethodII <- getWord8 notUse1 <- getTLP pipeRefTemp <- getIeeeFloat32 pipeMaterial <- getWord8 notUse2 <- getWord8 mtrTypeOrCdTbFtm <- getIeeeFloat32 frOrReynoldsNum <- getIeeeFloat32 orExpFactorTbFpm <- getIeeeFloat32 fpbFactor <- getIeeeFloat32 ftpFactor <- getIeeeFloat32 ftfFactor <- getIeeeFloat32 fgrFactor <- getIeeeFloat32 fpvFactor <- getIeeeFloat32 histPnt1 <- getWord8 rollUp1 <- getWord8 tLPParamArchived1 <- getTLP convRollUp1 <- getIeeeFloat32 histPnt2 <- getWord8 rollUp2 <- getWord8 tLPParamArchived2 <- getTLP convRollUp2 <- getIeeeFloat32 histPnt3 <- getWord8 rollUp3 <- getWord8 tLPParamArchived3 <- getTLP convRollUp3 <- getIeeeFloat32 histPnt4 <- getWord8 rollUp4 <- getWord8 tLPParamArchived4 <- getTLP convRollUp4 <- getIeeeFloat32 histPnt5 <- getWord8 rollUp5 <- getWord8 tLPParamArchived5 <- getTLP convRollUp5 <- getIeeeFloat32 histPnt6 <- getWord8 rollUp6 <- getWord8 tLPParamArchived6 <- getTLP convRollUp6 <- getIeeeFloat32 histPnt7 <- getWord8 rollUp7 <- getWord8 tLPParamArchived7 <- getTLP convRollUp7 <- getIeeeFloat32 histPnt8 <- getWord8 rollUp8 <- getWord8 tLPParamArchived8 <- getTLP convRollUp8 <- getIeeeFloat32 histPnt9 <- getWord8 rollUp9 <- getWord8 tLPParamArchived9 <- getTLP convRollUp9 <- getIeeeFloat32 histPnt10 <- getWord8 rollUp10 <- getWord8 tLPParamArchived10 <- getTLP convRollUp10 <- getIeeeFloat32 -- histPnt11 <- getWord8 -- rollUp11 <- getWord8 -- tLPParamArchived11 <- getTLP -- convRollUp11 <- getIeeeFloat32 -- histPnt12 <- getWord8 -- rollUp12 <- getWord8 -- tLPParamArchived12 <- getTLP -- convRollUp12 <- getIeeeFloat32 -- histPnt13 <- getWord8 -- rollUp13 <- getWord8 -- tLPParamArchived13 <- getTLP -- convRollUp13 <- getIeeeFloat32 -- histPnt14 <- getWord8 -- rollUp14 <- getWord8 -- tLPParamArchived14 <- getTLP -- convRollUp14 <- getIeeeFloat32 -- histPnt15 <- getWord8 -- rollUp15 <- getWord8 -- tLPParamArchived15 <- getTLP -- convRollUp15 <- getIeeeFloat32 -- histPnt16 <- getWord8 -- rollUp16 <- getWord8 -- tLPParamArchived16 <- getTLP -- convRollUp16 <- getIeeeFloat32 return $ PointType41 pointTag aTMPress calcMethodII notUse1 pipeRefTemp pipeMaterial notUse2 mtrTypeOrCdTbFtm frOrReynoldsNum orExpFactorTbFpm fpbFactor ftpFactor ftfFactor fgrFactor fpvFactor histPnt1 rollUp1 tLPParamArchived1 convRollUp1 histPnt2 rollUp2 tLPParamArchived2 convRollUp2 histPnt3 rollUp3 tLPParamArchived3 convRollUp3 histPnt4 rollUp4 tLPParamArchived4 convRollUp4 histPnt5 rollUp5 tLPParamArchived5 convRollUp5 histPnt6 rollUp6 tLPParamArchived6 convRollUp6 histPnt7 rollUp7 tLPParamArchived7 convRollUp7 histPnt8 rollUp8 tLPParamArchived8 convRollUp8 histPnt9 rollUp9 tLPParamArchived9 convRollUp9 histPnt10 rollUp10 tLPParamArchived10 convRollUp10 --histPnt11 -- rollUp11 tLPParamArchived11 convRollUp11 histPnt12 rollUp12 tLPParamArchived12 convRollUp12 histPnt13 rollUp13 tLPParamArchived13 convRollUp13 histPnt14 rollUp14 -- tLPParamArchived14 convRollUp14 histPnt15 rollUp15 tLPParamArchived15 convRollUp15 histPnt16 rollUp16 tLPParamArchived16 convRollUp16
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType41.hs
bsd-3-clause
20,833
0
9
11,160
1,422
818
604
293
1
{-# LANGUAGE NamedFieldPuns, LambdaCase #-} {-# LANGUAGE ScopedTypeVariables, TypeFamilies #-} {-# LANGUAGE RecordWildCards, QuasiQuotes, OverloadedStrings, DuplicateRecordFields #-} module Main where import qualified Graphics.UI.GLFW as GLFW import System.IO import System.Exit import Data.IORef (newIORef, readIORef, writeIORef, IORef) import Text.RawString.QQ import qualified Data.ByteString as B import Control.Exception (finally) import Control.Monad (when) import qualified Control.Concurrent.STM.TQueue as TQueue import qualified Control.Concurrent.STM as STM import GHC.Float (double2Float) import Data.Maybe (fromMaybe) import qualified GLWrap as GL import Hello import Textures import Behaviour import Coordinate (staticMatrixStack) import Lighting (lightingDemo) import qualified LightingReflex type EventQueue = TQueue.TQueue InputEvent data AppState = AppState { _window :: GLFW.Window , input :: EventQueue , lastMousePos :: STM.TVar (Maybe (Double, Double)) , states :: [IO Behaviour] , current :: Behaviour , screenWidth :: GL.Width , screenHeight :: GL.Height } main = LightingReflex.go main' :: IO () main' = do GLFW.setErrorCallback $ Just errorCb boolBracket GLFW.init GLFW.terminate (exitWithErr "init failed") $ do GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3 GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor 3 GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core GLFW.windowHint $ GLFW.WindowHint'Resizable False let createAction = GLFW.createWindow 800 600 "LearnOpenGL" Nothing Nothing maybeBracket createAction GLFW.destroyWindow (exitWithErr "failed to create window") $ \window -> do GLFW.setCursorInputMode window GLFW.CursorInputMode'Disabled GLFW.makeContextCurrent $ Just window (width, height) <- GLFW.getFramebufferSize window GL.viewport (GL.WinCoord 0) (GL.WinCoord 0) (GL.toWidth width) (GL.toHeight height) appState <- initializeApp window width height appStateRef <- newIORef appState GLFW.setKeyCallback window $ Just $ keyCallback (input appState) GLFW.setScrollCallback window $ Just $ scrollCallback (input appState) GLFW.setCursorPosCallback window $ Just $ cursorCallback (input appState) (lastMousePos appState) mainLoop appStateRef return () where exitWithErr err = do putStrLn err exitFailure initializeApp :: GLFW.Window -> Int -> Int -> IO AppState initializeApp window width height = do let r:rs = supportedRenderers input <- TQueue.newTQueueIO lastMousePos <- STM.newTVarIO $ Nothing behaviour <- r return $ AppState { _window = window , states = rs ++ [r] , current = behaviour , input = input , lastMousePos = lastMousePos , screenWidth = GL.Width (fromIntegral width) , screenHeight = GL.Height (fromIntegral height) } oldRendererToBehaviour :: IO (IO (), IO ()) -> IO Behaviour oldRendererToBehaviour act = do (render, cleanup) <- act return $ Behaviour { frameFun = \_ _ -> return () , renderFun = \_ _ -> do GL.clearColor $ GL.RGBA 0.2 0.3 0.3 1.0 GL.clear [GL.ClearColor] render , cleanupFun = cleanup } supportedRenderers = [ lightingDemo , staticMatrixStack , texturedRectangle ] ++ oldRenderers oldRenderers = map oldRendererToBehaviour [ triangleWithPerVertexColor , triangleColorFromUniform , triangleUsingArray , doubleTrianglesArray , rectangleUsingElements , doubleTrianglesDifferentArrays , doubleTrianglesDifferentColors ] boolBracket :: IO Bool -> IO () -> IO a -> IO a -> IO a boolBracket action cleanup onErr onSuccess = do success <- action case success of True -> onSuccess `finally` cleanup False -> onErr maybeBracket :: IO (Maybe a) -> (a -> IO ()) -> IO b -> (a -> IO b) -> IO b maybeBracket action cleanup onErr onSuccess = do result <- action case result of Nothing -> onErr Just val -> onSuccess val `finally` cleanup val keyCallback :: EventQueue -> GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> GLFW.ModifierKeys -> IO () keyCallback q window key scancode action mode = STM.atomically $ TQueue.writeTQueue q $ KeyEvent key scancode action mode scrollCallback :: EventQueue -> GLFW.Window -> Double -> Double -> IO () scrollCallback q window dx dy = STM.atomically $ TQueue.writeTQueue q $ ScrollEvent (double2Float dx) (double2Float dy) cursorCallback :: EventQueue -> STM.TVar (Maybe (Double, Double)) -> GLFW.Window -> Double -> Double -> IO () cursorCallback q last window x y = STM.atomically $ do STM.readTVar last >>= \case Just (lx, ly) -> do let dx = x - lx dy = y - ly TQueue.writeTQueue q $ MouseEvent (double2Float dx) (double2Float dy) Nothing -> return () STM.writeTVar last $ Just (x, y) appWindow :: IORef AppState -> IO GLFW.Window appWindow stateRef = do AppState{_window = window} <- readIORef stateRef return window mainLoop :: IORef AppState -> IO () mainLoop st = do window <- appWindow st shouldClose <- appWindow st >>= GLFW.windowShouldClose if not shouldClose then do GLFW.pollEvents handleInput st render st GLFW.swapBuffers window mainLoop st else return () handleInput :: IORef AppState -> IO () handleInput stRef = do st@(AppState{input, current}) <- readIORef stRef nextSt <- go st [] writeIORef stRef nextSt where go (st@(AppState{input, current})) behaviourEvents = do maybeEvent <- STM.atomically $ TQueue.tryReadTQueue input case maybeEvent of Nothing -> do callFrameFun (frameFun current) (reverse behaviourEvents) return st Just event -> do wasHandled <- handleEvent st event case wasHandled of Nothing -> go st (event:behaviourEvents) Just nextState -> go nextState behaviourEvents callFrameFun :: ([InputEvent] -> Float -> IO ()) -> [InputEvent] -> IO () callFrameFun frameFun events = do time <- double2Float . fromMaybe 0 <$> GLFW.getTime frameFun events time handleEvent :: AppState -> InputEvent -> IO (Maybe AppState) handleEvent st (KeyEvent GLFW.Key'Escape _ _ _) = do GLFW.setWindowShouldClose (_window st) True return $ Just st handleEvent st (KeyEvent GLFW.Key'Space _ action _) = do case action of GLFW.KeyState'Released -> do cleanupFun $ current st Just <$> initializeNextState st _ -> return $ Just st handleEvent st _ = do return Nothing initializeNextState st@(AppState {current, states = s:ss}) = do current' <- s return $ st { current = current', states = ss ++ [s] } render :: IORef AppState -> IO () render st = do AppState{..} <- readIORef st renderFun current screenWidth screenHeight return () errorCb err desc = do putStrLn desc
binarin/learnopengl
src/Main.hs
bsd-3-clause
7,213
0
19
1,784
2,263
1,125
1,138
177
3
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE FlexibleContexts #-} module Control.Monad.Quantum.CircuitBuilderToffoli ( CircuitBuilderToffoli, runCircuitBuilderToffoli, evalCircuitBuilderToffoli, evalCircuitBuilderToffoli_, execCircuitBuilderToffoli, buildCircuitToffoli) where import Control.Monad.Quantum.Base.CircuitBuilder import Control.Monad.Quantum.Control import Data.Quantum.Circuit.Class (Wire, IsCircuit) import Data.Quantum.Circuit.Invert (CircuitInvert) import Data.Quantum.Circuit.MinimizeWireIndices type CircuitBuilderToffoli c = QuantumControlT Wire (CircuitBuilderBase c) runCircuitBuilderToffoli :: CircuitBuilderToffoli c a -> [Wire] -> Integer -> (a, Integer, c) runCircuitBuilderToffoli m ctrls nextWireIndex = runCircuitBuilderBase (runQuantumControlT m ctrls) nextWireIndex evalCircuitBuilderToffoli :: IsCircuit g Wire c => CircuitBuilderToffoli c a -> [Wire] -> Integer -> (a, c) evalCircuitBuilderToffoli m ctrls nextWireIndex = evalCircuitBuilderBase (runQuantumControlT m ctrls) nextWireIndex evalCircuitBuilderToffoli_ :: IsCircuit g Wire c => CircuitBuilderToffoli c a -> [Wire] -> Integer -> c evalCircuitBuilderToffoli_ m ctrls nextWireIndex = evalCircuitBuilderBase_ (runQuantumControlT m ctrls) nextWireIndex execCircuitBuilderToffoli :: IsCircuit g Wire c => CircuitBuilderToffoli c a -> [Wire] -> Integer -> (Integer, c) execCircuitBuilderToffoli m ctrls nextWireIndex = execCircuitBuilderBase (runQuantumControlT m ctrls) nextWireIndex buildCircuitToffoli :: IsCircuit g Wire c => CircuitBuilderToffoli (CircuitInvert (MinimizeWireIndices c)) a -> c buildCircuitToffoli m = buildCircuitBase $ runQuantumControlT m []
ti1024/hacq
src/Control/Monad/Quantum/CircuitBuilderToffoli.hs
bsd-3-clause
1,866
0
11
242
407
221
186
25
1
module Tests where import Block import Main import Control.Monad import Control.Monad.Trans.State.Lazy strangeT = clearField oneToZero $ parseField $ "0,0,0,1,1,1,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;" ++ "0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;" ++ "0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;" ++ "0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;" ++ "0,0,0,0,0,2,2,0,0,0;0,0,0,2,0,2,2,2,2,2;0,0,2,2,0,2,2,2,2,2;" ++ "0,2,2,2,2,2,2,2,2,2;0,2,2,2,2,2,2,2,2,2;0,2,2,2,2,2,2,2,2,2;" ++ "3,3,3,3,3,3,3,3,3,3;3,3,3,3,3,3,3,3,3,3" run :: IO () run = do let field = blogki --strangeT p = Player{playerName = "testo", rowPoints = 0, combo = 0, field = field} startX = handleAction 1000 (f, pos) <- evalStateT startX $ GameState{timebank = 0, timePerMove = 0, players = [p], myBot = "testo", fieldHeight = 20, fieldWidth = 10, gameRound = 0, thisPieceType = L, nextPieceType = S, thisPiecePosition = (3, -1)} putStrLn $ "Chosen coord: " ++ (show pos) pretty (insertBlock f pos field) leftTest :: Block -> [Field] leftTest b = flipTest b flipLeft -- rightTest :: Block -> [Field] -- rightTest b = flipTest b flipRight flipTest :: Block -> (Block -> Field -> Field) -> [Field] flipTest b f = [first, second, third, fourth, fifth] where first = getBlock b second = f b first third = f b second fourth = f b third fifth = f b fourth testIsGrounded :: Bool testIsGrounded = isGrounded ((1,14), testField, getBlock O, 0) testInsertBlock :: (Int, Int) -> IO () testInsertBlock coord = pretty $ insertBlock (getBlock T) coord testField testField :: Field testField = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,2,2,0,0,0,0,0], [0,0,2,2,2,0,0,0,0,0], [0,0,2,2,2,2,0,0,0,0], [2,2,2,2,2,2,2,2,2,2], [2,2,2,2,2,2,2,2,2,2]] testField1 :: Field testField1 = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,2,2,0,0,0,0,0], [0,0,2,2,2,0,0,0,0,0], [0,0,2,2,0,2,0,0,2,0], [0,2,2,2,2,2,0,0,2,2], [2,2,2,2,2,2,2,2,2,2]] testField2 :: Field testField2 = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,2,2,0,0,0,0,0], [0,0,2,2,2,0,0,0,0,0], [0,0,2,2,2,2,0,2,0,0], [0,2,2,2,2,2,2,2,2,0], [2,2,2,2,2,2,2,2,2,0]] testField3 :: Field testField3 = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,2,2,0,0], [0,0,0,0,0,2,2,2,2,0], [0,0,0,0,0,0,0,0,2,2]] testParse :: Field testParse = parseField $ "0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;" ++ "0,0,0,0,0,0,0,0,0,0;0,0,0,0,0,0,0,0,0,0;0,0,0,2,0,0,0,0,0,0;" ++ "2,2,2,2,0,2,2,0,2,0;2,2,2,0,2,2,2,2,2,0;0,0,2,0,2,2,2,2,0,0;" ++ "2,2,2,2,2,2,2,0,2,0;0,2,2,0,0,2,0,2,2,0;0,2,2,2,2,2,2,2,2,0;" ++ "2,2,2,0,2,2,0,0,2,0;2,2,0,2,0,2,2,0,2,0;2,2,0,2,2,2,2,0,2,0;" ++ "2,2,2,2,2,2,2,0,2,0;0,0,2,0,0,2,2,0,2,0;2,2,2,0,2,2,0,2,2,0;" ++ "3,3,3,3,3,3,3,3,3,3;3,3,3,3,3,3,3,3,3,3" blogki :: Field blogki = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,2,0,0,0,0,0,0,0], [0,0,2,2,2,2,0,0,0,0], [2,0,2,2,2,2,2,2,2,0], [2,2,2,2,2,2,2,0,2,2]]
ksallberg/block-battle
Tests.hs
bsd-3-clause
6,396
0
13
2,225
3,849
2,509
1,340
161
1
-- | This module implements a "flattening" pass over RichText 'Inline' -- values. This means that a tree structure such as -- -- @ -- EStrong -- [ EStrikethrough -- [ EText "inside" -- ] -- , EText "outside" -- ] -- @ -- -- will be converted into a "flat" representation without a tree -- structure so that the style information encoded in the tree is -- available at each node: -- -- @ -- [ -- [ SingleInline (FlattenedInline (FText "inside") [Strong, Strikethrough] Nothing -- , SingleInline (FlattenedInline (FText "outside") [Strong] Nothing -- ] -- ] -- @ -- -- The outer sequence is a sequence of lines (since inline lists can -- introduce line breaks). Each inner sequence is a single line. -- Each 'SingleInline' can be rendered as-is; if a 'NonBreaking' is -- encountered, that group of inlines should be treated as a unit for -- the purposes of line-wrapping (to happen in the Wrap module). The -- above representation example shows how the tree path including the -- 'EStrong' and 'EStrikethrough' nodes is flattened into a list of -- styles to accompany each inline value. This makes it trivial to carry -- that style information along with each node during line-wrapping -- rather than needing to deal with the tree structure. module Matterhorn.Draw.RichText.Flatten ( FlattenedContent(..) , FlattenedInline(..) , InlineStyle(..) , FlattenedValue(..) , flattenInlineSeq ) where import Prelude () import Matterhorn.Prelude import Control.Monad.Reader import Control.Monad.State import Data.List ( nub ) import qualified Data.Sequence as Seq import Data.Sequence ( ViewL(..) , ViewR(..) , (<|) , (|>) ) import qualified Data.Set as Set import qualified Data.Text as T import Matterhorn.Constants ( normalChannelSigil ) import Matterhorn.Types ( HighlightSet(..), SemEq(..), addUserSigil ) import Matterhorn.Types.RichText -- | A piece of text in a sequence of flattened RichText elements. This -- type represents the lowest-level kind of data that we can get from a -- rich text document. data FlattenedContent = FText Text -- ^ Some text | FSpace -- ^ A space | FUser Text -- ^ A user reference | FChannel Text -- ^ A channel reference | FEmoji Text -- ^ An emoji | FEditSentinel Bool -- ^ An "edited" marking deriving (Eq, Show) -- | A flattened inline value. data FlattenedInline a = FlattenedInline { fiValue :: FlattenedContent -- ^ The content of the value. , fiStyles :: [InlineStyle] -- ^ The styles that should be applied to this -- value. , fiURL :: Maybe URL -- ^ If present, the URL to which we should -- hyperlink this value. , fiName :: Maybe a -- ^ The resource name, if any, that should be used -- to make this inline clickable once rendered. } deriving (Show) -- | A flattened value. data FlattenedValue a = SingleInline (FlattenedInline a) -- ^ A single flattened value | NonBreaking (Seq (Seq (FlattenedValue a))) -- ^ A sequence of flattened values that MUST be kept together and -- never broken up by line-wrapping deriving (Show) -- | The visual styles of inline values. data InlineStyle = Strong | Emph | Strikethrough | Code | Permalink deriving (Eq, Show) type FlattenM n a = ReaderT (FlattenEnv n) (State (FlattenState n)) a -- | The flatten monad state data FlattenState a = FlattenState { fsCompletedLines :: Seq (Seq (FlattenedValue a)) -- ^ The lines that we have accumulated so far in the -- flattening process , fsCurLine :: Seq (FlattenedValue a) -- ^ The current line we are accumulating in the -- flattening process , fsNameIndex :: Int -- ^ The index used to generate a new unique name (of -- type 'a') to make a region of text clickable. } -- | The flatten monad environment data FlattenEnv a = FlattenEnv { flattenStyles :: [InlineStyle] -- ^ The styles that should apply to the current value -- being flattened , flattenURL :: Maybe URL -- ^ The hyperlink URL, if any, that should be applied to -- the current value being flattened , flattenHighlightSet :: HighlightSet -- ^ The highlight set to use to check for valid user or -- channel references , flattenNameGen :: Maybe (Int -> Inline -> Maybe a) -- ^ The function to use to generate resource names -- for clickable inlines. If provided, this is used to -- determine whether a given Inline should be augmented -- with a resource name. , flattenNameFunc :: Maybe (Int -> Maybe a) -- ^ The currently active function to generate a resource -- name for any inline. In practice this is just the -- value of flattenNameGen, but partially applied with a -- specific Inline prior to flattening that Inline. } -- | Given a sequence of inlines, flatten it into a list of lines of -- flattened values. -- -- The flattening process also validates user and channel references -- against a 'HighlightSet'. For example, if an 'EUser' node is found, -- its username argument is looked up in the 'HighlightSet'. If the -- username is found, the 'EUser' node is preserved as an 'FUser' node. -- Otherwise it is rewritten as an 'FText' node so that the username -- does not get highlighted. Channel references ('EChannel') are handled -- similarly. -- -- The optional name generator function argument is used to assign -- resource names to each inline that should be clickable once rendered. -- The result of the name generator function will be stored in the -- 'fiName' field of each 'FlattenedInline' that results from calling -- that function on an 'Inline'. flattenInlineSeq :: SemEq a => HighlightSet -> Maybe (Int -> Inline -> Maybe a) -- ^ A name generator function for clickable inlines. -- The integer argument is a unique (to this inline -- sequence) sequence number. -> Inlines -> Seq (Seq (FlattenedValue a)) flattenInlineSeq hs nameGen is = snd $ flattenInlineSeq' initialEnv 0 is where initialEnv = FlattenEnv { flattenStyles = [] , flattenURL = Nothing , flattenHighlightSet = hs , flattenNameGen = nameGen , flattenNameFunc = Nothing } flattenInlineSeq' :: SemEq a => FlattenEnv a -> Int -> Inlines -> (Int, Seq (Seq (FlattenedValue a))) flattenInlineSeq' env c is = (fsNameIndex finalState, fsCompletedLines finalState) where finalState = execState stBody initialState initialState = FlattenState { fsCompletedLines = mempty , fsCurLine = mempty , fsNameIndex = c } stBody = runReaderT body env body = do flattenInlines is pushFLine flattenInlines :: SemEq a => Inlines -> FlattenM a () flattenInlines is = do pairs <- nameInlinePairs mapM_ wrapFlatten pairs where wrapFlatten (nameFunc, i) = withNameFunc nameFunc $ flatten i -- For each inline, prior to flattening it, obtain the resource -- name (if any) that should be assigned to each flattened -- fragment of the inline. nameInlinePairs = forM (unInlines is) $ \i -> do nameFunc <- nameGenWrapper i return (nameFunc, i) -- Determine whether the name generation function will produce -- a name for this inline. If it does (using a fake sequence -- number) then return a new name generation function to use for -- all flattened fragments of this inline. nameGenWrapper :: Inline -> FlattenM a (Maybe (Int -> Maybe a)) nameGenWrapper i = do c <- gets fsNameIndex nameGen <- asks flattenNameGen return $ case nameGen of Nothing -> Nothing Just f -> if isJust (f c i) then Just (flip f i) else Nothing withNameFunc :: Maybe (Int -> Maybe a) -> FlattenM a () -> FlattenM a () withNameFunc f@(Just _) = withReaderT (\e -> e { flattenNameFunc = f }) withNameFunc Nothing = id withInlineStyle :: InlineStyle -> FlattenM a () -> FlattenM a () withInlineStyle s = withReaderT (\e -> e { flattenStyles = nub (s : flattenStyles e) }) withHyperlink :: URL -> FlattenM a () -> FlattenM a () withHyperlink u = withReaderT (\e -> e { flattenURL = Just u }) -- | Push a FlattenedContent value onto the current line. pushFC :: SemEq a => FlattenedContent -> FlattenM a () pushFC v = do env <- ask name <- getNextName let styles = flattenStyles env mUrl = flattenURL env fi = FlattenedInline { fiValue = v , fiStyles = styles , fiURL = mUrl , fiName = name } pushFV $ SingleInline fi getNextName :: FlattenM a (Maybe a) getNextName = do nameGen <- asks flattenNameFunc case nameGen of Nothing -> return Nothing Just f -> f <$> getNextNameIndex getNextNameIndex :: FlattenM a Int getNextNameIndex = do c <- gets fsNameIndex modify ( \s -> s { fsNameIndex = c + 1} ) return c setNextNameIndex :: Int -> FlattenM a () setNextNameIndex i = modify ( \s -> s { fsNameIndex = i } ) -- | Push a FlattenedValue onto the current line. pushFV :: SemEq a => FlattenedValue a -> FlattenM a () pushFV fv = lift $ modify $ \s -> s { fsCurLine = appendFV fv (fsCurLine s) } -- | Append the value to the sequence. -- -- If the both the value to append AND the sequence's last value are -- both text nodes, AND if those nodes both have the same style and URL -- metadata, then merge them into one text node. This keeps adjacent -- non-whitespace text together as one logical token (e.g. "(foo" rather -- than "(" followed by "foo") to avoid undesirable line break points in -- the wrapping process. appendFV :: SemEq a => FlattenedValue a -> Seq (FlattenedValue a) -> Seq (FlattenedValue a) appendFV v line = case (Seq.viewr line, v) of (h :> SingleInline a, SingleInline b) -> case (fiValue a, fiValue b) of (FText aT, FText bT) -> if fiStyles a == fiStyles b && fiURL a == fiURL b && fiName a `semeq` fiName b then h |> SingleInline (FlattenedInline (FText $ aT <> bT) (fiStyles a) (fiURL a) (max (fiName a) (fiName b))) else line |> v _ -> line |> v _ -> line |> v -- | Push the current line onto the finished lines list and start a new -- line. pushFLine :: FlattenM a () pushFLine = lift $ modify $ \s -> s { fsCompletedLines = fsCompletedLines s |> fsCurLine s , fsCurLine = mempty } isKnownUser :: T.Text -> FlattenM a Bool isKnownUser u = do hSet <- asks flattenHighlightSet let uSet = hUserSet hSet return $ u `Set.member` uSet isKnownChannel :: T.Text -> FlattenM a Bool isKnownChannel c = do hSet <- asks flattenHighlightSet let cSet = hChannelSet hSet return $ c `Set.member` cSet flatten :: SemEq a => Inline -> FlattenM a () flatten i = case i of EUser u -> do known <- isKnownUser u if known then pushFC (FUser u) else pushFC (FText $ addUserSigil u) EChannel c -> do known <- isKnownChannel c if known then pushFC (FChannel c) else pushFC (FText $ normalChannelSigil <> c) ENonBreaking is -> do env <- ask ni <- getNextNameIndex let (ni', s) = flattenInlineSeq' env ni is pushFV $ NonBreaking s setNextNameIndex ni' ESoftBreak -> pushFLine ELineBreak -> pushFLine EText t -> pushFC $ FText t ESpace -> pushFC FSpace ERawHtml h -> pushFC $ FText h EEmoji e -> pushFC $ FEmoji e EEditSentinel r -> pushFC $ FEditSentinel r EEmph es -> withInlineStyle Emph $ flattenInlines es EStrikethrough es -> withInlineStyle Strikethrough $ flattenInlines es EStrong es -> withInlineStyle Strong $ flattenInlines es ECode es -> withInlineStyle Code $ flattenInlines es EPermalink _ _ mLabel -> let label' = fromMaybe (Inlines $ Seq.fromList [EText "post", ESpace, EText "link"]) mLabel in withInlineStyle Permalink $ flattenInlines $ decorateLinkLabel label' EHyperlink u label@(Inlines ls) -> let label' = if Seq.null ls then Inlines $ Seq.singleton $ EText $ unURL u else label in withHyperlink u $ flattenInlines $ decorateLinkLabel label' EImage u label@(Inlines ls) -> let label' = if Seq.null ls then Inlines $ Seq.singleton $ EText $ unURL u else label in withHyperlink u $ flattenInlines $ decorateLinkLabel label' linkOpenBracket :: Inline linkOpenBracket = EText "<" linkCloseBracket :: Inline linkCloseBracket = EText ">" addOpenBracket :: Inlines -> Inlines addOpenBracket (Inlines l) = case Seq.viewl l of EmptyL -> Inlines l h :< t -> let h' = ENonBreaking $ Inlines $ Seq.fromList [linkOpenBracket, h] in Inlines $ h' <| t addCloseBracket :: Inlines -> Inlines addCloseBracket (Inlines l) = case Seq.viewr l of EmptyR -> Inlines l h :> t -> let t' = ENonBreaking $ Inlines $ Seq.fromList [t, linkCloseBracket] in Inlines $ h |> t' decorateLinkLabel :: Inlines -> Inlines decorateLinkLabel = addOpenBracket . addCloseBracket
matterhorn-chat/matterhorn
src/Matterhorn/Draw/RichText/Flatten.hs
bsd-3-clause
15,142
0
19
5,251
2,876
1,528
1,348
223
21
import qualified Wigner.Transformations as T import qualified Wigner.Symbols as S import qualified Wigner.DefineExpression as D import qualified Wigner.OperatorAlgebra as O import Wigner.Texable import Wigner.Expression import qualified Data.Map as M import qualified Data.List as L index :: Integer -> Index index i = S.index (fromInteger i :: Int) s_psi = S.symbol "\\Psi" corr = M.fromList [(s_psi, s_psi)] psi1 = D.operatorFuncIx s_psi [index 1] [Func (Element S.x [] [])] psi1' = D.operatorFuncIx s_psi [index 1] [Func (Element S.x' [] [])] psi2 = D.operatorFuncIx s_psi [index 2] [Func (Element S.x [] [])] psi2' = D.operatorFuncIx s_psi [index 2] [Func (Element S.x' [] [])] x = S.x x' = S.x' psi i v = D.operatorFuncIx s_psi [index i] [Func (Element v [] [])] sx v = (dagger (psi 2 v) * (psi 1 v) + dagger (psi 1 v) * (psi 2 v)) sy v = (dagger (psi 2 v) * (psi 1 v) - dagger (psi 1 v) * (psi 2 v)) sz v = (dagger (psi 1 v) * (psi 1 v) - dagger (psi 2 v) * (psi 2 v)) main = do putStrLn $ showTex $ O.toSymmetricProduct O.bosonicCommutationRelation ( --sx x * sx x' --sy x * sy x' --sz x * sz x' sx x * sz x' + sz x * sx x' )
fjarri/wigner
examples/to_symm.hs
bsd-3-clause
1,183
2
13
266
591
305
286
25
1
-- | Critical pair generation. {-# LANGUAGE BangPatterns, FlexibleContexts, ScopedTypeVariables, MultiParamTypeClasses, RecordWildCards, OverloadedStrings, TypeFamilies, GeneralizedNewtypeDeriving #-} module Twee.CP where import qualified Twee.Term as Term import Twee.Base import Twee.Rule import Twee.Index(Index) import qualified Data.Set as Set import Control.Monad import Data.List import qualified Data.ChurchList as ChurchList import Data.ChurchList (ChurchList(..)) import Twee.Utils import Twee.Equation import qualified Twee.Proof as Proof import Twee.Proof(Derivation, congPath) -- | The set of positions at which a term can have critical overlaps. data Positions f = NilP | ConsP {-# UNPACK #-} !Int !(Positions f) type PositionsOf a = Positions (ConstantOf a) instance Show (Positions f) where show = show . ChurchList.toList . positionsChurch -- | Calculate the set of positions for a term. positions :: Term f -> Positions f positions t = aux 0 Set.empty (singleton t) where -- Consider only general superpositions. aux !_ !_ Empty = NilP aux n m (Cons (Var _) t) = aux (n+1) m t aux n m ConsSym{hd = t@App{}, rest = u} | t `Set.member` m = aux (n+1) m u | otherwise = ConsP n (aux (n+1) (Set.insert t m) u) {-# INLINE positionsChurch #-} positionsChurch :: Positions f -> ChurchList Int positionsChurch posns = ChurchList $ \c n -> let pos NilP = n pos (ConsP x posns) = c x (pos posns) in pos posns -- | A critical overlap of one rule with another. data Overlap f = Overlap { -- | The depth (1 for CPs of axioms, 2 for CPs whose rules have depth 1, etc.) overlap_depth :: {-# UNPACK #-} !Depth, -- | The critical term. overlap_top :: {-# UNPACK #-} !(Term f), -- | The part of the critical term which the inner rule rewrites. overlap_inner :: {-# UNPACK #-} !(Term f), -- | The position in the critical term which is rewritten. overlap_pos :: {-# UNPACK #-} !Int, -- | The critical pair itself. overlap_eqn :: {-# UNPACK #-} !(Equation f) } deriving Show type OverlapOf a = Overlap (ConstantOf a) -- | Represents the depth of a critical pair. newtype Depth = Depth Int deriving (Eq, Ord, Num, Real, Enum, Integral, Show) -- | Compute all overlaps of a rule with a set of rules. {-# INLINEABLE overlaps #-} overlaps :: forall a f. (Function f, Has a Id, Has a (Rule f), Has a (Positions f), Has a Depth) => Depth -> Index f a -> [a] -> a -> [(a, a, Overlap f)] overlaps max_depth idx rules r = ChurchList.toList (overlapsChurch max_depth idx rules r) {-# INLINE overlapsChurch #-} overlapsChurch :: forall f a. (Function f, Has a (Rule f), Has a (Positions f), Has a Depth) => Depth -> Index f a -> [a] -> a -> ChurchList (a, a, Overlap f) overlapsChurch max_depth idx rules r1 = do guard (the r1 < max_depth) r2 <- ChurchList.fromList rules guard (the r2 < max_depth) let !depth = 1 + max (the r1) (the r2) do { o <- asymmetricOverlaps idx depth (the r1) r1' (the r2); return (r1, r2, o) } `mplus` do { o <- asymmetricOverlaps idx depth (the r2) (the r2) r1'; return (r2, r1, o) } where !r1' = renameAvoiding (map the rules :: [Rule f]) (the r1) {-# INLINE asymmetricOverlaps #-} asymmetricOverlaps :: (Function f, Has a (Rule f), Has a Depth) => Index f a -> Depth -> Positions f -> Rule f -> Rule f -> ChurchList (Overlap f) asymmetricOverlaps idx depth posns r1 r2 = do n <- positionsChurch posns ChurchList.fromMaybe $ overlapAt n depth r1 r2 >>= simplifyOverlap idx -- | Create an overlap at a particular position in a term. -- Doesn't simplify the overlap. {-# INLINE overlapAt #-} {-# SCC overlapAt #-} overlapAt :: Int -> Depth -> Rule f -> Rule f -> Maybe (Overlap f) overlapAt !n !depth (Rule _ _ !outer !outer') (Rule _ _ !inner !inner') = do let t = at n (singleton outer) sub <- unifyTri inner t let top = termSubst sub outer innerTerm = termSubst sub inner -- Make sure to keep in sync with overlapProof lhs = termSubst sub outer' rhs = buildReplacePositionSub sub n (singleton inner') (singleton outer) guard (lhs /= rhs) return Overlap { overlap_depth = depth, overlap_top = top, overlap_inner = innerTerm, overlap_pos = n, overlap_eqn = lhs :=: rhs } -- | Simplify an overlap and remove it if it's trivial. {-# INLINE simplifyOverlap #-} simplifyOverlap :: (Function f, Has a (Rule f)) => Index f a -> Overlap f -> Maybe (Overlap f) simplifyOverlap idx overlap@Overlap{overlap_eqn = lhs :=: rhs, ..} | lhs == rhs = Nothing | lhs' == rhs' = Nothing | otherwise = Just overlap{overlap_eqn = lhs' :=: rhs'} where lhs' = simplify idx lhs rhs' = simplify idx rhs -- Put these in separate functions to avoid code blowup buildReplacePositionSub :: TriangleSubst f -> Int -> TermList f -> TermList f -> Term f buildReplacePositionSub !sub !n !inner' !outer = build (replacePositionSub sub n inner' outer) termSubst :: TriangleSubst f -> Term f -> Term f termSubst sub t = build (Term.subst sub t) -- | The configuration for the critical pair weighting heuristic. data Config = Config { cfg_lhsweight :: !Int, cfg_rhsweight :: !Int, cfg_funweight :: !Int, cfg_varweight :: !Int, cfg_depthweight :: !Int, cfg_dupcost :: !Int, cfg_dupfactor :: !Int } -- | The default heuristic configuration. defaultConfig :: Config defaultConfig = Config { cfg_lhsweight = 4, cfg_rhsweight = 1, cfg_funweight = 7, cfg_varweight = 6, cfg_depthweight = 16, cfg_dupcost = 7, cfg_dupfactor = 0 } -- | Compute a score for a critical pair. -- We compute: -- cfg_lhsweight * size l + cfg_rhsweight * size r -- where l is the biggest term and r is the smallest, -- and variables have weight 1 and functions have weight cfg_funweight. {-# INLINEABLE score #-} score :: Function f => Config -> Overlap f -> Int score Config{..} Overlap{..} = fromIntegral overlap_depth * cfg_depthweight + (m + n) * cfg_rhsweight + intMax m n * (cfg_lhsweight - cfg_rhsweight) where l :=: r = overlap_eqn m = size' 0 (singleton l) n = size' 0 (singleton r) size' !n Empty = n size' n (Cons t ts) | len t > 1, t `isSubtermOfList` ts = size' (n+cfg_dupcost+cfg_dupfactor*len t) ts size' n ts | Cons (App f ws@(Cons a (Cons b us))) vs <- ts, not (isVar a), not (isVar b), hasEqualsBonus (fun_value f), Just sub <- unify a b = size' (n+cfg_funweight) ws `min` size' (size' (n+1) (subst sub us)) (subst sub vs) size' n (Cons (Var _) ts) = size' (n+cfg_varweight) ts size' n ConsSym{hd = App{}, rest = ts} = size' (n+cfg_funweight) ts ---------------------------------------------------------------------- -- * Higher-level handling of critical pairs. ---------------------------------------------------------------------- -- | A critical pair together with information about how it was derived data CriticalPair f = CriticalPair { -- | The critical pair itself. cp_eqn :: {-# UNPACK #-} !(Equation f), -- | The depth of the critical pair. cp_depth :: {-# UNPACK #-} !Depth, -- | The critical term, if there is one. -- (Axioms do not have a critical term.) cp_top :: !(Maybe (Term f)), -- | A derivation of the critical pair from the axioms. cp_proof :: !(Derivation f) } instance Symbolic (CriticalPair f) where type ConstantOf (CriticalPair f) = f termsDL CriticalPair{..} = termsDL cp_eqn `mplus` termsDL cp_top `mplus` termsDL cp_proof subst_ sub CriticalPair{..} = CriticalPair { cp_eqn = subst_ sub cp_eqn, cp_depth = cp_depth, cp_top = subst_ sub cp_top, cp_proof = subst_ sub cp_proof } instance PrettyTerm f => Pretty (CriticalPair f) where pPrint CriticalPair{..} = vcat [ pPrint cp_eqn, nest 2 (text "top:" <+> pPrint cp_top) ] -- | Split a critical pair so that it can be turned into rules. -- -- The resulting critical pairs have the property that no variable appears on -- the right that is not on the left. -- See the comment below. split :: Function f => CriticalPair f -> [CriticalPair f] split CriticalPair{cp_eqn = l :=: r, ..} | l == r = [] | otherwise = -- If we have something which is almost a rule, except that some -- variables appear only on the right-hand side, e.g.: -- f x y -> g x z -- then we replace it with the following two rules: -- f x y -> g x ? -- g x z -> g x ? -- where the second rule is weakly oriented and ? is the minimal -- constant. -- -- If we have an unoriented equation with a similar problem, e.g.: -- f x y = g x z -- then we replace it with potentially three rules: -- f x ? = g x ? -- f x y -> f x ? -- g x z -> g x ? -- The main rule l -> r' or r -> l' or l' = r' [ CriticalPair { cp_eqn = l :=: r', cp_depth = cp_depth, cp_top = eraseExcept (vars l) cp_top, cp_proof = eraseExcept (vars l) cp_proof } | ord == Just GT ] ++ [ CriticalPair { cp_eqn = r :=: l', cp_depth = cp_depth, cp_top = eraseExcept (vars r) cp_top, cp_proof = Proof.symm (eraseExcept (vars r) cp_proof) } | ord == Just LT ] ++ [ CriticalPair { cp_eqn = l' :=: r', cp_depth = cp_depth, cp_top = eraseExcept (vars l) $ eraseExcept (vars r) cp_top, cp_proof = eraseExcept (vars l) $ eraseExcept (vars r) cp_proof } | ord == Nothing ] ++ -- Weak rules l -> l' or r -> r' [ CriticalPair { cp_eqn = l :=: l', cp_depth = cp_depth + 1, cp_top = Nothing, cp_proof = cp_proof `Proof.trans` Proof.symm (erase ls cp_proof) } | not (null ls), ord /= Just GT ] ++ [ CriticalPair { cp_eqn = r :=: r', cp_depth = cp_depth + 1, cp_top = Nothing, cp_proof = Proof.symm cp_proof `Proof.trans` erase rs cp_proof } | not (null rs), ord /= Just LT ] where ord = orientTerms l' r' l' = erase ls l r' = erase rs r ls = usort (vars l) \\ usort (vars r) rs = usort (vars r) \\ usort (vars l) eraseExcept vs t = erase (usort (vars t) \\ usort vs) t -- | Make a critical pair from two rules and an overlap. {-# INLINEABLE makeCriticalPair #-} makeCriticalPair :: forall f a. (Has a (Rule f), Has a Id, Function f) => a -> a -> Overlap f -> CriticalPair f makeCriticalPair r1 r2 overlap@Overlap{..} = CriticalPair overlap_eqn overlap_depth (Just overlap_top) (overlapProof r1 r2 overlap) -- | Return a proof for a critical pair. {-# INLINEABLE overlapProof #-} overlapProof :: forall a f. (Has a (Rule f), Has a Id) => a -> a -> Overlap f -> Derivation f overlapProof left right Overlap{..} = Proof.symm (ruleDerivation (subst leftSub (the left))) `Proof.trans` congPath path overlap_top (ruleDerivation (subst rightSub (the right))) where Just leftSub = match (lhs (the left)) overlap_top Just rightSub = match (lhs (the right)) overlap_inner path = positionToPath (lhs (the left) :: Term f) overlap_pos
nick8325/kbc
src/Twee/CP.hs
bsd-3-clause
11,211
0
18
2,775
3,445
1,799
1,646
-1
-1
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies#-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS -Wall #-} module LambdaCalculus.State2 ( SECDState(SECDState), emptySECD, SECDState1 ) where import Basic.Memory (Stack, MapLike, empty, emptyM) import LambdaCalculus.Types -- pretty much everything from this is needed import Control.Lens (makeLenses) -------------------------------------------------------------------- -- one example data SECDState s e c d = SECDState { _stk :: s, _envi :: e, _control :: c, _dmp :: d} makeLenses ''SECDState instance HasStack (SECDState s e c d) where type Stck (SECDState s e c d) = s stck = stk instance HasEnv (SECDState s e c d) where type Env (SECDState s e c d) = e env = envi instance HasCtrl (SECDState s e c d) where type Ctrl (SECDState s e c d) = c ctrl = control instance HasDump (SECDState s e c d) where type Dump (SECDState s e c d) = d dump = dmp type SECDState1 s m st c = SECDState (st s) m (st c) (st (st s, m, st c)) emptySECD :: (Stack st, MapLike m) => SECDState1 s (m var val) st c emptySECD = SECDState empty emptyM empty empty
davidzhulijun/TAM
LambdaCalculus/State2.hs
bsd-3-clause
1,158
0
9
227
394
221
173
31
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Servant.JQuery.Internal where import Control.Lens import Data.Monoid import Data.Proxy import GHC.TypeLits import Servant.API type Arg = String data Segment = Static String -- ^ a static path segment. like "/foo" | Cap Arg -- ^ a capture. like "/:userid" deriving (Eq, Show) isCapture :: Segment -> Bool isCapture (Cap _) = True isCapture _ = False captureArg :: Segment -> Arg captureArg (Cap s) = s captureArg _ = error "captureArg called on non capture" jsSegments :: [Segment] -> String jsSegments [] = "" jsSegments [x] = "/" ++ segmentToStr x False jsSegments (x:xs) = "/" ++ segmentToStr x True ++ jsSegments xs segmentToStr :: Segment -> Bool -> String segmentToStr (Static s) notTheEnd = if notTheEnd then s else s ++ "'" segmentToStr (Cap s) notTheEnd = "' + encodeURIComponent(" ++ s ++ if notTheEnd then ") + '" else ")" type Path = [Segment] data ArgType = Normal | Flag | List deriving (Eq, Show) data QueryArg = QueryArg { _argName :: Arg , _argType :: ArgType } deriving (Eq, Show) type HeaderArg = String data Url = Url { _path :: Path , _queryStr :: [QueryArg] } deriving (Eq, Show) defUrl :: Url defUrl = Url [] [] type FunctionName = String type Method = String data AjaxReq = AjaxReq { _reqUrl :: Url , _reqMethod :: Method , _reqHeaders :: [HeaderArg] , _reqBody :: Bool , _funcName :: FunctionName } deriving (Eq, Show) makeLenses ''QueryArg makeLenses ''Url makeLenses ''AjaxReq jsParams :: [QueryArg] -> String jsParams [] = "" jsParams [x] = paramToStr x False jsParams (x:xs) = paramToStr x True ++ "&" ++ jsParams xs paramToStr :: QueryArg -> Bool -> String paramToStr qarg notTheEnd = case qarg ^. argType of Normal -> name ++ "=' + encodeURIComponent(" ++ name ++ if notTheEnd then ") + '" else ")" Flag -> name ++ "=" List -> name ++ "[]=' + encodeURIComponent(" ++ name ++ if notTheEnd then ") + '" else ")" where name = qarg ^. argName defReq :: AjaxReq defReq = AjaxReq defUrl "GET" [] False "" class HasJQ layout where type JQ layout :: * jqueryFor :: Proxy layout -> AjaxReq -> JQ layout instance (HasJQ a, HasJQ b) => HasJQ (a :<|> b) where type JQ (a :<|> b) = JQ a :<|> JQ b jqueryFor Proxy req = jqueryFor (Proxy :: Proxy a) req :<|> jqueryFor (Proxy :: Proxy b) req instance (KnownSymbol sym, HasJQ sublayout) => HasJQ (Capture sym a :> sublayout) where type JQ (Capture sym a :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqUrl.path <>~ [Cap str] where str = symbolVal (Proxy :: Proxy sym) instance HasJQ Delete where type JQ Delete = AjaxReq jqueryFor Proxy req = req & funcName %~ ("delete" <>) & reqMethod .~ "DELETE" instance HasJQ (Get a) where type JQ (Get a) = AjaxReq jqueryFor Proxy req = req & funcName %~ ("get" <>) & reqMethod .~ "GET" instance (KnownSymbol sym, HasJQ sublayout) => HasJQ (Header sym a :> sublayout) where type JQ (Header sym a :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor subP (req & reqHeaders <>~ [hname]) where hname = symbolVal (Proxy :: Proxy sym) subP = Proxy :: Proxy sublayout instance HasJQ (Post a) where type JQ (Post a) = AjaxReq jqueryFor Proxy req = req & funcName %~ ("post" <>) & reqMethod .~ "POST" instance HasJQ (Put a) where type JQ (Put a) = AjaxReq jqueryFor Proxy req = req & funcName %~ ("put" <>) & reqMethod .~ "PUT" instance (KnownSymbol sym, HasJQ sublayout) => HasJQ (QueryParam sym a :> sublayout) where type JQ (QueryParam sym a :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqUrl.queryStr <>~ [QueryArg str Normal] where str = symbolVal (Proxy :: Proxy sym) strArg = str ++ "Value" instance (KnownSymbol sym, HasJQ sublayout) => HasJQ (QueryParams sym a :> sublayout) where type JQ (QueryParams sym a :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqUrl.queryStr <>~ [QueryArg str List] where str = symbolVal (Proxy :: Proxy sym) instance (KnownSymbol sym, HasJQ sublayout) => HasJQ (QueryFlag sym :> sublayout) where type JQ (QueryFlag sym :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqUrl.queryStr <>~ [QueryArg str Flag] where str = symbolVal (Proxy :: Proxy sym) instance HasJQ Raw where type JQ Raw = Method -> AjaxReq jqueryFor Proxy req method = req & reqMethod .~ method instance HasJQ sublayout => HasJQ (ReqBody a :> sublayout) where type JQ (ReqBody a :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqBody .~ True instance (KnownSymbol path, HasJQ sublayout) => HasJQ (path :> sublayout) where type JQ (path :> sublayout) = JQ sublayout jqueryFor Proxy req = jqueryFor (Proxy :: Proxy sublayout) $ req & reqUrl.path <>~ [Static str] & funcName %~ (str <>) where str = map (\c -> if c == '.' then '_' else c) $ symbolVal (Proxy :: Proxy path)
derekelkins/servant-jquery
src/Servant/JQuery/Internal.hs
bsd-3-clause
5,545
0
13
1,396
1,929
1,018
911
-1
-1
module Control where import SudokuCore import Solver import qualified Grader import Sequence import Digger import Warehouse data Instruction = MakeSolutions Int | MakePuzzles | GradePuzzles run :: Warehouse -> Instruction -> Warehouse run wh (MakeSolutions amount) = let (sols, newRest) = takeSolutions amount $ getRestSolutions wh in insertRestSolutions newRest $ insertSolutions sols wh run wh MakePuzzles = let puzzles = map (\grid -> (,) grid $ makePuzzles grid) $ getSolutions wh in insertPuzzles puzzles wh run wh GradePuzzles = let graded = map gradePuzzle $ getPuzzles wh in insertGrades graded wh makePuzzles :: Grid -> [Puzzle] makePuzzles grid = map newPuzzle $ dig grid mirrored newPuzzle :: Grid -> Puzzle newPuzzle grid = Puzzle { puzzle = grid, grade = Nothing} gradePuzzle :: Puzzle -> Puzzle gradePuzzle old = Puzzle {puzzle = puzzle old , grade = Grader.grade $ puzzle old}
Stulv/sudoku
src/Control.hs
bsd-3-clause
977
0
15
226
306
158
148
29
1
-- break beat import System.Cmd(system) import Temporal.Music.Western.P12 import Temporal.Music.Demo.GeneralMidi tom11 = mel [qd 0, qd 0, qnr, qd 0, hd 0.5, dhnr] tom12 = mel [qd 0, qd 0, qnr, qd 0, hd 0.5, qnr, qd 0] scoTom = ff' $ mel [tom11, tom12] scoSnare = mp' $ mel [hnr, hd 0, hnr, hd 0] scoMaracas = mp' $ mel [dhnr, trn $ mel [ed 0.5, ed 0, ed 0]] drums = loop 8 $ har [ bassDrum1 scoTom, loop 2 $ acousticSnare scoSnare, loop 3 $ maracas scoMaracas ] scoAccomp = withAccentRel [0, 1, 0.5, 1.5, 0.5, 1, 0] $ loop 2 $ mf' $ high $ sustain 0.5 $ har [ p' $ loop 2 $ qn $ mel [f, c, e, f, c, e, f, c], accent 1 $ low $ mel [dwn a, dwn gs, hnr], accent 1.5 $ mel [bnr, hnr, trn $ mel [dhn gs, dhn e, dhn d]] ] accomp = loop 4 $ glockenspiel scoAccomp -- fade out after 0.7*totalDur res = withAccentSeg [0, 0.7, 0, 0.3, -5] $ har [ drums, accomp ] main = do exportMidi "break.mid" res system "timidity break.mid"
spell-music/temporal-music-notation-demo
examples/break.hs
bsd-3-clause
1,024
1
14
297
504
265
239
25
1
module Win32Types ( module Win32Types , nullAddr ) where import StdDIS ---------------------------------------------------------------- -- Platform specific definitions -- -- Most typedefs and prototypes in Win32 are expressed in terms -- of these types. Try to follow suit - itll make it easier to -- get things working on Win64 (or whatever they call it on Alphas). ---------------------------------------------------------------- type BOOL = Bool type BYTE = Word8 type USHORT = Word16 type UINT = Word32 type INT = Int32 type WORD = Word16 type DWORD = Word32 type LONG = Int32 type FLOAT = Float type MbINT = Maybe INT ---------------------------------------------------------------- type ATOM = UINT type WPARAM = UINT type LPARAM = LONG type LRESULT = LONG type MbATOM = Maybe ATOM ---------------------------------------------------------------- -- Pointers ---------------------------------------------------------------- type LPVOID = Addr type LPCTSTR = Addr type LPCTSTR_ = String type LPCSTR = Addr type LPSTR = Addr -- Note: marshalling allocates mem, so the programmer -- has to make sure to free this stuff up after any -- uses of LPCTSTR. Automating this is tricky to do -- (in all situations). unmarshall_lpctstr_ :: Addr -> IO String unmarshall_lpctstr_ arg1 = prim_Win32Types_cpp_unmarshall_lpctstr_ arg1 >>= \ (gc_res2,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (unmarshall_string_ gc_res2) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32Types_cpp_unmarshall_lpctstr_ :: Addr -> IO (Addr,Int,Addr) marshall_lpctstr_ :: String -> IO Addr marshall_lpctstr_ gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32Types_cpp_marshall_lpctstr_ arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32Types_cpp_marshall_lpctstr_ :: Addr -> IO (Addr,Int,Addr) type MbLPVOID = Maybe LPVOID type MbLPCSTR = Maybe LPCSTR type MbLPCTSTR = Maybe LPCTSTR ---------------------------------------------------------------- -- Handles ---------------------------------------------------------------- type HANDLE = Addr handleToWord :: HANDLE -> UINT handleToWord arg1 = unsafePerformIO( prim_Win32Types_cpp_handleToWord arg1 >>= \ (res1) -> (return (res1))) primitive prim_Win32Types_cpp_handleToWord :: Addr -> IO (Word32) type HKEY = ForeignObj nullHANDLE :: Addr nullHANDLE = unsafePerformIO( prim_Win32Types_cpp_nullHANDLE >>= \ (res1) -> (return (res1))) primitive prim_Win32Types_cpp_nullHANDLE :: IO (Addr) type MbHANDLE = Maybe HANDLE type HINSTANCE = Addr type MbHINSTANCE = Maybe HINSTANCE type HMODULE = Addr type MbHMODULE = Maybe HMODULE nullFinalHANDLE :: ForeignObj nullFinalHANDLE = unsafePerformIO (makeForeignObj nullAddr nullAddr) ---------------------------------------------------------------- -- End ---------------------------------------------------------------- needPrims_hugs 2
OS2World/DEV-UTIL-HUGS
libraries/win32/Win32Types.hs
bsd-3-clause
3,379
27
12
725
648
378
270
-1
-1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , MagicHash , UnboxedTuples , ScopedTypeVariables , RankNTypes #-} {-# OPTIONS_GHC -Wno-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, forkOSWithUnmask, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Control.Exception.Base as Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import GHC.IO ( unsafeUnmask, catchException ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd ) import Foreign.StablePtr import Foreign.C.Types #if defined(mingw32_HOST_OS) import Foreign.C import System.IO import Data.Functor ( void ) import Data.Int ( Int64 ) #else import qualified GHC.Conc #endif import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- @since 4.6.0.0 forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. foreign import ccall unsafe rtsSupportsBoundThreads :: Bool {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export ccall forkOS_entry :: StablePtr (IO ()) -> IO () foreign import ccall "forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import ccall forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Like 'forkIOWithUnmask', but the child thread is a bound thread, -- as with 'forkOS'. forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need its main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap its @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `catchException` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd #if defined(mingw32_HOST_OS) -- we have no IO manager implementing threadWaitRead on Windows. -- fdReady does the right thing, but we have to call it in a -- separate thread, otherwise threadWaitRead won't be interruptible, -- and this only works with -threaded. | threaded = withThread (waitFd fd 0) | otherwise = case fd of 0 -> do _ <- hWaitForInput stdin (-1) return () -- hWaitForInput does work properly, but we can only -- do this for stdin since we know its FD. _ -> errorWithoutStackTrace "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput" #else = GHC.Conc.threadWaitRead fd #endif -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd #if defined(mingw32_HOST_OS) | threaded = withThread (waitFd fd 1) | otherwise = errorWithoutStackTrace "threadWaitWrite requires -threaded on Windows" #else = GHC.Conc.threadWaitWrite fd #endif -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitReadSTM :: Fd -> IO (STM (), IO ()) threadWaitReadSTM fd #if defined(mingw32_HOST_OS) | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd 0) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = errorWithoutStackTrace "threadWaitReadSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitReadSTM fd #endif -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) threadWaitWriteSTM fd #if defined(mingw32_HOST_OS) | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd 1) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = errorWithoutStackTrace "threadWaitWriteSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitWriteSTM fd #endif #if defined(mingw32_HOST_OS) foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool withThread :: IO a -> IO a withThread io = do m <- newEmptyMVar _ <- mask_ $ forkIO $ try io >>= putMVar m x <- takeMVar m case x of Right a -> return a Left e -> throwIO (e :: IOException) waitFd :: Fd -> CInt -> IO () waitFd fd write = do throwErrnoIfMinus1_ "fdReady" $ fdReady (fromIntegral fd) write (-1) 0 foreign import ccall safe "fdReady" fdReady :: CInt -> CInt -> Int64 -> CInt -> IO CInt #endif -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
ezyang/ghc
libraries/base/Control/Concurrent.hs
bsd-3-clause
24,912
0
21
6,066
1,998
1,054
944
133
3
--TODO -> Maybe this module is useful at more places than just func spec rendering. -- In that case it's not a Rendering module and it needs to be replaced module Database.Design.Ampersand.FSpec.Motivations (Motivated(purposeOf,purposesDefinedIn,explanations,explForObj), Meaning(..)) where import Database.Design.Ampersand.Core.AbstractSyntaxTree import Database.Design.Ampersand.FSpec.FSpec(FSpec(..),Activity(..)) import Database.Design.Ampersand.Basics import Text.Pandoc fatal :: Int -> String -> a fatal = fatalMsg "FSpec.Motivations" -- The general idea is that an Ampersand declaration such as: -- PURPOSE RELATION r[A*B] IN ENGLISH -- {+This text explains why r[A*B] exists-} -- produces the exact right text in the functional specification -- The class Motivated exists so that we can write the Haskell expression 'purposeOf fSpec l x' -- anywhere we like for every type of x that could possibly be motivated in an Purpose. -- 'purpose fSpec l x' produces all explanations related to x from the context (fSpec) -- that are available in the language specified in 'l'. -- The other functions in this class are solely meant to be used in the definition of purpose. -- They are defined once for each instance of Explainable, not be used in other code. -- TODO: Han, kan dat worden afgeschermd, zodat de programmeur alleen 'purpose' ziet en de andere functies -- dus niet kan gebruiken? -- @Stef: Ja, het is al zoveel mogelijk afgeschermd (zie definities die deze module exporteert, hierboven) -- maar er wordt nog gebruik van gemaakt voor oa foutmeldingen in de atlas, en het prototype. -- Zodra iemand iets anders verzint voor het gebruik van "ExplainOutputFormat(..),format", -- kunnen deze uit de export-list van deze module worden verwijderd. class Named a => Motivated a where purposeOf :: FSpec -> Lang -> a -> Maybe [Purpose] -- ^ explains the purpose of a, i.e. the reason why a exists. The purpose could be either given by the user, or generated by Ampersand. -- Multiple purposes are allowed for the following reasons: -- * Different purposes from different sources make me want to document them all. -- * Combining two overlapping scripts from (i.e. from different authors) may cause multiple purposes. purposeOf fSpec l x = case expls of [] -> Nothing -- fatal 40 "No purpose is generated! (should be automatically generated and available in FSpec.)" ps -> Just ps where expls = [e | e<-explanations fSpec , explForObj x (explObj e) -- informally: "if x and e are the same" , markupMatchesLang (explMarkup e) ] markupMatchesLang m = amLang m == l explForObj :: a -> ExplObj -> Bool -- ^ Given an Explainable object and an ExplObj, return TRUE if they concern the identical object. explanations :: a -> [Purpose] -- ^ The explanations that are defined inside a (including that of a itself) purposesDefinedIn :: FSpec -> Lang -> a -> [Purpose] -- ^ The explanations that are defined inside a (including that of a itself) purposesDefinedIn fSpec l x = [e | e<-explanations fSpec , amLang (explMarkup e) == l , explForObj x (explObj e) -- informally: "if x and e are the same" ] instance Motivated ConceptDef where -- meaning _ cd = fatal 49 ("Concept definitions have no intrinsic meaning, (used with concept definition of '"++cdcpt cd++"')") explForObj x (ExplConceptDef x') = x == x' explForObj _ _ = False explanations _ = [] instance Motivated A_Concept where -- meaning _ c = fatal 54 ("Concepts have no intrinsic meaning, (used with concept '"++name c++"')") explForObj x (ExplConceptDef cd) = name x == name cd explForObj _ _ = False explanations _ = [] instance Motivated Declaration where -- meaning l decl = if null (decMean decl) -- then concat [explCont expl | expl<-autoMeaning l decl, Just l == explLang expl || Nothing == explLang expl] -- else decMean decl explForObj d1 (ExplDeclaration d2) = d1 == d2 explForObj _ _ = False explanations _ = [] -- autoMeaning lang d -- = [Expl { explPos = decfpos d -- , explObj = ExplDeclaration d -- , explLang = Just lang -- , explRefIds = [] -- , explCont = [Para langInlines] -- } ] -- where -- langInlines = -- case lang of -- English -- | null ([Sym,Asy] >- multiplicities d) -> [Emph [Str (name d)]] -- ++[Str " is a property of a "] -- ++[Str ((unCap.name.source) d)] -- ++[Str "."] -- | null ([Sym,Rfx,Trn] >- multiplicities d) -> [Emph [Str (name d)]] -- ++[Str " is an equivalence relation on "] -- ++[Str ((unCap.plural English .name.source) d)] -- ++[Str "."] -- | null ([Asy,Trn] >- multiplicities d) -> [Emph [Str (name d)]] -- ++[Str " is an ordering relation on "] -- ++[Str ((unCap.plural English .name.source) d)] -- ++[Str "."] -- | null ([Uni,Tot,Inj,Sur] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("exactly one "++(unCap.name.target) d)] -- ++[Str " and vice versa."] -- | null ([Uni,Tot,Inj ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("exactly one "++(unCap.name.target) d)] -- ++[Str ", but not for each "] -- ++[Str ((unCap.name.target) d++" there must be a "++(unCap.name.source) d)] -- ++[Str "."] -- | null ([Uni,Tot, Sur] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("exactly one "++(unCap.name.target) d)] -- ++[Str ", but each "] -- ++[Str ((unCap.name.target) d++" is related to one or more "++(unCap.plural English .name.source) d)] -- ++[Str "."] -- | null ([Uni, Inj,Sur] >- multiplicities d) -> [Str ("There is exactly one "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") for each "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), for which: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str (", but not for each "++(unCap.name.source) d++" there must be a "++(unCap.name.target) d++".")] -- | null ([ Tot,Inj,Sur] >- multiplicities d) -> [Str ("There is exactly one "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") for each "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), for which: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str (", but each "++(unCap.name.source) d++" is related to one or more "++(unCap.plural English .name.target) d)] -- ++[Str "."] -- | null ([Uni,Tot ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("exactly one "++(unCap.name.target) d)] -- ++[Str "."] -- | null ([Uni, Inj ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("at most one "++(unCap.name.target) d)] -- ++[Str (" and each "++(unCap.name.target) d++" is related to at most one "++(unCap.name.source) d)] -- ++[Str "."] -- | null ([Uni, Sur] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("at most one "++(unCap.name.target) d)] -- ++[Str (", whereas each "++(unCap.name.target) d++" is related to at least one "++(unCap.name.source) d)] -- ++[Str "."] -- | null ([ Tot,Inj ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("at least one "++(unCap.name.target) d)] -- ++[Str (", whereas each "++(unCap.name.target) d++" is related to at most one "++(unCap.name.source) d)] -- ++[Str "."] -- | null ([ Tot, Sur] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("at least one "++(unCap.name.target) d)] -- ++[Str (" and each "++(unCap.name.target) d++" is related to at least one "++(unCap.name.source) d)] -- ++[Str "."] -- | null ([ Inj,Sur] >- multiplicities d) -> [Str ("There is exactly one "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") for each "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), for which: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Sur] >- multiplicities d) -> [Str ("There is at least one "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") for each "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), for which: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Inj ] >- multiplicities d) -> [Str ("There is at most one "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") for each "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), for which: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Tot ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("at least one "++(unCap.name.target) d)] -- ++[Str "."] -- | null ([Uni ] >- multiplicities d) -> applyM d [Str ("each "++(unCap.name.source) d)] -- [Str ("zero or one "++(unCap.name.target) d)] -- ++[Str "."] -- | otherwise -> [Str "The sentence: "] -- ++[Quoted DoubleQuote -- (applyM d [Math InlineMath ((var [].source) d)] -- [Math InlineMath ((var [source d].target) d)]) -- ] -- ++[Str (" is meaningful (i.e. it is either true or false) for any "++(unCap.name.source) d++" ")] -- ++[(Math InlineMath . var [] . source) d] -- ++[Str (" and "++(unCap.name.target) d++" ")] -- ++[(Math InlineMath . var [source d] . target) d] -- ++[Str "."] -- Dutch -- | null ([Sym,Asy] >- multiplicities d) -> [Emph [Str (name d)]] -- ++[Str " is een eigenschap van een "] -- ++[Str ((unCap.name.source) d)] -- ++[Str "."] -- | null ([Sym,Rfx,Trn] >- multiplicities d) ->[Emph [Str (name d)]] -- ++[Str " is een equivalentierelatie tussen "] -- ++[Str ((unCap.plural Dutch .name.source) d)] -- ++[Str "."] -- | null ([Asy,Trn] >- multiplicities d) ->[Emph [Str (name d)]] -- ++[Str " is een ordeningsrelatie tussen "] -- ++[Str ((unCap.plural Dutch .name.source) d)] -- ++[Str "."] -- | null ([Uni,Tot,Inj,Sur] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("precies één "++(unCap.name.target) d)] -- ++[Str " en vice versa."] -- | null ([Uni,Tot,Inj] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("precies één "++(unCap.name.target) d)] -- ++[Str ", maar niet voor elke "] -- ++[Str ((unCap.name.target) d)] -- ++[Str " hoeft er een "] -- ++[Str ((unCap.name.source) d)] -- ++[Str " te zijn."] -- | null ([Uni,Tot, Sur] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("precies één "++(unCap.name.target) d)] -- ++[Str ", maar elke "] ---- ++[Str ((unCap.name.target) d)] -- ++[Str (" is gerelateerd aan één of meer ")] -- ++[Str ((unCap.plural Dutch .name.source) d)] -- ++[Str "."] -- | null ([Uni, Inj,Sur] >- multiplicities d) -> [Str ("Er is precies één "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") voor elke "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), waarvoor geldt: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str (", maar niet voor elke "++(unCap.name.source) d++" hoeft er een "++(unCap.name.target) d++" te zijn.")] -- | null ([ Tot,Inj,Sur] >- multiplicities d) -> [Str ("Er is precies één "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") voor elke "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), waarvoor geldt: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str (", maar elke "++(unCap.name.source) d++" mag gerelateerd zijn aan meerdere "++(unCap.plural Dutch .name.target) d++".")] -- | null ([Uni,Tot ] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("precies één "++(unCap.name.target) d)] -- ++[Str "."] -- | null ([Uni, Inj ] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("ten hoogste één "++(unCap.name.target) d)] -- ++[Str " en elke "] -- ++[Str ((unCap.name.target) d)] -- ++[Str (" is gerelateerd aan ten hoogste één ")] -- ++[Str ((unCap.name.source) d++".")] -- ++[Str "."] -- | null ([Uni, Sur] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("ten hoogste één "++(unCap.name.target) d)] -- ++[Str ", terwijl elke "] -- ++[Str ((unCap.name.target) d)] -- ++[Str (" is gerelateerd aan tenminste één ")] -- ++[Str ((unCap.name.source) d)] -- ++[Str "."] -- | null ([ Tot,Inj ] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("tenminste één "++(unCap.name.target) d)] -- ++[Str ", terwijl elke "] -- ++[Str ((unCap.name.target) d)] -- ++[Str (" is gerelateerd aan ten hoogste één ")] -- ++[Str ((unCap.name.source) d)] -- ++[Str "."] -- | null ([ Tot, Sur] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("tenminste één "++(unCap.name.target) d)] -- ++[Str (" en elke "++(unCap.name.target) d++" is gerelateerd aan tenminste één "++(unCap.name.source) d++".")] -- | null ([ Inj,Sur] >- multiplicities d) -> [Str ("Er is precies één "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") voor elke "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), waarvoor geldt: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Sur] >- multiplicities d) -> [Str ("Er is tenminste één "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") voor elke "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), waarvoor geldt: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Inj ] >- multiplicities d) -> [Str ("Er is hooguit één "++(unCap.name.source) d++" (")] -- ++[Math InlineMath "a"] -- ++[Str (") voor elke "++(unCap.name.target) d++" (")] -- ++[Math InlineMath "b"] -- ++[Str "), waarvoor geldt: "] -- ++applyM d [Math InlineMath "b"] [Math InlineMath "a"] -- ++[Str "."] -- | null ([ Tot ] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("tenminste één "++(unCap.name.target) d)] -- ++[Str "."] -- | null ([Uni ] >- multiplicities d) -> applyM d [Str ("elke "++(unCap.name.source) d)] -- [Str ("nul of één "++(unCap.name.target) d)] -- ++[Str "."] -- | otherwise -> [Str "De zin: "] -- ++[Quoted DoubleQuote -- (applyM d [(Math InlineMath . var [] . source) d] -- [(Math InlineMath . var [source d] . target) d]) -- ] -- ++[Str (" heeft betekenis (dus: is waar of niet waar) voor een "++(unCap.name.source) d++" ")] -- ++[(Math InlineMath . var [].source) d] -- ++[Str (" en een "++(unCap.name.target) d++" ")] -- ++[(Math InlineMath . var [source d].target) d] -- ++[Str "."] -- -- applyM :: Declaration -> [Inline] -> [Inline] -> [Inline] -- applyM decl a b = -- case decl of -- Sgn{} | null (prL++prM++prR) -- -> a++[Space,Str "corresponds",Space,Str "to",Space]++b++[Space,Str "in",Space,Str "relation",Space,Str(name decl)] -- | null prL -- -> a++[Space,Str prM,Space]++b++[Space,Str prR] -- | otherwise -- -> [Str (upCap prL),Space]++a++[Space,Str prM,Space]++b++if null prR then [] else [Space,Str prR] -- where prL = decprL decl -- prM = decprM decl -- prR = decprR decl -- Isn{} -> a++[Space,Str "equals",Space]++b -- Vs{} -> [Str (show True)] -- -- var :: Named a => [a] -> a -> String -- TODO Vervangen door mkvar, uit predLogic.hs -- var seen c = low c ++ ['\'' | c'<-seen, low c == low c'] -- where low idt= if null (name idt) then "x" else [(toLower.head.name) idt] instance Motivated Rule where -- meaning l rule -- = head (expls++map explCont (autoMeaning l rule)) -- where -- expls = [econt | Means l' econt<-rrxpl rule, l'==Just l || l'==Nothing] explForObj x (ExplRule str) = name x == str explForObj _ _ = False explanations _ = [] -- autoMeaning lang r -- = [Expl { explObj = ExplRule (name r) -- , explPos = origin r -- , explLang = Just lang -- , explRefIds = [] -- , explCont = [Plain [RawInline (Text.Pandoc.Builder.Format "latex") (showPredLogic lang r++".")]] -- } ] instance Motivated Pattern where -- meaning _ pat = fatal 324 ("Patterns have no intrinsic meaning, (used with pattern '"++name pat++"')") explForObj x (ExplPattern str) = name x == str explForObj _ _ = False explanations = ptxps instance Motivated Interface where -- meaning _ obj = fatal 342 ("Interfaces have no intrinsic meaning, (used with interface '"++name obj++"')") explForObj x (ExplInterface str) = name x == str explForObj _ _ = False explanations _ = [] class Meaning a where meaning :: Lang -> a -> Maybe A_Markup meaning2Blocks :: Lang -> a -> [Block] meaning2Blocks l a = case meaning l a of Nothing -> [] Just m -> amPandoc m instance Meaning Rule where meaning l r = case filter isLang (ameaMrk (rrmean r)) of [] -> Nothing [m] -> Just m _ -> fatal 381 ("In the "++show l++" language, too many meanings given for rule "++name r ++".") where isLang m = l == amLang m instance Meaning Declaration where meaning l d = case d of Sgn{} -> let isLang m = l == amLang m in case filter isLang (ameaMrk (decMean d)) of [] -> Nothing [m] -> Just m _ -> fatal 388 ("In the "++show l++" language, too many meanings given for declaration "++name d ++".") Isn{} -> fatal 370 "meaning is undefined for Isn" Vs{} -> fatal 371 "meaning is undefined for Vs" instance Motivated FSpec where -- meaning _ fSpec = fatal 329 ("No FSpec has an intrinsic meaning, (used with FSpec '"++name fSpec++"')") explForObj x (ExplContext str) = name x == str explForObj _ _ = False explanations fSpec = fSexpls fSpec ++ (concatMap explanations . vpatterns) fSpec ++ (concatMap explanations . interfaceS) fSpec -- Ampersand allows multiple purposes for everything. -- The diagnosis report must make mention of this (so the user will notice if (s)he reads the diagnosis). -- Multiple purposes are simply concatenated, so the user sees them all. instance Motivated Activity where explForObj _ _ = False explanations activity = actPurp activity purposeOf _ l x = case [ e | e <- actPurp x, amLang (explMarkup e) == l ] of [] -> Nothing purps -> Just purps
guoy34/ampersand
src/Database/Design/Ampersand/FSpec/Motivations.hs
gpl-3.0
30,197
0
20
15,324
1,448
871
577
84
1
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module Tisch.Internal.Debug ( renderSqlQuery , renderSqlQuery' ) where import qualified Data.Profunctor.Product.Default as PP import qualified Opaleye.Sql as O import qualified Opaleye.Internal.Unpackspec as OI import Tisch.Internal.Query (Query(..)) -------------------------------------------------------------------------------- renderSqlQuery :: forall d v. (PP.Default OI.Unpackspec v v) => Query d () v -> Maybe String renderSqlQuery = renderSqlQuery' (PP.def :: OI.Unpackspec v v) renderSqlQuery' :: OI.Unpackspec v v' -> Query d () v -> Maybe String renderSqlQuery' u = O.showSqlForPostgresExplicit u . unQuery
k0001/opaleye-sot
src/lib/Tisch/Internal/Debug.hs
bsd-3-clause
732
0
9
99
177
103
74
15
1
{-# OPTIONS -cpp #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- -- (c) The University of Glasgow 2002-2006 -- -- Binary I/O library, with special tweaks for GHC -- -- Based on the nhc98 Binary library, which is copyright -- (c) Malcolm Wallace and Colin Runciman, University of York, 1998. -- Under the terms of the license for that software, we must tell you -- where you can obtain the original version of the Binary library, namely -- http://www.cs.york.ac.uk/fp/nhc98/ module Binary ( {-type-} Bin, {-class-} Binary(..), {-type-} BinHandle, SymbolTable, Dictionary, openBinIO, openBinIO_, openBinMem, -- closeBin, seekBin, seekBy, tellBin, castBin, writeBinMem, readBinMem, fingerprintBinMem, computeFingerprint, isEOFBin, putAt, getAt, -- for writing instances: putByte, getByte, -- lazy Bin I/O lazyGet, lazyPut, #ifdef __GLASGOW_HASKELL__ -- GHC only: ByteArray(..), getByteArray, putByteArray, #endif UserData(..), getUserData, setUserData, newReadState, newWriteState, putDictionary, getDictionary, putFS, ) where #include "HsVersions.h" -- The *host* architecture version: #include "../includes/MachDeps.h" import {-# SOURCE #-} Name (Name) import FastString import Panic import UniqFM import FastMutInt import Fingerprint import BasicTypes import Foreign import Data.Array import Data.IORef import Data.Char ( ord, chr ) import Data.Typeable #if __GLASGOW_HASKELL__ >= 701 import Data.Typeable.Internal #endif import Control.Monad ( when ) import System.IO as IO import System.IO.Unsafe ( unsafeInterleaveIO ) import System.IO.Error ( mkIOError, eofErrorType ) import GHC.Real ( Ratio(..) ) import GHC.Exts import GHC.Word ( Word8(..) ) import GHC.IO ( IO(..) ) type BinArray = ForeignPtr Word8 --------------------------------------------------------------- -- BinHandle --------------------------------------------------------------- data BinHandle = BinMem { -- binary data stored in an unboxed array bh_usr :: UserData, -- sigh, need parameterized modules :-) _off_r :: !FastMutInt, -- the current offset _sz_r :: !FastMutInt, -- size of the array (cached) _arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1)) } -- XXX: should really store a "high water mark" for dumping out -- the binary data to a file. | BinIO { -- binary data stored in a file bh_usr :: UserData, _off_r :: !FastMutInt, -- the current offset (cached) _hdl :: !IO.Handle -- the file handle (must be seekable) } -- cache the file ptr in BinIO; using hTell is too expensive -- to call repeatedly. If anyone else is modifying this Handle -- at the same time, we'll be screwed. getUserData :: BinHandle -> UserData getUserData bh = bh_usr bh setUserData :: BinHandle -> UserData -> BinHandle setUserData bh us = bh { bh_usr = us } --------------------------------------------------------------- -- Bin --------------------------------------------------------------- newtype Bin a = BinPtr Int deriving (Eq, Ord, Show, Bounded) castBin :: Bin a -> Bin b castBin (BinPtr i) = BinPtr i --------------------------------------------------------------- -- class Binary --------------------------------------------------------------- class Binary a where put_ :: BinHandle -> a -> IO () put :: BinHandle -> a -> IO (Bin a) get :: BinHandle -> IO a -- define one of put_, put. Use of put_ is recommended because it -- is more likely that tail-calls can kick in, and we rarely need the -- position return value. put_ bh a = do _ <- put bh a; return () put bh a = do p <- tellBin bh; put_ bh a; return p putAt :: Binary a => BinHandle -> Bin a -> a -> IO () putAt bh p x = do seekBin bh p; put_ bh x; return () getAt :: Binary a => BinHandle -> Bin a -> IO a getAt bh p = do seekBin bh p; get bh openBinIO_ :: IO.Handle -> IO BinHandle openBinIO_ h = openBinIO h openBinIO :: IO.Handle -> IO BinHandle openBinIO h = do r <- newFastMutInt writeFastMutInt r 0 return (BinIO noUserData r h) openBinMem :: Int -> IO BinHandle openBinMem size | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0" | otherwise = do arr <- mallocForeignPtrBytes size arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r size return (BinMem noUserData ix_r sz_r arr_r) tellBin :: BinHandle -> IO (Bin a) tellBin (BinIO _ r _) = do ix <- readFastMutInt r; return (BinPtr ix) tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix) seekBin :: BinHandle -> Bin a -> IO () seekBin (BinIO _ ix_r h) (BinPtr p) = do writeFastMutInt ix_r p hSeek h AbsoluteSeek (fromIntegral p) seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do sz <- readFastMutInt sz_r if (p >= sz) then do expandBin h p; writeFastMutInt ix_r p else writeFastMutInt ix_r p seekBy :: BinHandle -> Int -> IO () seekBy (BinIO _ ix_r h) off = do ix <- readFastMutInt ix_r let ix' = ix + off writeFastMutInt ix_r ix' hSeek h AbsoluteSeek (fromIntegral ix') seekBy h@(BinMem _ ix_r sz_r _) off = do sz <- readFastMutInt sz_r ix <- readFastMutInt ix_r let ix' = ix + off if (ix' >= sz) then do expandBin h ix'; writeFastMutInt ix_r ix' else writeFastMutInt ix_r ix' isEOFBin :: BinHandle -> IO Bool isEOFBin (BinMem _ ix_r sz_r _) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r return (ix >= sz) isEOFBin (BinIO _ _ h) = hIsEOF h writeBinMem :: BinHandle -> FilePath -> IO () writeBinMem (BinIO _ _ _) _ = error "Data.Binary.writeBinMem: not a memory handle" writeBinMem (BinMem _ ix_r _ arr_r) fn = do h <- openBinaryFile fn WriteMode arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> hPutBuf h p ix hClose h readBinMem :: FilePath -> IO BinHandle -- Return a BinHandle with a totally undefined State readBinMem filename = do h <- openBinaryFile filename ReadMode filesize' <- hFileSize h let filesize = fromIntegral filesize' arr <- mallocForeignPtrBytes (filesize*2) count <- withForeignPtr arr $ \p -> hGetBuf h p filesize when (count /= filesize) $ error ("Binary.readBinMem: only read " ++ show count ++ " bytes") hClose h arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r filesize return (BinMem noUserData ix_r sz_r arr_r) fingerprintBinMem :: BinHandle -> IO Fingerprint fingerprintBinMem (BinIO _ _ _) = error "Binary.md5BinMem: not a memory handle" fingerprintBinMem (BinMem _ ix_r _ arr_r) = do arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> fingerprintData p ix computeFingerprint :: Binary a => (BinHandle -> Name -> IO ()) -> a -> IO Fingerprint computeFingerprint put_name a = do bh <- openBinMem (3*1024) -- just less than a block bh <- return $ setUserData bh $ newWriteState put_name putFS put_ bh a fingerprintBinMem bh -- expand the size of the array to include a specified offset expandBin :: BinHandle -> Int -> IO () expandBin (BinMem _ _ sz_r arr_r) off = do sz <- readFastMutInt sz_r let sz' = head (dropWhile (<= off) (iterate (* 2) sz)) arr <- readIORef arr_r arr' <- mallocForeignPtrBytes sz' withForeignPtr arr $ \old -> withForeignPtr arr' $ \new -> copyBytes new old sz writeFastMutInt sz_r sz' writeIORef arr_r arr' when False $ -- disabled hPutStrLn stderr ("Binary: expanding to size: " ++ show sz') return () expandBin (BinIO _ _ _) _ = return () -- no need to expand a file, we'll assume they expand by themselves. -- ----------------------------------------------------------------------------- -- Low-level reading/writing of bytes putWord8 :: BinHandle -> Word8 -> IO () putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r -- double the size of the array if it overflows if (ix >= sz) then do expandBin h ix putWord8 h w else do arr <- readIORef arr_r withForeignPtr arr $ \p -> pokeByteOff p ix w writeFastMutInt ix_r (ix+1) return () putWord8 (BinIO _ ix_r h) w = do ix <- readFastMutInt ix_r hPutChar h (chr (fromIntegral w)) -- XXX not really correct writeFastMutInt ix_r (ix+1) return () getWord8 :: BinHandle -> IO Word8 getWord8 (BinMem _ ix_r sz_r arr_r) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r when (ix >= sz) $ ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing) arr <- readIORef arr_r w <- withForeignPtr arr $ \p -> peekByteOff p ix writeFastMutInt ix_r (ix+1) return w getWord8 (BinIO _ ix_r h) = do ix <- readFastMutInt ix_r c <- hGetChar h writeFastMutInt ix_r (ix+1) return $! (fromIntegral (ord c)) -- XXX not really correct putByte :: BinHandle -> Word8 -> IO () putByte bh w = put_ bh w getByte :: BinHandle -> IO Word8 getByte = getWord8 -- ----------------------------------------------------------------------------- -- Primitve Word writes instance Binary Word8 where put_ = putWord8 get = getWord8 instance Binary Word16 where put_ h w = do -- XXX too slow.. inline putWord8? putByte h (fromIntegral (w `shiftR` 8)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2) instance Binary Word32 where put_ h w = do putByte h (fromIntegral (w `shiftR` 24)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 24) .|. (fromIntegral w2 `shiftL` 16) .|. (fromIntegral w3 `shiftL` 8) .|. (fromIntegral w4)) instance Binary Word64 where put_ h w = do putByte h (fromIntegral (w `shiftR` 56)) putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h w5 <- getWord8 h w6 <- getWord8 h w7 <- getWord8 h w8 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 56) .|. (fromIntegral w2 `shiftL` 48) .|. (fromIntegral w3 `shiftL` 40) .|. (fromIntegral w4 `shiftL` 32) .|. (fromIntegral w5 `shiftL` 24) .|. (fromIntegral w6 `shiftL` 16) .|. (fromIntegral w7 `shiftL` 8) .|. (fromIntegral w8)) -- ----------------------------------------------------------------------------- -- Primitve Int writes instance Binary Int8 where put_ h w = put_ h (fromIntegral w :: Word8) get h = do w <- get h; return $! (fromIntegral (w::Word8)) instance Binary Int16 where put_ h w = put_ h (fromIntegral w :: Word16) get h = do w <- get h; return $! (fromIntegral (w::Word16)) instance Binary Int32 where put_ h w = put_ h (fromIntegral w :: Word32) get h = do w <- get h; return $! (fromIntegral (w::Word32)) instance Binary Int64 where put_ h w = put_ h (fromIntegral w :: Word64) get h = do w <- get h; return $! (fromIntegral (w::Word64)) -- ----------------------------------------------------------------------------- -- Instances for standard types instance Binary () where put_ _ () = return () get _ = return () instance Binary Bool where put_ bh b = putByte bh (fromIntegral (fromEnum b)) get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x)) instance Binary Char where put_ bh c = put_ bh (fromIntegral (ord c) :: Word32) get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32))) instance Binary Int where put_ bh i = put_ bh (fromIntegral i :: Int64) get bh = do x <- get bh return $! (fromIntegral (x :: Int64)) instance Binary a => Binary [a] where put_ bh l = do let len = length l if (len < 0xff) then putByte bh (fromIntegral len :: Word8) else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32) mapM_ (put_ bh) l get bh = do b <- getByte bh len <- if b == 0xff then get bh else return (fromIntegral b :: Word32) let loop 0 = return [] loop n = do a <- get bh; as <- loop (n-1); return (a:as) loop len instance (Binary a, Binary b) => Binary (a,b) where put_ bh (a,b) = do put_ bh a; put_ bh b get bh = do a <- get bh b <- get bh return (a,b) instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (a,b,c) instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d get bh = do a <- get bh b <- get bh c <- get bh d <- get bh return (a,b,c,d) instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh return (a,b,c,d,e) instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh f <- get bh return (a,b,c,d,e,f) instance Binary a => Binary (Maybe a) where put_ bh Nothing = putByte bh 0 put_ bh (Just a) = do putByte bh 1; put_ bh a get bh = do h <- getWord8 bh case h of 0 -> return Nothing _ -> do x <- get bh; return (Just x) instance (Binary a, Binary b) => Binary (Either a b) where put_ bh (Left a) = do putByte bh 0; put_ bh a put_ bh (Right b) = do putByte bh 1; put_ bh b get bh = do h <- getWord8 bh case h of 0 -> do a <- get bh ; return (Left a) _ -> do b <- get bh ; return (Right b) #if defined(__GLASGOW_HASKELL__) || 1 --to quote binary-0.3 on this code idea, -- -- TODO This instance is not architecture portable. GMP stores numbers as -- arrays of machine sized words, so the byte format is not portable across -- architectures with different endianess and word size. -- -- This makes it hard (impossible) to make an equivalent instance -- with code that is compilable with non-GHC. Do we need any instance -- Binary Integer, and if so, does it have to be blazing fast? Or can -- we just change this instance to be portable like the rest of the -- instances? (binary package has code to steal for that) -- -- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.lhs instance Binary Integer where -- XXX This is hideous put_ bh i = put_ bh (show i) get bh = do str <- get bh case reads str of [(i, "")] -> return i _ -> fail ("Binary Integer: got " ++ show str) {- put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#) put_ bh (J# s# a#) = do putByte bh 1 put_ bh (I# s#) let sz# = sizeofByteArray# a# -- in *bytes* put_ bh (I# sz#) -- in *bytes* putByteArray bh a# sz# get bh = do b <- getByte bh case b of 0 -> do (I# i#) <- get bh return (S# i#) _ -> do (I# s#) <- get bh sz <- get bh (BA a#) <- getByteArray bh sz return (J# s# a#) -} -- As for the rest of this code, even though this module -- exports it, it doesn't seem to be used anywhere else -- in GHC! putByteArray :: BinHandle -> ByteArray# -> Int# -> IO () putByteArray bh a s# = loop 0# where loop n# | n# ==# s# = return () | otherwise = do putByte bh (indexByteArray a n#) loop (n# +# 1#) getByteArray :: BinHandle -> Int -> IO ByteArray getByteArray bh (I# sz) = do (MBA arr) <- newByteArray sz let loop n | n ==# sz = return () | otherwise = do w <- getByte bh writeByteArray arr n w loop (n +# 1#) loop 0# freezeByteArray arr data ByteArray = BA ByteArray# data MBA = MBA (MutableByteArray# RealWorld) newByteArray :: Int# -> IO MBA newByteArray sz = IO $ \s -> case newByteArray# sz s of { (# s, arr #) -> (# s, MBA arr #) } freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray freezeByteArray arr = IO $ \s -> case unsafeFreezeByteArray# arr s of { (# s, arr #) -> (# s, BA arr #) } writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO () writeByteArray arr i (W8# w) = IO $ \s -> case writeWord8Array# arr i w s of { s -> (# s, () #) } indexByteArray :: ByteArray# -> Int# -> Word8 indexByteArray a# n# = W8# (indexWord8Array# a# n#) instance (Integral a, Binary a) => Binary (Ratio a) where put_ bh (a :% b) = do put_ bh a; put_ bh b get bh = do a <- get bh; b <- get bh; return (a :% b) #endif instance Binary (Bin a) where put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32) get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32))) -- ----------------------------------------------------------------------------- -- Instances for Data.Typeable stuff #if __GLASGOW_HASKELL__ >= 701 instance Binary TyCon where put_ bh (TyCon _ p m n) = do put_ bh (p,m,n) get bh = do (p,m,n) <- get bh return (mkTyCon3 p m n) #else instance Binary TyCon where put_ bh ty_con = do let s = tyConString ty_con put_ bh s get bh = do s <- get bh return (mkTyCon s) #endif instance Binary TypeRep where put_ bh type_rep = do let (ty_con, child_type_reps) = splitTyConApp type_rep put_ bh ty_con put_ bh child_type_reps get bh = do ty_con <- get bh child_type_reps <- get bh return (mkTyConApp ty_con child_type_reps) -- ----------------------------------------------------------------------------- -- Lazy reading/writing lazyPut :: Binary a => BinHandle -> a -> IO () lazyPut bh a = do -- output the obj with a ptr to skip over it: pre_a <- tellBin bh put_ bh pre_a -- save a slot for the ptr put_ bh a -- dump the object q <- tellBin bh -- q = ptr to after object putAt bh pre_a q -- fill in slot before a with ptr to q seekBin bh q -- finally carry on writing at q lazyGet :: Binary a => BinHandle -> IO a lazyGet bh = do p <- get bh -- a BinPtr p_a <- tellBin bh a <- unsafeInterleaveIO (getAt bh p_a) seekBin bh p -- skip over the object for now return a -- ----------------------------------------------------------------------------- -- UserData -- ----------------------------------------------------------------------------- data UserData = UserData { -- for *deserialising* only: ud_get_name :: BinHandle -> IO Name, ud_get_fs :: BinHandle -> IO FastString, -- for *serialising* only: ud_put_name :: BinHandle -> Name -> IO (), ud_put_fs :: BinHandle -> FastString -> IO () } newReadState :: (BinHandle -> IO Name) -> (BinHandle -> IO FastString) -> UserData newReadState get_name get_fs = UserData { ud_get_name = get_name, ud_get_fs = get_fs, ud_put_name = undef "put_name", ud_put_fs = undef "put_fs" } newWriteState :: (BinHandle -> Name -> IO ()) -> (BinHandle -> FastString -> IO ()) -> UserData newWriteState put_name put_fs = UserData { ud_get_name = undef "get_name", ud_get_fs = undef "get_fs", ud_put_name = put_name, ud_put_fs = put_fs } noUserData :: a noUserData = undef "UserData" undef :: String -> a undef s = panic ("Binary.UserData: no " ++ s) --------------------------------------------------------- -- The Dictionary --------------------------------------------------------- type Dictionary = Array Int FastString -- The dictionary -- Should be 0-indexed putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO () putDictionary bh sz dict = do put_ bh sz mapM_ (putFS bh) (elems (array (0,sz-1) (eltsUFM dict))) getDictionary :: BinHandle -> IO Dictionary getDictionary bh = do sz <- get bh elems <- sequence (take sz (repeat (getFS bh))) return (listArray (0,sz-1) elems) --------------------------------------------------------- -- The Symbol Table --------------------------------------------------------- -- On disk, the symbol table is an array of IfaceExtName, when -- reading it in we turn it into a SymbolTable. type SymbolTable = Array Int Name --------------------------------------------------------- -- Reading and writing FastStrings --------------------------------------------------------- putFS :: BinHandle -> FastString -> IO () putFS bh (FastString _ l _ buf _) = do put_ bh l withForeignPtr buf $ \ptr -> let go n | n == l = return () | otherwise = do b <- peekElemOff ptr n putByte bh b go (n+1) in go 0 {- -- possible faster version, not quite there yet: getFS bh@BinMem{} = do (I# l) <- get bh arr <- readIORef (arr_r bh) off <- readFastMutInt (off_r bh) return $! (mkFastSubStringBA# arr off l) -} getFS :: BinHandle -> IO FastString getFS bh = do l <- get bh fp <- mallocForeignPtrBytes l withForeignPtr fp $ \ptr -> do let go n | n == l = mkFastStringForeignPtr ptr fp l | otherwise = do b <- getByte bh pokeElemOff ptr n b go (n+1) -- go 0 instance Binary FastString where put_ bh f = case getUserData bh of UserData { ud_put_fs = put_fs } -> put_fs bh f get bh = case getUserData bh of UserData { ud_get_fs = get_fs } -> get_fs bh -- Here to avoid loop instance Binary Fingerprint where put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2 get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2) instance Binary FunctionOrData where put_ bh IsFunction = putByte bh 0 put_ bh IsData = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsFunction 1 -> return IsData _ -> panic "Binary FunctionOrData"
mcmaniac/ghc
compiler/utils/Binary.hs
bsd-3-clause
24,352
0
19
7,182
7,667
3,792
3,875
-1
-1
module Fun.Make where import Inter.Types import Fun.Type import Fun.Check import Fun.Machine import Fun.Examples import qualified Machine.Numerical.Config as C import qualified Machine.Numerical.Make as M import qualified Machine.Numerical.Inter as I import qualified Autolib.Reporter.Checker as R import Autolib.Set make :: Make make = M.make $ C.Config { C.name = "Fun" , C.conditions = [ ] , C.arity = 2 , C.op = read "x1 + x2" , C.num_args = 10 , C.max_arg = 20 , C.cut = 1000 , C.checks = [ Builtins [ Plus, Minus ] ] , C.start = plus :: Fun }
florianpilz/autotool
src/Fun/Make.hs
gpl-2.0
627
0
10
170
184
117
67
22
1
{-# LANGUAGE BangPatterns #-} module Data.IntPSQ.Benchmark ( benchmark ) where import Data.List (foldl') import qualified Data.IntPSQ as IntPSQ import Criterion.Main import Prelude hiding (lookup) import BenchmarkTypes benchmark :: String -> [BElem] -> BenchmarkSet benchmark name elems = BenchmarkSet { bGroupName = name , bMinView = whnf bench_minView initialPSQ , bLookup = whnf (bench_lookup keys) initialPSQ , bInsertEmpty = nf (bench_insert firstElems) IntPSQ.empty , bInsertNew = nf (bench_insert secondElems) initialPSQ , bInsertDuplicates = nf (bench_insert firstElems) initialPSQ , bDelete = nf (bench_delete firstKeys) initialPSQ } where (firstElems, secondElems) = splitAt (numElems `div` 2) elems numElems = length elems keys = map (\(x, _, _) -> x) elems firstKeys = map (\(x, _, _) -> x) firstElems initialPSQ = IntPSQ.fromList firstElems :: IntPSQ.IntPSQ Int () -- Get the sum of all priorities by getting all elements using 'lookup' bench_lookup :: [Int] -> IntPSQ.IntPSQ Int () -> Int bench_lookup xs m = foldl' (\n k -> maybe n fst (IntPSQ.lookup k m)) 0 xs -- Insert a list of elements one-by-one into a PSQ bench_insert :: [(Int, Int, ())] -> IntPSQ.IntPSQ Int () -> IntPSQ.IntPSQ Int () bench_insert xs m0 = foldl' (\m (k, p, v) -> IntPSQ.insert k p v m) m0 xs -- Get the sum of all priorities by sequentially popping all elements using -- 'minView' bench_minView :: IntPSQ.IntPSQ Int () -> Int bench_minView = go 0 where go !n t = case IntPSQ.minView t of Nothing -> n Just (k, p, _, t') -> go (n + k + p) t' -- Empty a queue by sequentially removing all elements bench_delete :: [Int] -> IntPSQ.IntPSQ Int () -> IntPSQ.IntPSQ Int () bench_delete keys t0 = foldl' (\t k -> IntPSQ.delete k t) t0 keys
ariep/psqueues
benchmarks/Data/IntPSQ/Benchmark.hs
bsd-3-clause
1,951
0
13
513
617
335
282
34
2
{-# OPTIONS -Wall #-} ----------------------------------------------------------------------------- -- | -- Module : CTest.hs (executable) -- Copyright : (c) 2008 Duncan Coutts, Benedikt Huber -- License : BSD-style -- Maintainer : [email protected] -- Portability : non-portable (Data.Generics) -- -- This is a very simple module, usable for quick tests. -- -- It provides a wrapper for parsing C-files which haven't been preprocessed yet. -- It is used as if gcc was called, and internally calls cpp (gcc -E) to preprocess the file. -- It then outputs the pretty printed AST, replacing declarations from included header -- files with a corresponding #include directive (This isn't always correct, as e.g. #define s -- get lost. But it makes it a lot easier to focus on the relevant part of the output). -- -- If used with a `-e str' command-line argument, the given string is parsed as an expression and pretty -- printed. Similar for `-d str' and top-level declarations. ------------------------------------------------------------------------------------------------------- module Main ( main ) where import Language.C import Language.C.System.GCC import Language.C.Analysis import Language.C.Test.Environment import Language.C.Test.GenericAST import Control.Monad import System.Environment (getEnv, getArgs) import System.Exit import System.IO import Data.Generics import Text.PrettyPrint.HughesPJ data CTestConfig = CTestConfig { debugFlag :: Bool, parseOnlyFlag :: Bool, useIncludes :: Bool, dumpAst :: Bool, semanticAnalysis :: Bool } usage :: String -> IO a usage msg = printUsage >> exitWith (ExitFailure 2) where printUsage = hPutStr stderr . unlines $ [ "! "++msg,"", "Usage: ./CTest -e expression", "Usage: ./CTest -s statement", "Usage: ./CTest -d declaration", "Usage: ./CTest [cpp-opts] file.(c|hc|i)", " parses the given C source file and pretty print the AST", "Environment Variables (some do not apply with -e,-s or -d): ", " TMPDIR: temporary directory for preprocessing", " NO_HEADERS_VIA_INCLUDE: do not use heuristic #include directives for pretty printing", " DEBUG: debug flag", " DUMP_AST: dump the ast to file dump.ast", " NO_SEMANTIC_ANALYSIS: do not perform semantic analysis", " PARSE_ONLY: do not pretty print" ] bailOut :: (Show err) => err -> IO a bailOut err = do hPutStrLn stderr (show err) hPutStrLn stderr "*** Exit on Error ***" exitWith (ExitFailure 1) main :: IO () main = do tmpdir <- getEnv "TMPDIR" dbg <- getEnvFlag "DEBUG" parseonly <- getEnvFlag "PARSE_ONLY" dumpast <- getEnvFlag "DUMP_AST" no_includes <- getEnvFlag "NO_HEADERS_VIA_INCLUDE" semantic <- liftM not (getEnvFlag "NO_SEMANTIC_ANALYSIS") let config = CTestConfig dbg parseonly (not $ no_includes) dumpast semantic args <- getArgs (file,ast) <- case args of ("-e":str:[]) -> runP config expressionP str >> exitWith ExitSuccess ("-s":str:[]) -> runP config statementP str >> exitWith ExitSuccess ("-d":str:[]) -> runP config extDeclP str >> exitWith ExitSuccess _otherArgs -> case mungeCcArgs args of Groked [cFile] gccOpts -> do presult <- parseCFile (newGCC "gcc") (Just tmpdir) gccOpts cFile either bailOut (return.((,) cFile)) presult Groked cFiles _ -> usage $ "More than one source file given: " ++ unwords cFiles Ignore -> usage $ "Not input files given" Unknown reason -> usage $ "Could not process arguments: " ++ reason output config file ast runP :: (CNode a, Pretty a, Data a) => CTestConfig -> P a -> String -> IO () runP config parser str = do ast <- either bailOut return $ pResult when (dumpAst config) $ writeFile "dump.ast" (gshow ast) when (not $ parseOnlyFlag config) $ print (pretty ast) where is = inputStreamFromString str pResult = execParser_ parser is (argPos) argPos = initPos "<cmd-line-arg>" output :: CTestConfig -> FilePath -> CTranslUnit -> IO () output config file ast = do when (dumpAst config) $ writeFile "dump.ast" (gshow ast) when (semanticAnalysis config && (not (null file))) $ do let result = runTrav_ (analyseAST ast) case result of Left errs -> hPutStrLn stderr (show errs) Right (ok,warnings) -> do mapM_ (hPutStrLn stderr . show) warnings printStats file ok when (not $ parseOnlyFlag config) $ print $ (if useIncludes config then prettyUsingInclude else pretty) ast when (debugFlag config) $ putStrLn . comment . show . pretty . mkGenericCAST $ ast comment :: String -> String comment str = "/*\n" ++ str ++ "\n*/" printStats :: FilePath -> GlobalDecls -> IO () printStats file = putStrLn . comment . show . prettyAssocsWith "global decl stats" text (text.show) . globalDeclStats (== file)
llelf/language-c
test/src/CTest.hs
bsd-3-clause
5,046
1
21
1,178
1,177
598
579
93
7
-- (c) The University of Glasgow 2006 -- -- FamInstEnv: Type checked family instance declarations {-# LANGUAGE CPP, GADTs, ScopedTypeVariables #-} module FamInstEnv ( FamInst(..), FamFlavor(..), famInstAxiom, famInstTyCon, famInstRHS, famInstsRepTyCons, famInstRepTyCon_maybe, dataFamInstRepTyCon, pprFamInst, pprFamInsts, mkImportedFamInst, FamInstEnvs, FamInstEnv, emptyFamInstEnv, emptyFamInstEnvs, extendFamInstEnv, deleteFromFamInstEnv, extendFamInstEnvList, identicalFamInstHead, famInstEnvElts, familyInstances, -- * CoAxioms mkCoAxBranch, mkBranchedCoAxiom, mkUnbranchedCoAxiom, mkSingleCoAxiom, mkNewTypeCoAxiom, FamInstMatch(..), lookupFamInstEnv, lookupFamInstEnvConflicts, lookupFamInstEnvByTyCon, isDominatedBy, apartnessCheck, -- Injectivity InjectivityCheckResult(..), lookupFamInstEnvInjectivityConflicts, injectiveBranches, -- Normalisation topNormaliseType, topNormaliseType_maybe, normaliseType, normaliseTcApp, reduceTyFamApp_maybe, -- Flattening flattenTys ) where #include "HsVersions.h" import Unify import Type import TyCoRep import TyCon import Coercion import CoAxiom import VarSet import VarEnv import Name import PrelNames ( eqPrimTyConKey ) import UniqDFM import Outputable import Maybes import TrieMap import Unique import Util import Var import Pair import SrcLoc import FastString import MonadUtils import Control.Monad import Data.Function ( on ) import Data.List( mapAccumL ) {- ************************************************************************ * * Type checked family instance heads * * ************************************************************************ Note [FamInsts and CoAxioms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * CoAxioms and FamInsts are just like DFunIds and ClsInsts * A CoAxiom is a System-FC thing: it can relate any two types * A FamInst is a Haskell source-language thing, corresponding to a type/data family instance declaration. - The FamInst contains a CoAxiom, which is the evidence for the instance - The LHS of the CoAxiom is always of form F ty1 .. tyn where F is a type family -} data FamInst -- See Note [FamInsts and CoAxioms] = FamInst { fi_axiom :: CoAxiom Unbranched -- The new coercion axiom -- introduced by this family -- instance -- INVARIANT: apart from freshening (see below) -- fi_tvs = cab_tvs of the (single) axiom branch -- fi_cvs = cab_cvs ...ditto... -- fi_tys = cab_lhs ...ditto... -- fi_rhs = cab_rhs ...ditto... , fi_flavor :: FamFlavor -- Everything below here is a redundant, -- cached version of the two things above -- except that the TyVars are freshened , fi_fam :: Name -- Family name -- Used for "rough matching"; same idea as for class instances -- See Note [Rough-match field] in InstEnv , fi_tcs :: [Maybe Name] -- Top of type args -- INVARIANT: fi_tcs = roughMatchTcs fi_tys -- Used for "proper matching"; ditto , fi_tvs :: [TyVar] -- Template tyvars for full match , fi_cvs :: [CoVar] -- Template covars for full match -- Like ClsInsts, these variables are always fresh -- See Note [Template tyvars are fresh] in InstEnv , fi_tys :: [Type] -- The LHS type patterns -- May be eta-reduced; see Note [Eta reduction for data families] , fi_rhs :: Type -- the RHS, with its freshened vars } data FamFlavor = SynFamilyInst -- A synonym family | DataFamilyInst TyCon -- A data family, with its representation TyCon {- Note [Eta reduction for data families] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this data family T a b :: * newtype instance T Int a = MkT (IO a) deriving( Monad ) We'd like this to work. From the 'newtype instance' you might think we'd get: newtype TInt a = MkT (IO a) axiom ax1 a :: T Int a ~ TInt a -- The newtype-instance part axiom ax2 a :: TInt a ~ IO a -- The newtype part But now what can we do? We have this problem Given: d :: Monad IO Wanted: d' :: Monad (T Int) = d |> ???? What coercion can we use for the ??? Solution: eta-reduce both axioms, thus: axiom ax1 :: T Int ~ TInt axiom ax2 :: TInt ~ IO Now d' = d |> Monad (sym (ax2 ; ax1)) This eta reduction happens for data instances as well as newtype instances. Here we want to eta-reduce the data family axiom. All this is done in TcInstDcls.tcDataFamInstDecl. See also Note [Newtype eta] in TyCon. Bottom line: For a FamInst with fi_flavour = DataFamilyInst rep_tc, - fi_tvs may be shorter than tyConTyVars of rep_tc - fi_tys may be shorter than tyConArity of the family tycon i.e. LHS is unsaturated - fi_rhs will be (rep_tc fi_tvs) i.e. RHS is un-saturated But when fi_flavour = SynFamilyInst, - fi_tys has the exact arity of the family tycon -} -- Obtain the axiom of a family instance famInstAxiom :: FamInst -> CoAxiom Unbranched famInstAxiom = fi_axiom -- Split the left-hand side of the FamInst famInstSplitLHS :: FamInst -> (TyCon, [Type]) famInstSplitLHS (FamInst { fi_axiom = axiom, fi_tys = lhs }) = (coAxiomTyCon axiom, lhs) -- Get the RHS of the FamInst famInstRHS :: FamInst -> Type famInstRHS = fi_rhs -- Get the family TyCon of the FamInst famInstTyCon :: FamInst -> TyCon famInstTyCon = coAxiomTyCon . famInstAxiom -- Return the representation TyCons introduced by data family instances, if any famInstsRepTyCons :: [FamInst] -> [TyCon] famInstsRepTyCons fis = [tc | FamInst { fi_flavor = DataFamilyInst tc } <- fis] -- Extracts the TyCon for this *data* (or newtype) instance famInstRepTyCon_maybe :: FamInst -> Maybe TyCon famInstRepTyCon_maybe fi = case fi_flavor fi of DataFamilyInst tycon -> Just tycon SynFamilyInst -> Nothing dataFamInstRepTyCon :: FamInst -> TyCon dataFamInstRepTyCon fi = case fi_flavor fi of DataFamilyInst tycon -> tycon SynFamilyInst -> pprPanic "dataFamInstRepTyCon" (ppr fi) {- ************************************************************************ * * Pretty printing * * ************************************************************************ -} instance NamedThing FamInst where getName = coAxiomName . fi_axiom instance Outputable FamInst where ppr = pprFamInst -- Prints the FamInst as a family instance declaration -- NB: FamInstEnv.pprFamInst is used only for internal, debug printing -- See pprTyThing.pprFamInst for printing for the user pprFamInst :: FamInst -> SDoc pprFamInst famInst = hang (pprFamInstHdr famInst) 2 (ifPprDebug debug_stuff) where ax = fi_axiom famInst debug_stuff = vcat [ text "Coercion axiom:" <+> ppr ax , text "Tvs:" <+> ppr (fi_tvs famInst) , text "LHS:" <+> ppr (fi_tys famInst) , text "RHS:" <+> ppr (fi_rhs famInst) ] pprFamInstHdr :: FamInst -> SDoc pprFamInstHdr fi@(FamInst {fi_flavor = flavor}) = pprTyConSort <+> pp_instance <+> pp_head where -- For *associated* types, say "type T Int = blah" -- For *top level* type instances, say "type instance T Int = blah" pp_instance | isTyConAssoc fam_tc = empty | otherwise = text "instance" (fam_tc, etad_lhs_tys) = famInstSplitLHS fi vanilla_pp_head = pprTypeApp fam_tc etad_lhs_tys pp_head | DataFamilyInst rep_tc <- flavor , isAlgTyCon rep_tc , let extra_tvs = dropList etad_lhs_tys (tyConTyVars rep_tc) , not (null extra_tvs) = getPprStyle $ \ sty -> if debugStyle sty then vanilla_pp_head -- With -dppr-debug just show it as-is else pprTypeApp fam_tc (etad_lhs_tys ++ mkTyVarTys extra_tvs) -- Without -dppr-debug, eta-expand -- See Trac #8674 -- (This is probably over the top now that we use this -- only for internal debug printing; PprTyThing.pprFamInst -- is used for user-level printing.) | otherwise = vanilla_pp_head pprTyConSort = case flavor of SynFamilyInst -> text "type" DataFamilyInst tycon | isDataTyCon tycon -> text "data" | isNewTyCon tycon -> text "newtype" | isAbstractTyCon tycon -> text "data" | otherwise -> text "WEIRD" <+> ppr tycon pprFamInsts :: [FamInst] -> SDoc pprFamInsts finsts = vcat (map pprFamInst finsts) {- Note [Lazy axiom match] ~~~~~~~~~~~~~~~~~~~~~~~ It is Vitally Important that mkImportedFamInst is *lazy* in its axiom parameter. The axiom is loaded lazily, via a forkM, in TcIface. Sometime later, mkImportedFamInst is called using that axiom. However, the axiom may itself depend on entities which are not yet loaded as of the time of the mkImportedFamInst. Thus, if mkImportedFamInst eagerly looks at the axiom, a dependency loop spontaneously appears and GHC hangs. The solution is simply for mkImportedFamInst never, ever to look inside of the axiom until everything else is good and ready to do so. We can assume that this readiness has been achieved when some other code pulls on the axiom in the FamInst. Thus, we pattern match on the axiom lazily (in the where clause, not in the parameter list) and we assert the consistency of names there also. -} -- Make a family instance representation from the information found in an -- interface file. In particular, we get the rough match info from the iface -- (instead of computing it here). mkImportedFamInst :: Name -- Name of the family -> [Maybe Name] -- Rough match info -> CoAxiom Unbranched -- Axiom introduced -> FamInst -- Resulting family instance mkImportedFamInst fam mb_tcs axiom = FamInst { fi_fam = fam, fi_tcs = mb_tcs, fi_tvs = tvs, fi_cvs = cvs, fi_tys = tys, fi_rhs = rhs, fi_axiom = axiom, fi_flavor = flavor } where -- See Note [Lazy axiom match] ~(CoAxBranch { cab_lhs = tys , cab_tvs = tvs , cab_cvs = cvs , cab_rhs = rhs }) = coAxiomSingleBranch axiom -- Derive the flavor for an imported FamInst rather disgustingly -- Maybe we should store it in the IfaceFamInst? flavor = case splitTyConApp_maybe rhs of Just (tc, _) | Just ax' <- tyConFamilyCoercion_maybe tc , ax' == axiom -> DataFamilyInst tc _ -> SynFamilyInst {- ************************************************************************ * * FamInstEnv * * ************************************************************************ Note [FamInstEnv] ~~~~~~~~~~~~~~~~~ A FamInstEnv maps a family name to the list of known instances for that family. The same FamInstEnv includes both 'data family' and 'type family' instances. Type families are reduced during type inference, but not data families; the user explains when to use a data family instance by using constructors and pattern matching. Nevertheless it is still useful to have data families in the FamInstEnv: - For finding overlaps and conflicts - For finding the representation type...see FamInstEnv.topNormaliseType and its call site in Simplify - In standalone deriving instance Eq (T [Int]) we need to find the representation type for T [Int] Note [Varying number of patterns for data family axioms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For data families, the number of patterns may vary between instances. For example data family T a b data instance T Int a = T1 a | T2 data instance T Bool [a] = T3 a Then we get a data type for each instance, and an axiom: data TInt a = T1 a | T2 data TBoolList a = T3 a axiom ax7 :: T Int ~ TInt -- Eta-reduced axiom ax8 a :: T Bool [a] ~ TBoolList a These two axioms for T, one with one pattern, one with two; see Note [Eta reduction for data families] Note [FamInstEnv determinism] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We turn FamInstEnvs into a list in some places that don't directly affect the ABI. That happens in family consistency checks and when producing output for `:info`. Unfortunately that nondeterminism is nonlocal and it's hard to tell what it affects without following a chain of functions. It's also easy to accidentally make that nondeterminism affect the ABI. Furthermore the envs should be relatively small, so it should be free to use deterministic maps here. Testing with nofib and validate detected no difference between UniqFM and UniqDFM. See Note [Deterministic UniqFM]. -} type FamInstEnv = UniqDFM FamilyInstEnv -- Maps a family to its instances -- See Note [FamInstEnv] -- See Note [FamInstEnv determinism] type FamInstEnvs = (FamInstEnv, FamInstEnv) -- External package inst-env, Home-package inst-env newtype FamilyInstEnv = FamIE [FamInst] -- The instances for a particular family, in any order instance Outputable FamilyInstEnv where ppr (FamIE fs) = text "FamIE" <+> vcat (map ppr fs) -- INVARIANTS: -- * The fs_tvs are distinct in each FamInst -- of a range value of the map (so we can safely unify them) emptyFamInstEnvs :: (FamInstEnv, FamInstEnv) emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv) emptyFamInstEnv :: FamInstEnv emptyFamInstEnv = emptyUDFM famInstEnvElts :: FamInstEnv -> [FamInst] famInstEnvElts fi = [elt | FamIE elts <- eltsUDFM fi, elt <- elts] -- See Note [FamInstEnv determinism] familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst] familyInstances (pkg_fie, home_fie) fam = get home_fie ++ get pkg_fie where get env = case lookupUDFM env fam of Just (FamIE insts) -> insts Nothing -> [] extendFamInstEnvList :: FamInstEnv -> [FamInst] -> FamInstEnv extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis extendFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv extendFamInstEnv inst_env ins_item@(FamInst {fi_fam = cls_nm}) = addToUDFM_C add inst_env cls_nm (FamIE [ins_item]) where add (FamIE items) _ = FamIE (ins_item:items) deleteFromFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv -- Used only for overriding in GHCi deleteFromFamInstEnv inst_env fam_inst@(FamInst {fi_fam = fam_nm}) = adjustUDFM adjust inst_env fam_nm where adjust :: FamilyInstEnv -> FamilyInstEnv adjust (FamIE items) = FamIE (filterOut (identicalFamInstHead fam_inst) items) identicalFamInstHead :: FamInst -> FamInst -> Bool -- ^ True when the LHSs are identical -- Used for overriding in GHCi identicalFamInstHead (FamInst { fi_axiom = ax1 }) (FamInst { fi_axiom = ax2 }) = coAxiomTyCon ax1 == coAxiomTyCon ax2 && numBranches brs1 == numBranches brs2 && and ((zipWith identical_branch `on` fromBranches) brs1 brs2) where brs1 = coAxiomBranches ax1 brs2 = coAxiomBranches ax2 identical_branch br1 br2 = isJust (tcMatchTys lhs1 lhs2) && isJust (tcMatchTys lhs2 lhs1) where lhs1 = coAxBranchLHS br1 lhs2 = coAxBranchLHS br2 {- ************************************************************************ * * Compatibility * * ************************************************************************ Note [Apartness] ~~~~~~~~~~~~~~~~ In dealing with closed type families, we must be able to check that one type will never reduce to another. This check is called /apartness/. The check is always between a target (which may be an arbitrary type) and a pattern. Here is how we do it: apart(target, pattern) = not (unify(flatten(target), pattern)) where flatten (implemented in flattenTys, below) converts all type-family applications into fresh variables. (See Note [Flattening].) Note [Compatibility] ~~~~~~~~~~~~~~~~~~~~ Two patterns are /compatible/ if either of the following conditions hold: 1) The patterns are apart. 2) The patterns unify with a substitution S, and their right hand sides equal under that substitution. For open type families, only compatible instances are allowed. For closed type families, the story is slightly more complicated. Consider the following: type family F a where F Int = Bool F a = Int g :: Show a => a -> F a g x = length (show x) Should that type-check? No. We need to allow for the possibility that 'a' might be Int and therefore 'F a' should be Bool. We can simplify 'F a' to Int only when we can be sure that 'a' is not Int. To achieve this, after finding a possible match within the equations, we have to go back to all previous equations and check that, under the substitution induced by the match, other branches are surely apart. (See Note [Apartness].) This is similar to what happens with class instance selection, when we need to guarantee that there is only a match and no unifiers. The exact algorithm is different here because the the potentially-overlapping group is closed. As another example, consider this: type family G x where G Int = Bool G a = Double type family H y -- no instances Now, we want to simplify (G (H Char)). We can't, because (H Char) might later simplify to be Int. So, (G (H Char)) is stuck, for now. While everything above is quite sound, it isn't as expressive as we'd like. Consider this: type family J a where J Int = Int J a = a Can we simplify (J b) to b? Sure we can. Yes, the first equation matches if b is instantiated with Int, but the RHSs coincide there, so it's all OK. So, the rule is this: when looking up a branch in a closed type family, we find a branch that matches the target, but then we make sure that the target is apart from every previous *incompatible* branch. We don't check the branches that are compatible with the matching branch, because they are either irrelevant (clause 1 of compatible) or benign (clause 2 of compatible). -} -- See Note [Compatibility] compatibleBranches :: CoAxBranch -> CoAxBranch -> Bool compatibleBranches (CoAxBranch { cab_lhs = lhs1, cab_rhs = rhs1 }) (CoAxBranch { cab_lhs = lhs2, cab_rhs = rhs2 }) = case tcUnifyTysFG (const BindMe) lhs1 lhs2 of SurelyApart -> True Unifiable subst | Type.substTyAddInScope subst rhs1 `eqType` Type.substTyAddInScope subst rhs2 -> True _ -> False -- | Result of testing two type family equations for injectiviy. data InjectivityCheckResult = InjectivityAccepted -- ^ Either RHSs are distinct or unification of RHSs leads to unification of -- LHSs | InjectivityUnified CoAxBranch CoAxBranch -- ^ RHSs unify but LHSs don't unify under that substitution. Relevant for -- closed type families where equation after unification might be -- overlpapped (in which case it is OK if they don't unify). Constructor -- stores axioms after unification. -- | Check whether two type family axioms don't violate injectivity annotation. injectiveBranches :: [Bool] -> CoAxBranch -> CoAxBranch -> InjectivityCheckResult injectiveBranches injectivity ax1@(CoAxBranch { cab_lhs = lhs1, cab_rhs = rhs1 }) ax2@(CoAxBranch { cab_lhs = lhs2, cab_rhs = rhs2 }) -- See Note [Verifying injectivity annotation]. This function implements first -- check described there. = let getInjArgs = filterByList injectivity in case tcUnifyTyWithTFs True rhs1 rhs2 of -- True = two-way pre-unification Nothing -> InjectivityAccepted -- RHS are different, so equations are -- injective. Just subst -> -- RHS unify under a substitution let lhs1Subst = Type.substTys subst (getInjArgs lhs1) lhs2Subst = Type.substTys subst (getInjArgs lhs2) -- If LHSs are equal under the substitution used for RHSs then this pair -- of equations does not violate injectivity annotation. If LHSs are not -- equal under that substitution then this pair of equations violates -- injectivity annotation, but for closed type families it still might -- be the case that one LHS after substitution is unreachable. in if eqTypes lhs1Subst lhs2Subst then InjectivityAccepted else InjectivityUnified ( ax1 { cab_lhs = Type.substTys subst lhs1 , cab_rhs = Type.substTy subst rhs1 }) ( ax2 { cab_lhs = Type.substTys subst lhs2 , cab_rhs = Type.substTy subst rhs2 }) -- takes a CoAxiom with unknown branch incompatibilities and computes -- the compatibilities -- See Note [Storing compatibility] in CoAxiom computeAxiomIncomps :: [CoAxBranch] -> [CoAxBranch] computeAxiomIncomps branches = snd (mapAccumL go [] branches) where go :: [CoAxBranch] -> CoAxBranch -> ([CoAxBranch], CoAxBranch) go prev_brs cur_br = (cur_br : prev_brs, new_br) where new_br = cur_br { cab_incomps = mk_incomps prev_brs cur_br } mk_incomps :: [CoAxBranch] -> CoAxBranch -> [CoAxBranch] mk_incomps prev_brs cur_br = filter (not . compatibleBranches cur_br) prev_brs {- ************************************************************************ * * Constructing axioms These functions are here because tidyType / tcUnifyTysFG are not available in CoAxiom Also computeAxiomIncomps is too sophisticated for CoAxiom * * ************************************************************************ Note [Tidy axioms when we build them] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We print out axioms and don't want to print stuff like F k k a b = ... Instead we must tidy those kind variables. See Trac #7524. -} -- all axiom roles are Nominal, as this is only used with type families mkCoAxBranch :: [TyVar] -- original, possibly stale, tyvars -> [CoVar] -- possibly stale covars -> [Type] -- LHS patterns -> Type -- RHS -> [Role] -> SrcSpan -> CoAxBranch mkCoAxBranch tvs cvs lhs rhs roles loc = CoAxBranch { cab_tvs = tvs1 , cab_cvs = cvs1 , cab_lhs = tidyTypes env lhs , cab_roles = roles , cab_rhs = tidyType env rhs , cab_loc = loc , cab_incomps = placeHolderIncomps } where (env1, tvs1) = tidyTyCoVarBndrs emptyTidyEnv tvs (env, cvs1) = tidyTyCoVarBndrs env1 cvs -- See Note [Tidy axioms when we build them] -- all of the following code is here to avoid mutual dependencies with -- Coercion mkBranchedCoAxiom :: Name -> TyCon -> [CoAxBranch] -> CoAxiom Branched mkBranchedCoAxiom ax_name fam_tc branches = CoAxiom { co_ax_unique = nameUnique ax_name , co_ax_name = ax_name , co_ax_tc = fam_tc , co_ax_role = Nominal , co_ax_implicit = False , co_ax_branches = manyBranches (computeAxiomIncomps branches) } mkUnbranchedCoAxiom :: Name -> TyCon -> CoAxBranch -> CoAxiom Unbranched mkUnbranchedCoAxiom ax_name fam_tc branch = CoAxiom { co_ax_unique = nameUnique ax_name , co_ax_name = ax_name , co_ax_tc = fam_tc , co_ax_role = Nominal , co_ax_implicit = False , co_ax_branches = unbranched (branch { cab_incomps = [] }) } mkSingleCoAxiom :: Role -> Name -> [TyVar] -> [CoVar] -> TyCon -> [Type] -> Type -> CoAxiom Unbranched -- Make a single-branch CoAxiom, incluidng making the branch itself -- Used for both type family (Nominal) and data family (Representational) -- axioms, hence passing in the Role mkSingleCoAxiom role ax_name tvs cvs fam_tc lhs_tys rhs_ty = CoAxiom { co_ax_unique = nameUnique ax_name , co_ax_name = ax_name , co_ax_tc = fam_tc , co_ax_role = role , co_ax_implicit = False , co_ax_branches = unbranched (branch { cab_incomps = [] }) } where branch = mkCoAxBranch tvs cvs lhs_tys rhs_ty (map (const Nominal) tvs) (getSrcSpan ax_name) -- | Create a coercion constructor (axiom) suitable for the given -- newtype 'TyCon'. The 'Name' should be that of a new coercion -- 'CoAxiom', the 'TyVar's the arguments expected by the @newtype@ and -- the type the appropriate right hand side of the @newtype@, with -- the free variables a subset of those 'TyVar's. mkNewTypeCoAxiom :: Name -> TyCon -> [TyVar] -> [Role] -> Type -> CoAxiom Unbranched mkNewTypeCoAxiom name tycon tvs roles rhs_ty = CoAxiom { co_ax_unique = nameUnique name , co_ax_name = name , co_ax_implicit = True -- See Note [Implicit axioms] in TyCon , co_ax_role = Representational , co_ax_tc = tycon , co_ax_branches = unbranched (branch { cab_incomps = [] }) } where branch = mkCoAxBranch tvs [] (mkTyVarTys tvs) rhs_ty roles (getSrcSpan name) {- ************************************************************************ * * Looking up a family instance * * ************************************************************************ @lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match. Multiple matches are only possible in case of type families (not data families), and then, it doesn't matter which match we choose (as the instances are guaranteed confluent). We return the matching family instances and the type instance at which it matches. For example, if we lookup 'T [Int]' and have a family instance data instance T [a] = .. desugared to data :R42T a = .. coe :Co:R42T a :: T [a] ~ :R42T a we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'. -} -- when matching a type family application, we get a FamInst, -- and the list of types the axiom should be applied to data FamInstMatch = FamInstMatch { fim_instance :: FamInst , fim_tys :: [Type] , fim_cos :: [Coercion] } -- See Note [Over-saturated matches] instance Outputable FamInstMatch where ppr (FamInstMatch { fim_instance = inst , fim_tys = tys , fim_cos = cos }) = text "match with" <+> parens (ppr inst) <+> ppr tys <+> ppr cos lookupFamInstEnvByTyCon :: FamInstEnvs -> TyCon -> [FamInst] lookupFamInstEnvByTyCon (pkg_ie, home_ie) fam_tc = get pkg_ie ++ get home_ie where get ie = case lookupUDFM ie fam_tc of Nothing -> [] Just (FamIE fis) -> fis lookupFamInstEnv :: FamInstEnvs -> TyCon -> [Type] -- What we are looking for -> [FamInstMatch] -- Successful matches -- Precondition: the tycon is saturated (or over-saturated) lookupFamInstEnv = lookup_fam_inst_env match where match _ _ tpl_tys tys = tcMatchTys tpl_tys tys lookupFamInstEnvConflicts :: FamInstEnvs -> FamInst -- Putative new instance -> [FamInstMatch] -- Conflicting matches (don't look at the fim_tys field) -- E.g. when we are about to add -- f : type instance F [a] = a->a -- we do (lookupFamInstConflicts f [b]) -- to find conflicting matches -- -- Precondition: the tycon is saturated (or over-saturated) lookupFamInstEnvConflicts envs fam_inst@(FamInst { fi_axiom = new_axiom }) = lookup_fam_inst_env my_unify envs fam tys where (fam, tys) = famInstSplitLHS fam_inst -- In example above, fam tys' = F [b] my_unify (FamInst { fi_axiom = old_axiom }) tpl_tvs tpl_tys _ = ASSERT2( tyCoVarsOfTypes tys `disjointVarSet` tpl_tvs, (ppr fam <+> ppr tys) $$ (ppr tpl_tvs <+> ppr tpl_tys) ) -- Unification will break badly if the variables overlap -- They shouldn't because we allocate separate uniques for them if compatibleBranches (coAxiomSingleBranch old_axiom) new_branch then Nothing else Just noSubst -- Note [Family instance overlap conflicts] noSubst = panic "lookupFamInstEnvConflicts noSubst" new_branch = coAxiomSingleBranch new_axiom -------------------------------------------------------------------------------- -- Type family injectivity checking bits -- -------------------------------------------------------------------------------- {- Note [Verifying injectivity annotation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Injectivity means that the RHS of a type family uniquely determines the LHS (see Note [Type inference for type families with injectivity]). User informs about injectivity using an injectivity annotation and it is GHC's task to verify that that annotation is correct wrt. to type family equations. Whenever we see a new equation of a type family we need to make sure that adding this equation to already known equations of a type family does not violate injectivity annotation supplied by the user (see Note [Injectivity annotation]). Of course if the type family has no injectivity annotation then no check is required. But if a type family has injectivity annotation we need to make sure that the following conditions hold: 1. For each pair of *different* equations of a type family, one of the following conditions holds: A: RHSs are different. B1: OPEN TYPE FAMILIES: If the RHSs can be unified under some substitution then it must be possible to unify the LHSs under the same substitution. Example: type family FunnyId a = r | r -> a type instance FunnyId Int = Int type instance FunnyId a = a RHSs of these two equations unify under [ a |-> Int ] substitution. Under this substitution LHSs are equal therefore these equations don't violate injectivity annotation. B2: CLOSED TYPE FAMILIES: If the RHSs can be unified under some substitution then either the LHSs unify under the same substitution or the LHS of the latter equation is overlapped by earlier equations. Example 1: type family SwapIntChar a = r | r -> a where SwapIntChar Int = Char SwapIntChar Char = Int SwapIntChar a = a Say we are checking the last two equations. RHSs unify under [ a |-> Int ] substitution but LHSs don't. So we apply the substitution to LHS of last equation and check whether it is overlapped by any of previous equations. Since it is overlapped by the first equation we conclude that pair of last two equations does not violate injectivity annotation. A special case of B is when RHSs unify with an empty substitution ie. they are identical. If any of the above two conditions holds we conclude that the pair of equations does not violate injectivity annotation. But if we find a pair of equations where neither of the above holds we report that this pair violates injectivity annotation because for a given RHS we don't have a unique LHS. (Note that (B) actually implies (A).) Note that we only take into account these LHS patterns that were declared as injective. 2. If a RHS of a type family equation is a bare type variable then all LHS variables (including implicit kind variables) also have to be bare. In other words, this has to be a sole equation of that type family and it has to cover all possible patterns. So for example this definition will be rejected: type family W1 a = r | r -> a type instance W1 [a] = a If it were accepted we could call `W1 [W1 Int]`, which would reduce to `W1 Int` and then by injectivity we could conclude that `[W1 Int] ~ Int`, which is bogus. 3. If a RHS of a type family equation is a type family application then the type family is rejected as not injective. 4. If a LHS type variable that is declared as injective is not mentioned on injective position in the RHS then the type family is rejected as not injective. "Injective position" means either an argument to a type constructor or argument to a type family on injective position. See also Note [Injective type families] in TyCon -} -- | Check whether an open type family equation can be added to already existing -- instance environment without causing conflicts with supplied injectivity -- annotations. Returns list of conflicting axioms (type instance -- declarations). lookupFamInstEnvInjectivityConflicts :: [Bool] -- injectivity annotation for this type family instance -- INVARIANT: list contains at least one True value -> FamInstEnvs -- all type instances seens so far -> FamInst -- new type instance that we're checking -> [CoAxBranch] -- conflicting instance delcarations lookupFamInstEnvInjectivityConflicts injList (pkg_ie, home_ie) fam_inst@(FamInst { fi_axiom = new_axiom }) -- See Note [Verifying injectivity annotation]. This function implements -- check (1.B1) for open type families described there. = lookup_inj_fam_conflicts home_ie ++ lookup_inj_fam_conflicts pkg_ie where fam = famInstTyCon fam_inst new_branch = coAxiomSingleBranch new_axiom -- filtering function used by `lookup_inj_fam_conflicts` to check whether -- a pair of equations conflicts with the injectivity annotation. isInjConflict (FamInst { fi_axiom = old_axiom }) | InjectivityAccepted <- injectiveBranches injList (coAxiomSingleBranch old_axiom) new_branch = False -- no conflict | otherwise = True lookup_inj_fam_conflicts ie | isOpenFamilyTyCon fam, Just (FamIE insts) <- lookupUDFM ie fam = map (coAxiomSingleBranch . fi_axiom) $ filter isInjConflict insts | otherwise = [] -------------------------------------------------------------------------------- -- Type family overlap checking bits -- -------------------------------------------------------------------------------- {- Note [Family instance overlap conflicts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - In the case of data family instances, any overlap is fundamentally a conflict (as these instances imply injective type mappings). - In the case of type family instances, overlap is admitted as long as the right-hand sides of the overlapping rules coincide under the overlap substitution. eg type instance F a Int = a type instance F Int b = b These two overlap on (F Int Int) but then both RHSs are Int, so all is well. We require that they are syntactically equal; anything else would be difficult to test for at this stage. -} ------------------------------------------------------------ -- Might be a one-way match or a unifier type MatchFun = FamInst -- The FamInst template -> TyVarSet -> [Type] -- fi_tvs, fi_tys of that FamInst -> [Type] -- Target to match against -> Maybe TCvSubst lookup_fam_inst_env' -- The worker, local to this module :: MatchFun -> FamInstEnv -> TyCon -> [Type] -- What we are looking for -> [FamInstMatch] lookup_fam_inst_env' match_fun ie fam match_tys | isOpenFamilyTyCon fam , Just (FamIE insts) <- lookupUDFM ie fam = find insts -- The common case | otherwise = [] where find [] = [] find (item@(FamInst { fi_tcs = mb_tcs, fi_tvs = tpl_tvs, fi_cvs = tpl_cvs , fi_tys = tpl_tys }) : rest) -- Fast check for no match, uses the "rough match" fields | instanceCantMatch rough_tcs mb_tcs = find rest -- Proper check | Just subst <- match_fun item (mkVarSet tpl_tvs) tpl_tys match_tys1 = (FamInstMatch { fim_instance = item , fim_tys = substTyVars subst tpl_tvs `chkAppend` match_tys2 , fim_cos = ASSERT( all (isJust . lookupCoVar subst) tpl_cvs ) substCoVars subst tpl_cvs }) : find rest -- No match => try next | otherwise = find rest where (rough_tcs, match_tys1, match_tys2) = split_tys tpl_tys -- Precondition: the tycon is saturated (or over-saturated) -- Deal with over-saturation -- See Note [Over-saturated matches] split_tys tpl_tys | isTypeFamilyTyCon fam = pre_rough_split_tys | otherwise = let (match_tys1, match_tys2) = splitAtList tpl_tys match_tys rough_tcs = roughMatchTcs match_tys1 in (rough_tcs, match_tys1, match_tys2) (pre_match_tys1, pre_match_tys2) = splitAt (tyConArity fam) match_tys pre_rough_split_tys = (roughMatchTcs pre_match_tys1, pre_match_tys1, pre_match_tys2) lookup_fam_inst_env -- The worker, local to this module :: MatchFun -> FamInstEnvs -> TyCon -> [Type] -- What we are looking for -> [FamInstMatch] -- Successful matches -- Precondition: the tycon is saturated (or over-saturated) lookup_fam_inst_env match_fun (pkg_ie, home_ie) fam tys = lookup_fam_inst_env' match_fun home_ie fam tys ++ lookup_fam_inst_env' match_fun pkg_ie fam tys {- Note [Over-saturated matches] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's ok to look up an over-saturated type constructor. E.g. type family F a :: * -> * type instance F (a,b) = Either (a->b) The type instance gives rise to a newtype TyCon (at a higher kind which you can't do in Haskell!): newtype FPair a b = FP (Either (a->b)) Then looking up (F (Int,Bool) Char) will return a FamInstMatch (FPair, [Int,Bool,Char]) The "extra" type argument [Char] just stays on the end. We handle data families and type families separately here: * For type families, all instances of a type family must have the same arity, so we can precompute the split between the match_tys and the overflow tys. This is done in pre_rough_split_tys. * For data family instances, though, we need to re-split for each instance, because the breakdown might be different for each instance. Why? Because of eta reduction; see Note [Eta reduction for data families]. -} -- checks if one LHS is dominated by a list of other branches -- in other words, if an application would match the first LHS, it is guaranteed -- to match at least one of the others. The RHSs are ignored. -- This algorithm is conservative: -- True -> the LHS is definitely covered by the others -- False -> no information -- It is currently (Oct 2012) used only for generating errors for -- inaccessible branches. If these errors go unreported, no harm done. -- This is defined here to avoid a dependency from CoAxiom to Unify isDominatedBy :: CoAxBranch -> [CoAxBranch] -> Bool isDominatedBy branch branches = or $ map match branches where lhs = coAxBranchLHS branch match (CoAxBranch { cab_lhs = tys }) = isJust $ tcMatchTys tys lhs {- ************************************************************************ * * Choosing an axiom application * * ************************************************************************ The lookupFamInstEnv function does a nice job for *open* type families, but we also need to handle closed ones when normalising a type: -} reduceTyFamApp_maybe :: FamInstEnvs -> Role -- Desired role of result coercion -> TyCon -> [Type] -> Maybe (Coercion, Type) -- Attempt to do a *one-step* reduction of a type-family application -- but *not* newtypes -- Works on type-synonym families always; data-families only if -- the role we seek is representational -- It does *not* normlise the type arguments first, so this may not -- go as far as you want. If you want normalised type arguments, -- use normaliseTcArgs first. -- -- The TyCon can be oversaturated. -- Works on both open and closed families -- -- Always returns a *homogeneous* coercion -- type family reductions are always -- homogeneous reduceTyFamApp_maybe envs role tc tys | Phantom <- role = Nothing | case role of Representational -> isOpenFamilyTyCon tc _ -> isOpenTypeFamilyTyCon tc -- If we seek a representational coercion -- (e.g. the call in topNormaliseType_maybe) then we can -- unwrap data families as well as type-synonym families; -- otherwise only type-synonym families , FamInstMatch { fim_instance = FamInst { fi_axiom = ax } , fim_tys = inst_tys , fim_cos = inst_cos } : _ <- lookupFamInstEnv envs tc tys -- NB: Allow multiple matches because of compatible overlap = let co = mkUnbranchedAxInstCo role ax inst_tys inst_cos ty = pSnd (coercionKind co) in Just (co, ty) | Just ax <- isClosedSynFamilyTyConWithAxiom_maybe tc , Just (ind, inst_tys, inst_cos) <- chooseBranch ax tys = let co = mkAxInstCo role ax ind inst_tys inst_cos ty = pSnd (coercionKind co) in Just (co, ty) | Just ax <- isBuiltInSynFamTyCon_maybe tc , Just (coax,ts,ty) <- sfMatchFam ax tys = let co = mkAxiomRuleCo coax (zipWith mkReflCo (coaxrAsmpRoles coax) ts) in Just (co, ty) | otherwise = Nothing -- The axiom can be oversaturated. (Closed families only.) chooseBranch :: CoAxiom Branched -> [Type] -> Maybe (BranchIndex, [Type], [Coercion]) -- found match, with args chooseBranch axiom tys = do { let num_pats = coAxiomNumPats axiom (target_tys, extra_tys) = splitAt num_pats tys branches = coAxiomBranches axiom ; (ind, inst_tys, inst_cos) <- findBranch (fromBranches branches) target_tys ; return ( ind, inst_tys `chkAppend` extra_tys, inst_cos ) } -- The axiom must *not* be oversaturated findBranch :: [CoAxBranch] -- branches to check -> [Type] -- target types -> Maybe (BranchIndex, [Type], [Coercion]) -- coercions relate requested types to returned axiom LHS at role N findBranch branches target_tys = go 0 branches where go ind (branch@(CoAxBranch { cab_tvs = tpl_tvs, cab_cvs = tpl_cvs , cab_lhs = tpl_lhs , cab_incomps = incomps }) : rest) = let in_scope = mkInScopeSet (unionVarSets $ map (tyCoVarsOfTypes . coAxBranchLHS) incomps) -- See Note [Flattening] below flattened_target = flattenTys in_scope target_tys in case tcMatchTys tpl_lhs target_tys of Just subst -- matching worked. now, check for apartness. | apartnessCheck flattened_target branch -> -- matching worked & we're apart from all incompatible branches. -- success ASSERT( all (isJust . lookupCoVar subst) tpl_cvs ) Just (ind, substTyVars subst tpl_tvs, substCoVars subst tpl_cvs) -- failure. keep looking _ -> go (ind+1) rest -- fail if no branches left go _ [] = Nothing -- | Do an apartness check, as described in the "Closed Type Families" paper -- (POPL '14). This should be used when determining if an equation -- ('CoAxBranch') of a closed type family can be used to reduce a certain target -- type family application. apartnessCheck :: [Type] -- ^ /flattened/ target arguments. Make sure -- they're flattened! See Note [Flattening]. -- (NB: This "flat" is a different -- "flat" than is used in TcFlatten.) -> CoAxBranch -- ^ the candidate equation we wish to use -- Precondition: this matches the target -> Bool -- ^ True <=> equation can fire apartnessCheck flattened_target (CoAxBranch { cab_incomps = incomps }) = all (isSurelyApart . tcUnifyTysFG (const BindMe) flattened_target . coAxBranchLHS) incomps where isSurelyApart SurelyApart = True isSurelyApart _ = False {- ************************************************************************ * * Looking up a family instance * * ************************************************************************ Note [Normalising types] ~~~~~~~~~~~~~~~~~~~~~~~~ The topNormaliseType function removes all occurrences of type families and newtypes from the top-level structure of a type. normaliseTcApp does the type family lookup and is fairly straightforward. normaliseType is a little more involved. The complication comes from the fact that a type family might be used in the kind of a variable bound in a forall. We wish to remove this type family application, but that means coming up with a fresh variable (with the new kind). Thus, we need a substitution to be built up as we recur through the type. However, an ordinary TCvSubst just won't do: when we hit a type variable whose kind has changed during normalisation, we need both the new type variable *and* the coercion. We could conjure up a new VarEnv with just this property, but a usable substitution environment already exists: LiftingContexts from the liftCoSubst family of functions, defined in Coercion. A LiftingContext maps a type variable to a coercion and a coercion variable to a pair of coercions. Let's ignore coercion variables for now. Because the coercion a type variable maps to contains the destination type (via coercionKind), we don't need to store that destination type separately. Thus, a LiftingContext has what we need: a map from type variables to (Coercion, Type) pairs. We also benefit because we can piggyback on the liftCoSubstVarBndr function to deal with binders. However, I had to modify that function to work with this application. Thus, we now have liftCoSubstVarBndrCallback, which takes a function used to process the kind of the binder. We don't wish to lift the kind, but instead normalise it. So, we pass in a callback function that processes the kind of the binder. After that brilliant explanation of all this, I'm sure you've forgotten the dangling reference to coercion variables. What do we do with those? Nothing at all. The point of normalising types is to remove type family applications, but there's no sense in removing these from coercions. We would just get back a new coercion witnessing the equality between the same types as the original coercion. Because coercions are irrelevant anyway, there is no point in doing this. So, whenever we encounter a coercion, we just say that it won't change. That's what the CoercionTy case is doing within normalise_type. -} topNormaliseType :: FamInstEnvs -> Type -> Type topNormaliseType env ty = case topNormaliseType_maybe env ty of Just (_co, ty') -> ty' Nothing -> ty topNormaliseType_maybe :: FamInstEnvs -> Type -> Maybe (Coercion, Type) -- ^ Get rid of *outermost* (or toplevel) -- * type function redex -- * data family redex -- * newtypes -- returning an appropriate Representational coercion. Specifically, if -- topNormaliseType_maybe env ty = Maybe (co, ty') -- then -- (a) co :: ty ~R ty' -- (b) ty' is not a newtype, and is not a type-family or data-family redex -- -- However, ty' can be something like (Maybe (F ty)), where -- (F ty) is a redex. -- -- Its a bit like Type.repType, but handles type families too topNormaliseType_maybe env ty = topNormaliseTypeX stepper mkTransCo ty where stepper = unwrapNewTypeStepper `composeSteppers` tyFamStepper tyFamStepper rec_nts tc tys -- Try to step a type/data familiy = let (args_co, ntys) = normaliseTcArgs env Representational tc tys in -- NB: It's OK to use normaliseTcArgs here instead of -- normalise_tc_args (which takes the LiftingContext described -- in Note [Normalising types]) because the reduceTyFamApp below -- works only at top level. We'll never recur in this function -- after reducing the kind of a bound tyvar. case reduceTyFamApp_maybe env Representational tc ntys of Just (co, rhs) -> NS_Step rec_nts rhs (args_co `mkTransCo` co) _ -> NS_Done --------------- normaliseTcApp :: FamInstEnvs -> Role -> TyCon -> [Type] -> (Coercion, Type) -- See comments on normaliseType for the arguments of this function normaliseTcApp env role tc tys = initNormM env role (tyCoVarsOfTypes tys) $ normalise_tc_app tc tys -- See Note [Normalising types] about the LiftingContext normalise_tc_app :: TyCon -> [Type] -> NormM (Coercion, Type) normalise_tc_app tc tys = do { (args_co, ntys) <- normalise_tc_args tc tys ; case expandSynTyCon_maybe tc ntys of { Just (tenv, rhs, ntys') -> do { (co2, ninst_rhs) <- normalise_type (substTy (mkTvSubstPrs tenv) rhs) ; return $ if isReflCo co2 then (args_co, mkTyConApp tc ntys) else (args_co `mkTransCo` co2, mkAppTys ninst_rhs ntys') } ; Nothing -> do { env <- getEnv ; role <- getRole ; case reduceTyFamApp_maybe env role tc ntys of Just (first_co, ty') -> do { (rest_co,nty) <- normalise_type ty' ; return ( args_co `mkTransCo` first_co `mkTransCo` rest_co , nty ) } _ -> -- No unique matching family instance exists; -- we do not do anything return (args_co, mkTyConApp tc ntys) }}} --------------- -- | Normalise arguments to a tycon normaliseTcArgs :: FamInstEnvs -- ^ env't with family instances -> Role -- ^ desired role of output coercion -> TyCon -- ^ tc -> [Type] -- ^ tys -> (Coercion, [Type]) -- ^ co :: tc tys ~ tc new_tys normaliseTcArgs env role tc tys = initNormM env role (tyCoVarsOfTypes tys) $ normalise_tc_args tc tys normalise_tc_args :: TyCon -> [Type] -- tc tys -> NormM (Coercion, [Type]) -- (co, new_tys), where -- co :: tc tys ~ tc new_tys normalise_tc_args tc tys = do { role <- getRole ; (cois, ntys) <- zipWithAndUnzipM normalise_type_role tys (tyConRolesX role tc) ; return (mkTyConAppCo role tc cois, ntys) } where normalise_type_role ty r = withRole r $ normalise_type ty --------------- normaliseType :: FamInstEnvs -> Role -- desired role of coercion -> Type -> (Coercion, Type) normaliseType env role ty = initNormM env role (tyCoVarsOfType ty) $ normalise_type ty normalise_type :: Type -- old type -> NormM (Coercion, Type) -- (coercion,new type), where -- co :: old-type ~ new_type -- Normalise the input type, by eliminating *all* type-function redexes -- but *not* newtypes (which are visible to the programmer) -- Returns with Refl if nothing happens -- Does nothing to newtypes -- The returned coercion *must* be *homogeneous* -- See Note [Normalising types] -- Try to not to disturb type synonyms if possible normalise_type = go where go (TyConApp tc tys) = normalise_tc_app tc tys go ty@(LitTy {}) = do { r <- getRole ; return (mkReflCo r ty, ty) } go (AppTy ty1 ty2) = do { (co, nty1) <- go ty1 ; (arg, nty2) <- withRole Nominal $ go ty2 ; return (mkAppCo co arg, mkAppTy nty1 nty2) } go (FunTy ty1 ty2) = do { (co1, nty1) <- go ty1 ; (co2, nty2) <- go ty2 ; r <- getRole ; return (mkFunCo r co1 co2, mkFunTy nty1 nty2) } go (ForAllTy (TvBndr tyvar vis) ty) = do { (lc', tv', h, ki') <- normalise_tyvar_bndr tyvar ; (co, nty) <- withLC lc' $ normalise_type ty ; let tv2 = setTyVarKind tv' ki' ; return (mkForAllCo tv' h co, ForAllTy (TvBndr tv2 vis) nty) } go (TyVarTy tv) = normalise_tyvar tv go (CastTy ty co) = do { (nco, nty) <- go ty ; lc <- getLC ; let co' = substRightCo lc co ; return (castCoercionKind nco co co', mkCastTy nty co') } go (CoercionTy co) = do { lc <- getLC ; r <- getRole ; let right_co = substRightCo lc co ; return ( mkProofIrrelCo r (liftCoSubst Nominal lc (coercionType co)) co right_co , mkCoercionTy right_co ) } normalise_tyvar :: TyVar -> NormM (Coercion, Type) normalise_tyvar tv = ASSERT( isTyVar tv ) do { lc <- getLC ; r <- getRole ; return $ case liftCoSubstTyVar lc r tv of Just co -> (co, pSnd $ coercionKind co) Nothing -> (mkReflCo r ty, ty) } where ty = mkTyVarTy tv normalise_tyvar_bndr :: TyVar -> NormM (LiftingContext, TyVar, Coercion, Kind) normalise_tyvar_bndr tv = do { lc1 <- getLC ; env <- getEnv ; let callback lc ki = runNormM (normalise_type ki) env lc Nominal ; return $ liftCoSubstVarBndrCallback callback lc1 tv } -- | a monad for the normalisation functions, reading 'FamInstEnvs', -- a 'LiftingContext', and a 'Role'. newtype NormM a = NormM { runNormM :: FamInstEnvs -> LiftingContext -> Role -> a } initNormM :: FamInstEnvs -> Role -> TyCoVarSet -- the in-scope variables -> NormM a -> a initNormM env role vars (NormM thing_inside) = thing_inside env lc role where in_scope = mkInScopeSet vars lc = emptyLiftingContext in_scope getRole :: NormM Role getRole = NormM (\ _ _ r -> r) getLC :: NormM LiftingContext getLC = NormM (\ _ lc _ -> lc) getEnv :: NormM FamInstEnvs getEnv = NormM (\ env _ _ -> env) withRole :: Role -> NormM a -> NormM a withRole r thing = NormM $ \ envs lc _old_r -> runNormM thing envs lc r withLC :: LiftingContext -> NormM a -> NormM a withLC lc thing = NormM $ \ envs _old_lc r -> runNormM thing envs lc r instance Monad NormM where ma >>= fmb = NormM $ \env lc r -> let a = runNormM ma env lc r in runNormM (fmb a) env lc r instance Functor NormM where fmap = liftM instance Applicative NormM where pure x = NormM $ \ _ _ _ -> x (<*>) = ap {- ************************************************************************ * * Flattening * * ************************************************************************ Note [Flattening] ~~~~~~~~~~~~~~~~~ As described in "Closed type families with overlapping equations" http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf we need to flatten core types before unifying them, when checking for "surely-apart" against earlier equations of a closed type family. Flattening means replacing all top-level uses of type functions with fresh variables, *taking care to preserve sharing*. That is, the type (Either (F a b) (F a b)) should flatten to (Either c c), never (Either c d). Here is a nice example of why it's all necessary: type family F a b where F Int Bool = Char F a b = Double type family G a -- open, no instances How do we reduce (F (G Float) (G Float))? The first equation clearly doesn't match, while the second equation does. But, before reducing, we must make sure that the target can never become (F Int Bool). Well, no matter what G Float becomes, it certainly won't become *both* Int and Bool, so indeed we're safe reducing (F (G Float) (G Float)) to Double. This is necessary not only to get more reductions (which we might be willing to give up on), but for substitutivity. If we have (F x x), we can see that (F x x) can reduce to Double. So, it had better be the case that (F blah blah) can reduce to Double, no matter what (blah) is! Flattening as done below ensures this. flattenTys is defined here because of module dependencies. -} data FlattenEnv = FlattenEnv { fe_type_map :: TypeMap TyVar , fe_subst :: TCvSubst } emptyFlattenEnv :: InScopeSet -> FlattenEnv emptyFlattenEnv in_scope = FlattenEnv { fe_type_map = emptyTypeMap , fe_subst = mkEmptyTCvSubst in_scope } -- See Note [Flattening] flattenTys :: InScopeSet -> [Type] -> [Type] flattenTys in_scope tys = snd $ coreFlattenTys env tys where -- when we hit a type function, we replace it with a fresh variable -- but, we need to make sure that this fresh variable isn't mentioned -- *anywhere* in the types we're flattening, even if locally-bound in -- a forall. That way, we can ensure consistency both within and outside -- of that forall. all_in_scope = in_scope `extendInScopeSetSet` allTyVarsInTys tys env = emptyFlattenEnv all_in_scope coreFlattenTys :: FlattenEnv -> [Type] -> (FlattenEnv, [Type]) coreFlattenTys = go [] where go rtys env [] = (env, reverse rtys) go rtys env (ty : tys) = let (env', ty') = coreFlattenTy env ty in go (ty' : rtys) env' tys coreFlattenTy :: FlattenEnv -> Type -> (FlattenEnv, Type) coreFlattenTy = go where go env ty | Just ty' <- coreView ty = go env ty' go env (TyVarTy tv) = (env, substTyVar (fe_subst env) tv) go env (AppTy ty1 ty2) = let (env1, ty1') = go env ty1 (env2, ty2') = go env1 ty2 in (env2, AppTy ty1' ty2') go env (TyConApp tc tys) -- NB: Don't just check if isFamilyTyCon: this catches *data* families, -- which are generative and thus can be preserved during flattening | not (isGenerativeTyCon tc Nominal) = let (env', tv) = coreFlattenTyFamApp env tc tys in (env', mkTyVarTy tv) | otherwise = let (env', tys') = coreFlattenTys env tys in (env', mkTyConApp tc tys') go env (FunTy ty1 ty2) = let (env1, ty1') = go env ty1 (env2, ty2') = go env1 ty2 in (env2, mkFunTy ty1' ty2') go env (ForAllTy (TvBndr tv vis) ty) = let (env1, tv') = coreFlattenVarBndr env tv (env2, ty') = go env1 ty in (env2, ForAllTy (TvBndr tv' vis) ty') go env ty@(LitTy {}) = (env, ty) go env (CastTy ty co) = let (env1, ty') = go env ty (env2, co') = coreFlattenCo env1 co in (env2, CastTy ty' co') go env (CoercionTy co) = let (env', co') = coreFlattenCo env co in (env', CoercionTy co') -- when flattening, we don't care about the contents of coercions. -- so, just return a fresh variable of the right (flattened) type coreFlattenCo :: FlattenEnv -> Coercion -> (FlattenEnv, Coercion) coreFlattenCo env co = (env2, mkCoVarCo covar) where (env1, kind') = coreFlattenTy env (coercionType co) fresh_name = mkFlattenFreshCoName subst1 = fe_subst env1 in_scope = getTCvInScope subst1 covar = uniqAway in_scope (mkCoVar fresh_name kind') env2 = env1 { fe_subst = subst1 `extendTCvInScope` covar } coreFlattenVarBndr :: FlattenEnv -> TyVar -> (FlattenEnv, TyVar) coreFlattenVarBndr env tv | kind' `eqType` kind = ( env { fe_subst = extendTvSubst old_subst tv (mkTyVarTy tv) } -- override any previous binding for tv , tv) | otherwise = let new_tv = uniqAway (getTCvInScope old_subst) (setTyVarKind tv kind') new_subst = extendTvSubstWithClone old_subst tv new_tv in (env' { fe_subst = new_subst }, new_tv) where kind = tyVarKind tv (env', kind') = coreFlattenTy env kind old_subst = fe_subst env coreFlattenTyFamApp :: FlattenEnv -> TyCon -- type family tycon -> [Type] -- args -> (FlattenEnv, TyVar) coreFlattenTyFamApp env fam_tc fam_args = case lookupTypeMap type_map fam_ty of Just tv -> (env, tv) -- we need fresh variables here, but this is called far from -- any good source of uniques. So, we just use the fam_tc's unique -- and trust uniqAway to avoid clashes. Recall that the in_scope set -- contains *all* tyvars, even locally bound ones elsewhere in the -- overall type, so this really is fresh. Nothing -> let tyvar_name = mkFlattenFreshTyName fam_tc tv = uniqAway (getTCvInScope subst) $ mkTyVar tyvar_name (typeKind fam_ty) env' = env { fe_type_map = extendTypeMap type_map fam_ty tv , fe_subst = extendTCvInScope subst tv } in (env', tv) where fam_ty = mkTyConApp fam_tc fam_args FlattenEnv { fe_type_map = type_map , fe_subst = subst } = env -- | Get the set of all type variables mentioned anywhere in the list -- of types. These variables are not necessarily free. allTyVarsInTys :: [Type] -> VarSet allTyVarsInTys [] = emptyVarSet allTyVarsInTys (ty:tys) = allTyVarsInTy ty `unionVarSet` allTyVarsInTys tys -- | Get the set of all type variables mentioned anywhere in a type. allTyVarsInTy :: Type -> VarSet allTyVarsInTy = go where go (TyVarTy tv) = unitVarSet tv go (TyConApp _ tys) = allTyVarsInTys tys go (AppTy ty1 ty2) = (go ty1) `unionVarSet` (go ty2) go (FunTy ty1 ty2) = (go ty1) `unionVarSet` (go ty2) go (ForAllTy (TvBndr tv _) ty) = unitVarSet tv `unionVarSet` go (tyVarKind tv) `unionVarSet` go ty -- Don't remove the tv from the set! go (LitTy {}) = emptyVarSet go (CastTy ty co) = go ty `unionVarSet` go_co co go (CoercionTy co) = go_co co go_co (Refl _ ty) = go ty go_co (TyConAppCo _ _ args) = go_cos args go_co (AppCo co arg) = go_co co `unionVarSet` go_co arg go_co (ForAllCo tv h co) = unionVarSets [unitVarSet tv, go_co co, go_co h] go_co (CoVarCo cv) = unitVarSet cv go_co (AxiomInstCo _ _ cos) = go_cos cos go_co (UnivCo p _ t1 t2) = go_prov p `unionVarSet` go t1 `unionVarSet` go t2 go_co (SymCo co) = go_co co go_co (TransCo c1 c2) = go_co c1 `unionVarSet` go_co c2 go_co (NthCo _ co) = go_co co go_co (LRCo _ co) = go_co co go_co (InstCo co arg) = go_co co `unionVarSet` go_co arg go_co (CoherenceCo c1 c2) = go_co c1 `unionVarSet` go_co c2 go_co (KindCo co) = go_co co go_co (SubCo co) = go_co co go_co (AxiomRuleCo _ cs) = go_cos cs go_cos = foldr (unionVarSet . go_co) emptyVarSet go_prov UnsafeCoerceProv = emptyVarSet go_prov (PhantomProv co) = go_co co go_prov (ProofIrrelProv co) = go_co co go_prov (PluginProv _) = emptyVarSet go_prov (HoleProv _) = emptyVarSet mkFlattenFreshTyName :: Uniquable a => a -> Name mkFlattenFreshTyName unq = mkSysTvName (getUnique unq) (fsLit "flt") mkFlattenFreshCoName :: Name mkFlattenFreshCoName = mkSystemVarName (deriveUnique eqPrimTyConKey 71) (fsLit "flc")
olsner/ghc
compiler/types/FamInstEnv.hs
bsd-3-clause
65,687
6
21
18,614
9,373
5,043
4,330
-1
-1
module Test15 where f n = n * f (n - 1) g = f 13
kmate/HaRe
old/testing/refacFunDef/Test15_TokOut.hs
bsd-3-clause
51
0
8
18
34
18
16
3
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -Wno-missing-signatures #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Conc.Windows -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Windows I/O manager -- ----------------------------------------------------------------------------- -- #not-home module GHC.Conc.Windows ( ensureIOManagerIsRunning -- * Waiting , threadDelay , registerDelay -- * Miscellaneous , asyncRead , asyncWrite , asyncDoProc , asyncReadBA , asyncWriteBA , ConsoleEvent(..) , win32ConsoleHandler , toWin32ConsoleEvent ) where import Data.Bits (shiftR) import GHC.Base import GHC.Conc.Sync import GHC.Enum (Enum) import GHC.IO (unsafePerformIO) import GHC.IORef import GHC.MVar import GHC.Num (Num(..)) import GHC.Ptr import GHC.Read (Read) import GHC.Real (div, fromIntegral) import GHC.Show (Show) import GHC.Word (Word32, Word64) import GHC.Windows #ifdef mingw32_HOST_OS # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif -- ---------------------------------------------------------------------------- -- Thread waiting -- Note: threadWaitRead and threadWaitWrite aren't really functional -- on Win32, but left in there because lib code (still) uses them (the manner -- in which they're used doesn't cause problems on a Win32 platform though.) asyncRead :: Int -> Int -> Int -> Ptr a -> IO (Int, Int) asyncRead (I# fd) (I# isSock) (I# len) (Ptr buf) = IO $ \s -> case asyncRead# fd isSock len buf s of (# s', len#, err# #) -> (# s', (I# len#, I# err#) #) asyncWrite :: Int -> Int -> Int -> Ptr a -> IO (Int, Int) asyncWrite (I# fd) (I# isSock) (I# len) (Ptr buf) = IO $ \s -> case asyncWrite# fd isSock len buf s of (# s', len#, err# #) -> (# s', (I# len#, I# err#) #) asyncDoProc :: FunPtr (Ptr a -> IO Int) -> Ptr a -> IO Int asyncDoProc (FunPtr proc) (Ptr param) = -- the 'length' value is ignored; simplifies implementation of -- the async*# primops to have them all return the same result. IO $ \s -> case asyncDoProc# proc param s of (# s', _len#, err# #) -> (# s', I# err# #) -- to aid the use of these primops by the IO Handle implementation, -- provide the following convenience funs: -- this better be a pinned byte array! asyncReadBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int) asyncReadBA fd isSock len off bufB = asyncRead fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off) asyncWriteBA :: Int -> Int -> Int -> Int -> MutableByteArray# RealWorld -> IO (Int,Int) asyncWriteBA fd isSock len off bufB = asyncWrite fd isSock len ((Ptr (byteArrayContents# (unsafeCoerce# bufB))) `plusPtr` off) -- ---------------------------------------------------------------------------- -- Threaded RTS implementation of threadDelay -- | Suspends the current thread for a given number of microseconds -- (GHC only). -- -- There is no guarantee that the thread will be rescheduled promptly -- when the delay has expired, but the thread will never continue to -- run /earlier/ than specified. -- threadDelay :: Int -> IO () threadDelay time | threaded = waitForDelayEvent time | otherwise = IO $ \s -> case time of { I# time# -> case delay# time# s of { s' -> (# s', () #) }} -- | Set the value of returned TVar to True after a given number of -- microseconds. The caveats associated with threadDelay also apply. -- registerDelay :: Int -> IO (TVar Bool) registerDelay usecs | threaded = waitForDelayEventSTM usecs | otherwise = errorWithoutStackTrace "registerDelay: requires -threaded" foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool waitForDelayEvent :: Int -> IO () waitForDelayEvent usecs = do m <- newEmptyMVar target <- calculateTarget usecs atomicModifyIORef pendingDelays (\xs -> (Delay target m : xs, ())) prodServiceThread takeMVar m -- Delays for use in STM waitForDelayEventSTM :: Int -> IO (TVar Bool) waitForDelayEventSTM usecs = do t <- atomically $ newTVar False target <- calculateTarget usecs atomicModifyIORef pendingDelays (\xs -> (DelaySTM target t : xs, ())) prodServiceThread return t calculateTarget :: Int -> IO USecs calculateTarget usecs = do now <- getMonotonicUSec return $ now + (fromIntegral usecs) data DelayReq = Delay {-# UNPACK #-} !USecs {-# UNPACK #-} !(MVar ()) | DelaySTM {-# UNPACK #-} !USecs {-# UNPACK #-} !(TVar Bool) {-# NOINLINE pendingDelays #-} pendingDelays :: IORef [DelayReq] pendingDelays = unsafePerformIO $ do m <- newIORef [] sharedCAF m getOrSetGHCConcWindowsPendingDelaysStore foreign import ccall unsafe "getOrSetGHCConcWindowsPendingDelaysStore" getOrSetGHCConcWindowsPendingDelaysStore :: Ptr a -> IO (Ptr a) {-# NOINLINE ioManagerThread #-} ioManagerThread :: MVar (Maybe ThreadId) ioManagerThread = unsafePerformIO $ do m <- newMVar Nothing sharedCAF m getOrSetGHCConcWindowsIOManagerThreadStore foreign import ccall unsafe "getOrSetGHCConcWindowsIOManagerThreadStore" getOrSetGHCConcWindowsIOManagerThreadStore :: Ptr a -> IO (Ptr a) ensureIOManagerIsRunning :: IO () ensureIOManagerIsRunning | threaded = startIOManagerThread | otherwise = return () startIOManagerThread :: IO () startIOManagerThread = do modifyMVar_ ioManagerThread $ \old -> do let create = do t <- forkIO ioManager; return (Just t) case old of Nothing -> create Just t -> do s <- threadStatus t case s of ThreadFinished -> create ThreadDied -> create _other -> return (Just t) insertDelay :: DelayReq -> [DelayReq] -> [DelayReq] insertDelay d [] = [d] insertDelay d1 ds@(d2 : rest) | delayTime d1 <= delayTime d2 = d1 : ds | otherwise = d2 : insertDelay d1 rest delayTime :: DelayReq -> USecs delayTime (Delay t _) = t delayTime (DelaySTM t _) = t type USecs = Word64 type NSecs = Word64 foreign import ccall unsafe "getMonotonicNSec" getMonotonicNSec :: IO NSecs getMonotonicUSec :: IO USecs getMonotonicUSec = fmap (`div` 1000) getMonotonicNSec {-# NOINLINE prodding #-} prodding :: IORef Bool prodding = unsafePerformIO $ do r <- newIORef False sharedCAF r getOrSetGHCConcWindowsProddingStore foreign import ccall unsafe "getOrSetGHCConcWindowsProddingStore" getOrSetGHCConcWindowsProddingStore :: Ptr a -> IO (Ptr a) prodServiceThread :: IO () prodServiceThread = do -- NB. use atomicModifyIORef here, otherwise there are race -- conditions in which prodding is left at True but the server is -- blocked in select(). was_set <- atomicModifyIORef prodding $ \b -> (True,b) when (not was_set) wakeupIOManager -- ---------------------------------------------------------------------------- -- Windows IO manager thread ioManager :: IO () ioManager = do wakeup <- c_getIOManagerEvent service_loop wakeup [] service_loop :: HANDLE -- read end of pipe -> [DelayReq] -- current delay requests -> IO () service_loop wakeup old_delays = do -- pick up new delay requests new_delays <- atomicModifyIORef pendingDelays (\a -> ([],a)) let delays = foldr insertDelay old_delays new_delays now <- getMonotonicUSec (delays', timeout) <- getDelay now delays r <- c_WaitForSingleObject wakeup timeout case r of 0xffffffff -> do throwGetLastError "service_loop" 0 -> do r2 <- c_readIOManagerEvent exit <- case r2 of _ | r2 == io_MANAGER_WAKEUP -> return False _ | r2 == io_MANAGER_DIE -> return True 0 -> return False -- spurious wakeup _ -> do start_console_handler (r2 `shiftR` 1); return False when (not exit) $ service_cont wakeup delays' _other -> service_cont wakeup delays' -- probably timeout service_cont :: HANDLE -> [DelayReq] -> IO () service_cont wakeup delays = do r <- atomicModifyIORef prodding (\_ -> (False,False)) r `seq` return () -- avoid space leak service_loop wakeup delays -- must agree with rts/win32/ThrIOManager.c io_MANAGER_WAKEUP, io_MANAGER_DIE :: Word32 io_MANAGER_WAKEUP = 0xffffffff io_MANAGER_DIE = 0xfffffffe data ConsoleEvent = ControlC | Break | Close -- these are sent to Services only. | Logoff | Shutdown deriving (Eq, Ord, Enum, Show, Read) start_console_handler :: Word32 -> IO () start_console_handler r = case toWin32ConsoleEvent r of Just x -> withMVar win32ConsoleHandler $ \handler -> do _ <- forkIO (handler x) return () Nothing -> return () toWin32ConsoleEvent :: (Eq a, Num a) => a -> Maybe ConsoleEvent toWin32ConsoleEvent ev = case ev of 0 {- CTRL_C_EVENT-} -> Just ControlC 1 {- CTRL_BREAK_EVENT-} -> Just Break 2 {- CTRL_CLOSE_EVENT-} -> Just Close 5 {- CTRL_LOGOFF_EVENT-} -> Just Logoff 6 {- CTRL_SHUTDOWN_EVENT-} -> Just Shutdown _ -> Nothing win32ConsoleHandler :: MVar (ConsoleEvent -> IO ()) win32ConsoleHandler = unsafePerformIO (newMVar (errorWithoutStackTrace "win32ConsoleHandler")) wakeupIOManager :: IO () wakeupIOManager = c_sendIOManagerEvent io_MANAGER_WAKEUP -- Walk the queue of pending delays, waking up any that have passed -- and return the smallest delay to wait for. The queue of pending -- delays is kept ordered. getDelay :: USecs -> [DelayReq] -> IO ([DelayReq], DWORD) getDelay _ [] = return ([], iNFINITE) getDelay now all@(d : rest) = case d of Delay time m | now >= time -> do putMVar m () getDelay now rest DelaySTM time t | now >= time -> do atomically $ writeTVar t True getDelay now rest _otherwise -> -- delay is in millisecs for WaitForSingleObject let micro_seconds = delayTime d - now milli_seconds = (micro_seconds + 999) `div` 1000 in return (all, fromIntegral milli_seconds) foreign import ccall unsafe "getIOManagerEvent" -- in the RTS (ThrIOManager.c) c_getIOManagerEvent :: IO HANDLE foreign import ccall unsafe "readIOManagerEvent" -- in the RTS (ThrIOManager.c) c_readIOManagerEvent :: IO Word32 foreign import ccall unsafe "sendIOManagerEvent" -- in the RTS (ThrIOManager.c) c_sendIOManagerEvent :: Word32 -> IO () foreign import WINDOWS_CCONV "WaitForSingleObject" c_WaitForSingleObject :: HANDLE -> DWORD -> IO DWORD
tolysz/prepare-ghcjs
spec-lts8/base-pure/GHC/Conc/Windows.hs
bsd-3-clause
10,948
4
22
2,367
2,742
1,418
1,324
-1
-1
-- This one killed GHC 6.4 because it bogusly attributed -- the CPR property to the constructor T -- Result: a mkWWcpr crash -- Needs -prof -auto-all to show it up module ShouldCompile where newtype T a = T { unT :: a } f = unT test cs = f $ case cs of [] -> T [] (x:xs) -> T $ test cs
urbanslug/ghc
testsuite/tests/stranal/should_compile/newtype.hs
bsd-3-clause
301
0
10
80
76
44
32
6
2
{- Copyright (C) 2015 Martin Linnemann <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.Odt.Generic.Namespaces Copyright : Copyright (C) 2015 Martin Linnemann License : GNU GPL, version 2 or above Maintainer : Martin Linnemann <[email protected]> Stability : alpha Portability : portable A class containing a set of namespace identifiers. Used to convert between typesafe Haskell namespace identifiers and unsafe "real world" namespaces. -} module Text.Pandoc.Readers.Odt.Generic.Namespaces where import qualified Data.Map as M -- type NameSpaceIRI = String -- type NameSpaceIRIs nsID = M.Map nsID NameSpaceIRI -- class (Eq nsID, Ord nsID) => NameSpaceID nsID where -- | Given a IRI, possibly update the map and return the id of the namespace. -- May fail if the namespace is unknown and the application does not -- allow unknown namespaces. getNamespaceID :: NameSpaceIRI -> NameSpaceIRIs nsID -> Maybe (NameSpaceIRIs nsID, nsID) -- | Given a namespace id, lookup its IRI. May be overriden for performance. getIRI :: nsID -> NameSpaceIRIs nsID -> Maybe NameSpaceIRI -- | The root element of an XML document has a namespace, too, and the -- "XML.Light-parser" is eager to remove the corresponding namespace -- attribute. -- As a result, at least this root namespace must be provided. getInitialIRImap :: NameSpaceIRIs nsID getIRI = M.lookup getInitialIRImap = M.empty
gbataille/pandoc
src/Text/Pandoc/Readers/Odt/Generic/Namespaces.hs
gpl-2.0
2,270
0
11
517
144
86
58
14
0
module Language.Haskell.Session.Hint.Util where import qualified Data.Char as Char type Expr = String -- @safeBndFor expr@ generates a name @e@ such that it does not -- occur free in @expr@ and, thus, it is safe to write something -- like @e = expr@ (otherwise, it will get accidentally bound). -- This ought to do the trick: observe that @safeBndFor expr@ -- contains more digits than @expr@ and, thus, cannot occur inside -- @expr@. safeBndFor :: Expr -> String safeBndFor expr = "e_1" ++ filter Char.isDigit expr
pmlodawski/ghc-session
src/Language/Haskell/Session/Hint/Util.hs
mit
520
0
7
89
57
37
20
5
1
-- Hurl -- For doing HTTP stuff. module Hurl ( request , requestUrl , requestMethod , requestHeaders , requestBody , constructRequest , doRequest , responseCode , responseReason , responseHeaders , responseBody {- url , protocol , user , host , port , path , query , hash , constructUrl -} ) where -- For using Maybe. import Data.Maybe -- For uppercasing. import Data.Char -- For either stuff. import Data.Either -- For splitting lists/strings. import Data.List.Split -- The Network stuff. import Network.HTTP -- import Network.HTTP.Base -- import Network.HTTP.Headers import Network.URI -- | All the options that go into an HTTP Request. data RequestOptions = RequestOptions { requestUrl :: String , requestMethod :: String , requestHeaders :: [String] , requestBody :: String } deriving (Show) -- | @request@ returns a 'RequestOptions' record with default values. request :: RequestOptions request = RequestOptions { requestUrl = "" , requestMethod = "" , requestHeaders = [] , requestBody = "" } -- | @constructRequest@ takes a 'RequestOptions' record -- and returns a 'Request' record. constructRequest :: RequestOptions -> Request String constructRequest options = Request { rqURI = constructURI (requestUrl options) , rqMethod = constructMethod (requestMethod options) , rqHeaders = constructHeaders (requestHeaders options) , rqBody = requestBody options } -- Construct a URI record from a string. -- If it can't be parsed, return an empty URI record. constructURI :: String -> URI constructURI url | isJust parsedUrl = fromJust parsedUrl | isNothing parsedUrl = URI { uriScheme = "" , uriAuthority = Nothing , uriPath = "" , uriQuery = "" , uriFragment = "" } where parsedUrl = parseURI url -- Construct a method record. constructMethod :: String -> RequestMethod constructMethod method | httpVerb == "GET" = GET | httpVerb == "POST" = POST | httpVerb == "PUT" = PUT | httpVerb == "DELETE" = DELETE | httpVerb == "HEAD" = HEAD | httpVerb == "OPTIONS" = OPTIONS | httpVerb == "TRACE" = TRACE | httpVerb == "CONNECT" = CONNECT | otherwise = Custom httpVerb where httpVerb = map toUpper method -- Construct a list of headers. constructHeaders :: [String] -> [Header] constructHeaders headers = map constructHeader headers -- Construct a Header from a string. constructHeader :: String -> Header constructHeader header = Header headerName value where pieces = splitOn ":" header name = pieces !! 0 value = pieces !! 1 headerName = HdrCustom name -- | @doRequest@ performs a request. doRequest :: (HStream ty) => Request ty -> IO (Response ty) doRequest request = do let response = simpleHTTP request contents <- response unwrapResponse contents -- unwrapResponse :: Result (Response ty) -> IO (Response ty) unwrapResponse (Left err) = fail (show err) unwrapResponse (Right response) = return response -- | @responseCode@ extracts the HTTP response code from the response. -- The response code is returned as a tuple. -- responseCode :: Response a -> (Int, Int, Int) responseCode response = rspCode response -- | @responseReason@ extracts the HTTP reason from the response. responseReason :: Response a -> String responseReason response = rspReason response -- | @responseHeaders@ extracts the headers from the response. responseHeaders :: Response a -> [Header] responseHeaders response = rspHeaders response -- | @responseBody@ extracts the body from the response. responseBody :: Response String -> String responseBody response = rspBody response {- URL STUFF -- -------------------------------------------------------- -- This is a data type that contains all the parts of a URL. data UrlParts = UrlParts { protocol :: String , user :: String , host :: String , port :: String , path :: String , query :: String , hash :: String } deriving (Show) -- This is a function that returns a `UrlParts` record -- with default values. url :: UrlParts url = UrlParts { protocol="http" , user = "" , host = "" , port = "" , path = "" , query = "" , hash = "" } -- This function takes a UrlParts record and -- constructs a URIAuth record from it. constructUriAuth :: UrlParts -> URIAuth constructUriAuth urlParts = URIAuth { uriUserInfo=(constructUriUserInfo (user urlParts)) , uriRegName=(host urlParts) , uriPort=(constructUriPort (port urlParts)) } -- This function takes a UrlParts record and builds -- a Network.URI record from it. constructUrl :: UrlParts -> URI constructUrl urlParts = URI { uriScheme=(constructProtocol (protocol urlParts)) , uriAuthority=(Just (constructUriAuth urlParts)) , uriPath=(path urlParts) , uriQuery=(query urlParts) , uriFragment=(constructHash (hash urlParts)) } -- This function makes sure a non-empty string -- has a colon after it, e.g., 'http' becomes 'http:'. constructProtocol :: String -> String constructProtocol x | length x > 0 = x ++ ":" | otherwise = x -- This function makes sure a non-empty string has -- an ampersand at the end, e.g., 'joe' becomes 'joe@'. constructUriUserInfo :: String -> String constructUriUserInfo x | length x > 0 = x ++ "@" | otherwise = x -- This function makes sure a non-empty string -- has a colon before it, e.g., '42' becomes ':42'. constructUriPort :: String -> String constructUriPort x | length x > 0 = ":" ++ x | otherwise = x -- This function makes sure a non-empty string -- has a hash before it, e.g., 'foo' becomes '#foo'. constructHash :: String -> String constructHash x | length x > 0 = "#" ++ x | otherwise = x -}
jtpaasch/Hurl
src/Hurl.hs
mit
5,842
0
10
1,314
754
408
346
81
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TypeSynonymInstances #-} -- | -- Module : Exercise4 -- Description : Functor, Applicative and Monad -- Copyright : (c) Tom Westerhout, 2017 -- License : MIT module Exercise4 ( -- * Appetizer Student(..) , f2 , f3 -- * Serialisation using Functor, Applicative and Monad , Serialised(Serialised) -- ** State access for primitive types , State(State) , Serialise , rd , wrt -- ** Monad for State -- | See 'State'. -- ** Matching strings , match , pred -- ** Serialisation of Generic Types -- | In the previous exercise I made extensive use of the 'ReadP' -- monad, i.e. all was already done using 'Monad', 'Applicative', and -- 'Alternative' classes. -- -- Anyways, to make better use of the tools developed in this -- exercise, let's adapt our 'Exercise3.Serialise' class a bit: , Serialisable(readPrec', writePrec') -- , SerialiseImpl(readPrecImpl, writePrecImpl) , Bin(..) , read' , show' ) where import Prelude hiding(pred, readParen, showParen) import Data.Proxy import GHC.Generics import Control.Monad import System.IO import Control.Applicative import Control.Exception import Control.Arrow -- | Student record. data Student = Student { fname :: String -- ^ First name. , lname :: String -- ^ Last name. , snum :: Int -- ^ Student number. } deriving (Show) -- | Reads a 'Student' from 'stdin'. This is a straighforward -- translation of the @f2@ function from Clean to Haskell. The only thing I -- couldn't get right is catching the exception. I'm quite new to them, and -- from the implementation of '<|>' for 'IO': -- -- > instance Alternative IO where -- > empty = failIO "mzero" -- > (<|>) = mplusIO -- > -- > -- with -- > mplusIO m n = m `catchException` \ (_ :: IOError) -> n -- -- I expected '<|>' to catch the exception thrown by 'Prelude.read'. f2 :: IO Student f2 = do f <- putStr "Your first name please: " >> getLine l <- putStr "Your last name please: " >> getLine s <- putStr "Your student number please: " >> getLine return (Student f l) `ap` evaluate (read s) -- <|> fail "Hello world!" -- | Reads a 'Student' from 'stdin'. One it's /very/ similar to 'f2', even -- the implementation looks pretty much the same. f3 :: IO Student f3 = let f = putStr "Your first name please: " *> getLine l = putStr "Your last name please: " *> getLine s = putStr "Your student number please: " *> getLine in pure Student <*> f <*> l <*> (read <$> s) -- | Our own definition of State monad so that we can reimplement @(<$>)@, -- @(>>=)@, @(<*>)@ etc. This is my second try at this. I've first -- implemented everything for 'State' as @s -> (a, s)@. For 'Alternative', -- however, 'Maybe' does come in handy. So I thought, maybe a 'MaybeT' -- monad transformer will help. Turned out I needed 'StateT'+'Maybe' -- combination rather than 'MaybeT'+'State', but 'StateT' is a bit too off -- topic, so I've decided to just use @s -> (Maybe a, s)@ :D newtype State s a = State { runState :: s -> (Maybe a, s) } deriving (Generic) -- | According to the exercise, I'm supposed to come up with a type to hold -- serialised version of objects that supports amortised \(\mathcal{O}(1)\) -- reading and writing. -- -- I've actually made a mistake here as appending to list is an -- \(\mathcal{O}(N)\) operation. Don't know why I haven't noticed it -- immediately, but it's quite a bit of work do re-implement everything, so -- I'll leave it be. newtype Serialised = Serialised { runSerialised :: [String] } deriving (Show, Generic) {- FIRST TRY -- | A type from the exercise. type Serialise a = State Serialised (Maybe a) -- | Serialises the argument and adds it to the state. wrt :: Show a => a -> Serialise String wrt x = let x' = show x in State $ \s -> ( return x' , Serialised $ x' : runSerialised s ) -- | Returns the last string that's been added to the state. rd :: Serialise String rd = State $ \s -> case runSerialised s of [] -> (Nothing, s) (x:xs) -> (Just x, Serialised xs) -- | Let's make 'State' a 'Functor'. instance Functor (State s) where fmap f x = State $ runState x >>> first f -- | Let's make 'State' an 'Applicative' functor. instance Applicative (State s) where pure x = State $ \s -> (x, s) f <*> x = State $ runState f >>> second (runState x) >>> \(f', (x', s)) -> (f' x', s) -- | Let's make 'State' a 'Monad'. instance Monad (State s) where return = pure x >>= f = State $ runState x >>> \(x', s) -> runState (f x') s -- | @match x@ Compares the serialised version of @x@ to the next string in -- the state. If these match, @Just x@ is returned, otherwise @Nothing@. -- -- This function is a perfect example of an absolutely unreadable Haskell -- code :D I mean, it's short and elegant, but nowhere near easy to -- undertand. match :: Show a => a -> Serialise a match x = let match' y = if (show x == y) then return x else Nothing in flip (>>=) match' <$> rd -- | Very similar to 'match' except that a predicate is used rather than -- operator @(==)@. pred :: (String -> Bool) -> Serialise String pred f = let match' y = if (f y) then return y else Nothing in flip (>>=) match' <$> rd newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) } instance Functor m => Functor (MaybeT m) where fmap f x = MaybeT $ (liftM f) <$> (runMaybeT x) instance (Monad m) => Applicative (MaybeT m) where pure = MaybeT . return . Just f <*> x = MaybeT $ runMaybeT f >>= \f' -> case f' of Nothing -> return Nothing Just f'' -> runMaybeT x >>= return . fmap f'' instance (Monad m) => Alternative (MaybeT m) where empty = MaybeT $ return Nothing x <|> y = MaybeT $ runMaybeT x >>= \x' -> case x' of Nothing -> runMaybeT y Just x'' -> return x' instance (Monad m) => Monad (MaybeT m) where return = pure x >>= f = MaybeT $ do x' <- runMaybeT x case x' of Nothing -> return Nothing Just x'' -> runMaybeT (f x'') -} -- | A type from the exercise. type Serialise a = State Serialised a -- | Serialises the argument and adds it to the state. wrt :: Show a => a -> Serialise String wrt x = wrt' (show x) wrt' :: String -> Serialise String wrt' x = State $ \s -> ( return x , Serialised $ (runSerialised s) ++ [x]) -- | Returns the next string in the state. rd :: Serialise String rd = State $ \s -> case runSerialised s of [] -> (Nothing, s) (x:xs) -> (Just x, Serialised xs) -- | Let's make 'State' a 'Functor'. instance Functor (State s) where fmap f x = State $ runState x >>> first (fmap f) -- | Let's make 'State' an 'Applicative' functor. instance Applicative (State s) where pure x = State $ \s -> (Just x, s) f <*> x = State $ \s -> case (runState f s) of (Nothing, s') -> (Nothing, s') (Just f', s') -> case (runState x s') of (Nothing, s'') -> (Nothing, s'') (Just x', s'') -> (Just (f' x'), s'') instance Alternative (State s) where empty = fail "empty" x <|> y = State $ \s -> case (runState x s) of (Nothing, _) -> runState y s x' -> x' -- | Let's make 'State' a 'Monad'. instance Monad (State s) where return = pure fail _ = State $ \s -> (Nothing, s) x >>= f = State $ \s -> case (runState x s) of (Nothing, s') -> (Nothing, s') (Just x', s') -> runState (f x') s' -- | @match x@ Compares the serialised version of @x@ to the next string in -- the state. If these match, @Just x@ is returned, otherwise @Nothing@. match :: Show a => a -> Serialise a match x = let match' y = if (show x == y) then return x else fail "No match" in rd >>= match' -- | Very similar to 'match' except that a predicate is used rather than -- operator @(==)@. pred :: (String -> Bool) -> Serialise String pred f = let match' y = if (f y) then return y else fail "No match" in rd >>= match' -- | Precision of function application. appPrec = 10 :: Int class SerialiseImpl a where readPrecImpl :: Int -> Serialise (a x) writePrecImpl :: Int -> (a x) -> Serialise String -- | Out serialisation. Notice how we now use 'Serialise' rather than -- 'ReadP' and 'ShowS'. class Serialisable a where readPrec' :: Int -> Serialise a writePrec' :: Int -> a -> Serialise String default readPrec' :: (Generic a, SerialiseImpl (Rep a)) => Int -> Serialise a readPrec' p = readPrecImpl p >>= return . to default writePrec' :: (Generic a, SerialiseImpl (Rep a)) => Int -> a -> Serialise String writePrec' p x = writePrecImpl p (from x) -- | Equivalent to 'Prelude.readParen' except that it works in our own -- 'State' monad. readParen :: Bool -> Serialise a -> Serialise a readParen p x = if p then mandatory else mandatory <|> x where mandatory = do pred ((==) "(") x' <- x pred ((==) ")") return x' -- | Equivalent to 'Prelude.showParen' except that it works in our own -- 'State' monad. showParen :: Bool -> Serialise String -> Serialise String showParen p x = if p then wrt' "(" >> x >> wrt' ")" else x -- | Both functions undefined, because one simply can create no instances -- of type 'V1'. instance SerialiseImpl V1 where readPrecImpl = undefined writePrecImpl = undefined -- | Reading always succeeds as there's nothing to read; writing fails! -- This is __a very cheaty way to eliminate brackets__ :) instance SerialiseImpl U1 where readPrecImpl _ = return U1 writePrecImpl _ U1 = fail "Nothing to write" instance (SerialiseImpl a, SerialiseImpl b) => SerialiseImpl (a :+: b) where readPrecImpl p = ((readPrecImpl p :: (SerialiseImpl a) => Serialise (a x)) >>= return . L1) <|> ((readPrecImpl p :: (SerialiseImpl b) => Serialise (b x)) >>= return . R1) writePrecImpl p (L1 x) = writePrecImpl p x writePrecImpl p (R1 x) = writePrecImpl p x instance (SerialiseImpl a, SerialiseImpl b) => SerialiseImpl (a :*: b) where readPrecImpl p = readParen False $ do x <- readPrecImpl 11 y <- readPrecImpl 11 return (x :*: y) writePrecImpl p (x :*: y) = (writePrecImpl 11 x) >> (writePrecImpl 11 y) instance (Serialisable v) => SerialiseImpl (K1 i v) where readPrecImpl p = readPrec' p >>= return . K1 writePrecImpl p (K1 x) = writePrec' p x -- | __NB:__ I've solved that problem I've been having last week. Turns -- out, /ScopedTypeVariables/ was the only thing missing. instance (SerialiseImpl a, Constructor x) => SerialiseImpl (M1 C x a) where readPrecImpl p = readParen False $ do pred $ (==) (conName (undefined :: M1 C x a t)) x <- readPrecImpl 11 return (M1 x) writePrecImpl p c@(M1 x) = let x' = writePrecImpl 11 x c' = wrt' (conName c) in (showParen (p > appPrec) $ c' >> x') <|> c' instance (SerialiseImpl a, Selector s) => SerialiseImpl (M1 S s a) where readPrecImpl p = readPrecImpl p >>= return . M1 writePrecImpl p (M1 x) = writePrecImpl p x instance (SerialiseImpl a) => SerialiseImpl (M1 D d a) where readPrecImpl p = readPrecImpl p >>= return . M1 writePrecImpl p (M1 x) = writePrecImpl p x -- | Simple tree. data Bin a = Leaf | Bin (Bin a) a (Bin a) deriving (Eq, Read, Show, Generic) instance Serialisable Int where readPrec' p = let toInt s = case [x | (x, "") <- readsPrec p s] of [x] -> return x _ -> fail "No parse" in rd >>= toInt writePrec' p x = wrt x instance Serialisable (Bin Int) -- | Our analogue of 'Prelude.read' read' :: Serialisable a => Serialised -> Maybe a read' = fst . runState (readPrec' 0 :: (Serialisable a) => Serialise a) -- | Out analogue of 'Prelude.show' show' :: Serialisable a => a -> Serialised show' x = snd $ runState (writePrec' 0 x) (Serialised [])
twesterhout/NWI-I00032-2017-Assignments
Exercise_4/Exercise4.hs
mit
12,706
0
17
3,532
2,486
1,324
1,162
174
2
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Control.Monad.Future.Class ( MonadFuture (..) ) where import Control.Monad.Writer -- | Async monad gives the safe and straightforward way to work -- asynchonous resources. -- class Monad m => MonadFuture r m | m -> r where async :: m a -> m (r a) await :: r a -> m a -- "async" forall a b. async a >> b = b {-# RULES "await" forall a b. await a >> b = b; #-} -- TODO: Instances --instance (Monoid w, MonadFuture e m) => MonadFuture e (WriterT w m) where -- await = lift . await
pxqr/monad-future
Control/Monad/Future/Class.hs
mit
640
0
10
143
93
55
38
10
0
module Lex (Prim(..), Slash(..), Cmplx(..), Lexicon, createLexicon) where import qualified Data.Map as Map data Prim = N | NP | S deriving (Eq, Show, Ord) data Slash = Forw | Back deriving (Eq, Ord) instance Show Slash where show Forw = "/" show Back = "\\" data Cmplx = CmplxLeaf Prim | CmplxTree Cmplx Slash Cmplx deriving (Eq, Ord) instance Show Cmplx where show (CmplxLeaf a) = show a show (CmplxTree a b c) = "(" ++ show a ++ show b ++ show c ++ ")" type Lexicon = Map.Map String [Cmplx] createLexicon :: [(String, [Cmplx])] -> Lexicon createLexicon = Map.fromList
agrasley/HaskellCCG
Lex.hs
mit
658
0
10
190
255
143
112
19
1
module Galua.Util.IOVector where import qualified Data.Vector.Mutable as MVector import Data.Vector.Mutable (MVector) import Control.Monad.Primitive readMaybe :: PrimMonad m => MVector (PrimState m) a -> Int -> m (Maybe a) readMaybe v i | 0 <= i, i < MVector.length v = Just <$> MVector.unsafeRead v i | otherwise = pure Nothing {-# INLINE readMaybe #-}
GaloisInc/galua
galua-rts/src/Galua/Util/IOVector.hs
mit
379
0
10
79
130
68
62
9
1
module CHPrelude (module CHPrelude) where import ClassyPrelude as CHPrelude hiding ( head -- These are unsafe , zip, zip3, zipWith, zipWith3 -- These are somewhat unsafe (import explicitly) , readFile, writeFile , sequence -- Replaced by more general functions , first, second , elem, notElem -- Deprecated (replaced by oelem, onotElem) , forM, forM_ -- Replaced by more general for and for_ , for_, delete, deleteBy -- Hide for forward compatibility with more recent versions of classy-prelude , async , mapConcurrently , Handler , toNullable , tailMay ) import Data.Foldable as CHPrelude ( for_ ) import Data.Bifunctor as CHPrelude import Data.Bifunctor.Extra as CHPrelude ( mapBoth ) import Data.Traversable as CHPrelude ( sequence ) import Data.Text.Read.Extra as CHPrelude ( readValidate , readValidateWith , readValidateExpect , readNote , readNoteWith , readNoteExpect ) import Text.Read as CHPrelude ( lex , readsPrec ) import Control.Monad as CHPrelude ( zipWithM , msum , foldM_ ) import Data.Either.Validation.Extra as CHPrelude ( validate ) import Control.Error.Safe as CHPrelude hiding ( tryJust , readErr -- Use readNote*/readValidate* instead ) import Control.Error.Util as CHPrelude ( (?:) )
circuithub/circuithub-prelude
CHPrelude.hs
mit
3,049
0
5
2,019
243
169
74
33
0
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} module Math.Vector ( Vector2(..) , Vector3(..) , Unit2(..) , Unit3(..) , vector2 , vector3 , unit2 , unit3 , origin , unit , fromUnit , len , (&.) , (*&) , (&^) , reflect' , extract3 ) where import Data.Vect.Double import Data.Vect.Double.Instances type Vector2 = Vec2 type Vector3 = Vec3 type Unit2 = Normal2 type Unit3 = Normal3 vector2 :: Double -> Double -> Vector2 vector2 = Vec2 vector3 :: Double -> Double -> Double -> Vector3 vector3 = Vec3 origin = vector3 0 0 0 class Unit a b where unit :: b -> a fromUnit :: a -> b instance Unit Unit2 Vector2 where unit = mkNormal fromUnit = fromNormal instance Unit Unit3 Vector3 where unit = mkNormal fromUnit = fromNormal unit2 :: Double -> Double -> Unit2 unit2 x y = unit $ vector2 x y unit3 :: Double -> Double -> Double -> Unit3 unit3 x y z = unit $ vector3 x y z extract3 :: Vector3 -> (Double -> Double -> Double -> a) -> a extract3 (Vec3 x y z) f = f x y z
burz/Rayzer
Math/Vector.hs
mit
1,040
0
10
241
368
213
155
46
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.StorageEvent (newStorageEvent, initStorageEvent, getKey, getKeyUnsafe, getKeyUnchecked, getOldValue, getOldValueUnsafe, getOldValueUnchecked, getNewValue, getNewValueUnsafe, getNewValueUnchecked, getUrl, getStorageArea, getStorageAreaUnsafe, getStorageAreaUnchecked, StorageEvent(..), gTypeStorageEvent) 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/StorageEvent Mozilla StorageEvent documentation> newStorageEvent :: (MonadDOM m, ToJSString type') => type' -> Maybe StorageEventInit -> m StorageEvent newStorageEvent type' eventInitDict = liftDOM (StorageEvent <$> new (jsg "StorageEvent") [toJSVal type', toJSVal eventInitDict]) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.initStorageEvent Mozilla StorageEvent.initStorageEvent documentation> initStorageEvent :: (MonadDOM m, ToJSString typeArg, ToJSString keyArg, ToJSString oldValueArg, ToJSString newValueArg, ToJSString urlArg) => StorageEvent -> Maybe typeArg -> Bool -> Bool -> Maybe keyArg -> Maybe oldValueArg -> Maybe newValueArg -> Maybe urlArg -> Maybe Storage -> m () initStorageEvent self typeArg canBubbleArg cancelableArg keyArg oldValueArg newValueArg urlArg storageAreaArg = liftDOM (void (self ^. jsf "initStorageEvent" [toJSVal typeArg, toJSVal canBubbleArg, toJSVal cancelableArg, toJSVal keyArg, toJSVal oldValueArg, toJSVal newValueArg, toJSVal urlArg, toJSVal storageAreaArg])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.key Mozilla StorageEvent.key documentation> getKey :: (MonadDOM m, FromJSString result) => StorageEvent -> m (Maybe result) getKey self = liftDOM ((self ^. js "key") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.key Mozilla StorageEvent.key documentation> getKeyUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => StorageEvent -> m result getKeyUnsafe self = liftDOM (((self ^. js "key") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.key Mozilla StorageEvent.key documentation> getKeyUnchecked :: (MonadDOM m, FromJSString result) => StorageEvent -> m result getKeyUnchecked self = liftDOM ((self ^. js "key") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.oldValue Mozilla StorageEvent.oldValue documentation> getOldValue :: (MonadDOM m, FromJSString result) => StorageEvent -> m (Maybe result) getOldValue self = liftDOM ((self ^. js "oldValue") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.oldValue Mozilla StorageEvent.oldValue documentation> getOldValueUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => StorageEvent -> m result getOldValueUnsafe self = liftDOM (((self ^. js "oldValue") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.oldValue Mozilla StorageEvent.oldValue documentation> getOldValueUnchecked :: (MonadDOM m, FromJSString result) => StorageEvent -> m result getOldValueUnchecked self = liftDOM ((self ^. js "oldValue") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.newValue Mozilla StorageEvent.newValue documentation> getNewValue :: (MonadDOM m, FromJSString result) => StorageEvent -> m (Maybe result) getNewValue self = liftDOM ((self ^. js "newValue") >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.newValue Mozilla StorageEvent.newValue documentation> getNewValueUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => StorageEvent -> m result getNewValueUnsafe self = liftDOM (((self ^. js "newValue") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.newValue Mozilla StorageEvent.newValue documentation> getNewValueUnchecked :: (MonadDOM m, FromJSString result) => StorageEvent -> m result getNewValueUnchecked self = liftDOM ((self ^. js "newValue") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.url Mozilla StorageEvent.url documentation> getUrl :: (MonadDOM m, FromJSString result) => StorageEvent -> m result getUrl self = liftDOM ((self ^. js "url") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.storageArea Mozilla StorageEvent.storageArea documentation> getStorageArea :: (MonadDOM m) => StorageEvent -> m (Maybe Storage) getStorageArea self = liftDOM ((self ^. js "storageArea") >>= fromJSVal) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.storageArea Mozilla StorageEvent.storageArea documentation> getStorageAreaUnsafe :: (MonadDOM m, HasCallStack) => StorageEvent -> m Storage getStorageAreaUnsafe self = liftDOM (((self ^. js "storageArea") >>= fromJSVal) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent.storageArea Mozilla StorageEvent.storageArea documentation> getStorageAreaUnchecked :: (MonadDOM m) => StorageEvent -> m Storage getStorageAreaUnchecked self = liftDOM ((self ^. js "storageArea") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/StorageEvent.hs
mit
6,969
0
16
1,387
1,442
789
653
-1
-1
module GHCJS.DOM.Counter ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/Counter.hs
mit
37
0
3
7
10
7
3
1
0
module GhciMain(peekValue) where import System.IO.Unsafe import Data.IORef import Control.Concurrent peekValue :: a -> a peekValue value = unsafePerformIO$ do ref <- newIORef value result <- newEmptyMVar _ <- forkIO (do val <- readIORef ref result `putMVar` val ) readMVar result
ThomasHickman/haskell-debug
GhciMain.hs
mit
322
0
14
82
101
51
50
12
1
{-# LANGUAGE OverloadedStrings #-} module Main where import HlAdif import HlOptions import Options.Applicative import Prelude hiding (readFile, putStr) import qualified Data.ByteString.Char8 as B import Data.Semigroup ((<>)) data Options = Options { basedir :: String } getOptionsParserInfo :: IO (ParserInfo Options) getOptionsParserInfo = do homeOption <- getHomeOption return $ info (helper <*> ( Options <$> homeOption )) ( fullDesc <> progDesc "Export the ADIF database to a single file" ) doExport :: Options -> IO () doExport opt = do parseResult <- adifLogParser <$> B.readFile (basedir opt ++ "/data/hl.adi") case parseResult of Left errorMsg -> putStrLn errorMsg Right l -> B.putStr $ writeLog l main :: IO () main = getOptionsParserInfo >>= execParser >>= doExport
netom/hamloghs
app/hl-export.hs
mit
869
0
12
207
234
125
109
27
2
{-# LANGUAGE UnicodeSyntax #-} module Control.Monad.Trace ( module Control.Monad.Trace.Class ) where import Control.Monad.Trace.Class import Control.Monad.Trace.ErrorTrace import Control.Monad.Trans.Trace
alephcloud/hs-trace
src/Control/Monad/Trace.hs
mit
207
0
5
19
39
28
11
6
0
-- -- Copyright (c) Krasimir Angelov 2008. -- -- Random GTK utils -- module Yi.UI.Pango.Utils where import Paths_yi import System.FilePath import Graphics.UI.Gtk import System.Glib.GError loadIcon :: FilePath -> IO Pixbuf loadIcon fpath = do iconfile <- getDataFileName $ "art" </> fpath icoProject <- catchGError (pixbufNewFromFile iconfile) (\(GError dom code msg) -> throwGError $ GError dom code $ msg ++ " -- use the yi_datadir environment variable to specify an alternate location") pixbufAddAlpha icoProject (Just (0,255,0))
codemac/yi-editor
src/Yi/UI/Pango/Utils.hs
gpl-2.0
598
0
14
141
144
79
65
12
1
{-# LANGUAGE TemplateHaskell #-} {-| Unittests for our template-haskell generated code. -} {- Copyright (C) 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Test.Ganeti.THH ( testTHH ) where import Test.QuickCheck import Text.JSON import Ganeti.THH import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon {-# ANN module "HLint: ignore Use camelCase" #-} -- * Custom types -- | Type used to test optional field implementation. Equivalent to -- @data TestObj = TestObj { tobjA :: Maybe Int, tobjB :: Maybe Int -- }@. $(buildObject "TestObj" "tobj" [ optionalField $ simpleField "a" [t| Int |] , optionalNullSerField $ simpleField "b" [t| Int |] ]) -- | Arbitrary instance for 'TestObj'. $(genArbitrary ''TestObj) -- | Tests that serialising an (arbitrary) 'TestObj' instance is -- correct: fully optional fields are represented in the resulting -- dictionary only when non-null, optional-but-required fields are -- always represented (with either null or an actual value). prop_OptFields :: TestObj -> Property prop_OptFields to = let a_member = case tobjA to of Nothing -> [] Just x -> [("a", showJSON x)] b_member = [("b", case tobjB to of Nothing -> JSNull Just x -> showJSON x)] in showJSON to ==? makeObj (a_member ++ b_member) -- | Test serialization of TestObj. prop_TestObj_serialization :: TestObj -> Property prop_TestObj_serialization = testArraySerialisation -- | Test that all superfluous keys will fail to parse. prop_TestObj_deserialisationFail :: Property prop_TestObj_deserialisationFail = forAll ((arbitrary :: Gen [(String, Int)]) `suchThat` any (flip notElem ["a", "b"] . fst)) $ testDeserialisationFail (TestObj Nothing Nothing) . encJSDict -- | A unit-like data type. $(buildObject "UnitObj" "uobj" []) $(genArbitrary ''UnitObj) -- | Test serialization of UnitObj. prop_UnitObj_serialization :: UnitObj -> Property prop_UnitObj_serialization = testArraySerialisation -- | Test that all superfluous keys will fail to parse. prop_UnitObj_deserialisationFail :: Property prop_UnitObj_deserialisationFail = forAll ((arbitrary :: Gen [(String, Int)]) `suchThat` (not . null)) $ testDeserialisationFail UnitObj . encJSDict testSuite "THH" [ 'prop_OptFields , 'prop_TestObj_serialization , 'prop_TestObj_deserialisationFail , 'prop_UnitObj_serialization , 'prop_UnitObj_deserialisationFail ]
ribag/ganeti-experiments
test/hs/Test/Ganeti/THH.hs
gpl-2.0
3,191
0
14
647
457
257
200
43
3
module Infernu.Builtins.Object (object) where import Infernu.Builtins.Util import Infernu.Prelude import Infernu.Types keyObj :: Int -> Type -> TQual Type keyObj tv = withTypeClass "StringKeys" (tvar tv) object :: TScheme (Fix FType) object = ts [] $ Fix $ TRow (Just "Object") -- assign - ES6 $ prop "create" (ts [0, 1] $ funcN [tvar 0, openRow 1] (openRow 1)) -- can't be supported in a sane way: -- "defineProperties" -- "defineProperty" -- "getOwnPropertyDescriptor" $ prop "freeze" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] (tvar 1)) $ prop "getOwnPropertyNames" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] (array string)) -- "getPrototypeOf" -- should we just return the same type? we don't support prototypes $ prop "isExtensible" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] boolean) $ prop "isFrozen" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] boolean) $ prop "isSealed" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] boolean) $ prop "keys" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] (array string)) $ prop "preventExtensions" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] (tvar 1)) $ prop "seal" (tsq [0, 1] $ keyObj 1 $ funcN [tvar 0, tvar 1] (tvar 1)) $ TRowEnd Nothing
sinelaw/infernu
src/Infernu/Builtins/Object.hs
gpl-2.0
1,495
0
20
509
587
295
292
20
1
module Main where import Language.Java.Jdi import qualified Language.Java.Jdi.VirtualMachine as Vm import qualified Language.Java.Jdi.Event as E import qualified Language.Java.Jdi.EventSet as ES import qualified Language.Java.Jdi.EventRequest as ER import qualified Language.Java.Jdi.ReferenceType as RT import qualified Language.Java.Jdi.ArrayReference as AR import qualified Language.Java.Jdi.StringReference as SR import qualified Language.Java.Jdi.Value as V import qualified Language.Java.Jdi.StackFrame as SF import qualified Language.Java.Jdi.ThreadReference as TR import qualified Language.Java.Jdi.ThreadGroupReference as TG import qualified Language.Java.Jdi.ObjectReference as OR import qualified Language.Java.Jdi.Method as M import qualified Language.Java.Jdi.Field as F import qualified Language.Java.Jdi.Location as L import Network.Socket.Internal (PortNumber(..)) import Network import Control.Monad.Trans (liftIO, lift) import Control.Applicative ((<$>)) import Control.Monad (forM_, filterM, void, liftM, when) import Control.Monad.Error (MonadError(..), runErrorT, ErrorT, Error(..)) import Data.List import System.Exit main = do result <- Vm.runVirtualMachine "localhost" (PortNumber 2044) body putStrLn "Execution ok" body :: Vm.VirtualMachine IO () body = do jdv <- Vm.version liftIO . putStrLn $ "JdwpVersion: " ++ (show jdv) es <- ES.removeEvent liftIO . putStrLn $ case ES.suspendPolicy es of SuspendAll -> "this is suspend all" SuspendNone -> "this is suspend none" SuspendEventThread -> "this is suspend event thread" liftIO . putStrLn $ show es rd <- ER.enable ER.createClassPrepareRequest liftIO . putStrLn $ show rd pollEvents $ \e -> case E.eventKind e of E.ClassPrepare -> isMainClass $ E.referenceType e _ -> False classes <- Vm.allClasses let cNames = map RT.name classes liftIO . putStrLn $ intercalate "\n" cNames threads <- Vm.allThreads liftIO . putStrLn $ intercalate "\n" (map show threads) filteredClasses <- Vm.classesByName "java.io.BufferedReader" liftIO . putStrLn $ intercalate "\n" (map show filteredClasses) threadGroups <- Vm.topLevelThreadGroups liftIO . putStrLn $ intercalate "\n" (map show threadGroups) let mainClass = head $ filter isMainClass classes liftIO . putStrLn $ "Before fields of main class" fields <- RT.fields mainClass liftIO . putStrLn $ "After fields of main class" liftIO . putStrLn $ show fields checkFieldsNames fields liftIO . putStrLn $ "Main class fields: " ++ show fields liftIO . putStrLn $ "Main class fields static: " ++ (show $ map F.isStatic fields) liftIO . putStrLn $ "Main class fields public: " ++ (show $ map F.isPublic fields) liftIO . putStrLn $ "Main class fields private: " ++ (show $ map F.isPrivate fields) sName <- RT.sourceName mainClass liftIO . putStrLn $ "Main class source name: " ++ sName mainClassInterfaces <- RT.interfaces mainClass mainSuper <- RT.superclass mainClass liftIO . putStrLn $ "Super classs of main class: " ++ show mainSuper let oneInterface = head mainClassInterfaces otherInterfaces <- RT.interfaces oneInterface liftIO . putStrLn $ "Other interfaces: " ++ show otherInterfaces liftIO . putStrLn $ "Main class interfaces: " ++ show mainClassInterfaces methods <- RT.methods mainClass liftIO . putStrLn $ "Methods for class " ++ (show mainClass) liftIO . putStrLn $ intercalate "\n" (map show methods) liftIO . putStrLn =<< Vm.name liftIO . putStrLn $ M.name $ head methods forM_ threads (\thread -> liftIO . putStrLn $ TR.name thread) let isMainMethod = ("main" ==) . M.name let isRunMethod = ("run" ==) . M.name let methodMain = head $ filter isMainMethod methods let runMethod = head $ filter isRunMethod methods let isAnotherMethod = ("anotherMethod" ==) . M.name let anotherMethod = head $ filter isAnotherMethod methods liftIO . putStrLn $ "Variables of method anotherMethod: " ++ (show anotherMethod) do l <- M.arguments anotherMethod liftIO $ putStrLn $ show l `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) liftIO . putStrLn $ "Variables of method main: " ++ (show methodMain) do l <- M.variables methodMain liftIO $ putStrLn $ show l `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) liftIO . putStrLn $ "VariablesByName" do l <- M.variablesByName methodMain "i" liftIO $ putStrLn $ show l `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) liftIO . putStrLn $ "Arguments of the method main" do mainArgs <- M.arguments methodMain liftIO $ putStrLn $ show mainArgs `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) liftIO . putStrLn $ "Printing line table" lineTable <- M.allLineLocations methodMain liftIO . putStrLn $ "After line table" mainLocation <- M.location methodMain runLocation <- M.location runMethod liftIO . putStrLn $ intercalate "\n" (map show lineTable) classLineLocations <- RT.allLineLocations mainClass liftIO . putStrLn $ intercalate "\n" (map show classLineLocations) liftIO . putStrLn $ "Enabling breakpoint request" bpr <- ER.enable $ ER.createBreakpointRequest mainLocation liftIO . putStrLn $ "breakpoint request is enabled" ev <- pollEvents $ \e -> case E.eventKind e of E.Breakpoint -> True _ -> False printThreadTree liftIO . putStrLn $ "breakpoint stopped at location" liftIO . putStrLn $ show methodMain loc <- E.location ev liftIO . putStrLn $ show loc liftIO . putStrLn $ "Values of args" curThread <- E.thread ev fr <- head <$> TR.allFrames curThread mainArgs <- M.arguments methodMain mainArgsValue <- SF.getValue fr (head mainArgs) case mainArgsValue of V.ArrayValue arrV -> do (V.StringValue aV) <- AR.getValue arrV 0 sV <- SR.value aV liftIO $ putStrLn sV otherwise -> liftIO $ putStrLn "Not array value" bpr <- ER.enable $ ER.createBreakpointRequest runLocation ev <- pollEvents $ \e -> case E.eventKind e of E.Breakpoint -> True _ -> False evThread <- E.thread ev spr <- ER.enable $ (ER.createStepRequest evThread StepLine StepOver) Vm.resume ev1 <- ES.removeEvent fieldValues <- mapM (RT.getValue mainClass) (take 2 fields) checkFieldValues fieldValues liftIO . putStrLn $ "==== taking value of non static field in reftype ====" (void $ RT.getValue mainClass (last fields)) `catchError` (\ee -> liftIO $ putStrLn $ "error message: " ++ (show ee)) liftIO . putStrLn $ "===== ============ ======" liftIO . putStrLn $ "===== this Object values ======" let evv = head $ ES.events ev1 curThread <- E.thread evv fr1 <- head <$> TR.allFrames curThread thisObj <- SF.thisObject fr1 argsValue <- OR.getValue thisObj (last fields) liftIO . putStrLn $ show argsValue liftIO . putStrLn $ "===== =========== ======" Vm.resume void $ ES.removeEvent liftIO . putStrLn $ "trying step requests" Vm.resume es0 <- ES.removeEvent let e0 = head $ ES.events es0 liftIO $ putStrLn $ show e0 do e0thread <- E.thread e0 v0 <- getValueOfI e0thread liftIO $ putStrLn $ show v0 `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) Vm.resume void $ ES.removeEvent Vm.resume es1 <- ES.removeEvent let e1 = head $ ES.events es1 liftIO $ putStrLn $ show e1 do e1thread <- E.thread e1 v1 <- getValueOfI e1thread liftIO $ putStrLn $ show v1 `catchError` (\ee -> liftIO $ putStrLn $ "error during arguments: " ++ (show ee)) pollEvents $ \e -> case E.eventKind e of E.VmDeath -> True _ -> False liftIO . putStrLn $ "Exiting" printThreadTree = do liftIO $ putStrLn "========== Thread Tree ===========" tgs <- Vm.topLevelThreadGroups mapM (printThreadGroup 0) tgs liftIO $ putStrLn "========== ----------- ===========" printThreadGroup depth tg = do let is = " " let indent = concat $ replicate depth is let tgName = TG.name tg liftIO $ putStrLn $ indent ++ "Thread group: " ++ tgName liftIO $ putStrLn $ indent ++ is ++ "Threads: " trds <- TG.threads tg tstats <- mapM ((show <$>) . TR.status) trds tsusps <- mapM ((show <$>) . TR.isSuspended) trds let ts = map TR.name trds let threadStrings = zipWith3 (\a b c -> a ++ " " ++ b ++ " " ++ c) ts tstats tsusps liftIO $ putStrLn $ intercalate "\n" $ map ((indent ++ is ++ is) ++ ) threadStrings mapM (printThreadGroup $ depth + 1) =<< TG.threadGroups tg return () checkFieldsNames fields = do when (length fields /= 3) $ liftIO exitFailure let f1name = F.name (fields !! 0) let f2name = F.name (fields !! 1) let f3name = F.name (fields !! 2) when (f1name /= "f1") $ liftIO exitFailure when (f2name /= "fprivate") $ liftIO exitFailure when (f3name /= "args") $ liftIO exitFailure checkFieldValues fieldValues = do liftIO . putStrLn $ "Main class field values: " ++ show fieldValues when ((intValue $ fieldValues !! 0) /= 10) $ throwError $ strMsg "field value not equals 10" sv <- strValue $ fieldValues !! 1 when (sv /= "fprivate_value") $ throwError $ strMsg "field value not equals fprivate_value" intValue (V.IntValue v) = v strValue (V.StringValue sv) = SR.value sv getValueOfI curThread = do frCnt <- TR.frameCount curThread liftIO $ putStrLn $ "Frame count: " ++ (show frCnt) fr <- head <$> TR.allFrames curThread liftIO $ putStrLn $ show fr liftIO $ putStrLn "Individual frames" indFrames <- sequence [TR.frame curThread x | x <- [0..(frCnt - 1)]] liftIO $ putStrLn $ show indFrames loc <- SF.location fr liftIO $ putStrLn $ show loc var <- head <$> M.variablesByName (L.method loc) "i" liftIO $ putStrLn $ show var SF.getValue fr var pollEvents stopFunction = do Vm.resume es <- ES.removeEvent liftIO $ putStrLn $ show es let e = head $ ES.events es if stopFunction e then return e else pollEvents stopFunction isMainClass ref = "LMain;" == RT.signature ref
VictorDenisov/jdi
Tests/Test.hs
gpl-2.0
10,674
0
16
2,624
3,443
1,662
1,781
247
8
module Language.Bitcoin.Test.Parser ( tests ) where import Data.Binary (encode) import Language.Bitcoin.Parser (run_parser) import Language.Bitcoin.Types import Language.Bitcoin.Utils (bs) import Test.HUnit import qualified Data.ByteString as B import qualified Data.List as List tests = TestLabel "Parser" $ TestList $ good ++ bad goodCases = [ ("OP_FALSE", [CmdOpcode OP_FALSE]) , ("OP_FALSE ", [CmdOpcode OP_FALSE]) , (" OP_FALSE", [CmdOpcode OP_FALSE]) , (" OP_FALSE ; ", [CmdOpcode OP_FALSE]) , ("OP_FALSE\n", [CmdOpcode OP_FALSE]) , ("OP_FALSE;", [CmdOpcode OP_FALSE]) , (" ; \n ;", []) , ("OP_FALSE # comment", [CmdOpcode OP_FALSE]) , ("# comment\nOP_FALSE", [CmdOpcode OP_FALSE]) , ("OP_FALSE;OP_TRUE", [CmdOpcode OP_FALSE, CmdOpcode OP_TRUE]) , ("OP_PUSHDATA 01 23", [CmdOpcode $ OP_PUSHDATA Direct (bs 0x23)]) , ("OP_PUSHDATA1 06 040815162342", [CmdOpcode $ OP_PUSHDATA OneByte (bs 0x40815162342)]) , ("OP_PUSHDATA2 0006 040815162342", [CmdOpcode $ OP_PUSHDATA TwoBytes (bs 0x40815162342)]) , ("OP_PUSHDATA4 00000006 040815162342", [CmdOpcode $ OP_PUSHDATA FourBytes (bs 0x40815162342)]) , ("DATA 040815162342", [DATA $ bs 0x40815162342]) , ("KEY 01", [KEY 1]) , ("SIG 01", [SIG 1]) ] badCases = [ ("foo", "expecting opcode") , ("OP_DOESNOTEXIST", "expecting opcode") , ("OP_PUSHDATA 0;", "expecting hexadecimal digit") , ("OP_PUSHDATA 4c;", "OP_PUSHDATA only support up to 75 bytes of data") , ("OP_PUSHDATA1 100 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111;", "expecting hexadecimal digit") , ("OP_PUSHDATA1 1 2342", "expecting hexadecimal digit") ] good :: [Test] good = map runTest goodCases where runTest (code, expected) = TestCase $ case run_parser "<<test>>" code of Left e -> assertFailure e Right script -> expected @=? script bad :: [Test] bad = map runTest badCases where runTest (code, expected) = TestCase $ case run_parser "<<test>>" code of Left err -> (last . lines) err @=? expected Right _ -> assertFailure "Parser should have failed"
copton/bitcoin-script-tools
test/Language/Bitcoin/Test/Parser.hs
gpl-3.0
2,295
0
14
381
619
357
262
48
2
{-# LANGUAGE RankNTypes #-} module Deserialization where import Control.Monad (liftM2) import Data.Foldable (traverse_) import Data.Function (fix) import Text.Read (readEither) import ExpSYM data Tree = Leaf String | Node String [Tree] deriving (Eq, Read, Show) instance ExpSYM Tree where lit n = Node "Lit" [Leaf (show n)] neg e = Node "Neg" [e] add e0 e1 = Node "Add" [e0, e1] -- | Serialization of a 'ExpSYM' via its instance. toTree :: Tree -> Tree toTree = id -------------------------------------------------------------------------------- -- De-serialization -------------------------------------------------------------------------------- type ErrMsg = String fromTree :: ExpSYM repr => Tree -> Either ErrMsg repr fromTree (Node "Lit" [Leaf n]) = lit <$> readEither n fromTree (Node "Neg" [e]) = neg <$> fromTree e fromTree (Node "Add" [e0, e1]) = liftM2 add (fromTree e0) (fromTree e1) fromTree e = Left $ "Invalid tree: " ++ show e tf1Tree :: Tree tf1Tree = toTree tf1 -- Then you can use 'fromTree' to de-serialize a tree into the desired representation: -- -- > eval <$> fromTree tf1Tree -- > Right 5 -- > it :: Either ErrMsg Int -- -- > view <$> fromTree tf1Tree -- > Right "(8 + - ((1 + 2)))" -- > it :: Either ErrMsg String -- -- But there's a problem.... we cannot use 'eval' and 'view' after decoding! evalAndShow :: IO () evalAndShow = case fromTree tf1Tree of Left e -> putStrLn $ "Error: " ++ e Right repr -> do print $ eval repr -- Here @repr@ will be bound to 'String', so we cannot use 'view'! -- print $ view repr -- We can fake the polymorphism as follows: newtype Wrapped = Wrapped (forall repr . ExpSYM repr => repr) fromTreeW :: Tree -> Either ErrMsg Wrapped fromTreeW (Node "Lit" [Leaf n]) = do r <- readEither n return $ Wrapped (lit r) fromTreeW (Node "Neg" [e]) = do Wrapped r <- fromTreeW e return $ Wrapped (neg r) fromTreeW (Node "Add" [e0, e1]) = do Wrapped r0 <- fromTreeW e0 Wrapped r1 <- fromTreeW e1 return $ Wrapped (add r0 r1) evalAndShowW :: IO () evalAndShowW = -- QUESTION TO SO: fromTreeW should be evaluated only once, right? How can -- this be checked? case fromTreeW tf1Tree of Left e -> putStrLn $ "Error: " ++ e Right (Wrapped repr) -> do print $ eval repr -- Here @repr@ will be bound to 'String', so we cannot use 'view'! print $ view repr -------------------------------------------------------------------------------- -- Solution with "The puzzling interpreter" -------------------------------------------------------------------------------- -- | A duplicating interpreter. instance (ExpSYM repr, ExpSYM repr') => ExpSYM (repr, repr') where lit x = (lit x, lit x) neg (e0, e1) = (neg e0, neg e1) add (le0, le1) (re0, re1) = (add le0 re0, add le1 re1) duplicate :: (ExpSYM repr, ExpSYM repr') => (repr, repr') -> (repr, repr') duplicate = id -- Now, how do we use this function to write a function 'thrice' that evals, -- prints, and encodes an expression? thrice :: (Int, (String, Tree)) -> IO () -- Is this the most generic type we can give? thrice x0 = do x1 <- dupConsume eval x0 x2 <- dupConsume view x1 print $ toTree x2 where dupConsume ev y = do print (ev y0) return y1 where (y0, y1) = duplicate y -- See https://stackoverflow.com/questions/51457533/typed-tagless-final-interpreters-what-is-the-use-of-duplicate thrice' :: (Int, (String, Tree)) -> IO () thrice' (reprInt, (reprStr, reprTree)) = do print $ eval reprInt print $ view reprStr print $ toTree reprTree printTrice :: IO () printTrice = traverse_ thrice' (fromTree tf1Tree) -- | Extension of the deserializer using the open recursion style. fromTreeExt :: (ExpSYM repr) => (Tree -> Either ErrMsg repr) -> (Tree -> Either ErrMsg repr) fromTreeExt _ (Node "Lit" [Leaf n]) = lit <$> readEither n fromTreeExt self (Node "Neg" [e]) = neg <$> self e fromTreeExt self (Node "Add" [e0, e1]) = liftM2 add (self e0) (self e1) fromTreeExt _ e = Left $ "Invalid tree: " ++ show e fromTree' :: ExpSYM repr => Tree -> Either ErrMsg repr fromTree' = fix fromTreeExt -- TODO: prove that fromTree' == fromTree -- Run the examples: tf1EInt3 :: IO () tf1EInt3 = traverse_ thrice (fromTree' tf1Tree) tfxEInt3 :: IO () tfxEInt3 = traverse_ thrice (fromTree' wrongTree) where wrongTree = Node "Lit" [Leaf "0", Leaf "2"]
capitanbatata/sandbox
tagless/src/Deserialization.hs
gpl-3.0
4,645
0
11
1,128
1,325
684
641
84
2
module Vigenere where import Alphabetical import Data.Either import Likelihood import Partial import Util key :: String -> Letters key = cycle . rights . letters encrypt :: Letters -> Letters -> Letters encrypt = zipWith (+) . cycle decrypt :: Letters -> Letters -> Letters decrypt = zipWith (flip (-)) . cycle
maugier/cctk
src/CCTK/Vigenere.hs
gpl-3.0
317
0
8
58
103
59
44
12
1
{-# LANGUAGE TypeFamilies #-} module Lamdu.GUI.ExpressionEdit.InferredEdit(make) where import Control.Applicative ((<$>)) import Control.Lens.Operators import Control.MonadA (MonadA) import Data.Monoid (mempty) import Lamdu.Config (Config) import Lamdu.GUI.ExpressionGui (ExpressionGui, ParentPrecedence(..)) import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM) import qualified Control.Lens as Lens import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.Bottle.Widgets.FocusDelegator as FocusDelegator import qualified Lamdu.Config as Config import qualified Lamdu.GUI.BottleWidgets as BWidgets import qualified Lamdu.GUI.ExpressionGui as ExpressionGui import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM import qualified Lamdu.GUI.ExpressionEdit.HoleEdit as HoleEdit import qualified Lamdu.GUI.WidgetEnvT as WE import qualified Lamdu.Sugar.Types as Sugar fdConfig :: Config -> FocusDelegator.Config fdConfig config = FocusDelegator.Config { FocusDelegator.startDelegatingKeys = Config.replaceInferredValueKeys config ++ Config.delKeys config , FocusDelegator.startDelegatingDoc = E.Doc ["Edit", "Inferred value", "Replace"] , FocusDelegator.stopDelegatingKeys = Config.keepInferredValueKeys config , FocusDelegator.stopDelegatingDoc = E.Doc ["Edit", "Inferred value", "Back"] } make :: MonadA m => ParentPrecedence -> Sugar.Inferred Sugar.Name m (ExprGuiM.SugarExpr m) -> Sugar.Payload Sugar.Name m ExprGuiM.Payload -> Widget.Id -> ExprGuiM m (ExpressionGui m) make parentPrecedence inferred pl myId = do config <- ExprGuiM.widgetEnv WE.readConfig let eventMap = maybe mempty (E.keyPresses (Config.acceptInferredValueKeys config) (E.Doc ["Edit", "Inferred value", "Accept"]) . fmap HoleEdit.eventResultOfPickedResult) $ inferred ^. Sugar.iMAccept ExprGuiM.wrapDelegated (fdConfig config) FocusDelegator.NotDelegating (ExpressionGui.egWidget %~) (makeUnwrapped parentPrecedence pl inferred) myId <&> ExpressionGui.egWidget %~ Widget.weakerEvents eventMap makeUnwrapped :: MonadA m => ParentPrecedence -> Sugar.Payload Sugar.Name m ExprGuiM.Payload -> Sugar.Inferred Sugar.Name m (ExprGuiM.SugarExpr m) -> Widget.Id -> ExprGuiM m (ExpressionGui m) makeUnwrapped (ParentPrecedence parentPrecedence) pl inferred myId = do config <- ExprGuiM.widgetEnv WE.readConfig mInnerCursor <- ExprGuiM.widgetEnv $ WE.subCursor myId inactive <- ExpressionGui.addInferredTypes pl =<< ExpressionGui.egWidget ( ExprGuiM.widgetEnv . BWidgets.makeFocusableView myId . Widget.tint (Config.inferredValueTint config) . Widget.scale (realToFrac <$> Config.inferredValueScaleFactor config) ) =<< ExprGuiM.makeSubexpression parentPrecedence (inferred ^. Sugar.iValue) case (mStoredGuid, mInnerCursor, inferred ^. Sugar.iHole . Sugar.holeMActions) of (Just storedGuid, Just _, Just actions) -> HoleEdit.makeUnwrappedActive pl storedGuid actions (inactive ^. ExpressionGui.egWidget . Widget.wSize) myId _ -> return inactive where mStoredGuid = pl ^? Sugar.plActions . Lens._Just . Sugar.storedGuid
sinelaw/lamdu
Lamdu/GUI/ExpressionEdit/InferredEdit.hs
gpl-3.0
3,212
0
18
466
853
467
386
-1
-1
-- Monadic command line checkers.. -- @2013 Angel Alvarez module OptsCheck where -- Main module needed imports import Control.Monad(foldM,liftM,ap) import Control.Monad.IO.Class import Control.Monad.Trans.Either import Data.List (find) import Data.Maybe ( fromMaybe ) import Data.Either import Text.Show.Functions import System.Environment import System.Console.GetOpt import System.Directory ( doesDirectoryExist, doesFileExist ) import System.FilePath -- Record for storing cmdline options data Options = Options { optDump :: Bool , optModules :: [(String,(Options-> IO()))] , optMode :: Maybe (Options->IO()) , optVerbose :: Bool , optShowVersion :: Bool , optOutput :: Maybe FilePath , optDataDir :: Maybe FilePath , optInput :: [FilePath] } deriving (Show) -- An EitherT container to store parsed opts from commandline or error messages type OptsResult = EitherT String IO Options -- An Opts filter runnng in the EitherT IO Stack type OptsFilter = ( Options -> OptsResult ) -- A Policy describing a command line options with a checking filter type OptsPolicy = OptDescr OptsFilter -- =============================================== Options checking ============================================== -- progOpts: getOpt args processor that also checks semantically getopt results or bang in front of the user -- Upon checking with getopt this function gets a list of lambdas representing semantical checks -- on every cmdline switch, as an example; we check for input file presence and the check that either data -- director is a valid one and input file exists and is readable. Those checks are performed by -- filename_check, check_datadir and check_input_file respectively. These funs are stored -- in the Options structure that getopt uses. -- We use a EitherT transformer to combine Either chaining with arbitrary IO actions needed during checking -- =============================================================================================================== progOpts :: [String] -> Options -> [OptsPolicy] -> OptsResult progOpts args defaultOptions acceptedOptions = case getOpt RequireOrder acceptedOptions args of (funs,[],[]) -> do left "input file(s) missing" (funs,filenames,[]) -> do resultOfFuns <- foldl (>>=) (return defaultOptions) funs -- Perform monadic checkings upon getOpt supplied functions foldM check_input_file resultOfFuns $ reverse filenames -- Now check if all the input files exist and are accesible (_,_,errs) -> do left ( concat errs ) -- =============================================== Monadic Options checkers ======================================= -- getOpt will partially apply against the supplied argument do we can just come over the options record -- Who we are?, sort of alien outbreak? check_version :: Options -> OptsResult check_version optsR = return $ optsR { optShowVersion = True } -- help message, dont panic, we are just not going anywhere after showing the help check_help :: Options -> OptsResult check_help _ = left "Command line help requested" --check supplied input files exist or bang if any is not. check_input_file :: Options -> String -> OptsResult check_input_file optsR@Options { optInput = files , optDataDir = dataDir } filename = do test <- liftIO $ filename_check dataDir filename case test of True -> return $ (optsR { optInput = filename : files }) False -> left $ "input file "++ filename ++ " not readable" where filename_check :: Maybe FilePath -> FilePath -> IO Bool --check file with or without data directory filename_check (Just datadir) filename = doesFileExist $ combine datadir filename filename_check Nothing filename = doesFileExist filename -- User passed some directory, we make sure this dir exits so file will matched against it check_data_dir :: String -> Options -> OptsResult check_data_dir dir optsR = do test <- liftIO $ doesDirectoryExist dir case test of True -> return $ optsR { optDataDir = Just dir } False -> left ( "Data directory " ++ dir ++ " does not exist" ) -- check user wants verbosity level increased check_verbosity :: Options -> OptsResult check_verbosity optsR = return $ optsR { optVerbose = True } -- check mode of operation. A list of modules is provided in the options record check_operation_mode :: String -> Options -> OptsResult check_operation_mode mode optsR@Options { optModules = modules } = do return $ optsR { optMode = selectedModule } where selectedModule = case (findmodule mode modules) of Just (_,fun) -> Just fun Nothing -> Nothing findmodule :: String -> [(String, (Options-> IO()))] -> Maybe (String,(Options -> IO ())) findmodule mode modules = find (\(x,_) -> x == mode ) modules -- dump either options or errors as we get passthrought check_dump_options :: Options -> OptsResult check_dump_options optsR = do liftIO $ putStrLn $ "\n\nOptions dumping selected record: \n\t" ++ show optsR ++ "\n" return $ optsR { optDump =True }
AngelitoJ/HsParser
src/OptsCheck.hs
gpl-3.0
5,239
0
14
1,092
982
542
440
68
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.YouTube.LiveBroadcasts.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a broadcast. -- -- /See:/ <https://developers.google.com/youtube/v3 YouTube Data API Reference> for @youtube.liveBroadcasts.insert@. module Network.Google.Resource.YouTube.LiveBroadcasts.Insert ( -- * REST Resource LiveBroadcastsInsertResource -- * Creating a Request , liveBroadcastsInsert , LiveBroadcastsInsert -- * Request Lenses , lbiPart , lbiPayload , lbiOnBehalfOfContentOwner , lbiOnBehalfOfContentOwnerChannel ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.liveBroadcasts.insert@ method which the -- 'LiveBroadcastsInsert' request conforms to. type LiveBroadcastsInsertResource = "youtube" :> "v3" :> "liveBroadcasts" :> QueryParam "part" Text :> QueryParam "onBehalfOfContentOwner" Text :> QueryParam "onBehalfOfContentOwnerChannel" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] LiveBroadcast :> Post '[JSON] LiveBroadcast -- | Creates a broadcast. -- -- /See:/ 'liveBroadcastsInsert' smart constructor. data LiveBroadcastsInsert = LiveBroadcastsInsert' { _lbiPart :: !Text , _lbiPayload :: !LiveBroadcast , _lbiOnBehalfOfContentOwner :: !(Maybe Text) , _lbiOnBehalfOfContentOwnerChannel :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LiveBroadcastsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lbiPart' -- -- * 'lbiPayload' -- -- * 'lbiOnBehalfOfContentOwner' -- -- * 'lbiOnBehalfOfContentOwnerChannel' liveBroadcastsInsert :: Text -- ^ 'lbiPart' -> LiveBroadcast -- ^ 'lbiPayload' -> LiveBroadcastsInsert liveBroadcastsInsert pLbiPart_ pLbiPayload_ = LiveBroadcastsInsert' { _lbiPart = pLbiPart_ , _lbiPayload = pLbiPayload_ , _lbiOnBehalfOfContentOwner = Nothing , _lbiOnBehalfOfContentOwnerChannel = Nothing } -- | The part parameter serves two purposes in this operation. It identifies -- the properties that the write operation will set as well as the -- properties that the API response will include. The part properties that -- you can include in the parameter value are id, snippet, contentDetails, -- and status. lbiPart :: Lens' LiveBroadcastsInsert Text lbiPart = lens _lbiPart (\ s a -> s{_lbiPart = a}) -- | Multipart request metadata. lbiPayload :: Lens' LiveBroadcastsInsert LiveBroadcast lbiPayload = lens _lbiPayload (\ s a -> s{_lbiPayload = a}) -- | Note: This parameter is intended exclusively for YouTube content -- partners. The onBehalfOfContentOwner parameter indicates that the -- request\'s authorization credentials identify a YouTube CMS user who is -- acting on behalf of the content owner specified in the parameter value. -- This parameter is intended for YouTube content partners that own and -- manage many different YouTube channels. It allows content owners to -- authenticate once and get access to all their video and channel data, -- without having to provide authentication credentials for each individual -- channel. The CMS account that the user authenticates with must be linked -- to the specified YouTube content owner. lbiOnBehalfOfContentOwner :: Lens' LiveBroadcastsInsert (Maybe Text) lbiOnBehalfOfContentOwner = lens _lbiOnBehalfOfContentOwner (\ s a -> s{_lbiOnBehalfOfContentOwner = a}) -- | This parameter can only be used in a properly authorized request. Note: -- This parameter is intended exclusively for YouTube content partners. The -- onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID -- of the channel to which a video is being added. This parameter is -- required when a request specifies a value for the onBehalfOfContentOwner -- parameter, and it can only be used in conjunction with that parameter. -- In addition, the request must be authorized using a CMS account that is -- linked to the content owner that the onBehalfOfContentOwner parameter -- specifies. Finally, the channel that the onBehalfOfContentOwnerChannel -- parameter value specifies must be linked to the content owner that the -- onBehalfOfContentOwner parameter specifies. This parameter is intended -- for YouTube content partners that own and manage many different YouTube -- channels. It allows content owners to authenticate once and perform -- actions on behalf of the channel specified in the parameter value, -- without having to provide authentication credentials for each separate -- channel. lbiOnBehalfOfContentOwnerChannel :: Lens' LiveBroadcastsInsert (Maybe Text) lbiOnBehalfOfContentOwnerChannel = lens _lbiOnBehalfOfContentOwnerChannel (\ s a -> s{_lbiOnBehalfOfContentOwnerChannel = a}) instance GoogleRequest LiveBroadcastsInsert where type Rs LiveBroadcastsInsert = LiveBroadcast type Scopes LiveBroadcastsInsert = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl"] requestClient LiveBroadcastsInsert'{..} = go (Just _lbiPart) _lbiOnBehalfOfContentOwner _lbiOnBehalfOfContentOwnerChannel (Just AltJSON) _lbiPayload youTubeService where go = buildClient (Proxy :: Proxy LiveBroadcastsInsertResource) mempty
rueshyna/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/LiveBroadcasts/Insert.hs
mpl-2.0
6,344
0
15
1,310
579
353
226
85
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.ServiceConsumerManagement.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.ServiceConsumerManagement.Types ( -- * Service Configuration serviceConsumerManagementService -- * OAuth Scopes , cloudPlatformScope -- * JwtLocation , JwtLocation , jwtLocation , jlValuePrefix , jlHeader , jlQuery -- * MetricDescriptorValueType , MetricDescriptorValueType (..) -- * SystemParameter , SystemParameter , systemParameter , spHTTPHeader , spURLQueryParameter , spName -- * MonitoredResourceDescriptor , MonitoredResourceDescriptor , monitoredResourceDescriptor , mrdName , mrdDisplayName , mrdLabels , mrdType , mrdDescription , mrdLaunchStage -- * BackendRulePathTranslation , BackendRulePathTranslation (..) -- * V1Beta1RefreshConsumerResponse , V1Beta1RefreshConsumerResponse , v1Beta1RefreshConsumerResponse -- * DocumentationRule , DocumentationRule , documentationRule , drSelector , drDeprecationDescription , drDescription -- * Status , Status , status , sDetails , sCode , sMessage -- * V1Beta1ServiceIdentity , V1Beta1ServiceIdentity , v1Beta1ServiceIdentity , vbsiEmail , vbsiTag , vbsiUniqueId , vbsiName -- * BillingDestination , BillingDestination , billingDestination , bdMetrics , bdMonitoredResource -- * Control , Control , control , cEnvironment -- * AuthRequirement , AuthRequirement , authRequirement , arProviderId , arAudiences -- * V1Beta1GenerateServiceIdentityResponse , V1Beta1GenerateServiceIdentityResponse , v1Beta1GenerateServiceIdentityResponse , vbgsirIdentity -- * Context , Context , context , cRules -- * LoggingDestination , LoggingDestination , loggingDestination , ldMonitoredResource , ldLogs -- * MetricDescriptor , MetricDescriptor , metricDescriptor , mdMonitoredResourceTypes , mdMetricKind , mdName , mdMetadata , mdDisplayName , mdLabels , mdType , mdValueType , mdDescription , mdUnit , mdLaunchStage -- * ListOperationsResponse , ListOperationsResponse , listOperationsResponse , lorNextPageToken , lorOperations -- * TenantResourceStatus , TenantResourceStatus (..) -- * CancelOperationRequest , CancelOperationRequest , cancelOperationRequest -- * BackendRule , BackendRule , backendRule , brJwtAudience , brSelector , brAddress , brProtocol , brDisableAuth , brOperationDeadline , brDeadline , brPathTranslation -- * SourceContext , SourceContext , sourceContext , scFileName -- * V1Beta1ImportProducerQuotaPoliciesResponse , V1Beta1ImportProducerQuotaPoliciesResponse , v1Beta1ImportProducerQuotaPoliciesResponse , vbipqprPolicies -- * SearchTenancyUnitsResponse , SearchTenancyUnitsResponse , searchTenancyUnitsResponse , sturTenancyUnits , sturNextPageToken -- * Field , Field , field , fKind , fOneofIndex , fName , fJSONName , fCardinality , fOptions , fPacked , fDefaultValue , fNumber , fTypeURL -- * MetricRule , MetricRule , metricRule , mrSelector , mrMetricCosts -- * FieldKind , FieldKind (..) -- * EnumSyntax , EnumSyntax (..) -- * V1Beta1QuotaOverrideDimensions , V1Beta1QuotaOverrideDimensions , v1Beta1QuotaOverrideDimensions , vbqodAddtional -- * Service , Service , service , sControl , sMetrics , sContext , sAuthentication , sAPIs , sTypes , sSystemTypes , sMonitoredResources , sBackend , sMonitoring , sName , sSystemParameters , sLogs , sDocumentation , sId , sUsage , sEndpoints , sEnums , sConfigVersion , sHTTP , sTitle , sProducerProjectId , sSourceInfo , sBilling , sCustomError , sLogging , sQuota -- * Operation , Operation , operation , oDone , oError , oResponse , oName , oMetadata -- * Empty , Empty , empty -- * V1Beta1ImportProducerOverridesResponse , V1Beta1ImportProducerOverridesResponse , v1Beta1ImportProducerOverridesResponse , vbiporOverrides -- * CustomErrorRule , CustomErrorRule , customErrorRule , cerIsErrorType , cerSelector -- * V1Beta1EnableConsumerResponse , V1Beta1EnableConsumerResponse , v1Beta1EnableConsumerResponse -- * OptionValue , OptionValue , optionValue , ovAddtional -- * EnumValue , EnumValue , enumValue , evName , evOptions , evNumber -- * Authentication , Authentication , authentication , aRules , aProviders -- * MetricDescriptorMetadataLaunchStage , MetricDescriptorMetadataLaunchStage (..) -- * V1EnableConsumerResponse , V1EnableConsumerResponse , v1EnableConsumerResponse -- * Mixin , Mixin , mixin , mRoot , mName -- * CustomHTTPPattern , CustomHTTPPattern , customHTTPPattern , chttppPath , chttppKind -- * UsageRule , UsageRule , usageRule , urSelector , urAllowUnregisteredCalls , urSkipServiceControl -- * StatusDetailsItem , StatusDetailsItem , statusDetailsItem , sdiAddtional -- * Page , Page , page , pSubpages , pContent , pName -- * V1GenerateServiceAccountResponse , V1GenerateServiceAccountResponse , v1GenerateServiceAccountResponse , vgsarAccount -- * AuthenticationRule , AuthenticationRule , authenticationRule , arRequirements , arSelector , arAllowWithoutCredential , arOAuth -- * V1AddVisibilityLabelsResponse , V1AddVisibilityLabelsResponse , v1AddVisibilityLabelsResponse , vavlrLabels -- * ServiceAccountConfig , ServiceAccountConfig , serviceAccountConfig , sacAccountId , sacTenantProjectRoles -- * V1Beta1QuotaOverride , V1Beta1QuotaOverride , v1Beta1QuotaOverride , vbqoAdminOverrideAncestor , vbqoMetric , vbqoOverrideValue , vbqoName , vbqoDimensions , vbqoUnit -- * LabelDescriptorValueType , LabelDescriptorValueType (..) -- * MetricRuleMetricCosts , MetricRuleMetricCosts , metricRuleMetricCosts , mrmcAddtional -- * V1Beta1ProducerQuotaPolicyDimensions , V1Beta1ProducerQuotaPolicyDimensions , v1Beta1ProducerQuotaPolicyDimensions , vbpqpdAddtional -- * DeleteTenantProjectRequest , DeleteTenantProjectRequest , deleteTenantProjectRequest , dtprTag -- * TenantProjectPolicy , TenantProjectPolicy , tenantProjectPolicy , tppPolicyBindings -- * PolicyBinding , PolicyBinding , policyBinding , pbMembers , pbRole -- * APISyntax , APISyntax (..) -- * TypeSyntax , TypeSyntax (..) -- * Backend , Backend , backend , bRules -- * TenancyUnit , TenancyUnit , tenancyUnit , tuService , tuName , tuTenantResources , tuConsumer , tuCreateTime -- * Monitoring , Monitoring , monitoring , mProducerDestinations , mConsumerDestinations -- * LogDescriptor , LogDescriptor , logDescriptor , ldName , ldDisplayName , ldLabels , ldDescription -- * Method , Method , method , metRequestStreaming , metResponseTypeURL , metName , metResponseStreaming , metRequestTypeURL , metOptions , metSyntax -- * V1RefreshConsumerResponse , V1RefreshConsumerResponse , v1RefreshConsumerResponse -- * SystemParameters , SystemParameters , systemParameters , spRules -- * Documentation , Documentation , documentation , dSummary , dDocumentationRootURL , dRules , dPages , dServiceRootURL , dOverview -- * V1GenerateDefaultIdentityResponse , V1GenerateDefaultIdentityResponse , v1GenerateDefaultIdentityResponse , vgdirAttachStatus , vgdirRole , vgdirIdentity -- * V1Beta1ProducerQuotaPolicy , V1Beta1ProducerQuotaPolicy , v1Beta1ProducerQuotaPolicy , vbpqpMetric , vbpqpName , vbpqpContainer , vbpqpDimensions , vbpqpPolicyValue , vbpqpUnit -- * Xgafv , Xgafv (..) -- * MetricDescriptorMetadata , MetricDescriptorMetadata , metricDescriptorMetadata , mdmSamplePeriod , mdmIngestDelay , mdmLaunchStage -- * V1DefaultIdentity , V1DefaultIdentity , v1DefaultIdentity , vdiEmail , vdiTag , vdiUniqueId , vdiName -- * UndeleteTenantProjectRequest , UndeleteTenantProjectRequest , undeleteTenantProjectRequest , utprTag -- * SystemParameterRule , SystemParameterRule , systemParameterRule , sprSelector , sprParameters -- * V1GenerateDefaultIdentityResponseAttachStatus , V1GenerateDefaultIdentityResponseAttachStatus (..) -- * LabelDescriptor , LabelDescriptor , labelDescriptor , lKey , lValueType , lDescription -- * MonitoredResourceDescriptorLaunchStage , MonitoredResourceDescriptorLaunchStage (..) -- * V1Beta1DisableConsumerResponse , V1Beta1DisableConsumerResponse , v1Beta1DisableConsumerResponse -- * Usage , Usage , usage , uRequirements , uRules , uProducerNotificationChannel -- * FieldCardinality , FieldCardinality (..) -- * V1Beta1BatchCreateProducerOverridesResponse , V1Beta1BatchCreateProducerOverridesResponse , v1Beta1BatchCreateProducerOverridesResponse , vbbcporOverrides -- * HTTP , HTTP , hTTP , hRules , hFullyDecodeReservedExpansion -- * Type , Type , type' , tSourceContext , tOneofs , tName , tOptions , tFields , tSyntax -- * API , API , api , aSourceContext , aMixins , aMethods , aName , aVersion , aOptions , aSyntax -- * MonitoringDestination , MonitoringDestination , monitoringDestination , mdMetrics , mdMonitoredResource -- * OperationMetadata , OperationMetadata , operationMetadata , omAddtional -- * Endpoint , Endpoint , endpoint , eAllowCORS , eName , eTarget -- * OAuthRequirements , OAuthRequirements , oAuthRequirements , oarCanonicalScopes -- * TenantProjectConfig , TenantProjectConfig , tenantProjectConfig , tpcFolder , tpcServiceAccountConfig , tpcTenantProjectPolicy , tpcLabels , tpcServices , tpcBillingConfig -- * MetricDescriptorMetricKind , MetricDescriptorMetricKind (..) -- * CustomError , CustomError , customError , ceRules , ceTypes -- * QuotaLimit , QuotaLimit , quotaLimit , qlValues , qlFreeTier , qlMetric , qlName , qlDisplayName , qlDuration , qlDefaultLimit , qlDescription , qlUnit , qlMaxLimit -- * Option , Option , option , optValue , optName -- * Billing , Billing , billing , bConsumerDestinations -- * SourceInfo , SourceInfo , sourceInfo , siSourceFiles -- * QuotaLimitValues , QuotaLimitValues , quotaLimitValues , qlvAddtional -- * V1ServiceAccount , V1ServiceAccount , v1ServiceAccount , vsaEmail , vsaTag , vsaIAMAccountName , vsaUniqueId , vsaName -- * AttachTenantProjectRequest , AttachTenantProjectRequest , attachTenantProjectRequest , atprTag , atprExternalResource , atprReservedResource -- * Enum' , Enum' , enum , enuSourceContext , enuEnumvalue , enuName , enuOptions , enuSyntax -- * Logging , Logging , logging , lProducerDestinations , lConsumerDestinations -- * MethodSyntax , MethodSyntax (..) -- * RemoveTenantProjectRequest , RemoveTenantProjectRequest , removeTenantProjectRequest , rtprTag -- * SourceInfoSourceFilesItem , SourceInfoSourceFilesItem , sourceInfoSourceFilesItem , sisfiAddtional -- * Quota , Quota , quota , qLimits , qMetricRules -- * V1DisableConsumerResponse , V1DisableConsumerResponse , v1DisableConsumerResponse -- * HTTPRule , HTTPRule , hTTPRule , httprSelector , httprPost , httprBody , httprCustom , httprResponseBody , httprPatch , httprGet , httprAdditionalBindings , httprDelete , httprPut -- * ApplyTenantProjectConfigRequest , ApplyTenantProjectConfigRequest , applyTenantProjectConfigRequest , atpcrProjectConfig , atpcrTag -- * ListTenancyUnitsResponse , ListTenancyUnitsResponse , listTenancyUnitsResponse , lturTenancyUnits , lturNextPageToken -- * OperationResponse , OperationResponse , operationResponse , orAddtional -- * TenantResource , TenantResource , tenantResource , trStatus , trTag , trResource -- * TenantProjectConfigLabels , TenantProjectConfigLabels , tenantProjectConfigLabels , tpclAddtional -- * MetricDescriptorLaunchStage , MetricDescriptorLaunchStage (..) -- * V1RemoveVisibilityLabelsResponse , V1RemoveVisibilityLabelsResponse , v1RemoveVisibilityLabelsResponse , vrvlrLabels -- * AuthProvider , AuthProvider , authProvider , apJWKsURI , apAudiences , apJwtLocations , apId , apAuthorizationURL , apIssuer -- * BillingConfig , BillingConfig , billingConfig , bcBillingAccount -- * CreateTenancyUnitRequest , CreateTenancyUnitRequest , createTenancyUnitRequest , cturTenancyUnitId -- * ContextRule , ContextRule , contextRule , crSelector , crRequested , crAllowedRequestExtensions , crProvided , crAllowedResponseExtensions -- * AddTenantProjectRequest , AddTenantProjectRequest , addTenantProjectRequest , aProjectConfig , aTag ) where import Network.Google.Prelude import Network.Google.ServiceConsumerManagement.Types.Product import Network.Google.ServiceConsumerManagement.Types.Sum -- | Default request referring to version 'v1' of the Service Consumer Management API. This contains the host and root path used as a starting point for constructing service requests. serviceConsumerManagementService :: ServiceConfig serviceConsumerManagementService = defaultService (ServiceId "serviceconsumermanagement:v1") "serviceconsumermanagement.googleapis.com" -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-serviceconsumermanagement/gen/Network/Google/ServiceConsumerManagement/Types.hs
mpl-2.0
15,530
0
7
4,210
1,799
1,246
553
528
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Services.Versions.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes an existing Version resource. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.services.versions.delete@. module Network.Google.Resource.AppEngine.Apps.Services.Versions.Delete ( -- * REST Resource AppsServicesVersionsDeleteResource -- * Creating a Request , appsServicesVersionsDelete , AppsServicesVersionsDelete -- * Request Lenses , asvdXgafv , asvdUploadProtocol , asvdPp , asvdAccessToken , asvdUploadType , asvdVersionsId , asvdBearerToken , asvdAppsId , asvdServicesId , asvdCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.services.versions.delete@ method which the -- 'AppsServicesVersionsDelete' request conforms to. type AppsServicesVersionsDeleteResource = "v1" :> "apps" :> Capture "appsId" Text :> "services" :> Capture "servicesId" Text :> "versions" :> Capture "versionsId" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes an existing Version resource. -- -- /See:/ 'appsServicesVersionsDelete' smart constructor. data AppsServicesVersionsDelete = AppsServicesVersionsDelete' { _asvdXgafv :: !(Maybe Text) , _asvdUploadProtocol :: !(Maybe Text) , _asvdPp :: !Bool , _asvdAccessToken :: !(Maybe Text) , _asvdUploadType :: !(Maybe Text) , _asvdVersionsId :: !Text , _asvdBearerToken :: !(Maybe Text) , _asvdAppsId :: !Text , _asvdServicesId :: !Text , _asvdCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AppsServicesVersionsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asvdXgafv' -- -- * 'asvdUploadProtocol' -- -- * 'asvdPp' -- -- * 'asvdAccessToken' -- -- * 'asvdUploadType' -- -- * 'asvdVersionsId' -- -- * 'asvdBearerToken' -- -- * 'asvdAppsId' -- -- * 'asvdServicesId' -- -- * 'asvdCallback' appsServicesVersionsDelete :: Text -- ^ 'asvdVersionsId' -> Text -- ^ 'asvdAppsId' -> Text -- ^ 'asvdServicesId' -> AppsServicesVersionsDelete appsServicesVersionsDelete pAsvdVersionsId_ pAsvdAppsId_ pAsvdServicesId_ = AppsServicesVersionsDelete' { _asvdXgafv = Nothing , _asvdUploadProtocol = Nothing , _asvdPp = True , _asvdAccessToken = Nothing , _asvdUploadType = Nothing , _asvdVersionsId = pAsvdVersionsId_ , _asvdBearerToken = Nothing , _asvdAppsId = pAsvdAppsId_ , _asvdServicesId = pAsvdServicesId_ , _asvdCallback = Nothing } -- | V1 error format. asvdXgafv :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdXgafv = lens _asvdXgafv (\ s a -> s{_asvdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). asvdUploadProtocol :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdUploadProtocol = lens _asvdUploadProtocol (\ s a -> s{_asvdUploadProtocol = a}) -- | Pretty-print response. asvdPp :: Lens' AppsServicesVersionsDelete Bool asvdPp = lens _asvdPp (\ s a -> s{_asvdPp = a}) -- | OAuth access token. asvdAccessToken :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdAccessToken = lens _asvdAccessToken (\ s a -> s{_asvdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). asvdUploadType :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdUploadType = lens _asvdUploadType (\ s a -> s{_asvdUploadType = a}) -- | Part of \`name\`. See documentation of \`appsId\`. asvdVersionsId :: Lens' AppsServicesVersionsDelete Text asvdVersionsId = lens _asvdVersionsId (\ s a -> s{_asvdVersionsId = a}) -- | OAuth bearer token. asvdBearerToken :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdBearerToken = lens _asvdBearerToken (\ s a -> s{_asvdBearerToken = a}) -- | Part of \`name\`. Name of the resource requested. Example: -- apps\/myapp\/services\/default\/versions\/v1. asvdAppsId :: Lens' AppsServicesVersionsDelete Text asvdAppsId = lens _asvdAppsId (\ s a -> s{_asvdAppsId = a}) -- | Part of \`name\`. See documentation of \`appsId\`. asvdServicesId :: Lens' AppsServicesVersionsDelete Text asvdServicesId = lens _asvdServicesId (\ s a -> s{_asvdServicesId = a}) -- | JSONP asvdCallback :: Lens' AppsServicesVersionsDelete (Maybe Text) asvdCallback = lens _asvdCallback (\ s a -> s{_asvdCallback = a}) instance GoogleRequest AppsServicesVersionsDelete where type Rs AppsServicesVersionsDelete = Operation type Scopes AppsServicesVersionsDelete = '["https://www.googleapis.com/auth/cloud-platform"] requestClient AppsServicesVersionsDelete'{..} = go _asvdAppsId _asvdServicesId _asvdVersionsId _asvdXgafv _asvdUploadProtocol (Just _asvdPp) _asvdAccessToken _asvdUploadType _asvdBearerToken _asvdCallback (Just AltJSON) appEngineService where go = buildClient (Proxy :: Proxy AppsServicesVersionsDeleteResource) mempty
rueshyna/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Services/Versions/Delete.hs
mpl-2.0
6,646
0
22
1,659
1,013
587
426
149
1
module TransPCallWhile where import AbsWhile import Control.Monad.State import Data.List(insert,nub) import Data.Maybe(fromMaybe) import Lib(true,false) import Data.Data -- Data import Data.Generics.Schemes -- everywhere import Data.Generics.Aliases -- mkT -- import qualified Data.Map.Strict as Map ------------------------------------------------------------------------------ -- Inline procedure calls ------------------------------------------------------------------------------ -- mapping from procedure names to their bodies -- type Penv = Map.Map String (Ident,[Com],Ident) type Penv = [(String,(Ident,[Com],Ident))] type Rename a = State ([(String,String)],Penv,Int) a mkPenv :: Program -> Penv mkPenv (Prog procs) = f procs where f (AProc pNameOp ident1 coms ident2 : procs) = case pNameOp of NoName -> f procs Name (Ident name) -> (name,(ident1,coms,ident2)) : f procs f [] = error "No procedure has a procedure name." doInline :: Program -> Program doInline prog = evalState (inline prog) ([],mkPenv prog,0) class RenameC a where inline :: a -> Rename a instance RenameC Program where inline (Prog procs) = liftM Prog (mapM inline procs) instance RenameC Proc where inline (AProc pnameop ident1 coms ident2) = do coms' <- mapM inline coms return $ AProc pnameop ident1 coms' ident2 instance RenameC Com where inline x = case x of CAsn ident exp -> return $ CAsn ident exp CProc (Ident s2) (Ident pname) (Ident s1) -> do (env,penv,n) <- get let Just (Ident s1',coms,Ident s2') = lookup pname penv let vs = varsComs coms let env' = (s1',s1) : (s2',s2) : zip vs (map (++"'"++show n) vs) put (env',penv,n+1) result <- mapM inline coms (_,_,n') <- get put (env,penv,n') return $ CBlk result CLoop exp coms -> do coms' <- mapM inline coms return $ CLoop exp coms' CIf exp coms cElseOp -> do coms' <- mapM inline coms cElseOp' <- inline cElseOp return $ CIf exp coms' cElseOp' CCase exp patComTs -> do patComTs' <- mapM inline patComTs return $ CCase exp patComTs' CBlk coms -> do coms' <- mapM inline coms return $ CBlk coms' CShow exp -> return (CShow exp) instance RenameC PatComT where inline (PatCom pat com) = do com' <- inline com return $ PatCom pat com' instance RenameC CElseOp where inline x = case x of ElseNone -> return ElseNone ElseOne coms -> do coms' <- mapM inline coms return $ ElseOne coms' ------------------------------------------------------------------------------ -- 変数をリストに集める ------------------------------------------------------------------------------ -- vars :: Data a => a -> [String] -- vars = everything (++) (mkQ [] varsCom) varsComs :: [Com] -> [String] varsComs coms = nub $ concatMap varsCom coms varsCom :: Com -> [String] varsCom x = case x of CAsn (Ident str) exp -> str : varsExp exp CProc (Ident str1) ident2 (Ident str2) -> [str1,str2] CLoop exp coms -> varsExp exp ++ concatMap varsCom coms CShow exp -> varsExp exp varsExp :: Exp -> [String] varsExp x = case x of ECons exp1 exp2 -> varsExp exp1 ++ varsExp exp2 EConsp exp -> varsExp exp EAtomp ident -> [] EHd exp -> varsExp exp ETl exp -> varsExp exp EEq exp1 exp2 -> varsExp exp1 ++ varsExp exp2 EListRep exps tl -> concatMap varsExp exps EVar (Ident str) -> [str] EVal val -> [] EConsStar exps -> concatMap varsExp exps EList exps -> concatMap varsExp exps ------------------------------------------------------------------------------ -- Expand if, PDF pp.34-35 ------------------------------------------------------------------------------ type RenameIf a = State Int a expandIf :: Data a => a -> a expandIf = everywhere (mkT tIf) tIf :: Com -> Com tIf x = case x of CLoop exp coms -> CLoop exp (map tIf coms) CIf exp coms celseop -> let comsNoIf = map tIf coms in case celseop of ElseNone -> CBlk [CAsn (Ident "_Z") exp, CLoop (EVar (Ident "_Z")) (CAsn (Ident "_Z") false : comsNoIf)] ElseOne coms' -> CBlk [CAsn (Ident "_Z") exp, CAsn (Ident "_W") true, CLoop (EVar (Ident "_Z")) (CAsn (Ident "_Z") false : comsNoIf ++ [CAsn (Ident "_W") false]), CLoop (EVar (Ident "_W")) (CAsn (Ident "_W") false : map tIf coms')] _ -> x
tetsuo-jp/while-C-ocaml
src/desugar/TransPCallWhile.hs
agpl-3.0
4,588
0
21
1,168
1,596
791
805
102
11
{-# LANGUAGE DerivingVia, StandaloneDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module ProjectM36.Serialise.DatabaseContextFunctionError where import Codec.Winery import ProjectM36.DatabaseContextFunctionError deriving via WineryVariant DatabaseContextFunctionError instance Serialise DatabaseContextFunctionError
agentm/project-m36
src/lib/ProjectM36/Serialise/DatabaseContextFunctionError.hs
unlicense
322
0
6
24
34
20
14
-1
-1
import MyUsefulFunctions (primes, isPrime) import Data.Bits import Data.Word import System.IO type JamcoinType = Word16 asBase::JamcoinType->Int->Int asBase l b = asBase_helper l b 0 asBase_helper::Word16->Int->Int->Int asBase_helper 0 _ acc = acc asBase_helper x b acc = asBase_helper (shiftR x 1) b (if (testBit x 0) then b*acc+1 else b*acc) compositeProof::(Integral a)=>a->a compositeProof n = head . filter (\p->mod n p == 0) $ primes isJamcoin::JamcoinType->Bool isJamcoin coin = testBit coin 0 {- && testBit coin (n - 1)-} && all (not . isPrime . asBase coin) [2..10] toBinString::JamcoinType->String toBinString 0 = [] toBinString b = (if testBit b 0 then '1' else '0'):toBinString (shiftR b 1) main = output >>= \handle-> (printCase handle >> let jamcoins = take j $ (filter (isJamcoin . fromIntegral) [firstCoin, firstCoin+2..shiftL 1 n - 1]::[Word16]) in mapM_ (hPutStrLn handle . outputJamcoin) $ do aCoin <- jamcoins let baseExpressions = map (asBase aCoin) [2..10] return (toBinString aCoin, (map (fromIntegral . compositeProof) baseExpressions)) ) where firstCoin = (shiftL 1 (pred n) + 1) printCase handle = hPutStrLn handle "Case #1:" n::Int n = 16 j::Int j = 50 outputJamcoin::(String, [Int])->String outputJamcoin (rep, proof) = rep ++ " " ++ spaceSep proof spaceSep [] = [] spaceSep (x:[]) = show x spaceSep (x:xs) = show x ++ ' ':spaceSep xs
Crazycolorz5/Haskell-Code
CoinJam.hs
unlicense
1,418
0
19
266
638
331
307
34
2
{-# LANGUAGE OverloadedStrings #-} import Control.Monad (forM_, when) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Resource (release) import Data.Int import qualified Data.Text as T import Data.Vector.Storable (Vector, (!)) import qualified Data.Vector.Storable as V import Data.Word import Graphics.ImageMagick.MagickWand import Graphics.ImageMagick.MagickWand.FFI.Types import System.Exit import Text.Printf (printf) throwAPIException w = undefined exitWithMessage msg = liftIO $ do putStrLn msg exitFailure iterateWand magick_wand = magickIterate magick_wand $ \w -> do i <- getIteratorIndex w s <- getImageScene w liftIO $ putStrLn $ printf "index %2d scene %2d" i s main :: IO () main = withMagickWandGenesis $ do (_,magick_wand) <- magickWand setSize magick_wand 640 480 size <- getSize magick_wand when (size /= (640,480)) $ exitWithMessage "Unexpected magick wand size" liftIO $ putStrLn "Reading images...\n" readImage magick_wand "sequence.miff" n <- getNumberImages magick_wand when (n /= 5) $ liftIO $ putStrLn $ printf "read %02d images; expected 5" n liftIO $ putStrLn "Iterate forward..." iterateWand magick_wand liftIO $ putStrLn "Iterate reverse..." magickIterateReverse magick_wand $ \w -> do i <- getIteratorIndex w s <- getImageScene w liftIO $ putStrLn $ printf "index %2d scene %2d" i s liftIO $ putStrLn "Remove scene 1..." setIteratorIndex magick_wand 1 (clone_key,clone_wand) <- getImage magick_wand removeImage magick_wand iterateWand magick_wand liftIO $ putStrLn "Insert scene 1 back in sequence..." setIteratorIndex magick_wand 0 addImage magick_wand clone_wand iterateWand magick_wand liftIO $ putStrLn "Set scene 2 to scene 1..." setIteratorIndex magick_wand 2 setImage magick_wand clone_wand release clone_key iterateWand magick_wand liftIO $ putStrLn "Apply image processing options..." cropImage magick_wand 60 60 10 10 resetIterator magick_wand background <- pixelWand background `setColor` "#000000" rotateImage magick_wand background 90.0 border <- pixelWand background `setColor` "green" border `setColor` "black" floodfillPaintImage magick_wand compositeChannels background (0.01*quantumRange) border 0 0 False (drawing_key,drawing_wand) <- drawingWand pushDrawingWand drawing_wand rotate drawing_wand 45 drawing_wand `setFontSize` 18 fill <- pixelWand fill `setColor` "green" drawing_wand `setFillColor` fill -- ? fill=DestroyPixelWand(fill); drawAnnotation drawing_wand 15 5 "Magick" popDrawingWand drawing_wand setIteratorIndex magick_wand 1 drawImage magick_wand drawing_wand annotateImage magick_wand drawing_wand 70 5 90 "Image" release drawing_key let primary_colors = [ 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 255, 0, 255, 255, 255, 0, 128, 128, 128 ] :: [Word8] setIteratorIndex magick_wand 2 importImagePixels magick_wand 10 10 3 3 "RGB" primary_colors pixels <- exportImagePixels magick_wand 10 10 3 3 "RGB" when (pixels /= primary_colors) $ exitWithMessage "Get pixels does not match set pixels" setIteratorIndex magick_wand 3 resizeImage magick_wand 50 50 undefinedFilter 1.0 magickIterate magick_wand $ \w -> do setImageDepth w 8 setImageCompression w rleCompression resetIterator magick_wand setIteratorIndex magick_wand 4 liftIO $ putStrLn "Utilitize pixel iterator to draw diagonal..." (iterator_key,iterator) <- pixelIterator magick_wand pixelRows <- pixelIterateList iterator forM_ (zip [0..] pixelRows) $ \(i, pixelRow) -> do pixelRow!i `setColor` "#224466" pixelSyncIterator iterator release iterator_key liftIO $ putStrLn "Write to wandtest_out.miff..." writeImages magick_wand "wandtest_out.miff" True liftIO $ putStrLn "Change image format from \"MIFF\" to \"GIF\"..." setImageFormat magick_wand "GIF" let wandDelay = 3 newDelay = 100 * wandDelay liftIO $ putStrLn $ printf "Set delay between frames to %d seconds..." wandDelay setImageDelay magick_wand newDelay delay <- getImageDelay magick_wand when (delay /= newDelay) $ exitWithMessage "Get delay does not match set delay" liftIO $ putStrLn "Write to wandtest_out.gif..." writeImages magick_wand "wandtest_out.gif" True let customOption = "custom option" customOptionName = "wand:custom-option" liftIO $ putStrLn "Set, list, get, and delete wand option..." setOption magick_wand customOptionName customOption option <- getOption magick_wand customOptionName when (option /= customOption) $ exitWithMessage "Option does not match" options <- getOptions magick_wand "*" forM_ options $ \o -> liftIO $ putStrLn $ printf " %s" (T.unpack o) deleteOption magick_wand customOptionName let customPropertyName = "wand:custom-property" customProperty = "custom profile" liftIO $ putStrLn "Set, list, get, and delete wand property..." setImageProperty magick_wand customPropertyName customProperty property <- getImageProperty magick_wand customPropertyName when (property /= customProperty) $ exitWithMessage "Property does not match" properties <- getImageProperties magick_wand "*" forM_ properties $ \p -> liftIO $ putStrLn $ printf " %s" (T.unpack p) deleteImageProperty magick_wand customPropertyName let profileName = "sRGB" liftIO $ putStrLn "Set, list, get, and remove sRGB color profile..." setImageProfile magick_wand profileName sRGBProfile profile <- getImageProfile magick_wand profileName when (profile /= sRGBProfile) $ exitWithMessage "Profile does not match" profiles <- getImageProfiles magick_wand "*" forM_ profiles $ \p -> liftIO $ putStrLn $ printf " %s" (T.unpack p) removedProfile <- removeImageProfile magick_wand profileName when (removedProfile /= sRGBProfile) $ exitWithMessage "Profile does not match" liftIO $ putStrLn "Wand tests pass." -- only first 24 bytes from wandtest.c taken (no actual need for 60k profile) sRGBProfile :: Vector Word8 sRGBProfile = V.fromList [ 0x00, 0x00, 0xee, 0x20, 0x00, 0x00, 0x00, 0x00, 0x04, 0x20, 0x00, 0x00, 0x73, 0x70, 0x61, 0x63, 0x52, 0x47, 0x42, 0x20, 0x4c, 0x61, 0x62, 0x20 ]
flowbox-public/imagemagick
examples/wandtest.hs
apache-2.0
6,566
0
14
1,419
1,693
806
887
149
1
{-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE AutoDeriveTypeable #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.Writer.Strict -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- The strict 'WriterT' monad transformer, which adds collection of -- outputs (such as a count or string output) to a given monad. -- -- This monad transformer provides only limited access to the output -- during the computation. For more general access, use -- "Control.Monad.Trans.State" instead. -- -- This version builds its output strictly; for a lazy version with -- the same interface, see "Control.Monad.Trans.Writer.Lazy". -- Although the output is built strictly, it is not possible to -- achieve constant space behaviour with this transformer: for that, -- use "Control.Monad.Trans.State.Strict" instead. ----------------------------------------------------------------------------- module Control.Monad.Trans.Writer.Strict ( -- * The Writer monad Writer, writer, runWriter, execWriter, mapWriter, -- * The WriterT monad transformer WriterT(..), execWriterT, mapWriterT, -- * Writer operations tell, listen, listens, pass, censor, -- * Lifting other operations liftCallCC, liftCatch, ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Data.Functor.Classes import Data.Functor.Identity import Control.Applicative import Control.Monad import Control.Monad.Fix import Control.Monad.Signatures import Data.Foldable (Foldable(foldMap)) import Data.Monoid import Data.Traversable (Traversable(traverse)) -- --------------------------------------------------------------------------- -- | A writer monad parameterized by the type @w@ of output to accumulate. -- -- The 'return' function produces the output 'mempty', while @>>=@ -- combines the outputs of the subcomputations using 'mappend'. type Writer w = WriterT w Identity -- | Construct a writer computation from a (result, output) pair. -- (The inverse of 'runWriter'.) writer :: (Monad m) => (a, w) -> WriterT w m a writer = WriterT . return -- | Unwrap a writer computation as a (result, output) pair. -- (The inverse of 'writer'.) runWriter :: Writer w a -> (a, w) runWriter = runIdentity . runWriterT -- | Extract the output from a writer computation. -- -- * @'execWriter' m = 'snd' ('runWriter' m)@ execWriter :: Writer w a -> w execWriter m = snd (runWriter m) -- | Map both the return value and output of a computation using -- the given function. -- -- * @'runWriter' ('mapWriter' f m) = f ('runWriter' m)@ mapWriter :: ((a, w) -> (b, w')) -> Writer w a -> Writer w' b mapWriter f = mapWriterT (Identity . f . runIdentity) -- --------------------------------------------------------------------------- -- | A writer monad parameterized by: -- -- * @w@ - the output to accumulate. -- -- * @m@ - The inner monad. -- -- The 'return' function produces the output 'mempty', while @>>=@ -- combines the outputs of the subcomputations using 'mappend'. newtype WriterT w m a = WriterT { runWriterT :: m (a, w) } instance (Eq w, Eq1 m, Eq a) => Eq (WriterT w m a) where WriterT x == WriterT y = eq1 x y instance (Ord w, Ord1 m, Ord a) => Ord (WriterT w m a) where compare (WriterT x) (WriterT y) = compare1 x y instance (Read w, Read1 m, Read a) => Read (WriterT w m a) where readsPrec = readsData $ readsUnary1 "WriterT" WriterT instance (Show w, Show1 m, Show a) => Show (WriterT w m a) where showsPrec d (WriterT m) = showsUnary1 "WriterT" d m instance (Eq w, Eq1 m) => Eq1 (WriterT w m) where eq1 = (==) instance (Ord w, Ord1 m) => Ord1 (WriterT w m) where compare1 = compare instance (Read w, Read1 m) => Read1 (WriterT w m) where readsPrec1 = readsPrec instance (Show w, Show1 m) => Show1 (WriterT w m) where showsPrec1 = showsPrec -- | Extract the output from a writer computation. -- -- * @'execWriterT' m = 'liftM' 'snd' ('runWriterT' m)@ execWriterT :: (Monad m) => WriterT w m a -> m w execWriterT m = do (_, w) <- runWriterT m return w -- | Map both the return value and output of a computation using -- the given function. -- -- * @'runWriterT' ('mapWriterT' f m) = f ('runWriterT' m)@ mapWriterT :: (m (a, w) -> n (b, w')) -> WriterT w m a -> WriterT w' n b mapWriterT f m = WriterT $ f (runWriterT m) instance (Functor m) => Functor (WriterT w m) where fmap f = mapWriterT $ fmap $ \ (a, w) -> (f a, w) instance (Foldable f) => Foldable (WriterT w f) where foldMap f = foldMap (f . fst) . runWriterT instance (Traversable f) => Traversable (WriterT w f) where traverse f = fmap WriterT . traverse f' . runWriterT where f' (a, b) = fmap (\ c -> (c, b)) (f a) instance (Monoid w, Applicative m) => Applicative (WriterT w m) where pure a = WriterT $ pure (a, mempty) f <*> v = WriterT $ liftA2 k (runWriterT f) (runWriterT v) where k (a, w) (b, w') = (a b, w `mappend` w') instance (Monoid w, Alternative m) => Alternative (WriterT w m) where empty = WriterT empty m <|> n = WriterT $ runWriterT m <|> runWriterT n instance (Monoid w, Monad m) => Monad (WriterT w m) where return a = writer (a, mempty) m >>= k = WriterT $ do (a, w) <- runWriterT m (b, w') <- runWriterT (k a) return (b, w `mappend` w') fail msg = WriterT $ fail msg instance (Monoid w, MonadPlus m) => MonadPlus (WriterT w m) where mzero = WriterT mzero m `mplus` n = WriterT $ runWriterT m `mplus` runWriterT n instance (Monoid w, MonadFix m) => MonadFix (WriterT w m) where mfix m = WriterT $ mfix $ \ ~(a, _) -> runWriterT (m a) instance (Monoid w) => MonadTrans (WriterT w) where lift m = WriterT $ do a <- m return (a, mempty) instance (Monoid w, MonadIO m) => MonadIO (WriterT w m) where liftIO = lift . liftIO -- | @'tell' w@ is an action that produces the output @w@. tell :: (Monad m) => w -> WriterT w m () tell w = writer ((), w) -- | @'listen' m@ is an action that executes the action @m@ and adds its -- output to the value of the computation. -- -- * @'runWriterT' ('listen' m) = 'liftM' (\\ (a, w) -> ((a, w), w)) ('runWriterT' m)@ listen :: (Monad m) => WriterT w m a -> WriterT w m (a, w) listen m = WriterT $ do (a, w) <- runWriterT m return ((a, w), w) -- | @'listens' f m@ is an action that executes the action @m@ and adds -- the result of applying @f@ to the output to the value of the computation. -- -- * @'listens' f m = 'liftM' (id *** f) ('listen' m)@ -- -- * @'runWriterT' ('listens' f m) = 'liftM' (\\ (a, w) -> ((a, f w), w)) ('runWriterT' m)@ listens :: (Monad m) => (w -> b) -> WriterT w m a -> WriterT w m (a, b) listens f m = WriterT $ do (a, w) <- runWriterT m return ((a, f w), w) -- | @'pass' m@ is an action that executes the action @m@, which returns -- a value and a function, and returns the value, applying the function -- to the output. -- -- * @'runWriterT' ('pass' m) = 'liftM' (\\ ((a, f), w) -> (a, f w)) ('runWriterT' m)@ pass :: (Monad m) => WriterT w m (a, w -> w) -> WriterT w m a pass m = WriterT $ do ((a, f), w) <- runWriterT m return (a, f w) -- | @'censor' f m@ is an action that executes the action @m@ and -- applies the function @f@ to its output, leaving the return value -- unchanged. -- -- * @'censor' f m = 'pass' ('liftM' (\\ x -> (x,f)) m)@ -- -- * @'runWriterT' ('censor' f m) = 'liftM' (\\ (a, w) -> (a, f w)) ('runWriterT' m)@ censor :: (Monad m) => (w -> w) -> WriterT w m a -> WriterT w m a censor f m = WriterT $ do (a, w) <- runWriterT m return (a, f w) -- | Lift a @callCC@ operation to the new monad. liftCallCC :: (Monoid w) => CallCC m (a,w) (b,w) -> CallCC (WriterT w m) a b liftCallCC callCC f = WriterT $ callCC $ \ c -> runWriterT (f (\ a -> WriterT $ c (a, mempty))) -- | Lift a @catchE@ operation to the new monad. liftCatch :: Catch e m (a,w) -> Catch e (WriterT w m) a liftCatch catchE m h = WriterT $ runWriterT m `catchE` \ e -> runWriterT (h e)
holoed/Junior
lib/transformers-0.4.3.0/Control/Monad/Trans/Writer/Strict.hs
apache-2.0
8,312
0
14
1,786
2,292
1,251
1,041
113
1
module Physics.Collision ( isCollide -- isFacing )where import Physics.Motion import FRP.Yampa.VectorSpace as Yam isCollide :: Position -> Position -> Bool isCollide m1 m2 = pos1 == pos2 where pos1 = getGridPos m1 pos2 = getGridPos m2 isFacing :: Motion -> Motion -> Bool isFacing = undefined
no-moree-ria10/utsuEater
src/Physics/Collision.hs
apache-2.0
320
0
7
73
88
50
38
11
1
rfac 0 = 1 rfac n = n * rfac (n-1)
LJKitchen/ljk-luv-fp-foss
RecFac.hs
apache-2.0
35
0
8
11
31
15
16
2
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} -- | Internal implementation of the CRF model. module Data.CRF.Chain1.Constrained.Model ( FeatIx (..) , Model (..) , mkModel , valueL , featToIx , featToJustIx , featToJustInt , sgValue , sgIxs , obIxs , nextIxs , prevIxs ) where import Control.Applicative ((<$>), (<*>)) import Data.Maybe (fromJust) import Data.List (groupBy, sort) import Data.Function (on) import Data.Binary -- import qualified Data.Vector.Generic.Base as G -- import qualified Data.Vector.Generic.Mutable as G import qualified Data.Set as Set import qualified Data.Map as M import qualified Data.Vector.Unboxed as U import qualified Data.Vector as V import qualified Data.Number.LogFloat as L import Data.Vector.Unboxed.Deriving import Data.CRF.Chain1.Constrained.Feature import Data.CRF.Chain1.Constrained.Dataset.Internal hiding (fromList) import qualified Data.CRF.Chain1.Constrained.Dataset.Internal as A -- | A feature index. To every model feature a unique index is assigned. -- It is equall to -1 if there is no corresponding feature in the model. newtype FeatIx = FeatIx { unFeatIx :: Int } deriving ( Show, Eq, Ord, Binary ) derivingUnbox "FeatIx" [t| FeatIx -> Int |] [| unFeatIx |] [| FeatIx |] -- | A label and a feature index determined by that label. type LbIx = (Lb, FeatIx) dummyFeatIx :: FeatIx dummyFeatIx = FeatIx (-1) {-# INLINE dummyFeatIx #-} isDummy :: FeatIx -> Bool isDummy (FeatIx ix) = ix < 0 {-# INLINE isDummy #-} notDummy :: FeatIx -> Bool notDummy = not . isDummy {-# INLINE notDummy #-} -- | The model is actually a map from features to their respective potentials, -- but for the sake of efficiency the internal representation is more complex. data Model = Model { -- | Value (potential) of the model for feature index. values :: U.Vector Double -- | A map from features to feature indices , ixMap :: M.Map Feature FeatIx -- | A default set of labels. It is used on sentence positions for which -- no constraints are assigned. , r0 :: AVec Lb -- | Singular feature index for the given label. Index is equall to -1 -- if feature is not present in the model. , sgIxsV :: U.Vector FeatIx -- | Set of labels for the given observation which, together with the -- observation, constitute an observation feature of the model. , obIxsV :: V.Vector (AVec LbIx) -- | Set of ,,previous'' labels for the value of the ,,current'' label. -- Both labels constitute a transition feature present in the the model. , prevIxsV :: V.Vector (AVec LbIx) -- | Set of ,,next'' labels for the value of the ,,current'' label. -- Both labels constitute a transition feature present in the the model. , nextIxsV :: V.Vector (AVec LbIx) } instance Binary Model where put crf = do put $ values crf put $ ixMap crf put $ r0 crf put $ sgIxsV crf put $ obIxsV crf put $ prevIxsV crf put $ nextIxsV crf get = Model <$> get <*> get <*> get <*> get <*> get <*> get <*> get -- | Construct CRF model from the associations list. We assume that -- the set of labels is of the {0, 1, .. 'lbMax'} form and, similarly, -- the set of observations is of the {0, 1, .. 'obMax'} form. -- There should be no repetition of features in the input list. -- TODO: We can change this function to take M.Map Feature Double. fromList :: Ob -> Lb -> [(Feature, Double)] -> Model fromList obMax' lbMax' fs = let _ixMap = M.fromList $ zip (map fst fs) (map FeatIx [0..]) sFeats = [feat | (feat, _val) <- fs, isSFeat feat] tFeats = [feat | (feat, _val) <- fs, isTFeat feat] oFeats = [feat | (feat, _val) <- fs, isOFeat feat] obMax = unOb obMax' lbMax = unLb lbMax' _r0 = A.fromList (map Lb [0 .. lbMax]) -- obMax = (unOb . maximum . Set.toList . obSet) (map fst fs) -- lbs = (Set.toList . lbSet) (map fst fs) -- lbMax = (unLb . maximum) lbs -- _r0 = A.fromList lbs _sgIxsV = sgVects lbMax [ (unLb x, featToJustIx crf feat) | feat@(SFeature x) <- sFeats ] _prevIxsV = adjVects lbMax [ (unLb x, (y, featToJustIx crf feat)) | feat@(TFeature x y) <- tFeats ] _nextIxsV = adjVects lbMax [ (unLb y, (x, featToJustIx crf feat)) | feat@(TFeature x y) <- tFeats ] _obIxsV = adjVects obMax [ (unOb o, (x, featToJustIx crf feat)) | feat@(OFeature o x) <- oFeats ] -- | Adjacency vectors. adjVects n xs = V.replicate (n + 1) (A.fromList []) V.// update where update = map mkVect $ groupBy ((==) `on` fst) $ sort xs mkVect (y:ys) = (fst y, A.fromList $ map snd (y:ys)) mkVect [] = error "mkVect: null list" sgVects n xs = U.replicate (n + 1) dummyFeatIx U.// xs _values = U.replicate (length fs) 0.0 U.// [ (featToJustInt crf feat, val) | (feat, val) <- fs ] crf = Model _values _ixMap _r0 _sgIxsV _obIxsV _prevIxsV _nextIxsV in crf -- -- | Compute the set of observations. -- obSet :: [Feature] -> Set.Set Ob -- obSet = -- Set.fromList . concatMap toObs -- where -- toObs (OFeature o _) = [o] -- toObs _ = [] -- -- -- | Compute the set of labels. -- lbSet :: [Feature] -> Set.Set Lb -- lbSet = -- Set.fromList . concatMap toLbs -- where -- toLbs (SFeature x) = [x] -- toLbs (OFeature _ x) = [x] -- toLbs (TFeature x y) = [x, y] -- | Construct the model from the list of features. All parameters will be -- set to 0. There can be repetitions in the input list. -- We assume that the set of labels is of the {0, 1, .. 'lbMax'} form and, -- similarly, the set of observations is of the {0, 1, .. 'obMax'} form. mkModel :: Ob -> Lb -> [Feature] -> Model mkModel obMax lbMax fs = let fSet = Set.fromList fs fs' = Set.toList fSet vs = replicate (Set.size fSet) 0.0 in fromList obMax lbMax (zip fs' vs) -- | Model potential defined for the given feature interpreted as a -- number in logarithmic domain. valueL :: Model -> FeatIx -> L.LogFloat valueL crf (FeatIx i) = L.logToLogFloat (values crf U.! i) {-# INLINE valueL #-} -- | Determine index for the given feature. featToIx :: Model -> Feature -> Maybe FeatIx featToIx crf feat = M.lookup feat (ixMap crf) {-# INLINE featToIx #-} -- | Determine index for the given feature. Throw error when -- the feature is not a member of the model. featToJustIx :: Model -> Feature -> FeatIx featToJustIx _crf = fromJust . featToIx _crf {-# INLINE featToJustIx #-} -- | Determine index for the given feature and return it as an integer. -- Throw error when the feature is not a member of the model. featToJustInt :: Model -> Feature -> Int featToJustInt _crf = unFeatIx . featToJustIx _crf {-# INLINE featToJustInt #-} -- | Potential value (in log domain) of the singular feature with the -- given label. The value defaults to 1 (0 in log domain) when the feature -- is not a member of the model. sgValue :: Model -> Lb -> L.LogFloat sgValue crf (Lb x) = case unFeatIx (sgIxsV crf U.! x) of -1 -> L.logToLogFloat (0 :: Double) ix -> L.logToLogFloat (values crf U.! ix) -- | List of labels which can be located on the first position of -- a sentence together with feature indices determined by them. sgIxs :: Model -> [LbIx] sgIxs crf = filter (notDummy . snd) . zip (map Lb [0..]) . U.toList $ sgIxsV crf {-# INLINE sgIxs #-} -- | List of labels which constitute a valid feature in combination with -- the given observation accompanied by feature indices determined by -- these labels. obIxs :: Model -> Ob -> AVec LbIx obIxs crf x = obIxsV crf V.! unOb x {-# INLINE obIxs #-} -- | List of ,,next'' labels which constitute a valid feature in combination -- with the ,,current'' label accompanied by feature indices determined by -- ,,next'' labels. nextIxs :: Model -> Lb -> AVec LbIx nextIxs crf x = nextIxsV crf V.! unLb x {-# INLINE nextIxs #-} -- | List of ,,previous'' labels which constitute a valid feature in -- combination with the ,,current'' label accompanied by feature indices -- determined by ,,previous'' labels. prevIxs :: Model -> Lb -> AVec LbIx prevIxs crf x = prevIxsV crf V.! unLb x {-# INLINE prevIxs #-}
kawu/crf-chain1-constrained
src/Data/CRF/Chain1/Constrained/Model.hs
bsd-2-clause
8,556
0
15
2,126
1,771
992
779
134
2
-------------------------------------------------------------------------------- module WhatMorphism.DirectedGraph ( DirectedGraph , fromNode , fromEdge , fromEdges , nodes , neighbours , delete ) where -------------------------------------------------------------------------------- import Data.Map (Map) import qualified Data.Map as M import Data.Maybe (fromMaybe) import Data.Monoid (Monoid (..)) import Data.Set (Set) import qualified Data.Set as S -------------------------------------------------------------------------------- newtype DirectedGraph a = DirectedGraph { unDirectedGraph :: Map a (Set a) } deriving (Show) -------------------------------------------------------------------------------- instance Ord a => Monoid (DirectedGraph a) where mempty = DirectedGraph M.empty mappend x y = DirectedGraph $ M.unionWith S.union (unDirectedGraph x) (unDirectedGraph y) -------------------------------------------------------------------------------- fromNode :: a -> DirectedGraph a fromNode x = DirectedGraph $ M.singleton x S.empty -------------------------------------------------------------------------------- fromEdge :: a -> a -> DirectedGraph a fromEdge x y = fromEdges x (S.singleton y) -------------------------------------------------------------------------------- fromEdges :: a -> Set a -> DirectedGraph a fromEdges x ys = DirectedGraph $ M.singleton x ys -------------------------------------------------------------------------------- nodes :: DirectedGraph a -> Set a nodes = M.keysSet . unDirectedGraph -------------------------------------------------------------------------------- neighbours :: Ord a => a -> DirectedGraph a -> Set a neighbours x (DirectedGraph m) = fromMaybe S.empty $ M.lookup x m -------------------------------------------------------------------------------- -- | Expensive... delete :: Ord a => a -> DirectedGraph a -> DirectedGraph a delete x (DirectedGraph m) = DirectedGraph $ M.map (S.delete x) $ M.delete x m
jaspervdj/what-morphism
src/WhatMorphism/DirectedGraph.hs
bsd-3-clause
2,102
0
10
337
466
248
218
33
1
import Distribution.PackageDescription import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Setup import System.Exit import System.Process import Data.Monoid ((<>)) main :: IO () main = defaultMainWithHooks simpleUserHooks { postBuild = installRtsPackage } installRtsPackage :: Args -> BuildFlags -> PackageDescription -> LocalBuildInfo -> IO () installRtsPackage _ _ _ _ = traceProcess (proc "idris" ["--install", "cil.ipkg"]) { cwd = Just "rts" } traceProcess :: CreateProcess -> IO () traceProcess args = do (code, stdout, stderr) <- readCreateProcessWithExitCode args "" case code of ExitFailure _ -> error $ stdout <> stderr _ -> return ()
bamboo/idris-cil
Setup.hs
bsd-3-clause
719
0
11
120
217
115
102
18
2
module ExactCover (Matrix, solve, solve', cover) where import Matrix import Data.List {-- Implementation of Donald Knuth's algorithm X in haskell. Algorithm X is a well known algorithm to solve the exact cover problem. Given a set X and a S, a collection of subsets of X, determine the collection of subsets S* of S that cover each element of X exactly once. For a more thorough explanation see http://en.wikipedia.org/wiki/Exact_cover For a similar approach in Python see: http://www.cs.mcgill.ca/~aassaf9/python/algorithm_x.html --} -- Select the column from the matrix which has the lowest count of occurences in the rows of the matrix selectColumn :: Ord c => Ord r => Matrix c r -> c selectColumn m = head $ getColumnsSorted m -- Solve the exact cover problem as encoded in the given matrix solve :: Ord c => Ord r => Matrix c r -> [r] solve matrix = solve' matrix [] -- The recursive function that does the actual heavy lifting of solving the exact cover problem. solve' :: Ord c => Ord r => Matrix c r->[r] -> [r] solve' [] solution = solution -- The base case, the reduced matrix is empty. solve' m solution = [s | let c = selectColumn m, -- Otherwise, select a column to be covered deterministically occurences m c > 0, -- If the element represented by column c is not contained in any row, terminate unsuccessfully, r <- getRows m c, -- nondeterministically choose a row that covers the element represented by column c let solution' = solution ++ [r], -- Include row r in the partial solution. let m' = cover m r, s <- solve' m' solution'] -- Repeat this algorithm recursively on the reduced matrix m' -- Cover the matrix with the given row. Remove the columns contained in that row and remove all other rows that contain at least one element also contained in the given row. cover :: Ord c => Ord r => Matrix c r -> r -> Matrix c r cover m r = deleteCols (columnsToDelete r) $ deleteRows (rowsToDelete r) m where columnsToDelete = getCols m rowsToDelete row = (nub . concat) $ map (getRows m) (getCols m row)
jaapterwoerds/algorithmx
src/ExactCover.hs
bsd-3-clause
2,328
0
11
673
392
199
193
-1
-1
module Data.Aeson.Versions ( SerializedVersion(..) , DeserializedVersion(..) , runSerializer , serialize , serialize' , serializeAll , serializeAll' , serializeLatest , serializeLatest' , runDeserializer , deserialize , deserialize' , deserializeLatest , deserializeLatest' , getSerializer , getSerializers , getDeserializer , getDeserializers , Serializer , Deserializer , FailableToJSON(..) , TraversableFromJSON(..) , FunctorToJSON(..) , Version(..) , CatMaybes(..) , V1 , V2 , V3 , V4 , V5 , v1 , v2 , v3 , v4 , v5 , pv1 , pv2 , pv3 , pv4 , pv5 , KnownVersion(..) , versionVal , UsingAeson(..) ) where import Data.Aeson.Versions.AesonExtensions import Data.Aeson.Versions.Internal import Data.Aeson.Versions.Version import Data.Aeson.Versions.CatMaybes
vfiles/aeson-versioned
src/Data/Aeson/Versions.hs
bsd-3-clause
1,923
0
5
1,264
202
139
63
47
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Mismi.S3.Internal ( f' , calculateChunks , calculateChunksCapped , bytesRange , sinkChan , sinkChanWithDelay , sinkQueue , waitForNResults , withFileSafe ) where import Control.Concurrent (Chan, readChan, threadDelay, writeChan) import Control.Monad.Catch (MonadCatch, onException) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Conduit (Source, ($$)) import qualified Data.Conduit.List as DC import qualified Data.Text as T import Data.UUID (toString) import Data.UUID.V4 (nextRandom) import P import Mismi (AWS, rawRunAWS) import Mismi.Amazonka (Env) import Mismi.S3.Data import Network.AWS.S3 (BucketName (..), ObjectKey (..)) import System.Directory (renameFile, removeFile) import System.IO (IO) import System.FilePath (FilePath, takeDirectory, takeFileName) import Twine.Data (Queue, writeQueue) f' :: (BucketName -> ObjectKey -> a) -> Address -> a f' f (Address (Bucket b) k) = BucketName b `f` ObjectKey (unKey k) calculateChunksCapped :: Int -> Int -> Int -> [(Int, Int, Int)] calculateChunksCapped size chunk' capped = calculateChunks size cappedChunk where minChunk = ceiling $ size' / capped' cappedChunk = max chunk' minChunk size' :: Double size' = fromIntegral size capped' :: Double capped' = fromIntegral capped -- filesize -> Chunk -> [(offset, chunk, index)] calculateChunks :: Int -> Int -> [(Int, Int, Int)] calculateChunks size chunk' = let chunk = max 1 chunk' go :: Int -> Int -> [(Int, Int, Int)] go !index offset = let !offset' = (offset + chunk) in if (offset' < size) then (offset, chunk, index) : go (index + 1) offset' else let !c' = (size - offset) in -- last chunk [(offset, c', index)] in go 1 0 -- http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 -- https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L1135 bytesRange :: Int -> Int -> Text bytesRange start end = T.pack $ "bytes=" <> show start <> "-" <> show end sinkChan :: MonadIO m => Source m a -> Chan a -> m Int sinkChan source c = sinkChanWithDelay 0 source c sinkChanWithDelay :: MonadIO m => Int -> Source m a -> Chan a -> m Int sinkChanWithDelay delay source c = source $$ DC.foldM (\i v -> liftIO $ threadDelay delay >> writeChan c v >> pure (i + 1)) 0 sinkQueue :: Env -> Source AWS a -> Queue a -> IO () sinkQueue e source q = rawRunAWS e (source $$ DC.mapM_ (liftIO . writeQueue q)) waitForNResults :: Int -> Chan a -> IO [a] waitForNResults i c = do let waitForDone acc = if (length acc == i) then pure acc else do r <- readChan c waitForDone (r : acc) waitForDone [] -- | Create a temporary file location that can be used safely, and on a successful operation, do an (atomic) rename -- NOTE: This function requires that the `FilePath` provided in the callback exists, otherwise throws an exception withFileSafe :: (MonadCatch m, MonadIO m) => FilePath -> (FilePath -> m a) -> m a withFileSafe f1 run = do uuid <- liftIO nextRandom >>= return . toString let f2 = takeDirectory f1 <> "/" <> "." <> takeFileName f1 <> "." <> uuid onException (run f2 >>= \a -> liftIO (renameFile f2 f1) >> return a) (liftIO $ removeFile f2)
ambiata/mismi
mismi-s3/src/Mismi/S3/Internal.hs
bsd-3-clause
3,641
0
17
915
1,110
594
516
81
2
module Lambda.Evaluator.Eval.Util ( gointoCaseRoute, ) where import DeepControl.Applicative import DeepControl.Monad import Lambda.Action import Lambda.Compiler import Lambda.DataType import qualified Lambda.DataType.PatternMatch as PM import qualified Lambda.DataType.Type as Ty import Lambda.Util ---------------------------------------------------------------------- -- gointoCaseRoute ---------------------------------------------------------------------- gointoCaseRoute :: Term -> [(PM, Term)] -> Lambda Term gointoCaseRoute x ((pm,t):pairs) = do if x == convert pm then (*:) t else case pairs of [] -> do e <- restore x throwEvalError $ strMsg $ "CASE: unexhausted pattern: "++ show e _ -> gointoCaseRoute x pairs
ocean0yohsuke/Simply-Typed-Lambda
src/Lambda/Evaluator/Eval/Util.hs
bsd-3-clause
791
0
15
150
187
107
80
18
3
{-# LANGUAGE ScopedTypeVariables #-} -- compile with: ghc -O2 --make Foo.hs -pgml /path/to/g++ module Main where import Sprng main = do seed <- newSeed gen1 :: RNG LFG <- newRng seed [gen2, gen3, gen4] <- spawnRng gen1 3 printRandInts gen1 10 printRandDoubles gen1 10 printRandInts gen2 10 printRandDoubles gen2 10 printRandInts gen3 10 printRandDoubles gen3 10 printRandInts gen4 10 printRandDoubles gen4 10 printRandInts :: SprngGen a => RNG a -> Int -> IO () printRandInts rng num = do printRng rng is <- sequence $ replicate num $ randomInt rng mapM_ print is printRandDoubles :: SprngGen a => RNG a -> Int -> IO () printRandDoubles rng num = do printRng rng ds <- sequence $ replicate num $ randomDouble rng mapM_ print ds
bjpop/haskell-sprng
examples/Simple.hs
bsd-3-clause
785
0
10
181
269
119
150
25
1
module TimeSeriesData.Summary where import TimeSeriesData.Types import Time import Control.Exception (assert) -- Intervals must be sorted in ascending order. Result in seconds groupByDay :: [Day] -> [TSInterval] -> [[TSInterval]] groupByDay [] _ = [] groupByDay days [] = replicate (length days) [] groupByDay (d:ds) intervals = (map trim a) : groupByDay ds nextIntervals where (a, b) = (span isNotAfterDay . dropWhile isBeforeDay) intervals isBeforeDay (_, end) = end <= dayStart isNotAfterDay (start, _) = start < dayEnd trim (start, end) = (max start dayStart, min end dayEnd) nextIntervals = if null a then b else let (start, end) = last a in if start < dayEnd && dayEnd < end then (last a) : b else b dayStart = dayToDiffTime d dayEnd = dayToDiffTime (addDays 1 d) dayToDiffTime = (flip diffUTCTime) refTime . localDayToUTC sumByDay :: [Day] -> [TSInterval] -> [Double] sumByDay ds xs = assert (sum (map durationOf xs) == sum result) result where result = map (foldr (+) 0 . map durationOf) $ groupByDay ds xs durationOf (s, e) = realToFrac (e - s) groupByDay' :: [Day] -> [NominalDiffTime] -> [[NominalDiffTime]] groupByDay' [] _ = [] groupByDay' (d:ds) events = a : groupByDay' ds b where (a, b) = (span isNotAfterDay . dropWhile isBeforeDay) events isBeforeDay t = t <= dayStart isNotAfterDay t = t <= dayEnd dayStart = dayToDiffTime d dayEnd = dayToDiffTime (addDays 1 d) dayToDiffTime = (flip diffUTCTime) refTime . localDayToUTC sumByDay' :: [Day] -> [NominalDiffTime] -> [Int] sumByDay' ds xs = assert (length xs == sum result) result where result = map length (groupByDay' ds xs)
hectorhon/autotrace2
src/TimeSeriesData/Summary.hs
bsd-3-clause
1,868
0
13
536
677
354
323
37
3
module Voting.Model where import HAppS.Server hiding (result) import Control.Monad import Control.Applicative import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Rfc2822 (local_part, dot_atom_text, atext) -- email address parsing import Voting.State vote :: Vote -> Web String vote (Vote (Left _)) = badRequest $ "Email address or vote is invalid" vote (Vote (Right (email, ballot))) = do success <- webUpdate $ AddVote email ballot if success then ok "Thanks for voting!" else badRequest "Oh, you already voted." result :: Web String result = do winners <- webQuery Result ok $ "Winners: " ++ show winners type Email = String newtype Vote = Vote (Either String (Email, Ballot)) -- TODO: Clean this up, check if candidates are within range? instance FromData Vote where fromData = do email <- look "email" vote <- look "vote" return $ case parse validEmailParser "" email of Left err -> Vote (Left $ show err) Right _ -> case parseBallot vote of Left err -> Vote (Left $ show err) Right ballot -> Vote (Right (email, ballot)) -- == Parsers -- Every Monad is an Applicative. instance Applicative (GenParser s a) where pure = return (<*>) = ap -- Every MonadPlus is an Alternative. instance Alternative (GenParser s a) where empty = mzero (<|>) = mplus -- A bit more restrictive than addr_text, since we always want a tld, and of at least 2 chars validEmailParser = (\somebody somewhere -> concat [ somebody, "@", somewhere ]) <$> local_part <* char '@' <*> domain where domain = (\subs top -> concat $ subs ++ [top]) <$> many1 (try subdomain) <*> tld subdomain = flip (++) "." <$> many1 atext <* char '.' tld = (:) <$> atext <*> many1 atext -- Parse the ballot (copied from Condorcet demo) parseBallot :: String -> Either ParseError Ballot parseBallot input = parse ballot "" input where ballot :: Parser [[Int]] ballot = sepBy1 rank (char ',') <* eof rank :: Parser [Int] rank = sepBy1 number (char '=') number :: Parser Int number = read <$> many1 digit
eelco/voting
Voting/Model.hs
bsd-3-clause
2,281
0
18
635
657
345
312
50
2
-- ------------------------------------------------------------ {- | Module : Yuuko.Text.XML.HXT.Arrow.Pickle.Xml Copyright : Copyright (C) 2005-2008 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt ([email protected]) Stability : experimental Portability: portable Pickler functions for converting between user defined data types and XmlTree data. Usefull for persistent storage and retreival of arbitray data as XML documents This module is an adaptation of the pickler combinators developed by Andrew Kennedy ( http:\/\/research.microsoft.com\/~akenn\/fun\/picklercombinators.pdf ) The difference to Kennedys approach is that the target is not a list of Chars but a list of XmlTrees. The basic picklers will convert data into XML text nodes. New are the picklers for creating elements and attributes. One extension was neccessary: The unpickling may fail. Therefore the unpickler has a Maybe result type. Failure is used to unpickle optional elements (Maybe data) and lists of arbitray length There is an example program demonstrating the use of the picklers for a none trivial data structure. (see \"examples\/arrows\/pickle\" directory) -} -- ------------------------------------------------------------ module Yuuko.Text.XML.HXT.Arrow.Pickle.Xml where import Data.Maybe import Data.Map (Map) import qualified Data.Map as M import Yuuko.Text.XML.HXT.DOM.Interface import qualified Yuuko.Text.XML.HXT.DOM.XmlNode as XN import Yuuko.Control.Arrow.ListArrows import Yuuko.Text.XML.HXT.Arrow.XmlArrow import Yuuko.Text.XML.HXT.Arrow.Pickle.Schema import Yuuko.Text.XML.HXT.Arrow.ReadDocument (xread) import Yuuko.Text.XML.HXT.Arrow.Edit (xshowEscapeXml) -- ------------------------------------------------------------ data St = St { attributes :: [XmlTree] , contents :: [XmlTree] } data PU a = PU { appPickle :: (a, St) -> St , appUnPickle :: St -> (Maybe a, St) , theSchema :: Schema } emptySt :: St emptySt = St { attributes = [] , contents = [] } addAtt :: XmlTree -> St -> St addAtt x s = s {attributes = x : attributes s} addCont :: XmlTree -> St -> St addCont x s = s {contents = x : contents s} dropCont :: St -> St dropCont s = s { contents = drop 1 (contents s) } getAtt :: QName -> St -> Maybe XmlTree getAtt qn s = listToMaybe $ runLA ( arrL attributes >>> isAttr >>> hasQName qn ) s getCont :: St -> Maybe XmlTree getCont s = listToMaybe . contents $ s -- ------------------------------------------------------------ -- | conversion of an arbitrary value into an XML document tree. -- -- The pickler, first parameter, controls the conversion process. -- Result is a complete document tree including a root node pickleDoc :: PU a -> a -> XmlTree pickleDoc p v = XN.mkRoot (attributes st) (contents st) where st = appPickle p (v, emptySt) -- | Conversion of an XML document tree into an arbitrary data type -- -- The inverse of 'pickleDoc'. -- This law should hold for all picklers: @ unpickle px . pickle px $ v == Just v @. -- Not every possible combination of picklers make sense. -- For reconverting a value from an XML tree, is becomes neccessary, -- to introduce \"enough\" markup for unpickling the value unpickleDoc :: PU a -> XmlTree -> Maybe a unpickleDoc p t | XN.isRoot t = fst . appUnPickle p $ St { attributes = fromJust . XN.getAttrl $ t , contents = XN.getChildren t } | otherwise = unpickleDoc p (XN.mkRoot [] [t]) -- ------------------------------------------------------------ -- | The zero pickler -- -- Encodes nothing, fails always during unpickling xpZero :: PU a xpZero = PU { appPickle = snd , appUnPickle = \ s -> (Nothing, s) , theSchema = scNull } -- unit pickler xpUnit :: PU () xpUnit = xpLift () -- | Lift a value to a pickler -- -- When pickling, nothing is encoded, when unpickling, the given value is inserted. -- This pickler always succeeds. xpLift :: a -> PU a xpLift x = PU { appPickle = snd , appUnPickle = \ s -> (Just x, s) , theSchema = scEmpty } -- | Lift a Maybe value to a pickler. -- -- @Nothing@ is mapped to the zero pickler, @Just x@ is pickled with @xpLift x@. xpLiftMaybe :: Maybe a -> PU a xpLiftMaybe v = (xpLiftMaybe' v) { theSchema = scOption scEmpty } where xpLiftMaybe' Nothing = xpZero xpLiftMaybe' (Just x) = xpLift x -- | pickle\/unpickle combinator for sequence and choice. -- -- When the first unpickler fails, -- the second one is taken, else the third one configured with the result from the first -- is taken. This pickler is a generalisation for 'xpSeq' and 'xpChoice' . -- -- The schema must be attached later, e.g. in xpPair or other higher level combinators xpCondSeq :: PU b -> (b -> a) -> PU a -> (a -> PU b) -> PU b xpCondSeq pd f pa k = PU { appPickle = ( \ (b, s) -> let a = f b pb = k a in appPickle pa (a, (appPickle pb (b, s))) ) , appUnPickle = ( \ s -> let (a, s') = appUnPickle pa s in case a of Nothing -> appUnPickle pd s Just a' -> appUnPickle (k a') s' ) , theSchema = undefined } -- | Combine two picklers sequentially. -- -- If the first fails during -- unpickling, the whole unpickler fails xpSeq :: (b -> a) -> PU a -> (a -> PU b) -> PU b xpSeq = xpCondSeq xpZero -- | combine tow picklers with a choice -- -- Run two picklers in sequence like with xpSeq. -- When during unpickling the first one fails, -- an alternative pickler (first argument) is applied. -- This pickler is only used as combinator for unpickling. xpChoice :: PU b -> PU a -> (a -> PU b) -> PU b xpChoice pb = xpCondSeq pb undefined -- | map value into another domain and apply pickler there -- -- One of the most often used picklers. xpWrap :: (a -> b, b -> a) -> PU a -> PU b xpWrap (i, j) pa = (xpSeq j pa (xpLift . i)) { theSchema = theSchema pa } -- | like 'xpWrap', but if the inverse mapping is undefined, the unpickler fails -- -- Map a value into another domain. If the inverse mapping is -- undefined (Nothing), the unpickler fails xpWrapMaybe :: (a -> Maybe b, b -> a) -> PU a -> PU b xpWrapMaybe (i, j) pa = (xpSeq j pa (xpLiftMaybe . i)) { theSchema = theSchema pa } -- | pickle a pair of values sequentially -- -- Used for pairs or together with wrap for pickling -- algebraic data types with two components xpPair :: PU a -> PU b -> PU (a, b) xpPair pa pb = ( xpSeq fst pa (\ a -> xpSeq snd pb (\ b -> xpLift (a,b))) ) { theSchema = scSeq (theSchema pa) (theSchema pb) } -- | Like 'xpPair' but for triples xpTriple :: PU a -> PU b -> PU c -> PU (a, b, c) xpTriple pa pb pc = xpWrap (toTriple, fromTriple) (xpPair pa (xpPair pb pc)) where toTriple ~(a, ~(b, c)) = (a, b, c ) fromTriple ~(a, b, c ) = (a, (b, c)) -- | Like 'xpPair' and 'xpTriple' but for 4-tuples xp4Tuple :: PU a -> PU b -> PU c -> PU d -> PU (a, b, c, d) xp4Tuple pa pb pc pd = xpWrap (toQuad, fromQuad) (xpPair pa (xpPair pb (xpPair pc pd))) where toQuad ~(a, ~(b, ~(c, d))) = (a, b, c, d ) fromQuad ~(a, b, c, d ) = (a, (b, (c, d))) -- | Like 'xpPair' and 'xpTriple' but for 5-tuples xp5Tuple :: PU a -> PU b -> PU c -> PU d -> PU e -> PU (a, b, c, d, e) xp5Tuple pa pb pc pd pe = xpWrap (toQuint, fromQuint) (xpPair pa (xpPair pb (xpPair pc (xpPair pd pe)))) where toQuint ~(a, ~(b, ~(c, ~(d, e)))) = (a, b, c, d, e ) fromQuint ~(a, b, c, d, e ) = (a, (b, (c, (d, e)))) -- | Like 'xpPair' and 'xpTriple' but for 6-tuples xp6Tuple :: PU a -> PU b -> PU c -> PU d -> PU e -> PU f -> PU (a, b, c, d, e, f) xp6Tuple pa pb pc pd pe pf = xpWrap (toSix, fromSix) (xpPair pa (xpPair pb (xpPair pc (xpPair pd (xpPair pe pf))))) where toSix ~(a, ~(b, ~(c, ~(d, ~(e, f))))) = (a, b, c, d, e, f ) fromSix ~(a, b, c, d, e, f) = (a, (b, (c, (d, (e, f))))) -- | Pickle a string into an XML text node -- -- One of the most often used primitive picklers. Attention: -- For pickling empty strings use 'xpText0'. If the text has a more -- specific datatype than xsd:string, use 'xpTextDT' xpText :: PU String xpText = xpTextDT scString1 -- | Pickle a string into an XML text node -- -- Text pickler with a description of the structure of the text -- by a schema. A schema for a data type can be defined by 'Yuuko.Text.XML.HXT.Arrow.Pickle.Schema.scDT'. -- In 'Yuuko.Text.XML.HXT.Arrow.Pickle.Schema' there are some more functions for creating -- simple datatype descriptions. xpTextDT :: Schema -> PU String xpTextDT sc = PU { appPickle = \ (s, st) -> addCont (XN.mkText s) st , appUnPickle = \ st -> fromMaybe (Nothing, st) (unpickleString st) , theSchema = sc } where unpickleString st = do t <- getCont st s <- XN.getText t return (Just s, dropCont st) -- | Pickle a possibly empty string into an XML node. -- -- Must be used in all places, where empty strings are legal values. -- If the content of an element can be an empty string, this string disapears -- during storing the DOM into a document and reparse the document. -- So the empty text node becomes nothing, and the pickler must deliver an empty string, -- if there is no text node in the document. xpText0 :: PU String xpText0 = xpText0DT scString1 -- | Pickle a possibly empty string with a datatype description into an XML node. -- -- Like 'xpText0' but with extra Parameter for datatype description as in 'xpTextDT'. xpText0DT :: Schema -> PU String xpText0DT sc = xpWrap (fromMaybe "", emptyToNothing) $ xpOption $ xpTextDT sc where emptyToNothing "" = Nothing emptyToNothing x = Just x -- | Pickle an arbitrary value by applyling show during pickling -- and read during unpickling. -- -- Real pickling is then done with 'xpText'. -- One of the most often used pimitive picklers. Applicable for all -- types which are instances of @Read@ and @Show@ xpPrim :: (Read a, Show a) => PU a xpPrim = xpWrapMaybe (readMaybe, show) xpText where readMaybe :: Read a => String -> Maybe a readMaybe str = val (reads str) where val [(x,"")] = Just x val _ = Nothing -- ------------------------------------------------------------ -- | Pickle an XmlTree by just adding it -- -- Usefull for components of type XmlTree in other data structures xpTree :: PU XmlTree xpTree = PU { appPickle = \ (s, st) -> addCont s st , appUnPickle = \ st -> fromMaybe (Nothing, st) (unpickleTree st) , theSchema = Any } where unpickleTree st = do t <- getCont st return (Just t, dropCont st) -- | Pickle a whole list of XmlTrees by just adding the list, unpickle is done by taking all element contens. -- -- This pickler should always combined with 'xpElem' for taking the whole contents of an element. xpTrees :: PU [XmlTree] xpTrees = (xpList xpTree) { theSchema = Any } -- | Pickle a string representing XML contents by inserting the tree representation into the XML document. -- -- Unpickling is done by converting the contents with -- 'Yuuko.Text.XML.HXT.Arrow.Edit.xshowEscapeXml' into a string, -- this function will escape all XML special chars, such that pickling the value back becomes save. -- Pickling is done with 'Yuuko.Text.XML.HXT.Arrow.ReadDocument.xread' xpXmlText :: PU String xpXmlText = xpWrap ( showXML, readXML ) $ xpTrees where showXML = concat . runLA ( xshowEscapeXml unlistA ) readXML = runLA xread -- ------------------------------------------------------------ -- | Encoding of optional data by ignoring the Nothing case during pickling -- and relying on failure during unpickling to recompute the Nothing case -- -- The default pickler for Maybe types xpOption :: PU a -> PU (Maybe a) xpOption pa = PU { appPickle = ( \ (a, st) -> case a of Nothing -> st Just x -> appPickle pa (x, st) ) , appUnPickle = appUnPickle $ xpChoice (xpLift Nothing) pa (xpLift . Just) , theSchema = scOption (theSchema pa) } -- | Optional conversion with default value -- -- The default value is not encoded in the XML document, -- during unpickling the default value is inserted if the pickler fails xpDefault :: (Eq a) => a -> PU a -> PU a xpDefault df = xpWrap ( fromMaybe df , \ x -> if x == df then Nothing else Just x ) . xpOption -- ------------------------------------------------------------ -- | Encoding of list values by pickling all list elements sequentially. -- -- Unpickler relies on failure for detecting the end of the list. -- The standard pickler for lists. Can also be used in combination with 'xpWrap' -- for constructing set and map picklers xpList :: PU a -> PU [a] xpList pa = PU { appPickle = ( \ (a, st) -> case a of [] -> st _:_ -> appPickle pc (a, st) ) , appUnPickle = appUnPickle $ xpChoice (xpLift []) pa (\ x -> xpSeq id (xpList pa) (\xs -> xpLift (x:xs))) , theSchema = scList (theSchema pa) } where pc = xpSeq head pa (\ x -> xpSeq tail (xpList pa) (\ xs -> xpLift (x:xs))) -- | Encoding of a none empty list of values -- -- Attention: when calling this pickler with an empty list, -- an internal error \"head of empty list is raised\". xpList1 :: PU a -> PU [a] xpList1 pa = ( xpWrap (\ (x, xs) -> x : xs ,\ (x : xs) -> (x, xs) ) $ xpPair pa (xpList pa) ) { theSchema = scList1 (theSchema pa) } -- ------------------------------------------------------------ -- | Standard pickler for maps -- -- This pickler converts a map into a list of pairs. -- All key value pairs are mapped to an element with name (1.arg), -- the key is encoded as an attribute named by the 2. argument, -- the 3. arg is the pickler for the keys, the last one for the values xpMap :: Ord k => String -> String -> PU k -> PU v -> PU (Map k v) xpMap en an xpk xpv = xpWrap ( M.fromList , M.toList ) $ xpList $ xpElem en $ xpPair ( xpAttr an $ xpk ) xpv -- ------------------------------------------------------------ -- | Pickler for sum data types. -- -- Every constructor is mapped to an index into the list of picklers. -- The index is used only during pickling, not during unpickling, there the 1. match is taken xpAlt :: (a -> Int) -> [PU a] -> PU a xpAlt tag ps = PU { appPickle = ( \ (a, st) -> let pa = ps !! (tag a) in appPickle pa (a, st) ) , appUnPickle = appUnPickle $ ( case ps of [] -> xpZero pa:ps1 -> xpChoice (xpAlt tag ps1) pa xpLift ) , theSchema = scAlts (map theSchema ps) } -- ------------------------------------------------------------ -- | Pickler for wrapping\/unwrapping data into an XML element -- -- Extra parameter is the element name given as a QName. THE pickler for constructing -- nested structures -- -- Example: -- -- > xpElemQN (mkName "number") $ xpickle -- -- will map an (42::Int) onto -- -- > <number>42</number> xpElemQN :: QName -> PU a -> PU a xpElemQN qn pa = PU { appPickle = ( \ (a, st) -> let st' = appPickle pa (a, emptySt) in addCont (XN.mkElement qn (attributes st') (contents st')) st ) , appUnPickle = \ st -> fromMaybe (Nothing, st) (unpickleElement st) , theSchema = scElem (qualifiedName qn) (theSchema pa) } where unpickleElement st = do t <- getCont st n <- XN.getElemName t if n /= qn then fail ("element name " ++ show n ++ " does not match" ++ show qn) else do let cs = XN.getChildren t al <- XN.getAttrl t res <- fst . appUnPickle pa $ St {attributes = al, contents = cs} return (Just res, dropCont st) -- | convenient Pickler for xpElemQN -- -- > xpElem n = xpElemQN (mkName n) xpElem :: String -> PU a -> PU a xpElem = xpElemQN . mkName -- ------------------------------------------------------------ -- | Pickler for wrapping\/unwrapping data into an XML element with an attribute with given value -- -- To make XML structures flexible but limit the number of different elements, it's sometimes -- useful to use a kind of generic element with a key value structure -- -- Example: -- -- > <attr name="key1">value1</attr> -- > <attr name="key2">value2</attr> -- > <attr name="key3">value3</attr> -- -- the Haskell datatype may look like this -- -- > type T = T { key1 :: Int ; key2 :: String ; key3 :: Double } -- -- Then the picker for that type looks like this -- -- > xpT :: PU T -- > xpT = xpWrap ( uncurry3 T, \ t -> (key1 t, key2 t, key3 t) ) $ -- > xpTriple (xpElemWithAttrValue "attr" "name" "key1" $ xpickle) -- > (xpElemWithAttrValue "attr" "name" "key2" $ xpText0) -- > (xpElemWithAttrValue "attr" "name" "key3" $ xpickle) xpElemWithAttrValue :: String -> String -> String -> PU a -> PU a xpElemWithAttrValue name an av pa = PU { appPickle = ( \ (a, st) -> let st' = appPickle pa' (a, emptySt) in addCont (XN.mkElement (mkName name) (attributes st') (contents st')) st ) , appUnPickle = \ st -> fromMaybe (Nothing, st) (unpickleElement st) , theSchema = scElem name (theSchema pa') } where pa' = xpAddFixedAttr an av $ pa noMatch = null . runLA ( isElem >>> hasName name >>> hasAttrValue an (==av) ) unpickleElement st = do t <- getCont st if noMatch t then fail "element name or attr value does not match" else do let cs = XN.getChildren t al <- XN.getAttrl t res <- fst . appUnPickle pa $ St {attributes = al, contents = cs} return (Just res, dropCont st) -- ------------------------------------------------------------ -- | Pickler for storing\/retreiving data into\/from an attribute value -- -- The attribute is inserted in the surrounding element constructed by the 'xpElem' pickler xpAttrQN :: QName -> PU a -> PU a xpAttrQN qn pa = PU { appPickle = ( \ (a, st) -> let st' = appPickle pa (a, emptySt) in addAtt (XN.mkAttr qn (contents st')) st ) , appUnPickle = \ st -> fromMaybe (Nothing, st) (unpickleAttr st) , theSchema = scAttr (qualifiedName qn) (theSchema pa) } where unpickleAttr st = do a <- getAtt qn st let av = XN.getChildren a res <- fst . appUnPickle pa $ St {attributes = [], contents = av} return (Just res, st) -- attribute is not removed from attribute list, -- attributes are selected by name -- | convenient Pickler for xpAttrQN -- -- > xpAttr n = xpAttrQN (mkName n) xpAttr :: String -> PU a -> PU a xpAttr = xpAttrQN . mkName -- | Add an optional attribute for an optional value (Maybe a). xpAttrImplied :: String -> PU a -> PU (Maybe a) xpAttrImplied name pa = xpOption $ xpAttr name pa xpAttrFixed :: String -> String -> PU () xpAttrFixed name val = ( xpWrapMaybe ( \ v -> if v == val then Just () else Nothing , const val ) $ xpAttr name xpText ) { theSchema = scAttr name (scFixed val) } -- | Add an attribute with a fixed value. -- -- Useful e.g. to declare namespaces. Is implemented by 'xpAttrFixed' xpAddFixedAttr :: String -> String -> PU a -> PU a xpAddFixedAttr name val pa = xpWrap ( snd , (,) () ) $ xpPair (xpAttrFixed name val) pa -- ------------------------------------------------------------ -- | The class for overloading 'xpickle', the default pickler class XmlPickler a where xpickle :: PU a instance XmlPickler Int where xpickle = xpPrim instance XmlPickler Integer where xpickle = xpPrim {- no instance of XmlPickler Char because then every text would be encoded char by char, because of the instance for lists instance XmlPickler Char where xpickle = xpPrim -} instance XmlPickler () where xpickle = xpUnit instance (XmlPickler a, XmlPickler b) => XmlPickler (a,b) where xpickle = xpPair xpickle xpickle instance (XmlPickler a, XmlPickler b, XmlPickler c) => XmlPickler (a,b,c) where xpickle = xpTriple xpickle xpickle xpickle instance (XmlPickler a, XmlPickler b, XmlPickler c, XmlPickler d) => XmlPickler (a,b,c,d) where xpickle = xp4Tuple xpickle xpickle xpickle xpickle instance (XmlPickler a, XmlPickler b, XmlPickler c, XmlPickler d, XmlPickler e) => XmlPickler (a,b,c,d,e) where xpickle = xp5Tuple xpickle xpickle xpickle xpickle xpickle instance XmlPickler a => XmlPickler [a] where xpickle = xpList xpickle instance XmlPickler a => XmlPickler (Maybe a) where xpickle = xpOption xpickle -- ------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Text/XML/HXT/Arrow/Pickle/Xml.hs
bsd-3-clause
21,043
288
18
5,267
5,317
2,899
2,418
300
2