code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} module Language.JsonGrammar.Serializer (serializeValue) where import Language.JsonGrammar.Grammar import Language.JsonGrammar.Util import Control.Applicative ((<$>), (<|>)) import Control.Monad ((>=>)) import qualified Data.Aeson as Ae import qualified Data.HashMap.Strict as H import qualified Data.Vector as V -- | Convert a 'Grammar' to a JSON serializer. serializeValue :: Grammar 'Val t1 t2 -> t2 -> Maybe t1 serializeValue = \case Id -> return g1 :. g2 -> serializeValue g1 >=> serializeValue g2 Empty -> fail "empty grammar" g1 :<> g2 -> \x -> serializeValue g1 x <|> serializeValue g2 x Pure _ f -> f Many g -> manyM (serializeValue g) Literal val -> return . (val :-) Label _ g -> serializeValue g Object g -> \x -> do (obj, y) <- serializeProperties g (H.empty, x) return (Ae.Object obj :- y) Array g -> \x -> do (arr, y) <- serializeElements g (V.empty, x) return (Ae.Array arr :- y) Coerce _ g -> serializeValue g serializeProperties :: Grammar 'Obj t1 t2 -> (Ae.Object, t2) -> Maybe (Ae.Object, t1) serializeProperties = \case Id -> return g1 :. g2 -> serializeProperties g1 >=> serializeProperties g2 Empty -> fail "empty grammar" g1 :<> g2 -> \objx -> serializeProperties g1 objx <|> serializeProperties g2 objx Pure _ f -> \(obj, x) -> (obj, ) <$> f x Many g -> manyM (serializeProperties g) Property n g -> \(obj, x) -> do val :- y <- serializeValue g x return (H.insert n val obj, y) serializeElements :: Grammar 'Arr t1 t2 -> (Ae.Array, t2) -> Maybe (Ae.Array, t1) serializeElements = \case Id -> return g1 :. g2 -> serializeElements g1 >=> serializeElements g2 Empty -> fail "empty grammar" g1 :<> g2 -> \x -> serializeElements g1 x <|> serializeElements g2 x Pure _ f -> \(arr, x) -> (arr, ) <$> f x Many g -> manyM (serializeElements g) Element g -> \(arr, x) -> do val :- y <- serializeValue g x return (V.snoc arr val, y)
MedeaMelana/JsonGrammar2
src/Language/JsonGrammar/Serializer.hs
bsd-3-clause
2,152
0
15
530
809
418
391
53
11
{-#LANGUAGE GADTs #-} module Calc where data Expr a where I :: Int -> Expr Int B :: Bool -> Expr Bool Add :: Expr Int -> Expr Int -> Expr Int Mul :: Expr Int -> Expr Int -> Expr Int Eq :: (Eq a) => Expr a -> Expr a -> Expr Bool eval :: Expr a -> a eval (I n) = n eval (B b) = b eval (Add e1 e2) = eval e1 + eval e2 eval (Mul e1 e2) = eval e1 * eval e2 eval (Eq e1 e2) = eval e1 == eval e2 v1 = eval $ ( I 1 `Add` I 4 ) `Eq` I 7 v2 = eval $ ( I 1 `Add` I 4 ) `Eq` I 5 x1 = I 3 `Add` I 4 `Mul` I 9 x2 = x1 `Eq` (I 63)
aztecrex/haskell-experiments-gadt
src/Calc.hs
bsd-3-clause
537
0
9
166
336
171
165
18
1
{-| Module : Idris.Reflection Description : Code related to Idris's reflection system. This module contains quoters and unquoters along with some supporting datatypes. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE CPP, PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-unused-imports #-} module Idris.Reflection where import Idris.Core.Elaborate (claim, fill, focus, getNameFrom, initElaborator, movelast, runElab, solve) import Idris.Core.Evaluate (Def(TyDecl), initContext, lookupDefExact, lookupTyExact) import Idris.Core.TT import Idris.AbsSyntaxTree (ArgOpt(..), ElabD, Fixity(..), IState(idris_datatypes, idris_implicits, idris_patdefs, tt_ctxt), PArg, PArg'(..), PTactic, PTactic'(..), PTerm(..), initEState, pairCon, pairTy) import Idris.Delaborate (delab) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (pure, (<$>), (<*>)) import Data.Traversable (mapM) import Prelude hiding (mapM) #endif import Control.Monad (liftM, liftM2, liftM4) import Control.Monad.State.Strict (lift) import Data.List (findIndex, (\\)) import Data.Maybe (catMaybes) import qualified Data.Text as T data RErasure = RErased | RNotErased deriving Show data RPlicity = RExplicit | RImplicit | RConstraint deriving Show data RFunArg = RFunArg { argName :: Name , argTy :: Raw , argPlicity :: RPlicity , erasure :: RErasure } deriving Show data RTyDecl = RDeclare Name [RFunArg] Raw deriving Show data RTyConArg = RParameter RFunArg | RIndex RFunArg deriving Show data RCtorArg = RCtorParameter RFunArg | RCtorField RFunArg deriving Show data RDatatype = RDatatype Name [RTyConArg] Raw [(Name, [RCtorArg], Raw)] deriving Show data RConstructorDefn = RConstructor Name [RFunArg] Raw data RDataDefn = RDefineDatatype Name [RConstructorDefn] rArgOpts :: RErasure -> [ArgOpt] rArgOpts RErased = [InaccessibleArg] rArgOpts _ = [] rFunArgToPArg :: RFunArg -> PArg rFunArgToPArg (RFunArg n _ RExplicit e) = PExp 0 (rArgOpts e) n Placeholder rFunArgToPArg (RFunArg n _ RImplicit e) = PImp 0 False (rArgOpts e) n Placeholder rFunArgToPArg (RFunArg n _ RConstraint e) = PConstraint 0 (rArgOpts e) n Placeholder data RFunClause a = RMkFunClause a a | RMkImpossibleClause a deriving Show data RFunDefn a = RDefineFun Name [RFunClause a] deriving Show -- | Prefix a name with the "Language.Reflection" namespace reflm :: String -> Name reflm n = sNS (sUN n) ["Reflection", "Language"] -- | Prefix a name with the "Language.Reflection.Elab" namespace tacN :: String -> Name tacN str = sNS (sUN str) ["Elab", "Reflection", "Language"] -- | Reify tactics from their reflected representation reify :: IState -> Term -> ElabD PTactic reify _ (P _ n _) | n == reflm "Intros" = return Intros reify _ (P _ n _) | n == reflm "Trivial" = return Trivial reify _ (P _ n _) | n == reflm "Implementation" = return TCImplementation reify _ (P _ n _) | n == reflm "Solve" = return Solve reify _ (P _ n _) | n == reflm "Compute" = return Compute reify _ (P _ n _) | n == reflm "Skip" = return Skip reify _ (P _ n _) | n == reflm "SourceFC" = return SourceFC reify _ (P _ n _) | n == reflm "Unfocus" = return Unfocus reify ist t@(App _ _ _) | (P _ f _, args) <- unApply t = reifyApp ist f args reify _ t = fail ("Unknown tactic " ++ show t) reifyApp :: IState -> Name -> [Term] -> ElabD PTactic reifyApp ist t [l, r] | t == reflm "Try" = liftM2 Try (reify ist l) (reify ist r) reifyApp _ t [Constant (I i)] | t == reflm "Search" = return (ProofSearch True True i Nothing [] []) reifyApp _ t [x] | t == reflm "Refine" = do n <- reifyTTName x return $ Refine n [] reifyApp ist t [n, ty] | t == reflm "Claim" = do n' <- reifyTTName n goal <- reifyTT ty return $ Claim n' (delab ist goal) reifyApp ist t [l, r] | t == reflm "Seq" = liftM2 TSeq (reify ist l) (reify ist r) reifyApp ist t [Constant (Str n), x] | t == reflm "GoalType" = liftM (GoalType n) (reify ist x) reifyApp _ t [n] | t == reflm "Intro" = liftM (Intro . (:[])) (reifyTTName n) reifyApp ist t [t'] | t == reflm "Induction" = liftM (Induction . delab ist) (reifyTT t') reifyApp ist t [t'] | t == reflm "Case" = liftM (CaseTac . delab ist) (reifyTT t') reifyApp ist t [t'] | t == reflm "ApplyTactic" = liftM (ApplyTactic . delab ist) (reifyTT t') reifyApp ist t [t'] | t == reflm "Reflect" = liftM (Reflect . delab ist) (reifyTT t') reifyApp ist t [t'] | t == reflm "ByReflection" = liftM (ByReflection . delab ist) (reifyTT t') reifyApp _ t [t'] | t == reflm "Fill" = liftM (Fill . PQuote) (reifyRaw t') reifyApp ist t [t'] | t == reflm "Exact" = liftM (Exact . delab ist) (reifyTT t') reifyApp ist t [x] | t == reflm "Focus" = liftM Focus (reifyTTName x) reifyApp ist t [t'] | t == reflm "Rewrite" = liftM (Rewrite . delab ist) (reifyTT t') reifyApp ist t [n, t'] | t == reflm "LetTac" = do n' <- reifyTTName n t'' <- reifyTT t' return $ LetTac n' (delab ist t') reifyApp ist t [n, tt', t'] | t == reflm "LetTacTy" = do n' <- reifyTTName n tt'' <- reifyTT tt' t'' <- reifyTT t' return $ LetTacTy n' (delab ist tt'') (delab ist t'') reifyApp ist t [errs] | t == reflm "Fail" = fmap TFail (reifyReportParts errs) reifyApp _ f args = fail ("Unknown tactic " ++ show (f, args)) -- shouldn't happen reifyBool :: Term -> ElabD Bool reifyBool (P _ n _) | n == sNS (sUN "True") ["Bool", "Prelude"] = return True | n == sNS (sUN "False") ["Bool", "Prelude"] = return False reifyBool tm = fail $ "Not a Boolean: " ++ show tm reifyInt :: Term -> ElabD Int reifyInt (Constant (I i)) = return i reifyInt tm = fail $ "Not an Int: " ++ show tm reifyPair :: (Term -> ElabD a) -> (Term -> ElabD b) -> Term -> ElabD (a, b) reifyPair left right (App _ (App _ (App _ (App _ (P _ n _) _) _) x) y) | n == pairCon = liftM2 (,) (left x) (right y) reifyPair left right tm = fail $ "Not a pair: " ++ show tm reifyList :: (Term -> ElabD a) -> Term -> ElabD [a] reifyList getElt lst = case unList lst of Nothing -> fail "Couldn't reify a list" Just xs -> mapM getElt xs reifyReportParts :: Term -> ElabD [ErrorReportPart] reifyReportParts errs = case unList errs of Nothing -> fail "Failed to reify errors" Just errs' -> let parts = mapM reifyReportPart errs' in case parts of Left err -> fail $ "Couldn't reify \"Fail\" tactic - " ++ show err Right errs'' -> return errs'' -- | Reify terms from their reflected representation reifyTT :: Term -> ElabD Term reifyTT t@(App _ _ _) | (P _ f _, args) <- unApply t = reifyTTApp f args reifyTT t@(P _ n _) | n == reflm "Erased" = return Erased reifyTT t@(P _ n _) | n == reflm "Impossible" = return Impossible reifyTT t = fail ("Unknown reflection term: " ++ show t) reifyTTApp :: Name -> [Term] -> ElabD Term reifyTTApp t [nt, n, x] | t == reflm "P" = do nt' <- reifyTTNameType nt n' <- reifyTTName n x' <- reifyTT x return $ P nt' n' x' reifyTTApp t [Constant (I i)] | t == reflm "V" = return $ V i reifyTTApp t [n, b, x] | t == reflm "Bind" = do n' <- reifyTTName n b' <- reifyTTBinder reifyTT (reflm "TT") b x' <- reifyTT x return $ Bind n' b' x' reifyTTApp t [f, x] | t == reflm "App" = do f' <- reifyTT f x' <- reifyTT x return $ App Complete f' x' reifyTTApp t [c] | t == reflm "TConst" = liftM Constant (reifyTTConst c) reifyTTApp t [t', Constant (I i)] | t == reflm "Proj" = do t'' <- reifyTT t' return $ Proj t'' i reifyTTApp t [tt] | t == reflm "TType" = liftM TType (reifyTTUExp tt) reifyTTApp t [tt] | t == reflm "UType" = liftM UType (reifyUniverse tt) reifyTTApp t args = fail ("Unknown reflection term: " ++ show (t, args)) reifyUniverse :: Term -> ElabD Universe reifyUniverse (P _ n _) | n == reflm "AllTypes" = return AllTypes | n == reflm "UniqueType" = return UniqueType | n == reflm "NullType" = return NullType reifyUniverse tm = fail ("Unknown reflection universe: " ++ show tm) -- | Reify raw terms from their reflected representation reifyRaw :: Term -> ElabD Raw reifyRaw t@(App _ _ _) | (P _ f _, args) <- unApply t = reifyRawApp f args reifyRaw t@(P _ n _) | n == reflm "RType" = return RType reifyRaw t = fail ("Unknown reflection raw term in reifyRaw: " ++ show t) reifyRawApp :: Name -> [Term] -> ElabD Raw reifyRawApp t [n] | t == reflm "Var" = liftM Var (reifyTTName n) reifyRawApp t [n, b, x] | t == reflm "RBind" = do n' <- reifyTTName n b' <- reifyTTBinder reifyRaw (reflm "Raw") b x' <- reifyRaw x return $ RBind n' b' x' reifyRawApp t [f, x] | t == reflm "RApp" = liftM2 RApp (reifyRaw f) (reifyRaw x) reifyRawApp t [c] | t == reflm "RConstant" = liftM RConstant (reifyTTConst c) reifyRawApp t args = fail ("Unknown reflection raw term in reifyRawApp: " ++ show (t, args)) reifyTTName :: Term -> ElabD Name reifyTTName t | (P _ f _, args) <- unApply t = reifyTTNameApp f args reifyTTName t = fail ("Unknown reflection term name: " ++ show t) reifyTTNameApp :: Name -> [Term] -> ElabD Name reifyTTNameApp t [Constant (Str n)] | t == reflm "UN" = return $ sUN n reifyTTNameApp t [n, ns] | t == reflm "NS" = do n' <- reifyTTName n ns' <- reifyTTNamespace ns return $ sNS n' ns' reifyTTNameApp t [Constant (I i), Constant (Str n)] | t == reflm "MN" = return $ sMN i n reifyTTNameApp t [sn] | t == reflm "SN" , (P _ f _, args) <- unApply sn = SN <$> reifySN f args where reifySN :: Name -> [Term] -> ElabD SpecialName reifySN t [Constant (I i), n1, n2] | t == reflm "WhereN" = WhereN i <$> reifyTTName n1 <*> reifyTTName n2 reifySN t [Constant (I i), n] | t == reflm "WithN" = WithN i <$> reifyTTName n reifySN t [n, ss] | t == reflm "ImplementationN" = case unList ss of Nothing -> fail "Can't reify ImplementationN strings" Just ss' -> ImplementationN <$> reifyTTName n <*> pure [T.pack s | Constant (Str s) <- ss'] reifySN t [n, Constant (Str s)] | t == reflm "ParentN" = ParentN <$> reifyTTName n <*> pure (T.pack s) reifySN t [n] | t == reflm "MethodN" = MethodN <$> reifyTTName n reifySN t [fc, n] | t == reflm "CaseN" = CaseN <$> (FC' <$> reifyFC fc) <*> reifyTTName n reifySN t [n] | t == reflm "ElimN" = ElimN <$> reifyTTName n reifySN t [n] | t == reflm "ImplementationCtorN" = ImplementationCtorN <$> reifyTTName n reifySN t [n1, n2] | t == reflm "MetaN" = MetaN <$> reifyTTName n1 <*> reifyTTName n2 reifySN t args = fail $ "Can't reify special name " ++ show t ++ show args reifyTTNameApp t args = fail ("Unknown reflection term name: " ++ show (t, args)) reifyTTNamespace :: Term -> ElabD [String] reifyTTNamespace t@(App _ _ _) = case unApply t of (P _ f _, [Constant StrType]) | f == sNS (sUN "Nil") ["List", "Prelude"] -> return [] (P _ f _, [Constant StrType, Constant (Str n), ns]) | f == sNS (sUN "::") ["List", "Prelude"] -> liftM (n:) (reifyTTNamespace ns) _ -> fail ("Unknown reflection namespace arg: " ++ show t) reifyTTNamespace t = fail ("Unknown reflection namespace arg: " ++ show t) reifyTTNameType :: Term -> ElabD NameType reifyTTNameType t@(P _ n _) | n == reflm "Bound" = return $ Bound reifyTTNameType t@(P _ n _) | n == reflm "Ref" = return $ Ref reifyTTNameType t@(App _ _ _) = case unApply t of (P _ f _, [Constant (I tag), Constant (I num)]) | f == reflm "DCon" -> return $ DCon tag num False -- FIXME: Uniqueness! | f == reflm "TCon" -> return $ TCon tag num _ -> fail ("Unknown reflection name type: " ++ show t) reifyTTNameType t = fail ("Unknown reflection name type: " ++ show t) reifyTTBinder :: (Term -> ElabD a) -> Name -> Term -> ElabD (Binder a) reifyTTBinder reificator binderType t@(App _ _ _) = case unApply t of (P _ f _, bt:args) | forget bt == Var binderType -> reifyTTBinderApp reificator f args _ -> fail ("Mismatching binder reflection: " ++ show t) reifyTTBinder _ _ t = fail ("Unknown reflection binder: " ++ show t) reifyTTBinderApp :: (Term -> ElabD a) -> Name -> [Term] -> ElabD (Binder a) reifyTTBinderApp reif f [t] | f == reflm "Lam" = liftM Lam (reif t) reifyTTBinderApp reif f [t, k] | f == reflm "Pi" = liftM2 (Pi Nothing) (reif t) (reif k) reifyTTBinderApp reif f [x, y] | f == reflm "Let" = liftM2 Let (reif x) (reif y) reifyTTBinderApp reif f [t] | f == reflm "Hole" = liftM Hole (reif t) reifyTTBinderApp reif f [t] | f == reflm "GHole" = liftM (GHole 0 []) (reif t) reifyTTBinderApp reif f [x, y] | f == reflm "Guess" = liftM2 Guess (reif x) (reif y) reifyTTBinderApp reif f [t] | f == reflm "PVar" = liftM PVar (reif t) reifyTTBinderApp reif f [t] | f == reflm "PVTy" = liftM PVTy (reif t) reifyTTBinderApp _ f args = fail ("Unknown reflection binder: " ++ show (f, args)) reifyTTConst :: Term -> ElabD Const reifyTTConst (P _ n _) | n == reflm "StrType" = return StrType reifyTTConst (P _ n _) | n == reflm "VoidType" = return VoidType reifyTTConst (P _ n _) | n == reflm "Forgot" = return Forgot reifyTTConst t@(App _ _ _) | (P _ f _, [arg]) <- unApply t = reifyTTConstApp f arg reifyTTConst t = fail ("Unknown reflection constant: " ++ show t) reifyTTConstApp :: Name -> Term -> ElabD Const reifyTTConstApp f aty | f == reflm "AType" = fmap AType (reifyArithTy aty) reifyTTConstApp f (Constant c@(I _)) | f == reflm "I" = return c reifyTTConstApp f (Constant c@(BI _)) | f == reflm "BI" = return c reifyTTConstApp f (Constant c@(Fl _)) | f == reflm "Fl" = return c reifyTTConstApp f (Constant c@(Ch _)) | f == reflm "Ch" = return c reifyTTConstApp f (Constant c@(Str _)) | f == reflm "Str" = return c reifyTTConstApp f (Constant c@(B8 _)) | f == reflm "B8" = return c reifyTTConstApp f (Constant c@(B16 _)) | f == reflm "B16" = return c reifyTTConstApp f (Constant c@(B32 _)) | f == reflm "B32" = return c reifyTTConstApp f (Constant c@(B64 _)) | f == reflm "B64" = return c reifyTTConstApp f v@(P _ _ _) = lift . tfail . Msg $ "Can't reify the variable " ++ show v ++ " as a constant, because its value is not statically known." reifyTTConstApp f arg = fail ("Unknown reflection constant: " ++ show (f, arg)) reifyArithTy :: Term -> ElabD ArithTy reifyArithTy (App _ (P _ n _) intTy) | n == reflm "ATInt" = fmap ATInt (reifyIntTy intTy) reifyArithTy (P _ n _) | n == reflm "ATDouble" = return ATFloat reifyArithTy x = fail ("Couldn't reify reflected ArithTy: " ++ show x) reifyNativeTy :: Term -> ElabD NativeTy reifyNativeTy (P _ n _) | n == reflm "IT8" = return IT8 reifyNativeTy (P _ n _) | n == reflm "IT16" = return IT16 reifyNativeTy (P _ n _) | n == reflm "IT32" = return IT32 reifyNativeTy (P _ n _) | n == reflm "IT64" = return IT64 reifyNativeTy x = fail $ "Couldn't reify reflected NativeTy " ++ show x reifyIntTy :: Term -> ElabD IntTy reifyIntTy (App _ (P _ n _) nt) | n == reflm "ITFixed" = fmap ITFixed (reifyNativeTy nt) reifyIntTy (P _ n _) | n == reflm "ITNative" = return ITNative reifyIntTy (P _ n _) | n == reflm "ITBig" = return ITBig reifyIntTy (P _ n _) | n == reflm "ITChar" = return ITChar reifyIntTy tm = fail $ "The term " ++ show tm ++ " is not a reflected IntTy" reifyTTUExp :: Term -> ElabD UExp reifyTTUExp t@(App _ _ _) = case unApply t of (P _ f _, [Constant (Str str), Constant (I i)]) | f == reflm "UVar" -> return $ UVar str i (P _ f _, [Constant (I i)]) | f == reflm "UVal" -> return $ UVal i _ -> fail ("Unknown reflection type universe expression: " ++ show t) reifyTTUExp t = fail ("Unknown reflection type universe expression: " ++ show t) -- | Create a reflected call to a named function/constructor reflCall :: String -> [Raw] -> Raw reflCall funName args = raw_apply (Var (reflm funName)) args -- | Lift a term into its Language.Reflection.TT representation reflect :: Term -> Raw reflect = reflectTTQuote [] -- | Lift a term into its Language.Reflection.Raw representation reflectRaw :: Raw -> Raw reflectRaw = reflectRawQuote [] claimTy :: Name -> Raw -> ElabD Name claimTy n ty = do n' <- getNameFrom n claim n' ty return n' intToReflectedNat :: Int -> Raw intToReflectedNat i = if i <= 0 then Var (natN "Z") else RApp (Var (natN "S")) (intToReflectedNat (i - 1)) where natN :: String -> Name natN n = sNS (sUN n) ["Nat", "Prelude"] reflectFixity :: Fixity -> Raw reflectFixity (Infixl p) = RApp (Var (tacN "Infixl")) (intToReflectedNat p) reflectFixity (Infixr p) = RApp (Var (tacN "Infixr")) (intToReflectedNat p) reflectFixity (InfixN p) = RApp (Var (tacN "InfixN")) (intToReflectedNat p) reflectFixity (PrefixN p) = RApp (Var (tacN "PrefixN")) (intToReflectedNat p) -- | Convert a reflected term to a more suitable form for pattern-matching. -- In particular, the less-interesting bits are elaborated to _ patterns. This -- happens to NameTypes, universe levels, names that are bound but not used, -- and the type annotation field of the P constructor. reflectTTQuotePattern :: [Name] -> Term -> ElabD () reflectTTQuotePattern unq (P _ n _) | n `elem` unq = -- the unquoted names have been claimed as TT already - just use them do fill (Var n) ; solve | otherwise = do tyannot <- claimTy (sMN 0 "pTyAnnot") (Var (reflm "TT")) movelast tyannot -- use a _ pattern here nt <- getNameFrom (sMN 0 "nt") claim nt (Var (reflm "NameType")) movelast nt -- use a _ pattern here n' <- getNameFrom (sMN 0 "n") claim n' (Var (reflm "TTName")) fill $ reflCall "P" [Var nt, Var n', Var tyannot] solve focus n'; reflectNameQuotePattern n reflectTTQuotePattern unq (V n) = do fill $ reflCall "V" [RConstant (I n)] solve reflectTTQuotePattern unq (Bind n b x) = do x' <- claimTy (sMN 0 "sc") (Var (reflm "TT")) movelast x' b' <- getNameFrom (sMN 0 "binder") claim b' (RApp (Var (sNS (sUN "Binder") ["Reflection", "Language"])) (Var (sNS (sUN "TT") ["Reflection", "Language"]))) if n `elem` freeNames x then do fill $ reflCall "Bind" [reflectName n, Var b', Var x'] solve else do any <- getNameFrom (sMN 0 "anyName") claim any (Var (reflm "TTName")) movelast any fill $ reflCall "Bind" [Var any, Var b', Var x'] solve focus x'; reflectTTQuotePattern unq x focus b'; reflectBinderQuotePattern reflectTTQuotePattern (Var $ reflm "TT") unq b reflectTTQuotePattern unq (App _ f x) = do f' <- claimTy (sMN 0 "f") (Var (reflm "TT")) ; movelast f' x' <- claimTy (sMN 0 "x") (Var (reflm "TT")) ; movelast x' fill $ reflCall "App" [Var f', Var x'] solve focus f'; reflectTTQuotePattern unq f focus x'; reflectTTQuotePattern unq x reflectTTQuotePattern unq (Constant c) = do fill $ reflCall "TConst" [reflectConstant c] solve reflectTTQuotePattern unq (Proj t i) = lift . tfail . InternalMsg $ "Phase error! The Proj constructor is for optimization only and should not have been reflected during elaboration." reflectTTQuotePattern unq Erased = do erased <- claimTy (sMN 0 "erased") (Var (reflm "TT")) movelast erased fill (Var erased) reflectTTQuotePattern unq Impossible = lift . tfail . InternalMsg $ "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration." reflectTTQuotePattern unq (TType exp) = do ue <- getNameFrom (sMN 0 "uexp") claim ue (Var (sNS (sUN "TTUExp") ["Reflection", "Language"])) movelast ue fill $ reflCall "TType" [Var ue] solve reflectTTQuotePattern unq (UType u) = do uH <- getNameFrom (sMN 0 "someUniv") claim uH (Var (reflm "Universe")) movelast uH fill $ reflCall "UType" [Var uH] solve focus uH fill (Var (reflm (case u of NullType -> "NullType" UniqueType -> "UniqueType" AllTypes -> "AllTypes"))) solve reflectRawQuotePattern :: [Name] -> Raw -> ElabD () reflectRawQuotePattern unq (Var n) -- the unquoted names already have types, just use them | n `elem` unq = do fill (Var n); solve | otherwise = do fill (reflCall "Var" [reflectName n]); solve reflectRawQuotePattern unq (RBind n b sc) = do scH <- getNameFrom (sMN 0 "sc") claim scH (Var (reflm "Raw")) movelast scH bH <- getNameFrom (sMN 0 "binder") claim bH (RApp (Var (reflm "Binder")) (Var (reflm "Raw"))) if n `elem` freeNamesR sc then do fill $ reflCall "RBind" [reflectName n, Var bH, Var scH] solve else do any <- getNameFrom (sMN 0 "anyName") claim any (Var (reflm "TTName")) movelast any fill $ reflCall "RBind" [Var any, Var bH, Var scH] solve focus scH; reflectRawQuotePattern unq sc focus bH; reflectBinderQuotePattern reflectRawQuotePattern (Var $ reflm "Raw") unq b where freeNamesR (Var n) = [n] freeNamesR (RBind n (Let t v) body) = concat [freeNamesR v, freeNamesR body \\ [n], freeNamesR t] freeNamesR (RBind n b body) = freeNamesR (binderTy b) ++ (freeNamesR body \\ [n]) freeNamesR (RApp f x) = freeNamesR f ++ freeNamesR x freeNamesR RType = [] freeNamesR (RUType _) = [] freeNamesR (RConstant _) = [] reflectRawQuotePattern unq (RApp f x) = do fH <- getNameFrom (sMN 0 "f") claim fH (Var (reflm "Raw")) movelast fH xH <- getNameFrom (sMN 0 "x") claim xH (Var (reflm "Raw")) movelast xH fill $ reflCall "RApp" [Var fH, Var xH] solve focus fH; reflectRawQuotePattern unq f focus xH; reflectRawQuotePattern unq x reflectRawQuotePattern unq RType = do fill (Var (reflm "RType")) solve reflectRawQuotePattern unq (RUType univ) = do uH <- getNameFrom (sMN 0 "universe") claim uH (Var (reflm "Universe")) movelast uH fill $ reflCall "RUType" [Var uH] solve focus uH; fill (reflectUniverse univ); solve reflectRawQuotePattern unq (RConstant c) = do cH <- getNameFrom (sMN 0 "const") claim cH (Var (reflm "Constant")) movelast cH fill (reflCall "RConstant" [Var cH]); solve focus cH fill (reflectConstant c); solve reflectBinderQuotePattern :: ([Name] -> a -> ElabD ()) -> Raw -> [Name] -> Binder a -> ElabD () reflectBinderQuotePattern q ty unq (Lam t) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' fill $ reflCall "Lam" [ty, Var t'] solve focus t'; q unq t reflectBinderQuotePattern q ty unq (Pi _ t k) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' k' <- claimTy (sMN 0 "k") ty; movelast k'; fill $ reflCall "Pi" [ty, Var t', Var k'] solve focus t'; q unq t reflectBinderQuotePattern q ty unq (Let x y) = do x' <- claimTy (sMN 0 "ty") ty; movelast x'; y' <- claimTy (sMN 0 "v")ty; movelast y'; fill $ reflCall "Let" [ty, Var x', Var y'] solve focus x'; q unq x focus y'; q unq y reflectBinderQuotePattern q ty unq (NLet x y) = do x' <- claimTy (sMN 0 "ty") ty; movelast x' y' <- claimTy (sMN 0 "v") ty; movelast y' fill $ reflCall "Let" [ty, Var x', Var y'] solve focus x'; q unq x focus y'; q unq y reflectBinderQuotePattern q ty unq (Hole t) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' fill $ reflCall "Hole" [ty, Var t'] solve focus t'; q unq t reflectBinderQuotePattern q ty unq (GHole _ _ t) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' fill $ reflCall "GHole" [ty, Var t'] solve focus t'; q unq t reflectBinderQuotePattern q ty unq (Guess x y) = do x' <- claimTy (sMN 0 "ty") ty; movelast x' y' <- claimTy (sMN 0 "v") ty; movelast y' fill $ reflCall "Guess" [ty, Var x', Var y'] solve focus x'; q unq x focus y'; q unq y reflectBinderQuotePattern q ty unq (PVar t) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' fill $ reflCall "PVar" [ty, Var t'] solve focus t'; q unq t reflectBinderQuotePattern q ty unq (PVTy t) = do t' <- claimTy (sMN 0 "ty") ty; movelast t' fill $ reflCall "PVTy" [ty, Var t'] solve focus t'; q unq t reflectUniverse :: Universe -> Raw reflectUniverse u = (Var (reflm (case u of NullType -> "NullType" UniqueType -> "UniqueType" AllTypes -> "AllTypes"))) -- | Create a reflected TT term, but leave refs to the provided name intact reflectTTQuote :: [Name] -> Term -> Raw reflectTTQuote unq (P nt n t) | n `elem` unq = Var n | otherwise = reflCall "P" [reflectNameType nt, reflectName n, reflectTTQuote unq t] reflectTTQuote unq (V n) = reflCall "V" [RConstant (I n)] reflectTTQuote unq (Bind n b x) = reflCall "Bind" [reflectName n, reflectBinderQuote reflectTTQuote (reflm "TT") unq b, reflectTTQuote unq x] reflectTTQuote unq (App _ f x) = reflCall "App" [reflectTTQuote unq f, reflectTTQuote unq x] reflectTTQuote unq (Constant c) = reflCall "TConst" [reflectConstant c] reflectTTQuote unq (TType exp) = reflCall "TType" [reflectUExp exp] reflectTTQuote unq (UType u) = reflCall "UType" [reflectUniverse u] reflectTTQuote _ (Proj _ _) = error "Phase error! The Proj constructor is for optimization only and should not have been reflected during elaboration." reflectTTQuote unq Erased = Var (reflm "Erased") reflectTTQuote _ Impossible = error "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration." reflectRawQuote :: [Name] -> Raw -> Raw reflectRawQuote unq (Var n) | n `elem` unq = Var n | otherwise = reflCall "Var" [reflectName n] reflectRawQuote unq (RBind n b r) = reflCall "RBind" [reflectName n, reflectBinderQuote reflectRawQuote (reflm "Raw") unq b, reflectRawQuote unq r] reflectRawQuote unq (RApp f x) = reflCall "RApp" [reflectRawQuote unq f, reflectRawQuote unq x] reflectRawQuote unq RType = Var (reflm "RType") reflectRawQuote unq (RUType u) = reflCall "RUType" [reflectUniverse u] reflectRawQuote unq (RConstant cst) = reflCall "RConstant" [reflectConstant cst] reflectNameType :: NameType -> Raw reflectNameType (Bound) = Var (reflm "Bound") reflectNameType (Ref) = Var (reflm "Ref") reflectNameType (DCon x y _) = reflCall "DCon" [RConstant (I x), RConstant (I y)] -- FIXME: Uniqueness! reflectNameType (TCon x y) = reflCall "TCon" [RConstant (I x), RConstant (I y)] reflectName :: Name -> Raw reflectName (UN s) = reflCall "UN" [RConstant (Str (str s))] reflectName (NS n ns) = reflCall "NS" [ reflectName n , foldr (\ n s -> raw_apply ( Var $ sNS (sUN "::") ["List", "Prelude"] ) [ RConstant StrType, RConstant (Str n), s ]) ( raw_apply ( Var $ sNS (sUN "Nil") ["List", "Prelude"] ) [ RConstant StrType ]) (map str ns) ] reflectName (MN i n) = reflCall "MN" [RConstant (I i), RConstant (Str (str n))] reflectName (SN sn) = raw_apply (Var (reflm "SN")) [reflectSpecialName sn] reflectName (SymRef _) = error "The impossible happened: symbol table ref survived IBC loading" reflectSpecialName :: SpecialName -> Raw reflectSpecialName (WhereN i n1 n2) = reflCall "WhereN" [RConstant (I i), reflectName n1, reflectName n2] reflectSpecialName (WithN i n) = reflCall "WithN" [ RConstant (I i) , reflectName n ] reflectSpecialName (ImplementationN impl ss) = reflCall "ImplementationN" [ reflectName impl , mkList (RConstant StrType) $ map (RConstant . Str . T.unpack) ss ] reflectSpecialName (ParentN n s) = reflCall "ParentN" [reflectName n, RConstant (Str (T.unpack s))] reflectSpecialName (MethodN n) = reflCall "MethodN" [reflectName n] reflectSpecialName (CaseN fc n) = reflCall "CaseN" [reflectFC (unwrapFC fc), reflectName n] reflectSpecialName (ElimN n) = reflCall "ElimN" [reflectName n] reflectSpecialName (ImplementationCtorN n) = reflCall "ImplementationCtorN" [reflectName n] reflectSpecialName (MetaN parent meta) = reflCall "MetaN" [reflectName parent, reflectName meta] -- | Elaborate a name to a pattern. This means that NS and UN will be intact. -- MNs corresponding to will care about the string but not the number. All -- others become _. reflectNameQuotePattern :: Name -> ElabD () reflectNameQuotePattern n@(UN s) = do fill $ reflectName n solve reflectNameQuotePattern n@(NS _ _) = do fill $ reflectName n solve reflectNameQuotePattern (MN _ n) = do i <- getNameFrom (sMN 0 "mnCounter") claim i (RConstant (AType (ATInt ITNative))) movelast i fill $ reflCall "MN" [Var i, RConstant (Str $ T.unpack n)] solve reflectNameQuotePattern _ -- for all other names, match any = do nameHole <- getNameFrom (sMN 0 "name") claim nameHole (Var (reflm "TTName")) movelast nameHole fill (Var nameHole) solve reflectBinder :: Binder Term -> Raw reflectBinder = reflectBinderQuote reflectTTQuote (reflm "TT") [] reflectBinderQuote :: ([Name] -> a -> Raw) -> Name -> [Name] -> Binder a -> Raw reflectBinderQuote q ty unq (Lam t) = reflCall "Lam" [Var ty, q unq t] reflectBinderQuote q ty unq (Pi _ t k) = reflCall "Pi" [Var ty, q unq t, q unq k] reflectBinderQuote q ty unq (Let x y) = reflCall "Let" [Var ty, q unq x, q unq y] reflectBinderQuote q ty unq (NLet x y) = reflCall "Let" [Var ty, q unq x, q unq y] reflectBinderQuote q ty unq (Hole t) = reflCall "Hole" [Var ty, q unq t] reflectBinderQuote q ty unq (GHole _ _ t) = reflCall "GHole" [Var ty, q unq t] reflectBinderQuote q ty unq (Guess x y) = reflCall "Guess" [Var ty, q unq x, q unq y] reflectBinderQuote q ty unq (PVar t) = reflCall "PVar" [Var ty, q unq t] reflectBinderQuote q ty unq (PVTy t) = reflCall "PVTy" [Var ty, q unq t] mkList :: Raw -> [Raw] -> Raw mkList ty [] = RApp (Var (sNS (sUN "Nil") ["List", "Prelude"])) ty mkList ty (x:xs) = RApp (RApp (RApp (Var (sNS (sUN "::") ["List", "Prelude"])) ty) x) (mkList ty xs) reflectConstant :: Const -> Raw reflectConstant c@(I _) = reflCall "I" [RConstant c] reflectConstant c@(BI _) = reflCall "BI" [RConstant c] reflectConstant c@(Fl _) = reflCall "Fl" [RConstant c] reflectConstant c@(Ch _) = reflCall "Ch" [RConstant c] reflectConstant c@(Str _) = reflCall "Str" [RConstant c] reflectConstant c@(B8 _) = reflCall "B8" [RConstant c] reflectConstant c@(B16 _) = reflCall "B16" [RConstant c] reflectConstant c@(B32 _) = reflCall "B32" [RConstant c] reflectConstant c@(B64 _) = reflCall "B64" [RConstant c] reflectConstant (AType (ATInt ITNative)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITNative")]] reflectConstant (AType (ATInt ITBig)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITBig")]] reflectConstant (AType ATFloat) = reflCall "AType" [Var (reflm "ATDouble")] reflectConstant (AType (ATInt ITChar)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITChar")]] reflectConstant StrType = Var (reflm "StrType") reflectConstant (AType (ATInt (ITFixed IT8))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT8")]]] reflectConstant (AType (ATInt (ITFixed IT16))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT16")]]] reflectConstant (AType (ATInt (ITFixed IT32))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT32")]]] reflectConstant (AType (ATInt (ITFixed IT64))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT64")]]] reflectConstant VoidType = Var (reflm "VoidType") reflectConstant Forgot = Var (reflm "Forgot") reflectConstant WorldType = Var (reflm "WorldType") reflectConstant TheWorld = Var (reflm "TheWorld") reflectUExp :: UExp -> Raw reflectUExp (UVar ns i) = reflCall "UVar" [RConstant (Str ns), RConstant (I i)] reflectUExp (UVal i) = reflCall "UVal" [RConstant (I i)] -- | Reflect the environment of a proof into a List (TTName, Binder TT) reflectEnv :: Env -> Raw reflectEnv = foldr consToEnvList emptyEnvList where consToEnvList :: (Name, Binder Term) -> Raw -> Raw consToEnvList (n, b) l = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"])) [ envTupleType , raw_apply (Var pairCon) [ (Var $ reflm "TTName") , (RApp (Var $ reflm "Binder") (Var $ reflm "TT")) , reflectName n , reflectBinder b ] , l ] emptyEnvList :: Raw emptyEnvList = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"])) [envTupleType] reifyEnv :: Term -> ElabD Env reifyEnv = reifyList (reifyPair reifyTTName (reifyTTBinder reifyTT (reflm "TT"))) -- | Reflect an error into the internal datatype of Idris -- TODO rawBool :: Bool -> Raw rawBool True = Var (sNS (sUN "True") ["Bool", "Prelude"]) rawBool False = Var (sNS (sUN "False") ["Bool", "Prelude"]) rawNil :: Raw -> Raw rawNil ty = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"])) [ty] rawCons :: Raw -> Raw -> Raw -> Raw rawCons ty hd tl = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"])) [ty, hd, tl] rawList :: Raw -> [Raw] -> Raw rawList ty = foldr (rawCons ty) (rawNil ty) rawPairTy :: Raw -> Raw -> Raw rawPairTy t1 t2 = raw_apply (Var pairTy) [t1, t2] rawPair :: (Raw, Raw) -> (Raw, Raw) -> Raw rawPair (a, b) (x, y) = raw_apply (Var pairCon) [a, b, x, y] -- | Idris tuples nest to the right rawTripleTy :: Raw -> Raw -> Raw -> Raw rawTripleTy a b c = rawPairTy a (rawPairTy b c) rawTriple :: (Raw, Raw, Raw) -> (Raw, Raw, Raw) -> Raw rawTriple (a, b, c) (x, y, z) = rawPair (a, rawPairTy b c) (x, rawPair (b, c) (y, z)) reflectCtxt :: [(Name, Type)] -> Raw reflectCtxt ctxt = rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TT")) (map (\ (n, t) -> (rawPair (Var $ reflm "TTName", Var $ reflm "TT") (reflectName n, reflect t))) ctxt) reflectErr :: Err -> Raw reflectErr (Msg msg) = raw_apply (Var $ reflErrName "Msg") [RConstant (Str msg)] reflectErr (InternalMsg msg) = raw_apply (Var $ reflErrName "InternalMsg") [RConstant (Str msg)] reflectErr (CantUnify b (t1,_) (t2,_) e ctxt i) = raw_apply (Var $ reflErrName "CantUnify") [ rawBool b , reflect t1 , reflect t2 , reflectErr e , reflectCtxt ctxt , RConstant (I i)] reflectErr (InfiniteUnify n tm ctxt) = raw_apply (Var $ reflErrName "InfiniteUnify") [ reflectName n , reflect tm , reflectCtxt ctxt ] reflectErr (CantConvert t t' ctxt) = raw_apply (Var $ reflErrName "CantConvert") [ reflect t , reflect t' , reflectCtxt ctxt ] reflectErr (CantSolveGoal t ctxt) = raw_apply (Var $ reflErrName "CantSolveGoal") [ reflect t , reflectCtxt ctxt ] reflectErr (UnifyScope n n' t ctxt) = raw_apply (Var $ reflErrName "UnifyScope") [ reflectName n , reflectName n' , reflect t , reflectCtxt ctxt ] reflectErr (CantInferType str) = raw_apply (Var $ reflErrName "CantInferType") [RConstant (Str str)] reflectErr (NonFunctionType t t') = raw_apply (Var $ reflErrName "NonFunctionType") [reflect t, reflect t'] reflectErr (NotEquality t t') = raw_apply (Var $ reflErrName "NotEquality") [reflect t, reflect t'] reflectErr (TooManyArguments n) = raw_apply (Var $ reflErrName "TooManyArguments") [reflectName n] reflectErr (CantIntroduce t) = raw_apply (Var $ reflErrName "CantIntroduce") [reflect t] reflectErr (NoSuchVariable n) = raw_apply (Var $ reflErrName "NoSuchVariable") [reflectName n] reflectErr (WithFnType t) = raw_apply (Var $ reflErrName "WithFnType") [reflect t] reflectErr (CantMatch t) = raw_apply (Var $ reflErrName "CantMatch") [reflect t] reflectErr (NoTypeDecl n) = raw_apply (Var $ reflErrName "NoTypeDecl") [reflectName n] reflectErr (NotInjective t1 t2 t3) = raw_apply (Var $ reflErrName "NotInjective") [ reflect t1 , reflect t2 , reflect t3 ] reflectErr (CantResolve _ t more) = raw_apply (Var $ reflErrName "CantResolve") [reflect t, reflectErr more] reflectErr (InvalidTCArg n t) = raw_apply (Var $ reflErrName "InvalidTCArg") [reflectName n, reflect t] reflectErr (CantResolveAlts ss) = raw_apply (Var $ reflErrName "CantResolveAlts") [rawList (Var $ reflm "TTName") (map reflectName ss)] reflectErr (IncompleteTerm t) = raw_apply (Var $ reflErrName "IncompleteTerm") [reflect t] reflectErr (NoEliminator str t) = raw_apply (Var $ reflErrName "NoEliminator") [RConstant (Str str), reflect t] reflectErr (UniverseError fc ue old new tys) = -- NB: loses information, but OK because this is not likely to be rewritten Var $ reflErrName "UniverseError" reflectErr ProgramLineComment = Var $ reflErrName "ProgramLineComment" reflectErr (Inaccessible n) = raw_apply (Var $ reflErrName "Inaccessible") [reflectName n] reflectErr (UnknownImplicit n f) = raw_apply (Var $ reflErrName "UnknownImplicit") [reflectName n, reflectName f] reflectErr (NonCollapsiblePostulate n) = raw_apply (Var $ reflErrName "NonCollabsiblePostulate") [reflectName n] reflectErr (AlreadyDefined n) = raw_apply (Var $ reflErrName "AlreadyDefined") [reflectName n] reflectErr (ProofSearchFail e) = raw_apply (Var $ reflErrName "ProofSearchFail") [reflectErr e] reflectErr (NoRewriting l r tm) = raw_apply (Var $ reflErrName "NoRewriting") [reflect l, reflect r, reflect tm] reflectErr (ProviderError str) = raw_apply (Var $ reflErrName "ProviderError") [RConstant (Str str)] reflectErr (LoadingFailed str err) = raw_apply (Var $ reflErrName "LoadingFailed") [RConstant (Str str)] reflectErr x = raw_apply (Var (sNS (sUN "Msg") ["Errors", "Reflection", "Language"])) [RConstant . Str $ "Default reflection: " ++ show x] -- | Reflect a file context reflectFC :: FC -> Raw reflectFC fc = raw_apply (Var (reflm "FileLoc")) [ RConstant (Str (fc_fname fc)) , raw_apply (Var pairCon) $ [intTy, intTy] ++ map (RConstant . I) [ fst (fc_start fc) , snd (fc_start fc) ] , raw_apply (Var pairCon) $ [intTy, intTy] ++ map (RConstant . I) [ fst (fc_end fc) , snd (fc_end fc) ] ] where intTy = RConstant (AType (ATInt ITNative)) reifyFC :: Term -> ElabD FC reifyFC tm | (P (DCon _ _ _) cn _, [Constant (Str fn), st, end]) <- unApply tm , cn == reflm "FileLoc" = FC fn <$> reifyPair reifyInt reifyInt st <*> reifyPair reifyInt reifyInt end | otherwise = fail $ "Not a source location: " ++ show tm fromTTMaybe :: Term -> Maybe Term -- WARNING: Assumes the term has type Maybe a fromTTMaybe (App _ (App _ (P (DCon _ _ _) (NS (UN just) _) _) ty) tm) | just == txt "Just" = Just tm fromTTMaybe x = Nothing reflErrName :: String -> Name reflErrName n = sNS (sUN n) ["Errors", "Reflection", "Language"] -- | Attempt to reify a report part from TT to the internal -- representation. Not in Idris or ElabD monads because it should be usable -- from either. reifyReportPart :: Term -> Either Err ErrorReportPart reifyReportPart (App _ (P (DCon _ _ _) n _) (Constant (Str msg))) | n == reflm "TextPart" = Right (TextPart msg) reifyReportPart (App _ (P (DCon _ _ _) n _) ttn) | n == reflm "NamePart" = case runElab initEState (reifyTTName ttn) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of Error e -> Left . InternalMsg $ "could not reify name term " ++ show ttn ++ " when reflecting an error:" ++ show e OK (n', _)-> Right $ NamePart n' reifyReportPart (App _ (P (DCon _ _ _) n _) tm) | n == reflm "TermPart" = case runElab initEState (reifyTT tm) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of Error e -> Left . InternalMsg $ "could not reify reflected term " ++ show tm ++ " when reflecting an error:" ++ show e OK (tm', _) -> Right $ TermPart tm' reifyReportPart (App _ (P (DCon _ _ _) n _) tm) | n == reflm "RawPart" = case runElab initEState (reifyRaw tm) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of Error e -> Left . InternalMsg $ "could not reify reflected raw term " ++ show tm ++ " when reflecting an error: " ++ show e OK (tm', _) -> Right $ RawPart tm' reifyReportPart (App _ (P (DCon _ _ _) n _) tm) | n == reflm "SubReport" = case unList tm of Just xs -> do subParts <- mapM reifyReportPart xs Right (SubReport subParts) Nothing -> Left . InternalMsg $ "could not reify subreport " ++ show tm reifyReportPart x = Left . InternalMsg $ "could not reify " ++ show x reifyErasure :: Term -> ElabD RErasure reifyErasure (P (DCon _ _ _) n _) | n == tacN "Erased" = return RErased | n == tacN "NotErased" = return RNotErased reifyErasure tm = fail $ "Can't reify " ++ show tm ++ " as erasure info." reifyPlicity :: Term -> ElabD RPlicity reifyPlicity (P (DCon _ _ _) n _) | n == tacN "Explicit" = return RExplicit | n == tacN "Implicit" = return RImplicit | n == tacN "Constraint" = return RConstraint reifyPlicity tm = fail $ "Couldn't reify " ++ show tm ++ " as RPlicity." reifyRFunArg :: Term -> ElabD RFunArg reifyRFunArg (App _ (App _ (App _ (App _ (P (DCon _ _ _) n _) argN) argTy) argPl) argE) | n == tacN "MkFunArg" = liftM4 RFunArg (reifyTTName argN) (reifyRaw argTy) (reifyPlicity argPl) (reifyErasure argE) reifyRFunArg aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RArg." reifyTyDecl :: Term -> ElabD RTyDecl reifyTyDecl (App _ (App _ (App _ (P (DCon _ _ _) n _) tyN) args) ret) | n == tacN "Declare" = do tyN' <- reifyTTName tyN args' <- case unList args of Nothing -> fail $ "Couldn't reify " ++ show args ++ " as an arglist." Just xs -> mapM reifyRFunArg xs ret' <- reifyRaw ret return $ RDeclare tyN' args' ret' reifyTyDecl tm = fail $ "Couldn't reify " ++ show tm ++ " as a type declaration." reifyFunDefn :: Term -> ElabD (RFunDefn Raw) reifyFunDefn (App _ (App _ (App _ (P _ n _) (P _ t _)) fnN) clauses) | n == tacN "DefineFun" && t == reflm "Raw" = do fnN' <- reifyTTName fnN clauses' <- case unList clauses of Nothing -> fail $ "Couldn't reify " ++ show clauses ++ " as a clause list" Just cs -> mapM reifyC cs return $ RDefineFun fnN' clauses' where reifyC :: Term -> ElabD (RFunClause Raw) reifyC (App _ (App _ (App _ (P (DCon _ _ _) n _) (P _ t _)) lhs) rhs) | n == tacN "MkFunClause" && t == reflm "Raw" = liftM2 RMkFunClause (reifyRaw lhs) (reifyRaw rhs) reifyC (App _ (App _ (P (DCon _ _ _) n _) (P _ t _)) lhs) | n == tacN "MkImpossibleClause" && t == reflm "Raw" = fmap RMkImpossibleClause $ reifyRaw lhs reifyC tm = fail $ "Couldn't reify " ++ show tm ++ " as a clause." reifyFunDefn tm = fail $ "Couldn't reify " ++ show tm ++ " as a function declaration." reifyRConstructorDefn :: Term -> ElabD RConstructorDefn reifyRConstructorDefn (App _ (App _ (App _ (P _ n _) cn) args) retTy) | n == tacN "Constructor", Just args' <- unList args = RConstructor <$> reifyTTName cn <*> mapM reifyRFunArg args' <*> reifyRaw retTy reifyRConstructorDefn aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RConstructorDefn" reifyRDataDefn :: Term -> ElabD RDataDefn reifyRDataDefn (App _ (App _ (P _ n _) tyn) ctors) | n == tacN "DefineDatatype", Just ctors' <- unList ctors = RDefineDatatype <$> reifyTTName tyn <*> mapM reifyRConstructorDefn ctors' reifyRDataDefn aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RDataDefn" envTupleType :: Raw envTupleType = raw_apply (Var pairTy) [ (Var $ reflm "TTName") , (RApp (Var $ reflm "Binder") (Var $ reflm "TT")) ] reflectList :: Raw -> [Raw] -> Raw reflectList ty [] = RApp (Var (sNS (sUN "Nil") ["List", "Prelude"])) ty reflectList ty (x:xs) = RApp (RApp (RApp (Var (sNS (sUN "::") ["List", "Prelude"])) ty) x) (reflectList ty xs) -- | Apply Idris's implicit info to get a signature. The [PArg] should -- come from a lookup in idris_implicits on IState. getArgs :: [PArg] -> Raw -> ([RFunArg], Raw) getArgs [] r = ([], r) getArgs (a:as) (RBind n (Pi _ ty _) sc) = let (args, res) = getArgs as sc erased = if InaccessibleArg `elem` argopts a then RErased else RNotErased arg' = case a of PImp {} -> RFunArg n ty RImplicit erased PExp {} -> RFunArg n ty RExplicit erased PConstraint {} -> RFunArg n ty RConstraint erased PTacImplicit {} -> RFunArg n ty RImplicit erased in (arg':args, res) getArgs _ r = ([], r) unApplyRaw :: Raw -> (Raw, [Raw]) unApplyRaw tm = ua [] tm where ua args (RApp f a) = ua (a:args) f ua args t = (t, args) -- | Build the reflected function definition(s) that correspond(s) to -- a provided unqualifed name buildFunDefns :: IState -> Name -> [RFunDefn Term] buildFunDefns ist n = [ mkFunDefn name clauses | (name, (clauses, _)) <- lookupCtxtName n $ idris_patdefs ist ] where mkFunDefn name clauses = RDefineFun name (map mkFunClause clauses) mkFunClause ([], lhs, Impossible) = RMkImpossibleClause lhs mkFunClause ([], lhs, rhs) = RMkFunClause lhs rhs mkFunClause (((n, ty) : ns), lhs, rhs) = mkFunClause (ns, bind lhs, bind rhs) where bind Impossible = Impossible bind tm = Bind n (PVar ty) tm -- | Build the reflected datatype definition(s) that correspond(s) to -- a provided unqualified name buildDatatypes :: IState -> Name -> [RDatatype] buildDatatypes ist n = catMaybes [ mkDataType dn ti | (dn, ti) <- lookupCtxtName n datatypes ] where datatypes = idris_datatypes ist ctxt = tt_ctxt ist impls = idris_implicits ist ctorSig params cn = do cty <- fmap forget (lookupTyExact cn ctxt) argInfo <- lookupCtxtExact cn impls let (args, res) = getArgs argInfo cty return (cn, ctorArgsStatus args res params, res) argPos n [] res = findPos n res where findPos n app = case unApplyRaw app of (_, argL) -> findIndex (== Var n) argL argPos n (arg:args) res = if n == argName arg then Nothing else argPos n args res ctorArgsStatus :: [RFunArg] -> Raw -> [Int] -> [RCtorArg] ctorArgsStatus [] _ _ = [] ctorArgsStatus (arg:args) res params = case argPos (argName arg) args res of Nothing -> RCtorField arg : ctorArgsStatus args res params Just i -> if i `elem` params then RCtorParameter arg : ctorArgsStatus args res params else RCtorField arg : ctorArgsStatus args res params mkDataType name (TI {param_pos = params, con_names = constrs}) = do (TyDecl (TCon _ _) ty) <- lookupDefExact name ctxt implInfo <- lookupCtxtExact name impls let (tcargs, tcres) = getTCArgs params implInfo (forget ty) ctors <- mapM (ctorSig params) constrs return $ RDatatype name tcargs tcres ctors getTCArgs :: [Int] -> [PArg] -> Raw -> ([RTyConArg], Raw) getTCArgs params implInfo tcTy = let (args, res) = getArgs implInfo tcTy in (tcArg args 0, res) where tcArg [] _ = [] tcArg (arg:args) i | i `elem` params = RParameter arg : tcArg args (i+1) | otherwise = RIndex arg : tcArg args (i+1) reflectErasure :: RErasure -> Raw reflectErasure RErased = Var (tacN "Erased") reflectErasure RNotErased = Var (tacN "NotErased") reflectPlicity :: RPlicity -> Raw reflectPlicity RExplicit = Var (tacN "Explicit") reflectPlicity RImplicit = Var (tacN "Implicit") reflectPlicity RConstraint = Var (tacN "Constraint") reflectArg :: RFunArg -> Raw reflectArg (RFunArg n ty plic erasure) = RApp (RApp (RApp (RApp (Var $ tacN "MkFunArg") (reflectName n)) (reflectRaw ty)) (reflectPlicity plic)) (reflectErasure erasure) reflectCtorArg :: RCtorArg -> Raw reflectCtorArg (RCtorParameter arg) = RApp (Var $ tacN "CtorParameter") (reflectArg arg) reflectCtorArg (RCtorField arg) = RApp (Var $ tacN "CtorField") (reflectArg arg) reflectDatatype :: RDatatype -> Raw reflectDatatype (RDatatype tyn tyConArgs tyConRes constrs) = raw_apply (Var $ tacN "MkDatatype") [ reflectName tyn , rawList (Var $ tacN "TyConArg") (map reflectConArg tyConArgs) , reflectRaw tyConRes , rawList (rawTripleTy (Var $ reflm "TTName") (RApp (Var (sNS (sUN "List") ["List", "Prelude"])) (Var $ tacN "CtorArg")) (Var $ reflm "Raw")) [ rawTriple ((Var $ reflm "TTName") ,(RApp (Var (sNS (sUN "List") ["List", "Prelude"])) (Var $ tacN "CtorArg")) ,(Var $ reflm "Raw")) (reflectName cn ,rawList (Var $ tacN "CtorArg") (map reflectCtorArg cargs) ,reflectRaw cty) | (cn, cargs, cty) <- constrs ] ] where reflectConArg (RParameter a) = RApp (Var $ tacN "TyConParameter") (reflectArg a) reflectConArg (RIndex a) = RApp (Var $ tacN "TyConIndex") (reflectArg a) reflectFunClause :: RFunClause Term -> Raw reflectFunClause (RMkFunClause lhs rhs) = raw_apply (Var $ tacN "MkFunClause") $ (Var $ reflm "TT") : map reflect [ lhs, rhs ] reflectFunClause (RMkImpossibleClause lhs) = raw_apply (Var $ tacN "MkImpossibleClause") [ Var $ reflm "TT", reflect lhs ] reflectFunDefn :: RFunDefn Term -> Raw reflectFunDefn (RDefineFun name clauses) = raw_apply (Var $ tacN "DefineFun") [ Var $ reflm "TT" , reflectName name , rawList (RApp (Var $ tacN "FunClause") (Var $ reflm "TT")) (map reflectFunClause clauses) ]
ben-schulz/Idris-dev
src/Idris/Reflection.hs
bsd-3-clause
55,395
0
18
17,242
20,700
10,068
10,632
1,053
11
module TypedPerl.PerlAST ( PerlASTMapper (..) , foldAST , nopMapper ) where import TypedPerl.Types import qualified Data.Map as M import Prelude hiding (seq); data PerlASTMapper a b c = PerlASTMapper { declare :: PerlVars -> a -> a , int :: Integer -> a , str :: String -> a , var :: PerlVars -> a , implicitItem :: a -> Int -> a , op :: PerlBinOp -> a -> a -> a , obj :: b -> String -> a , objMapItem :: String -> a -> b -> b , objMapNil :: b , objItem :: a -> String -> a , objMeth :: a -> String -> c -> a , abstract :: a -> a , app :: a -> c -> a , appListCons :: a -> c -> c , appListNil :: c , seq :: a -> a -> a , package :: String -> a -> a } nopMapper :: PerlASTMapper PerlAST (M.Map String PerlAST) [PerlAST] nopMapper = PerlASTMapper { declare = PerlDeclare , int = PerlInt , str = PerlStr , var = PerlVar , implicitItem = PerlImplicitItem , op = PerlOp , obj = PerlObj , objMapItem = M.insert , objMapNil = M.empty , objItem = PerlObjItem , objMeth = PerlObjMeth , abstract = PerlAbstract , app = PerlApp , appListCons = (:) , appListNil = [] , seq = PerlSeq , package = PerlPackage } foldAST :: PerlASTMapper a b c -> PerlAST -> a foldAST m (PerlDeclare v ast) = declare m v (foldAST m ast) foldAST m (PerlInt n) = int m n foldAST m (PerlStr s) = str m s foldAST m (PerlVar v) = var m v foldAST m (PerlImplicitItem ast n) = implicitItem m (foldAST m ast) n foldAST m (PerlOp o ast1 ast2) = op m o (foldAST m ast1) (foldAST m ast2) foldAST m (PerlObj ma s) = obj m (foldObjMap m ma) s foldAST m (PerlObjItem ast1 s) = objItem m (foldAST m ast1) s foldAST m (PerlObjMeth ast s asts) = objMeth m (foldAST m ast) s (foldAppList m asts) foldAST m (PerlAbstract ast) = abstract m (foldAST m ast) foldAST m (PerlApp ast asts) = app m (foldAST m ast) (foldAppList m asts) foldAST m (PerlSeq ast1 ast2) = seq m (foldAST m ast1) (foldAST m ast2) foldAST m (PerlPackage name ast) = package m name (foldAST m ast) foldObjMap :: PerlASTMapper a b c -> M.Map String PerlAST -> b foldObjMap m ma = M.foldWithKey (\k -> objMapItem m k . foldAST m) (objMapNil m) ma foldAppList :: PerlASTMapper a b c -> [PerlAST] -> c foldAppList m asts = foldr (appListCons m . foldAST m) (appListNil m) asts
hiratara/TypedPerl
src/TypedPerl/PerlAST.hs
bsd-3-clause
2,354
0
11
615
996
536
460
64
1
{-# LANGUAGE CPP , GADTs , DataKinds , PolyKinds , ExistentialQuantification , StandaloneDeriving , TypeFamilies , TypeOperators , OverloadedStrings , DeriveDataTypeable , ScopedTypeVariables , RankNTypes , FlexibleContexts #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} module Language.Hakaru.Parser.AST where import Prelude hiding (replicate, unlines) import Control.Arrow ((***)) import qualified Data.Foldable as F import qualified Data.Vector as V import qualified Data.Number.Nat as N import qualified Data.Number.Natural as N import qualified Data.List.NonEmpty as L import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import Language.Hakaru.Types.Coercion import Language.Hakaru.Syntax.ABT hiding (Var, Bind) import Language.Hakaru.Syntax.AST (Literal(..), MeasureOp(..), LCs(), UnLCs ()) import qualified Language.Hakaru.Syntax.AST as T import Language.Hakaru.Syntax.IClasses #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid(..)) #endif import qualified Data.Text as T import Text.Parsec (SourcePos) import Text.Parsec.Pos import Data.Generics hiding ((:~:)(..)) -- N.B., because we're not using the ABT's trick for implementing a HOAS API, we can make the identifier strict. data Name = Name {-# UNPACK #-}!N.Nat {-# UNPACK #-}!T.Text deriving (Read, Show, Eq, Ord, Data, Typeable) nameID :: Name -> N.Nat nameID (Name i _) = i hintID :: Name -> T.Text hintID (Name _ t) = t ---------------------------------------------------------------- ---------------------------------------------------------------- type Name' = T.Text data Branch' a = Branch' (Pattern' Name') (AST' a) | Branch'' (Pattern' Name) (AST' a) deriving (Eq, Show, Data, Typeable) data Pattern' a = PVar' a | PWild' | PData' (PDatum a) deriving (Eq, Show, Data, Typeable) data PDatum a = DV Name' [Pattern' a] deriving (Eq, Show, Data, Typeable) -- Meta stores start and end position for AST in source code data SourceSpan = SourceSpan !SourcePos !SourcePos deriving (Eq, Show, Data, Typeable) printSourceSpan :: SourceSpan -> V.Vector T.Text -> T.Text printSourceSpan (SourceSpan start stop) input = T.unlines (concatMap line [startLine..stopLine]) where line :: Int -> [T.Text] line i | (sourceLine start, sourceColumn start) <= (i, 1) && (i, eol) <= (sourceLine stop, sourceColumn stop) = [T.empty | i == startLine] ++ [quote '>'] ++ [T.empty | i == stopLine] | i == stopLine = [T.empty | i == startLine] ++ [quote ' ', marking (if i == sourceLine start then sourceColumn start else 1) (if i == sourceLine stop then sourceColumn stop else eol) '^'] | i == sourceLine start = [marking (sourceColumn start) eol '.', quote ' '] | otherwise = [quote ' '] where numbering = T.pack (show i) lining = input V.! (i-1) eol = T.length lining + 1 quote c = spacing (digits - T.length numbering) `T.append` numbering `T.append` T.singleton '|' `T.append` T.singleton c `T.append` lining spacing k = T.replicate k (T.singleton ' ') marking l r c = spacing (digits + 1 + l) `T.append` T.replicate (max 1 (r - l)) (T.singleton c) startLine = max 1 $ sourceLine start stopLine = max startLine $ min (V.length input) $ (if sourceColumn stop == 1 then pred else id) $ sourceLine stop digits = loop stopLine 1 where loop i res | i < 10 = res | otherwise = (loop $! div i 10) $! (res + 1) data Literal' = Nat Integer | Int Integer | Prob Rational | Real Rational deriving (Eq, Show, Data, Typeable) data NaryOp = And | Or | Xor | Iff | Min | Max | Sum | Prod deriving (Eq, Show, Data, Typeable) data ArrayOp = Index_ | Size | Reduce deriving (Data, Typeable) data TypeAST' = TypeVar Name' | TypeApp Name' [TypeAST'] | TypeFun TypeAST' TypeAST' deriving (Eq, Show, Data, Typeable) data Reducer' a = R_Fanout (Reducer' a) (Reducer' a) | R_Index a (AST' a) (AST' a) (Reducer' a) | R_Split (AST' a) (Reducer' a) (Reducer' a) | R_Nop | R_Add (AST' a) deriving (Eq, Show, Data, Typeable) data AST' a = Var a | Lam a TypeAST' (AST' a) | App (AST' a) (AST' a) | Let a (AST' a) (AST' a) | If (AST' a) (AST' a) (AST' a) | Ann (AST' a) TypeAST' | Infinity' | ULiteral Literal' | NaryOp NaryOp [AST' a] | Unit | Pair (AST' a) (AST' a) | Array a (AST' a) (AST' a) | ArrayLiteral [AST' a] | Index (AST' a) (AST' a) | Case (AST' a) [(Branch' a)] -- match | Bind a (AST' a) (AST' a) | Plate a (AST' a) (AST' a) | Chain a (AST' a) (AST' a) (AST' a) | Integrate a (AST' a) (AST' a) (AST' a) | Summate a (AST' a) (AST' a) (AST' a) | Product a (AST' a) (AST' a) (AST' a) | Bucket a (AST' a) (AST' a) (Reducer' a) | Expect a (AST' a) (AST' a) | Msum [AST' a] | Data a [a] [TypeAST'] (AST' a) | WithMeta (AST' a) SourceSpan deriving (Show, Data, Typeable) withoutMeta :: AST' a -> AST' a withoutMeta (WithMeta e _) = withoutMeta e withoutMeta e = e withoutMetaE :: forall a . Data a => AST' a -> AST' a withoutMetaE = everywhere (mkT (withoutMeta :: AST' a -> AST' a)) instance Eq a => Eq (AST' a) where (Var t) == (Var t') = t == t' (Lam n e1 e2) == (Lam n' e1' e2') = n == n' && e1 == e1' && e2 == e2' (App e1 e2) == (App e1' e2') = e1 == e1' && e2 == e2' (Let n e1 e2) == (Let n' e1' e2') = n == n' && e1 == e1' && e2 == e2' (If c e1 e2) == (If c' e1' e2') = c == c' && e1 == e1' && e2 == e2' (Ann e typ) == (Ann e' typ') = e == e' && typ == typ' Infinity' == Infinity' = True (ULiteral v) == (ULiteral v') = v == v' (NaryOp op args) == (NaryOp op' args') = op == op' && args == args' Unit == Unit = True (Pair e1 e2) == (Pair e1' e2') = e1 == e1' && e2 == e2' (Array e1 e2 e3) == (Array e1' e2' e3') = e1 == e1' && e2 == e2' && e3 == e3' (ArrayLiteral es) == (ArrayLiteral es') = es == es' (Index e1 e2) == (Index e1' e2') = e1 == e1' && e2 == e2' (Case e1 bs) == (Case e1' bs') = e1 == e1' && bs == bs' (Bind e1 e2 e3) == (Bind e1' e2' e3') = e1 == e1' && e2 == e2' && e3 == e3' (Plate e1 e2 e3) == (Plate e1' e2' e3') = e1 == e1' && e2 == e2' && e3 == e3' (Chain e1 e2 e3 e4) == (Chain e1' e2' e3' e4') = e1 == e1' && e2 == e2' && e3 == e3' && e4 == e4' (Integrate a b c d) == (Integrate a' b' c' d') = a == a' && b == b' && c == c' && d == d' (Summate a b c d) == (Summate a' b' c' d') = a == a' && b == b' && c == c' && d == d' (Product a b c d) == (Product a' b' c' d') = a == a' && b == b' && c == c' && d == d' (Bucket a b c d) == (Bucket a' b' c' d') = a == a' && b == b' && c == c' && d == d' (Expect e1 e2 e3) == (Expect e1' e2' e3') = e1 == e1' && e2 == e2' && e3 == e3' (Msum es) == (Msum es') = es == es' (Data n ft ts e) == (Data n' ft' ts' e') = n == n' && ft == ft' && ts == ts' && e == e' (WithMeta e1 _ ) == e2 = e1 == e2 e1 == (WithMeta e2 _) = e1 == e2 _ == _ = False data Import a = Import a deriving (Eq, Show) data ASTWithImport' a = ASTWithImport' [Import a] (AST' a) deriving (Eq, Show) ---------------------------------------------------------------- ---------------------------------------------------------------- val :: Literal' -> Some1 Literal val (Nat n) = Some1 $ LNat (N.unsafeNatural n) val (Int n) = Some1 $ LInt n val (Prob n) = Some1 $ LProb (N.unsafeNonNegativeRational n) val (Real n) = Some1 $ LReal n data PrimOp = Not | Impl | Diff | Nand | Nor | Pi | Sin | Cos | Tan | Asin | Acos | Atan | Sinh | Cosh | Tanh | Asinh | Acosh | Atanh | RealPow | NatPow | Exp | Log | Infinity | GammaFunc | BetaFunc | Equal | Less | Negate | Recip | Abs | Signum | NatRoot | Erf deriving (Eq, Show) data SomeOp op where SomeOp :: (typs ~ UnLCs args, args ~ LCs typs) => !(op typs a) -> SomeOp op data SSing = forall (a :: Hakaru). SSing !(Sing a) data Branch_ abt = Branch_ Pattern (abt '[] 'U) fmapBranch :: (f '[] 'U -> g '[] 'U) -> Branch_ f -> Branch_ g fmapBranch f (Branch_ pat e) = Branch_ pat (f e) foldBranch :: (abt '[] 'U -> m) -> Branch_ abt -> m foldBranch f (Branch_ _ e) = f e data Pattern = PWild | PVar Name | PDatum T.Text PCode data PFun = PKonst Pattern | PIdent Pattern data PStruct = PEt PFun PStruct | PDone data PCode = PInr PCode | PInl PStruct infixr 7 `Et`, `PEt` data DFun abt = Konst (abt '[] 'U) | Ident (abt '[] 'U) data DStruct abt = Et (DFun abt) (DStruct abt) | Done data DCode abt = Inr (DCode abt) | Inl (DStruct abt) data Datum abt = Datum T.Text (DCode abt) fmapDatum :: (f '[] 'U -> g '[] 'U) -> Datum f -> Datum g fmapDatum f (Datum t dcode) = Datum t (fdcode f dcode) where fdcode f' (Inr d) = Inr (fdcode f' d) fdcode f' (Inl d) = Inl (fdstruct f' d) fdstruct f' (Et df ds) = Et (fdfun f' df) (fdstruct f' ds) fdstruct _ Done = Done fdfun f' (Konst e) = Konst (f' e) fdfun f' (Ident e) = Ident (f' e) foldDatum :: (Monoid m) => (abt '[] 'U -> m) -> Datum abt -> m foldDatum f (Datum _ dcode) = fdcode f dcode where fdcode f' (Inr d) = fdcode f' d fdcode f' (Inl d) = fdstruct f' d fdstruct f' (Et df ds) = fdfun f' df `mappend` fdstruct f' ds fdstruct _ Done = mempty fdfun f' (Konst e) = f' e fdfun f' (Ident e) = f' e data Reducer (xs :: [Untyped]) (abt :: [Untyped] -> Untyped -> *) (a :: Untyped) where R_Fanout_ :: Reducer xs abt 'U -> Reducer xs abt 'U -> Reducer xs abt 'U R_Index_ :: Variable 'U -- HACK: Shouldn't need to pass this argument -> abt xs 'U -> abt ( 'U ': xs) 'U -> Reducer ( 'U ': xs) abt 'U -> Reducer xs abt 'U R_Split_ :: abt ( 'U ': xs) 'U -> Reducer xs abt 'U -> Reducer xs abt 'U -> Reducer xs abt 'U R_Nop_ :: Reducer xs abt 'U R_Add_ :: abt ( 'U ': xs) 'U -> Reducer xs abt 'U instance Functor21 (Reducer xs) where fmap21 f (R_Fanout_ r1 r2) = R_Fanout_ (fmap21 f r1) (fmap21 f r2) fmap21 f (R_Index_ bv e1 e2 r1) = R_Index_ bv (f e1) (f e2) (fmap21 f r1) fmap21 f (R_Split_ e1 r1 r2) = R_Split_ (f e1) (fmap21 f r1) (fmap21 f r2) fmap21 _ R_Nop_ = R_Nop_ fmap21 f (R_Add_ e1) = R_Add_ (f e1) instance Foldable21 (Reducer xs) where foldMap21 f (R_Fanout_ r1 r2) = foldMap21 f r1 `mappend` foldMap21 f r2 foldMap21 f (R_Index_ _ e1 e2 r1) = f e1 `mappend` f e2 `mappend` foldMap21 f r1 foldMap21 f (R_Split_ e1 r1 r2) = f e1 `mappend` foldMap21 f r1 `mappend` foldMap21 f r2 foldMap21 _ R_Nop_ = mempty foldMap21 f (R_Add_ e1) = f e1 -- | The kind containing exactly one type. data Untyped = U deriving (Read, Show) data instance Sing (a :: Untyped) where SU :: Sing 'U instance SingI 'U where sing = SU instance Show (Sing (a :: Untyped)) where showsPrec = showsPrec1 show = show1 instance Show1 (Sing :: Untyped -> *) where showsPrec1 _ SU = ("SU" ++) instance Eq (Sing (a :: Untyped)) where SU == SU = True instance Eq1 (Sing :: Untyped -> *) where eq1 SU SU = True instance JmEq1 (Sing :: Untyped -> *) where jmEq1 SU SU = Just Refl nameToVar :: Name -> Variable 'U nameToVar (Name i h) = Variable h i SU data Term :: ([Untyped] -> Untyped -> *) -> Untyped -> * where Lam_ :: SSing -> abt '[ 'U ] 'U -> Term abt 'U App_ :: abt '[] 'U -> abt '[] 'U -> Term abt 'U Let_ :: abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Ann_ :: SSing -> abt '[] 'U -> Term abt 'U CoerceTo_ :: Some2 Coercion -> abt '[] 'U -> Term abt 'U UnsafeTo_ :: Some2 Coercion -> abt '[] 'U -> Term abt 'U PrimOp_ :: PrimOp -> [abt '[] 'U] -> Term abt 'U ArrayOp_ :: ArrayOp -> [abt '[] 'U] -> Term abt 'U MeasureOp_ :: SomeOp MeasureOp -> [abt '[] 'U] -> Term abt 'U NaryOp_ :: NaryOp -> [abt '[] 'U] -> Term abt 'U Literal_ :: Some1 Literal -> Term abt 'U Pair_ :: abt '[] 'U -> abt '[] 'U -> Term abt 'U Array_ :: abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U ArrayLiteral_ :: [abt '[] 'U] -> Term abt 'U Datum_ :: Datum abt -> Term abt 'U Case_ :: abt '[] 'U -> [Branch_ abt] -> Term abt 'U Dirac_ :: abt '[] 'U -> Term abt 'U MBind_ :: abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Plate_ :: abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Chain_ :: abt '[] 'U -> abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Integrate_ :: abt '[] 'U -> abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Summate_ :: abt '[] 'U -> abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Product_ :: abt '[] 'U -> abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Bucket_ :: abt '[] 'U -> abt '[] 'U -> Reducer xs abt 'U -> Term abt 'U Expect_ :: abt '[] 'U -> abt '[ 'U ] 'U -> Term abt 'U Observe_ :: abt '[] 'U -> abt '[] 'U -> Term abt 'U Superpose_ :: L.NonEmpty (abt '[] 'U, abt '[] 'U) -> Term abt 'U Reject_ :: Term abt 'U InjTyped :: (forall abt . ABT T.Term abt => abt '[] x) -> Term abt 'U -- TODO: instance of Traversable21 for Term instance Functor21 Term where fmap21 f (Lam_ typ e1) = Lam_ typ (f e1) fmap21 f (App_ e1 e2) = App_ (f e1) (f e2) fmap21 f (Let_ e1 e2) = Let_ (f e1) (f e2) fmap21 f (Ann_ typ e1) = Ann_ typ (f e1) fmap21 f (CoerceTo_ c e1) = CoerceTo_ c (f e1) fmap21 f (UnsafeTo_ c e1) = UnsafeTo_ c (f e1) fmap21 f (PrimOp_ op es) = PrimOp_ op (fmap f es) fmap21 f (ArrayOp_ op es) = ArrayOp_ op (fmap f es) fmap21 f (MeasureOp_ op es) = MeasureOp_ op (fmap f es) fmap21 f (NaryOp_ op es) = NaryOp_ op (fmap f es) fmap21 _ (Literal_ v) = Literal_ v fmap21 f (Pair_ e1 e2) = Pair_ (f e1) (f e2) fmap21 f (Array_ e1 e2) = Array_ (f e1) (f e2) fmap21 f (ArrayLiteral_ es) = ArrayLiteral_ (fmap f es) fmap21 f (Datum_ d) = Datum_ (fmapDatum f d) fmap21 f (Case_ e1 bs) = Case_ (f e1) (fmap (fmapBranch f) bs) fmap21 f (Dirac_ e1) = Dirac_ (f e1) fmap21 f (MBind_ e1 e2) = MBind_ (f e1) (f e2) fmap21 f (Plate_ e1 e2) = Plate_ (f e1) (f e2) fmap21 f (Chain_ e1 e2 e3) = Chain_ (f e1) (f e2) (f e3) fmap21 f (Integrate_ e1 e2 e3) = Integrate_ (f e1) (f e2) (f e3) fmap21 f (Summate_ e1 e2 e3) = Summate_ (f e1) (f e2) (f e3) fmap21 f (Product_ e1 e2 e3) = Product_ (f e1) (f e2) (f e3) fmap21 f (Bucket_ e1 e2 e3) = Bucket_ (f e1) (f e2) (fmap21 f e3) fmap21 f (Expect_ e1 e2) = Expect_ (f e1) (f e2) fmap21 f (Observe_ e1 e2) = Observe_ (f e1) (f e2) fmap21 f (Superpose_ es) = Superpose_ (L.map (f *** f) es) fmap21 _ Reject_ = Reject_ fmap21 _ (InjTyped x) = InjTyped x instance Foldable21 Term where foldMap21 f (Lam_ _ e1) = f e1 foldMap21 f (App_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Let_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Ann_ _ e1) = f e1 foldMap21 f (CoerceTo_ _ e1) = f e1 foldMap21 f (UnsafeTo_ _ e1) = f e1 foldMap21 f (PrimOp_ _ es) = F.foldMap f es foldMap21 f (ArrayOp_ _ es) = F.foldMap f es foldMap21 f (MeasureOp_ _ es) = F.foldMap f es foldMap21 f (NaryOp_ _ es) = F.foldMap f es foldMap21 _ (Literal_ _) = mempty foldMap21 f (Pair_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Array_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (ArrayLiteral_ es) = F.foldMap f es foldMap21 f (Datum_ d) = foldDatum f d foldMap21 f (Case_ e1 bs) = f e1 `mappend` F.foldMap (foldBranch f) bs foldMap21 f (Dirac_ e1) = f e1 foldMap21 f (MBind_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Plate_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Chain_ e1 e2 e3) = f e1 `mappend` f e2 `mappend` f e3 foldMap21 f (Integrate_ e1 e2 e3) = f e1 `mappend` f e2 `mappend` f e3 foldMap21 f (Summate_ e1 e2 e3) = f e1 `mappend` f e2 `mappend` f e3 foldMap21 f (Product_ e1 e2 e3) = f e1 `mappend` f e2 `mappend` f e3 foldMap21 f (Bucket_ e1 e2 e3) = f e1 `mappend` f e2 `mappend` foldMap21 f e3 foldMap21 f (Expect_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Observe_ e1 e2) = f e1 `mappend` f e2 foldMap21 f (Superpose_ es) = F.foldMap (\(e1,e2) -> f e1 `mappend` f e2) es foldMap21 _ Reject_ = mempty foldMap21 _ InjTyped{} = mempty type U_ABT = MetaABT SourceSpan Term type AST = U_ABT '[] 'U type MetaTerm = Term U_ABT 'U type Branch = Branch_ U_ABT type DFun_ = DFun U_ABT type DStruct_ = DStruct U_ABT type DCode_ = DCode U_ABT ---------------------------------------------------------------- ---------------------------------------------------------- fin.
zachsully/hakaru
haskell/Language/Hakaru/Parser/AST.hs
bsd-3-clause
21,439
3
17
9,221
8,272
4,227
4,045
466
4
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.GA (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList [("integer (numeric)", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}}), ("ar\250 am\225rach", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("inniu", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("dd/mm/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 1}}), ("<time> seo chugainn", Classifier{okData = ClassData{prior = 0.0, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("day", -0.8266785731844679), ("d\233 named-day", -2.0794415416798357), ("named-day", -1.3862943611198906), ("an named-day", -1.6739764335716716)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("d\233 named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 2}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("anois", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("named-day", Classifier{okData = ClassData{prior = -0.2876820724517809, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -1.3862943611198906, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}}), ("an named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("am\225rach", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("inn\233", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.6931471805599453, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("<time> seo", Classifier{okData = ClassData{prior = 0.0, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("day", -0.7985076962177716), ("d\233 named-day", -2.3025850929940455), ("named-day", -1.3862943611198906), ("an named-day", -1.6094379124341003)], n = 8}, koData = ClassData{prior = -infinity, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [], n = 0}}), ("ar\250 inn\233", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}})]
rfranek/duckling
Duckling/Ranking/Classifiers/GA.hs
bsd-3-clause
8,101
0
15
3,588
1,717
1,069
648
141
1
module Text.Luthor.Classifier ( Classifier(..) , classifier , classify , classes , classSet , classMap -- * Classifier internals , Run , runChar , runClass , packRun ) where import qualified Data.Set as Set import Data.Set (Set) import qualified Data.IntSet as IntSet import Data.IntSet (IntSet) import Text.Luthor.Silhouette import Data.Array.Base (Array, numElements, unsafeAt, listArray, elems) type Run = Word32 runChar :: Run -> Char runChar i = toEnum (fromEnum (i .&. 0x1fffff)) {-# INLINE runChar #-} runClass :: Run -> Int runClass i = fromEnum (i `shiftR` 21) {-# INLINE runClass #-} packRun :: Char -> Int -> Start packRun c i = toEnum (fromEnum c) .|. (toEnum i `shiftL` 21) {-# INLINE packRun #-} newtype Classifier = Classifier { classifierArray :: UArray Int Run } deriving (Show, Data, Typeable) -- | we limit ourselves to classifiers that have fewer than 2048 equivalence classes maxClass :: Int maxClass = 2048 -- | We use two distinct tries during the construction of a classifier: -- -- * the trie of the silhouettes to assign unique identifiers to each distinct silhouette -- -- * the trie of signatures for each exemplar to count the number of distinct fragmented silhouettes -- -- TODO: This mechanism could be improved to try to find ranges that are common split points -- and factor them (and all ranges that share their signature) out of the signature calculation -- increasing the number of equivalence classes by one, and reducing the number of signatures under -- consideration by a factor of two at the expense of longer compile times and expending a lot more -- brainpower. Optimal selection is quite expensive, but we could do this greedily, and achieve a -- k-optimal result. classifierSize :: Classifier -> Int classifierSize (Classifier arr) = numElements arr {-# INLINE classifierSize #-} classifier :: [CharSet] -> Classifier classifier charSets | exemplarCount > maxClass && signatureCount > maxClass = error "Too many equivalence classes" | signatureCount > exemplarCount = classifyIntSet exemplars | otherwise = classifyIntSet (IntMap.keysSet starts) where classifyIntSet :: IntSet a -> Classifier classifyIntSet s = Classifier $ listArray (0, IntSet.size s - 1) $ zipWith (packStart . toEnum) (IntSet.elems s) [0..] -- find all the characters that matter -- exemplars :: IntSet exemplars = mconcat $ map silhouette charSets exemplarCount = IntSet.size exemplars -- map each a silhouette to a charset with that silhouette and unique identifier -- silhouetteCount :: Int -- silhouetteTrie :: IntTrie (CharSet, Int) (silhouetteCount, silhouetteTrie) = Traversable.mapAccumL enumerate 0 $ -- enumerate IntTrie.fromList $ -- distinct silhouettes [ (IntSet.toAscList (silhouette cs), cs) | cs <- charSets ] -- map each character to a unique set of silhouettes exemplarSignatures :: IntMap [Int] exemplarSignatures = IntMap.fromListWith cons1 [ (c, [n]) | c <- IntSet.toList exemplars , (cs, n) <- Foldable.toList silhouetteTrie , c `CharSet.member` cs ] -- signatureCount :: Int -- signatureTrie :: IntTrie ([Int], Int) (signatureCount, signatureTrie) Traversable.mapAccumL enumerate 0 $ IntTrie.fromListWith cons1 $ [ (sig, [c]) | (c, sig) <- IntMap.toList exemplarSignatures ] -- starts :: IntMap Int -- maps starts to signatures starts = IntMap.fromList [ (c, signature) | (exemplars, signature) <- Foldable.toList signatureTrie , c <- exemplars ] {-# INLINE classifier #-} cons1 :: [Int] -> [Int] -> [Int] cons1 [x] xs = (x:xs) cons1 _ _ = error "classifier: logic error" {-# INLINE cons1 #-} enumerate :: Int -> a -> (Int, (a, Int)) enumerate !n a = (n + 1, (a, n)) {-# INLINE enumerate #-} classify :: Char -> Classifier -> Int classify c (Classifier arr) = go 0 (len - 1) where len = numElements arr go !l !h | l == h = runClass ms | runChar ms <= c = go l m | otherwise = go (m + 1) h where -- not concerned about overflow m = (l + h) `div` 2 ms = unsafeAt arr m {-# INLINE classify #-} classes :: Classifier -> [(Char,Char)] classes (Classifier arr) = go (elems arr) where go (x:yys@(y:_)) = (x, pred y) : go yys go [x] = (x,maxBound) go _ = error "classes: empty classifier" {-# INLINE classes #-} -- | assumes that the 'CharSet' is distinguished by the 'Classifier' classSet :: CharSet -> Classifier -> IntSet classSet cs cls = IntSet.fromList $ go $ IntSet.toList $ silhouette cs where go [] = [] go (s:ss) | s `CharSet.member` cs = classify s cls : go ss | otherwise = go ss {-# INLINE classSet #-} intSetToMap :: IntSet -> e -> IntMap e intSetToMap is e = IntMap.fromDistinctAscList $ map (\i -> (i,e)) $ IntSet.toAscList is {-# INLINE intSetToMap #-} classMap :: [(CharSet,e)] -> Classifier -> IntMap [e] classMap cse cls = foldr (IntMap.unionWith cons1) IntMap.empty $ map swizzle cse where swizzle (cs,e) = intSetToMap (classSet cs cls) e {-# INLINE classMap #-}
ekmett/luthor
Text/Luthor/Classifier.hs
bsd-3-clause
5,570
5
13
1,549
1,368
746
622
-1
-1
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, GeneralizedNewtypeDeriving #-} -- | Functions for starting QML engines, displaying content in a window. module Graphics.QML.Engine ( -- * Engines EngineConfig( EngineConfig, initialDocument, contextObject, importPaths, pluginPaths), defaultEngineConfig, Engine, runEngine, runEngineWith, runEngineAsync, runEngineLoop, -- * Event Loop RunQML(), runEventLoop, runEventLoopNoArgs, requireEventLoop, setQtArgs, getQtArgs, shutdownQt, EventLoopException(), -- * Document Paths DocumentPath(), fileDocument, uriDocument ) where import Graphics.QML.Internal.JobQueue import Graphics.QML.Internal.Marshal import Graphics.QML.Internal.BindPrim import Graphics.QML.Internal.BindCore import Graphics.QML.Marshal () import Graphics.QML.Objects import Control.Applicative import Control.Concurrent import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import qualified Data.Text as T import Data.List import Data.Traversable hiding (mapM) import Data.Typeable import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import System.Environment (getProgName, getArgs, withProgName, withArgs) import System.FilePath (FilePath, isAbsolute, splitDirectories, pathSeparators) -- | Holds parameters for configuring a QML runtime engine. data EngineConfig = EngineConfig { -- | Path to the first QML document to be loaded. initialDocument :: DocumentPath, -- | Context 'Object' made available to QML script code. contextObject :: Maybe AnyObjRef, -- | Additional search paths for QML modules importPaths :: [FilePath], -- | Additional search paths for QML native plugins pluginPaths :: [FilePath] } -- | Default engine configuration. Loads @\"main.qml\"@ from the current -- working directory into a visible window with no context object. defaultEngineConfig :: EngineConfig defaultEngineConfig = EngineConfig { initialDocument = DocumentPath "main.qml", contextObject = Nothing, importPaths = [], pluginPaths = [] } -- | Represents a QML engine. data Engine = Engine runEngineImpl :: EngineConfig -> IO () -> IO Engine runEngineImpl config stopCb = do hsqmlInit let obj = contextObject config DocumentPath res = initialDocument config impPaths = importPaths config plugPaths = pluginPaths config hndl <- sequenceA $ fmap mToHndl obj mWithCVal (T.pack res) $ \resPtr -> withManyArray0 mWithCVal (map T.pack impPaths) nullPtr $ \impPtr -> withManyArray0 mWithCVal (map T.pack plugPaths) nullPtr $ \plugPtr -> hsqmlCreateEngine hndl (HsQMLStringHandle $ castPtr resPtr) (castPtr impPtr) (castPtr plugPtr) stopCb return Engine withMany :: (a -> (b -> m c) -> m c) -> [a] -> ([b] -> m c) -> m c withMany func as cont = let rec (a:as') bs = func a (\b -> rec as' (bs . (b:))) rec [] bs = cont $ bs [] in rec as id withManyArray0 :: Storable b => (a -> (b -> IO c) -> IO c) -> [a] -> b -> (Ptr b -> IO c) -> IO c withManyArray0 func as term cont = withMany func as $ \ptrs -> withArray0 term ptrs cont -- | Starts a new QML engine using the supplied configuration and blocks until -- the engine has terminated. runEngine :: EngineConfig -> RunQML () runEngine config = runEngineWith config (const $ return ()) -- | Starts a new QML engine using the supplied configuration. The \'with\' -- function is executed once the engine has been started and after it returns -- this function blocks until the engine has terminated. runEngineWith :: EngineConfig -> (Engine -> RunQML a) -> RunQML a runEngineWith config with = RunQML $ do finishVar <- newEmptyMVar let stopCb = putMVar finishVar () eng <- runEngineImpl config stopCb let (RunQML withIO) = with eng ret <- withIO void $ takeMVar finishVar return ret -- | Starts a new QML engine using the supplied configuration and returns -- immediately without blocking. runEngineAsync :: EngineConfig -> RunQML Engine runEngineAsync config = RunQML $ runEngineImpl config (return ()) -- | Conveniance function that both runs the event loop and starts a new QML -- engine. It blocks keeping the event loop running until the engine has -- terminated. runEngineLoop :: EngineConfig -> IO () runEngineLoop config = runEventLoop $ runEngine config -- | Wrapper around the IO monad for running actions which depend on the Qt -- event loop. newtype RunQML a = RunQML (IO a) deriving (Functor, Applicative, Monad) instance MonadIO RunQML where liftIO = RunQML -- | This function enters the Qt event loop and executes the supplied function -- in the 'RunQML' monad on a new unbound thread. The event loop will continue -- to run until all functions in the 'RunQML' monad have completed. This -- includes both the 'RunQML' function launched by this call and any launched -- asynchronously via 'requireEventLoop'. When the event loop exits, all -- engines will be terminated. -- -- It's recommended that applications run the event loop on their primordial -- thread as some platforms mandate this. Once the event loop has finished, it -- can be started again, but only on the same operating system thread as -- before. If the event loop fails to start then an 'EventLoopException' will -- be thrown. -- -- If the event loop is entered for the first time then the currently set -- runtime command line arguments will be passed to Qt. Hence, while calling -- back to the supplied function, attempts to read the runtime command line -- arguments using the System.Environment module will only return those -- arguments not already consumed by Qt (per 'getQtArgs'). runEventLoop :: RunQML a -> IO a runEventLoop (RunQML runFn) = do prog <- getProgName args <- getArgs setQtArgs prog args runEventLoopNoArgs . RunQML $ do (prog', args') <- getQtArgsIO withProgName prog' $ withArgs args' runFn -- | Enters the Qt event loop in the same manner as 'runEventLoop', but does -- not perform any processing related to command line arguments. runEventLoopNoArgs :: RunQML a -> IO a runEventLoopNoArgs (RunQML runFn) = tryRunInBoundThread $ do hsqmlInit finishVar <- newEmptyMVar let startCb = void $ forkIO $ do ret <- try runFn case ret of Left ex -> putMVar finishVar $ throwIO (ex :: SomeException) Right ret' -> putMVar finishVar $ return ret' hsqmlEvloopRelease yieldCb = if rtsSupportsBoundThreads then Nothing else Just yield status <- hsqmlEvloopRun startCb processJobs yieldCb case statusException status of Just ex -> throw ex Nothing -> do finFn <- takeMVar finishVar finFn tryRunInBoundThread :: IO a -> IO a tryRunInBoundThread action = if rtsSupportsBoundThreads then runInBoundThread action else action -- | Executes a function in the 'RunQML' monad asynchronously to the event -- loop. Callers must apply their own sychronisation to ensure that the event -- loop is currently running when this function is called, otherwise an -- 'EventLoopException' will be thrown. The event loop will not exit until the -- supplied function has completed. requireEventLoop :: RunQML a -> IO a requireEventLoop (RunQML runFn) = do hsqmlInit let reqFn = do status <- hsqmlEvloopRequire case statusException status of Just ex -> throw ex Nothing -> return () bracket_ reqFn hsqmlEvloopRelease runFn -- | Sets the program name and command line arguments used by Qt and returns -- True if successful. This must be called before the first time the Qt event -- loop is entered otherwise it will have no effect and return False. By -- default Qt receives no arguments and the program name is set to "HsQML". setQtArgs :: String -> [String] -> IO Bool setQtArgs prog args = do hsqmlInit withManyArray0 mWithCVal (map T.pack (prog:args)) nullPtr (hsqmlSetArgs . castPtr) -- | Gets the program name and any command line arguments remaining from an -- earlier call to 'setQtArgs' once Qt has removed any it understands, leaving -- only application specific arguments. getQtArgs :: RunQML (String, [String]) getQtArgs = RunQML getQtArgsIO getQtArgsIO :: IO (String, [String]) getQtArgsIO = do argc <- hsqmlGetArgsCount withManyArray0 mWithCVal (replicate argc $ T.pack "") nullPtr $ \argv -> do hsqmlGetArgs $ castPtr argv argvs <- peekArray0 nullPtr argv Just (arg0:args) <- runMaybeT $ mapM (fmap T.unpack . mFromCVal) argvs return (arg0, args) -- | Shuts down and frees resources used by the Qt framework, preventing -- further use of the event loop. The framework is initialised when -- 'runEventLoop' is first called and remains initialised afterwards so that -- the event loop can be reentered if desired (e.g. when using GHCi). Once -- shut down, the framework cannot be reinitialised. -- -- It is recommended that you call this function at the end of your program as -- this library will try, but cannot guarantee in all configurations to be able -- to shut it down for you. Failing to shutdown the framework has been known to -- intermittently cause crashes on process exit on some platforms. -- -- This function must be called from the event loop thread and the event loop -- must not be running at the time otherwise an 'EventLoopException' will be -- thrown. shutdownQt :: IO () shutdownQt = do status <- hsqmlEvloopShutdown case statusException status of Just ex -> throw ex Nothing -> return () statusException :: HsQMLEventLoopStatus -> Maybe EventLoopException statusException HsqmlEvloopOk = Nothing statusException HsqmlEvloopAlreadyRunning = Just EventLoopAlreadyRunning statusException HsqmlEvloopPostShutdown = Just EventLoopPostShutdown statusException HsqmlEvloopWrongThread = Just EventLoopWrongThread statusException HsqmlEvloopNotRunning = Just EventLoopNotRunning statusException _ = Just EventLoopOtherError -- | Exception type used to report errors pertaining to the event loop. data EventLoopException = EventLoopAlreadyRunning | EventLoopPostShutdown | EventLoopWrongThread | EventLoopNotRunning | EventLoopOtherError deriving (Show, Typeable) instance Exception EventLoopException -- | Path to a QML document file. newtype DocumentPath = DocumentPath String -- | Converts a local file path into a 'DocumentPath'. fileDocument :: FilePath -> DocumentPath fileDocument fp = let ds = splitDirectories fp isAbs = isAbsolute fp fixHead = (\cs -> if null cs then [] else '/':cs) . takeWhile (`notElem` pathSeparators) mapHead _ [] = [] mapHead f (x:xs) = f x : xs afp = intercalate "/" $ mapHead fixHead ds rfp = intercalate "/" ds in DocumentPath $ if isAbs then "file://" ++ afp else rfp -- | Converts a URI string into a 'DocumentPath'. uriDocument :: String -> DocumentPath uriDocument = DocumentPath
marcinmrotek/hsqml-fork
src/Graphics/QML/Engine.hs
bsd-3-clause
11,230
0
19
2,385
2,126
1,124
1,002
204
4
module Skell.Core where import Control.Lens import Control.Monad.State import qualified Data.Sequence as S import Pipes import Skell.Buffer import Skell.Types coreModel :: PSkell coreModel = do iSk <- await st <- lift $ get yield $ OSkell (case S.viewl (st^.buffers) of S.EmptyL -> "" a S.:< _ -> a^.content ) -- | Aplica una funcion al buffer en uso, si no -- ningun buffer no hace nada withCurrentBuffer :: (Buffer -> Buffer) -> IOSkell () withCurrentBuffer f = do buffers %= (\ss -> case S.viewl ss of S.EmptyL -> S.empty a S.:< se -> f a S.<| se ) -- defaultEmacsKeymap :: S.Seq Keys -> IOSkell () -- defaultEmacsKeymap sq -- | S.drop (S.length sq - 1) sq == ctrlG = return () -- | isChar /= Nothing = let Just a = isChar -- in withCurrentBuffer (insertStr_ [a]) -- | otherwise = mkKeymap -- [ -- ("C-x-s", exit .= True) -- TODO -- ("Left", withCurrentBuffer moveLeft_) -- , ("Right", withCurrentBuffer moveRight_) -- -- , ("C-Left", edit.buffers._1._1 %= prevToken >> return True) -- -- , ("C-Right", edit.buffers._1._1 %= nextToken >> return True) -- ] sq -- where Right ctrlG = parseKeys "C-g" -- isChar = case S.viewl sq of -- (KChar a) S.:< _ -> Just a -- _ -> Nothing
EleDiaz/Skell
src/Skell/Core.hs
bsd-3-clause
1,585
0
14
616
221
125
96
20
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. import Prelude import Duckling.Ranking.Generate main :: IO () main = regenAllClassifiers
rfranek/duckling
exe/RegenMain.hs
bsd-3-clause
393
0
6
67
31
20
11
4
1
{-# LANGUAGE CPP #-} module Main where import Distribution.Client.DistDirLayout import Distribution.Client.ProjectConfig import Distribution.Client.Config (defaultCabalDir) import Distribution.Client.ProjectPlanning import Distribution.Client.ProjectBuilding import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.Types (GenericReadyPackage(..), installedPackageId) import Distribution.Package hiding (installedPackageId) import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Version import Distribution.Verbosity import Distribution.Text #if !MIN_VERSION_base(4,8,0) import Data.Monoid #endif import qualified Data.Map as Map import Control.Monad import Control.Exception import System.FilePath import System.Directory import Test.Tasty import Test.Tasty.HUnit main :: IO () main = defaultMain (testGroup "Integration tests (internal)" tests) tests :: [TestTree] tests = --TODO: tests for: -- * normal success -- * dry-run tests with changes [ testGroup "Exceptions during discovey and planning" $ [ testCase "no package" testExceptionInFindingPackage , testCase "no package2" testExceptionInFindingPackage2 ] , testGroup "Exceptions during building (local inplace)" $ [ testCase "configure" testExceptionInConfigureStep , testCase "build" testExceptionInBuildStep -- , testCase "register" testExceptionInRegisterStep ] --TODO: need to repeat for packages for the store , testGroup "Regression tests" $ [ testCase "issue #3324" testRegressionIssue3324 ] ] testExceptionInFindingPackage :: Assertion testExceptionInFindingPackage = do BadPackageLocations locs <- expectException "BadPackageLocations" $ void $ planProject testdir config case locs of [BadLocGlobEmptyMatch "./*.cabal"] -> return () _ -> assertFailure "expected BadLocGlobEmptyMatch" cleanProject testdir where testdir = "exception/no-pkg" config = mempty testExceptionInFindingPackage2 :: Assertion testExceptionInFindingPackage2 = do BadPackageLocations locs <- expectException "BadPackageLocations" $ void $ planProject testdir config case locs of [BadLocGlobBadMatches "./" [BadLocDirNoCabalFile "."]] -> return () _ -> assertFailure $ "expected BadLocGlobBadMatches, got " ++ show locs cleanProject testdir where testdir = "exception/no-pkg2" config = mempty testExceptionInConfigureStep :: Assertion testExceptionInConfigureStep = do plan <- planProject testdir config plan' <- executePlan plan (_pkga1, failure) <- expectPackageFailed plan' pkgidA1 case failure of ConfigureFailed _str -> return () _ -> assertFailure $ "expected ConfigureFailed, got " ++ show failure cleanProject testdir where testdir = "exception/configure" config = mempty pkgidA1 = PackageIdentifier (PackageName "a") (Version [1] []) testExceptionInBuildStep :: Assertion testExceptionInBuildStep = do plan <- planProject testdir config plan' <- executePlan plan (_pkga1, failure) <- expectPackageFailed plan' pkgidA1 expectBuildFailed failure where testdir = "exception/build" config = mempty pkgidA1 = PackageIdentifier (PackageName "a") (Version [1] []) -- | See <https://github.com/haskell/cabal/issues/3324> -- testRegressionIssue3324 :: Assertion testRegressionIssue3324 = do -- expected failure first time due to missing dep plan1 <- executePlan =<< planProject testdir config (_pkgq, failure) <- expectPackageFailed plan1 pkgidQ expectBuildFailed failure -- add the missing dep, now it should work let qcabal = basedir </> testdir </> "q" </> "q.cabal" withFileFinallyRestore qcabal $ do appendFile qcabal (" build-depends: p\n") plan2 <- executePlan =<< planProject testdir config _ <- expectPackageInstalled plan2 pkgidP _ <- expectPackageInstalled plan2 pkgidQ return () where testdir = "regression/3324" config = mempty pkgidP = PackageIdentifier (PackageName "p") (Version [0,1] []) pkgidQ = PackageIdentifier (PackageName "q") (Version [0,1] []) --------------------------------- -- Test utils to plan and build -- basedir :: FilePath basedir = "tests" </> "IntegrationTests2" planProject :: FilePath -> ProjectConfig -> IO PlanDetails planProject testdir cliConfig = do cabalDir <- defaultCabalDir let cabalDirLayout = defaultCabalDirLayout cabalDir projectRootDir <- canonicalizePath ("tests" </> "IntegrationTests2" </> testdir) let distDirLayout = defaultDistDirLayout projectRootDir -- Clear state between test runs. The state remains if the previous run -- ended in an exception (as we leave the files to help with debugging). cleanProject testdir (elaboratedPlan, elaboratedShared, projectConfig) <- rebuildInstallPlan verbosity projectRootDir distDirLayout cabalDirLayout cliConfig let targets = Map.fromList [ (installedPackageId pkg, [BuildDefaultComponents]) | InstallPlan.Configured pkg <- InstallPlan.toList elaboratedPlan , pkgBuildStyle pkg == BuildInplaceOnly ] elaboratedPlan' = pruneInstallPlanToTargets targets elaboratedPlan (elaboratedPlan'', pkgsBuildStatus) <- rebuildTargetsDryRun distDirLayout elaboratedPlan' let buildSettings = resolveBuildTimeSettings verbosity cabalDirLayout (projectConfigShared projectConfig) (projectConfigBuildOnly projectConfig) (projectConfigBuildOnly cliConfig) return (distDirLayout, elaboratedPlan'', elaboratedShared, pkgsBuildStatus, buildSettings) type PlanDetails = (DistDirLayout, ElaboratedInstallPlan, ElaboratedSharedConfig, BuildStatusMap, BuildTimeSettings) executePlan :: PlanDetails -> IO ElaboratedInstallPlan executePlan (distDirLayout, elaboratedPlan, elaboratedShared, pkgsBuildStatus, buildSettings) = rebuildTargets verbosity distDirLayout elaboratedPlan elaboratedShared pkgsBuildStatus -- Avoid trying to use act-as-setup mode: buildSettings { buildSettingNumJobs = 1 } cleanProject :: FilePath -> IO () cleanProject testdir = do alreadyExists <- doesDirectoryExist distDir when alreadyExists $ removeDirectoryRecursive distDir where projectRootDir = "tests" </> "IntegrationTests2" </> testdir distDirLayout = defaultDistDirLayout projectRootDir distDir = distDirectory distDirLayout verbosity :: Verbosity verbosity = minBound --normal --verbose --maxBound --minBound --------------------------------------- -- HUint style utils for this context -- expectException :: Exception e => String -> IO a -> IO e expectException expected action = do res <- try action case res of Left e -> return e Right _ -> throwIO $ HUnitFailure $ "expected an exception " ++ expected expectPackagePreExisting :: ElaboratedInstallPlan -> PackageId -> IO InstalledPackageInfo expectPackagePreExisting plan pkgid = do planpkg <- expectPlanPackage plan pkgid case planpkg of InstallPlan.PreExisting pkg -> return pkg _ -> unexpectedPackageState "PreExisting" planpkg expectPackageConfigured :: ElaboratedInstallPlan -> PackageId -> IO ElaboratedConfiguredPackage expectPackageConfigured plan pkgid = do planpkg <- expectPlanPackage plan pkgid case planpkg of InstallPlan.Configured pkg -> return pkg _ -> unexpectedPackageState "Configured" planpkg expectPackageInstalled :: ElaboratedInstallPlan -> PackageId -> IO (ElaboratedConfiguredPackage, Maybe InstalledPackageInfo, BuildSuccess) expectPackageInstalled plan pkgid = do planpkg <- expectPlanPackage plan pkgid case planpkg of InstallPlan.Installed (ReadyPackage pkg) mipkg result -> return (pkg, mipkg, result) _ -> unexpectedPackageState "Installed" planpkg expectPackageFailed :: ElaboratedInstallPlan -> PackageId -> IO (ElaboratedConfiguredPackage, BuildFailure) expectPackageFailed plan pkgid = do planpkg <- expectPlanPackage plan pkgid case planpkg of InstallPlan.Failed pkg failure -> return (pkg, failure) _ -> unexpectedPackageState "Failed" planpkg unexpectedPackageState :: String -> ElaboratedPlanPackage -> IO a unexpectedPackageState expected planpkg = throwIO $ HUnitFailure $ "expected to find " ++ display (packageId planpkg) ++ " in the " ++ expected ++ " state, but it is actually in the " ++ actual ++ "state." where actual = case planpkg of InstallPlan.PreExisting{} -> "PreExisting" InstallPlan.Configured{} -> "Configured" InstallPlan.Processing{} -> "Processing" InstallPlan.Installed{} -> "Installed" InstallPlan.Failed{} -> "Failed" expectPlanPackage :: ElaboratedInstallPlan -> PackageId -> IO ElaboratedPlanPackage expectPlanPackage plan pkgid = case [ pkg | pkg <- InstallPlan.toList plan , packageId pkg == pkgid ] of [pkg] -> return pkg [] -> throwIO $ HUnitFailure $ "expected to find " ++ display pkgid ++ " in the install plan but it's not there" _ -> throwIO $ HUnitFailure $ "expected to find only one instance of " ++ display pkgid ++ " in the install plan but there's several" expectBuildFailed :: BuildFailure -> IO () expectBuildFailed (BuildFailed _str) = return () expectBuildFailed failure = assertFailure $ "expected BuildFailed, got " ++ show failure --------------------------------------- -- Other utils -- -- | Allow altering a file during a test, but then restore it afterwards -- withFileFinallyRestore :: FilePath -> IO a -> IO a withFileFinallyRestore file action = do copyFile file backup action `finally` renameFile backup file where backup = file <.> "backup"
Heather/cabal
cabal-install/tests/IntegrationTests2.hs
bsd-3-clause
10,650
0
15
2,666
2,137
1,081
1,056
224
5
{-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-import-lists #-} {-| Module : Reflex.Dom.HTML5.Component.Tree.LevelNCombNS Description : Helpers to build tree-based components. Copyright : (c) gspia 2018 - License : BSD Maintainer : gspia = Tree.LevelNCombNS This contains structures to define the behavior of the nodes having depth larger than 1 or 1 (root is 0, and level below root has depth 1). -} module Reflex.Dom.HTML5.Component.Tree.LevelNCombNS ( LevelNFuns (..) , levelNfADEs , levelNfCombFun , levelNfNodeAttr , levelNfWrapAttr , levelNfEUP , levelNfnext , levelNfMkLevelNF , defLevelNUlLiFuns , silentPlainLevelNUlLiFuns , defLevelNDivAFuns , silentPlainLevelNDivAFuns , defLevelNDivDivFuns , silentPlainLevelNDivDivFuns , defLevelNNoneDivFuns , silentPlainLevelNNoneDivFuns , defLevelNNoneAFuns , silentPlainLevelNNoneAFuns , levelNListener , levelNDraw , levelNActivity , setLevelNDraws , mkLevelN ) where import Control.Lens import Control.Monad (forM) import Control.Monad.Fix -- import qualified Data.Map as Map import Data.Tree -- import Data.Text (Text) import qualified Data.Text as T import Language.Javascript.JSaddle import Reflex import Reflex.Dom.Core import qualified Reflex.Dom.HTML5.Attrs as A -- import qualified Reflex.Dom.HTML5.Elements as E -- TODO -- import Reflex.Dom.HTML5.Component.Common.StateInfo import Reflex.Dom.HTML5.Component.Common.CompEvent -- import Reflex.Dom.HTML5.Component.Common.DrawFuns import Reflex.Dom.HTML5.Component.Tree.Common import Reflex.Dom.HTML5.Component.Tree.ActNode -- import Data.Monoid -- TODO DD -------------------------------------------------------------------------------- -- | A data structure used to specify the non-root-node behavior. data LevelNFuns t m a r = LevelNFuns { _levelNfADEs ∷ CommonADEfuns t m a ActNode r -- ^ See 'CommonADEfuns'. This contains four functions that -- change the 'ActiveState', decide on how to activate nodes, -- draw nodes and how the nodes produce events. , _levelNfCombFun ∷ CommonADEfuns t m a ActNode r → Dynamic t (Maybe [ActiveState t ActNode r]) → ActiveState t ActNode r → Dynamic t a → Event t (CompEvent t ActNode r) → CompState t ActNode r → m (CompEvent t ActNode r) -- ^ A function that combines the above fours functions given in -- the 'CommonADfuns'. -- See 'adeCombFun'. , _levelNfNodeAttr ∷ ActiveState t ActNode r → Dynamic t A.Attr -- ^ A function that sets the attributes for a node in a level n of a tree -- (where n > 1). -- , _levelNfWrapAttr ∷ Dynamic t (ActiveState t ActNode r) -- → ActNode → Dynamic t E.Ul , _levelNfWrapAttr ∷ Dynamic t (ActiveState t ActNode r) → ActNode → Dynamic t A.Attr -- ^ A function that sets the attributes. First param is the last node -- where an event occurred (with state info) and the second parameter tells, -- which node we are making (drawing, building). , _levelNfEUP ∷ ElemUse -- ^ This gives the elements that we use. The wrapper wraps the nodes of -- a level. E.g. ul-element is a wrapper and li-element is the node item. , _levelNfnext ∷ Maybe (LevelNFuns t m a r) -- ^ If given a new set of funs, then those are applied on the next -- level when constructing the nodes. If this is not given and the tree -- is deeper (has futher levels of nodes), then we continue to use the -- current 'LevelNFuns' on those nodes. , _levelNfMkLevelNF ∷ (LevelNFuns t m a r → Dynamic t (Maybe [ActiveState t ActNode r]) → Event t (CompEvent t ActNode r) → CompState t ActNode r → [Int] → Tree (ActiveState t ActNode r, Dynamic t a) → m [CompEvent t ActNode r]) -- ^ The function that makes the Nth level of nodes (not 1st nor root). } -------------------------------------------------------------------------------- -- | A lens. levelNfADEs ∷ Lens' (LevelNFuns t m a r) (CommonADEfuns t m a ActNode r) levelNfADEs f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns g f2 f3 f4 f5 f6 f7) (f f1) -- | A lens. levelNfCombFun ∷ Lens' (LevelNFuns t m a r) (CommonADEfuns t m a ActNode r → Dynamic t (Maybe [ActiveState t ActNode r]) → ActiveState t ActNode r → Dynamic t a → Event t (CompEvent t ActNode r) → CompState t ActNode r → m (CompEvent t ActNode r)) levelNfCombFun f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns f1 g f3 f4 f5 f6 f7) (f f2) -- | A lens. levelNfNodeAttr ∷ Lens' (LevelNFuns t m a r) (ActiveState t ActNode r → Dynamic t A.Attr) levelNfNodeAttr f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns f1 f2 g f4 f5 f6 f7) (f f3) -- | A lens. levelNfWrapAttr ∷ Lens' (LevelNFuns t m a r) (Dynamic t (ActiveState t ActNode r) → ActNode → Dynamic t A.Attr) levelNfWrapAttr f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns f1 f2 f3 g f5 f6 f7) (f f4) -- | A lens. levelNfEUP ∷ Lens' (LevelNFuns t m a r) ElemUse levelNfEUP f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns f1 f2 f3 f4 g f6 f7) (f f5) -- | A lens. levelNfnext ∷ Lens' (LevelNFuns t m a r) (Maybe (LevelNFuns t m a r)) levelNfnext f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (\g → LevelNFuns f1 f2 f3 f4 f5 g f7) (f f6) -- | A lens. levelNfMkLevelNF ∷ Lens' (LevelNFuns t m a r) (LevelNFuns t m a r → Dynamic t (Maybe [ActiveState t ActNode r]) → Event t (CompEvent t ActNode r) → CompState t ActNode r → [Int] → Tree (ActiveState t ActNode r, Dynamic t a) → m [CompEvent t ActNode r]) levelNfMkLevelNF f (LevelNFuns f1 f2 f3 f4 f5 f6 f7) = fmap (LevelNFuns f1 f2 f3 f4 f5 f6) (f f7) -------------------------------------------------------------------------------- -- | Default value for 'LevelNFuns'. Uses ul and li. defLevelNUlLiFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r defLevelNUlLiFuns = LevelNFuns defCommonADEfuns adeCombFun defLiLeafNodeAttrF defUlSFWrapAttrF elemUseUlLi Nothing -- no next level in the default mkLevelN -- | Silent value for 'LevelNFuns'. Uses ul and li. silentPlainLevelNUlLiFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r silentPlainLevelNUlLiFuns = LevelNFuns silentPlainADE adeCombSilentPlain defLiLeafNodeAttrF defUlSFWrapAttrF elemUseUlLi Nothing -- no next level in the default mkLevelN -- | Default value for 'LevelNFuns'. Uses div and a. defLevelNDivAFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r defLevelNDivAFuns = LevelNFuns defCommonADEfuns adeCombFun defALeafNodeAttrF defDivSFWrapAttrF elemUseDivA Nothing -- no next level in the default mkLevelN -- | Silent value for 'LevelNFuns'. Uses div and a. silentPlainLevelNDivAFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r silentPlainLevelNDivAFuns = LevelNFuns silentPlainADE adeCombSilentPlain defALeafNodeAttrF defDivSFWrapAttrF elemUseDivA Nothing -- no next level in the default mkLevelN -- | Default value for 'LevelNFuns'. Uses div and div. defLevelNDivDivFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r defLevelNDivDivFuns = LevelNFuns defCommonADEfuns adeCombFun defDivLeafNodeAttrF defDivSFWrapAttrF elemUseDivDiv Nothing -- no next level in the default mkLevelN -- | Silent value for 'LevelNFuns'. Uses div and div. silentPlainLevelNDivDivFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r silentPlainLevelNDivDivFuns = LevelNFuns silentPlainADE adeCombSilentPlain defDivLeafNodeAttrF defDivSFWrapAttrF elemUseDivDiv Nothing -- no next level in the default mkLevelN -- | Default value for 'LevelNFuns'. Uses div for the elements and nothing -- for the wrapper. defLevelNNoneDivFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r defLevelNNoneDivFuns = LevelNFuns defCommonADEfuns adeCombFun defDivLeafNodeAttrF defDivSFWrapAttrF -- this is not used, can be any of the AttrFs. elemUseNoneDiv Nothing -- no next level in the default mkLevelN -- | Silent value for 'LevelNFuns'. Uses div for the elements and nothing -- for the wrapper. silentPlainLevelNNoneDivFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r silentPlainLevelNNoneDivFuns = LevelNFuns silentPlainADE adeCombSilentPlain defDivLeafNodeAttrF defDivSFWrapAttrF -- this is not used, can be any of the AttrFs. elemUseNoneDiv Nothing -- no next level in the default mkLevelN -- | Default value for 'LevelNFuns'. Uses a for the elements and nothing -- for the wrapper. defLevelNNoneAFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r defLevelNNoneAFuns = LevelNFuns defCommonADEfuns adeCombFun defALeafNodeAttrF defDivSFWrapAttrF -- this is not used, can be any of the AttrFs. elemUseNoneA Nothing -- no next level in the default mkLevelN -- | Silent value for 'LevelNFuns'. Uses div for the elements and nothing -- for the wrapper. silentPlainLevelNNoneAFuns ∷ (Reflex t, MonadHold t m, TriggerEvent t m, MonadFix m , DomBuilder t m, PostBuild t m, MonadJSM m -- , Show a, Eq a , DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r silentPlainLevelNNoneAFuns = LevelNFuns silentPlainADE adeCombSilentPlain defALeafNodeAttrF defDivSFWrapAttrF -- this is not used, can be any of the AttrFs. elemUseNoneA Nothing -- no next level in the default mkLevelN -------------------------------------------------------------------------------- -- | Listening-lens for levelN-nodes. levelNListener ∷ Lens' (LevelNFuns t m a r) (ActiveState t ActNode r → ActiveState t ActNode r) levelNListener = levelNfADEs . adeListen -- | Node drawing -lens for levelN-nodes. levelNDraw ∷ Lens' (LevelNFuns t m a r) (Dynamic t a → ActiveState t ActNode r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r)) levelNDraw = levelNfADEs . adeDraw -- | Node activity function -lens for levelN-nodes. levelNActivity ∷ Lens' (LevelNFuns t m a r) (Dynamic t (Maybe [ActiveState t ActNode r]) → Event t (CompEvent t ActNode r) → CompState t ActNode r → ActiveState t ActNode r → m (ActiveState t ActNode r)) levelNActivity = levelNfADEs . adeActivate -- | Recursively set a drawing function to each 'LevelNFuns' used. setLevelNDraws ∷ (Dynamic t a → ActiveState t ActNode r → m (Element EventResult (DomBuilderSpace m) t, Dynamic t r)) → LevelNFuns t m a r → LevelNFuns t m a r setLevelNDraws fd lf = case n of Just nn → let sublf = setLevelNDraws fd nn in lf2 { _levelNfnext = Just sublf } Nothing → lf2 where lf2 = set levelNDraw fd lf n = _levelNfnext lf2 -------------------------------------------------------------------------------- -- | A function to make a level of nodes that have depth larger than 1 or 1. -- It means specifying, how to draw and handle events. -- -- Note: this doesn't show the root label of a tree. mkLevelN ∷ forall t m a r. (Reflex t, DomBuilder t m, PostBuild t m , TriggerEvent t m, MonadJSM m, MonadFix m -- , Eq a, Show a , MonadHold t m, DomBuilderSpace m ~ GhcjsDomSpace , ActSretval r) ⇒ LevelNFuns t m a r -- ^ Funs and decorations → Dynamic t (Maybe [ActiveState t ActNode r]) -- ^ User given activity information obtained from tree configurations. → Event t (CompEvent t ActNode r) -- ^ Event coming from tree (can be from nodes). → CompState t ActNode r -- ^ A function combining XX's can use the current 'CompState'. → [Int] -- ^ A path from root to the node. → Tree (ActiveState t ActNode r, Dynamic t a) -- ^ Some content... → m [CompEvent t ActNode r] mkLevelN lvlFs dmlst evB trSt pth treeE = do let combF = _levelNfCombFun lvlFs (_levelNfADEs lvlFs) mNextL = _levelNfnext lvlFs mkFun = _levelNfMkLevelNF lvlFs sFelms = subForest treeE -- Note: these are pairs and have the content that we will show. -- We take the forest and show the root of each tree in the forest. -- dmlst = _treeCActivityConf tc ∷ Dynamic t (Maybe [ActiveState t ActNode]) astD = defActiveStateTree & set activeStateElemId (ActNpath pth) useEltxt = _euLeafNode . _levelNfEUP $ lvlFs -- text -- useEltxtAlt = _euLNodeDD . _levelNfEUP $ lvlFs -- text useWraptxt = _euSFWrap . _levelNfEUP $ lvlFs -- text -- defElm = _euDef . _levelNfEUP $ lvlFs ∷ A.Attr -- ∷ ActiveState t ActNode actS ∷ ActiveState t ActNode r ← (_adeActivate . _levelNfADEs) lvlFs dmlst evB trSt $ (_adeListen . _levelNfADEs) lvlFs astD -- evTE ← E.ulD (_levelNfWrapAttr lvlFs (constDyn actS) $ ActNpath pth) $ do -- text "mkLevelN" evTE ← if not (T.null useWraptxt) then do -- text "not null wrap (mkLevelN)." -- text $ " and useWraptxt = " <> useWraptxt -- text $ ". Len sFelms = " <> (T.pack . show . length) sFelms elDynAttr useWraptxt (_levelNfWrapAttr lvlFs (constDyn actS) $ ActNpath pth) $ edsF sFelms useEltxt combF mNextL mkFun else do -- text "null wrap (mkLevelN)" -- text $ ". Len sFelms = " <> (T.pack . show . length) sFelms edsF sFelms useEltxt combF mNextL mkFun -- eds ∷ [Event t (CompEvent t ActNode)] ← forM sFelms pure evTE where edsF sFelms useEltxt combF mNextL mkFun = do -- text "edsF" eds ∷ [[CompEvent t ActNode r]] ← forM sFelms ( \elmTr → do -- for each tree in forest, do: let (elm,ast2) = rootLabel elmTr -- and its node and content -- sFelms2 = subForest elmTr pth2 = getPath $ _activeStateElemId elm -- text $ "pth2 = " <> (T.pack . show) pth2 -- text $ "useEltxt = " <> useEltxt -- Here we have to check if this a leaf or does this have a -- sub-tree. if isLeaf elmTr then mdo -- text $ "leaf elmTr" -- te ← E.liD (_levelNfNodeAttr lvlFs $ _ceMe te) $ te ∷ CompEvent t ActNode r -- ← elDynAttr useEltxt (_levelNfNodeAttr lvlFs $ _ceMe te) $ ← elDynAttr useEltxt (_levelNfNodeAttr lvlFs $ _ceMe te) $ combF dmlst elm ast2 evB trSt -- let te2 = compEvFiring [te] -- pure te2 pure [te] else mdo -- This is a tree (a sub-tree). -- text $ "non-leaf elmTr" -- E.brN blank -- Thus, draw the root node and recurse into the tree. let dAttr = _levelNfNodeAttr lvlFs $ _ceMe te -- evTe ∷ Event t (CompEvent t ActNode) (te,teRst) ∷ (CompEvent t ActNode r, [CompEvent t ActNode r]) ← elDynAttr useEltxt dAttr $ do te3 ∷ CompEvent t ActNode r ← combF dmlst elm ast2 evB trSt -- and next the forest ce ∷ [CompEvent t ActNode r] ← case mNextL of Just nFs → mkFun nFs dmlst evB trSt pth2 elmTr Nothing → mkFun lvlFs dmlst evB trSt pth2 elmTr pure (te3, ce) pure $ te : teRst ) pure $ concat eds
gspia/reflex-dom-htmlea
lib/src/Reflex/Dom/HTML5/Component/Tree/LevelNCombNS.hs
bsd-3-clause
18,523
0
27
5,607
3,785
1,971
1,814
281
4
module Types where import Jetpack data HLSProxy = HLSProxy { url :: String , ready :: Bool } deriving (Show) data TwitchStream = TwitchStream { tsId :: Int , channel :: String , quality :: String , proxy :: Maybe HLSProxy } deriving (Show) u = undefined instance ToJSON HLSProxy where toJSON HLSProxy{..} = js_object [ "ready" .= ready , "indexUrl" .= url ] instance FromJSON HLSProxy where parseJSON (JsObject v) = HLSProxy <$> v .: "indexUrl" <*> v .: "ready" instance ToJSON TwitchStream where toJSON TwitchStream{..} = js_object [ "id" .= tsId , "channel" .= channel , "quality" .= quality , "proxy" .= proxy ] instance FromJSON TwitchStream where parseJSON (JsObject v) = TwitchStream <$> v .: "id" <*> v .: "channel" <*> v .: "quality" <*> v .: "proxy" ----------------- demoStream :: Maybe TwitchStream demoStream = js_decode d2 pp1 :: Maybe HLSProxy pp1 = js_decode p1 p1 = "{\"indexUrl\": \"http://54.171.4.111/video/lirik/best/stream.m3u8\", \"ready\": true}" c = js_decode' d1 d1 = "{\"url\": \"twitch.tv/geers_art\", \"quality\": \"best\", \"channel\": \"geers_art\", \"id\": 4, \"proxy\": null}" d1' = TwitchStream { tsId = 4 , channel = "geers_art" , quality = "best" , proxy = Nothing } d2 = "{\"url\": \"twitch.tv/lirik\", \"quality\": \"best\", \"channel\": \"lirik\", \"id\": 5, \"proxy\": {\"indexUrl\": \"http://54.171.4.111/video/lirik/best/stream.m3u8\", \"ready\": true}}" d2' = TwitchStream { tsId = 4 , channel = "geers_art" , quality = "best" , proxy = Just $ HLSProxy { ready = True , url = "http://54.171.4.111/video/lirik/best/stream.m3u8" } } jsToS :: ToJSON a => a -> LbsByteString jsToS = js_encode . toJSON printJs :: ToJSON a => a -> IO () printJs x = lbs_putStr (jsToS x) >> putStrLn ""
rvion/ride
twitch-cast/src/Types.hs
bsd-3-clause
1,850
0
13
395
473
260
213
-1
-1
{-# LANGUAGE OverloadedStrings #-} module State.User where import Control.Monad (void, forM) import Control.Applicative import Snap.Snaplet.PostgresqlSimple import Data.ByteString (ByteString) import Data.Text (Text) import Data.Maybe import Application import State.Site import Helpers.State data SiteUser = SiteUser { siteUserId :: Int , siteUserSiteId :: Int , siteUserAdmin :: Bool } deriving (Eq, Show) instance FromRow SiteUser where fromRow = SiteUser <$> field <*> field <*> field newUser :: SiteUser -> AppHandler () newUser (SiteUser uid si adm) = void $ do execute "insert into users (id, admin) values (?,?)" (uid, adm) execute "insert into users_sites (user_id, site_id) values (?,?)" (uid, si) newSiteUser :: SiteUser -> AppHandler () newSiteUser (SiteUser uid si _) = void $ execute "insert into users_sites (user_id, site_id) values (?,?)" (uid, si) getUser :: Int -> AppHandler (Maybe SiteUser) getUser id' = singleQuery "select id, site_id, admin from users join users_sites on id = user_id where id = ?" (Only id') deleteSiteUser :: Site -> Int -> AppHandler () deleteSiteUser site i = void $ execute "delete from users_sites where user_id = ? and site_id = ?" (i, siteId site) deleteUser :: Int -> AppHandler () deleteUser i = void $ execute "delete from snap_auth_user where uid = ?" (Only i) updateUser :: SiteUser -> AppHandler () updateUser u = void $ execute "update users set admin = ? where id = ?" (siteUserAdmin u, siteUserId u) instance FromRow Text where fromRow = field getUserNameById :: Int -> AppHandler (Maybe Text) getUserNameById id' = singleQuery "select login from snap_auth_user where uid = ?" (Only id') getUserAndNameById :: Int -> AppHandler (Maybe (SiteUser, Text)) getUserAndNameById i = do r <- query "select U.id, S.site_id, U.admin, A.login from users as U join users_sites as S on U.id = S.user_id join snap_auth_user as A on A.uid = U.id where U.id = ?" (Only i) fmap listToMaybe $ forM r $ \(s :. Only t) -> return (s, t) getSiteUsers :: Site -> AppHandler [(SiteUser, Text)] getSiteUsers site = do res <- query "select U.id, S.site_id, U.admin, A.login from users as U join users_sites as S on U.id = S.user_id join snap_auth_user as A on A.uid = U.id where S.site_id = ?" (Only (siteId site)) forM res $ \(s :. Only t) -> return (s, t)
dbp/positionsites
src/State/User.hs
bsd-3-clause
2,428
0
12
509
634
329
305
42
1
module Main where import Lib main :: IO () main = start
dinosaur-lin/haskell-game2048
app/Main.hs
bsd-3-clause
58
0
6
14
22
13
9
4
1
{-# LANGUAGE OverloadedStrings #-} import System.Environment import Data.Attoparsec.ByteString.Char8 (parseOnly) import qualified Data.ByteString as B import qualified Data.Vector as V import VM.Core import VM.Parser main = do [filename] <- getArgs file <- B.readFile filename case parseOnly parseFile file of Left err -> putStrLn $ "Error parsing: " ++ err Right (cpu, instructions) -> do putStrLn $ "Current CPU: \n" ++ (show cpu) putStrLn . unlines . (map show) $ instructions runPrint (V.fromList instructions) cpu
gabrielPeart/VM.hs
src/Main.hs
mit
586
0
15
140
170
89
81
16
2
-- -- -- ----------------- -- Exercise 8.18. ----------------- -- -- -- module E'8'18 where -- Note: Chapter 7> cabal install import E'7'12 ( ins ) import E'8'11 ( isInteger ) import GHC.Base ( map ) import Data.List ( intercalate ) sortIntegers :: IO () sortIntegers = do putStr "\nType in integers to sort (get result typing 0)\n\n" sortedList <- (sortIntegers' []) putStr ( '\n' : ( intercalate ", " (map show sortedList) ) ++ "\n\n" ) where sortIntegers' :: [Integer] -> IO [Integer] sortIntegers' carry = do input <- getLine if (isInteger input) then ( if ( (read input :: Integer) /= 0 ) then ( sortIntegers' ( ins (read input :: Integer) carry ) ) else (return carry) ) else ( do putStr "This is not an integer.\n" sortIntegers' carry ) -- I used insertion sort. From an algorithmic/domain viewpoint there may still exist better -- (hybrid-) solutions (depending on the input-size, response time, energy consumption ...). -- If you want a quick result after the user typed in 0, then insertion sort should do OK. If the -- number of integers that will be typed in is known to be small, they will be sorted in time -- (without noticeable delay) even if we sort after all input was received and we might use a more -- efficient algorithm (quick sort, merge sort, ...).
pascal-knodel/haskell-craft
_/links/E'8'18.hs
mit
1,464
0
17
416
248
138
110
21
3
{-# LANGUAGE TemplateHaskell, UnicodeSyntax #-} {-# OPTIONS_GHC -Wno-unused-imports -Wno-type-defaults #-} module FlexTest where import Control.Lens import Control.Lens.TH import Data.List import Linear hiding (basis, trace) import Prelude.Unicode import qualified Hedgehog as H import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Tasty import Test.Tasty.ExpectedFailure import Test.Tasty.Hspec import Test.Tasty.HUnit import Test.Tasty.QuickCheck hiding (shrink) import Text.Printf (printf) import Flatland import Flex -- * Dummy Flex -- data FreeFlex = FF { _ffGeo ∷ Geo , _ffSize ∷ Di (Maybe Double) , _ffChildren ∷ [FreeFlex] , _ffArea ∷ Area'LU Double } makeLenses ''FreeFlex instance Flex (FreeFlex) where geo = ffGeo size = ffSize children = ffChildren area = ffArea leaf ∷ Double → Double → FreeFlex leaf w h = node' (Just w) (Just h) [] leaf' ∷ Maybe Double → Maybe Double → FreeFlex leaf' w h = node' w h [] node ∷ Double → Double → [FreeFlex] → FreeFlex node w h cs = node' (Just w) (Just h) cs node' ∷ Maybe Double → Maybe Double → [FreeFlex] → FreeFlex node' w h cs = FF mempty (Di $ V2 w h) cs mempty -- * -- test_scene ∷ TestTree test_scene = let r = node 400 200 [ leaf 50 50 , node' Nothing Nothing [ leaf 50 100 , leaf 100 50 ] & geo.direction .~ DirRow & geo.align'content .~ AlignStart & geo.grow .~ 1 , leaf 200 50 ] & geo.direction .~ DirColumn & geo.align'content .~ AlignStart & geo.grow .~ 1 & layout (mkSize 400 200) in testGroup "scene" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 400 100) , testCase "child 1.0" $ r^.child 1.child 0.area @?= Area (mkLU 0 0) (mkSize 50 100) , testCase "child 1.1" $ r^.child 1.child 1.area @?= Area (mkLU 50 0) (mkSize 100 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 150) (mkSize 200 50) ] -- * -- test_grow1 ∷ TestTree test_grow1 = let r = node 60 240 [ leaf 60 30 & geo.grow .~ 0 , leaf 60 0 & geo.grow .~ 1 , leaf 60 0 & geo.grow .~ 2 ] & layout (mkSize 60 240) in testGroup "grow1: three children grow proportionally to property" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 60 30) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 30) (mkSize 60 70) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 100) (mkSize 60 140) ] test_grow2 ∷ TestTree test_grow2 = let r = node 100 100 [ leaf 100 20 & geo.grow .~ 1 , leaf 100 20 & geo.grow .~ 0 , leaf 100 20 ] & layout (mkSize 100 100) in testGroup "grow2: only grow if property set to 1" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 60) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 60) (mkSize 100 20) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 80) (mkSize 100 20) ] test_grow3 ∷ TestTree test_grow3 = let r = node 100 100 [ leaf 100 50 & geo.grow .~ 2 , leaf 100 50 & geo.grow .~ 3 ] & layout (mkSize 100 100) in testGroup "grow3: growth has no effect if parent already full" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 100 50) ] test_grow4 ∷ TestTree test_grow4 = let r = node 100 100 [ leaf 100 25 , leaf 100 25 ] & geo.grow .~ 2 & layout (mkSize 100 100) in testGroup "grow4: parent growth property has no effect on children" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 100 25) ] test_grow5 ∷ TestTree test_grow5 = let r = node 100 100 [ leaf 100 25 & geo.grow .~ 1 ] & layout (mkSize 100 100) in testGroup "grow5: single child fills parent" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 100) ] test_grow6 ∷ TestTree test_grow6 = let r = node 100 100 [ leaf 100 45 & geo.grow .~ 1 , leaf 100 45 & geo.grow .~ 1 ] & layout (mkSize 100 100) in testGroup "grow6: two undersized children fill at equal rate" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 100 50) ] test_grow7 ∷ TestTree test_grow7 = let r = node 500 600 [ leaf 250 0 & geo.grow .~ 1 , leaf 250 50 & geo.grow .~ 1 , leaf 250 0 , leaf 250 0 & geo.grow .~ 1 , leaf 250 0 ] & layout (mkSize 500 600) in testGroup "grow7: sizes of flexible items should be ignored when growing" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 250 200) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 200) (mkSize 250 200) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 400) (mkSize 250 0) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 0 400) (mkSize 250 200) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 0 600) (mkSize 250 0) ] -- COMPLETE -- * -- test_wrap1 ∷ TestTree test_wrap1 = let r = node 100 300 [ leaf 100 150 , leaf 100 150 , leaf 100 150 , leaf 100 150 ] & geo.wrap .~ NoWrap & layout (mkSize 100 300) in testGroup "wrap1: NoWrap doesn't enable wrapping" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 75) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 75) (mkSize 100 75) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 150) (mkSize 100 75) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 0 225) (mkSize 100 75) ] test_wrap2 ∷ TestTree test_wrap2 = let r = node 100 300 [ leaf 50 150 , leaf 50 150 , leaf 50 150 , leaf 50 150 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignStart & layout (mkSize 100 300) in testGroup "wrap2: four non-stretching children wrap across two rows" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 150) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 150) (mkSize 50 150) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 150) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 50 150) (mkSize 50 150) ] test_wrap3 ∷ TestTree test_wrap3 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 50) ] test_wrap4 ∷ TestTree test_wrap4 = let r = node 120 120 [ leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 25 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 25 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 25 0) (mkSize 25 50) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 25 50) (mkSize 25 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 50 0) (mkSize 25 50) , testCase "child 5" $ r^.child 5.area @?= Area (mkLU 50 50) (mkSize 25 50) ] test_wrap5 ∷ TestTree test_wrap5 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.justify'content .~ AlignEnd & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 20) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 70) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 70) (mkSize 50 50) ] test_wrap6 ∷ TestTree test_wrap6 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.justify'content .~ AlignCenter & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap6: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 10) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 60) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 35) (mkSize 50 50) ] test_wrap7 ∷ TestTree test_wrap7 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.justify'content .~ AlignSpaceAround & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap7: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 5) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 65) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 35) (mkSize 50 50) ] test_wrap8 ∷ TestTree test_wrap8 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.justify'content .~ AlignSpaceBetween & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap8: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 70) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 50) ] test_wrap9 ∷ TestTree test_wrap9 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 & geo.grow .~ 1 , leaf 50 50 & geo.grow .~ 1 , leaf 50 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap9: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 70) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 70) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 50 70) (mkSize 50 50) ] test_wrap10 ∷ TestTree test_wrap10 = let r = node 120 120 [ leaf 50 40 , leaf 70 30 , leaf 60 40 , leaf 40 50 , leaf 50 60 ] & geo.wrap .~ Wrap & geo.align'items .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap10: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 70 30) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 70) (mkSize 60 40) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 70 0) (mkSize 40 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 70 50) (mkSize 50 60) ] -- XXX: ⊥ test_wrap11 ∷ TestTree test_wrap11 = let r = node 120 120 [ leaf 50 40 , leaf 70 30 , leaf 60 40 , leaf 40 50 , leaf 50 60 ] & geo.wrap .~ Wrap & geo.align'items .~ AlignCenter & layout (mkSize 120 120) in testGroup "wrap11: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 0) (mkSize 50 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 70 30) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 5 70) (mkSize 60 40) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 75 0) (mkSize 40 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 70 50) (mkSize 50 60) ] test_wrap12 ∷ TestTree test_wrap12 = let r = node 120 120 [ leaf 50 40 , leaf 70 30 , leaf 60 40 , leaf 40 50 , leaf 50 60 ] & geo.wrap .~ Wrap & geo.align'items .~ AlignEnd & layout (mkSize 120 120) in testGroup "wrap12: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 20 0) (mkSize 50 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 70 30) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 10 70) (mkSize 60 40) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 80 0) (mkSize 40 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 70 50) (mkSize 50 60) ] test_wrap13 ∷ TestTree test_wrap13 = let r = node 120 120 [ leaf 50 40 & geo.align'self .~ AlignEnd , leaf 70 30 , leaf 60 40 & geo.align'self .~ AlignCenter , leaf 40 50 & geo.align'self .~ AlignStart , leaf 50 60 , leaf 10 10 & geo.align'self .~ AlignEnd ] & geo.wrap .~ Wrap & layout (mkSize 120 120) in testGroup "wrap13: potpourri" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 20 0) (mkSize 50 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 70 30) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 5 70) (mkSize 60 40) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 70 0) (mkSize 40 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 70 50) (mkSize 50 60) , testCase "child 5" $ r^.child 5.area @?= Area (mkLU 110 110) (mkSize 10 10) ] test_wrap14 ∷ TestTree test_wrap14 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.wrap .~ ReverseWrap & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap14: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 70 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 70 50) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 20 0) (mkSize 50 50) ] test_wrap15 ∷ TestTree test_wrap15 = let r = node 120 120 [ leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 , leaf 25 50 ] & geo.wrap .~ ReverseWrap & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "wrap15: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 95 0) (mkSize 25 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 95 50) (mkSize 25 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 70 0) (mkSize 25 50) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 70 50) (mkSize 25 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 45 0) (mkSize 25 50) , testCase "child 5" $ r^.child 5.area @?= Area (mkLU 45 50) (mkSize 25 50) ] test_wrap16 ∷ TestTree test_wrap16 = let r = node 120 120 [ leaf 20 50 , leaf 20 50 , leaf 20 50 ] & geo.direction .~ DirColumn & geo.wrap .~ Wrap & geo.align'content .~ AlignStretch & layout (mkSize 120 120) in testGroup "wrap16: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 20 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 20 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 60 0) (mkSize 20 50) ] test_wrap17 ∷ TestTree test_wrap17 = let r = node 120 120 [ leaf 20 50 , leaf 20 50 , leaf 20 50 , leaf 20 50 , leaf 20 50 ] & geo.direction .~ DirColumn & geo.wrap .~ Wrap & geo.align'content .~ AlignStretch & layout (mkSize 120 120) in testGroup "wrap17: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 20 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 20 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 40 0) (mkSize 20 50) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 40 50) (mkSize 20 50) , testCase "child 4" $ r^.child 4.area @?= Area (mkLU 80 0) (mkSize 20 50) ] -- COMPLETE -- * -- test_basis1 ∷ TestTree test_basis1 = let r = node 100 100 [ leaf' (Just 100) Nothing & geo.basis .~ 60 , leaf 100 40 ] & layout (mkSize 100 100) in testGroup "basis1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 60) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 60) (mkSize 100 40) ] test_basis2 ∷ TestTree test_basis2 = let r = node 100 100 [ leaf 100 40 & geo.basis .~ 60 , leaf 100 40 ] & layout (mkSize 100 100) in testGroup "basis2: the basis attribute has priority over width/height" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 60) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 60) (mkSize 100 40) ] test_basis3 ∷ TestTree test_basis3 = let r = node 100 100 [ leaf' (Just 100) Nothing & geo.basis .~ (-60) , leaf 100 40 ] & layout (mkSize 100 100) in testGroup "basis3: the basis attribute is ignored if negative" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 0) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 0) (mkSize 100 40) ] test_basis4 ∷ TestTree test_basis4 = let r = node 100 100 [ leaf 100 40 & geo.basis .~ (-60) , leaf 100 40 ] & layout (mkSize 100 100) in testGroup "basis4: the basis attribute is ignored if negative" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 100 40) ] test_basis5 ∷ TestTree test_basis5 = let r = node 100 100 [ leaf 100 40 & geo.basis .~ 0 , leaf 100 40 ] & layout (mkSize 100 100) in testGroup "basis5: the basis attribute is ignored if 0" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 100 40) ] -- COMPLETE -- * -- test_order1 ∷ TestTree test_order1 = let r = node 200 200 [ leaf 50 50 & geo.order .~ Just 1 , leaf 50 50 & geo.order .~ Just 3 , leaf 50 50 & geo.order .~ Just 2 ] & layout (mkSize 200 200) in testGroup "order1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , expectFail $ testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 100) (mkSize 50 50) , expectFail $ testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 50 50) ] test_order2 ∷ TestTree test_order2 = let r = node 200 200 [ leaf 50 50 & geo.order .~ Just 2 , leaf 50 50 & geo.order .~ Just 3 , leaf 50 50 & geo.order .~ Just 1 ] & geo.direction .~ DirColumnReverse & layout (mkSize 200 200) in testGroup "order2: " [ expectFail $ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 100) (mkSize 50 50) , expectFail $ testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 50) , expectFail $ testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 150) (mkSize 50 50) ] test_order3 ∷ TestTree test_order3 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 & geo.order .~ Just (-1) , leaf 50 50 ] & geo.direction .~ DirColumnReverse & layout (mkSize 200 200) in testGroup "order3: " [ expectFail $ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 50) (mkSize 50 50) , expectFail $ testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 0) (mkSize 50 50) , expectFail $ testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 100) (mkSize 50 50) ] -- -- test_order4 skipped: -- > this test ensures that the insertion order of the children is preserved when they get re-ordered during layout -- -- * -- test_margin1 ∷ TestTree test_margin1 = let r = node 100 100 [ leaf 25 25 , leaf 25 25 & geo.margin .~ LRTB 15 15 10 10 , leaf 25 25 ] & geo.align'items .~ AlignStart & geo.justify'content .~ AlignStart & layout (mkSize 100 100) in testGroup "margin1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 25 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 15 35) (mkSize 25 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 70) (mkSize 25 25) ] test_margin2 ∷ TestTree test_margin2 = let r = node 100 100 [ leaf 25 25 , leaf 25 25 & geo.margin .~ LRTB 15 15 10 10 , leaf 25 25 ] & geo.align'items .~ AlignEnd & geo.justify'content .~ AlignStart & layout (mkSize 100 100) in testGroup "margin2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 75 0) (mkSize 25 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 60 35) (mkSize 25 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 75 70) (mkSize 25 25) ] test_margin3 ∷ TestTree test_margin3 = let r = node 100 100 [ leaf 25 25 , leaf 25 25 & geo.margin .~ LRTB 15 15 10 10 , leaf 25 25 ] & geo.align'items .~ AlignStart & geo.justify'content .~ AlignEnd & layout (mkSize 100 100) in testGroup "margin3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 5) (mkSize 25 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 15 40) (mkSize 25 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 75) (mkSize 25 25) ] test_margin4 ∷ TestTree test_margin4 = let r = node 100 100 [ leaf 25 25 , leaf 25 25 & geo.margin .~ LRTB 15 15 10 10 , leaf 25 25 ] & geo.align'items .~ AlignEnd & geo.justify'content .~ AlignEnd & layout (mkSize 100 100) in testGroup "margin4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 75 5) (mkSize 25 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 60 40) (mkSize 25 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 75 75) (mkSize 25 25) ] test_margin5 ∷ TestTree test_margin5 = let r = node 100 100 [ leaf 10 10 , leaf 10 10 & geo.margin .~ LRTB 15 10 0 0 , leaf 10 10 ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignStart & layout (mkSize 100 100) in testGroup "margin5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 45 0) (mkSize 10 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 10) (mkSize 10 10) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 45 20) (mkSize 10 10) ] test_margin6 ∷ TestTree test_margin6 = let r = node 100 100 [ leaf 10 10 , leaf 0 10 & geo.margin .~ LRTB 15 10 0 0 & geo.align'self .~ AlignStretch , leaf 10 10 ] & layout (mkSize 100 100) in testGroup "margin6 " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 10 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 15 10) (mkSize 75 10) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 20) (mkSize 10 10) ] test_margin7 ∷ TestTree test_margin7 = let r = node 100 100 [ leaf 10 10 , leaf 10 10 & geo.margin .~ LRTB 15 10 0 0 & geo.align'self .~ AlignStretch , leaf 10 10 ] & layout (mkSize 100 100) in testGroup "margin7 " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 10 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 15 10) (mkSize 10 10) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 20) (mkSize 10 10) ] test_margin8 ∷ TestTree test_margin8 = let r = node 100 100 [ leaf' Nothing (Just 10) & geo.margin .~ LRTB 10 0 0 0 , leaf' Nothing (Just 10) & geo.margin .~ LRTB 0 10 0 0 , leaf' Nothing (Just 10) & geo.margin .~ LRTB 10 20 0 0 ] & geo.direction .~ DirColumn & layout (mkSize 100 100) in testGroup "margin8 " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 0) (mkSize 90 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 10) (mkSize 90 10) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 10 20) (mkSize 70 10) ] test_margin9 ∷ TestTree test_margin9 = let r = node 100 100 [ leaf' (Just 10) Nothing & geo.margin .~ LRTB 0 0 10 0 , leaf' (Just 10) Nothing & geo.margin .~ LRTB 0 0 0 10 , leaf' (Just 10) Nothing & geo.margin .~ LRTB 0 0 10 20 ] & geo.direction .~ DirRow & layout (mkSize 100 100) in testGroup "margin9 " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 10) (mkSize 10 90) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 10 0) (mkSize 10 90) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 20 10) (mkSize 10 70) ] -- COMPLETE -- * -- test_shrink1 ∷ TestTree test_shrink1 = let r = node 100 100 [ leaf 100 100 & geo.shrink .~ 2 , leaf 100 100 & geo.shrink .~ 3 ] & layout (mkSize 100 100) in testGroup "shrink1" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 60) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 60) (mkSize 100 40) ] test_shrink2 ∷ TestTree test_shrink2 = let r = node 100 100 [ leaf 100 100 , leaf 100 100 & geo.shrink .~ 4 ] & layout (mkSize 100 100) in testGroup "shrink2" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 80) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 80) (mkSize 100 20) ] test_shrink3 ∷ TestTree test_shrink3 = let r = node 100 100 [ leaf 100 40 & geo.shrink .~ 2 , leaf 100 40 & geo.shrink .~ 3 ] & layout (mkSize 100 100) in testGroup "shrink3: the shrink attributes are not taken into account when there is enough flexible space available" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 40) (mkSize 100 40) ] test_shrink4 ∷ TestTree test_shrink4 = let r = node 100 100 [ leaf 100 25 , leaf 100 25 ] & geo.shrink .~ 2 & layout (mkSize 100 100) in testGroup "shrink4: the shrink attribute is not inherited from children" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 100 25) ] test_shrink5 ∷ TestTree test_shrink5 = let r = node 100 100 [ leaf 100 550 & geo.shrink .~ 1 ] & layout (mkSize 100 100) in testGroup "shrink5: all the container space is used when there is only one item with a positive value for the shrink attribute" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 100) ] test_shrink6 ∷ TestTree test_shrink6 = let r = node 100 100 [ leaf 100 75 & geo.shrink .~ 1 , leaf 100 75 & geo.shrink .~ 1 ] & layout (mkSize 100 100) in testGroup "shrink6: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 100 50) ] -- COMPLETE -- * padding -- test_padding1 ∷ TestTree test_padding1 = let r = node 100 100 [ leaf 25 25 ] & geo.direction .~ DirColumn & geo.justify'content .~ AlignStart & geo.align'items .~ AlignStart & geo.padding .~ LRTB 10 15 15 10 & layout (mkSize 100 100) in testGroup "padding1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 15) (mkSize 25 25) ] test_padding2 ∷ TestTree test_padding2 = let r = node 100 100 [ leaf 25 25 ] & geo.direction .~ DirColumn & geo.justify'content .~ AlignEnd & geo.align'items .~ AlignStart & geo.padding .~ LRTB 10 15 15 10 & layout (mkSize 100 100) in testGroup "padding2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 65) (mkSize 25 25) ] test_padding3 ∷ TestTree test_padding3 = let r = node 100 100 [ leaf 25 25 ] & geo.direction .~ DirColumn & geo.justify'content .~ AlignEnd & geo.align'items .~ AlignEnd & geo.padding .~ LRTB 10 15 15 10 & layout (mkSize 100 100) in testGroup "padding3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 60 65) (mkSize 25 25) ] test_padding4 ∷ TestTree test_padding4 = let r = node 100 100 [ leaf 25 25 ] & geo.direction .~ DirColumn & geo.justify'content .~ AlignStart & geo.align'items .~ AlignEnd & geo.padding .~ LRTB 10 15 15 10 & layout (mkSize 100 100) in testGroup "padding4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 60 15) (mkSize 25 25) ] test_padding5 ∷ TestTree test_padding5 = let r = node 100 100 [ leaf 0 25 & geo.align'self .~ AlignStretch ] & geo.direction .~ DirColumn & geo.justify'content .~ AlignStart & geo.align'items .~ AlignStart & geo.padding .~ LRTB 10 15 15 10 & layout (mkSize 100 100) in testGroup "padding5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 15) (mkSize 75 25) ] -- COMPLETE -- * -- -- test_children1 -- ignoring -- test_children2 -- ignoring -- test_children3 -- ignoring -- test_children4 ∷ TestTree test_children4 = let r = node 100 100 [ node 90 90 [ node 80 80 [ node 70 70 [ node 60 60 [ leaf 50 50 & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignCenter & layout (mkSize 100 100) in testGroup "children4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 5 5) (mkSize 90 90) , testCase "child 0.0" $ r^.child 0.child 0.area @?= Area (mkLU 5 5) (mkSize 80 80) , testCase "child 0.0.0" $ r^.child 0.child 0.child 0.area @?= Area (mkLU 5 5) (mkSize 70 70) , testCase "child 0.0.0.0" $ r^.child 0.child 0.child 0.child 0.area @?= Area (mkLU 5 5) (mkSize 60 60) , testCase "child 0.0.0.0.0" $ r^.child 0.child 0.child 0.child 0.child 0.area @?= Area (mkLU 5 5) (mkSize 50 50) ] -- COMPLETE -- * position -- test_position1 ∷ TestTree test_position1 = let r = node 100 100 [ leaf 10 10 & geo.positioning .~ Absolute ] & layout (mkSize 100 100) in testGroup "position1: items with an absolute position default to the left/top corner" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 10 10) ] test_position2 ∷ TestTree test_position2 = let r = node 100 100 [ leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) Nothing (Just 10) Nothing , leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing (Just 10) (Just 10) Nothing , leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing (Just 10) Nothing (Just 10) , leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) Nothing Nothing (Just 10) ] & geo.align'items .~ AlignCenter & geo.justify'content .~ AlignStart & layout (mkSize 100 100) in testGroup "position2 " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 10) (mkSize 10 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 80 10) (mkSize 10 10) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 80 80) (mkSize 10 10) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 10 80) (mkSize 10 10) ] test_position3 ∷ TestTree test_position3 = let r = node 100 100 [ leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) (Just 10) Nothing Nothing , leaf 10 10 & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing Nothing (Just 10) (Just 10) ] & layout (mkSize 100 100) in testGroup "position3: if both left/right or top/bottom are given, left/top get the priority if the item has the appropriate size dimension set" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 0) (mkSize 10 10) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 10) (mkSize 10 10) ] test_position4 ∷ TestTree test_position4 = let r = node 100 100 [ leaf' Nothing (Just 20) & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) (Just 10) Nothing Nothing , leaf' (Just 20) Nothing & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing Nothing (Just 10) (Just 10) ] & layout (mkSize 100 100) in testGroup "position4: if both left/right or top/bottom are given, the item is properly resized if the appropriate size dimension hasn't been set" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 0) (mkSize 80 20) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 10) (mkSize 20 80) ] test_position5 ∷ TestTree test_position5 = let r = node 100 100 [ leaf 10 10 & geo.positioning .~ Absolute & geo.basis .~ 20 & geo.absolute .~ LRTB (Just 10) Nothing Nothing (Just 10) ] & layout (mkSize 100 100) in testGroup "position5: the `basis' property is ignored for items with an absolute position" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 80) (mkSize 10 10) ] test_position6 ∷ TestTree test_position6 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing (Just 0) Nothing (Just 0) , leaf 50 50 ] & geo.direction .~ DirRow & layout (mkSize 200 200) in testGroup "position6: items with an absolute position are separated from the other items during the layout" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 150 150) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 50) ] test_position7 ∷ TestTree test_position7 = let r = node 120 120 [ leaf 50 50 , leaf 50 50 , leaf 50 50 & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing (Just 0) (Just 0) Nothing , leaf 50 50 ] & geo.wrap .~ Wrap & geo.justify'content .~ AlignSpaceAround & geo.align'content .~ AlignStart & layout (mkSize 120 120) in testGroup "position7: items with an absolute position are separated from the other items during the layout and are not taken into account when calculating spacing" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 5) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 65) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 70 0) (mkSize 50 50) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 50 35) (mkSize 50 50) ] test_position8 ∷ TestTree test_position8 = let r = node 100 100 [ node' Nothing Nothing [ node 60 60 [ leaf 40 40 & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) Nothing Nothing (Just 10) ] & geo.positioning .~ Absolute & geo.absolute .~ LRTB Nothing (Just 10) (Just 10) Nothing ] & geo.positioning .~ Absolute & geo.absolute .~ LRTB (Just 10) (Just 10) (Just 10) (Just 10) ] & geo.direction .~ DirRow & layout (mkSize 100 100) in testGroup "position8: items with an absolute position can be nested" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 10 10) (mkSize 80 80) , testCase "child 1" $ r^.child 0.child 0.area @?= Area (mkLU 10 10) (mkSize 60 60) , testCase "child 2" $ r^.child 0.child 0.child 0.area @?= Area (mkLU 10 10) (mkSize 40 40) ] -- COMPLETE -- * direction -- test_direction1 ∷ TestTree test_direction1 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.direction .~ DirRow & layout (mkSize 200 200) in testGroup "direction1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 0) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 100 0) (mkSize 50 50) ] test_direction2 ∷ TestTree test_direction2 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.direction .~ DirColumn & layout (mkSize 200 200) in testGroup "direction2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 100) (mkSize 50 50) ] test_direction3 ∷ TestTree test_direction3 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.direction .~ DirRowReverse & layout (mkSize 200 200) in testGroup "direction3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 150 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 100 0) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 0) (mkSize 50 50) ] test_direction4 ∷ TestTree test_direction4 = let r = node 200 200 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.direction .~ DirColumnReverse & layout (mkSize 200 200) in testGroup "direction4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 150) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 100) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 50 50) ] -- COMPLETE -- * -- test_align_self1 ∷ TestTree test_align_self1 = let r = node 100 100 [ leaf 50 25 & geo.align'self .~ AlignStart , leaf 50 25 & geo.align'self .~ AlignStart , leaf 50 25 & geo.align'self .~ AlignStart ] & layout (mkSize 100 100) in testGroup "align_self1" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 50 25) ] test_align_self2 ∷ TestTree test_align_self2 = let r = node 100 100 [ leaf 50 25 & geo.align'self .~ AlignEnd , leaf 50 25 & geo.align'self .~ AlignEnd , leaf 50 25 & geo.align'self .~ AlignEnd ] & layout (mkSize 100 100) in testGroup "align_self2" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 50 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 50) (mkSize 50 25) ] test_align_self3 ∷ TestTree test_align_self3 = let r = node 100 100 [ leaf 50 25 & geo.align'self .~ AlignCenter , leaf 50 25 & geo.align'self .~ AlignCenter , leaf 50 25 & geo.align'self .~ AlignCenter ] & layout (mkSize 100 100) in testGroup "align_self3" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 25 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 25 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 25 50) (mkSize 50 25) ] test_align_self4 ∷ TestTree test_align_self4 = let r = node 100 100 [ leaf' Nothing (Just 25) & geo.align'self .~ AlignStretch , leaf 0 25 & geo.align'self .~ AlignStretch , leaf' Nothing (Just 25) & geo.align'self .~ AlignStretch ] & layout (mkSize 100 100) in testGroup "align_self4: stretch works if the align dimension is not set or is 0" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 100 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 100 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 100 25) ] test_align_self5 ∷ TestTree test_align_self5 = let r = node 100 100 [ leaf 50 25 & geo.align'self .~ AlignStretch , leaf 50 50 & geo.align'self .~ AlignStretch , leaf 50 25 & geo.align'self .~ AlignStretch ] & layout (mkSize 100 100) in testGroup "align_self5: stretch does not work if the align dimension is set" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 75) (mkSize 50 25) ] test_align_self6 ∷ TestTree test_align_self6 = let r = node 100 100 [ leaf 50 25 & geo.align'self .~ AlignStart , leaf 50 25 & geo.align'self .~ AlignCenter , leaf 0 25 & geo.align'self .~ AlignStretch , leaf 50 25 & geo.align'self .~ AlignEnd ] & layout (mkSize 100 100) in testGroup "align_self6: potpourri" [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 25 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 100 25) , testCase "child 2" $ r^.child 3.area @?= Area (mkLU 50 75) (mkSize 50 25) ] -- COMPLETE -- * -- test_align_items1 ∷ TestTree test_align_items1 = let r = node 100 100 [ leaf 50 25 , leaf 50 25 , leaf 50 25 ] & geo.align'items .~ AlignStart & layout (mkSize 100 100) in testGroup "align_items1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 50 25) ] test_align_items2 ∷ TestTree test_align_items2 = let r = node 100 100 [ leaf 50 25 , leaf 50 25 , leaf 50 25 ] & geo.align'items .~ AlignEnd & layout (mkSize 100 100) in testGroup "align_items2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 50 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 50 50) (mkSize 50 25) ] test_align_items3 ∷ TestTree test_align_items3 = let r = node 100 100 [ leaf 50 25 , leaf 50 25 , leaf 50 25 ] & geo.align'items .~ AlignCenter & layout (mkSize 100 100) in testGroup "align_items3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 25 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 25 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 25 50) (mkSize 50 25) ] test_align_items4 ∷ TestTree test_align_items4 = let r = node 100 100 [ leaf 50 25 , leaf 0 25 , leaf' Nothing (Just 25) ] & geo.align'items .~ AlignStretch & layout (mkSize 100 100) in testGroup "align_items4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 100 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 50) (mkSize 100 25) ] test_align_items5 ∷ TestTree test_align_items5 = let r = node 100 100 [ leaf 50 25 , leaf 50 25 & geo.align'self .~ AlignStart , leaf 50 25 & geo.align'self .~ AlignAuto , leaf 50 25 & geo.align'self .~ AlignEnd ] & geo.align'items .~ AlignCenter & layout (mkSize 100 100) in testGroup "align_items5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 25 0) (mkSize 50 25) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 25) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 25 50) (mkSize 50 25) , testCase "child 3" $ r^.child 3.area @?= Area (mkLU 50 75) (mkSize 50 25) ] -- COMPLETE -- * -- test_align_content1 ∷ TestTree test_align_content1 = let r = node 200 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignStart & layout (mkSize 200 120) in testGroup "align_content1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 60 0) (mkSize 40 50) ] test_align_content2 ∷ TestTree test_align_content2 = let r = node 200 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignCenter & layout (mkSize 200 120) in testGroup "align_content2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 50 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 110 0) (mkSize 40 50) ] test_align_content3 ∷ TestTree test_align_content3 = let r = node 200 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignEnd & layout (mkSize 200 120) in testGroup "align_content3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 100 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 100 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 160 0) (mkSize 40 50) ] test_align_content4 ∷ TestTree test_align_content4 = let r = node 200 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignSpaceBetween & layout (mkSize 200 120) in testGroup "align_content4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 160 0) (mkSize 40 50) ] test_align_content5 ∷ TestTree test_align_content5 = let r = node 200 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignSpaceAround & layout (mkSize 200 120) in testGroup "align_content5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 25 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 25 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 135 0) (mkSize 40 50) ] test_align_content6 ∷ TestTree test_align_content6 = let r = node 250 120 [ leaf 50 50 , leaf 60 50 , leaf 40 50 ] & geo.wrap .~ Wrap & geo.align'content .~ AlignSpaceEvenly & layout (mkSize 250 120) in testGroup "align_content6: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 50 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 50 50) (mkSize 60 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 160 0) (mkSize 40 50) ] -- COMPLETE -- * -- -- test_default1 -- too simple to test -- test_default_values2 ∷ TestTree test_default_values2 = let r = node 200 200 [ leaf' (Just 100) Nothing , leaf' Nothing (Just 100) , leaf' Nothing Nothing ] & geo.direction .~ DirColumn & layout (mkSize 200 200) in testGroup "default_values2: if the width/height property isn't set on a child, it's frame size defaults to 0 for the main axis and the parent's size for the minor axis" [ testCase "child 0" $ r^.child 0.area.area'b @?= mkSize 100 0 , testCase "child 1" $ r^.child 1.area.area'b @?= mkSize 200 100 , testCase "child 2" $ r^.child 2.area.area'b @?= mkSize 200 0 ] test_default_values3 ∷ TestTree test_default_values3 = let r = node 200 200 [ leaf' (Just 100) Nothing , leaf' Nothing (Just 100) , leaf' Nothing Nothing ] & geo.direction .~ DirRow & layout (mkSize 200 200) in testGroup "default_values3: " [ testCase "child 0" $ r^.child 0.area.area'b @?= mkSize 100 200 , testCase "child 1" $ r^.child 1.area.area'b @?= mkSize 0 100 , testCase "child 2" $ r^.child 2.area.area'b @?= mkSize 0 200 ] -- COMPLETE -- * -- test_justify_content1 ∷ TestTree test_justify_content1 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ AlignCenter & layout (mkSize 100 300) in testGroup "justify_content1: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 50) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 150) (mkSize 50 100) ] test_justify_content2 ∷ TestTree test_justify_content2 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ AlignStart & layout (mkSize 100 300) in testGroup "justify_content2: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 100) (mkSize 50 100) ] test_justify_content3 ∷ TestTree test_justify_content3 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ AlignEnd & layout (mkSize 100 300) in testGroup "justify_content3: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 100) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 200) (mkSize 50 100) ] test_justify_content4 ∷ TestTree test_justify_content4 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ AlignSpaceBetween & layout (mkSize 100 300) in testGroup "justify_content4: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 200) (mkSize 50 100) ] test_justify_content5 ∷ TestTree test_justify_content5 = let r = node 100 300 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.justify'content .~ AlignSpaceBetween & layout (mkSize 100 300) in testGroup "justify_content5: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 125) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 250) (mkSize 50 50) ] test_justify_content6 ∷ TestTree test_justify_content6 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ AlignSpaceAround & layout (mkSize 100 300) in testGroup "justify_content6: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 25) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 175) (mkSize 50 100) ] test_justify_content7 ∷ TestTree test_justify_content7 = let r = node 100 300 [ leaf 50 50 , leaf 50 50 , leaf 50 50 ] & geo.justify'content .~ AlignSpaceAround & layout (mkSize 100 300) in testGroup "justify_content7: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 25) (mkSize 50 50) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 125) (mkSize 50 50) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 225) (mkSize 50 50) ] test_justify_content8 ∷ TestTree test_justify_content8 = let r = node 100 300 [ leaf 50 105 , leaf 50 105 ] & geo.justify'content .~ AlignSpaceEvenly & layout (mkSize 100 300) in testGroup "justify_content8: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 30) (mkSize 50 105) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 165) (mkSize 50 105) ] test_justify_content9 ∷ TestTree test_justify_content9 = let r = node 100 300 [ leaf 50 40 , leaf 50 40 , leaf 50 40 ] & geo.justify'content .~ AlignSpaceEvenly & layout (mkSize 100 300) in testGroup "justify_content9: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 45) (mkSize 50 40) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 130) (mkSize 50 40) , testCase "child 2" $ r^.child 2.area @?= Area (mkLU 0 215) (mkSize 50 40) ] test_justify_content10 ∷ TestTree test_justify_content10 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignCenter & layout (mkSize 100 300) in testGroup "justify_content10: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 150) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 100) ] test_justify_content11 ∷ TestTree test_justify_content11 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignStart & layout (mkSize 100 300) in testGroup "justify_content11: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 200) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 100) (mkSize 50 100) ] test_justify_content12 ∷ TestTree test_justify_content12 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignEnd & layout (mkSize 100 300) in testGroup "justify_content12: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 100) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 0) (mkSize 50 100) ] test_justify_content13 ∷ TestTree test_justify_content13 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignSpaceBetween & layout (mkSize 100 300) in testGroup "justify_content13: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 200) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 0) (mkSize 50 100) ] test_justify_content14 ∷ TestTree test_justify_content14 = let r = node 100 300 [ leaf 50 100 , leaf 50 100 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignSpaceAround & layout (mkSize 100 300) in testGroup "justify_content14: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 175) (mkSize 50 100) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 100) ] test_justify_content15 ∷ TestTree test_justify_content15 = let r = node 100 300 [ leaf 50 105 , leaf 50 105 ] & geo.direction .~ DirColumnReverse & geo.justify'content .~ AlignSpaceEvenly & layout (mkSize 100 300) in testGroup "justify_content15: " [ testCase "child 0" $ r^.child 0.area @?= Area (mkLU 0 165) (mkSize 50 105) , testCase "child 1" $ r^.child 1.area @?= Area (mkLU 0 30) (mkSize 50 105) ] test_justify_content16 ∷ TestTree test_justify_content16 = let modes = [AlignStart, AlignCenter, AlignEnd, AlignSpaceBetween, AlignSpaceAround, AlignSpaceEvenly] r mode = node 100 100 [ leaf 50 50 , leaf 50 50 ] & geo.justify'content .~ mode & layout (mkSize 100 100) in testGroup "justify_content16: the `justify_content' property is ignored when the children fill up all the space" $ flip concatMap modes (\mode→ [ testCase (printf "child 0 / %s" $ show mode) $ (r mode)^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 50) , testCase (printf "child 1 / %s" $ show mode) $ (r mode)^.child 1.area @?= Area (mkLU 0 50) (mkSize 50 50) ]) test_justify_content17 ∷ TestTree test_justify_content17 = let modes = [AlignStart, AlignCenter, AlignEnd, AlignSpaceBetween, AlignSpaceAround, AlignSpaceEvenly] r mode = node 100 100 [ leaf 50 100 , leaf 50 100 , leaf 50 100 , leaf 50 100 ] & geo.justify'content .~ mode & layout (mkSize 100 100) in testGroup "justify_content17: the `justify_content' property is ignored when the children fill up all the space" $ flip concatMap modes (\mode→ [ testCase (printf "child 0 / %s" $ show mode) $ (r mode)^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 25) , testCase (printf "child 1 / %s" $ show mode) $ (r mode)^.child 1.area @?= Area (mkLU 0 25) (mkSize 50 25) , testCase (printf "child 2 / %s" $ show mode) $ (r mode)^.child 2.area @?= Area (mkLU 0 50) (mkSize 50 25) , testCase (printf "child 3 / %s" $ show mode) $ (r mode)^.child 3.area @?= Area (mkLU 0 75) (mkSize 50 25) ]) test_justify_content18 ∷ TestTree test_justify_content18 = let modes = [AlignStart, AlignCenter, AlignEnd, AlignSpaceBetween, AlignSpaceAround, AlignSpaceEvenly] r mode = node 100 100 [ leaf 50 20 , leaf 50 20 & geo.grow .~ 1 , leaf 50 20 ] & geo.justify'content .~ mode & layout (mkSize 100 100) in testGroup "justify_content18: the `justify_content' property is ignored when there are flexible children" $ flip concatMap modes (\mode→ [ testCase (printf "child 0 / %s" $ show mode) $ (r mode)^.child 0.area @?= Area (mkLU 0 0) (mkSize 50 20) , testCase (printf "child 1 / %s" $ show mode) $ (r mode)^.child 1.area @?= Area (mkLU 0 20) (mkSize 50 60) , testCase (printf "child 2 / %s" $ show mode) $ (r mode)^.child 2.area @?= Area (mkLU 0 80) (mkSize 50 20) ]) -- COMPLETE
deepfire/mood
tests/FlexTest.hs
agpl-3.0
63,263
0
44
21,399
24,150
11,720
12,430
-1
-1
module GreetIfCool1 where greetIfCool :: String -> IO() greetIfCool coolness = putStrLn coolness mytup = (1 :: Integer, "blah") awesome = ["Papuchon", "curry", ":)"] alsoAwesome = ["Quake", "The Simons"] allAwesome = [awesome, alsoAwesome] isPalindrome :: (Eq a) => [a] -> Bool isPalindrome x = x == reverse x myAbs :: Integer -> Integer myAbs x = if x > 0 then x else -x f :: (a, b) -> (c, d) -> ((b, d), (a, c)) f x y = ((snd x, snd y), (fst x, fst y)) x = (+) g xs = w `x` 1 where w = length xs h xs = xs !! 0
punitrathore/haskell-first-principles
src/greetIfCool1.hs
bsd-3-clause
533
0
8
128
272
155
117
20
2
{-# LANGUAGE RecordWildCards #-} module Network.MQTT.ClientSpec (spec) where import Control.Concurrent ( threadDelay ) import Control.Concurrent.MVar ( newEmptyMVar, putMVar, takeMVar, isEmptyMVar ) import qualified Data.ByteString as BS import Data.Maybe ( isJust, fromJust ) import qualified Data.Text as T import Network.MQTT.Client ( runClient , UserCredentials(..) , ClientCommand(..) , ClientConfig(..) , ClientResult(..)) import Network.MQTT.Packet import System.IO.Streams ( InputStream, OutputStream ) import qualified System.IO.Streams as S import qualified System.IO.Streams.Concurrent as S import System.Log ( Priority(DEBUG) ) import System.Log.Logger ( rootLoggerName , setLevel , updateGlobalLogger ) import Control.Monad ( forM_ ) import qualified Data.Set as Set import Test.Hspec import System.Timeout (timeout) debugTests :: IO () debugTests = updateGlobalLogger rootLoggerName (setLevel DEBUG) data Session = Session { is :: InputStream Packet , os :: OutputStream Packet , result_is :: InputStream ClientResult , command_os :: OutputStream ClientCommand } newSession :: ClientConfig -> IO Session newSession config = do (is', os) <- S.makeChanPipe (is, os') <- S.makeChanPipe (result_is, result_os) <- S.makeChanPipe command_os <- runClient config result_os is' os' CONNECT _ <- readFromStream is writeToStream os $ CONNACK (ConnackPacket False Accepted) return Session{..} readFromStream :: InputStream a -> IO a readFromStream is = fromJust <$> S.read is writeToStream :: OutputStream a -> a -> IO () writeToStream os x = S.write (Just x) os disconnectClient :: OutputStream Packet -> IO () disconnectClient = S.write Nothing defaultConfig = ClientConfig { ccClientIdenfier = ClientIdentifier $ T.pack "arachne-test" , ccWillMsg = Nothing , ccUserCredentials = Nothing , ccCleanSession = True , ccKeepAlive = 0 } defaultMessage = Message { messageTopic = TopicName $ T.pack "a/b" , messageQoS = QoS0 , messageMessage = BS.pack [0xab, 0x12] , messageRetain = False } defaultPacketIdentifier = PacketIdentifier 42 defaultPublish = PublishPacket{ publishDup = False , publishPacketIdentifier = Just defaultPacketIdentifier , publishMessage = defaultMessage { messageQoS = QoS1 } } spec :: Spec spec = do describe "MQTT Client" $ do it "In the QoS 0 delivery protocol, the Sender MUST send a PUBLISH packet with QoS=0, DUP=0 [MQTT-4.3.1-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS0 } PUBLISH PublishPacket{..} <- readFromStream is messageQoS publishMessage `shouldBe` QoS0 publishDup `shouldBe` False it "In the QoS 1 delivery protocol, the Sender MUST assign an unused Packet Identifier each time it has a newSession Application Message to publish [MQTT-4.3.2-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS1 } PUBLISH p1 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS1 } PUBLISH p2 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS1 } PUBLISH p3 <- readFromStream is Set.size (Set.fromList [ publishPacketIdentifier p1 , publishPacketIdentifier p2 , publishPacketIdentifier p3 ]) `shouldBe` 3 it "In the QoS 1 delivery protocol, the Sender MUST send a PUBLISH Packet containing this Packet Identifier with QoS=1, DUP=0 [MQTT-4.3.2-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS1 } PUBLISH PublishPacket{..} <- readFromStream is messageQoS publishMessage `shouldBe` QoS1 publishDup `shouldBe` False it "In the QoS 1 delivery protocol, the Sender MUST treat the PUBLISH Packet as 'unacknowledged' until it has received the corresponding PUBACK packet from the receiver [MQTT-4.3.2-1]" $ do pending it "In the QoS 1 delivery protocol, the Receiver MUST respond with a PUBACK Packet containing the Packet Identifier from the incoming PUBLISH Packet, having accepted ownership of the Application Message [MQTT-4.3.2-2]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS1 } } PUBACK PubackPacket{..} <- readFromStream is PublishResult message <- readFromStream result_is message `shouldBe` defaultMessage { messageQoS = QoS1 } pubackPacketIdentifier `shouldBe` defaultPacketIdentifier it "In the QoS 1 delivery protocol, the Receiver After it has sent a PUBACK Packet the Receiver MUST treat any incoming PUBLISH packet that contains the same Packet Identifier as being a newSession publication, irrespective of the setting of its DUP flag [MQTT-4.3.2-2]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS1 } } PUBACK p1 <- readFromStream is PublishResult message' <- readFromStream result_is message' `shouldBe` defaultMessage { messageQoS = QoS1 } pubackPacketIdentifier p1 `shouldBe` defaultPacketIdentifier writeToStream os $ PUBLISH defaultPublish { publishDup = True , publishMessage = defaultMessage { messageQoS = QoS1 } } PUBACK p2 <- readFromStream is PublishResult message'' <- readFromStream result_is message'' `shouldBe` defaultMessage { messageQoS = QoS1 } pubackPacketIdentifier p2 `shouldBe` defaultPacketIdentifier it "In the QoS 2 delivery protocol, the Sender MUST assign an unused Packet Identifier when it has a newSession Application Message to publish [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p1 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p2 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p3 <- readFromStream is Set.size (Set.fromList [ publishPacketIdentifier p1 , publishPacketIdentifier p2 , publishPacketIdentifier p3 ]) `shouldBe` 3 it "In the QoS 2 delivery protocol, the Sender MUST send a PUBLISH packet containing this Packet Identifier with QoS=2, DUP=0 [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH PublishPacket{..} <- readFromStream is messageQoS publishMessage `shouldBe` QoS2 publishDup `shouldBe` False it "In the QoS 2 delivery protocol, the Sender MUST treat the PUBLISH packet as 'unacknowledged' until it has received the corresponding PUBREC packet from the receiver [MQTT-4.3.3-1]" $ do pending it "In the QoS 2 delivery protocol, the Sender MUST send a PUBREL packet when it receives a PUBREC packet from the receiver [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH PublishPacket{..} <- readFromStream is let packetIdentifier = fromJust publishPacketIdentifier writeToStream os $ PUBREC (PubrecPacket packetIdentifier) PUBREL PubrelPacket{..} <- readFromStream is pubrelPacketIdentifier `shouldBe` packetIdentifier it "In the QoS 2 delivery protocol, the Sender MUST treat the PUBREL packet as 'unacknowledged' until it has received the corresponding PUBCOMP packet from the receiver [MQTT-4.3.3-1]" $ do pending it "In the QoS 2 delivery protocol, the Sender MUST NOT re-send the PUBLISH once it has sent the corresponding PUBREL packet [MQTT-4.3.3-1]" $ do pending it "In the QoS2 delivery protocol, the Receiver MUST respond with a PUBREC containing the Packet Identifier from the incoming PUBLISH Packet, having accepted ownership of the Application Message [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC PubrecPacket{..} <- readFromStream is PublishResult message <- readFromStream result_is message `shouldBe` defaultMessage { messageQoS = QoS2 } pubrecPacketIdentifier `shouldBe` defaultPacketIdentifier it "In the QoS2 delivery protocol, the Receiver Until it has received the corresponding PUBREL packet, the Receiver MUST acknowledge any subsequent PUBLISH packet with the same Packet Identifier by sending a PUBREC [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC p1 <- readFromStream is writeToStream os $ PUBLISH defaultPublish { publishDup = True , publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC p2 <- readFromStream is pubrecPacketIdentifier p1 `shouldBe` defaultPacketIdentifier pubrecPacketIdentifier p2 `shouldBe` defaultPacketIdentifier it "In the QoS2 delivery protocol, the Receiver MUST respond to a PUBREL packet by sending a PUBCOMP packet containing the same Packet Identifier as the PUBREL [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC _ <- readFromStream is writeToStream os $ PUBREL $ PubrelPacket defaultPacketIdentifier PUBCOMP PubcompPacket{..} <- readFromStream is pubcompPacketIdentifier `shouldBe` defaultPacketIdentifier it "In the QoS2 delivery protocol, the Receiver After it has sent a PUBCOMP, the receiver MUST treat any subsequent PUBLISH packet that contains that Packet Identifier as being a newSession publication [MQTT-4.3.3-1]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC _ <- readFromStream is PublishResult message' <- readFromStream result_is message' `shouldBe` defaultMessage { messageQoS = QoS2 } -- Check whether Receiver Before it has sent a PUBCOMP does not treat PUBLISH packet that contains that Packet Identifier as being a newSession publication writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC _ <- readFromStream is Nothing <- timeout 100000 (S.read result_is) -- Send a PUBCOMP writeToStream os $ PUBREL $ PubrelPacket defaultPacketIdentifier PUBCOMP PubcompPacket{..} <- readFromStream is writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } } PUBREC _ <- readFromStream is PublishResult message'' <- readFromStream result_is message'' `shouldBe` defaultMessage { messageQoS = QoS2 } it "When a Client reconnects with CleanSession set to 0, both the Client and Server MUST re-send any unacknowledged PUBLISH Packets (where QoS > 0) and PUBREL Packets using their original Packet Identifiers [MQTT-4.4.0-1]" $ do pending it "When it re-sends any PUBLISH packets, it MUST re-send them in the order in which the original PUBLISH packets were sent (this applies to QoS 1 and QoS 2 messages) [MQTT-4.6.0-1]" $ do -- Session{..} <- newSession defaultConfig -- writeToStream command_os $ PublishCommand $ -- defaultMessage { messageTopic = TopicName $ T.pack "a/b" -- , messageQoS = QoS1 -- } -- PUBLISH p1 <- readFromStream is -- writeToStream command_os $ PublishCommand $ -- defaultMessage { messageTopic = TopicName $ T.pack "c/d" -- , messageQoS = QoS2 -- } -- PUBLISH p2 <- readFromStream is -- writeToStream command_os $ PublishCommand $ -- defaultMessage { messageTopic = TopicName $ T.pack "a/b" -- , messageQoS = QoS1 -- } -- PUBLISH p3 <- readFromStream is -- disconnectClient os -- CONNECT ConnectPacket{..} <- readFromStream is -- writeToStream os $ CONNACK (ConnackPacket False Accepted) -- PUBLISH p1' <- readFromStream is -- PUBLISH p2' <- readFromStream is -- PUBLISH p3' <- readFromStream is -- forM_ (zip [p1, p2, p3] [p1', p2', p3']) $ \(p, p') -> do -- publishPacketIdentifier p `shouldBe` publishPacketIdentifier p' -- publishDup p `shouldBe` False -- publishDup p' `shouldBe` True pending it "It MUST send PUBACK packets in the order in which the corresponding PUBLISH packets were received (QoS 1 messages) [MQTT-4.6.0-2]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS1 } , publishPacketIdentifier = Just $ PacketIdentifier 1 } writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS1 } , publishPacketIdentifier = Just $ PacketIdentifier 2 } writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS1 } , publishPacketIdentifier = Just $ PacketIdentifier 3 } PUBACK p1 <- readFromStream is PUBACK p2 <- readFromStream is PUBACK p3 <- readFromStream is pubackPacketIdentifier p1 `shouldBe` PacketIdentifier 1 pubackPacketIdentifier p2 `shouldBe` PacketIdentifier 2 pubackPacketIdentifier p3 `shouldBe` PacketIdentifier 3 it "It MUST send PUBREC packets in the order in which the corresponding PUBLISH packets were received (QoS 2 messages) [MQTT-4.6.0-3]" $ do Session{..} <- newSession defaultConfig writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } , publishPacketIdentifier = Just $ PacketIdentifier 1 } writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } , publishPacketIdentifier = Just $ PacketIdentifier 2 } writeToStream os $ PUBLISH defaultPublish { publishMessage = defaultMessage { messageQoS = QoS2 } , publishPacketIdentifier = Just $ PacketIdentifier 3 } PUBREC p1 <- readFromStream is PUBREC p2 <- readFromStream is PUBREC p3 <- readFromStream is pubrecPacketIdentifier p1 `shouldBe` PacketIdentifier 1 pubrecPacketIdentifier p2 `shouldBe` PacketIdentifier 2 pubrecPacketIdentifier p3 `shouldBe` PacketIdentifier 3 it "It MUST send PUBREL packets in the order in which the corresponding PUBREC packets were received (QoS 2 messages) [MQTT-4.6.0-4]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p1 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p2 <- readFromStream is writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS2 } PUBLISH p3 <- readFromStream is let packetIdentifier1 = fromJust $ publishPacketIdentifier p1 let packetIdentifier2 = fromJust $ publishPacketIdentifier p2 let packetIdentifier3 = fromJust $ publishPacketIdentifier p3 writeToStream os $ PUBREC (PubrecPacket packetIdentifier1) writeToStream os $ PUBREC (PubrecPacket packetIdentifier2) writeToStream os $ PUBREC (PubrecPacket packetIdentifier3) PUBREL p1' <- readFromStream is PUBREL p2' <- readFromStream is PUBREL p3' <- readFromStream is pubrelPacketIdentifier p1' `shouldBe` packetIdentifier1 pubrelPacketIdentifier p2' `shouldBe` packetIdentifier2 pubrelPacketIdentifier p3' `shouldBe` packetIdentifier3 it "After sending a DISCONNECT Packet the Client MUST close the Network Connection [MQTT-3.14.4-1]" $ do pending it "After sending a DISCONNECT Packet the Client MUST NOT send any more Control Packets on that Network Connection [MQTT-3.14.4-2]" $ do pending it "If the Client supplies a zero-byte ClientId, the Client MUST also set CleanSession to 1 [MQTT-3.1.3-7]." $ do pending it "If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a newSession one. This Session lasts as long as the Network Connection. State data associated with this Session MUST NOT be reused in any subsequent Session [MQTT-3.1.2-6]" $ do pending it "The Client and Server MUST store the Session after the Client and Server are disconnected [MQTT-3.1.2-4]" $ do pending it "Each time a Client sends a newSession packet of one of these types (SUBSCRIBE, UNSUBSCRIBE, and PUBLISH (in cases where QoS > 0)) it MUST assign it a currently unused Packet Identifier [MQTT-2.3.1-2]" $ do Session{..} <- newSession defaultConfig writeToStream command_os $ PublishCommand $ defaultMessage { messageQoS = QoS1 } PUBLISH p1 <- readFromStream is writeToStream command_os $ SubscribeCommand [ (TopicFilter $ T.pack "c/d", QoS2) ] SUBSCRIBE p2 <- readFromStream is writeToStream command_os $ UnsubscribeCommand [ TopicFilter $ T.pack "c/d" ] UNSUBSCRIBE p3 <- readFromStream is Set.size (Set.fromList [ fromJust $ publishPacketIdentifier p1 , subscribePacketIdentifier p2 , unsubscribePacketIdentifier p3 ]) `shouldBe` 3 it "If a Client re-sends a particular Control Packet, then it MUST use the same Packet Identifier in subsequent re-sends of that packet. The Packet Identifier becomes available for reuse after the Client has processed the corresponding acknowledgement packet. In the case of a QoS 1 PUBLISH this is the corresponding PUBACK; in the case of QoS 2 it is PUBCOMP. For SUBSCRIBE or UNSUBSCRIBE it is the corresponding SUBACK or UNSUBACK [MQTT-2.3.1-3]" $ do pending it "Similarly SUBACK and UNSUBACK MUST contain the Packet Identifier that was used in the corresponding SUBSCRIBE and UNSUBSCRIBE Packet respectively [MQTT-2.3.1-7]" $ do pending it "The DUP flag MUST be set to 1 by the Client or Server when it attempts to re-deliver a PUBLISH Packet [MQTT-3.3.1-1]" $ do pending it "Unless stated otherwise, if either the Server or Client encounters a protocol violation, it MUST close the Network Connection on which it received that Control Packet which caused the protocol violation [MQTT-4.8.0-1]" $ do pending it "It is the responsibility of the Client to ensure that the interval between Control Packets being sent does not exceed the Keep Alive value. In the absence of sending any other Control Packets, the Client MUST send a PINGREQ Packet [MQTT-3.1.2-23]" $ do pending
rasendubi/mqtt-broker
test/Network/MQTT/ClientSpec.hs
bsd-3-clause
20,754
0
19
5,597
3,560
1,726
1,834
281
1
import Testsuite import Data.Array.Parallel.Unlifted $(testcases [ "" <@ [t| ( (), Char, Bool, Int ) |] , "acc" <@ [t| ( (), Int ) |] , "num" <@ [t| ( Int ) |] , "ord" <@ [t| ( (), Char, Bool, Int ) |] , "enum" <@ [t| ( (), Char, Bool, Int ) |] ] [d| prop_sliceU :: (Eq a, UA a) => UArr a -> Len -> Len -> Property prop_sliceU arr (Len i) (Len n) = i <= lengthU arr && n <= lengthU arr - i ==> fromU (sliceU arr i n) == take n (drop i $ fromU arr) prop_extractU :: (Eq a, UA a) => UArr a -> Len -> Len -> Property prop_extractU arr (Len i) (Len n) = i <= lengthU arr && n <= lengthU arr - i ==> fromU (extractU arr i n) == take n (drop i $ fromU arr) prop_takeU :: (Eq a, UA a) => Len -> UArr a -> Property prop_takeU (Len n) arr = n <= lengthU arr ==> fromU (takeU n arr) == take n (fromU arr) prop_dropU :: (Eq a, UA a) => Len -> UArr a -> Property prop_dropU (Len n) arr = n <= lengthU arr ==> fromU (dropU n arr) == drop n (fromU arr) prop_splitAtU :: (Eq a, UA a) => Len -> UArr a -> Property prop_splitAtU (Len n) arr = n <= lengthU arr ==> let (brr, crr) = splitAtU n arr in (fromU brr, fromU crr) == splitAt n (fromU arr) |])
mainland/dph
dph-test/old/Unlifted_Subarrays.hs
bsd-3-clause
1,331
0
9
453
82
56
26
-1
-1
module Sound.Tidal.Cycle where import Control.Monad import Control.Monad.State import Control.Monad.Reader import Control.Concurrent.MVar import Data.Array.IArray import Graphics.UI.SDL import Graphics.UI.SDL.Image import qualified Graphics.UI.SDL.Framerate as FR import qualified Graphics.UI.SDL.Primitives as SDLP import qualified Graphics.UI.SDL.TTF.General as TTFG import Graphics.UI.SDL.TTF.Management import Graphics.UI.SDL.TTF.Render import Graphics.UI.SDL.TTF.Types import Data.Maybe (listToMaybe, fromMaybe, fromJust, isJust, catMaybes) import GHC.Int (Int16) import Data.List (intercalate, tails, nub, sortBy) import Data.Colour import Data.Colour.Names import Data.Colour.SRGB import Data.Colour.RGBSpace.HSV (hsv) import qualified GHC.Word import Data.Bits import Data.Ratio import Debug.Trace (trace) import Data.Fixed (mod') import Control.Concurrent import System.Exit import Sound.OSC.FD import Sound.Tidal.Stream (ParamPattern) import Sound.Tidal.Pattern import Sound.Tidal.Parse import Sound.Tidal.Tempo import qualified Sound.Tidal.Time as Time import Sound.Tidal.Utils --enumerate :: [a] -> [(Int, a)] --enumerate = zip [0..] maybeHead [] = Nothing maybeHead (x:_) = Just x sortByFst :: Ord a => [(a, b)] -> [(a, b)] sortByFst = sortBy (\a b -> compare (fst a) (fst b)) parenthesise :: String -> String parenthesise x = "(" ++ x ++ ")" spaces :: Int -> String spaces n = take n $ repeat ' ' single :: [a] -> Maybe a single (x:[]) = Just x single _ = Nothing fromJust' (Just x) = x fromJust' Nothing = error "nothing is just" data Scene = Scene {mouseXY :: (Float, Float), cursor :: (Float, Float) } data AppConfig = AppConfig { screen :: Surface, font :: Font, tempoMV :: MVar (Tempo), fr :: FR.FPSManager, mpat :: MVar (Pattern ColourD) } type AppState = StateT Scene IO type AppEnv = ReaderT AppConfig AppState screenWidth = 1024 screenHeight = 768 screenBpp = 32 middle = (fromIntegral $ screenWidth`div`2,fromIntegral $ screenHeight`div`2) toScreen :: (Float, Float) -> (Int, Int) toScreen (x, y) = (floor (x * (fromIntegral screenWidth)), floor (y * (fromIntegral screenHeight)) ) toScreen16 :: (Float, Float) -> (Int16, Int16) toScreen16 (x, y) = (fromIntegral $ floor (x * (fromIntegral screenWidth)), fromIntegral $ floor (y * (fromIntegral screenHeight)) ) fromScreen :: (Int, Int) -> (Float, Float) fromScreen (x, y) = ((fromIntegral x) / (fromIntegral screenWidth), (fromIntegral y) / (fromIntegral screenHeight) ) isInside :: Integral a => Rect -> a -> a -> Bool isInside (Rect rx ry rw rh) x y = (x' > rx) && (x' < rx + rw) && (y' > ry) && (y' < ry + rh) where (x', y') = (fromIntegral x, fromIntegral y) ctrlDown mods = or $ map (\x -> elem x [KeyModLeftCtrl, KeyModRightCtrl ] ) mods shiftDown mods = or $ map (\x -> elem x [KeyModLeftShift, KeyModRightShift, KeyModShift ] ) mods handleEvent :: Scene -> Event -> AppEnv (Scene) handleEvent scene (KeyDown k) = handleKey scene (symKey k) (symUnicode k) (symModifiers k) handleEvent scene _ = return scene handleKey :: Scene -> SDLKey -> Char -> [Modifier] -> AppEnv Scene handleKey scene SDLK_SPACE _ _ = return scene handleKey scene _ _ _ = return scene applySurface :: Int -> Int -> Surface -> Surface -> Maybe Rect -> IO Bool applySurface x y src dst clip = blitSurface src clip dst offset where offset = Just Rect { rectX = x, rectY = y, rectW = 0, rectH = 0 } initEnv :: MVar (Pattern ColourD) -> IO AppConfig initEnv mp = do screen <- setVideoMode screenWidth screenHeight screenBpp [SWSurface] font <- openFont "futura.ttf" 22 setCaption "Cycle" [] tempoMV <- tempoMVar fps <- FR.new FR.init fps FR.set fps 15 return $ AppConfig screen font tempoMV fps mp blankWidth = 0.015 drawArc' :: Surface -> ColourD -> (Double, Double) -> (Double, Double) -> Double -> Double -> Double -> IO () drawArc' screen c (x,y) (r,r') t o step | o <= 0 = return () | otherwise = do let pix = (colourToPixel c) steps = [t, (t + step) .. (t + o)] coords = map (\s -> (floor $ x + (r*cos(s)),floor $ y + (r*sin(s)))) steps ++ map (\s -> (floor $ x + (r'*cos(s)),floor $ y + (r'*sin(s)))) (reverse steps) SDLP.filledPolygon screen coords pix --drawArc screen c (x,y) (r,r') t (o-step) step return () where a = max t (t + o - step) b = t + o drawArc :: Surface -> ColourD -> (Double, Double) -> (Double, Double) -> Double -> Double -> Double -> IO () drawArc screen c (x,y) (r,r') t o step | o <= 0 = return () | otherwise = do let pix = (colourToPixel c) SDLP.filledPolygon screen coords pix drawArc screen c (x,y) (r,r') t (o-step) step return () where a = max t (t + o - step) b = t + o coords = map ((\(x',y') -> (floor $ x + x', floor $ y + y'))) [(r * cos(a), r * sin(a)), (r' * cos(a), r' * sin(a)), (r' * cos(b), r' * sin(b)), (r * cos(b), r * sin(b)) ] loop :: AppEnv () loop = do quit <- whileEvents $ act screen <- screen `liftM` ask font <- font `liftM` ask tempoM <- tempoMV `liftM` ask fps <- fr `liftM` ask scene <- get mp <- mpat `liftM` ask liftIO $ do pat <- readMVar mp tempo <- readMVar tempoM beat <- beatNow tempo bgColor <- (mapRGB . surfaceGetPixelFormat) screen 0x00 0x00 0x00 clipRect <- Just `liftM` getClipRect screen fillRect screen clipRect bgColor --drawArc screen middle (100,110) ((beat) * pi) (pi/2) (pi/32) drawPat middle (100,(fi screenHeight)/2) pat screen beat Graphics.UI.SDL.flip screen FR.delay fps unless quit loop where act e = do scene <- get scene' <- handleEvent scene e put $ scene' drawPat :: (Double, Double) -> (Double, Double) -> Pattern ColourD -> Surface -> Double -> IO () drawPat (x, y) (r,r') p screen beat = mapM_ drawEvents es where es = map (\(_, (s,e), evs) -> ((max s pos, min e (pos + 1)), evs)) $ arc (segment p) (pos, pos + 1) pos = toRational $ beat / 8 drawEvents ((s,e), cs) = mapM_ (\(n', c) -> drawEvent (s,e) c n' (length cs)) (enumerate $ reverse cs) drawEvent (s,e) c n' len = do let thickness = (1 / fromIntegral len) * (r' - r) let start = r + thickness * (fromIntegral n') drawArc screen c middle (start,start+thickness) ((pi*2) * (fromRational (s-pos))) ((pi*2) * fromRational (e-s)) (pi/16) {- (thickLine h (n*scale+n') (linesz/ (fromIntegral scale)) (x1 + (xd * fromRational (e-pos))) (y1 + (yd * fromRational (e-pos))) (x1 + (xd * fromRational (s-pos))) (y1 + (yd * fromRational (s-pos))) ) screen (colourToPixel c)-} segment2 :: Pattern a -> Pattern [(Bool, a)] segment2 p = Pattern $ \(s,e) -> filter (\(_, (s',e'),_) -> s' < e && e' > s) $ groupByTime (segment2' (arc (fmap (\x -> (True, x)) p) (s,e))) segment2' :: [Time.Event (Bool, a)] -> [Time.Event (Bool, a)] segment2' es = foldr splitEs es pts where pts = nub $ points es splitEs :: Time.Time -> [Time.Event (Bool, a)] -> [Time.Event (Bool, a)] splitEs _ [] = [] splitEs t ((ev@(a, (s,e), (h,v))):es) | t > s && t < e = (a, (s,t),(h,v)):(a, (t,e),(False,v)):(splitEs t es) | otherwise = ev:splitEs t es whileEvents :: MonadIO m => (Event -> m ()) -> m Bool whileEvents act = do event <- liftIO pollEvent case event of Quit -> return True NoEvent -> return False _ -> do act event whileEvents act runLoop :: AppConfig -> Scene -> IO () runLoop = evalStateT . runReaderT loop textSize :: String -> Font -> IO ((Float,Float)) textSize text font = do message <- renderTextSolid font text (Color 0 0 0) return (fromScreen (surfaceGetWidth message, surfaceGetHeight message)) run = do mp <- newMVar silence forkIO $ run' mp return mp run' mp = withInit [InitEverything] $ do result <- TTFG.init if not result then putStrLn "Failed to init ttf" else do enableUnicode True env <- initEnv mp --ws <- wordMenu (font env) things let scene = Scene (0,0) (0.5,0.5) --putStrLn $ show scene runLoop env scene -- colourToPixel :: Colour Double -> Pixel -- colourToPixel c = rgbColor (floor $ 256*r) (floor $ 256* g) (floor $ 256*b) -- where (RGB r g b) = toSRGB c colourToPixel :: Colour Double -> Pixel colourToPixel c = rgbColor (floor $ r*255) (floor $ g*255) (floor $ b *255) -- mapRGB (surfaceGetPixelFormat screen) 255 255 255 where (RGB r g b) = toSRGB c --colourToPixel :: Surface -> Colour Double -> IO Pixel --colourToPixel s c = (mapRGB . surfaceGetPixelFormat) s (floor $ r*255) (floor $ g*255) (floor $ b*255) fi a = fromIntegral a rgbColor :: GHC.Word.Word8 -> GHC.Word.Word8 -> GHC.Word.Word8 -> Pixel rgbColor r g b = Pixel (shiftL (fi r) 24 .|. shiftL (fi g) 16 .|. shiftL (fi b) 8 .|. (fi 255)) pixel :: Surface -> (GHC.Word.Word8,GHC.Word.Word8,GHC.Word.Word8) -> IO Pixel pixel surface (r,g,b) = mapRGB (surfaceGetPixelFormat surface) r g b
d0kt0r0/Tidal
vis/Sound/Tidal/Cycle.hs
gpl-3.0
10,084
0
20
3,068
3,822
2,046
1,776
203
3
{-# LANGUAGE GADTs #-} module Data.TConsList where import Data.Interface.TSequence data TConsList c x y where CNil :: TConsList c x x Cons :: c x y -> TConsList c y z -> TConsList c x z instance TSequence TConsList where tempty = CNil tsingleton c = Cons c CNil (<|) = Cons tviewl CNil = TEmptyL tviewl (Cons h t) = h :| t
JohnLato/transducers
src/Data/TConsList.hs
bsd-3-clause
341
0
8
82
125
68
57
12
0
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[Foreign]{Foreign calls} -} {-# LANGUAGE DeriveDataTypeable #-} module ForeignCall ( ForeignCall(..), isSafeForeignCall, Safety(..), playSafe, playInterruptible, CExportSpec(..), CLabelString, isCLabelString, pprCLabelString, CCallSpec(..), CCallTarget(..), isDynamicTarget, CCallConv(..), defaultCCallConv, ccallConvToInt, ccallConvAttribute, Header(..), CType(..), ) where import FastString import Binary import Outputable import Module import BasicTypes ( SourceText ) import Data.Char import Data.Data {- ************************************************************************ * * \subsubsection{Data types} * * ************************************************************************ -} newtype ForeignCall = CCall CCallSpec deriving Eq {-! derive: Binary !-} isSafeForeignCall :: ForeignCall -> Bool isSafeForeignCall (CCall (CCallSpec _ _ safe)) = playSafe safe -- We may need more clues to distinguish foreign calls -- but this simple printer will do for now instance Outputable ForeignCall where ppr (CCall cc) = ppr cc data Safety = PlaySafe -- Might invoke Haskell GC, or do a call back, or -- switch threads, etc. So make sure things are -- tidy before the call. Additionally, in the threaded -- RTS we arrange for the external call to be executed -- by a separate OS thread, i.e., _concurrently_ to the -- execution of other Haskell threads. | PlayInterruptible -- Like PlaySafe, but additionally -- the worker thread running this foreign call may -- be unceremoniously killed, so it must be scheduled -- on an unbound thread. | PlayRisky -- None of the above can happen; the call will return -- without interacting with the runtime system at all deriving ( Eq, Show, Data ) -- Show used just for Show Lex.Token, I think {-! derive: Binary !-} instance Outputable Safety where ppr PlaySafe = text "safe" ppr PlayInterruptible = text "interruptible" ppr PlayRisky = text "unsafe" playSafe :: Safety -> Bool playSafe PlaySafe = True playSafe PlayInterruptible = True playSafe PlayRisky = False playInterruptible :: Safety -> Bool playInterruptible PlayInterruptible = True playInterruptible _ = False {- ************************************************************************ * * \subsubsection{Calling C} * * ************************************************************************ -} data CExportSpec = CExportStatic -- foreign export ccall foo :: ty SourceText -- of the CLabelString. -- See note [Pragma source text] in BasicTypes CLabelString -- C Name of exported function CCallConv deriving Data {-! derive: Binary !-} data CCallSpec = CCallSpec CCallTarget -- What to call CCallConv -- Calling convention to use. Safety deriving( Eq ) {-! derive: Binary !-} -- The call target: -- | How to call a particular function in C-land. data CCallTarget -- An "unboxed" ccall# to named function in a particular package. = StaticTarget SourceText -- of the CLabelString. -- See note [Pragma source text] in BasicTypes CLabelString -- C-land name of label. (Maybe UnitId) -- What package the function is in. -- If Nothing, then it's taken to be in the current package. -- Note: This information is only used for PrimCalls on Windows. -- See CLabel.labelDynamic and CoreToStg.coreToStgApp -- for the difference in representation between PrimCalls -- and ForeignCalls. If the CCallTarget is representing -- a regular ForeignCall then it's safe to set this to Nothing. -- The first argument of the import is the name of a function pointer (an Addr#). -- Used when importing a label as "foreign import ccall "dynamic" ..." Bool -- True => really a function -- False => a value; only -- allowed in CAPI imports | DynamicTarget deriving( Eq, Data ) {-! derive: Binary !-} isDynamicTarget :: CCallTarget -> Bool isDynamicTarget DynamicTarget = True isDynamicTarget _ = False {- Stuff to do with calling convention: ccall: Caller allocates parameters, *and* deallocates them. stdcall: Caller allocates parameters, callee deallocates. Function name has @N after it, where N is number of arg bytes e.g. _Foo@8. This convention is x86 (win32) specific. See: http://www.programmersheaven.com/2/Calling-conventions -} -- any changes here should be replicated in the CallConv type in template haskell data CCallConv = CCallConv | CApiConv | StdCallConv | PrimCallConv | JavaScriptCallConv deriving (Eq, Data) {-! derive: Binary !-} instance Outputable CCallConv where ppr StdCallConv = text "stdcall" ppr CCallConv = text "ccall" ppr CApiConv = text "capi" ppr PrimCallConv = text "prim" ppr JavaScriptCallConv = text "javascript" defaultCCallConv :: CCallConv defaultCCallConv = CCallConv ccallConvToInt :: CCallConv -> Int ccallConvToInt StdCallConv = 0 ccallConvToInt CCallConv = 1 ccallConvToInt CApiConv = panic "ccallConvToInt CApiConv" ccallConvToInt (PrimCallConv {}) = panic "ccallConvToInt PrimCallConv" ccallConvToInt JavaScriptCallConv = panic "ccallConvToInt JavaScriptCallConv" {- Generate the gcc attribute corresponding to the given calling convention (used by PprAbsC): -} ccallConvAttribute :: CCallConv -> SDoc ccallConvAttribute StdCallConv = text "__attribute__((__stdcall__))" ccallConvAttribute CCallConv = empty ccallConvAttribute CApiConv = empty ccallConvAttribute (PrimCallConv {}) = panic "ccallConvAttribute PrimCallConv" ccallConvAttribute JavaScriptCallConv = panic "ccallConvAttribute JavaScriptCallConv" type CLabelString = FastString -- A C label, completely unencoded pprCLabelString :: CLabelString -> SDoc pprCLabelString lbl = ftext lbl isCLabelString :: CLabelString -> Bool -- Checks to see if this is a valid C label isCLabelString lbl = all ok (unpackFS lbl) where ok c = isAlphaNum c || c == '_' || c == '.' -- The '.' appears in e.g. "foo.so" in the -- module part of a ExtName. Maybe it should be separate -- Printing into C files: instance Outputable CExportSpec where ppr (CExportStatic _ str _) = pprCLabelString str instance Outputable CCallSpec where ppr (CCallSpec fun cconv safety) = hcat [ ifPprDebug callconv, ppr_fun fun ] where callconv = text "{-" <> ppr cconv <> text "-}" gc_suf | playSafe safety = text "_GC" | otherwise = empty ppr_fun (StaticTarget _ fn mPkgId isFun) = text (if isFun then "__pkg_ccall" else "__pkg_ccall_value") <> gc_suf <+> (case mPkgId of Nothing -> empty Just pkgId -> ppr pkgId) <+> pprCLabelString fn ppr_fun DynamicTarget = text "__dyn_ccall" <> gc_suf <+> text "\"\"" -- The filename for a C header file -- Note [Pragma source text] in BasicTypes data Header = Header SourceText FastString deriving (Eq, Data) instance Outputable Header where ppr (Header _ h) = quotes $ ppr h -- | A C type, used in CAPI FFI calls -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CTYPE'@, -- 'ApiAnnotation.AnnHeader','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@, -- For details on above see note [Api annotations] in ApiAnnotation data CType = CType SourceText -- Note [Pragma source text] in BasicTypes (Maybe Header) -- header to include for this type (SourceText,FastString) -- the type itself deriving (Eq, Data) instance Outputable CType where ppr (CType _ mh (_,ct)) = hDoc <+> ftext ct where hDoc = case mh of Nothing -> empty Just h -> ppr h {- ************************************************************************ * * \subsubsection{Misc} * * ************************************************************************ -} {-* Generated by DrIFT-v1.0 : Look, but Don't Touch. *-} instance Binary ForeignCall where put_ bh (CCall aa) = put_ bh aa get bh = do aa <- get bh; return (CCall aa) instance Binary Safety where put_ bh PlaySafe = do putByte bh 0 put_ bh PlayInterruptible = do putByte bh 1 put_ bh PlayRisky = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return PlaySafe 1 -> do return PlayInterruptible _ -> do return PlayRisky instance Binary CExportSpec where put_ bh (CExportStatic ss aa ab) = do put_ bh ss put_ bh aa put_ bh ab get bh = do ss <- get bh aa <- get bh ab <- get bh return (CExportStatic ss aa ab) instance Binary CCallSpec where put_ bh (CCallSpec aa ab ac) = do put_ bh aa put_ bh ab put_ bh ac get bh = do aa <- get bh ab <- get bh ac <- get bh return (CCallSpec aa ab ac) instance Binary CCallTarget where put_ bh (StaticTarget ss aa ab ac) = do putByte bh 0 put_ bh ss put_ bh aa put_ bh ab put_ bh ac put_ bh DynamicTarget = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do ss <- get bh aa <- get bh ab <- get bh ac <- get bh return (StaticTarget ss aa ab ac) _ -> do return DynamicTarget instance Binary CCallConv where put_ bh CCallConv = do putByte bh 0 put_ bh StdCallConv = do putByte bh 1 put_ bh PrimCallConv = do putByte bh 2 put_ bh CApiConv = do putByte bh 3 put_ bh JavaScriptCallConv = do putByte bh 4 get bh = do h <- getByte bh case h of 0 -> do return CCallConv 1 -> do return StdCallConv 2 -> do return PrimCallConv 3 -> do return CApiConv _ -> do return JavaScriptCallConv instance Binary CType where put_ bh (CType s mh fs) = do put_ bh s put_ bh mh put_ bh fs get bh = do s <- get bh mh <- get bh fs <- get bh return (CType s mh fs) instance Binary Header where put_ bh (Header s h) = put_ bh s >> put_ bh h get bh = do s <- get bh h <- get bh return (Header s h)
vikraman/ghc
compiler/prelude/ForeignCall.hs
bsd-3-clause
11,947
0
15
4,174
2,132
1,069
1,063
206
1
{-# LANGUAGE QuasiQuotes, OverloadedStrings, ExtendedDefaultRules, CPP #-} -- Keep all the language pragmas here so it can be compiled separately. module Main where import Prelude import qualified Data.Text as T import GHC hiding (Qualified) import GHC.Paths import Data.IORef import Control.Monad import Control.Monad.IO.Class (MonadIO, liftIO) import Data.List import System.Directory import Shelly (Sh, shelly, cmd, (</>), toTextIgnore, cd, withTmpDir, mkdir_p, touchfile, fromText) import qualified Data.Text as T import qualified Shelly import Control.Applicative ((<$>)) import System.SetEnv (setEnv) import Data.String.Here import Data.Monoid import IHaskell.Eval.Parser import IHaskell.Types import IHaskell.IPython import IHaskell.Eval.Evaluate as Eval hiding (liftIO) import qualified IHaskell.Eval.Evaluate as Eval (liftIO) import IHaskell.Eval.Completion import IHaskell.Eval.ParseShell import Debug.Trace import Test.Hspec import Test.Hspec.HUnit import Test.HUnit (assertBool, assertFailure) lstrip :: String -> String lstrip = dropWhile (`elem` (" \t\r\n" :: String)) rstrip :: String -> String rstrip = reverse . lstrip . reverse strip :: String -> String strip = rstrip . lstrip replace :: String -> String -> String -> String replace needle replacement haystack = T.unpack $ T.replace (T.pack needle) (T.pack replacement) (T.pack haystack) traceShowId x = traceShow x x doGhc = runGhc (Just libdir) parses str = do res <- doGhc $ parseString str return $ map unloc res like parser desired = parser >>= (`shouldBe` desired) is string blockType = do result <- doGhc $ parseString string map unloc result `shouldBe` [blockType $ strip string] eval string = do outputAccum <- newIORef [] pagerAccum <- newIORef [] let publish evalResult = case evalResult of IntermediateResult {} -> return () FinalResult outs page [] -> do modifyIORef outputAccum (outs :) modifyIORef pagerAccum (page :) noWidgetHandling s _ = return s getTemporaryDirectory >>= setCurrentDirectory let state = defaultKernelState { getLintStatus = LintOff } interpret libdir False $ const $ Eval.evaluate state string publish noWidgetHandling out <- readIORef outputAccum pagerOut <- readIORef pagerAccum return (reverse out, unlines . map extractPlain . reverse $ pagerOut) evaluationComparing comparison string = do let indent (' ':x) = 1 + indent x indent _ = 0 empty = null . strip stringLines = filter (not . empty) $ lines string minIndent = minimum (map indent stringLines) newString = unlines $ map (drop minIndent) stringLines eval newString >>= comparison becomes string expected = evaluationComparing comparison string where comparison :: ([Display], String) -> IO () comparison (results, pageOut) = do when (length results /= length expected) $ expectationFailure $ "Expected result to have " ++ show (length expected) ++ " results. Got " ++ show results forM_ (zip results expected) $ \(ManyDisplay [Display result], expected) -> case extractPlain result of "" -> expectationFailure $ "No plain-text output in " ++ show result ++ "\nExpected: " ++ expected str -> str `shouldBe` expected pages string expected = evaluationComparing comparison string where comparison (results, pageOut) = strip (stripHtml pageOut) `shouldBe` strip (unlines expected) -- A very, very hacky method for removing HTML stripHtml str = go str where go ('<':str) = case stripPrefix "script" str of Nothing -> go' str Just str -> dropScriptTag str go (x:xs) = x : go xs go [] = [] go' ('>':str) = go str go' (x:xs) = go' xs go' [] = error $ "Unending bracket html tag in string " ++ str dropScriptTag str = case stripPrefix "</script>" str of Just str -> go str Nothing -> dropScriptTag $ tail str readCompletePrompt :: String -> (String, Int) -- | @readCompletePrompt "xs*ys"@ return @(xs, i)@ where i is the location of -- @'*'@ in the input string. readCompletePrompt string = case elemIndex '*' string of Nothing -> error "Expected cursor written as '*'." Just idx -> (replace "*" "" string, idx) completes string expected = completionTarget newString cursorloc `shouldBe` expected where (newString, cursorloc) = readCompletePrompt string completionEvent :: String -> Interpreter (String, [String]) completionEvent string = complete newString cursorloc where (newString, cursorloc) = case elemIndex '*' string of Nothing -> error "Expected cursor written as '*'." Just idx -> (replace "*" "" string, idx) completionEventInDirectory :: String -> IO (String, [String]) completionEventInDirectory string = withHsDirectory $ const $ completionEvent string shouldHaveCompletionsInDirectory :: String -> [String] -> IO () shouldHaveCompletionsInDirectory string expected = do (matched, completions) <- completionEventInDirectory string let existsInCompletion = (`elem` completions) unmatched = filter (not . existsInCompletion) expected expected `shouldBeAmong` completions completionHas string expected = do (matched, completions) <- doGhc $ do initCompleter completionEvent string let existsInCompletion = (`elem` completions) unmatched = filter (not . existsInCompletion) expected expected `shouldBeAmong` completions initCompleter :: Interpreter () initCompleter = do flags <- getSessionDynFlags setSessionDynFlags $ flags { hscTarget = HscInterpreted, ghcLink = LinkInMemory } -- Import modules. imports <- mapM parseImportDecl ["import Prelude", "import qualified Control.Monad", "import qualified Data.List as List", "import IHaskell.Display", "import Data.Maybe as Maybe"] setContext $ map IIDecl imports inDirectory :: [Shelly.FilePath] -- ^ directories relative to temporary directory -> [Shelly.FilePath] -- ^ files relative to temporary directory -> (Shelly.FilePath -> Interpreter a) -> IO a -- | Run an Interpreter action, but first make a temporary directory -- with some files and folder and cd to it. inDirectory dirs files action = shelly $ withTmpDir $ \dirPath -> do cd dirPath mapM_ mkdir_p dirs mapM_ touchfile files liftIO $ doGhc $ wrap (T.unpack $ toTextIgnore dirPath) (action dirPath) where cdEvent path = liftIO $ setCurrentDirectory path --Eval.evaluate defaultKernelState (":! cd " ++ path) noPublish wrap :: FilePath -> Interpreter a -> Interpreter a wrap path action = do initCompleter pwd <- Eval.liftIO getCurrentDirectory cdEvent path -- change to the temporary directory out <- action -- run action cdEvent pwd -- change back to the original directory return out withHsDirectory :: (Shelly.FilePath -> Interpreter a) -> IO a withHsDirectory = inDirectory [p "" </> p "dir", p "dir" </> p "dir1"] [p ""</> p "file1.hs", p "dir" </> p "file2.hs", p "" </> p "file1.lhs", p "dir" </> p "file2.lhs"] where p :: FilePath -> FilePath p = id main :: IO () main = hspec $ do parserTests evalTests completionTests completionTests = do parseShellTests describe "Completion" $ do it "correctly gets the completion identifier without dots" $ do "hello*" `completes` ["hello"] "hello aa*bb goodbye" `completes` ["aa"] "hello aabb* goodbye" `completes` ["aabb"] "aacc* goodbye" `completes` ["aacc"] "hello *aabb goodbye" `completes` [] "*aabb goodbye" `completes` [] it "correctly gets the completion identifier with dots" $ do "hello test.aa*bb goodbye" `completes` ["test", "aa"] "Test.*" `completes` ["Test", ""] "Test.Thing*" `completes` ["Test", "Thing"] "Test.Thing.*" `completes` ["Test", "Thing", ""] "Test.Thing.*nope" `completes` ["Test", "Thing", ""] it "correctly gets the completion type" $ do completionType "import Data." 12 ["Data", ""] `shouldBe` ModuleName "Data" "" completionType "import Prel" 11 ["Prel"] `shouldBe` ModuleName "" "Prel" completionType "import D.B.M" 12 ["D", "B", "M"] `shouldBe` ModuleName "D.B" "M" completionType " import A." 10 ["A", ""] `shouldBe` ModuleName "A" "" completionType "import a.x" 10 ["a", "x"] `shouldBe` Identifier "x" completionType "A.x" 3 ["A", "x"] `shouldBe` Qualified "A" "x" completionType "a.x" 3 ["a", "x"] `shouldBe` Identifier "x" completionType "pri" 3 ["pri"] `shouldBe` Identifier "pri" completionType ":load A" 7 ["A"] `shouldBe` HsFilePath ":load A" "A" completionType ":! cd " 6 [""] `shouldBe` FilePath ":! cd " "" it "properly completes identifiers" $ do "pri*" `completionHas` ["print"] "ma*" `completionHas` ["map"] "hello ma*" `completionHas` ["map"] "print $ catMa*" `completionHas` ["catMaybes"] it "properly completes qualified identifiers" $ do "Control.Monad.liftM*" `completionHas` [ "Control.Monad.liftM" , "Control.Monad.liftM2" , "Control.Monad.liftM5"] "print $ List.intercal*" `completionHas` ["List.intercalate"] "print $ Data.Maybe.cat*" `completionHas` ["Data.Maybe.catMaybes"] "print $ Maybe.catM*" `completionHas` ["Maybe.catMaybes"] it "properly completes imports" $ do "import Data.*" `completionHas` ["Data.Maybe", "Data.List"] "import Data.M*" `completionHas` ["Data.Maybe"] "import Prel*" `completionHas` ["Prelude"] it "properly completes haskell file paths on :load directive" $ let loading xs = ":load " ++ T.unpack (toTextIgnore xs) paths = map (T.unpack . toTextIgnore) in do loading ("dir" </> "file*") `shouldHaveCompletionsInDirectory` paths ["dir" </> "file2.hs", "dir" </> "file2.lhs"] loading ("" </> "file1*") `shouldHaveCompletionsInDirectory` paths ["" </> "file1.hs", "" </> "file1.lhs"] loading ("" </> "file1*") `shouldHaveCompletionsInDirectory` paths ["" </> "file1.hs", "" </> "file1.lhs"] loading ("" </> "./*") `shouldHaveCompletionsInDirectory` paths ["./" </> "dir/" , "./" </> "file1.hs" , "./" </> "file1.lhs"] loading ("" </> "./*") `shouldHaveCompletionsInDirectory` paths ["./" </> "dir/" , "./" </> "file1.hs" , "./" </> "file1.lhs"] it "provides path completions on empty shell cmds " $ ":! cd *" `shouldHaveCompletionsInDirectory` map (T.unpack . toTextIgnore) ["" </> "dir/" , "" </> "file1.hs" , "" </> "file1.lhs"] let withHsHome action = withHsDirectory $ \dirPath-> do home <- shelly $ Shelly.get_env_text "HOME" setHomeEvent dirPath result <- action setHomeEvent $ Shelly.fromText home return result setHomeEvent path = liftIO $ setEnv "HOME" (T.unpack $ toTextIgnore path) it "correctly interprets ~ as the environment HOME variable" $ let shouldHaveCompletions :: String -> [String] -> IO () shouldHaveCompletions string expected = do (matched, completions) <- withHsHome $ completionEvent string let existsInCompletion = (`elem` completions) unmatched = filter (not . existsInCompletion) expected expected `shouldBeAmong` completions in do ":! cd ~/*" `shouldHaveCompletions` ["~/dir/"] ":! ~/*" `shouldHaveCompletions` ["~/dir/"] ":load ~/*" `shouldHaveCompletions` ["~/dir/"] ":l ~/*" `shouldHaveCompletions` ["~/dir/"] let shouldHaveMatchingText :: String -> String -> IO () shouldHaveMatchingText string expected = do matchText <- withHsHome $ fst <$> uncurry complete (readCompletePrompt string) matchText `shouldBe` expected setHomeEvent path = liftIO $ setEnv "HOME" (T.unpack $ toTextIgnore path) it "generates the correct matchingText on `:! cd ~/*` " $ do ":! cd ~/*" `shouldHaveMatchingText` ("~/" :: String) it "generates the correct matchingText on `:load ~/*` " $ do ":load ~/*" `shouldHaveMatchingText` ("~/" :: String) it "generates the correct matchingText on `:l ~/*` " $ do ":l ~/*" `shouldHaveMatchingText` ("~/" :: String) evalTests = do describe "Code Evaluation" $ do it "evaluates expressions" $ do "3" `becomes` ["3"] "3+5" `becomes` ["8"] "print 3" `becomes` ["3"] [hereLit| let x = 11 z = 10 in x+z |] `becomes` ["21"] it "evaluates flags" $ do ":set -package hello" `becomes` ["Warning: -package not supported yet"] ":set -XNoImplicitPrelude" `becomes` [] it "evaluates multiline expressions" $ do [hereLit| import Control.Monad forM_ [1, 2, 3] $ \x -> print x |] `becomes` ["1\n2\n3"] it "evaluates function declarations silently" $ do [hereLit| fun :: [Int] -> Int fun [] = 3 fun (x:xs) = 10 fun [1, 2] |] `becomes` ["10"] it "evaluates data declarations" $ do [hereLit| data X = Y Int | Z String deriving (Show, Eq) print [Y 3, Z "No"] print (Y 3 == Z "No") |] `becomes` ["[Y 3,Z \"No\"]", "False"] it "evaluates do blocks in expressions" $ do [hereLit| show (show (do Just 10 Nothing Just 100)) |] `becomes` ["\"\\\"Nothing\\\"\""] it "is silent for imports" $ do "import Control.Monad" `becomes` [] "import qualified Control.Monad" `becomes` [] "import qualified Control.Monad as CM" `becomes` [] "import Control.Monad (when)" `becomes` [] it "evaluates directives" $ do ":typ 3" `becomes` ["3 :: forall a. Num a => a"] ":k Maybe" `becomes` ["Maybe :: * -> *"] #if MIN_VERSION_ghc(7, 8, 0) ":in String" `pages` ["type String = [Char] \t-- Defined in \8216GHC.Base\8217"] #else ":in String" `pages` ["type String = [Char] \t-- Defined in `GHC.Base'"] #endif parserTests = do layoutChunkerTests moduleNameTests parseStringTests layoutChunkerTests = describe "Layout Chunk" $ do it "chunks 'a string'" $ map unloc (layoutChunks "a string") `shouldBe` ["a string"] it "chunks 'a\\n string'" $ map unloc (layoutChunks "a\n string") `shouldBe` ["a\n string"] it "chunks 'a\\n string\\nextra'" $ map unloc (layoutChunks "a\n string\nextra") `shouldBe` ["a\n string","extra"] it "chunks strings with too many lines" $ map unloc (layoutChunks "a\n\nstring") `shouldBe` ["a","string"] it "parses multiple exprs" $ do let text = [hereLit| first second third fourth |] layoutChunks text `shouldBe` [Located 2 "first", Located 4 "second", Located 5 "third", Located 7 "fourth"] moduleNameTests = describe "Get Module Name" $ do it "parses simple module names" $ "module A where\nx = 3" `named` ["A"] it "parses module names with dots" $ "module A.B where\nx = 3" `named` ["A", "B"] it "parses module names with exports" $ "module A.B.C ( x ) where x = 3" `named` ["A", "B", "C"] it "errors when given unnamed modules" $ do doGhc (getModuleName "x = 3") `shouldThrow` anyException where named str result = do res <- doGhc $ getModuleName str res `shouldBe` result parseStringTests = describe "Parser" $ do it "parses empty strings" $ parses "" `like` [] it "parses simple imports" $ "import Data.Monoid" `is` Import it "parses simple arithmetic" $ "3 + 5" `is` Expression it "parses :type" $ parses ":type x\n:ty x" `like` [ Directive GetType "x", Directive GetType "x" ] it "parses :info" $ parses ":info x\n:in x" `like` [ Directive GetInfo "x", Directive GetInfo "x" ] it "parses :help and :?" $ parses ":? x\n:help x" `like` [ Directive GetHelp "x", Directive GetHelp "x" ] it "parses :set x" $ parses ":set x" `like` [ Directive SetDynFlag "x" ] it "parses :extension x" $ parses ":ex x\n:extension x" `like` [ Directive SetExtension "x", Directive SetExtension "x" ] it "fails to parse :nope" $ parses ":nope goodbye" `like` [ ParseError (Loc 1 1) "Unknown directive: 'nope'." ] it "parses number followed by let stmt" $ parses "3\nlet x = expr" `like` [ Expression "3", Statement "let x = expr" ] it "parses let x in y" $ "let x = 3 in x + 3" `is` Expression it "parses a data declaration" $ "data X = Y Int" `is` Declaration it "parses number followed by type directive" $ parses "3\n:t expr" `like` [ Expression "3", Directive GetType "expr" ] it "parses a <- statement" $ "y <- print 'no'" `is` Statement it "parses a <- stmt followed by let stmt" $ parses "y <- do print 'no'\nlet x = expr" `like` [ Statement "y <- do print 'no'", Statement "let x = expr" ] it "parses <- followed by let followed by expr" $ parses "y <- do print 'no'\nlet x = expr\nexpression" `like` [ Statement "y <- do print 'no'", Statement "let x = expr", Expression "expression" ] it "parses two print statements" $ parses "print yes\nprint no" `like` [ Expression "print yes", Expression "print no" ] it "parses a pattern-maching function declaration" $ "fun [] = 10" `is` Declaration it "parses a function decl followed by an expression" $ parses "fun [] = 10\nprint 'h'" `like` [ Declaration "fun [] = 10", Expression "print 'h'" ] it "parses list pattern matching fun decl" $ "fun (x : xs) = 100" `is` Declaration it "parses two pattern matches as the same declaration" $ "fun [] = 10\nfun (x : xs) = 100" `is` Declaration it "parses a type signature followed by a declaration" $ "fun :: [a] -> Int\nfun [] = 10\nfun (x : xs) = 100" `is` Declaration it "parases a simple module" $ "module A where x = 3" `is` Module it "parses a module with an export" $ "module B (x) where x = 3" `is` Module it "breaks when a let is incomplete" $ parses "let x = 3 in" `like` [ ParseError (Loc 1 13) "parse error (possibly incorrect indentation or mismatched brackets)" ] it "breaks without data kinds" $ parses "data X = 3" `like` [ #if MIN_VERSION_ghc(7, 8, 0) ParseError (Loc 1 10) "Illegal literal in type (use DataKinds to enable): 3" #else ParseError (Loc 1 10) "Illegal literal in type (use -XDataKinds to enable): 3" #endif ] it "parses statements after imports" $ do parses "import X\nprint 3" `like` [ Import "import X", Expression "print 3" ] parses "import X\n\nprint 3" `like` [ Import "import X", Expression "print 3" ] it "ignores blank lines properly" $ [hereLit| test arg = hello where x = y z = w |] `is` Declaration it "doesn't break on long strings" $ do let longString = concat $ replicate 20 "hello " ("img ! src \"" ++ longString ++ "\" ! width \"500\"") `is` Expression it "parses do blocks in expression" $ do [hereLit| show (show (do Just 10 Nothing Just 100)) |] `is` Expression it "correctly locates parsed items" $ do let go = doGhc . parseString go [hereLit| first second |] >>= (`shouldBe` [Located 2 (Expression "first"), Located 4 (Expression "second")]) parseShellTests = describe "Parsing Shell Commands" $ do test "A" ["A"] test ":load A" [":load", "A"] test ":!l ~/Downloads/MyFile\\ Has\\ Spaces.txt" [":!l", "~/Downloads/MyFile\\ Has\\ Spaces.txt"] test ":!l \"~/Downloads/MyFile Has Spaces.txt\" /Another/File\\ WithSpaces.doc" [":!l", "~/Downloads/MyFile Has Spaces.txt", "/Another/File\\ WithSpaces.doc" ] where test string expected = it ("parses " ++ string ++ " correctly") $ string `shouldParseTo` expected shouldParseTo xs ys = fun ys (parseShell xs) where fun ys (Right xs') = xs' `shouldBe` ys fun ys (Left e) = assertFailure $ "parseShell returned error: \n" ++ show e -- Useful HSpec expectations ---- --------------------------------- shouldBeAmong :: (Show a, Eq a) => [a] -> [a] -> Expectation -- | -- @sublist \`shouldbeAmong\` list@ sets the expectation that @sublist@ elements are -- among those in @list@. sublist `shouldBeAmong` list = assertBool errorMsg $ and [x `elem` list | x <- sublist] where errorMsg = show list ++ " doesn't contain " ++ show sublist
artuuge/IHaskell
Hspec.hs
mit
22,744
0
22
7,066
5,323
2,744
2,579
436
7
import Data.List import Data.Word import Data.Int fib1 n = snd . foldl fib' (1, 0) . map toEnum $ unfoldl divs n where unfoldl f x = case f x of Nothing -> [] Just (u, v) -> unfoldl f v ++ [u] divs 0 = Nothing divs k = Just (uncurry (flip (,)) (k `divMod` 2)) fib' (f, g) p | p = (f*(f+2*g), f^(2::Int) + g^(2::Int)) | otherwise = (f^(2::Int)+g^(2::Int), g*(2*f-g)) main :: IO () main = do print (fib1 22 :: Int) print (fib1 22 :: Int8) print (fib1 22 :: Int16) print (fib1 22 :: Int32) print (fib1 22 :: Int64) print (fib1 22 :: Word) print (fib1 22 :: Word8) print (fib1 22 :: Word16) print (fib1 22 :: Word32) print (fib1 22 :: Word64) print (fib1 22 :: Integer)
hvr/jhc
regress/tests/7_large/fastest_fib.hs
mit
821
6
10
290
442
227
215
25
3
{-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fdefer-type-errors #-} module Main where type A a = forall b. a doA :: A a -> [a] doA = undefined f :: A a -> a f = doA main = do { print "Hello 1" ; f `seq` print "Hello 2" -- The casts are pushed inside the lambda -- for f, so this seq succeds fine ; f (error "urk") `seq` print "Bad" -- But when we *call* f we get a type error }
green-haskell/ghc
testsuite/tests/typecheck/should_run/T7861.hs
bsd-3-clause
454
0
10
160
106
61
45
11
1
module ListSort () where {-@ LIQUID "--no-termination" @-} import Language.Haskell.Liquid.Prelude {-@ type OList a = [a]<{\x v -> v >= x}> @-} {-@ app :: forall <p :: a -> Prop, q :: a -> Prop, r :: a -> Prop>. {x::a<p> |- a<q> <: {v:a| x <= v}} {a<p> <: a<r>} {a<q> <: a<r>} Ord a => OList (a<p>) -> OList (a<q>) -> OList a<r> @-} app :: Ord a => [a] -> [a] -> [a] app [] ys = ys app (x:xs) ys = x:(app xs (x:ys)) takeL :: Ord a => a -> [a] -> [a] {-@ takeL :: Ord a => x:a -> [a] -> [{v:a|v<=x}] @-} takeL x [] = [] takeL x (y:ys) = if (y<x) then y:(takeL x ys) else takeL x ys takeGE :: Ord a => a -> [a] -> [a] {-@ takeGE :: Ord a => x:a -> [a] -> [{v:a|v>=x}] @-} takeGE x [] = [] takeGE x (y:ys) = if (y>=x) then y:(takeGE x ys) else takeGE x ys {-@ quicksort :: (Ord a) => xs:[a] -> [a]<{\fld v -> (v >= fld)}> @-} quicksort [] = [] quicksort (x:xs) = app xsle (x:xsge) where xsle = quicksort (takeL x xs) xsge = quicksort (takeGE x xs) {-@ qsort :: (Ord a) => xs:[a] -> [a]<{\fld v -> (v >= fld)}> @-} qsort [] = [] qsort (x:xs) = app (qsort [y | y <- xs, y < x]) (x:(qsort [z | z <- xs, z >= x]))
mightymoose/liquidhaskell
tests/neg/ConstraintsAppend.hs
bsd-3-clause
1,188
0
12
332
438
235
203
17
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Data.FileEmbed import Unlisted main :: IO () main = do putStrLn ("main " ++ show foo ++ " " ++ show embedded) if embedded == "FAIL\n" then error "embedded contains FAIL" else return () embedded = $(embedFile "embed.txt")
akhileshs/stack
test/integration/tests/32-unlisted-module/files/src/Main.hs
bsd-3-clause
342
0
12
78
91
47
44
12
2
-- !!! buggy deriving with function type, reported by Sigbjorn Finne module ShouldFail where data Foo = Foo (Int -> Int) deriving Eq
urbanslug/ghc
testsuite/tests/deriving/should_fail/drvfail007.hs
bsd-3-clause
134
0
8
24
24
15
9
2
0
module Employee where import Data.Tree -- Employee names are represented by Strings. type Name = String -- The amount of fun an employee would have at the party, represented -- by an Integer type Fun = Integer -- An Employee consists of a name and a fun score. data Employee = Emp { empName :: Name, empFun :: Fun } deriving (Show, Read, Eq) -- A small company hierarchy to use for testing purposes. testCompany :: Tree Employee testCompany = Node (Emp "Stan" 9) [ Node (Emp "Bob" 2) [ Node (Emp "Joe" 5) [ Node (Emp "John" 1) [] , Node (Emp "Sue" 5) [] ] , Node (Emp "Fred" 3) [] ] , Node (Emp "Sarah" 17) [ Node (Emp "Sam" 18) [] ] ] testCompany2 :: Tree Employee testCompany2 = Node (Emp "Stan" 9) [ Node (Emp "Bob" 3) -- (8, 8) [ Node (Emp "Joe" 5) -- (5, 6) [ Node (Emp "John" 1) [] -- (1, 0) , Node (Emp "Sue" 5) [] -- (5, 0) ] , Node (Emp "Fred" 3) [] -- (3, 0) ] , Node (Emp "Sarah" 17) -- (17, 4) [ Node (Emp "Sam" 4) [] -- (4, 0) ] ] -- A type to store a list of guests and their total fun score. data GuestList = GL [Employee] Fun deriving (Show, Eq) instance Ord GuestList where compare (GL _ f1) (GL _ f2) = compare f1 f2
vaibhav276/haskell_cs194_assignments
io/Employee.hs
mit
1,296
0
13
400
426
227
199
30
1
-- | -- An API for the implementation of interpreters. -- Should only be used by the libraries, which implement the interpreters. module XMLQuery.AST where import XMLQuery.Prelude hiding (Text) import qualified XMLQuery.Prelude as Prelude data Text a = Text (Prelude.Text -> Either Prelude.Text a) deriving instance Functor Text data Element a = ElementNameText (Alt Text a) | ElementAttr (Alt Attr a) | ElementNodes (Alt Nodes a) deriving instance Functor Element data Attr a = AttrNameText (Alt Text a) | AttrValueText (Alt Text a) deriving instance Functor Attr data Nodes a = NodesNode (Alt Node a) deriving instance Functor Nodes data Node a = NodeElement (Alt Element a) | NodeText (Alt Text a) deriving instance Functor Node
sannsyn/xml-query
library/XMLQuery/AST.hs
mit
769
0
10
153
218
122
96
-1
-1
-- file ch02/Take.hs -- `->` is right-associative! take :: Int -> ([a] -> [a])
supermitch/learn-haskell
real-world-haskell/ch02/Take.hs
mit
79
0
8
14
25
15
10
1
0
module FileFormat.INES (readINESFile) where import Data.Array.Unboxed import Data.Bits import Data.Char import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Word import Prelude hiding (Maybe(..)) import Motherboard.NES import Data.Strict.Maybe data INESHeader = INESHeaderVersion1 { inesHeaderProgramReadOnlyMemoryBlocks :: Word8, inesHeaderCharacterReadOnlyMemoryBlocks :: Word8, inesHeaderProgramReadWriteMemoryBlocks :: Word8, inesHeaderMapperNumber :: Word8, inesHeaderMirroringType :: Mirroring, inesHeaderBatteryPresent :: Bool, inesHeaderTrainerPresent :: Bool, inesHeaderSystem :: System } readINESFile :: FilePath -> IO (Maybe HardwareState) readINESFile filename = do bytestring <- BS.readFile filename return $ decodeINESFile bytestring decodeINESHeader :: ByteString -> Maybe (INESHeader, ByteString) decodeINESHeader bytestring = if BS.length bytestring < 16 then Nothing else let (headerBytes, rest) = BS.splitAt 16 bytestring magicNumber = BS.take 4 headerBytes magicNumberValid = magicNumber == inesHeaderMagicNumber versionBits = shiftR (BS.index headerBytes 7) 2 .&. 0x3 padBytes = BS.take 5 $ BS.drop 11 headerBytes padBytesAllZero = all (== 0x00) $ BS.unpack padBytes programReadOnlyMemoryBlocks = BS.index headerBytes 4 characterReadOnlyMemoryBlocks = BS.index headerBytes 5 programReadWriteMemoryBlocks = BS.index headerBytes 8 flagsByte1 = BS.index headerBytes 6 flagsByte2 = BS.index headerBytes 7 mapperNumberLowNibble = shiftR flagsByte1 4 .&. 0x0F mapperNumberHighNibble = shiftR flagsByte2 4 .&. 0x0F mapperNumber = shiftL mapperNumberHighNibble 4 .|. mapperNumberLowNibble mirroringTypeLowBit = shiftR flagsByte1 0 .&. 0x01 mirroringTypeHighBit = shiftR flagsByte1 3 .&. 0x01 mirroringType = case (mirroringTypeHighBit, mirroringTypeLowBit) of (0, 0) -> HorizontalMirroring (0, 1) -> VerticalMirroring (1, _) -> FourScreenMirroring batteryPresentBit = shiftR flagsByte1 1 .&. 0x01 batteryPresent = case batteryPresentBit of 0 -> False 1 -> True trainerPresentBit = shiftR flagsByte1 2 .&. 0x01 trainerPresent = case trainerPresentBit of 0 -> False 1 -> True systemLowBit = shiftR flagsByte2 0 .&. 0x01 systemHighBit = shiftR flagsByte2 1 .&. 0x01 (system, systemValid) = case (systemHighBit, systemLowBit) of (0, 0) -> (PlainSystem, True) (0, 1) -> (VersusUnisystem, True) (1, 0) -> (PlayChoice10, True) (1, 1) -> (undefined, False) in if (not magicNumberValid) || (not systemValid) then Nothing else if (versionBits == 0) && padBytesAllZero then Just (INESHeaderVersion1 { inesHeaderProgramReadOnlyMemoryBlocks = programReadOnlyMemoryBlocks, inesHeaderCharacterReadOnlyMemoryBlocks = characterReadOnlyMemoryBlocks, inesHeaderProgramReadWriteMemoryBlocks = programReadWriteMemoryBlocks, inesHeaderMapperNumber = mapperNumber, inesHeaderMirroringType = mirroringType, inesHeaderBatteryPresent = batteryPresent, inesHeaderTrainerPresent = trainerPresent, inesHeaderSystem = system }, rest) else Nothing decodeINESFile :: ByteString -> Maybe HardwareState decodeINESFile bytestring = do (header, bytestring) <- decodeINESHeader bytestring (maybeTrainer, bytestring) <- case (inesHeaderTrainerPresent header, BS.length bytestring >= 512) of (False, _) -> return $ (Nothing, bytestring) (True, True) -> return $ (Just $ array (0, 511) $ zip [0..] $ BS.unpack $ BS.take 512 bytestring, BS.drop 512 bytestring) _ -> Nothing programReadOnlyMemorySize <- return $ (fromIntegral $ inesHeaderProgramReadOnlyMemoryBlocks header) * 16384 (programReadOnlyMemory, bytestring) <- if BS.length bytestring >= fromIntegral programReadOnlyMemorySize then return $ (array (0, programReadOnlyMemorySize - 1) $ zip [0..] $ BS.unpack $ BS.take (fromIntegral programReadOnlyMemorySize) bytestring, BS.drop programReadOnlyMemorySize bytestring) else Nothing characterReadOnlyMemorySize <- return $ (fromIntegral $ inesHeaderCharacterReadOnlyMemoryBlocks header) * 8192 (characterReadOnlyMemory, bytestring) <- if BS.length bytestring >= characterReadOnlyMemorySize then return $ (array (0, characterReadOnlyMemorySize - 1) $ zip [0..] $ BS.unpack $ BS.take characterReadOnlyMemorySize bytestring, BS.drop characterReadOnlyMemorySize bytestring) else Nothing (maybePlayChoice10HintScreen, bytestring) <- case (inesHeaderSystem header == PlayChoice10, BS.length bytestring >= 8192) of (False, _) -> return $ (Nothing, bytestring) (True, True) -> return $ (Just $ array (0, 8191) $ zip [0..] $ BS.unpack $ BS.take 8192 bytestring, BS.drop 8192 bytestring) _ -> Nothing if BS.null bytestring then return $ HardwareState { hardwareStateProgramReadOnlyMemory = programReadOnlyMemory, hardwareStateCharacterReadOnlyMemory = characterReadOnlyMemory, hardwareStateTrainer = maybeTrainer, hardwareStatePlayChoice10HintScreen = maybePlayChoice10HintScreen, hardwareStateMapperNumber = inesHeaderMapperNumber header, hardwareStateMirroringType = inesHeaderMirroringType header, hardwareStateBatteryPresent = inesHeaderBatteryPresent header, hardwareStateSystem = inesHeaderSystem header } else Nothing inesHeaderMagicNumber :: ByteString inesHeaderMagicNumber = BS.pack $ map fromIntegral [ord 'N', ord 'E', ord 'S', 0x1A]
IreneKnapp/legal-emulator
BackEnd/FileFormat/INES.hs
mit
7,809
0
18
3,241
1,470
797
673
161
11
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Poker.Classify where import Control.Applicative import Control.Monad import Control.Monad.Identity import Control.Monad.Reader import Data.Function (on) import qualified Data.List as L import Data.Maybe import Poker.Types -- Hand Classification data ClassificationEnv = ClassificationEnv { base :: [Card] , rankGroups :: [[Card]] , suitGroups :: [[Card]] } deriving (Show, Read) type Classification a = ClassifiactionT Identity a newtype ClassifiactionT m a = ClassifiactionT { unClassificationT :: ReaderT ClassificationEnv m a } deriving ( Functor, Applicative, Monad , MonadReader ClassificationEnv ) runClassification :: ClassificationEnv -> Classification [Maybe Hand] -> [Maybe Hand] runClassification env = runIdentity . runClassificationT env runClassificationT :: ClassificationEnv -> ClassifiactionT m a -> m a runClassificationT env = flip runReaderT env . unClassificationT class MonadClassification m where getBase :: m [Card] getRankGroups :: m [[Card]] getSuitGroups :: m [[Card]] instance (Monad m) => MonadClassification (ClassifiactionT m) where getBase = liftM base ask getRankGroups = liftM rankGroups ask getSuitGroups = liftM suitGroups ask classify :: [Classification (Maybe Hand)] -> [Card] -> Hand classify classes cards = head $ catMaybes $ runClassification (createClassificationEnv cards) $ sequence classes createClassificationEnv :: [Card] -> ClassificationEnv createClassificationEnv cards = ClassificationEnv { base = cards' , rankGroups = L.groupBy ((==) `on` rank) cards' , suitGroups = L.groupBy ((==) `on` suit) $ L.sortBy (compare `on` suit) cards } where cards' = L.sort cards defaultHandRules :: [ClassifiactionT Identity (Maybe Hand)] defaultHandRules = [ straightFlush, fourOfAKind, fullHouse, flush, straight, threeOfAKind, pairs, highCard ] highCard :: (Monad m) => ClassifiactionT m (Maybe Hand) highCard = do (Card r s:_) <- getBase return $ Just $ HighCard (r, s) pairs :: (Monad m) => ClassifiactionT m (Maybe Hand) pairs = do p <- liftM (foldl collapse (Nothing, Nothing)) getRankGroups case p of (Just (r0, s0), Just (r1, s1)) -> return $ Just $ TwoPair (r0, s0) (r1, s1) ( Just (r, s), Nothing) -> return $ Just $ OnePair (r, s) _ -> return Nothing where collapse (Nothing, Nothing) [Card r s, _] = (Just (r, s), Nothing) collapse ( a, Nothing) [Card r s, _] = ( a , Just (r, s)) collapse o _ = o threeOfAKind :: (Monad m) => ClassifiactionT m (Maybe Hand) threeOfAKind = liftM (foldl collapse Nothing) getRankGroups where collapse Nothing [Card r s, _, _] = Just $ ThreeOfAKind (r, s) collapse o _ = o straight :: (Monad m) => ClassifiactionT m (Maybe Hand) straight = do x <- liftM (foldl collapse (dc, dc, 1::Int) . L.nubBy ((==) `on` rank)) getBase case x of (Card r s, _, i) | i >= 5 -> return $ Just $ Straight (r, s) _ -> return Nothing where dc = Card Two Clubs collapse (o, s, i) c | rank s == maxBound = (c, c, 1) | succ (rank s) == rank c = (o, c, i + 1) | i >= 5 = (o, c, i) | otherwise = (c, c, 1) flush :: (Monad m) => ClassifiactionT m (Maybe Hand) flush = liftM (foldl collapse Nothing) getSuitGroups where collapse Nothing [Card r s, _, _, _, _] = Just $ Flush (r, s) collapse o _ = o fullHouse :: (Monad m) => ClassifiactionT m (Maybe Hand) fullHouse = do three <- liftM extract threeOfAKind two <- liftM extract pairs case (three, two) of (Just (r, s), Just (r', s')) -> return $ Just $ FullHouse (r, s) (r', s') _ -> return Nothing where extract :: Maybe Hand -> Maybe Scale extract (Just (OnePair (r, s))) = Just (r, s) extract (Just (TwoPair (r, s) _)) = Just (r, s) extract (Just (ThreeOfAKind (r, s))) = Just (r, s) extract _ = Nothing fourOfAKind :: (Monad m) => ClassifiactionT m (Maybe Hand) fourOfAKind = liftM (foldl collapse Nothing) getRankGroups where collapse Nothing [Card r s, _, _, _] = Just $ FourOfAKind (r, s) collapse o _ = o straightFlush :: (Monad m) => ClassifiactionT m (Maybe Hand) straightFlush = liftM (foldl collapse Nothing) getSuitGroups where collapse Nothing cs | length cs >= 5 = do mStraight <- runClassificationT (createClassificationEnv cs) straight case mStraight of Just (Straight (r, s)) -> Just $ StraightFlush (r, s) _ -> Nothing | otherwise = Nothing collapse o _ = o
AndrewRademacher/poker
src/Poker/Classify.hs
mit
5,434
0
16
1,873
1,871
1,002
869
99
5
{- Arch.hs: Architecture-specific information needed for stub generation. Part of Flounder: a message passing IDL for Barrelfish Copyright (c) 2007-2010, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Universit\"atstr. 6, CH-8092 Zurich. Attn: Systems Group. -} module Arch (Arch (..), parse_arch) where import Syntax -- everything the generic LMP backend needs to know about the architecture data Arch = Arch { archname :: String, -- name of the architecture -- architecture-specific sizes wordsize :: Int, -- size of words, in bits ptrsize :: Int, -- size of pointers, in bits sizesize :: Int, -- size of size_t, in bits enum_type :: TypeBuiltin, -- type of an enumeration -- details of the barrelfish LMP channel implementation for this arch lmp_words :: Int, -- payload of an LMP message, in number of words lrpc_words :: Int -- payload of LRPC, in number of words } x86_64 = Arch { archname = "x86_64", wordsize = 64, ptrsize = 64, sizesize = 64, enum_type = Int32, lmp_words = 10, lrpc_words = 4 } x86_32 = Arch { archname = "x86_32", wordsize = 32, ptrsize = 32, sizesize = 32, enum_type = Int32, lmp_words = 4, lrpc_words = 0 } arm = Arch { archname = "arm", wordsize = 32, ptrsize = 32, sizesize = 32, enum_type = Int32, lmp_words = 4, lrpc_words = 0 } -- settings for the xeon phi. TODO: Verify. k1om = Arch { archname = "k1om", wordsize = 64, ptrsize = 64, sizesize = 64, enum_type = Int32, lmp_words = 10, lrpc_words = 4 } all_archs = [x86_64, x86_32, arm, k1om] -- for option parsing: find the matching arch info parse_arch :: String -> Maybe Arch parse_arch n = case [a | a <- all_archs, archname a == n] of [a] -> Just a _ -> Nothing
utsav2601/cmpe295A
tools/flounder/Arch.hs
mit
1,997
0
9
530
360
230
130
47
2
{-# LANGUAGE ScopedTypeVariables #-} module Scratch where -- base import Control.Concurrent (forkIO, killThread, threadDelay) import Control.Monad (void, when) import Data.Int (Int64) -- import GHC.Generics () -- import Data.Proxy (Proxy(Proxy)) -- assert import Control.Exception.Assert (assert) -- async -- import Control.Concurrent.Async () -- exceptions -- import Control.Monad.Catch () -- http-client import Network.HTTP.Client (Manager, defaultManagerSettings, newManager) -- mtl import Control.Monad.Except (ExceptT, runExceptT) -- import Control.Monad.Reader import Control.Monad.Reader (MonadIO, MonadReader, asks, liftIO) import Database.Persist.Postgresql (fromSqlKey, runSqlPool) import Servant ( (:>), (:<|>)((:<|>)), Capture , DeleteNoContent, Get , JSON, Post, Proxy(Proxy) , NoContent(..), ReqBody , ServerT, err404, throwError) -- servant-client import Servant.Client (BaseUrl(BaseUrl), ClientM, Scheme(Http), ServantError, client) import Client import Config import Models import qualified Db import Database.Persist.Types (Entity, entityVal) import Models import Api.Aircraft import Ios io1 :: IO () io1 = do putStrLn "io1" let ac1 = Aircraft "SN1" 4 pool <- makePool Localhost flip runSqlPool pool $ do Db.deleteAllAircraft nAc <- Db.countAircraft liftIO $ putStrLn $ "nAc: " ++ show nAc key1 <- Db.insertAircraft ac1 let id1 = fromSqlKey key1 liftIO $ putStrLn $ "id1: " ++ show id1 nAc <- Db.countAircraft liftIO $ putStrLn $ "nAc: " ++ show nAc (acs :: [Entity Aircraft]) <- Db.allAircrafts let ac2 = entityVal $ head $ acs :: Aircraft when (ac2 /= ac1) $ do liftIO $ putStrLn "error" liftIO $ assert (ac1 == ac2) $ return () io2 :: IO () io2 = do mgr <- newManager defaultManagerSettings port <- readPort let bu = BaseUrl Http "localhost" port "" ac1 = Aircraft "SN1" 2 ac2 = Aircraft "SN2" 4 mapM_ (postAircraftIO mgr bu) [ac1, ac2] eAcs <- getAllAircraftsIO mgr bu case eAcs of Left err -> putStrLn $ "Error: " ++ show err Right acs -> putStrLn $ "acs: " ++ show acs void $ deleteAllIO mgr bu {- io3 :: IO () io3 = do x1 <- async Ios.io1 io2 void $ wait x1 -} io3 :: IO () io3 = do tid <- forkIO Ios.runService threadDelay 100000 io2 killThread tid --getAllAircraftsQuery :: ClientM [Entity Aircraft] --getAllAircraftsQuery = getAllAircrafts {- io2 :: IO () io2 = do manager <- newManager defaultManagerSettings res <- runClientM getAllAircrafts (ClientEnv manager (BaseUrl Http "localhost" 8080 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right acs -> putStrLn $ "acs: " ++ show acs -} {- io2 :: IO () io2 = do manager <- newManager defaultManagerSettings res <- runExceptT (getAllAircrafts manager (BaseUrl Http "localhost" 8080 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right acs -> putStrLn $ "acs: " ++ show acs -} {- data ClientEnv = ClientEnv { manager :: Manager , baseUrl :: BaseUrl } -- | @ClientM@ is the monad in which client functions run. Contains the -- 'Manager' and 'BaseUrl' used for requests in the reader environment. newtype ClientM a = ClientM { runClientM' :: ReaderT ClientEnv (ExceptT ServantError IO) a } deriving ( Functor, Applicative, Monad, MonadIO, Generic , MonadReader ClientEnv , MonadError ServantError , MonadThrow, MonadCatch ) runClientM :: ClientM a -> ClientEnv -> IO (Either ServantError a) runClientM cm env = runExceptT $ (flip runReaderT env) $ runClientM' cm -}
tdox/aircraft-service
src/Scratch.hs
mit
3,989
0
14
1,140
726
391
335
64
2
module Fass.Parser.Value where import Fass.Parser.Color import Fass.Parser.Helper import Control.Applicative hiding ((<|>)) import Text.Parsec import Text.Parsec.String data Units = Pixel | Em | Ex | Vh data ValueTerm = Color RGBA | Size Float String deriving (Show, Eq) term :: Parser ValueTerm term = try (Color <$> colorParser) <|> size -- Parser for property value where there is size required, -- such as in "width: 100px" the parser would match on "100px" size :: Parser ValueTerm size = do n <- floatNumber s <- units return $ Size n s -- Parser for CSS units, for example 10px, 2.3em, etc. units :: Parser String units = try (string "em") <|> try (string "ex") <|> string "px" <|> string "%"
darthdeus/fass
src/Fass/Parser/Value.hs
mit
784
0
10
202
204
112
92
22
1
-- | -- Module: Math.NumberTheory.CurvesTests -- Copyright: (c) 2017 Andrew Lelechenko -- Licence: MIT -- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com> -- Stability: Provisional -- -- Tests for Math.NumberTheory.Curves -- {-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Math.NumberTheory.CurvesTests where import Test.Tasty import Test.Tasty.QuickCheck as QC hiding (Positive, NonNegative, generate, getNonNegative) import GHC.TypeNats.Compat import Math.NumberTheory.Curves.Montgomery import Math.NumberTheory.TestUtils #if __GLASGOW_HASKELL__ < 709 import Data.Word #endif (==>?) :: Maybe a -> (a -> Property) -> Property x ==>? f = case x of Nothing -> discard Just y -> f y isValid :: KnownNat n => Point a24 n -> Property isValid p = counterexample "x is not reduced by modulo" (x >= 0 && x < n) .&&. counterexample "z is not reduced by modulo" (z >= 0 && z < n) where n = pointN p x = pointX p z = pointZ p isValid' :: KnownNat n => Point a24 n -> Bool isValid' p = (x >= 0 && x < n) && (z >= 0 && z < n) where n = pointN p x = pointX p z = pointZ p newPointRangeProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Property newPointRangeProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) = newPoint s n ==>? \case SomePoint p -> isValid p multiplyRangeProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Shrink2 Word -> Property multiplyRangeProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) (Shrink2 k) = newPoint s n ==>? \case SomePoint p -> isValid' p ==> isValid (multiply k p) doubleRangeProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Shrink2 Word -> Property doubleRangeProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) (Shrink2 k) = newPoint s n ==>? \case SomePoint p -> isValid' p ==> isValid' kp ==> isValid (double kp) where kp = multiply k p addRangeProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Shrink2 Word -> Shrink2 Word -> Property addRangeProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) (Shrink2 k) (Shrink2 l) = newPoint s n ==>? \case SomePoint p -> isValid' p ==> isValid' kp ==> isValid' lp ==> isValid' klp ==> isValid (add kp lp klp) where kp = multiply k p lp = multiply l p klp = multiply (k + l) p doubleAndMultiplyProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Shrink2 Word -> Property doubleAndMultiplyProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) (Shrink2 k) = newPoint s n ==>? \case SomePoint p -> k < maxBound `div` 2 ==> double (multiply k p) === multiply (2 * k) p addAndMultiplyProperty :: Shrink2 (Positive Integer) -> Shrink2 (Positive Integer) -> Shrink2 Word -> Shrink2 Word -> Property addAndMultiplyProperty (Shrink2 (Positive s)) (Shrink2 (Positive n)) (Shrink2 k) (Shrink2 l) = newPoint s n ==>? \case SomePoint p -> k < maxBound `div` 3 && l < maxBound `div` 3 && pointX kp /= 0 && gcd n (pointZ kp) == 1 && gcd n (pointZ lp) == 1 && gcd n (pointZ klp) == 1 ==> add kp lp klp === k2lp where kp = multiply k p lp = multiply l p klp = multiply (k + l) p k2lp = multiply (k + 2 * l) p testSuite :: TestTree testSuite = localOption (QuickCheckMaxRatio 100) $ localOption (QuickCheckTests 1000) $ testGroup "Montgomery" [ QC.testProperty "range of newPoint" newPointRangeProperty , QC.testProperty "range of double" doubleRangeProperty , QC.testProperty "range of add" addRangeProperty , QC.testProperty "range of multiply" multiplyRangeProperty , QC.testProperty "double matches multiply" doubleAndMultiplyProperty , QC.testProperty "add matches multiply" addAndMultiplyProperty ]
cfredric/arithmoi
test-suite/Math/NumberTheory/CurvesTests.hs
mit
3,944
0
23
886
1,379
690
689
66
2
module Main where import Prelude import qualified Hasql.Connection import qualified Hasql.Statement import qualified Hasql.Encoders import qualified Hasql.Decoders import qualified Hasql.Session import qualified Main.Statements as Statements main = acquire >>= use where acquire = (,) <$> acquire <*> acquire where acquire = join $ fmap (either (fail . show) return) $ Hasql.Connection.acquire connectionSettings where connectionSettings = Hasql.Connection.settings "localhost" 5432 "postgres" "" "postgres" use (connection1, connection2) = do beginVar <- newEmptyMVar finishVar <- newEmptyMVar forkIO $ do traceM "1: in" putMVar beginVar () session connection1 (Hasql.Session.statement 0.2 Statements.selectSleep) traceM "1: out" void (tryPutMVar finishVar False) forkIO $ do takeMVar beginVar traceM "2: in" session connection2 (Hasql.Session.statement 0.1 Statements.selectSleep) traceM "2: out" void (tryPutMVar finishVar True) bool exitFailure exitSuccess . traceShowId =<< takeMVar finishVar where session connection session = Hasql.Session.run session connection >>= either (fail . show) return
nikita-volkov/hasql
threads-test/Main.hs
mit
1,383
0
15
416
339
169
170
38
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Control.Lens import Control.Monad import qualified Data.ByteString.Char8 as C import Data.IORef import Data.Monoid ((<>)) import System.Exit import System.Mesos.Lens import System.Mesos.Resources import System.Mesos.Scheduler import System.Mesos.Types hiding (commandInfo) import qualified System.Mesos.Types as T -- import Text.Groom cpusPerTask :: Double cpusPerTask = 1 memPerTask :: Double memPerTask = 32 requiredResources :: [Resource] requiredResources = [cpusPerTask ^. re cpus, memPerTask ^. re mem] data TestScheduler = TestScheduler { schedulerRole :: C.ByteString , totalTasks :: Int , tasksLaunched :: IORef Int , tasksFinished :: IORef Int } executorSettings fid = e & name ?~ "Test Executor (Haskell)" where e = executorInfo (ExecutorID "default") fid (T.commandInfo $ ShellCommand "/Users/ian/Code/personal/hs-mesos/dist/build/test-executor/test-executor") requiredResources instance ToScheduler TestScheduler where registered _ _ _ _ = putStrLn "Registered!" resourceOffers s driver offers = do finishedCount <- readIORef $ tasksFinished s if totalTasks s == finishedCount then forM_ offers $ \offer -> declineOffer driver (offer^.id') filters else forM_ offers $ \offer -> do putStrLn ("Starting task on " <> show (offer^.hostname)) status <- launchTasks driver [ offer^.id' ] [ taskInfo "Task foo" (TaskID "foo") (offer^.slaveId) requiredResources (TaskExecutor $ executorSettings $ (offer^.frameworkId)) ] (Filters Nothing) putStrLn "Launched tasks" return () statusUpdate s driver status = do putStrLn $ "Task " <> show (status^.taskId) <> " is in state " <> show (status^.state) print status when ((status^.state) == Finished) $ do count <- atomicModifyIORef' (tasksFinished s) (\x -> let x' = succ x in (x', x')) when (count == totalTasks s) $ void $ do getLine stop driver False errorMessage _ _ message = C.putStrLn message main = do r <- return "*" -- role to use when registering master <- return "127.0.0.1:5050" -- ip:port of master to connect to let info = (frameworkInfo "" "Test Framework (Haskell)") & role ?~ r scheduler <- TestScheduler "master" 5 <$> newIORef 0 <*> newIORef 0 status <- withSchedulerDriver scheduler info master Nothing $ \d -> do status <- run d -- Ensure that the driver process terminates stop d False if status /= Stopped then exitFailure else exitSuccess
jhedev/hs-mesos
test/TestFramework.hs
mit
2,781
0
20
721
769
396
373
63
2
{-# LANGUAGE TemplateHaskell #-} import qualified Graphics.Svg as SVG import Options.Applicative import Paths_juicy_gcode (version) import Data.Version (showVersion) import Development.GitRev (gitHash) import Data.Text (Text, pack, unpack, replace) import qualified Data.Configurator as C import Data.Monoid import Render import GCode data Options = Options { _svgfile :: String , _cfgfile :: Maybe String , _outfile :: Maybe String , _dpi :: Int , _resolution :: Double , _generateBezier :: Bool } options :: Parser Options options = Options <$> argument str ( metavar "SVGFILE" <> help "The SVG file to be converted" ) <*> (optional $ strOption ( long "flavor" <> short 'f' <> metavar "CONFIGFILE" <> help "Configuration of G-Code flavor" )) <*> (optional $ strOption ( long "output" <> short 'o' <> metavar "OUTPUTFILE" <> help "The output G-Code file (default is standard output)" )) <*> (option auto ( long "dpi" <> value 96 <> short 'd' <> metavar "DPI" <> help "Used to determine the size of the SVG when it does not contain any units; dot per inch (default is 96)" )) <*> (option auto ( long "resolution" <> value 0.1 <> short 'r' <> metavar "RESOLUTION" <> help "Shorter paths are replaced by line segments; mm (default is 0.1)" )) <*> (switch ( long "generate-bezier" <> short 'b' <> help "Generate bezier curves (G5) instead of arcs (G2,G3)" )) runWithOptions :: Options -> IO () runWithOptions (Options svgFile mbCfg mbOut dpi resolution generateBezier) = do mbDoc <- SVG.loadSvgFile svgFile flavor <- maybe (return defaultFlavor) readFlavor mbCfg case mbDoc of (Just doc) -> writer (toString flavor dpi $ renderDoc generateBezier dpi resolution doc) Nothing -> putStrLn "juicy-gcode: error during opening the SVG file" where writer = maybe putStrLn (\fn -> writeFile fn) mbOut toLines :: Text -> String toLines t = unpack $ replace (pack ";") (pack "\n") t readFlavor :: FilePath -> IO GCodeFlavor readFlavor cfgFile = do cfg <- C.load [C.Required cfgFile] begin <- C.require cfg (pack "gcode.begin") end <- C.require cfg (pack "gcode.end") toolon <- C.require cfg (pack "gcode.toolon") tooloff <- C.require cfg (pack "gcode.tooloff") return $ GCodeFlavor (toLines begin) (toLines end) (toLines toolon) (toLines tooloff) versionOption :: Parser (a -> a) versionOption = infoOption (concat ["juicy-gcode ", showVersion version, ", git revision ", $(gitHash)]) (long "version" <> short 'v' <> help "Show version") main :: IO () main = execParser opts >>= runWithOptions where opts = info (helper <*> versionOption <*> options) ( fullDesc <> progDesc "Convert SVGFILE to G-Code" <> header "juicy-gcode - The SVG to G-Code converter" )
domoszlai/juicy-gcode
src/Main.hs
mit
3,142
17
13
912
868
435
433
77
2
{-# OPTIONS_GHC -Wall #-} module LogAnalysis where import Log parseMessage :: String -> LogMessage parseMessage = parseMessage' . words parseMessage' :: [String] -> LogMessage parseMessage' pieces | (=='I') label = LogMessage Info timestampOrError (unwords rest) | (=='W') label = LogMessage Warning timestampOrError (unwords rest) | (=='E') label = LogMessage (Error timestampOrError) maybeTimestamp (unwords maybeRest) | otherwise = Unknown (unwords pieces) where label = head . head $ pieces timestampOrError = read . head . tail $ pieces rest = tail . tail $ pieces maybeTimestamp = read . head $ rest maybeRest = tail rest parse :: String -> [LogMessage] parse = map parseMessage . lines insert :: LogMessage -> MessageTree -> MessageTree insert (Unknown _) tree = tree insert msg Leaf = Node Leaf msg Leaf insert newMsg@(LogMessage _ t1 _) (Node left msg@(LogMessage _ t2 _) right) | t1 < t2 = Node (insert newMsg left) msg right | otherwise = Node left msg (insert newMsg right) insert _ tree@(Node _ (Unknown _) _) = tree build :: [LogMessage] -> MessageTree build = foldr insert Leaf inOrder :: MessageTree -> [LogMessage] inOrder tree = inOrder' tree [] inOrder' :: MessageTree -> [LogMessage] -> [LogMessage] inOrder' Leaf list = list inOrder' (Node Leaf msg Leaf) list = msg : list inOrder' (Node Leaf msg right) list = msg : inOrder' right list inOrder' (Node left msg Leaf) list = inOrder' left (msg : list) inOrder' (Node left msg right) list = inOrder' left (msg : inOrder' right list) whatWentWrong :: [LogMessage] -> [String] whatWentWrong messages = map messageFrom (filter (errorGreaterThan 50) sorted) where sorted = inOrder (build messages) errorGreaterThan :: Int -> LogMessage -> Bool errorGreaterThan n (LogMessage (Error z) _ _) = n < z errorGreaterThan _ _ = False messageFrom :: LogMessage -> String messageFrom (LogMessage _ _ msg) = msg messageFrom _ = ""
GrooveStomp/yorgey-haskell-course
week-02/exercise-05.hs
mit
1,948
0
10
370
760
387
373
44
1
module TwinkleStar where import Haskore import AutoComp -- note updaters for mappings fd d n = n d v vol n = n v v = [Volume(80)] lmap f l = line (map f l) v1a = lmap (fd qn) [c 4, c 4, g 4, g 4, a 4, a 4] v1b = lmap vol [g 4 hn] v2a = lmap (fd qn) [f 4, f 4, e 4, e 4, d 4,d 4] v2b = lmap vol [c 4 hn] v3a = lmap (fd qn) [g 4, g 4, f 4, f 4, e 4, e 4] v3b = lmap vol [d 4 hn] v1 = v1a :+: v1b v2 = v2a :+: v2b v3 = v3a :+: v3b mainVoice = v1 :+: v2 :+: v3 :+: v3 :+: v1 :+: v2 twinkleChords :: [[Chord]] twinkleChords = [[(C, "Major"),(C, "Major")],[(F, "Major"),(C, "Major")],[(G, "Major"),(C, "Major")],[(G, "Major"),(C, "Major")],[(C, "Major"),(G, "Major")],[(C, "Major"),(G, "Major")],[(C, "Major"),(G, "Major")],[(C, "Major"),(G, "Major")],[(C, "Major"),(C, "Major")],[(F, "Major"),(C, "Major")],[(G, "Major"),(C, "Major")],[(G, "Major"),(C, "Major")]] twinkleBasic = (Instr "piano" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "piano" (Tempo 3 (Phrase [Dyn SF] (autoComp basic (C,"Ionian") twinkleChords)))) twinkleCalypso = (Instr "piano" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "piano" (Tempo 3 (Phrase [Dyn SF] (autoComp calypso (C,"Ionian") twinkleChords)))) twinkleBoogie = (Instr "piano" (Tempo 3 (Phrase [Dyn SF] mainVoice))) :=: (Instr "piano" (Tempo 3 (Phrase [Dyn SF] (autoComp boogie (C,"Ionian") twinkleChords))))
Zolomon/edan40-functional-music
twinkle.hs
mit
1,417
0
14
299
857
481
376
22
1
----------------------------------------------------------------------------- -- -- Module : SamplingOptions -- Copyright : -- License : GPL v3 -- -- Maintainer : Tobias Fuchs -- Stability : unstable -- Portability : Win32, POSIX -- -- | -- ----------------------------------------------------------------------------- {-# OPTIONS -O2 -Wall #-} module Drool.UI.SignalBufferOptions ( initComponent, updateSettings ) where import Data.IORef import qualified Graphics.UI.Gtk as Gtk import qualified Graphics.UI.Gtk.Builder as GtkBuilder import Graphics.Rendering.OpenGL import qualified Drool.Utils.SigGen as SigGen import qualified Drool.ApplicationContext as AC ( ContextSettings(..) ) import qualified Drool.ContextObjects as AC -- Initializes GUI component for view options. -- Expects a GtkBuilder instance. initComponent :: GtkBuilder.Builder -> IORef AC.ContextSettings -> IORef AC.ContextObjects-> IO Bool initComponent gtkBuilder contextSettings contextObjects = do putStrLn "Initializing SignalBufferOptions component" defaultSettings <- readIORef contextSettings defaultObjects <- readIORef contextObjects let defaultSigGen = AC.signalGenerator defaultObjects adjSignalPushFreq <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjSignalPushFreq" _ <- Gtk.onValueChanged adjSignalPushFreq $ do val <- Gtk.adjustmentGetValue adjSignalPushFreq settings <- readIORef contextSettings contextSettings $=! settings { AC.signalPushFrequency = round val } adjRenderingFreq <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjRenderingFreq" _ <- Gtk.onValueChanged adjRenderingFreq $ do val <- Gtk.adjustmentGetValue adjRenderingFreq settings <- readIORef contextSettings contextSettings $=! settings { AC.renderingFrequency = round val } adjBufferSize <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjBufferSize" _ <- Gtk.onValueChanged adjBufferSize $ do val <- Gtk.adjustmentGetValue adjBufferSize settings <- readIORef contextSettings contextSettings $=! settings { AC.signalBufferSize = round val } adjBufferSamples <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjBufferSamples" Gtk.adjustmentSetValue adjBufferSamples (fromIntegral $ SigGen.numSamples defaultSigGen) _ <- Gtk.onValueChanged adjBufferSamples $ do val <- Gtk.adjustmentGetValue adjBufferSamples objects <- readIORef contextObjects let currentSigGen = AC.signalGenerator objects let siggen = currentSigGen { SigGen.numSamples = round val } contextObjects $=! objects { AC.signalGenerator = siggen } _ <- updateSettings gtkBuilder defaultSettings return True updateSettings :: GtkBuilder.Builder -> AC.ContextSettings -> IO Bool updateSettings gtkBuilder settings = do adjSignalPushFreq <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjSignalPushFreq" Gtk.adjustmentSetValue adjSignalPushFreq (fromIntegral $ AC.signalPushFrequency settings) adjBufferSize <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjBufferSize" Gtk.adjustmentSetValue adjBufferSize (fromIntegral $ AC.signalBufferSize settings) adjRenderingFreq <- GtkBuilder.builderGetObject gtkBuilder Gtk.castToAdjustment "adjRenderingFreq" Gtk.adjustmentSetValue adjRenderingFreq (fromIntegral $ AC.renderingFrequency settings) return True
fuchsto/drool
src/Drool/UI/SignalBufferOptions.hs
mit
3,412
0
16
461
712
350
362
50
1
{-# OPTIONS -w -O0 #-} {- | Module : RDF/ATC_RDF.der.hs Description : generated Typeable, ShATermConvertible instances Copyright : (c) DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable(overlapping Typeable instances) Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible for the type(s): 'RDF.AS.TurtleDocument' 'RDF.AS.Statement' 'RDF.AS.Prefix' 'RDF.AS.Base' 'RDF.AS.Triples' 'RDF.AS.Subject' 'RDF.AS.Predicate' 'RDF.AS.Object' 'RDF.AS.PredicateObjectList' 'RDF.AS.RDFLiteral' 'RDF.AS.Term' 'RDF.AS.Axiom' 'RDF.AS.RDFEntityType' 'RDF.AS.RDFEntity' 'OWL2.AS.IRIType' 'OWL2.AS.QName' 'OWL2.AS.EquivOrDisjoint' 'OWL2.AS.DomainOrRange' 'OWL2.AS.SameOrDifferent' 'OWL2.AS.Relation' 'OWL2.AS.Character' 'OWL2.AS.PositiveOrNegative' 'OWL2.AS.QuantifierType' 'OWL2.AS.DatatypeCat' 'OWL2.AS.CardinalityType' 'OWL2.AS.Cardinality' 'OWL2.AS.JunctionType' 'OWL2.AS.Entity' 'OWL2.AS.EntityType' 'OWL2.AS.TypedOrUntyped' 'OWL2.AS.Literal' 'OWL2.AS.NNInt' 'OWL2.AS.IntLit' 'OWL2.AS.DecLit' 'OWL2.AS.FloatLit' 'OWL2.AS.ObjectPropertyExpression' 'OWL2.AS.DataRange' 'OWL2.AS.ClassExpression' 'OWL2.AS.Annotation' 'OWL2.AS.AnnotationValue' 'RDF.Symbols.SymbItems' 'RDF.Symbols.SymbMapItems' 'RDF.Symbols.RawSymb' 'RDF.Sign.Sign' 'RDF.Morphism.RDFMorphism' -} {- Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!! dependency files: RDF/AS.hs OWL2/AS.hs RDF/Symbols.hs RDF/Sign.hs RDF/Morphism.hs RDF/Sublogic.hs -} module RDF.ATC_RDF () where import ATC.Result import ATerm.Lib import Common.DocUtils import Common.Id import Common.Result import Data.Char (intToDigit) import Data.List import Data.Maybe import Data.Typeable import OWL2.AS import OWL2.ColonKeywords import OWL2.Keywords import RDF.AS import RDF.Function import RDF.Morphism import RDF.Print () import RDF.Sign import RDF.Sublogic import RDF.Symbols import qualified Data.Map as Map import qualified Data.Set as Set {-! for RDF.AS.TurtleDocument derive : Typeable !-} {-! for RDF.AS.Statement derive : Typeable !-} {-! for RDF.AS.Prefix derive : Typeable !-} {-! for RDF.AS.Base derive : Typeable !-} {-! for RDF.AS.Triples derive : Typeable !-} {-! for RDF.AS.Subject derive : Typeable !-} {-! for RDF.AS.Predicate derive : Typeable !-} {-! for RDF.AS.Object derive : Typeable !-} {-! for RDF.AS.PredicateObjectList derive : Typeable !-} {-! for RDF.AS.RDFLiteral derive : Typeable !-} {-! for RDF.AS.Term derive : Typeable !-} {-! for RDF.AS.Axiom derive : Typeable !-} {-! for RDF.AS.RDFEntityType derive : Typeable !-} {-! for RDF.AS.RDFEntity derive : Typeable !-} {-! for OWL2.AS.IRIType derive : Typeable !-} {-! for OWL2.AS.QName derive : Typeable !-} {-! for OWL2.AS.EquivOrDisjoint derive : Typeable !-} {-! for OWL2.AS.DomainOrRange derive : Typeable !-} {-! for OWL2.AS.SameOrDifferent derive : Typeable !-} {-! for OWL2.AS.Relation derive : Typeable !-} {-! for OWL2.AS.Character derive : Typeable !-} {-! for OWL2.AS.PositiveOrNegative derive : Typeable !-} {-! for OWL2.AS.QuantifierType derive : Typeable !-} {-! for OWL2.AS.DatatypeCat derive : Typeable !-} {-! for OWL2.AS.CardinalityType derive : Typeable !-} {-! for OWL2.AS.Cardinality derive : Typeable !-} {-! for OWL2.AS.JunctionType derive : Typeable !-} {-! for OWL2.AS.Entity derive : Typeable !-} {-! for OWL2.AS.EntityType derive : Typeable !-} {-! for OWL2.AS.TypedOrUntyped derive : Typeable !-} {-! for OWL2.AS.Literal derive : Typeable !-} {-! for OWL2.AS.NNInt derive : Typeable !-} {-! for OWL2.AS.IntLit derive : Typeable !-} {-! for OWL2.AS.DecLit derive : Typeable !-} {-! for OWL2.AS.FloatLit derive : Typeable !-} {-! for OWL2.AS.ObjectPropertyExpression derive : Typeable !-} {-! for OWL2.AS.DataRange derive : Typeable !-} {-! for OWL2.AS.ClassExpression derive : Typeable !-} {-! for OWL2.AS.Annotation derive : Typeable !-} {-! for OWL2.AS.AnnotationValue derive : Typeable !-} {-! for RDF.Symbols.SymbItems derive : Typeable !-} {-! for RDF.Symbols.SymbMapItems derive : Typeable !-} {-! for RDF.Symbols.RawSymb derive : Typeable !-} {-! for RDF.Sign.Sign derive : Typeable !-} {-! for RDF.Morphism.RDFMorphism derive : Typeable !-} {-! for RDF.AS.TurtleDocument derive : ShATermConvertible !-} {-! for RDF.AS.Statement derive : ShATermConvertible !-} {-! for RDF.AS.Prefix derive : ShATermConvertible !-} {-! for RDF.AS.Base derive : ShATermConvertible !-} {-! for RDF.AS.Triples derive : ShATermConvertible !-} {-! for RDF.AS.Subject derive : ShATermConvertible !-} {-! for RDF.AS.Predicate derive : ShATermConvertible !-} {-! for RDF.AS.Object derive : ShATermConvertible !-} {-! for RDF.AS.PredicateObjectList derive : ShATermConvertible !-} {-! for RDF.AS.RDFLiteral derive : ShATermConvertible !-} {-! for RDF.AS.Term derive : ShATermConvertible !-} {-! for RDF.AS.Axiom derive : ShATermConvertible !-} {-! for RDF.AS.RDFEntityType derive : ShATermConvertible !-} {-! for RDF.AS.RDFEntity derive : ShATermConvertible !-} {-! for OWL2.AS.IRIType derive : ShATermConvertible !-} {-! for OWL2.AS.QName derive : ShATermConvertible !-} {-! for OWL2.AS.EquivOrDisjoint derive : ShATermConvertible !-} {-! for OWL2.AS.DomainOrRange derive : ShATermConvertible !-} {-! for OWL2.AS.SameOrDifferent derive : ShATermConvertible !-} {-! for OWL2.AS.Relation derive : ShATermConvertible !-} {-! for OWL2.AS.Character derive : ShATermConvertible !-} {-! for OWL2.AS.PositiveOrNegative derive : ShATermConvertible !-} {-! for OWL2.AS.QuantifierType derive : ShATermConvertible !-} {-! for OWL2.AS.DatatypeCat derive : ShATermConvertible !-} {-! for OWL2.AS.CardinalityType derive : ShATermConvertible !-} {-! for OWL2.AS.Cardinality derive : ShATermConvertible !-} {-! for OWL2.AS.JunctionType derive : ShATermConvertible !-} {-! for OWL2.AS.Entity derive : ShATermConvertible !-} {-! for OWL2.AS.EntityType derive : ShATermConvertible !-} {-! for OWL2.AS.TypedOrUntyped derive : ShATermConvertible !-} {-! for OWL2.AS.Literal derive : ShATermConvertible !-} {-! for OWL2.AS.NNInt derive : ShATermConvertible !-} {-! for OWL2.AS.IntLit derive : ShATermConvertible !-} {-! for OWL2.AS.DecLit derive : ShATermConvertible !-} {-! for OWL2.AS.FloatLit derive : ShATermConvertible !-} {-! for OWL2.AS.ObjectPropertyExpression derive : ShATermConvertible !-} {-! for OWL2.AS.DataRange derive : ShATermConvertible !-} {-! for OWL2.AS.ClassExpression derive : ShATermConvertible !-} {-! for OWL2.AS.Annotation derive : ShATermConvertible !-} {-! for OWL2.AS.AnnotationValue derive : ShATermConvertible !-} {-! for RDF.Symbols.SymbItems derive : ShATermConvertible !-} {-! for RDF.Symbols.SymbMapItems derive : ShATermConvertible !-} {-! for RDF.Symbols.RawSymb derive : ShATermConvertible !-} {-! for RDF.Sign.Sign derive : ShATermConvertible !-} {-! for RDF.Morphism.RDFMorphism derive : ShATermConvertible !-}
nevrenato/Hets_Fork
RDF/ATC_RDF.der.hs
gpl-2.0
6,922
0
5
835
221
173
48
23
0
import Data.Bits import Data.List import Data.Char nimSum :: [Integer] -> Integer nimSum = foldl' xor 0 hasMove :: [Integer] -> Bool hasMove = not . all (== 0) isValidMove :: [Integer] -> (Integer, Integer) -> Bool isValidMove xs (i, a) = i >= 0 && i < genericLength xs && a > 0 && a <= genericIndex xs i move :: [Integer] -> (Integer, Integer) move xs = case [(i,x) | (i,x) <- zip [0..] xs, s `xor` x < x] of [] -> arbitraryMove (i,x) : _ -> (i, x - (s `xor` x)) where s = nimSum xs arbitraryMove = head [(i,1) | (i,x) <- zip [0..] xs, x > 0] applyMove :: [Integer] -> (Integer, Integer) -> [Integer] applyMove xs (i,a) = case genericSplitAt i xs of (xs1, x:xs2) -> xs1 ++ [x - a] ++ xs2 readMove :: [Integer] -> IO (Integer,Integer) readMove xs = do putStr "Human: " s <- getLine case words s of [a,b] | all isDigit a && all isDigit b && isValidMove xs (read a, read b) -> return (read a, read b) _ -> putStrLn "Invalid move. Input format is \"POSITION AMOUNT\", e.g. \"0 2\"." >> readMove xs readConfiguration :: IO [Integer] readConfiguration = do s <- getLine let c = words s if all (all isDigit) c then return (map read c) else putStrLn "Invalid configuration. Input format is \"1 2 3\"" >> readConfiguration data Player = Human | Computer deriving (Show, Eq) other :: Player -> Player other Human = Computer other Computer = Human printMove :: (Integer,Integer) -> IO () printMove (a,b) = putStrLn (show a ++ " " ++ show b) printConfiguration :: [Integer] -> IO () printConfiguration = putStrLn . intercalate " " . map show playNim :: Player -> [Integer] -> IO () playNim p xs | not (hasMove xs) = putStrLn $ show (other p) ++ " wins." playNim p xs = do m <- if p == Human then readMove xs else let m = move xs in putStr "Computer: " >> printMove m >> return m let xs' = applyMove xs m putStr "Game state: " printConfiguration xs' playNim (other p) xs' main = do putStrLn "Enter initial configuration" c <- readConfiguration putStr "Game state: " printConfiguration c playNim Computer c
3of8/haskell_playground
nim/Nim.hs
gpl-2.0
2,154
1
16
540
948
481
467
54
2
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances #-} module Algebraic.Relation where import Algebraic.Relation.Restriction import PL.Struktur ( Predicate (..) ) import Algebraic2.Class import Algebraic2.Instance as AI import Condition import qualified Autolib.Relation as R import qualified Autolib.TES.Binu as B import Autolib.ToDoc import Autolib.Choose import Autolib.Reader import Autolib.Size import Autolib.Set import Autolib.FiniteMap import qualified Autolib.Reporter.Set import Data.Typeable import Data.Ix instance ( Ord a, ToDoc a ) => Condition Restriction ( Re a ) where condition r s = case r of Size_Range rng -> assert ( inRange rng $ size s ) $ text "Größe im erlaubten Bereich" <+> toDoc rng data Algebraic_Relation = Algebraic_Relation deriving ( Read, Show, Typeable ) --------------------------------------------------------------------------- data Re a = Re { unRe :: R.Type a a } deriving Typeable instance Ord a => Size ( Re a ) where size ( Re r ) = length $ R.pairs r toPred :: Ord a => Re a -> Predicate a toPred (Re r) = Predicate $ mkSet $ do (x,y) <- R.pairs r return [x,y] fromPred :: Ord a => Predicate a -> Re a fromPred ( Predicate p ) = Re $ R.make $ do [x,y] <- setToList p return (x,y) instance (Ord a,ToDoc a) => ToDoc ( Re a ) where toDoc = toDoc . toPred instance (Ord a,Reader a) => Reader ( Re a) where reader = do p <- reader ; return $ fromPred p --------------------------------------------------------------------------- instance (ToDoc a, Ord a ) => Ops ( Re a ) where bops = B.Binu { B.nullary = [] , B.unary = [ Op { name = "inv", arity = 1 , precedence = Nothing, assoc = AssocNone , inter = lift1R $ R.inverse } , Op { name = "tcl", arity = 1 , precedence = Nothing, assoc = AssocNone , inter = lift1R $ R.trans } , Op { name = "rcl", arity = 1 , precedence = Nothing, assoc = AssocNone , inter = lift1R $ R.reflex } ] , B.binary = [ Op { name = "+", arity = 2 , precedence = Just 5, assoc = AssocLeft , inter = lift2R $ R.plus } , Op { name = "-", arity = 2 , precedence = Just 5, assoc = AssocLeft , inter = lift2R $ R.difference } , Op { name = "&", arity = 2 , precedence = Just 6, assoc = AssocLeft , inter = lift2R $ R.intersection } , Op { name = "*", arity = 2 , precedence = Just 6, assoc = AssocLeft , inter = lift2R $ R.times } ] } lift1R fun xs = fmap Re $ lift1 fun $ map unRe xs lift2R fun xs = fmap Re $ lift2 fun $ map unRe xs --------------------------------------------------------------------------- instance Algebraic Algebraic_Relation ( Set Integer ) ( Re Integer ) where introduce tag con = do inform $ vcat [ text "Die folgende Aufgabe bezieht sich auf Relationen" , text "über dem Grundbereich" <+> toDoc con ] -- evaluate :: tag -> Exp a -> Reporter a evaluateC tag con bel0 exp = do let bel = mapFM ( \ k ( Re v ) -> Re v { R.source = con, R.target = con } ) $ bel0 v <- tfoldB bel inter exp inform $ vcat [ text "Der Wert Ihres Terms ist die Relation" , nest 4 $ toDoc v ] return v -- equivalent :: tag -> a -> a -> Reporter Bool equivalent tag a b = do inform $ text "stimmen die Relationen überein?" Autolib.Reporter.Set.eq ( text "Aufgabenstellung", mkSet $ R.pairs $ unRe a ) ( text "Einsendung", mkSet $ R.pairs $ unRe b ) return True -- some_formula :: tag -> Algebraic.Instance.Type a -> Exp a some_formula tag i = read "R * S + S" default_context tag = mkSet [ 1 .. 10 ] -- default_instance :: tag -> Algebraic.Instance.Type a default_instance tag = AI.Make { target = read "{(1,4)}" , context = default_context tag , description = Nothing , operators = default_operators tag , predefined = listToFM [ (read "R", read "{(1,2),(3,4)}" ) , (read "S", read "{(2,3)}" ) ] , max_size = 7 } default_operators tag = bops
Erdwolf/autotool-bonn
src/Algebraic/Relation.hs
gpl-2.0
4,193
82
17
1,154
1,150
653
497
100
1
{-# LANGUAGE DeriveDataTypeable #-} ------------------------------------------------------------------------------- -- Module : Util.CmdOpts -- Desc : Utilities for the command line options -- Copyright : (c) 2016 Marcelo Sousa ------------------------------------------------------------------------------- module Util.CmdOpts where import System.Console.CmdArgs import System.FilePath.Posix import Util.Generic -- Command Line Options Strings _program, _summary :: String _program = "poet" _summary = unlines ["POET - v0.2.2","Partial Order Exploration Tools" ,"Exploration methods for concurrent C programs based on event structures" ,"Copyright 2015-17 @ Marcelo Sousa"] _help = "The input files of poet are C files written in a restricted " ++ "subset of the C language." ++ "For more info, check the documentation!" _helpFE = unlines ["poet frontend receives a concurrent C program in a restricted " ++ "subset of the language and performs a series of transformations " ++ "to simplify the analysis." , "Example: poet frontend file.c"] _helpInter = unlines ["poet interpret receives a concurrent C program in a restricted " ++ "subset of the language and runs the interpreter on the " ++ "corresponding model of computation." , "Example: poet interpret -i=file.c"] _helpExec = unlines ["poet execute receives a concurrent C program in a restricted " ++ "subset of the language and executes one run of the corresponding " ++ "model of computation." , "Example: poet execute -i=file.c -s=int (optional)"] _helpExplore = unlines ["poet explore receives a concurrent C program in a restricted " ++ "subset of the language and explores the state space of the " ++ "corresponding model of computation using a partial order " ++ "representation." , "Example: poet explore -i=file.c"] _helpStid = unlines ["poet stid receives a concurrent C program as an LLVM .ll file " ++ "and explores the state space of this program using the STID FE." , "Example: poet stid -i=file.c"] _helpDebug = "poet debug receives a concurrent C program in a restricted " ++ " subset of the language and explores the state space and " ++ "explores the unfolding. At the end, it prints the LPES." _helpTest = "poet test runs the explore mode over the set of examples in " ++ "Test/Examples." _helpAi = "poet ai -i=file.c runs the abstract interpreter for intervals" instance Default Analysis where def = Concrete data Option = Frontend {inp :: FilePath} | Interpret {inp :: FilePath, dom :: Analysis, mode :: Int, seed :: Int, stf :: Int, cut :: Int, wid :: Int} | Explore {inp :: FilePath, dom :: Analysis, stf :: Int, cut :: Int, wid :: Int} | Prime {inp :: FilePath, dom :: Analysis, stf :: Int, cut :: Int} | Stid {inp :: FilePath, stf :: Int, cut :: Int} | Test deriving (Show, Data, Typeable, Eq) -- | Mode options frontend_mode, interpret_mode :: Option frontend_mode = Frontend { inp = def &= args } &= help _helpFE interpret_mode = Interpret { inp = def , dom = def , mode = def &= help "mode of the interpreter (0=Executes [default], 1=Step By Step)" , seed = def &= help "seed for the scheduler" , stf = def &= help "stateful mode (0=False [default], 1=True)" , cut = def &= help "cut mode (0=False [default], 1=True)" , wid = 10 &= help "widening" } &= help _helpInter explore_mode = Explore { inp = def , dom = def , stf = def &= help "stf mode (0=False [default], 1=True)" , cut = def &= help "cut mode (0=False [default], 1=True)" , wid = 10 &= help "widening" } &= help _helpExplore prime_mode = Prime { inp = def , dom = def , stf = def &= help "stf mode (0=False [default], 1=True)" , cut = def &= help "cut mode (0=False [default], 1=True)" } &= help _helpExplore stid_mode = Stid { inp = def , stf = def &= help "stf mode (0=False [default], 1=True)" , cut = def &= help "cut mode (0=False [default], 1=True)" } &= help _helpStid test_mode = Test {} &= help _helpTest prog_modes :: Mode (CmdArgs Option) prog_modes = cmdArgsMode $ modes [ frontend_mode, interpret_mode , explore_mode, test_mode , prime_mode, stid_mode ] &= help _help &= program _program &= summary _summary
marcelosousa/poet
src/Util/CmdOpts.hs
gpl-2.0
4,532
0
10
1,141
764
442
322
100
1
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <!-- title --> <title>jtreg - Command Line Help</title> <!-- maps --> <maps> <homeID>usage</homeID> <mapref location="default/map.xml"/> </maps> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data>default/JavaHelpSearch</data> </view> </helpset>
otmarjr/jtreg-fork
src/share/doc/javatest/regtest/usage/usage.hs
gpl-2.0
556
42
28
96
208
107
101
-1
-1
-- -- This file aims to provide (the essential subset of) the same functionality -- that vim plugins ctrlp and command-t provide. -- -- Setup: -- -- Add something like this to your config: -- -- (ctrlCh 'p' ?>>! fuzzyFile) -- module FuzzyFile ( fuzzyFile ) where import Control.Monad import Control.Monad.Base import Control.Monad.State import Data.List (isInfixOf, isSuffixOf) import Data.Monoid import qualified Data.Map.Strict as M import qualified Data.Text as T import System.Directory (doesDirectoryExist, getDirectoryContents) import System.FilePath ((</>)) import Yi import Yi.Types import Fuzzy fuzzyFile :: YiM () fuzzyFile = genericFuzzy =<< getItems fileItem :: FilePath -> FuzzyItem fileItem filename = FuzzyItem { fiAction = void (editFile filename) , fiToText = T.pack ("File " <> filename) } bufferItem :: BufferId -> FuzzyItem bufferItem bufId = FuzzyItem { fiAction = withEditor $ do bufs <- gets (M.assocs . buffers) case filter ((== bufId) . ident . attributes . snd) bufs of [] -> error ("Couldn't find buffer" <> show bufId) (bufRef, _) : _ -> switchToBufferE bufRef , fiToText = T.pack "Buffer " <> case bufId of MemBuffer x -> x FileBuffer x -> T.pack x } getItems :: YiM [FuzzyItem] getItems = do fileList <- fmap (fmap fileItem) (liftBase (getRecursiveContents ".")) bufList <- fmap (fmap (bufferItem . ident . attributes)) (withEditor (gets (M.elems . buffers))) return (fileList <> bufList) -- shamelessly stolen from Chapter 9 of Real World Haskell -- takes about 3 seconds to traverse linux kernel, which is not too outrageous -- TODO: check if it works at all with cyclic links -- TODO: perform in background, limit file count or directory depth -- TODO: ignore what is in .gitignore getRecursiveContents :: FilePath -> IO [FilePath] getRecursiveContents topdir = do names <- getDirectoryContents topdir let properNames = filter predicate names predicate fileName = and [ fileName `notElem` [ "." , ".." , ".git" , ".svn" , "node_modules" , "_build" , ".build" , "Packages" , ".stack-work" , ".tox" , ".stack-work" , ".build" , ".compiled" , "dist-newstyle" ] , not (".hi" `isSuffixOf` fileName) , not ("-boot" `isSuffixOf` fileName) , not (".dyn_hi" `isSuffixOf` fileName) , not (".dyn_o" `isSuffixOf` fileName) , not (".p_hi" `isSuffixOf` fileName) , not (".p_o" `isSuffixOf` fileName) , not (".o" `isSuffixOf` fileName) , not (".swp" `isSuffixOf` fileName) , not (".beam" `isSuffixOf` fileName) , not (".pyc" `isSuffixOf` fileName) , not ("~" `isSuffixOf` fileName) , not ("dist/build/" `isInfixOf` fileName) , not (".eunit" `isInfixOf` fileName) ] paths <- forM properNames $ \name -> do let path = topdir </> name isDirectory <- doesDirectoryExist path if isDirectory then getRecursiveContents path else return [path] return (concat paths)
ethercrow/yi-config
modules/FuzzyFile.hs
gpl-2.0
3,452
0
16
1,096
831
464
367
81
3
module Hkl.Types ( Beamline(..) , Mode(..) , Engine(..) , Factory(..) , Geometry(..) , Lattice(..) , Sample(..) , Source(..) , Trajectory -- factory , factoryFromString -- hdf5 , H5Path , ExtendDims(..) , DataItem(..) , module X ) where import Hkl.Types.Parameter as X import Data.Vector.Storable (Vector) import Numeric.Units.Dimensional.Prelude (Length, Angle) -- | Beamline data Beamline = Diffabs | Sixs instance Show Beamline where show Diffabs = "diffabs" show Sixs = "sixs" -- | Engine data Mode = Mode String -- ^ name [Parameter] -- ^ parameters of the @Mode@ deriving (Show) data Engine = Engine String -- ^ name [Parameter] -- ^ pseudo axes values of the @Engine@ Mode -- ^ current Mode deriving (Show) -- | Factory data Factory = K6c | Uhv | MedH | MedV instance Show Factory where show K6c = "K6C" show Uhv = "ZAXIS" show MedH = "todo" show MedV = "todo" factoryFromString :: String -> Factory factoryFromString s | s == "K6C" = K6c | s == "ZAXIS" = Uhv | s == "todo" = MedH | s == "todo" = MedV | otherwise = error $ "unknown diffractometer type:" ++ s -- | Geometry data Geometry = Geometry Factory -- ^ the type of diffractometer Source -- ^ source (Vector Double) -- ^ axes position (Maybe [Parameter]) -- ^ axes configuration deriving (Show) -- | Lattice data Lattice = Cubic -- ^ a = b = c, alpha = beta = gamma = 90 (Length Double) -- a | Tetragonal -- ^ a = b != c, alpha = beta = gamma = 90 (Length Double) -- ^ a, b (Length Double) -- ^ c | Orthorhombic -- ^ a != b != c, alpha = beta = gamma = 90 (Length Double) -- ^ a (Length Double) -- ^ b (Length Double) -- ^ c | Rhombohedral -- ^ a = b = c, alpha = beta = gamma != 90 (Length Double) -- ^ a, b, c (Angle Double) -- ^ alpha, beta, gamma | Hexagonal -- ^ a = b != c, alpha = beta = 90, gamma = 120 (Length Double) -- ^ a, b (Length Double) -- ^ c | Monoclinic -- ^ a != b != c, alpha = gamma = 90, beta != 90 (Length Double) -- ^ a (Length Double) -- ^ b (Length Double) -- ^ c (Angle Double) -- ^ beta | Triclinic -- ^ a != b != c, alpha != beta != gamma != 90 (Length Double) -- ^ a (Length Double) -- ^ b (Length Double) -- ^ c (Angle Double) -- ^ alpha (Angle Double) -- ^ beta (Angle Double) -- ^ gamma deriving (Show) -- | Sample data Sample = Sample String -- ^ name of the sample Lattice -- ^ the lattice of the sample Parameter -- ^ ux Parameter -- ^ uy Parameter -- ^ uz deriving (Show) -- | Source data Source = Source (Length Double) -- ^ wavelength deriving (Show) -- | Trajectory type Trajectory = [[Double]] -- | Hdf5 type H5Path = String data ExtendDims = ExtendDims | StrictDims deriving (Show) data DataItem = DataItem H5Path ExtendDims deriving (Show)
picca/hkl
contrib/haskell/src/Hkl/Types.hs
gpl-3.0
3,210
0
9
1,086
723
429
294
96
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedLists #-} module Math ( VecN ,Vec2(..) ,vLengthSq ,vLength ,normalize ,uncheckedNormalize ,vMap, vZip, vFold ,dot , (*|), (|*) , (|+|), (|-|), (-|) , toTuple , rotateToUnit , degToRad, radToDeg , angleBetween ) where import ClassyPrelude import Safe(fromJustDef) import Foreign class VecN v where vMap :: (Float -> Float) -> v -> v vZip :: (Float -> Float -> Float) -> v -> v -> v vFold :: (Float -> Float -> Float) -> v -> Float {-# INLINE (*|) #-} infixl 7 *| (*|) :: VecN v => Float -> v -> v s *| v = vMap (*s) v {-# INLINE (|*) #-} infixl 7 |* (|*) :: VecN v => v -> Float -> v v |* s = s *| v {-# INLINE (|+|) #-} infixl 6 |+| (|+|) :: VecN v => v -> v -> v (|+|) = vZip (+) {-# INLINE (|-|) #-} infixl 6 |-| (|-|) :: VecN v => v -> v -> v (|-|) = vZip (-) {-# INLINE (-|) #-} (-|) :: VecN v => v -> v (-|) = vMap negate {-# INLINE vLengthSq #-} vLengthSq :: VecN v => v -> Float vLengthSq = vFold (+) . vMap (\x -> x*x) {-# INLINE vLength #-} vLength :: VecN v => v -> Float vLength = sqrt . vLengthSq {-# INLINE normalize #-} normalize :: VecN v => v -> Maybe v normalize v = if len==0 then Nothing else Just $ (1/len) *| v where len = vLength v {-# INLINE uncheckedNormalize #-} uncheckedNormalize :: VecN v => v -> v uncheckedNormalize v = (1/vLength v) *| v {-# INLINE dot #-} dot :: VecN v => v -> v -> Float dot a b = vFold (+) $ vZip (*) a b toTuple :: Vec2 -> (Float, Float) toTuple (Vec2 a b) = (a,b) rotateToUnit :: Float -> Vec2 rotateToUnit r = Vec2 (cos r) (-sin r) data Vec2 = Vec2 !Float !Float deriving (Show, Eq) instance VecN Vec2 where {-# SPECIALIZE instance VecN Vec2 #-} vMap f (Vec2 x y) = Vec2 (f x) (f y) vZip f (Vec2 x0 y0) (Vec2 x1 y1) = Vec2 (f x0 x1) (f y0 y1) vFold f (Vec2 x y) = f x y radToDeg x = x * 180 / pi degToRad x = x * pi / 180 angleBetween :: Vec2 -> Vec2 -> Float angleBetween (Vec2 x0 y0) (Vec2 x1 y1) = atan2 (x1-x0) (y1-y0)
Marthog/ld35
src/Math.hs
gpl-3.0
2,064
1
10
545
903
498
405
79
2
module Language where import Control.Applicative import Control.Monad (liftM, ap) import Data.Char (isAlpha, isDigit, isLetter, isSpace) data Expr a = EVar Name | ENum Int | EConstr Int Int | EAp (Expr a) (Expr a) | ELet IsRec [(a,Expr a)] (Expr a) | ECase (Expr a) [Alter a] | ELam [a] (Expr a) deriving (Show) type CoreExpr = Expr Name type Name = String type IsRec = Bool recursive, nonRecursive :: IsRec recursive = True nonRecursive = False binderOf :: [(a, b)] -> [a] binderOf defns = [name | (name,rhs) <- defns] rhssOf :: [(a, b)] -> [b] rhssOf defns = [rhs | (name,rhs) <- defns] type Alter a = (Int, [a], Expr a) type CoreAlt = Alter Name isAtomicExpr :: Expr a -> Bool isAtomicExpr (EVar v) = True isAtomicExpr (ENum n) = True isAtomicExpr e = False type Program a = [ScDefn a] type CoreProgram = Program Name type ScDefn a = (Name, [a], Expr a) type CoreScDefn = ScDefn Name preludeDefs :: CoreProgram preludeDefs = [("I",["x"],EVar "x") ,("K",["x","y"],EVar "x") ,("K1",["x","y"],EVar "y") ,("S" ,["f","g","x"] ,EAp (EAp (EVar "f") (EVar "x")) (EAp (EVar "g") (EVar "x"))) ,("compose" ,["f","g","x"] ,EAp (EVar "f") (EAp (EVar "g") (EVar "x"))) ,("twice" ,["f"] ,EAp (EAp (EVar "compose") (EVar "f")) (EVar "f"))] {- Pretty print -} data Iseq = INil | IStr String | IAppend Iseq Iseq | IIndent Iseq | INewline deriving (Show) iNil :: Iseq iNil = INil iStr :: String -> Iseq iStr str = IStr str iAppend :: Iseq -> Iseq -> Iseq iAppend seq1 seq2 = IAppend seq1 seq2 iNewline :: Iseq iNewline = INewline iIndent :: Iseq -> Iseq iIndent s = IIndent s space :: Int -> String space n = take n $ repeat ' ' flatten :: Int -> [(Iseq, Int)] -> String flatten _ [] = "" flatten col ((INil, _):seqs) = flatten col seqs flatten col ((IStr s, _) : seqs) = s ++ flatten (col + length s) seqs flatten col ((IAppend seq1 seq2, n) : seqs) = flatten col ((seq1, n) : (seq2, n) : seqs) flatten _ ((INewline, n) : seqs) = '\n' : (space n) ++ flatten n seqs flatten col ((IIndent s, _) : seqs) = flatten col ((s, col) : seqs) iDisplay :: Iseq -> String iDisplay s = flatten 0 [(s, 0)] iConcat :: [Iseq] -> Iseq iConcat [] = iNil iConcat (x:xs) = x `iAppend` (iConcat xs) iInterleave :: Iseq -> [Iseq] -> Iseq iInterleave _ [] = iNil iInterleave _ [y] = y iInterleave x (y:ys) = y `iAppend` x `iAppend` (iInterleave x ys) iNum :: Int -> Iseq iNum n = iStr (show n) iFWNum :: Int -> Int -> Iseq iFWNum width n = iStr (space (width - length digits) ++ digits) where digits = show n iLayn :: [Iseq] -> Iseq iLayn seqs = iConcat (map lay_item (zip [1..] seqs)) where lay_item (n, seq) = iConcat [ iFWNum 4 n, iStr ") ", iIndent seq, iNewline ] pprExpr :: CoreExpr -> Iseq pprExpr (ENum n) = iStr (show n) pprExpr (EVar v) = iStr v pprExpr (EAp e1 e2) = (pprExpr e1) `iAppend` (iStr " ") `iAppend` (pprExpr e2) pprExpr (ELet isrec defns expr) = iConcat [iStr keyword ,iNewline ,iStr " " ,iIndent (pprDefns defns) ,iNewline ,iStr "in " ,pprExpr expr] where keyword | not isrec = "let" | isrec = "letrec" pprDefns :: [(Name, CoreExpr)] -> Iseq pprDefns defns = iInterleave s (map pprDefn defns) where s = iConcat [ iStr ";", iNewline] pprDefn :: (Name, CoreExpr) -> Iseq pprDefn (name, expr) = iConcat [ iStr name, iStr " = ", iIndent (pprExpr expr)] pprScDefn :: CoreScDefn -> Iseq pprScDefn (name, vars, expr) = iConcat [ iStr name, iVars, iStr " = ", pprExpr expr] where iVars = (iAddBefore (iStr " ") (map iStr vars)) iAddBefore :: Iseq -> [Iseq] -> Iseq iAddBefore _ [] = iNil iAddBefore s (x:xs) = iConcat [s, x, iAddBefore s xs] pprint :: CoreProgram -> String pprint p = iDisplay $ iInterleave s (map pprScDefn p) where s = iConcat [ iStr ";", iNewline] {- Lexer and Parser -} type Token = (Int, String) twoCharOps :: [String] twoCharOps = ["==", "~=", ">=" , "<=", "->"] clex :: Int -> String -> [Token] clex line (c:cs) | c == '\n' = clex (line+1) cs | isSpace c = clex line cs clex line (c:cs) | isDigit c = (line, num_token) : clex line rest_cs where num_token = c : takeWhile isDigit cs rest_cs = dropWhile isDigit cs clex line ('-':'-':cs) = clex line cs_rest where cs_rest = dropWhile (\c -> c /= '\n') cs clex line (c:cs) | isLetter c = (line, var_tok) : clex line rest_cs where var_tok = c : takeWhile isIdChar cs rest_cs = dropWhile isIdChar cs clex line (a:b:cs) | elem [a,b] twoCharOps = (line, [a,b]) : clex line cs clex line (c:cs) = (line, [c]) : clex line cs clex _ [] = [] isIdChar :: Char -> Bool isIdChar c = isAlpha c || isDigit c || (c == '_') newtype Parser a = Parser {runParser :: [Token] -> [(a, [Token])]} instance Monad Parser where return a = Parser (\toks -> [(a,toks)]) p >>= f = Parser (\toks -> [(r2,toks2) | (r1,toks1) <- runParser p toks , (r2,toks2) <- runParser (f r1) toks1]) instance Applicative Parser where pure a = return a (<*>) = ap instance Functor Parser where fmap = liftM pAlt :: Parser a -> Parser a -> Parser a pAlt p1 p2 = Parser (\toks -> (runParser p1 toks) ++ (runParser p2 toks)) pGreeting :: Parser (String, String) pGreeting = do greeting <- pHelloOrGoodbye somebody <- pVar pLit "!" return (greeting,somebody) pHelloOrGoodbye :: Parser String pHelloOrGoodbye = (pLit "hello") `pAlt` (pLit "goodbye") pZeroOrMore :: Parser a -> Parser [a] pZeroOrMore p = (pOneOrMore p) `pAlt` (return []) pOneOrMore :: Parser a -> Parser [a] pOneOrMore p = Parser (\toks -> [(r : rs,toks2) | (r,toks1) <- runParser p toks , (rs,toks2) <- [head . runParser (pZeroOrMore p) $ toks1]]) toToken :: [String] -> [Token] toToken = map (\s -> (1,s)) pGreetingN :: Parser Int pGreetingN = liftM length (pZeroOrMore pGreeting) pOneOrMoreWithSep :: Parser a -> Parser b -> Parser [a] pOneOrMoreWithSep p sep = do r <- p rs <- pRest p sep return (r : rs) pRest :: Parser a -> Parser b -> Parser [a] pRest p sep = (sep >> pOneOrMoreWithSep p sep) `pAlt` (return []) pFail :: Parser a pFail = Parser (\_ -> []) pSat :: (String -> Bool) -> Parser String pSat p = Parser (\toks -> case toks of [] -> [] (_, tok):toks' -> if p tok then [(tok, toks')] else []) pLit :: String -> Parser String pLit s = pSat (== s) pVar :: Parser String pVar = pSat (\s -> (isAlpha . head $ s) && (not $ elem s keywords)) keywords :: [String] keywords = ["let", "letrec", "case", "in", "of", "Pack"] pNum :: Parser Int pNum = liftM read (pSat $ and . map isDigit) syntax :: [Token] -> CoreProgram syntax = take_first_parse . runParser pProgram where take_first_parse ((prog,[]):others) = prog take_first_parse (p:others) = take_first_parse others take_first_parse _ = error "Syntex error" pProgram :: Parser CoreProgram pProgram = pOneOrMoreWithSep pSc (pLit ";") pSc :: Parser CoreScDefn pSc = do var <- pVar args <- pZeroOrMore pVar pLit "=" expr <- pExpr return (var,args,expr) pExpr :: Parser CoreExpr pExpr = pLet `pAlt` pLetRec `pAlt` pCase `pAlt` pLambda `pAlt` pExpr1 pApp :: Parser CoreExpr pApp = liftM make_ap_chain (pOneOrMore pAExpr) make_ap_chain :: [CoreExpr] -> CoreExpr make_ap_chain xs = foldl1 make_ap xs where make_ap l r = EAp l r -- make_ap_chain [x] = x -- make_ap_chain [x,y] = EAp x y -- make_ap_chain (x:y:xs) = EAp (EAp x y) (make_ap_chain xs) pLet :: Parser CoreExpr pLet = do pLit "let" defns <- pDefns pLit "in" expr <- pExpr return (ELet nonRecursive defns expr) pDefns :: Parser [(Name, CoreExpr)] pDefns = pOneOrMoreWithSep pDefn (pLit ";") pDefn :: Parser (Name, CoreExpr) pDefn = do var <- pVar pLit "=" expr <- pExpr return (var,expr) pLetRec :: Parser CoreExpr pLetRec = do pLit "letrec" defns <- pDefns pLit "in" expr <- pExpr return (ELet recursive defns expr) pCase :: Parser CoreExpr pCase = do pLit "case" expr <- pExpr pLit "of" alters <- pAlters return (ECase expr alters) pAlters :: Parser [CoreAlt] pAlters = pOneOrMoreWithSep pAlter (pLit ";") pAlter :: Parser CoreAlt pAlter = do pLit "<" num <- pNum pLit ">" vars <- pOneOrMore pVar pLit "->" expr <- pExpr return (num,vars,expr) pLambda :: Parser CoreExpr pLambda = do pLit "\\" vars <- pOneOrMore pVar pLit "." expr <- pExpr return (ELam vars expr) pAExpr :: Parser CoreExpr pAExpr = (liftM EVar pVar) `pAlt` (liftM ENum pNum) `pAlt` pPack `pAlt` (do pLit "(" expr <- pExpr pLit ")" return expr) pPack :: Parser CoreExpr pPack = do pLit "Pack" pLit "{" num1 <- pNum pLit "," num2 <- pNum pLit "}" return (EConstr num1 num2) data PartialExpr = NoOp | FoundOp Name CoreExpr pExpr1 :: Parser CoreExpr pExpr1 = do expr <- pExpr2 expr' <- pExpr1c return (assembleOp expr expr') pExpr1c :: Parser PartialExpr pExpr1c = (do op <- pLit "|" expr <- pExpr1 return (FoundOp op expr)) `pAlt` (return NoOp) assembleOp :: CoreExpr -> PartialExpr -> CoreExpr assembleOp e1 NoOp = e1 assembleOp e1 (FoundOp op e2) = EAp (EAp (EVar op) e1) e2 pExpr2 :: Parser CoreExpr pExpr2 = do expr <- pExpr3 expr' <- pExpr2c return (assembleOp expr expr') pExpr2c :: Parser PartialExpr pExpr2c = (do op <- pLit "&" expr <- pExpr1 return (FoundOp op expr)) `pAlt` (return NoOp) pExpr3 :: Parser CoreExpr pExpr3 = do expr <- pExpr4 expr' <- pExpr3c return (assembleOp expr expr') pExpr3c :: Parser PartialExpr pExpr3c = (do op <- prelop expr <- pExpr4 return (FoundOp op expr)) `pAlt` (return NoOp) prelop :: Parser String prelop = (pLit "<") `pAlt` (pLit "<=") `pAlt` (pLit "==") `pAlt` (pLit "~=") `pAlt` (pLit ">=") `pAlt` (pLit ">") pExpr4 :: Parser CoreExpr pExpr4 = do expr <- pExpr5 expr' <- pExpr4c `pAlt` pExpr4c' return (assembleOp expr expr') pExpr4c :: Parser PartialExpr pExpr4c = (do op <- pLit "+" expr <- pExpr4 return (FoundOp op expr)) `pAlt` (return NoOp) pExpr4c' :: Parser PartialExpr pExpr4c' = (do op <- pLit "-" expr <- pExpr5 return (FoundOp op expr)) `pAlt` (return NoOp) pExpr5 :: Parser CoreExpr pExpr5 = do expr <- pApp expr' <- pExpr5c `pAlt` pExpr5c' return (assembleOp expr expr') pExpr5c :: Parser PartialExpr pExpr5c = (do op <- pLit "*" expr <- pExpr5 return (FoundOp op expr)) `pAlt` (return NoOp) pExpr5c' :: Parser PartialExpr pExpr5c' = (do op <- pLit "/" expr <- pApp return (FoundOp op expr)) `pAlt` (return NoOp) parse :: String -> CoreProgram parse = syntax . clex 1
bixuanzju/SCore
src/Language.hs
gpl-3.0
11,113
0
16
2,933
4,834
2,521
2,313
380
3
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Util.Snap where import Control.Error import Data.Monoid import qualified Data.ByteString.Char8 as BS import qualified Data.Text as T import qualified Data.Text.Encoding as T import Snap.Core requireParam :: MonadSnap m => BS.ByteString -> m BS.ByteString requireParam p = do r <- getParam p case r of Nothing -> finishWith (setResponseStatus 412 ("Missing Parameter '" <> p <> "'") emptyResponse) Just v -> return v checkedParam :: MonadSnap m => BS.ByteString -> ExceptT ReffitError m BS.ByteString checkedParam p = noteT (RErr 412 ("Missing parameter " <> T.decodeUtf8 p)) $ MaybeT $ getParam p checkedAssert :: MonadSnap m => ReffitError -> Bool -> ExceptT ReffitError m () checkedAssert e@(RErr _ _) b = bool (hoistEither $ Left e) (return ()) b checkedAssert ROk _ = checkedAssert (RErr 500 "Unknown error") False data ReffitError = RErr Int T.Text | ROk instance Semigroup ReffitError where ROk <> r = r r <> _ = r instance Monoid ReffitError where mempty = ROk runReffitErrorT :: MonadSnap m => ExceptT ReffitError m a -> m a runReffitErrorT = exceptT (\case ROk -> do writeText "Unknown error" finishWith (setResponseStatus 500 "Unknown Error" emptyResponse) RErr n msg -> do modifyResponse $ setResponseStatus n (T.encodeUtf8 msg) writeText msg r <- getResponse finishWith r ) return -- runErrors :: MonadSnap m => ReffitErrors -> m () -- runErrors (ReffitErrors es) = -- let eMap = M.fromListWith (<>) $ fmap (second (: [])) es -- in case M.minViewWithKey eMap of -- Nothing -> return () -- Just ((i,v), _) -> finishWith -- (setResponseStatus i -- (BS.pack $ show v) -- emptyResponse -- )
imalsogreg/reffit
src/Util/Snap.hs
gpl-3.0
1,980
0
16
579
494
251
243
49
2
module Middleware.Gloss.Environment where import Graphics.Gloss.Interface.IO.Game runEnvironment:: Int -> game -> (game -> IO Picture) -> (Event -> game -> IO game) -> (Float -> game -> IO game) -> IO () runEnvironment = playIO (InWindow "GameNumber on gloss" (800, 550) (10, 10)) black
EPashkin/gamenumber-gloss
src/Middleware/Gloss/Environment.hs
gpl-3.0
293
0
13
49
115
63
52
5
1
{-| Module : Main Description : The entry point of the voogie executable. Copyright : (c) Evgenii Kotelnikov, 2019 License : GPL-3 Maintainer : evgeny.kotelnikov@gmail.com Stability : provisional -} module Main ( main ) where import Data.Text (Text) import qualified Data.Text.IO as TIO import Options.Applicative (execParser) import System.Exit (exitSuccess, exitFailure) import System.IO (stdout, stderr) import System.IO.Error (tryIOError) import System.Posix.Terminal (queryTerminal) import System.Posix.IO (stdOutput, stdError) import Voogie.Back import Voogie.Error import Voogie.Front import Voogie.Parse.Boogie (parseBoogie) import Voogie.Pretty.TPTP import Voogie.TPTP import CmdArgs collectOptions :: CmdArgs -> TranslationOptions collectOptions cmdArgs = TranslationOptions (not $ noArrayTheory cmdArgs) printErrorReport :: Doc -> IO () printErrorReport e = do istty <- queryTerminal stdError hPutDoc stderr (if istty then e else plain e) exitFailure printResult :: Doc -> IO () printResult r = do istty <- queryTerminal stdOutput hPutDoc stdout (if istty then r else plain r) exitSuccess type Output = Either ErrorReport Doc printOutput :: Output -> IO () printOutput = either (printErrorReport . pretty) printResult reportIOError :: Either IOError a -> Either ErrorReport a reportIOError = fmapError (ErrorReport Nothing . InputOutputError) runVoogie :: CmdArgs -> Text -> Output runVoogie cmdArgs contents = reportContents $ case action cmdArgs of Parse -> pretty <$> runParser Check -> pretty <$> (runParser >>= runAnalyzer) Translate -> pretty <$> (runParser >>= runAnalyzer >>= runTranslator) where source = filePath cmdArgs options = collectOptions cmdArgs runParser = parseBoogie source contents runAnalyzer = analyze runTranslator = return . toTPTP . translate options reportContents = fmapError (ErrorReport $ Just contents) main :: IO () main = do cmdArgs <- execParser cmdArgsParserInfo let input = maybe TIO.getContents TIO.readFile (filePath cmdArgs) tryContents <- tryIOError input printOutput $ reportIOError tryContents >>= runVoogie cmdArgs
aztek/voogie
src/Voogie/Executable/Main.hs
gpl-3.0
2,174
0
12
379
591
310
281
51
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-| Module : Main Description : The Main module of the tool The Main module of the fuzzy matching tool. -} module Main where import Fuzzball.Algorithm import UI.NCurses import System.Posix.IO import Control.Applicative (Applicative, (<$>)) import Control.Monad import Control.Monad.Trans import Control.Monad.State (MonadState, gets, modify) import Control.Monad.Trans.State hiding (gets, modify) import Control.DeepSeq import qualified Data.Foldable as F (forM_) import Data.List (nub, sort) -- | The state of a running fuzzball instance data FuzzballState = FuzzballState { input :: String , candidates :: [String] , inputW :: Window , candidatesW :: Window , highlight :: ColorID } -- | The Fuzzball custom monad newtype Fuzzball a = Fuzzball (StateT FuzzballState Curses a) deriving (Functor, Applicative, Monad, MonadState FuzzballState) -- | Run a Fuzzball runFuzzball :: FuzzballState -> Fuzzball a -> Curses a runFuzzball s (Fuzzball m) = evalStateT m s -- | Lift a Curses into a Fuzzball liftC :: Curses a -> Fuzzball a liftC = Fuzzball . lift -- | The main routine main :: IO () main = do -- Read candidates from stdin inputCandidates <- nub . lines <$> getContents deepseq inputCandidates . return $ () -- Remap tty to stdin tty <- openFd "/dev/tty" ReadWrite Nothing defaultFileFlags void . dupTo tty $ stdInput result <- runCurses $ do setEcho True setCBreak True defaultWindow >>= flip setKeypad True -- Create the two windows (height, width) <- screenSize inputW <- newWindow 1 width 0 0 candidatesW <- newWindow (height - 1) width 1 1 setKeypad inputW True setKeypad candidatesW True -- Decide on a highlight color highlight <- newColorID ColorDefault ColorCyan 1 -- Run the fuzzball instance let state = FuzzballState "" inputCandidates inputW candidatesW highlight result <- runFuzzball state loop -- Close the windows closeWindow inputW closeWindow candidatesW return result -- Maybe print a result F.forM_ result putStrLn -- | The main loop of the program loop :: Fuzzball (Maybe String) loop = do draw handleEvent -- | Draw the two windows draw :: Fuzzball () draw = do clearWindows drawCandidates drawInput liftC render -- | A disgusting hack to clear all the windows clearWindows :: Fuzzball () clearWindows = do (height, width) <- liftC screenSize inputW <- gets inputW liftC . updateWindow inputW $ do moveCursor 0 0 drawString . replicate (fromInteger (width - 1)) $ ' ' candidatesW <- gets candidatesW liftC . updateWindow candidatesW $ do moveCursor 0 0 drawString . replicate (fromInteger ((width - 1) * (height - 1))) $ ' ' -- | Draw the input field drawInput :: Fuzzball () drawInput = do input <- gets input inputW <- gets inputW width <- fromInteger . snd <$> liftC screenSize liftC . updateWindow inputW $ do moveCursor 0 0 -- Make sure the input fits the input line let dropLength = length input - width + 3 fixedInput = if dropLength > 0 then drop dropLength input else input drawString $ "> " ++ fixedInput -- | Draw the matching candidates drawCandidates :: Fuzzball () drawCandidates = do candidatesW <- gets candidatesW matchingCandidates <- matchingCandidates height <- fromInteger . (\x -> x - 1) . fst <$> liftC screenSize width <- snd <$> liftC screenSize highlight <- gets highlight liftC . updateWindow candidatesW $ do forM_ (zip [0..] . take height $ matchingCandidates) $ \(y, candidate) -> do moveCursor y 0 when (y == 0) $ do setColor highlight drawLineH (Just . Glyph ' ' $ []) width displayMatchResult candidate when (y == 0) $ setColor defaultColorID -- | Returns all the candidates matching the current input matchingCandidates :: Fuzzball [(MatchRating, String)] matchingCandidates = liftM2 order (gets input) (gets candidates) where order x xs = sort . squash . flip zip xs . map (fuzzyMatch x) $ xs squash [] = [] squash ((Just a, b):xs) = (a, b):squash xs squash (_:xs) = squash xs -- | Display a matched candidate displayMatchResult :: (MatchRating, String) -> Update () displayMatchResult ((MatchRating _ []), s) = drawString s -- Underline a matched character displayMatchResult ((MatchRating _ (0:xs)), (c:cs)) = do setAttribute AttributeUnderline True drawString [c] setAttribute AttributeUnderline False let nextRating = MatchRating 0 . map (\x -> x - 1) $ xs displayMatchResult (nextRating, cs) displayMatchResult ((MatchRating _ xs), (c:cs)) = do drawString [c] let nextRating = MatchRating 0 . map (\x -> x - 1) $ xs displayMatchResult (nextRating, cs) -- | Handle the different incoming keyboard events handleEvent :: Fuzzball (Maybe String) handleEvent = do event <- liftC (defaultWindow >>= flip getEvent Nothing) case event of Just e -> handle e _ -> return Nothing where -- Delete a charcter handle (EventSpecialKey KeyBackspace) = do input <- gets input unless (null input) (modify $ \s -> s { input = init input }) loop -- Maybe return the matched result handle (EventCharacter '\n') = do result <- matchingCandidates return $ if null result then Nothing else Just . snd . head $ result -- Append a character handle (EventCharacter c) = do input <- gets input modify $ \s -> s { input = input ++ [c] } loop -- Resize the windows handle EventResized = do candidatesW <- gets candidatesW liftC . closeWindow $ candidatesW (height, width) <- liftC screenSize newCandidatesW <- liftC . newWindow (height - 1) width 1 $ 0 modify $ \s -> s { candidatesW = newCandidatesW } loop handle _ = loop
froozen/fuzzball
src/Main.hs
gpl-3.0
6,288
0
21
1,769
1,844
919
925
138
7
{-# LANGUAGE GADTs , MultiParamTypeClasses , TemplateHaskell , ViewPatterns #-} module Satter.Types ( -- * Geometry simulationScale , Geometrics (..) , position , direction , velocity , geometricsDefault , playersAt , randomizePosition , randomizeDirection , beyond , isBehind , currentEnemyOffside , currentOurOffside , keepInRange , onEdge -- * Player Index and Roll , PlayerIndex , PlayerRoll (..) , Team (..) -- * Action Target , ActionTarget (..) -- * Ball , Ball (..) , geometrics_b , holdBy , ballDefault , ballSize -- * Director Intention , DirectorIntention (..) -- * Player Property and Intention , PlayerProperty (..) , roll , team , number , idNumber , defaultPosition -- * Team Context , TeamContext (..) , positions , directorIntention , goalPosition , getTeammatePositions , getEnemies , getEnemyPositions -- * Player , Player (..) , geometrics_p , property , intention , Intention (..) , playerPropertyDefault , playerSize -- * Game Context , GameContext (..) , time , ball , players , runMode , team1 , team2 , score , debug , nthPlayer , suspendByGoal , solverIteration , satAssignments , numberOfRun , usedSeeds , defaultGameContext , getTeamContext , getPositions , inOurPenaltyArea , isInOurPenaltyArea , inEnemyPenaltyArea , isInEnemyPenaltyArea , inOurArea , isInOurArea , inEnemyArea , isInEnemyArea -- * SObject , SObject (..) ) where import Control.Applicative import Control.Lens import Control.Monad import Data.IORef import qualified Data.Vector as V import Satter.TwoD import Satter.Field simulationScale :: Double simulationScale = 1.7 -------------------------------------------------------------------------------- Geometry data Geometrics = Geometrics { _position :: TwoD , _direction :: TwoD , _velocity :: Double } deriving (Eq, Ord, Read, Show) makeLenses ''Geometrics instance Num Geometrics where (Geometrics (x1, y1) (dx1, dy1) v1) + (Geometrics (x2, y2) (dx2, dy2) v2) = Geometrics ((x1 + x2) / 2, (y1 + y2) / 2) ((dx1 + dx2) / 2, (dy1 + dy2) / 2) ((v1 + v2) / 2) (*) = undefined (-) = undefined negate (Geometrics (x, y) (dx, dy) v) = Geometrics (negate x, negate y) (negate dx, negate dy) v abs = undefined signum = undefined fromInteger = undefined geometricsDefault :: Geometrics geometricsDefault = Geometrics (0, 0) (0, 0) 0 newPosition :: Geometrics -> Double -> TwoD newPosition (Geometrics (x, y) (dx, dy) v) k =(x + k' * dx * (v + k) * simulationScale, y + k' * dy * (v + k) * simulationScale) where k' = max 0.5 $ min 1 k -------------------------------------------------------------------------------- PlayerIndex and Roll type PlayerIndex = Int data PlayerRoll = PlayerForward | PlayerKeeper | PlayerDefence | PlayerSAT deriving (Eq, Ord, Read, Show) data Team = Team1 | Team2 deriving (Eq, Ord, Read, Show) instance Enum Team where fromEnum Team1 = 1 fromEnum Team2 = 2 toEnum 1 = Team1 toEnum 2 = Team2 -------------------------------------------------------------------------------- Action Target -- | total 18 kinds data ActionTarget where -- + [0 .. 5] TargetBall :: ActionTarget TargetMate :: ActionTarget TargetDefaultPosition :: ActionTarget TargetOffsideLine :: ActionTarget TargetGoal :: ActionTarget DefenceLine :: ActionTarget -- + this is a synonym of TargetGrid -- + [6 .. 17] TargetZone :: Int -> ActionTarget TargetGrid :: (Int, Int) -> Int -> ActionTarget deriving (Eq, Ord, Read, Show) instance Bounded ActionTarget where minBound = TargetBall maxBound = DefenceLine instance Enum ActionTarget where succ = toEnum . (1 +) . fromEnum pred = toEnum . (1 -) . fromEnum fromEnum TargetBall = 0 fromEnum TargetMate = 1 fromEnum TargetDefaultPosition = 2 fromEnum TargetOffsideLine = 3 fromEnum TargetGoal = 4 fromEnum DefenceLine = 5 fromEnum (TargetZone n) = 5 + n fromEnum (TargetGrid _ n) = 5 + n toEnum 0 = TargetBall toEnum 1 = TargetMate toEnum 2 = TargetDefaultPosition toEnum 3 = TargetOffsideLine toEnum 4 = TargetGoal toEnum 5 = DefenceLine -- we can't convert Int into TargetGrid, so we use TargetZone here -- and this means we can check the upper bound here toEnum n = if 6 <= n then TargetZone (n - 5) else error "out of index for ActionTarget" -------------------------------------------------------------------------------- Ball data Ball = Ball { _geometrics_b :: Geometrics , _holdBy :: Maybe PlayerIndex } deriving (Eq, Ord, Read, Show) makeLenses ''Ball ballDefault :: Ball ballDefault = Ball (Geometrics (fwidth / 2, fvmargin + fheight / 2) (0,0) 2.2) Nothing ballSize :: Double ballSize = 2 -------------------------------------------------------------------------------- DirectorIntention data DirectorIntention where NoStrategy :: DirectorIntention BoringAttack :: DirectorIntention AggressiveAttack :: DirectorIntention OpenToLeft :: DirectorIntention OpenToRight :: DirectorIntention deriving (Eq, Ord, Read, Show) -------------------------------------------------------------------------------- Player Property and Intention data PlayerProperty = PlayerProperty { _roll :: PlayerRoll , _team :: Team , _number :: Int , _idNumber :: Int , _defaultPosition :: TwoD } deriving (Eq, Ord, Read, Show) makeLenses ''PlayerProperty playerPropertyDefault :: PlayerProperty playerPropertyDefault = PlayerProperty PlayerForward Team1 0 0 (0, 0) data Intention where Lost :: Double -> Intention NoPlan :: Intention Keep :: Double -> Intention GoFor :: Double -> ActionTarget -> Intention KickTo :: Double -> ActionTarget -> Intention DribblingTo :: Double -> ActionTarget -> Intention deriving (Eq, Ord, Read, Show) playerIntentionDefault = NoPlan -------------------------------------------------------------------------------- Team data TeamContext = TeamContext { _teammates :: [PlayerIndex] , _positions :: ([(Int, TwoD)], [(Int, TwoD)]) , _directorIntention :: DirectorIntention , _goalPosition :: TwoD , _baseDirection :: Double } deriving (Eq, Ord, Read, Show) makeLenses ''TeamContext -------------------------------------------------------------------------------- Player playerSize :: Double playerSize = 8 data Player = Player { _geometrics_p :: Geometrics , _property :: PlayerProperty , _intention :: Intention } deriving (Eq, Ord, Read, Show) makeLenses ''Player belongsToTeam :: Int -> Player -> Bool belongsToTeam t' (_property -> _team -> t) = t' == fromEnum t' getTeamContext :: GameContext -> Player -> TeamContext getTeamContext game (_property -> _team -> Team1) = _team1 game getTeamContext game (_property -> _team -> Team2) = _team2 game -- | return [(PlayerProperty, TwoD)]. -- If the 3rd arg is True, delete himself getTeammatePositions :: GameContext -> Player -> Bool -> [(PlayerProperty, TwoD)] getTeammatePositions (_players -> ps) p@(_property -> _team -> tid) deleteMe | deleteMe = map getValue . filter ((i /=) . getID) . filter ((tid ==) . getTeam) $ V.toList ps | otherwise = map getValue . filter ((tid ==) . getTeam) $ V.toList ps where i = p ^. property . idNumber getID = _idNumber . _property getTeam = _team . _property getValue (Player pg pp _) = (pp, _position pg) getEnemies :: GameContext -> Player -> [Player] getEnemies (_players -> ps) (_property -> _team -> tid) = filter ((tid /=) . getTeam) $ V.toList ps where getTeam = _team . _property getEnemyPositions :: GameContext -> Player -> [(PlayerProperty, TwoD)] getEnemyPositions p l = map getValue $ getEnemies p l where getValue (Player pg pp _) = (pp, _position pg) -------------------------------------------------------------------------------- Game Context data GameContext = GameContext { _time :: Int , _ball :: Ball , _players :: V.Vector Player , _runMode :: Bool , _team1 :: TeamContext , _team2 :: TeamContext , _score :: (Int, Int) , _debug :: Bool , _suspendByGoal :: Int , _solverIteration :: Int , _satAssignments :: IORef [Bool] , _numberOfRun :: Int , _usedSeeds :: [(Double, Double)] } -- deriving (Eq, Read, Show) defaultGameContext = GameContext (-1) -- time undefined -- ball undefined -- player undefined -- runMode undefined -- team1 undefined -- team2 (0, 0) -- score undefined -- debug 0 -- suspendByGoal 0 -- solverIteration undefined -- satAssignments 0 -- numberOfRun [] -- usedSeeds makeLenses ''GameContext nthPlayer :: GameContext -> Int -> Player nthPlayer g i = (g ^. players) V.! (i -1) getPositions :: GameContext -> ([(PlayerProperty, TwoD)], [(PlayerProperty, TwoD)]) getPositions (_players -> players) = (map getValue $ filter ((Team1 ==) . getTeam) l, map getValue $ filter ((Team2 ==) . getTeam) l) where l = V.toList players getTeam (Player _ pp _) = _team pp getValue (Player pg pp _) = (pp, _position pg) -------------------------------------------------------------------------------- SObject class SObject a where geometricsOf :: a -> Geometrics positionOf :: a -> TwoD positionOf = _position . geometricsOf directionOf :: a -> TwoD directionOf = _direction . geometricsOf velocityOf :: a -> Double velocityOf = _velocity . geometricsOf sizeOf :: a -> Double -- * return /a/ with a new position after /second/ (<!!) :: a -> Double -> a (<!!) = undefined updateIntention :: GameContext -> a -> IO a updateIntention _ _ = error "no default method of updateIntention" updatePhysics :: GameContext -> a -> IO (Either (a, Ball) a) updatePhysics _ _ = error "no default method of updatePhysics" -------------------------------------------------------------------------------- misc functions playersAt :: GameContext -> TwoD -> Double -> IO [Player] playersAt game pos range = do let players = _players game let l = V.toList players return $ filter (\(_geometrics_p -> _position -> pos') -> near2 range pos' pos) l randomizePosition :: GameContext -> TwoD -> Double -> Int -> TwoD randomizePosition game (x, y) d k = (x + fromIntegral ox, y + fromIntegral oy) where t' = _time game d' = ceiling d ox = mod (t' * k) (2 * d') - d' oy = mod (t' * (k +1)) (2 * d') - d' randomizeDirection :: GameContext -> TwoD -> Double -> Int -> TwoD randomizeDirection game (x, y) d k = randomizeDirectionWithSeed (_time game) (x, y) d k randomizeDirectionWithSeed :: Int -> TwoD -> Double -> Int -> TwoD randomizeDirectionWithSeed t' (x, y) d k | 0 == x && 0 == y = (0, 0) | 0 <= x && 0 <= y = (cos rad, sin rad) | x <= 0 && 0 <= y = (-cos rad, -sin rad) | 0 <= x && y <= 0 = (cos rad, sin rad) | x <= 0 && y <= 0 = (-cos rad, -sin rad) | otherwise = (0.5, 0.5) where d' = ceiling d ox = if d == 0 then 0 else pi / 180 * (fromIntegral $ mod (div (t' * k) d') (2 * d') - d') rad = atan (y/x) + ox -- | 第2引数が第3引数を超えていたらTrue beyond :: GameContext -> Player -> ActionTarget -> Bool beyond game player@(Player (_position -> (_,y)) (_team -> t) _) TargetOffsideLine = case t of Team1 -> y < y' Team2 -> y' < y where y' = currentOurOffside game player beyond game player@(Player (_position -> (_,y)) (_team -> t) _) TargetBall = case t of Team1 -> y < y' Team2 -> y' < y where (Ball (Geometrics (_, y') _ _) _) = _ball game isBehind :: Player -> Player -> Bool isBehind p1@(_geometrics_p -> _position -> (_, y1)) p2@(_geometrics_p -> _position -> (_, y2)) | p1 ^. property . team == Team1 = y2 < y1 | otherwise = y1 < y2 currentEnemyOffside :: GameContext -> Player -> Double currentEnemyOffside game player@(Player _ (_team -> t) _) = case t of Team1 -> (maximum . map (snd . snd) . filter ((PlayerKeeper /=) . _roll . fst) . fst) $ getPositions game Team2 -> (minimum . map (snd . snd) . filter ((PlayerKeeper /=) . _roll . fst) . snd) $ getPositions game currentOurOffside :: GameContext -> Player -> Double currentOurOffside game player@(Player _ (_team -> t) _) = case t of Team1 -> (minimum . map (snd . snd) . filter ((PlayerKeeper /=) . _roll . fst) . snd) $ getPositions game Team2 -> (maximum . map (snd . snd) . filter ((PlayerKeeper /=) . _roll . fst) . fst) $ getPositions game inOurPenaltyArea :: GameContext -> Player -> Bool inOurPenaltyArea game player@(Player (_position -> (x, y)) (_team -> t) _) = do case t of Team1 -> fvmargin + 3 * fheight / 4 < y Team2 -> y < fvmargin + fheight / 4 isInOurPenaltyArea :: GameContext -> Player -> TwoD -> Bool isInOurPenaltyArea game (_property -> _team -> t) (x, y) = do case t of Team1 -> fvmargin + 3 * fheight / 4 < y Team2 -> y < fvmargin + fheight / 4 inEnemyPenaltyArea :: GameContext -> Player -> Bool inEnemyPenaltyArea game player@(Player (_position -> (x, y)) (_team -> t) _) = do case t of Team1 -> y < fvmargin + fheight / 4 Team2 -> fvmargin + 3 * fheight / 4 < y isInEnemyPenaltyArea :: GameContext -> Player -> TwoD -> Bool isInEnemyPenaltyArea game (_property -> _team -> t) (x, y) = do case t of Team1 -> y < fvmargin + fheight / 4 Team2 -> fvmargin + 3 * fheight / 4 < y inOurArea :: GameContext -> Player -> Bool inOurArea game player@(Player (_position -> (x, y)) (_team -> t) _) = do case t of Team1 -> fvmargin + fheight / 2 < y Team2 -> y < fvmargin + fheight / 2 isInOurArea :: GameContext -> Player -> TwoD -> Bool isInOurArea game (_property -> _team -> t) (x, y) = do case t of Team1 -> fvmargin + fheight / 2 < y Team2 -> y < fvmargin + fheight / 2 inEnemyArea :: GameContext -> Player -> Bool inEnemyArea game player@(Player (_position -> (x, y)) (_team -> t) _) = do case t of Team1 -> y < fvmargin + fheight / 2 Team2 -> fvmargin + fheight / 2 < y isInEnemyArea :: GameContext -> Player -> TwoD -> Bool isInEnemyArea game (_property -> _team -> t) (x, y) = do case t of Team1 -> y < fvmargin + fheight / 2 Team2 -> fvmargin + fheight / 2 < y keepInRange :: TwoD -> TwoD keepInRange (x, y) = (inRange x left right, inRange y top bottom) where left = fhmargin right = fwidth + fhmargin - playerSize top = fvmargin bottom = fheight + fvmargin - playerSize inRange a l u = case () of { _ | a < l -> l; _ | u < a -> u; _ -> a } onEdge :: TwoD -> Bool onEdge (x, y) = elem x [left, right] || elem y [top, bottom] where left = fhmargin right = fwidth + fhmargin - playerSize top = fvmargin bottom = fheight + fvmargin - playerSize
shnarazk/satter
Satter/Types.hs
gpl-3.0
16,112
4
16
4,573
4,945
2,715
2,230
-1
-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.AndroidEnterprise.Entitlements.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists all entitlements for the specified user. Only the ID is set. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.entitlements.list@. module Network.Google.Resource.AndroidEnterprise.Entitlements.List ( -- * REST Resource EntitlementsListResource -- * Creating a Request , entitlementsList , EntitlementsList -- * Request Lenses , entXgafv , entUploadProtocol , entEnterpriseId , entAccessToken , entUploadType , entUserId , entCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.entitlements.list@ method which the -- 'EntitlementsList' request conforms to. type EntitlementsListResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "users" :> Capture "userId" Text :> "entitlements" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] EntitlementsListResponse -- | Lists all entitlements for the specified user. Only the ID is set. -- -- /See:/ 'entitlementsList' smart constructor. data EntitlementsList = EntitlementsList' { _entXgafv :: !(Maybe Xgafv) , _entUploadProtocol :: !(Maybe Text) , _entEnterpriseId :: !Text , _entAccessToken :: !(Maybe Text) , _entUploadType :: !(Maybe Text) , _entUserId :: !Text , _entCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EntitlementsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'entXgafv' -- -- * 'entUploadProtocol' -- -- * 'entEnterpriseId' -- -- * 'entAccessToken' -- -- * 'entUploadType' -- -- * 'entUserId' -- -- * 'entCallback' entitlementsList :: Text -- ^ 'entEnterpriseId' -> Text -- ^ 'entUserId' -> EntitlementsList entitlementsList pEntEnterpriseId_ pEntUserId_ = EntitlementsList' { _entXgafv = Nothing , _entUploadProtocol = Nothing , _entEnterpriseId = pEntEnterpriseId_ , _entAccessToken = Nothing , _entUploadType = Nothing , _entUserId = pEntUserId_ , _entCallback = Nothing } -- | V1 error format. entXgafv :: Lens' EntitlementsList (Maybe Xgafv) entXgafv = lens _entXgafv (\ s a -> s{_entXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). entUploadProtocol :: Lens' EntitlementsList (Maybe Text) entUploadProtocol = lens _entUploadProtocol (\ s a -> s{_entUploadProtocol = a}) -- | The ID of the enterprise. entEnterpriseId :: Lens' EntitlementsList Text entEnterpriseId = lens _entEnterpriseId (\ s a -> s{_entEnterpriseId = a}) -- | OAuth access token. entAccessToken :: Lens' EntitlementsList (Maybe Text) entAccessToken = lens _entAccessToken (\ s a -> s{_entAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). entUploadType :: Lens' EntitlementsList (Maybe Text) entUploadType = lens _entUploadType (\ s a -> s{_entUploadType = a}) -- | The ID of the user. entUserId :: Lens' EntitlementsList Text entUserId = lens _entUserId (\ s a -> s{_entUserId = a}) -- | JSONP entCallback :: Lens' EntitlementsList (Maybe Text) entCallback = lens _entCallback (\ s a -> s{_entCallback = a}) instance GoogleRequest EntitlementsList where type Rs EntitlementsList = EntitlementsListResponse type Scopes EntitlementsList = '["https://www.googleapis.com/auth/androidenterprise"] requestClient EntitlementsList'{..} = go _entEnterpriseId _entUserId _entXgafv _entUploadProtocol _entAccessToken _entUploadType _entCallback (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy EntitlementsListResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Entitlements/List.hs
mpl-2.0
5,182
0
20
1,289
785
456
329
118
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.Blogger.PageViews.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets page views by blog id. -- -- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.pageViews.get@. module Network.Google.Resource.Blogger.PageViews.Get ( -- * REST Resource PageViewsGetResource -- * Creating a Request , pageViewsGet , PageViewsGet -- * Request Lenses , pvgXgafv , pvgUploadProtocol , pvgAccessToken , pvgUploadType , pvgBlogId , pvgRange , pvgCallback ) where import Network.Google.Blogger.Types import Network.Google.Prelude -- | A resource alias for @blogger.pageViews.get@ method which the -- 'PageViewsGet' request conforms to. type PageViewsGetResource = "v3" :> "blogs" :> Capture "blogId" Text :> "pageviews" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParams "range" PageViewsGetRange :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Pageviews -- | Gets page views by blog id. -- -- /See:/ 'pageViewsGet' smart constructor. data PageViewsGet = PageViewsGet' { _pvgXgafv :: !(Maybe Xgafv) , _pvgUploadProtocol :: !(Maybe Text) , _pvgAccessToken :: !(Maybe Text) , _pvgUploadType :: !(Maybe Text) , _pvgBlogId :: !Text , _pvgRange :: !(Maybe [PageViewsGetRange]) , _pvgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PageViewsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pvgXgafv' -- -- * 'pvgUploadProtocol' -- -- * 'pvgAccessToken' -- -- * 'pvgUploadType' -- -- * 'pvgBlogId' -- -- * 'pvgRange' -- -- * 'pvgCallback' pageViewsGet :: Text -- ^ 'pvgBlogId' -> PageViewsGet pageViewsGet pPvgBlogId_ = PageViewsGet' { _pvgXgafv = Nothing , _pvgUploadProtocol = Nothing , _pvgAccessToken = Nothing , _pvgUploadType = Nothing , _pvgBlogId = pPvgBlogId_ , _pvgRange = Nothing , _pvgCallback = Nothing } -- | V1 error format. pvgXgafv :: Lens' PageViewsGet (Maybe Xgafv) pvgXgafv = lens _pvgXgafv (\ s a -> s{_pvgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pvgUploadProtocol :: Lens' PageViewsGet (Maybe Text) pvgUploadProtocol = lens _pvgUploadProtocol (\ s a -> s{_pvgUploadProtocol = a}) -- | OAuth access token. pvgAccessToken :: Lens' PageViewsGet (Maybe Text) pvgAccessToken = lens _pvgAccessToken (\ s a -> s{_pvgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pvgUploadType :: Lens' PageViewsGet (Maybe Text) pvgUploadType = lens _pvgUploadType (\ s a -> s{_pvgUploadType = a}) pvgBlogId :: Lens' PageViewsGet Text pvgBlogId = lens _pvgBlogId (\ s a -> s{_pvgBlogId = a}) pvgRange :: Lens' PageViewsGet [PageViewsGetRange] pvgRange = lens _pvgRange (\ s a -> s{_pvgRange = a}) . _Default . _Coerce -- | JSONP pvgCallback :: Lens' PageViewsGet (Maybe Text) pvgCallback = lens _pvgCallback (\ s a -> s{_pvgCallback = a}) instance GoogleRequest PageViewsGet where type Rs PageViewsGet = Pageviews type Scopes PageViewsGet = '["https://www.googleapis.com/auth/blogger"] requestClient PageViewsGet'{..} = go _pvgBlogId _pvgXgafv _pvgUploadProtocol _pvgAccessToken _pvgUploadType (_pvgRange ^. _Default) _pvgCallback (Just AltJSON) bloggerService where go = buildClient (Proxy :: Proxy PageViewsGetResource) mempty
brendanhay/gogol
gogol-blogger/gen/Network/Google/Resource/Blogger/PageViews/Get.hs
mpl-2.0
4,645
0
18
1,152
795
461
334
114
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.Directory.Users.Photos.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Add a photo for the user -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.users.photos.update@. module Network.Google.Resource.Directory.Users.Photos.Update ( -- * REST Resource UsersPhotosUpdateResource -- * Creating a Request , usersPhotosUpdate , UsersPhotosUpdate -- * Request Lenses , upuPayload , upuUserKey ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.users.photos.update@ method which the -- 'UsersPhotosUpdate' request conforms to. type UsersPhotosUpdateResource = "admin" :> "directory" :> "v1" :> "users" :> Capture "userKey" Text :> "photos" :> "thumbnail" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] UserPhoto :> Put '[JSON] UserPhoto -- | Add a photo for the user -- -- /See:/ 'usersPhotosUpdate' smart constructor. data UsersPhotosUpdate = UsersPhotosUpdate' { _upuPayload :: !UserPhoto , _upuUserKey :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersPhotosUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'upuPayload' -- -- * 'upuUserKey' usersPhotosUpdate :: UserPhoto -- ^ 'upuPayload' -> Text -- ^ 'upuUserKey' -> UsersPhotosUpdate usersPhotosUpdate pUpuPayload_ pUpuUserKey_ = UsersPhotosUpdate' { _upuPayload = pUpuPayload_ , _upuUserKey = pUpuUserKey_ } -- | Multipart request metadata. upuPayload :: Lens' UsersPhotosUpdate UserPhoto upuPayload = lens _upuPayload (\ s a -> s{_upuPayload = a}) -- | Email or immutable Id of the user upuUserKey :: Lens' UsersPhotosUpdate Text upuUserKey = lens _upuUserKey (\ s a -> s{_upuUserKey = a}) instance GoogleRequest UsersPhotosUpdate where type Rs UsersPhotosUpdate = UserPhoto type Scopes UsersPhotosUpdate = '["https://www.googleapis.com/auth/admin.directory.user"] requestClient UsersPhotosUpdate'{..} = go _upuUserKey (Just AltJSON) _upuPayload directoryService where go = buildClient (Proxy :: Proxy UsersPhotosUpdateResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Users/Photos/Update.hs
mpl-2.0
3,205
0
16
771
395
237
158
64
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.Webmasters.URLCrawlErrorscounts.Query -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves a time series of the number of URL crawl errors per error -- category and platform. -- -- /See:/ <https://developers.google.com/webmaster-tools/ Search Console API Reference> for @webmasters.urlcrawlerrorscounts.query@. module Network.Google.Resource.Webmasters.URLCrawlErrorscounts.Query ( -- * REST Resource URLCrawlErrorscountsQueryResource -- * Creating a Request , urlCrawlErrorscountsQuery , URLCrawlErrorscountsQuery -- * Request Lenses , uceqPlatform , uceqCategory , uceqSiteURL , uceqLatestCountsOnly ) where import Network.Google.Prelude import Network.Google.WebmasterTools.Types -- | A resource alias for @webmasters.urlcrawlerrorscounts.query@ method which the -- 'URLCrawlErrorscountsQuery' request conforms to. type URLCrawlErrorscountsQueryResource = "webmasters" :> "v3" :> "sites" :> Capture "siteUrl" Text :> "urlCrawlErrorsCounts" :> "query" :> QueryParam "platform" URLCrawlErrorscountsQueryPlatform :> QueryParam "category" URLCrawlErrorscountsQueryCategory :> QueryParam "latestCountsOnly" Bool :> QueryParam "alt" AltJSON :> Get '[JSON] URLCrawlErrorsCountsQueryResponse -- | Retrieves a time series of the number of URL crawl errors per error -- category and platform. -- -- /See:/ 'urlCrawlErrorscountsQuery' smart constructor. data URLCrawlErrorscountsQuery = URLCrawlErrorscountsQuery' { _uceqPlatform :: !(Maybe URLCrawlErrorscountsQueryPlatform) , _uceqCategory :: !(Maybe URLCrawlErrorscountsQueryCategory) , _uceqSiteURL :: !Text , _uceqLatestCountsOnly :: !Bool } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'URLCrawlErrorscountsQuery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uceqPlatform' -- -- * 'uceqCategory' -- -- * 'uceqSiteURL' -- -- * 'uceqLatestCountsOnly' urlCrawlErrorscountsQuery :: Text -- ^ 'uceqSiteURL' -> URLCrawlErrorscountsQuery urlCrawlErrorscountsQuery pUceqSiteURL_ = URLCrawlErrorscountsQuery' { _uceqPlatform = Nothing , _uceqCategory = Nothing , _uceqSiteURL = pUceqSiteURL_ , _uceqLatestCountsOnly = True } -- | The user agent type (platform) that made the request. For example: web. -- If not specified, returns results for all platforms. uceqPlatform :: Lens' URLCrawlErrorscountsQuery (Maybe URLCrawlErrorscountsQueryPlatform) uceqPlatform = lens _uceqPlatform (\ s a -> s{_uceqPlatform = a}) -- | The crawl error category. For example: serverError. If not specified, -- returns results for all categories. uceqCategory :: Lens' URLCrawlErrorscountsQuery (Maybe URLCrawlErrorscountsQueryCategory) uceqCategory = lens _uceqCategory (\ s a -> s{_uceqCategory = a}) -- | The site\'s URL, including protocol. For example: -- http:\/\/www.example.com\/ uceqSiteURL :: Lens' URLCrawlErrorscountsQuery Text uceqSiteURL = lens _uceqSiteURL (\ s a -> s{_uceqSiteURL = a}) -- | If true, returns only the latest crawl error counts. uceqLatestCountsOnly :: Lens' URLCrawlErrorscountsQuery Bool uceqLatestCountsOnly = lens _uceqLatestCountsOnly (\ s a -> s{_uceqLatestCountsOnly = a}) instance GoogleRequest URLCrawlErrorscountsQuery where type Rs URLCrawlErrorscountsQuery = URLCrawlErrorsCountsQueryResponse type Scopes URLCrawlErrorscountsQuery = '["https://www.googleapis.com/auth/webmasters", "https://www.googleapis.com/auth/webmasters.readonly"] requestClient URLCrawlErrorscountsQuery'{..} = go _uceqSiteURL _uceqPlatform _uceqCategory (Just _uceqLatestCountsOnly) (Just AltJSON) webmasterToolsService where go = buildClient (Proxy :: Proxy URLCrawlErrorscountsQueryResource) mempty
rueshyna/gogol
gogol-webmaster-tools/gen/Network/Google/Resource/Webmasters/URLCrawlErrorscounts/Query.hs
mpl-2.0
4,967
0
17
1,160
552
327
225
90
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, ConstraintKinds, TypeSynonymInstances, LiberalTypeSynonyms #-}module Has ( Has(..) , MonadHas , peek , peeks , focusIO ) where import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Reader (MonadReader, ReaderT(..), reader) class Has a c where view :: c -> a instance Has a a where view = id type MonadHas a s m = (Functor m, Applicative m, MonadReader s m, Has a s) {-# INLINE peek #-} peek :: (MonadReader c m, Has a c) => m a peek = reader view {-# INLINE peeks #-} peeks :: (MonadReader c m, Has a c) => (a -> b) -> m b peeks f = reader (f . view) {-# INLINE focusReader #-} focusReader :: Has a c => (a -> m b) -> ReaderT c m b focusReader f = ReaderT (f . view) {-# INLINE[2] focusIO #-} focusIO :: (MonadIO m, MonadHas a c m) => (a -> IO b) -> m b focusIO f = liftIO . f =<< peek {-# RULES "focusIO/ReaderT" focusIO = focusReader #-}
databrary/databrary
src/Has.hs
agpl-3.0
933
0
9
196
341
189
152
27
1
{-# LANGUAGE DeriveGeneric #-} module Papstehrenwort.Types where import Protolude import Data.Time.Calendar (Day) import qualified Network.URL as U import Data.Aeson (ToJSON(..), FromJSON(..)) -- | We wrap the @U.URL@ type because it works with Text -- and does not provide aeson instances newtype URL = URL U.URL deriving (Eq, Show, Generic) exportURL :: URL -> Text exportURL (URL u) = toS $ U.exportURL u importURL :: Text -> Maybe URL importURL t = URL <$> U.importURL (toS t) -- | A task that needs to be repeatet regularly data Task = Task { tTitle :: Text , tDescription :: Text , tHow :: Maybe Text , tUrl :: Maybe URL , tRecur :: Integer , tStart :: Day } deriving (Show, Eq, Generic) -- | A splasher is a papstehrenwort user data Splasher = Splasher { sNick :: Text , sMail :: Text } deriving (Show, Eq, Generic) instance ToJSON Task instance ToJSON URL where toJSON = toJSON . exportURL
openlab-aux/papstehrenwort
src/Papstehrenwort/Types.hs
agpl-3.0
929
0
9
189
272
157
115
26
1
module Test(test1, test2, test3, repeatedTest) where import System.Random import Test.HUnit import Data.List data ErrorInfo = ErrorInfo [String] String -- Operand strings and error string addOperand :: (Show a) => a -> ErrorInfo -> ErrorInfo addOperand a (ErrorInfo ops err) = ErrorInfo ((show a):ops) err instance Show ErrorInfo where show (ErrorInfo ops err) | (op:[]) <- ops = err ++ " Operand is " ++ op | otherwise = err ++ " Operands are " ++ (intercalate ", " ops) runTest1 :: (Random a, Show a, Eq b, Show b) => (a -> b) -> (a -> IO b) -> IO (Maybe ErrorInfo) runTest1 goldenF testF = do op <- randomIO test <- testF op let golden = goldenF op return (if test == golden then Nothing else Just (ErrorInfo [show op] ("Expecting " ++ show golden ++ ", but got " ++ show test ++ "."))) runTest2 :: (Random a, Show a, Random b, Show b, Eq c, Show c) => (a -> b -> c) -> (a -> b -> IO c) -> IO (Maybe ErrorInfo) runTest2 goldenF testF = do a <- randomIO (fmap $ fmap $ addOperand a) $ runTest1 (goldenF a) (testF a) runTest3 :: (Random a, Show a, Random b, Show b, Random c, Show c, Eq d, Show d) => (a -> b -> c -> d) -> (a -> b -> c -> IO d) -> IO (Maybe ErrorInfo) runTest3 goldenF testF = do a <- randomIO (fmap $ fmap $ addOperand a) $ runTest2 (goldenF a) (testF a) -- | Test unary function test1 :: (Random a, Show a, Eq b, Show b) => (a -> b) -> (a -> IO b) -> IO (Maybe String) test1 goldenF testF = fmap (fmap show) $ runTest1 goldenF testF test2 :: (Random a, Show a, Random b, Show b, Eq c, Show c) => (a -> b -> c) -> (a -> b -> IO c) -> IO (Maybe String) test2 goldenF testF = fmap (fmap show) $ runTest2 goldenF testF test3 :: (Random a, Show a, Random b, Show b, Random c, Show c, Eq d, Show d) => (a -> b -> c -> d) -> (a -> b -> c -> IO d) -> IO (Maybe String) test3 goldenF testF = fmap (fmap show) $ runTest3 goldenF testF repeatedTest :: Int -> IO (Maybe String) -> Test repeatedTest n test = TestCase ((sequence $ replicate n test) >>= assertAllNothing) where assertAllNothing [] = return () assertAllNothing (x:xs) | Just msg <- x = assertFailure msg | Nothing <- x = assertAllNothing xs
yjwen/hada
test/Test.hs
lgpl-3.0
2,590
0
18
908
1,113
557
556
43
2
{-# LANGUAGE TupleSections #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} -- |Contains the 'Successor' type which is used to -- construct crawl trees, together with a set of useful -- helper functions for creating 'Successor' functions. -- -- For examples of successor functions, see @Galleries.Examples@. module Crawling.Hephaestos.Fetch.Successor ( -- *Types ForestResult(..), results, metadataFiles, downloadFolder, Successor, HTMLSuccessor, StrictSuccessor, FetchResult(..), blob, plainText, binaryData, xmlResult, info, failure, isLeaf, SuccessorNode(..), SuccessorNode', SuccessorNodeSum(..), HasExt(..), -- *Helper functions relating to state and failure voidNode, noneAsFailure, -- *Discriminator functions getURL, getError, isBlob, isInner, isBinaryData, isPlainText, isXmlResult, isFailure, isInfo, ) where import Prelude hiding (lex, FilePath) import Control.Exception import Control.Lens (makeLenses) import Data.ByteString.Lazy (ByteString) import Control.Monad.Trans.Resource (ResourceT) import qualified Data.Conduit as Con import Data.Functor.Monadic import qualified Data.List.Safe as LS import Data.Maybe (fromMaybe) import Data.Text.Lazy hiding (pack, toStrict) import Data.Void import Data.UUID (UUID) import Filesystem.Path.CurrentOS import Network.URI (URI) import Text.XML.HXT.DOM.TypeDefs import qualified Crawling.Hephaestos.Fetch.Types as FT -- |A function which extracts a number of successor nodes from a page. type Successor e i a = URI -- ^The URI of the input -> ResourceT IO (Con.Source (ResourceT IO) ByteString) -- ^The input as a byte string. -> a -- ^The input state. -> IO [SuccessorNode e i a] -- ^The list of resultant leaves and nodes. -- |A Successor which only works on HTML input. See 'htmlSuccessor'. type HTMLSuccessor e i a = URI -> XmlTree -> a -> IO [SuccessorNode e i a] -- |A Successor which consumes the page contents as one instead of streaming them. type StrictSuccessor e i a = URI -> ByteString -> a -> IO [SuccessorNode e i a] -- |Result of a fetching operation. data FetchResult e i = -- |A URL which is to be downloaded. Blob{fetchIdent::Maybe i, blobURL::URI, reqMod::FT.RequestConfig} -- |An inner node in a search treee. | Inner{innerURL::URI, reqMod::FT.RequestConfig} -- |Some plain text without any deeper semantic value. | PlainText{fetchIdent::Maybe i, fromPlainText::Text} -- |A ByteString (binary data). | BinaryData{fetchIdent::Maybe i, fromBinary::ByteString} -- |An XML tree. | XmlResult{fetchIdent::Maybe i, fromXmlResult::XmlTree} -- |A failure which stores an error and the original node, if present. | Failure{failureError::e, -- ^The error which occurred. originalNode::Maybe (FetchResult e i, Maybe FilePath) -- ^If applicable, the original node which couldn't be saved. -- This is most useful in the case of 'Blob's. } -- |A piece of named auxiliary information, such as a title or an author. | Info{fetchIdent::Maybe i, infoKey::Text, infoValue::Text} -- |A node generated by a 'Successor' function. -- See 'simpleNode', 'voidNode' and 'redNode' for smart constructors. data SuccessorNode e i a = SuccessorNode {nodeState::a, -- ^The new state. nodeRes::FetchResult e i -- ^The node's result. } -- |Results of a downloading operation. data ForestResult i coll b = ForestResult{ -- |Leftover nodes of the download process, i.e. Failures and unknown -- node types that weren't handled. _results :: coll (FT.Path URI, SuccessorNode SomeException i b), -- |The name of the created metadata file(s). _metadataFiles :: [FilePath], -- |Folder into which the files were downloaded. _downloadFolder :: FilePath } makeLenses ''ForestResult -- |A version of 'SuccessorNode' that distinguishes between inner nodes and -- leaf nodes. Leaf nodes have a UUID and a path from the root (needed by -- "Crawling.Hephaestos.Fetch.Forest"). data SuccessorNodeSum coll e i a = InnerSuccessor a (FetchResult e i) | LeafSuccessor a (FetchResult e i) UUID (FT.Path URI) (ForestResult i coll a) -- |Shorthand for @SuccessorNode SomeException i a@ type SuccessorNode' i a = SuccessorNode SomeException i a -- |Functor instance over the node state. instance Functor (SuccessorNode e i) where fmap f s@SuccessorNode{nodeState=a} = s{nodeState=f a} -- |Selects the first non-EQ element from a list or EQ if no such element exists. lex :: [Ordering] -> Ordering lex = fromMaybe EQ . LS.head . LS.dropWhile (EQ==) -- |Creates a 'SuccessorNode' from a 'FetchResult' and no state. -- No request modifiers will be applied. voidNode :: FetchResult e i -> SuccessorNode e i Void voidNode = SuccessorNode undefined -- |Transforms the identifier of a 'FetchResult'. instance Functor (FetchResult e) where fmap f (Blob i url r) = Blob (fmap f i) url r fmap _ (Inner u r) = Inner u r fmap f (PlainText i t) = PlainText (fmap f i) t fmap f (BinaryData i t) = BinaryData (fmap f i) t fmap f (XmlResult i t) = XmlResult (fmap f i) t fmap _ (Failure e Nothing) = Failure e Nothing fmap f (Failure e (Just (r, fp))) = Failure e $ Just (fmap f r, fp) fmap f (Info i k v) = Info (fmap f i) k v -- |Gets the URL of a Blob or an Inner. For all other result types, returns Nothing. getURL :: FetchResult e i -> Maybe URI getURL (Blob _ url _) = Just url getURL (Inner url _) = Just url getURL _ = Nothing -- |Gets the error from a Failure. getError :: FetchResult e i -> Maybe e getError (Failure e _) = Just e getError _ = Nothing -- |Constructs a 'Blob' without an identifier. blob :: URI -> FT.RequestConfig -> FetchResult e i blob = Blob Nothing -- |Constructs a 'PlainText' without an identifier. plainText :: Text -> FetchResult e i plainText = PlainText Nothing -- |Constructs a 'BinaryData' without an identifier. binaryData :: ByteString -> FetchResult e i binaryData = BinaryData Nothing -- |Constructs an 'XmlResult' without an identifier. xmlResult :: XmlTree -> FetchResult e i xmlResult = XmlResult Nothing -- |Constructs an 'Info' without an identifier. info :: Text -> Text -> FetchResult e i info = Info Nothing -- |Constructs a failure nodes, wrapping the error into 'SomeException'. failure :: Exception e => e -> Maybe (FetchResult SomeException i, Maybe FilePath) -> FetchResult SomeException i failure e = Failure (SomeException e) instance (Show i, Show e) => Show (FetchResult e i) where show (Blob i uri _) = "Blob " LS.++ show i LS.++ " " LS.++ show uri show (Inner uri _) = "Inner" LS.++ " " LS.++ show uri show (PlainText i t) = "PlainText " LS.++ show i LS.++ " " LS.++ show t show (BinaryData i t) = "BinaryData " LS.++ show i LS.++ " " LS.++ show t show (XmlResult i t) = "XmlResult " LS.++ show i LS.++ " "LS.++ show t show (Failure e t) = "Failure " LS.++ show e LS.++ " " LS.++ show t show (Info i k v) = "Info " LS.++ show i LS.++ " " LS.++ show k LS.++ " " LS.++ show v -- |Types which can be saved to disk and have an associated file extension. class HasExt a where -- |Returns the extension of a given value. ext :: a -> Text -- |The file extension associated with a specific 'FetchResult'. -- The values are: -- -- * @.bin@ for 'Blob', -- * @.txt@ for 'PlainText', -- * @.xml@ for 'XmlResult', -- * @.bin@ for 'BinaryData', -- * @.info@ for 'Info'. -- * @.error@ for 'Failure', -- * @.inner@ for 'Inner'. instance HasExt (FetchResult e i) where ext Blob{} = "blob" ext Inner{} = "inner" ext PlainText{} = "txt" ext BinaryData{} = "bin" ext XmlResult{} = "xml" ext Failure{} = "error" ext Info{} = "info" -- |True iff the result is not of type 'Inner'. isLeaf :: FetchResult e i -> Bool isLeaf Inner{} = False isLeaf _ = True instance Ord XNode where compare (XText s) (XText t) = compare s t compare (XBlob s) (XBlob t) = compare s t compare (XCharRef s) (XCharRef t) = compare s t compare (XEntityRef s) (XEntityRef t) = compare s t compare (XCmt s) (XCmt t) = compare s t compare (XCdata s) (XCdata t) = compare s t compare (XPi s s') (XPi t t') = lex [compare s t, compare s' t'] compare (XTag s s') (XTag t t') = lex [compare s t, compare s' t'] compare (XDTD s s') (XDTD t t') = lex [compare s t, compare s' t'] compare (XAttr s) (XAttr t) = compare s t compare (XError s s') (XError t t') = lex [compare s t, compare s' t'] compare s t = compare (pos s) (pos t) where pos (XText _) = 0 pos (XBlob _) = 1 pos (XCharRef _) = 2 pos (XEntityRef _) = 3 pos (XCmt _) = 4 pos (XCdata _) = 5 pos (XPi _ _) = 6 pos (XTag _ _) = 7 pos (XDTD _ _) = 8 pos (XAttr _) = 9 pos (XError _ _) = 10 instance (Ord i, Ord e) => Eq (FetchResult e i) where x == y = compare x y == EQ instance (Ord i, Ord e) => Ord (FetchResult e i) where compare (Blob i s _) (Blob j t _) = lex [compare i j, compare s t] compare (Inner s _) (Inner t _) = compare s t compare (PlainText i s) (PlainText j t) = lex [compare i j, compare s t] compare (BinaryData i s) (BinaryData j t) = lex [compare i j, compare s t] compare (XmlResult i s) (XmlResult j t) = lex [compare i j, compare s t] compare (Failure s s') (Failure t t') = lex [compare s t, compare s' t'] compare (Info i k v) (Info j k' v') = lex [compare i j, compare k k', compare v v'] compare s t = compare (pos s) (pos t) where pos :: FetchResult e i -> Int pos Blob{} = 0 pos Inner{} = 1 pos PlainText{} = 2 pos BinaryData{} = 3 pos XmlResult{} = 4 pos Failure{} = 5 pos Info{} = 6 -- |Automatically creates a failure node if the result -- set is empty. This is useful for when at least 1 result -- is expected. noneAsFailure :: e -- ^The error to create. -> Maybe (FetchResult e i) -- ^The original node. -> [FetchResult e i] -- ^The result set @S@ to check for emptiness. -> [FetchResult e i] -- ^@S@ if @not.null $ S@, @[f]@ -- otherwise (for a new 'Failure' @f@). noneAsFailure e b [] = [Failure e $ b >$> (,Nothing)] noneAsFailure _ _ (x:xs) = x:xs -- |Returns True iff the result is a Blob. isBlob :: FetchResult e i -> Bool isBlob Blob{} = True isBlob _ = False -- |Returns True iff the result is an inner node. isInner :: FetchResult e i -> Bool isInner Inner{} = True isInner _ = False -- |Returns True iff the result is binary data. isBinaryData :: FetchResult e i -> Bool isBinaryData BinaryData{} = True isBinaryData _ = False -- |Returns True iff the result is plain text. isPlainText :: FetchResult e i -> Bool isPlainText PlainText{} = True isPlainText _ = False -- |Returns True iff the result is an XML tree. isXmlResult :: FetchResult e i -> Bool isXmlResult XmlResult{} = True isXmlResult _ = False -- |Returns True iff the result is a failure. isFailure :: FetchResult e i -> Bool isFailure Failure{} = True isFailure _ = False -- |Returns True iff the result is auxiliary information. isInfo :: FetchResult e i -> Bool isInfo Info{} = True isInfo _ = False
jtapolczai/Hephaestos
Crawling/Hephaestos/Fetch/Successor.hs
apache-2.0
11,838
0
12
3,034
3,400
1,805
1,595
210
1
-- * Lack of extensibility in the data type view module ExtI where import qualified Intro1 as Old -- Attempt to add a new expression form: multiplication -- We would like to reuse the old code, in Intro1.hs (show the code) -- We don't want to extend the data type declaration in Intro1.hs -- as that would require adjusting and recompiling all the code -- that uses Intro1.hs (in particular, all the interpreters) data Exp = EOld Old.Exp | Mul Exp Exp -- add a new variant -- An extended sample expression tim2 = Mul (EOld (Old.Lit 7)) (EOld Old.ti1) -- tim2 is a bit ugly. But this is only a part of a problem -- Why does the following fails to type check? {- tim1 = EOld (Old.Add (Old.Lit 7) (Old.Neg (Mul (EOld (Old.Lit 1)) (EOld (Old.Lit 2))))) -} -- So, we are stuck. Data type variants are NOT extensible. main = do print "Done"
mjhopkins/ttfi
src/haskell/ExtI.hs
apache-2.0
863
0
10
184
83
51
32
7
1
module Day16pt2 where import Data.List.Split type Line = (String, [(String, Int)]) main :: IO () main = do f <- readFile "input.txt" let lns = map parse $ map (splitOn " ") (lines f) fxs = [(adjust "children" (==3)), (adjust "cats" (>7)), (adjust "samoyeds" (==2)), (adjust "pomeranians" (<3)), (adjust "akitas" (==0)), (adjust "vizslas" (==0)), (adjust "goldfish" (<5)), (adjust "trees" (>3)), (adjust "cars" (==2)), (adjust "perfumes" (==1))] final = foldl (\acc x -> filter x acc) lns fxs putStrLn $ "Optimal: " ++ show final adjust :: String -> (Int -> Bool) -> Line -> Bool adjust str b (numb, xs) = case lookup str xs of Nothing -> True Just cat -> b cat parse :: [String] -> Line parse [_name,numb,pt1,pt1v,pt2,pt2v,pt3,pt3v] = (numb, [(init pt1, read $ init pt1v), (init pt2, read $ init pt2v), (init pt3, read pt3v)])
ksallberg/adventofcode
2015/src/Day16pt2.hs
bsd-2-clause
1,045
0
13
357
457
255
202
29
2
{-# LANGUAGE CPP #-} module Manager (tests) where import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Exception (finally) import Control.Monad (replicateM_) import Foreign.C.Error (throwErrnoIfMinus1) import Foreign.Marshal (alloca) import Network.Socket hiding (shutdown) import System.Event.Control (setNonBlockingFD) import System.Event.Internal (Backend) import System.Event.Manager import System.Posix.IO (createPipe) import System.Posix.Internals (c_close, c_read, c_write) import System.Posix.Types (Fd) import Test.HUnit (Assertion, assertBool, assertEqual) import qualified System.Event.EPoll as EPoll import qualified System.Event.KQueue as KQueue import qualified System.Event.Poll as Poll import qualified Test.Framework as F import qualified Test.Framework.Providers.HUnit as F withBackend :: IO Backend -> (EventManager -> IO a) -> IO a withBackend what act = do mgr <- newWith =<< what done <- newEmptyMVar forkIO $ loop mgr >> putMVar done () a <- act mgr `finally` shutdown mgr takeMVar done assertBool "finished" =<< finished mgr return a -- Ensure that we can create and tear down many backends without -- leaking limited resources such as file descriptors. createN :: IO Backend -> Assertion createN what = replicateM_ 10000 . withBackend what $ \_mgr -> return () -- Send and receive a single byte through a pipe. pipe :: IO Backend -> Assertion pipe what = withBackend what $ \mgr -> uncurry (fdPair mgr) =<< createPipe -- Send and receive a single byte through a Unix socket pair. socketpair :: IO Backend -> Assertion socketpair what = withBackend what $ \mgr -> do (a,b) <- socketPair AF_UNIX Stream defaultProtocol fdPair mgr (fromSocket a) (fromSocket b) where fromSocket (MkSocket a _ _ _ _) = fromIntegral a -- Send and receive a single byte through a connected pair of file -- descriptors. fdPair :: EventManager -> Fd -> Fd -> IO () fdPair mgr rd wr = go `finally` do c_close (fromIntegral rd) c_close (fromIntegral wr) return () where go = do #if __GLASGOW_HASKELL__ > 611 setNonBlockingFD (fromIntegral rd) True setNonBlockingFD (fromIntegral wr) True #else setNonBlockingFD (fromIntegral rd) setNonBlockingFD (fromIntegral wr) #endif done <- newEmptyMVar let canRead fdk evt = do assertEqual "read fd" (keyFd fdk) rd assertEqual "read event" evt evtRead alloca $ \p -> do n <- throwErrnoIfMinus1 "read" $ c_read (fromIntegral (keyFd fdk)) p 1 assertEqual "read 1 byte" n 1 putMVar done () canWrite fdk evt = do unregisterFd mgr fdk assertEqual "write fd" (keyFd fdk) wr assertEqual "write event" evt evtWrite alloca $ \p -> do n <- throwErrnoIfMinus1 "write" $ c_write (fromIntegral (keyFd fdk)) p 1 assertEqual "wrote 1 byte" n 1 registerFd mgr canRead rd evtRead registerFd mgr canWrite wr evtWrite takeMVar done backendTests :: IO Backend -> [F.Test] backendTests what = map ($what) [ F.testCase "createN" . createN , F.testCase "pipe" . pipe , F.testCase "socketpair" . socketpair ] tests :: F.Test tests = F.testGroup "System.Event.Manager" [ group | (available, group) <- [ (EPoll.available, F.testGroup "EPoll" $ backendTests EPoll.new) , (KQueue.available, F.testGroup "KQueue" $ backendTests KQueue.new) , (Poll.available, F.testGroup "Poll" $ backendTests Poll.new) ], available]
tibbe/event
tests/Manager.hs
bsd-2-clause
3,639
0
24
826
1,071
550
521
77
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} {- - Copyright (c) 2015, Peter Lebbing <peter@digitalbrains.com> - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. -} module Simul.LT24.UARTInterface ( module Simul.LT24.UARTInterface , module Simul.Common , module LT24.UARTInterface , module CLaSH.Prelude ) where import CLaSH.Prelude import Simul.Common import LT24.UARTInterface import qualified LT24.LT24 as LT24 simulateCommandIf :: [((Bool, Unsigned 8), Bool, Bool, Bool, Unsigned 16)] -> [( (Bool, Unsigned 8, LT24.Action, Unsigned 16, Bit) , ((Bool, Unsigned 8), Bool, Bool, Bool, Unsigned 16))] simulateCommandIf = (\i -> zip (simulate (pack . commandIf . unpack) i) i) . (++ repeat ((False, 0), False, True, True, 0)) data ELCI = RX (Unsigned 8) | RXV Bool | TXDone Bool | Ready Bool | DOut (Unsigned 16) trELCI (rxoF, rxoV, txDone, ready, dout) (RX d ) = ((False, d), rxoV , txDone , ready , dout ) trELCI (rxoF, rxoV, txDone, ready, dout) (RXV rxoV' ) = (rxoF , rxoV', txDone , ready , dout ) trELCI (rxoF, rxoV, txDone, ready, dout) (TXDone txDone') = (rxoF , rxoV , txDone', ready , dout ) trELCI (rxoF, rxoV, txDone, ready, dout) (Ready ready' ) = (rxoF , rxoV , txDone , ready', dout ) trELCI (rxoF, rxoV, txDone, ready, dout) (DOut dout' ) = (rxoF , rxoV , txDone , ready , dout') simulatePassCommand :: [(Unsigned 8, Unsigned 16, Bool, Bool)] -> [( (LT24.Action, Unsigned 16, Bit, Bool) , (Unsigned 8, Unsigned 16, Bool, Bool))] simulatePassCommand = (\i -> zip (simulate pc i) i) . (++ repeat (0, 0, False, True)) where pc = (pack . (passCommand <^> (PCIdle, 0, 0, L)) . unpack) passCommandStimulus1 ::[(Unsigned 8, Unsigned 16, Bool, Bool)] passCommandStimulus1 = [ ( 0 , 0 , True , True ) , ( 1 , 11 , True , False ) , ( 1 , 11 , True , False ) , ( 1 , 11 , True , True ) , ( 2 , 5 , True , False ) , ( 2 , 8 , True , True ) , ( 1 , 58 , True , False ) , ( 1 , 58 , True , True ) , ( 2 , 5 , True , True ) , ( 2 , 5 , True , False ) , ( 2 , 5 , True , False ) , ( 2 , 5 , True , True ) , ( 0 , 0 , False , True ) , ( 0 , 0 , False , False ) , ( 0 , 0 , False , True ) , ( 0 , 0 , False , True ) , ( 1 , 45 , True , True ) , ( 0 , 0 , False , False ) ] passCommandStimulus1Expected :: [( (LT24.Action, Unsigned 16, Bit, Bool) , (Unsigned 8, Unsigned 16, Bool, Bool))] passCommandStimulus1Expected = [ ( ( LT24.Reset , 0 , L , True ) , ( 0 , 0 , True , True ) ) , ( ( LT24.Command , 11 , L , False ) , ( 1 , 11 , True , False ) ) , ( ( LT24.Command , 11 , L , False ) , ( 1 , 11 , True , False ) ) , ( ( LT24.Command , 11 , L , True ) , ( 1 , 11 , True , True ) ) , ( ( LT24.Write , 5 , L , False ) , ( 2 , 5 , True , False ) ) , ( ( LT24.Write , 5 , L , True ) , ( 2 , 8 , True , True ) ) , ( ( LT24.Command , 58 , L , False ) , ( 1 , 58 , True , False ) ) , ( ( LT24.Command , 58 , L , True ) , ( 1 , 58 , True , True ) ) , ( ( LT24.Command , 58 , L , False ) , ( 2 , 5 , True , True ) ) , ( ( LT24.Write , 5 , L , False ) , ( 2 , 5 , True , False ) ) , ( ( LT24.Write , 5 , L , False ) , ( 2 , 5 , True , False ) ) , ( ( LT24.Write , 5 , L , True ) , ( 2 , 5 , True , True ) ) , ( ( LT24.Write , 5 , L , False ) , ( 0 , 0 , False , True ) ) , ( ( LT24.NOP , 5 , L , False ) , ( 0 , 0 , False , False ) ) , ( ( LT24.NOP , 5 , L , False ) , ( 0 , 0 , False , True ) ) , ( ( LT24.NOP , 5 , L , False ) , ( 0 , 0 , False , True ) ) , ( ( LT24.Command , 45 , L , True ) , ( 1 , 45 , True , True ) ) , ( ( LT24.NOP , 45 , L , False ) , ( 0 , 0 , False , False ) ) , ( ( LT24.NOP , 45 , L , False ) , ( 0 , 0 , False , True ) ) , ( ( LT24.NOP , 45 , L , False ) , ( 0 , 0 , False , True ) ) ]
DigitalBrains1/clash-lt24
Simul/LT24/UARTInterface.hs
bsd-2-clause
5,412
0
13
1,662
1,719
1,089
630
77
1
{-# LANGUAGE BangPatterns, ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} import Control.DeepSeq import Control.Monad import Text.JSON import Data.Time.Clock import System.Environment (getArgs) import System.IO instance NFData JSValue where rnf JSNull = () rnf (JSBool b) = rnf b rnf (JSRational b r) = rnf b `seq` rnf r `seq` () rnf (JSString s) = rnf (fromJSString s) rnf (JSArray vs) = rnf vs rnf (JSObject kvs) = rnf (fromJSObject kvs) main = do (cnt:args) <- getArgs let count = read cnt :: Int forM_ args $ \arg -> do putStrLn $ arg ++ ":" start <- getCurrentTime let loop !good !bad | good+bad >= count = return (good, bad) | otherwise = do s <- readFile arg case decodeStrict s of Ok (v::JSValue) -> loop (good+1) 0 _ -> loop 0 (bad+1) (good, _) <- loop 0 0 end <- getCurrentTime putStrLn $ " " ++ show good ++ " good, " ++ show (diffUTCTime end start)
moonKimura/aeson-0.6.2.1
benchmarks/JsonParse.hs
bsd-3-clause
1,002
0
22
281
412
201
211
31
2
{-# LANGUAGE BangPatterns #-} module Y2017.Day22 (answer1, answer2) where import Control.Monad import Data.Foldable import qualified Data.HashMap.Strict as Map answer1, answer2 :: IO () answer1 = do grid <- parseInput let initialState = ((0,-1), (0,0), grid, 0) let n = 10000 let (_, _, _, c) = foldl' (\s _ -> step s) initialState [1..n] print c answer2 = do grid <- parseInput let initialState = ((0,-1), (0,0), grid, 0) let n = 10000000 let (_, _, _, c) = foldl' (\s _ -> step2 s) initialState [1..n] print c data Status = Clean | Infected | Weakened | Flagged deriving Show type Coord = (Int, Int) type Grid = Map.HashMap Coord Status type Direction = Coord step :: (Direction, Coord, Grid, Int) -> (Direction, Coord, Grid, Int) step (dir, pos, grid, !counter) = let node = Map.lookupDefault Clean pos grid dir' = case node of Infected -> turnRight dir Clean -> turnLeft dir _ -> dir node' = switchStatus node grid' = Map.insert pos node' grid pos' = pos +: dir' counter' = if isInfected node' then counter + 1 else counter in (dir', pos', grid', counter') switchStatus Infected = Clean switchStatus Clean = Infected switchStatus x = x isInfected Infected = True isInfected _ = False step2 :: (Direction, Coord, Grid, Int) -> (Direction, Coord, Grid, Int) step2 (dir, pos, grid, !counter) = let node = Map.lookupDefault Clean pos grid dir' = case node of Clean -> turnLeft dir Weakened -> dir Infected -> turnRight dir Flagged -> turnRight (turnRight dir) node' = switchStatus2 node grid' = Map.insert pos node' grid pos' = pos +: dir' counter' = if isInfected node' then counter + 1 else counter in (dir', pos', grid', counter') switchStatus2 Clean = Weakened switchStatus2 Weakened = Infected switchStatus2 Infected = Flagged switchStatus2 Flagged = Clean turnLeft (x, y) = (y, -x) turnRight (x, y) = (-y, x) (a, b) +: (c, d) = (a + c, b + d) parseInput = do rows <- lines <$> readFile "./data/2017/day22.txt" let cy = (length rows - 1) `div` 2 let cx = (length (head rows) - 1) `div` 2 let rowsWithIdx = zip [-cy ..] rows let as = [ ((x, y), c) | (y, row) <- rowsWithIdx , (x, k ) <- zip [-cx ..] row , let c = if k == '#' then Infected else Clean ] pure $ Map.fromList as testInput :: Grid testInput = Map.fromList [((1,-1), Infected), ((-1,0), Infected)]
geekingfrog/advent-of-code
src/Y2017/Day22.hs
bsd-3-clause
2,644
0
16
786
1,063
584
479
72
5
{-# LANGUAGE CPP, DeriveDataTypeable, UnboxedTuples #-} {-# OPTIONS_HADDOCK not-home #-} -- | -- Module : Data.Text.Internal -- Copyright : (c) 2008, 2009 Tom Harper, -- (c) 2009, 2010 Bryan O'Sullivan, -- (c) 2009 Duncan Coutts -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : GHC -- -- A module containing private 'Text' internals. This exposes the -- 'Text' representation and low level construction functions. -- Modules which extend the 'Text' system may need to use this module. -- -- You should not use this module unless you are determined to monkey -- with the internals, as the functions here do just about nothing to -- preserve data invariants. You have been warned! #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) #include "MachDeps.h" #endif module Data.Text.Internal ( -- * Types -- $internals Text(..) -- * Construction , text , textP -- * Safety , safe -- * Code that must be here for accessibility , empty -- * Utilities , firstf -- * Checked multiplication , mul , mul32 , mul64 -- * Debugging , showText ) where #if defined(ASSERTS) import Control.Exception (assert) #endif import Data.Bits import Data.Int (Int32, Int64) import Data.Text.Internal.Unsafe.Char (ord) import Data.Typeable (Typeable) import qualified Data.Text.Array as A -- | A space efficient, packed, unboxed Unicode text type. data Text = Text {-# UNPACK #-} !A.Array -- payload (Word16 elements) {-# UNPACK #-} !Int -- offset (units of Word16, not Char) {-# UNPACK #-} !Int -- length (units of Word16, not Char) deriving (Typeable) -- | Smart constructor. text_ :: A.Array -> Int -> Int -> Text text_ arr off len = #if defined(ASSERTS) let c = A.unsafeIndex arr off alen = A.length arr in assert (len >= 0) . assert (off >= 0) . assert (alen == 0 || len == 0 || off < alen) . assert (len == 0 || c < 0xDC00 || c > 0xDFFF) $ #endif Text arr off len {-# INLINE text_ #-} -- | /O(1)/ The empty 'Text'. empty :: Text empty = Text A.empty 0 0 {-# INLINE [1] empty #-} -- | Construct a 'Text' without invisibly pinning its byte array in -- memory if its length has dwindled to zero. text :: A.Array -> Int -> Int -> Text text arr off len | len == 0 = empty | otherwise = text_ arr off len {-# INLINE text #-} textP :: A.Array -> Int -> Int -> Text {-# DEPRECATED textP "Use text instead" #-} textP = text -- | A useful 'show'-like function for debugging purposes. showText :: Text -> String showText (Text arr off len) = "Text " ++ show (A.toList arr off len) ++ ' ' : show off ++ ' ' : show len -- | Map a 'Char' to a 'Text'-safe value. -- -- UTF-16 surrogate code points are not included in the set of Unicode -- scalar values, but are unfortunately admitted as valid 'Char' -- values by Haskell. They cannot be represented in a 'Text'. This -- function remaps those code points to the Unicode replacement -- character (U+FFFD, \'&#xfffd;\'), and leaves other code points -- unchanged. safe :: Char -> Char safe c | ord c .&. 0x1ff800 /= 0xd800 = c | otherwise = '\xfffd' {-# INLINE safe #-} -- | Apply a function to the first element of an optional pair. firstf :: (a -> c) -> Maybe (a,b) -> Maybe (c,b) firstf f (Just (a, b)) = Just (f a, b) firstf _ Nothing = Nothing -- | Checked multiplication. Calls 'error' if the result would -- overflow. mul :: Int -> Int -> Int #if WORD_SIZE_IN_BITS == 64 mul a b = fromIntegral $ fromIntegral a `mul64` fromIntegral b #else mul a b = fromIntegral $ fromIntegral a `mul32` fromIntegral b #endif {-# INLINE mul #-} infixl 7 `mul` -- | Checked multiplication. Calls 'error' if the result would -- overflow. mul64 :: Int64 -> Int64 -> Int64 mul64 a b | a >= 0 && b >= 0 = mul64_ a b | a >= 0 = -mul64_ a (-b) | b >= 0 = -mul64_ (-a) b | otherwise = mul64_ (-a) (-b) {-# INLINE mul64 #-} infixl 7 `mul64` mul64_ :: Int64 -> Int64 -> Int64 mul64_ a b | ahi > 0 && bhi > 0 = error "overflow" | top > 0x7fffffff = error "overflow" | total < 0 = error "overflow" | otherwise = total where (# ahi, alo #) = (# a `shiftR` 32, a .&. 0xffffffff #) (# bhi, blo #) = (# b `shiftR` 32, b .&. 0xffffffff #) top = ahi * blo + alo * bhi total = (top `shiftL` 32) + alo * blo {-# INLINE mul64_ #-} -- | Checked multiplication. Calls 'error' if the result would -- overflow. mul32 :: Int32 -> Int32 -> Int32 mul32 a b = case fromIntegral a * fromIntegral b of ab | ab < min32 || ab > max32 -> error "overflow" | otherwise -> fromIntegral ab where min32 = -0x80000000 :: Int64 max32 = 0x7fffffff {-# INLINE mul32 #-} infixl 7 `mul32` -- $internals -- -- Internally, the 'Text' type is represented as an array of 'Word16' -- UTF-16 code units. The offset and length fields in the constructor -- are in these units, /not/ units of 'Char'. -- -- Invariants that all functions must maintain: -- -- * Since the 'Text' type uses UTF-16 internally, it cannot represent -- characters in the reserved surrogate code point range U+D800 to -- U+DFFF. To maintain this invariant, the 'safe' function maps -- 'Char' values in this range to the replacement character (U+FFFD, -- \'&#xfffd;\'). -- -- * A leading (or \"high\") surrogate code unit (0xD800–0xDBFF) must -- always be followed by a trailing (or \"low\") surrogate code unit -- (0xDC00-0xDFFF). A trailing surrogate code unit must always be -- preceded by a leading surrogate code unit.
robinp/nemnem
tsrc/DataTextInternal.hs
bsd-3-clause
5,791
2
16
1,465
1,116
624
492
81
1
-- (C) vasylp https://github.com/vasylp/hgettext/blob/master/src/hgettext.hs import qualified Language.Haskell.Exts.Annotated as H import System.Environment import System.Console.GetOpt import Data.Time import System.Locale (defaultTimeLocale) import Data.Generics.Uniplate.Data import Distribution.Simple.PreProcess.Unlit import Data.List import Data.Char import Data.Ord import Data.Function (on) import System.FilePath import Data.Version (showVersion) version = undefined -- import Paths_hgettext (version) data Options = Options { outputFile :: String, keywords :: [String], printVersion :: Bool } deriving Show options :: [OptDescr (Options->Options)] options = [ Option ['o'] ["output"] (ReqArg (\o opts -> opts {outputFile = o}) "FILE") "write output to specified file", Option ['d'] ["default-domain"] (ReqArg (\d opts -> opts {outputFile = d ++ ".po"}) "NAME") "use NAME.po instead of messages.po", Option ['k'] ["keyword"] (ReqArg (\d opts -> opts {keywords = d: keywords opts}) "WORD") "function names, in which searched words are wrapped. Can be used multiple times, for multiple funcitons", Option [] ["version"] (NoArg (\opts -> opts {printVersion = True})) "print version of hgettexts" ] defaultOptions = Options "messages.po" ["__", "lprintf"] False parseArgs :: [String] -> IO (Options, [String]) parseArgs args = case getOpt Permute options args of (o, n, []) -> return (foldl (flip id) defaultOptions o, n) (_, _, errs) -> ioError (userError (concat errs ++ usageInfo header options)) where header = "Usage: hgettext [OPTION] [INPUTFILE] ..." toTranslate :: [String] -> H.ParseResult (H.Module H.SrcSpanInfo) -> [(H.SrcSpanInfo, String)] toTranslate f (H.ParseOk z) = nub [ (loc, s) | H.App _ (H.Var _ (H.UnQual _ (H.Ident _ x))) (H.Lit _ (H.String loc s _)) <- universeBi z, x `elem` f] toTranslate _ _ = [] -- Create list of messages from a single file formatMessages :: String -> [(H.SrcSpanInfo, String)] -> String formatMessages path l = concat $ map potEntry $ nubBy ((==) `on` snd) $ sortBy (comparing snd) l where potEntry (l, s) = unlines [ "#: " ++ showSrc l, "msgid " ++ (show s), "msgstr \"\"", "" ] showSrc l = path ++ ":" ++ show (H.srcSpanStartLine (H.srcInfoSpan l)) ++ ":" ++ show (H.srcSpanStartColumn (H.srcInfoSpan l)) formatPotFile :: [String] -> IO String formatPotFile lines = do time <- getZonedTime let timeStr = formatTime defaultTimeLocale "%F %R%z" time let header = formatPotHeader timeStr return $ concat $ header: lines where formatPotHeader timeStr = unlines ["# Translation file", "", "msgid \"\"", "msgstr \"\"", "", "\"Project-Id-Version: PACKAGE VERSION\\n\"", "\"Report-Msgid-Bugs-To: \\n\"", "\"POT-Creation-Date: " ++ timeStr ++ "\\n\"", "\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n\"", "\"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n\"", "\"Language-Team: LANGUAGE <LL@li.org>\\n\"", "\"MIME-Version: 1.0\\n\"", "\"Content-Type: text/plain; charset=UTF-8\\n\"", "\"Content-Transfer-Encoding: 8bit\\n\"", ""] process :: Options -> [String] -> IO () process Options{printVersion = True} _ = putStrLn $ "hgettext, version " ++ (showVersion version) process opts fl = do t <- mapM read' fl pot <- formatPotFile $ map (\(n,c) -> formatMessages n $ toTranslate (keywords opts) c) t writeFile (outputFile opts) pot where read' "-" = getContents >>= \c -> return ("-", H.parseFileContents c) read' f = H.parseFile f >>= \m -> return (f, m) main = getArgs >>= parseArgs >>= uncurry process
portnov/localize
hgettext.hs
bsd-3-clause
4,088
0
16
1,124
1,190
643
547
85
2
module Data.Map.TernaryMap ( TernaryMap, insert, singleton, member, size, fromList, lookup, (!), findWithDefault, insertWith, insertWithKey, keys, assocs, elems, null ) where import Data.Map.TernaryMap.Internal (TernaryMap(..)) import Data.Bits import Data.Binary import Control.Monad import Control.Arrow (first) import Prelude hiding (null,lookup) -- | Quickly build a tree without an initial tree. This should be used -- to create an initial tree, using insert there after. singleton :: Ord k => [k] -> v -> TernaryMap k v singleton (x:xs) v = Node x End (singleton xs v) End singleton [] v = Null v End -- | Inserts an entrie into a tree. Values with the same key will be replaced -- with the newer value. insert :: Ord k => [k] -> v -> TernaryMap k v -> TernaryMap k v insert xss@(_:_) v End = singleton xss v insert xss@(_:_) v (Null v' rest) = Null v' $ insert xss v rest insert [] v End = Null v End insert [] v (Node ele l e h) = Node ele (insert [] v l) e h insert [] v (Null _ rest) = Null v rest insert xss@(x:xs) v (Node ele l e h) = case compare x ele of LT -> Node ele (insert xss v l) e h EQ -> Node ele l (insert xs v e) h GT -> Node ele l e (insert xss v h) -- | Inserts a new value into the tree with a given function that combines the new value -- and the old value together to for a new entry. -- -- > insertWith f key newval (fromList [(notkey,val1),(key,oldval)]) == fromList [(notkey,val1),(key,f newval oldval)] insertWith :: Ord k => (v -> v -> v) -> [k] -> v -> TernaryMap k v -> TernaryMap k v insertWith _ xss@(_:_) v End = singleton xss v insertWith f xss@(_:_) v (Null v' rest) = Null (f v v') $ insertWith f xss v rest insertWith _ [] v End = Null v End insertWith f [] v (Node ele l e h) = Node ele (insertWith f [] v l) e h insertWith _ [] v (Null _ rest) = Null v rest insertWith f xss@(x:xs) v (Node ele l e h) = case compare x ele of LT -> Node ele (insertWith f xss v l) e h EQ -> Node ele l (insertWith f xs v e) h GT -> Node ele l e (insertWith f xss v h) -- | Inserts a new value into the tree with a given function that combines the new value -- and the old value together to for a new entry. -- -- > insertWithKey f key newval (fromList [(notkey,val1),(key,oldval)]) == fromList [(notkey,val1),(key,f key newval oldval)] insertWithKey :: Ord k => ([k] -> v -> v -> v) -> [k] -> v -> TernaryMap k v -> TernaryMap k v insertWithKey f ks v m = insertWith (f ks) ks v m -- | Returns true if the `[k]` is a key in the TernaryMap. member :: Ord k => [k] -> TernaryMap k v -> Bool member _ End = False member [] (Null _ _) = True member [] (Node _ l _ _) = member [] l member xss@(_:_) (Null _ rest) = member xss rest member xss@(x:xs) (Node ele l e h) = case compare x ele of LT -> member xss l EQ -> member xs e GT -> member xss h lookup :: Ord k => [k] -> TernaryMap k v -> Maybe v lookup _ End = Nothing lookup [] (Null v _) = Just v lookup [] (Node _ l _ _) = lookup [] l lookup xs (Null _ rest) = lookup xs rest lookup xss@(x:xs) (Node ele l e h) = case compare x ele of LT -> lookup xss l EQ -> lookup xs e GT -> lookup xss h (!) :: Ord k => TernaryMap k v -> [k] -> Maybe v (!) = flip lookup findWithDefault :: Ord k => v -> [k] -> TernaryMap k v -> v findWithDefault k _ End = k findWithDefault _ [] (Null v _) = v findWithDefault k [] (Node _ l _ _) = findWithDefault k [] l findWithDefault k xs (Null _ rest) = findWithDefault k xs rest findWithDefault k xss@(x:xs) (Node ele l e h) = case compare x ele of LT -> findWithDefault k xss l EQ -> findWithDefault k xs e GT -> findWithDefault k xss h -- | Returns the number of non-Val Elems. not exported treeSize :: TernaryMap k v -> Int treeSize End = 0 treeSize (Node _ l e h) = 1 + treeSize l + treeSize e + treeSize h treeSize (Null _ rest) = treeSize rest -- | Counts how many entries there are in the tree. size :: TernaryMap k v -> Int size End = 0 size (Node _ l e h) = size l + size e + size h size (Null _ rest) = 1 + size rest -- | Creates a new tree from a list of 'strings' fromList :: Ord k => [([k],v)] -> TernaryMap k v fromList = foldl (\tree (as,v) -> insert as v tree) empty -- | An empty map. empty :: TernaryMap k v empty = End -- | Makes a list of all the values in the map. elems :: TernaryMap k v -> [v] elems End = [] elems (Node _ l e h) = elems l ++ (elems e ++ elems h) elems (Null v rest) = v : elems rest -- | Returns a (sorted) list of all keys in the map. keys :: TernaryMap k v -> [[k]] keys End = [] keys (Null _ rest) = []:keys rest keys (Node ele l e g) = keys l ++ map (ele:) (keys e) ++ keys g -- | Returns a (sorted) list of all keys in the map. assocs :: TernaryMap k v -> [([k],v)] assocs End = [] assocs (Null v rest) = ([],v):assocs rest assocs (Node ele l e g) = assocs l ++ map (first (ele:)) (assocs e) ++ assocs g -- | Returns true if the map is empty. null :: TernaryMap k v -> Bool null End = True null _ = False -- keySet :: TernaryMap k v -> S.TernarySet a -- keySet End = S.End -- keySet (Node (C x) l e h) = S.Node (S.C x) (keySet l) (keySet e) (keySet h) -- keySet (Node (Val _) l e h) = S.Node (S.Null) (keySet l) (keySet e) (keySet h) instance Functor (TernaryMap k) where fmap _ End = End fmap f (Null v rest) = Null (f v) (fmap f rest) fmap f (Node ele l e h) = Node ele (fmap f l) (fmap f e) (fmap f h) -- | A rather long Binary instance, that uses binary numbers to indicate -- where Ends are efficiently. instance (Binary k, Binary v) => Binary (TernaryMap k v) where put (Node ch End End End) = do putWord8 0 put ch put (Node ch End End h) = do putWord8 1 put ch put h put (Node ch End e End) = do putWord8 2 put ch put e put (Node ch End e h) = do putWord8 3 put ch put e put h put (Node ch l End End) = do putWord8 4 put ch put l put (Node ch l End h) = do putWord8 5 put ch put l put h put (Node ch l e End) = do putWord8 6 put ch put l put e -- General case put (Node ch l e h) = do putWord8 7 put ch put l put e put h put (Null v End) = putWord8 8 >> put v put (Null v rest) = do putWord8 9 put v put rest put End = putWord8 10 get = do tag <- getWord8 case tag of _ | tag < 8 -> do ch <- get l <- if tag `testBit` 2 then get else return End e <- if tag `testBit` 1 then get else return End h <- if tag `testBit` 0 then get else return End return (Node ch l e h) 8 -> liftM (flip Null End) get 9 -> liftM2 Null get get 10 -> return End _ -> error ("Invalid data in binary stream. tag: " ++ show tag)
axman6/TernaryTrees
Data/Map/TernaryMap.hs
bsd-3-clause
7,650
0
16
2,695
2,957
1,466
1,491
169
3
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com> -- Stability : experimental -- Portability : portable -- -- Meshes are the way geometry is built up. A 'Mesh' is a bunch of -- 'Vertices' and a description of faces through a 'VGroup'. ---------------------------------------------------------------------------- module Quaazar.Geometry.Mesh ( -- * Mesh Mesh(Mesh) , meshVertices , meshVGroup , getMeshManager -- * Re-exported modules , module Quaazar.Geometry.Vertex , module Quaazar.Geometry.VGroup ) where import Control.Lens import Data.Aeson import Quaazar.Geometry.Vertex import Quaazar.Geometry.VGroup import Quaazar.System.Loader import Quaazar.System.Resource -- |A mesh is a pair of vertices and vertex group. data Mesh = Mesh { _meshVertices :: Vertices , _meshVGroup :: VGroup } deriving (Eq,Show) makeLenses ''Mesh instance FromJSON Mesh where parseJSON = withObject "mesh" $ \o -> Mesh <$> o .: "vertices" <*> o .: "vgroup" instance Load () Mesh where loadRoot = const "meshes" loadExt = const "qmsh" getMeshManager :: (MonadIO m,MonadScoped IO m,MonadLogger m,MonadError Log m) => m (String -> m Mesh) getMeshManager = getSimpleManager
phaazon/quaazar
src/Quaazar/Geometry/Mesh.hs
bsd-3-clause
1,411
0
11
248
252
150
102
-1
-1
module Pear.Operator (pearAlgebra) where import Pear.Types import Pear.Operator.Lexer (PAlgebra(..)) import Pear.Operator.Concrete -- import Pear.Operator.Algebra -- import Pear.Operator.Stack -- import Pear.Operator.Lexer -- import Pear.Operator.Tree import Text.Parsec.String (Parser) algebra :: PAlgebra Ast algebra = PAlgebra binaryLists unaryLists [integerConstant] pearAlgebra :: Parser Ast pearAlgebra = parseAlgebra algebra
Charlesetc/haskell-parsing
src/Pear/Operator.hs
bsd-3-clause
438
0
6
50
91
55
36
9
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.NB.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale NB Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "0" , "null" ] , examples (NumeralValue 1) [ "1" , "én" , "en" , "Ett" ] , examples (NumeralValue 2) [ "2" , "to" , "et par" ] , examples (NumeralValue 7) [ "7" , "syv" , "sju" ] , examples (NumeralValue 14) [ "14" , "fjorten" ] , examples (NumeralValue 16) [ "16" , "seksten" ] , examples (NumeralValue 17) [ "17" , "sytten" , "søtten" ] , examples (NumeralValue 18) [ "18" , "atten" ] , examples (NumeralValue 20) [ "20" , "tyve" , "Tjue" ] , examples (NumeralValue 30) [ "30" , "tretti" , "tredve" ] , examples (NumeralValue 70) [ "70" , "søtti" , "sytti" ] , examples (NumeralValue 1.1) [ "1,1" , "1,10" , "01,10" ] , examples (NumeralValue 0.77) [ "0,77" , ",77" ] , examples (NumeralValue 100000) [ "100.000" , "100000" , "100K" , "100k" , "100 000" ] , examples (NumeralValue 3000000) [ "3M" , "3000K" , "3000000" , "3.000.000" , "3 000 000" ] , examples (NumeralValue 1200000) [ "1.200.000" , "1200000" , "1,2M" , "1200K" , ",0012G" , "1 200 000" ] , examples (NumeralValue (-1200000)) [ "- 1.200.000" , "-1200000" , "minus 1.200.000" , "negativ 1200000" , "-1,2M" , "-1200K" , "-,0012G" , "-1 200 000" ] , examples (NumeralValue 5000) [ "5 tusen" , "fem tusen" , "5 000" ] , examples (NumeralValue 100) [ "hundre" ] , examples (NumeralValue 5020) [ "fem tusen og tjue" ] , examples (NumeralValue 1e9) [ "en milliard" ] , examples (NumeralValue 1e12) [ "en billion" ] , examples (NumeralValue 1e15) [ "en billiard" ] , examples (NumeralValue 1e18) [ "en trillion" ] , examples (NumeralValue 1e21) [ "en trilliard" ] , examples (NumeralValue 1e24) [ "en kvadrillion" ] , examples (NumeralValue 1e27) [ "en kvadrilliard" ] , examples (NumeralValue 6e10) [ "seksti milliarder" , "60 milliarder" ] , examples (NumeralValue 3e12) [ "tre billioner" , "3 billioner" ] , examples (NumeralValue 4e17) [ "fire hundre billiarder" , "400 billiarder" ] , examples (NumeralValue 2e18) [ "to trillioner" , "2 trillioner" ] , examples (NumeralValue 1.8e22) [ "atten trilliarder" , "18 trilliarder" ] , examples (NumeralValue 1.8e22) [ "atten trilliarder" , "18 trilliarder" ] , examples (NumeralValue 4.11e26) [ "fire hundre og elleve kvadrillioner" , "411 kvadrillioner" ] , examples (NumeralValue 9e27) [ "ni kvadrilliarder" , "9 kvadrilliarder" ] , examples (NumeralValue 21) [ "tjueen" , "tjueén" ] , examples (NumeralValue 22) [ "tjueto" ] , examples (NumeralValue 23) [ "tjuetre" ] , examples (NumeralValue 24) [ "tjuefire" ] , examples (NumeralValue 25) [ "tjuefem" ] , examples (NumeralValue 26) [ "tjueseks" ] , examples (NumeralValue 27) [ "tjuesju" , "tjuesyv" ] , examples (NumeralValue 28) [ "tjueåtte" ] , examples (NumeralValue 29) [ "tjueni" ] , examples (NumeralValue 31) [ "trettien" , "trettién" ] , examples (NumeralValue 32) [ "trettito" ] , examples (NumeralValue 33) [ "trettitre" ] , examples (NumeralValue 34) [ "trettifire" ] , examples (NumeralValue 35) [ "trettifem" ] , examples (NumeralValue 36) [ "trettiseks" ] , examples (NumeralValue 37) [ "trettisju" , "trettisyv" ] , examples (NumeralValue 38) [ "trettiåtte" ] , examples (NumeralValue 39) [ "trettini" ] , examples (NumeralValue 41) [ "førtien" , "førtién" ] , examples (NumeralValue 42) [ "førtito" ] , examples (NumeralValue 43) [ "førtitre" ] , examples (NumeralValue 44) [ "førtifire" ] , examples (NumeralValue 45) [ "førtifem" ] , examples (NumeralValue 46) [ "førtiseks" ] , examples (NumeralValue 47) [ "førtisju" , "førtisyv" ] , examples (NumeralValue 48) [ "førtiåtte" ] , examples (NumeralValue 49) [ "førtini" ] , examples (NumeralValue 51) [ "femtien" , "femtién" ] , examples (NumeralValue 52) [ "femtito" ] , examples (NumeralValue 53) [ "femtitre" ] , examples (NumeralValue 54) [ "femtifire" ] , examples (NumeralValue 55) [ "femtifem" ] , examples (NumeralValue 56) [ "femtiseks" ] , examples (NumeralValue 57) [ "femtisju" , "femtisyv" ] , examples (NumeralValue 58) [ "femtiåtte" ] , examples (NumeralValue 59) [ "femtini" ] , examples (NumeralValue 61) [ "sekstien" , "sekstién" ] , examples (NumeralValue 62) [ "sekstito" ] , examples (NumeralValue 63) [ "sekstitre" ] , examples (NumeralValue 64) [ "sekstifire" ] , examples (NumeralValue 65) [ "sekstifem" ] , examples (NumeralValue 66) [ "sekstiseks" ] , examples (NumeralValue 67) [ "sekstisju" , "sekstisyv" ] , examples (NumeralValue 68) [ "sekstiåtte" ] , examples (NumeralValue 69) [ "sekstini" ] , examples (NumeralValue 71) [ "syttien" , "søttien" , "søttién" , "søttién" ] , examples (NumeralValue 72) [ "syttito" , "søttito" ] , examples (NumeralValue 73) [ "syttitre" , "søttitre" ] , examples (NumeralValue 74) [ "syttifire" , "søttifire" ] , examples (NumeralValue 75) [ "syttifem" , "søttifem" ] , examples (NumeralValue 76) [ "syttiseks" , "søttiseks" ] , examples (NumeralValue 77) [ "syttisju" , "syttisju" , "søttisyv" , "søttisyv" ] , examples (NumeralValue 78) [ "søttiåtte" , "søttiåtte" ] , examples (NumeralValue 79) [ "søttini" , "søttini" ] , examples (NumeralValue 81) [ "åttien" , "åttién" ] , examples (NumeralValue 82) [ "åttito" ] , examples (NumeralValue 83) [ "åttitre" ] , examples (NumeralValue 84) [ "åttifire" ] , examples (NumeralValue 85) [ "åttifem" ] , examples (NumeralValue 86) [ "åttiseks" ] , examples (NumeralValue 87) [ "åttisju" , "åttisyv" ] , examples (NumeralValue 88) [ "åttiåtte" ] , examples (NumeralValue 89) [ "åttini" ] , examples (NumeralValue 91) [ "nittien" , "nittién" ] , examples (NumeralValue 92) [ "nittito" ] , examples (NumeralValue 93) [ "nittitre" ] , examples (NumeralValue 94) [ "nittifire" ] , examples (NumeralValue 95) [ "nittifem" ] , examples (NumeralValue 96) [ "nittiseks" ] , examples (NumeralValue 97) [ "nittisju" , "nittisyv" ] , examples (NumeralValue 98) [ "nittiåtte" ] , examples (NumeralValue 99) [ "nittini" ] ]
facebookincubator/duckling
Duckling/Numeral/NB/Corpus.hs
bsd-3-clause
10,452
0
11
5,062
2,158
1,186
972
306
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude , ExistentialQuantification , MagicHash , DeriveDataTypeable #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Exception -- Copyright : (c) The University of Glasgow, 1998-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Exceptions and exception-handling functions. -- ----------------------------------------------------------------------------- module GHC.Exception ( Exception(..) -- Class , throw , SomeException(..), ErrorCall(..), ArithException(..) , divZeroException, overflowException, ratioZeroDenomException , errorCallException ) where import Data.Maybe import Data.Typeable (Typeable, cast) -- loop: Data.Typeable -> GHC.Err -> GHC.Exception import GHC.Base import GHC.Show {- | The @SomeException@ type is the root of the exception type hierarchy. When an exception of type @e@ is thrown, behind the scenes it is encapsulated in a @SomeException@. -} data SomeException = forall e . Exception e => SomeException e deriving Typeable instance Show SomeException where showsPrec p (SomeException e) = showsPrec p e {- | Any type that you wish to throw or catch as an exception must be an instance of the @Exception@ class. The simplest case is a new exception type directly below the root: > data MyException = ThisException | ThatException > deriving (Show, Typeable) > > instance Exception MyException The default method definitions in the @Exception@ class do what we need in this case. You can now throw and catch @ThisException@ and @ThatException@ as exceptions: @ *Main> throw ThisException \`catch\` \\e -> putStrLn (\"Caught \" ++ show (e :: MyException)) Caught ThisException @ In more complicated examples, you may wish to define a whole hierarchy of exceptions: > --------------------------------------------------------------------- > -- Make the root exception type for all the exceptions in a compiler > > data SomeCompilerException = forall e . Exception e => SomeCompilerException e > deriving Typeable > > instance Show SomeCompilerException where > show (SomeCompilerException e) = show e > > instance Exception SomeCompilerException > > compilerExceptionToException :: Exception e => e -> SomeException > compilerExceptionToException = toException . SomeCompilerException > > compilerExceptionFromException :: Exception e => SomeException -> Maybe e > compilerExceptionFromException x = do > SomeCompilerException a <- fromException x > cast a > > --------------------------------------------------------------------- > -- Make a subhierarchy for exceptions in the frontend of the compiler > > data SomeFrontendException = forall e . Exception e => SomeFrontendException e > deriving Typeable > > instance Show SomeFrontendException where > show (SomeFrontendException e) = show e > > instance Exception SomeFrontendException where > toException = compilerExceptionToException > fromException = compilerExceptionFromException > > frontendExceptionToException :: Exception e => e -> SomeException > frontendExceptionToException = toException . SomeFrontendException > > frontendExceptionFromException :: Exception e => SomeException -> Maybe e > frontendExceptionFromException x = do > SomeFrontendException a <- fromException x > cast a > > --------------------------------------------------------------------- > -- Make an exception type for a particular frontend compiler exception > > data MismatchedParentheses = MismatchedParentheses > deriving (Typeable, Show) > > instance Exception MismatchedParentheses where > toException = frontendExceptionToException > fromException = frontendExceptionFromException We can now catch a @MismatchedParentheses@ exception as @MismatchedParentheses@, @SomeFrontendException@ or @SomeCompilerException@, but not other types, e.g. @IOException@: @ *Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: MismatchedParentheses)) Caught MismatchedParentheses *Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: SomeFrontendException)) Caught MismatchedParentheses *Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: SomeCompilerException)) Caught MismatchedParentheses *Main> throw MismatchedParentheses `catch` \e -> putStrLn (\"Caught \" ++ show (e :: IOException)) *** Exception: MismatchedParentheses @ -} class (Typeable e, Show e) => Exception e where toException :: e -> SomeException fromException :: SomeException -> Maybe e toException = SomeException fromException (SomeException e) = cast e instance Exception SomeException where toException se = se fromException = Just -- | Throw an exception. Exceptions may be thrown from purely -- functional code, but may only be caught within the 'IO' monad. throw :: Exception e => e -> a throw e = raise# (toException e) -- |This is thrown when the user calls 'error'. The @String@ is the -- argument given to 'error'. newtype ErrorCall = ErrorCall String deriving (Eq, Ord, Typeable) instance Exception ErrorCall instance Show ErrorCall where showsPrec _ (ErrorCall err) = showString err errorCallException :: String -> SomeException errorCallException s = toException (ErrorCall s) -- |Arithmetic exceptions. data ArithException = Overflow | Underflow | LossOfPrecision | DivideByZero | Denormal | RatioZeroDenominator -- ^ /Since: 4.6.0.0/ deriving (Eq, Ord, Typeable) divZeroException, overflowException, ratioZeroDenomException :: SomeException divZeroException = toException DivideByZero overflowException = toException Overflow ratioZeroDenomException = toException RatioZeroDenominator instance Exception ArithException instance Show ArithException where showsPrec _ Overflow = showString "arithmetic overflow" showsPrec _ Underflow = showString "arithmetic underflow" showsPrec _ LossOfPrecision = showString "loss of precision" showsPrec _ DivideByZero = showString "divide by zero" showsPrec _ Denormal = showString "denormal" showsPrec _ RatioZeroDenominator = showString "Ratio has zero denominator"
jstolarek/ghc
libraries/base/GHC/Exception.hs
bsd-3-clause
6,477
0
9
1,094
525
292
233
57
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MonoLocalBinds #-} module Config where import Prelude hiding (fail, lookup) import qualified Data.Configurator as C import qualified Data.Configurator.Types as CT import qualified Data.Map.Strict as Map import qualified Data.HashMap.Strict as HM import qualified Data.Text as T import qualified Options.Applicative as O import Options.Applicative ((<>)) import Data.List (intercalate, sort) import Data.List.Ordered (subset, minus') import qualified Rel.Cmd as Cmd import qualified Rel.FS as FS import qualified Rel.Git as Git import qualified Rel.Github as Github import qualified Rel.Log as Log import qualified Rel.User as User import Monad.Result import AppMonad data CliOpts = CliOpts { configFilePath :: String , enableDaemonMode :: Bool } instance CT.Configured Log.Level where convert (CT.String x) = toMaybe . Log.parseLevel $ T.unpack x convert _ = Nothing appConfig :: AppConfig appConfig = AppConfig { configPath = "/etc/pure.conf" , storageRoot = "/var/run/pure/repos" , keystorePath = "/var/run/pure/keys" , pidFile = "/var/run/pure/pure.pid" , listenPort = 3000 , daemonMode = False , cmdConfig = Cmd.Config { Cmd.envVars = Map.fromList [ ("PATH", "/usr/local/bin:/usr/bin:/bin") ] } , gitConfig = Git.Config { Git.identity = Nothing , Git.sshClient = "/usr/share/pure/git-ssh-compat" } , logConfig = Log.Config { Log.path = Nothing , Log.level = Log.INFO , Log.print = True } , fsConfig = FS.defaultConfig , githubConfig = Github.defaultConfig , userConfig = User.defaultConfig } loadConfig :: App () loadConfig = do cfgPath <- getConfigPath current <- getConfig c <- safe $ C.load [ C.Optional cfgPath ] keys <- safe $ (sort . map T.unpack . HM.keys) `fmap` C.getMap c keystorePath <- getOr c "keystore.path" $ keystorePath current storageRoot <- getOr c "repocache.path" $ storageRoot current listenPort <- getOr c "server.port" $ listenPort current pidFile <- getOr c "server.pidFile" $ pidFile current logLevel <- getOr c "server.logLevel" . Log.level $ logConfig current gitSsh <- getOr c "server.sshClient" . Git.sshClient $ gitConfig current logPath <- get c "server.logFile" setConfig $ current { storageRoot, keystorePath, pidFile, listenPort , logConfig = (logConfig current) { Log.path = logPath , Log.level = logLevel } , gitConfig = (gitConfig current) { Git.sshClient = gitSsh } } assert' (subset keys validKeys) $ "Unknown keys in configuration: " ++ (intercalate " " $ minus' keys validKeys) where get cfg k = safe $ C.lookup cfg k -- no default getOr cfg k v = safe $ C.lookupDefault v cfg k -- default validKeys = sort [ "keystore.path" , "repocache.path" , "server.port" , "server.logFile" , "server.logLevel" , "server.pidFile" , "server.sshClient" ] readCliOpts :: App () readCliOpts = do opts <- parseOpts setConfigFilePath $ configFilePath opts setDaemonMode $ enableDaemonMode opts where parseOpts = safe . O.execParser $ O.info (O.helper <*> cliOpts) ( O.fullDesc <> O.progDesc "Automatically push Github commits to a remote repository." <> O.header "pure - push relay for Github repositories" ) cliOpts = CliOpts <$> O.strOption ( O.long "config-file" <> O.short 'c' <> O.value "/etc/pure.conf" <> O.metavar "FILE" <> O.help "Path to pure.conf" ) <*> O.switch ( O.long "daemon" <> O.short 'd' <> O.help "Run as a background process (daemon mode)" )
shmookey/pure
app/Config.hs
bsd-3-clause
3,986
0
16
1,046
1,016
559
457
104
1
-- | construct a feed from a mailman (pipermail) archive, -- e.g., https://mail.haskell.org/pipermail/libraries/ -- see https://github.com/chrisdone/haskellnews/issues/12 -- and https://github.com/haskell-infra/hl/issues/63#issuecomment-74420850 {-# language OverloadedStrings #-} module HN.Model.Mailman where import Network.HTTP.Conduit import Text.Feed.Types import Text.Feed.Query (getItemTitle) import Text.Feed.Constructor import qualified Text.HTML.DOM import Text.XML import Text.XML.Cursor as XMLCursor import Text.XML.Cursor.Generic as XMLGeneric import qualified Data.Text as T import Data.Time.Format import Data.Time.LocalTime ( ZonedTime ) import Data.Char (isDigit) import qualified Data.Set as S test1 :: IO (Either String Feed) test1 = downloadFeed 10 "https://mail.haskell.org/pipermail/haskell-cafe/" -- | look at archive and produce a feed. -- 1st argument is minimal number of items to produce. -- 2st argument is "base name" of archive, e.g. -- "https://mail.haskell.org/pipermail/haskell-cafe/" -- it should end with "/" downloadFeed :: Int -> String -> IO (Either String Feed) downloadFeed its uri= do result <- getDoc uri case result of Left err -> return $ Left err Right doc -> do let cursor = fromDocument doc let entries = descendant cursor >>= element "A" >>= laxAttribute "href" dates = filter (T.isSuffixOf "thread.html" ) entries archivedon = fetchDate cursor "Archived on:" items <- getItems its uri $ take 1 dates let pubdate = case archivedon of [] -> "Tue Feb 17 18:55:05 UTC 2015" d : _ -> d let feed0 = newFeed (RSSKind Nothing) feed = withFeedPubDate pubdate $ foldr addItem feed0 items return $ Right feed getDoc :: String -> IO (Either a Document) getDoc uri = do result <- simpleHttp uri return $ Right $ Text.HTML.DOM.parseLBS result -- | get at least @its@ items (since we cannot easily sort by time here, -- we get the full month, and if it contains less that @its@ messages, -- we get the previous month as well, etc.) getItems :: Int -> String -> [T.Text] -> IO [Item] getItems its uri dates = getItemsUnique S.empty its uri dates -- | get only the newest item for each subject getItemsUnique :: S.Set (Maybe String) -> Int -> String -> [T.Text] -> IO [Item] getItemsUnique seen its uri dates = if its <= 0 then return [] else case dates of [] -> return [] d:ates -> do result <- getDoc $ uri ++ T.unpack d let (seen', items) = uniques seen $ reverse $ case result of Left _ -> [] Right doc -> let cursor = fromDocument doc in descendant cursor >>= element "A" >>= hasAttribute "HREF" >>= parent >>= element "LI" >>= mkItem uri (dropSuffix "thread.html" d ) later <- getItemsUnique seen' (its - length items) uri ates return $ items ++ later uniques seen [] = (seen, []) uniques seen (x:xs) = let s = getItemTitle x in if S.member s seen then uniques seen xs else let (seen', xs') = uniques (S.insert s seen) xs in (seen', x:xs') dropSuffix :: T.Text -> T.Text -> T.Text dropSuffix suf s = if T.isSuffixOf suf s then T.take (T.length s - T.length suf) s else s fetchDate :: XMLGeneric.Cursor Node -> T.Text -> [String] fetchDate cursor desc = do d <- fetch cursor desc -- we get this from mailman "Tue Feb 17 18:55:05 UTC 2015" -- and apparently we need "Tue, 17 Feb 2015 21:12:55 UTC" t <- maybe [] return $ parseTimeM True defaultTimeLocale "%a %b %d %H:%M:%S %Z %Y" $ T.unpack d return $ formatTime defaultTimeLocale rfc822DateFormat ( t :: ZonedTime ) fetch :: XMLGeneric.Cursor Node -> T.Text -> [T.Text] fetch cursor desc = descendant cursor >>= element "b" >>= hasChildContents desc >>= followingSibling >>= element "i" >>= child >>= content hasChildContents :: T.Text -> XMLCursor.Axis hasChildContents desc = check $ \ c -> desc == T.concat (child c >>= content ) mkItem :: String -> T.Text -> XMLGeneric.Cursor Node -> [Item] mkItem uri d c = do href <- child c >>= element "A" >>= laxAttribute "HREF" title <- child c >>= element "A" >>= hasAttribute "HREF" >>= child >>= content author <- child c >>= element "I" >>= child >>= content -- UGLY date hack. The information looks like this: -- NodeComment "2 01424167545.118214-01424175253.118215-01424184970.118219- " -- and we need to get to this part: --------------------^^^^^^^^^^^ -- which gives the epoch time of the current message NodeComment com <- map node ( precedingSibling c >>= precedingSibling ) let (s,_) = T.breakOnEnd "." com n = T.reverse $ T.takeWhile isDigit $ T.drop 1 $ T.reverse s Just pubdate = parseTimeM True defaultTimeLocale "%s" $ T.unpack n pubdateString = formatTime defaultTimeLocale rfc822DateFormat ( pubdate :: ZonedTime ) let unpack = T.unpack . T.unwords . T.words return $ withItemLink (uri ++ T.unpack d ++ T.unpack href) $ withItemTitle (unpack title) $ withItemDescription (unpack title) $ withItemAuthor (unpack author) $ withItemPubDate pubdateString $ newItem (RSSKind Nothing)
jwaldmann/haskellnews
src/HN/Model/Mailman.hs
bsd-3-clause
5,413
113
21
1,354
1,424
757
667
105
4
module Mandelbrot.Algorithms.EscapeTime.Internal where import Data.Complex radius :: RealFloat a => a radius = 3 lessThanRadius :: (RealFloat a) => Complex a -> Bool lessThanRadius z = pythagoreanLT (realPart z) (imagPart z) radius where pythagoreanLT a b c = a ** 2 + b ** 2 < c ** 2 zSeries :: RealFloat a => Complex a -> [Complex a] zSeries c = iterate nextZ (0 :+ 0) where nextZ z = (z ^ (2 :: Integer)) + c
matt-keibler/mandelbrot
src/Mandelbrot/Algorithms/EscapeTime/Internal.hs
bsd-3-clause
420
0
11
86
184
96
88
10
1
module Util where import System.Environment (getArgs) import System.Directory (doesFileExist, getCurrentDirectory) import System.IO import System.FilePath ((</>)) parseArgs :: [String] -> (String, [String]) parseArgs args = case iter args "" [""] of ("", _) -> error "filename is missing" ret -> ret where iter :: [String] -> String -> [String] -> (String, [String]) iter [] filename searchpath = (filename, searchpath) iter ("-I":a:as) filename searchpath = iter as filename (a:searchpath) iter (a:as) filename searchpath | filename /= "" = error "Only one file allowed" | otherwise = iter as a searchpath findFile :: String -> [String] -> IO String findFile filename [] = error $ "Could not find " ++ filename ++ " in the search path" findFile filename (path:searchpath) = do let fullpath = path </> filename exists <- doesFileExist fullpath if exists then return fullpath else findFile filename searchpath -- Supports a single argument of the file to load, along with -- any number of pairs of the form "-I path". Each such "path" -- will be added to the searchpath getContentsFromCmdLine :: IO String getContentsFromCmdLine = do args <- getArgs file <- uncurry findFile $ parseArgs args readFile file getFileContents :: String -> IO String getFileContents filename = do dir <- getCurrentDirectory let fullpath = dir </> filename exists <- doesFileExist fullpath if exists then readFile fullpath else error $ "Could not find " ++ filename
ehamberg/tapl-haskell-untyped
src/Util.hs
bsd-3-clause
1,807
0
11
591
467
241
226
35
4
{-# LANGUAGE TemplateHaskell #-} module TypeLevel.Number.Nat.TH where import Language.Haskell.TH import TypeLevel.Number.Nat.Types splitToBits :: Integer -> [Int] splitToBits 0 = [] splitToBits x | odd x = 1 : splitToBits rest | otherwise = 0 : splitToBits rest where rest = x `div` 2 -- | Create type for natural number. natT :: Integer -> TypeQ natT n | n >= 0 = foldr appT (conT ''Z) . map con . splitToBits $ n | otherwise = error "natT: negative number is supplied" where con 0 = conT ''O con 1 = conT ''I con _ = error "natT: Strange bit nor 0 nor 1" -- | Create value for type level natural. Value itself is undefined. nat :: Integer -> ExpQ nat n = sigE [|undefined|] (natT n)
Shimuuar/type-level-numbers
TypeLevel/Number/Nat/TH.hs
bsd-3-clause
748
0
12
191
236
121
115
17
3
{-# LANGUAGE BinaryLiterals #-} module OpCodes where import BinUtils import Types import Header import qualified Data.Vector as V import Data.Word import Data.Either import Control.Monad import Debug.Trace import qualified Data.ByteString as B import qualified Data.Binary.Strict.Get as BS import qualified Data.Binary.Strict.BitGet as BG data BranchForm = BrTrue | BrFalse | BrAddress ByteAddr deriving (Show, Eq) data OpcodeForm = LongForm | ShortForm | ExtendedForm | VariableForm deriving (Show, Eq) data OperandCount = Op0Count | Op1Count | Op2Count | VarCount deriving (Show, Eq) data OperandType = LargeOpandType | SmallOpandType | VarOpandType | OmittedType deriving (Show, Eq) data Bytecode = OP2_1 | OP2_2 | OP2_3 | OP2_4 | OP2_5 | OP2_6 | OP2_7 | OP2_8 | OP2_9 | OP2_10 | OP2_11 | OP2_12 | OP2_13 | OP2_14 | OP2_15 | OP2_16 | OP2_17 | OP2_18 | OP2_19 | OP2_20 | OP2_21 | OP2_22 | OP2_23 | OP2_24 | OP2_25 | OP2_26 | OP2_27 | OP2_28 | OP1_128 | OP1_129 | OP1_130 | OP1_131 | OP1_132 | OP1_133 | OP1_134 | OP1_135 | OP1_136 | OP1_137 | OP1_138 | OP1_139 | OP1_140 | OP1_141 | OP1_142 | OP1_143 | OP0_176 | OP0_177 | OP0_178 | OP0_179 | OP0_180 | OP0_181 | OP0_182 | OP0_183 | OP0_184 | OP0_185 | OP0_186 | OP0_187 | OP0_188 | OP0_189 | OP0_190 | OP0_191 | VAR_224 | VAR_225 | VAR_226 | VAR_227 | VAR_228 | VAR_229 | VAR_230 | VAR_231 | VAR_232 | VAR_233 | VAR_234 | VAR_235 | VAR_236 | VAR_237 | VAR_238 | VAR_239 | VAR_240 | VAR_241 | VAR_242 | VAR_243 | VAR_244 | VAR_245 | VAR_246 | VAR_247 | VAR_248 | VAR_249 | VAR_250 | VAR_251 | VAR_252 | VAR_253 | VAR_254 | VAR_255 | EXT_0 | EXT_1 | EXT_2 | EXT_3 | EXT_4 | EXT_5 | EXT_6 | EXT_7 | EXT_8 | EXT_9 | EXT_10 | EXT_11 | EXT_12 | EXT_13 | EXT_14 | EXT_16 | EXT_17 | EXT_18 | EXT_19 | EXT_20 | EXT_21 | EXT_22 | EXT_23 | EXT_24 | EXT_25 | EXT_26 | EXT_27 | EXT_28 | EXT_29 | ILLEGAL deriving (Show, Eq) -- The tables which follow are maps from the opcode identification number -- to the opcode type; the exact order matters. oneOperandBytecodes :: V.Vector Bytecode oneOperandBytecodes = V.fromList [ OP1_128, OP1_129, OP1_130, OP1_131, OP1_132, OP1_133, OP1_134, OP1_135, OP1_136, OP1_137, OP1_138, OP1_139, OP1_140, OP1_141, OP1_142, OP1_143 ] zeroOperandBytecodes :: V.Vector Bytecode zeroOperandBytecodes = V.fromList [ OP0_176, OP0_177, OP0_178, OP0_179, OP0_180, OP0_181, OP0_182, OP0_183, OP0_184, OP0_185, OP0_186, OP0_187, OP0_188, OP0_189, OP0_190, OP0_191 ] twoOperandBytecodes :: V.Vector Bytecode twoOperandBytecodes = V.fromList [ ILLEGAL, OP2_1, OP2_2, OP2_3, OP2_4, OP2_5, OP2_6, OP2_7, OP2_8, OP2_9, OP2_10, OP2_11, OP2_12, OP2_13, OP2_14, OP2_15, OP2_16, OP2_17, OP2_18, OP2_19, OP2_20, OP2_21, OP2_22, OP2_23, OP2_24, OP2_25, OP2_26, OP2_27, OP2_28, ILLEGAL, ILLEGAL, ILLEGAL ] varOperandBytecodes :: V.Vector Bytecode varOperandBytecodes = V.fromList [ VAR_224, VAR_225, VAR_226, VAR_227, VAR_228, VAR_229, VAR_230, VAR_231, VAR_232, VAR_233, VAR_234, VAR_235, VAR_236, VAR_237, VAR_238, VAR_239, VAR_240, VAR_241, VAR_242, VAR_243, VAR_244, VAR_245, VAR_246, VAR_247, VAR_248, VAR_249, VAR_250, VAR_251, VAR_252, VAR_253, VAR_254, VAR_255 ] extBytecodes :: V.Vector Bytecode extBytecodes = V.fromList [ EXT_0, EXT_1, EXT_2, EXT_3, EXT_4, EXT_5, EXT_6, EXT_7, EXT_8, EXT_9, EXT_10, EXT_11, EXT_12, EXT_13, EXT_14, ILLEGAL, EXT_16, EXT_17, EXT_18, EXT_19, EXT_20, EXT_21, EXT_22, EXT_23, EXT_24, EXT_25, EXT_26, EXT_27, EXT_28, EXT_29, ILLEGAL, ILLEGAL ] readForm :: B.ByteString -> BS.Get OpcodeForm readForm w = either fail return $ BG.runBitGet w $ do b <- BG.getAsWord8 2 case b of 0b11 -> return VariableForm 0b10 -> return ShortForm -- Extended _ -> return LongForm readOpandCount :: OpcodeForm -> B.ByteString -> BS.Get OperandCount readOpandCount form w = either fail return $ BG.runBitGet w $ do BG.skip 2 b4 <- BG.getBit b5 <- BG.getBit case form of LongForm -> return Op2Count ShortForm -> case (b4,b5) of (True,True) -> return Op0Count _ -> return Op1Count VariableForm -> if b5 then return VarCount else return Op2Count ExtendedForm -> return VarCount readOpFormCount :: B.ByteString -> BS.Get (OpcodeForm, OperandCount) readOpFormCount w = do form <- readForm w opandCount <- readOpandCount form w return (form,opandCount) -- fetch :: B.ByteString -> Int -> Int -> V.Vector r -> BS.Get r fetch :: B.ByteString -> Int -> Int -> V.Vector r -> BS.Get r fetch s skip count array = either fail return $ BG.runBitGet s $ do BG.skip skip idx <- fromIntegral <$> BG.getAsWord8 count return $ array V.! idx fetchBytecode :: B.ByteString -> OpcodeForm -> OperandCount -> BS.Get Bytecode fetchBytecode w ExtendedForm _ = (extBytecodes V.!) . fromIntegral <$> BS.getWord8 fetchBytecode w _ Op0Count = fetch w 4 4 zeroOperandBytecodes fetchBytecode w _ Op1Count = fetch w 4 4 oneOperandBytecodes fetchBytecode w _ Op2Count = fetch w 3 5 twoOperandBytecodes fetchBytecode w _ VarCount = fetch w 3 5 varOperandBytecodes readOpBytecode :: BS.Get (OpcodeForm, OperandCount, Bytecode, [OperandType]) readOpBytecode = do w <- BS.getByteString 1 (f,c) <- readOpFormCount w bc <- fetchBytecode w f c opandTypes <- readOpandType w f c bc -- traceShowM (f,c, bc, opandTypes) return (f,c, bc, opandTypes) -- (_, _) -> return ILLEGAL readOpandType :: B.ByteString -> OpcodeForm -> OperandCount -> Bytecode -> BS.Get [OperandType] readOpandType w f c op = case (f,c) of (_, Op0Count) -> runBitGet $ return [] (_, Op1Count) -> runBitGet $ do BG.skip 2 n <- BG.getAsWord8 2 traceShowM ("opandType",n) return [decodeOpandTypes n] (LongForm, Op2Count) -> runBitGet $ do BG.skip 1 let f x = if x then VarOpandType else SmallOpandType b1 <- f <$> BG.getBit b2 <- f<$> BG.getBit return [b1, b2] (VariableForm, _) | op == VAR_236 || op == VAR_250 -> do w2 <- BS.getByteString 2 either fail return $ BG.runBitGet w2 $ readVar 0 _ -> do w2 <- BS.getByteString 1 either fail return $ BG.runBitGet w2 $ readVar 0 where runBitGet g = either fail return $ BG.runBitGet w g readVar :: Int -> BG.BitGet [OperandType] readVar i = if i == 4 then return [] else do n <- BG.getAsWord8 2 rest <- readVar (i+1) return $ case decodeOpandTypes n of OmittedType -> [] x -> x : rest getTypeLength :: OpcodeForm -> Bytecode -> Int getTypeLength form opcode = case (form, opcode) of (VariableForm, VAR_236) -> 2 (VariableForm, VAR_250) -> 2 (VariableForm, _) -> 1 _ -> 0 decodeOpandTypes :: (Eq a, Num a) => a -> OperandType decodeOpandTypes 0 = LargeOpandType decodeOpandTypes 1 = SmallOpandType decodeOpandTypes 2 = VarOpandType decodeOpandTypes _ = OmittedType data Var = Local Int | Global Int | Stack deriving(Show, Eq) data Operand = Large Word16 | Small Word8 | Variable Var deriving(Show, Eq) data OpN = Op0 Bytecode | Op1 (Bytecode, Operand) | Op2 (Bytecode, Operand, Operand) deriving(Show, Eq) opnOp :: OpN -> Bytecode opnOp (Op0 b) = b opnOp (Op1(b, _)) = b opnOp (Op2(b, _, _)) = b -- data Store = Stack newtype Op = Op (OpN, Maybe Branch, Maybe Var) deriving(Show, Eq) readOperand :: OperandType -> BS.Get Operand readOperand SmallOpandType = Small <$> BS.getWord8 readOperand LargeOpandType = Large <$> BS.getWord16be readOperand VarOpandType = do w <- BS.getWord8 return . Variable $ case w of 0x00 -> Stack x | x <= 0x0f -> Local . fromIntegral $ x x -> Global . fromIntegral $ x readOperand _ = fail "READ OPERAND FAIL" readOperands :: Traversable t => t OperandType -> BS.Get (t Operand) readOperands = mapM readOperand readOpN :: Version -> BS.Get OpN readOpN ver = do (f,c,b,t) <- readOpBytecode o <- readOperands t case (Prelude.length t, o) of (0, []) -> return $ Op0 b (1, [o1]) -> return $ Op1(b, o1) (2, [o1,o2]) -> return $ Op2(b, o1, o2) _ -> fail "WEIRD" readOp :: Version -> BS.Get Op readOp ver = do opn <- readOpN ver let bc = opnOp opn br <- readBranchMaybe bc ver return $ Op(opn, br, Nothing) -- Branching hasBranch :: Bytecode -> Version -> Bool hasBranch opcode ver = case opcode of OP0_181 -> Header.v3OrLower ver -- "save" branches in v3, stores in v4 OP0_182 -> Header.v3OrLower ver -- "restore" branches in v3, stores in v4 x | x == OP2_1 || x == OP2_2 || x == OP2_3 || x == OP2_4 || x == OP2_5 || x == OP2_6 || x == OP2_7 || x == OP2_10 || x == OP1_128 || x == OP1_129 || x == OP1_130 || x == OP0_189 || x == OP0_191 || x == VAR_247 || x == VAR_255 || x == EXT_6 || x == EXT_14 || x == EXT_24 || x == EXT_27 -> True _ -> False type Branch = (Bool, BranchForm) readBranch :: BS.Get Branch readBranch = do w <- BS.getByteString 1 either fail return $ BG.runBitGet w g where g = do sense <- BG.getBit -- b7 short <- BG.getBit -- b6 offset <- if short then BG.getAsWord16 6 else BG.getAsWord16 14 case offset of 0 -> return (sense, BrFalse) 1 -> return (sense, BrTrue) _ -> return (sense, BrAddress . ByteAddr $ offset) -- fail "ASDASD" readBranchMaybe :: Bytecode -> Version -> BS.Get (Maybe Branch) readBranchMaybe b v = if hasBranch b v then do b <- readBranch return $ Just b else return Nothing
theor/zorkell
src/OpCodes.hs
bsd-3-clause
10,286
0
47
2,902
3,352
1,826
1,526
226
8
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Trustworthy #-} module Data.Hexagon.Neighbors (HasNeighbors (..), neighbor, isNeighbor) where import Control.Lens.Operators import Data.Hexagon.Types import Data.List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) -- | a 'HexCoordinate' which has neighbors. class (Integral a) => HasNeighbors (t :: * -> *) a where -- | get all 6 neighbors of a 'HexCoordinate' directions :: t a -> Map Direction (t a) -- | given a 'Direction' return that neighbor neighbor :: (HasNeighbors t a) => Direction -> t a -> t a neighbor d = fromJust . Map.lookup d . directions -- | in case of a being a neighbor of b return 'Just' 'Direction' else 'Nothing' isNeighbor :: (HasNeighbors t a, Eq (t a)) => t a -> t a -> Maybe Direction isNeighbor a = findMapKeyByValue a . directions findMapKeyByValue :: (Eq a) => a -> Map k a -> Maybe k findMapKeyByValue a = fmap fst . find ((==) a . snd) . Map.toList cubeDirections :: Num t => CubeCoordinate t -> Map Direction (CubeCoordinate t) cubeDirections c = Map.fromList [ (D0, c & cubeX +~ 1 & cubeY -~ 1) , (D1, c & cubeX +~ 1 & cubeZ -~ 1) , (D2, c & cubeY +~ 1 & cubeZ -~ 1) , (D3, c & cubeX -~ 1 & cubeY +~ 1) , (D4, c & cubeX -~ 1 & cubeZ +~ 1) , (D5, c & cubeY -~ 1 & cubeZ +~ 1) ] axialDirections :: Num t => AxialCoordinate t -> Map Direction (AxialCoordinate t) axialDirections c = Map.fromList [ (D0, c & axialCol +~ 1) , (D1, c & axialCol +~ 1 & axialRow -~ 1) , (D2, c & axialRow -~ 1) , (D3, c & axialCol -~ 1) , (D4, c & axialCol -~ 1 & axialRow +~ 1) , (D5, c & axialRow +~ 1) ] offsetEvenQDirections :: (Integral t) => OffsetEvenQ t -> Map Direction (OffsetEvenQ t) offsetEvenQDirections c = Map.fromList $ if (even $ c ^. offsetCol) then [ (D0, c & offsetCol +~ 1 & offsetRow +~ 1) , (D1, c & offsetCol +~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetCol -~ 1 & offsetRow +~ 1) , (D5, c & offsetRow +~ 1) ] else [ (D0, c & offsetCol +~ 1) , (D1, c & offsetCol +~ 1 & offsetRow -~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1 & offsetRow -~ 1) , (D4, c & offsetCol -~ 1) , (D5, c & offsetRow +~ 1) ] offsetOddQDirections :: (Integral t) => OffsetOddQ t -> Map Direction (OffsetOddQ t) offsetOddQDirections c = Map.fromList $ if (even $ c ^. offsetCol) then [ (D0, c & offsetCol +~ 1) , (D1, c & offsetCol +~ 1 & offsetRow -~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1 & offsetRow -~ 1) , (D4, c & offsetCol -~ 1) , (D5, c & offsetRow +~ 1) ] else [ (D0, c & offsetCol +~ 1 & offsetRow +~ 1) , (D1, c & offsetCol +~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetCol -~ 1 & offsetRow +~ 1) , (D5, c & offsetRow +~ 1) ] offsetEvenRDirections :: (Integral t) => OffsetEvenR t -> Map Direction (OffsetEvenR t) offsetEvenRDirections c = Map.fromList $ if (even $ c ^. offsetRow) then [ (D0, c & offsetCol +~ 1) , (D1, c & offsetCol +~ 1 & offsetRow -~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetRow +~ 1) , (D5, c & offsetCol +~ 1 & offsetRow +~ 1) ] else [ (D0, c & offsetCol +~ 1) , (D1, c & offsetRow -~ 1) , (D2, c & offsetCol -~ 1 & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetCol -~ 1 & offsetRow +~ 1) , (D5, c & offsetRow +~ 1) ] offsetOddRDirections :: (Integral t) => OffsetOddR t -> Map Direction (OffsetOddR t) offsetOddRDirections c = Map.fromList $ if (even $ c ^. offsetRow) then [ (D0, c & offsetCol +~ 1) , (D1, c & offsetRow -~ 1) , (D2, c & offsetCol -~ 1 & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetCol -~ 1 & offsetRow +~ 1) , (D5, c & offsetRow +~ 1) ] else [ (D0, c & offsetCol +~ 1) , (D1, c & offsetCol +~ 1 & offsetRow -~ 1) , (D2, c & offsetRow -~ 1) , (D3, c & offsetCol -~ 1) , (D4, c & offsetRow +~ 1) , (D5, c & offsetCol +~ 1 & offsetRow +~ 1) ] instance (Integral a) => HasNeighbors CubeCoordinate a where directions = cubeDirections instance (Integral a) => HasNeighbors AxialCoordinate a where directions = axialDirections instance (Integral a) => HasNeighbors OffsetEvenQ a where directions = offsetEvenQDirections instance (Integral a) => HasNeighbors OffsetOddQ a where directions = offsetOddQDirections instance (Integral a) => HasNeighbors OffsetEvenR a where directions = offsetEvenRDirections instance (Integral a) => HasNeighbors OffsetOddR a where directions = offsetOddRDirections
alios/hexagon
src/Data/Hexagon/Neighbors.hs
bsd-3-clause
5,092
0
12
1,527
2,007
1,116
891
108
2
{-# LINE 1 "Foreign.Safe.hs" #-} {-# LANGUAGE Safe #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.Safe -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- A collection of data types, classes, and functions for interfacing -- with another programming language. -- -- Safe API Only. -- ----------------------------------------------------------------------------- module Foreign.Safe {-# DEPRECATED "Safe is now the default, please use Foreign instead" #-} ( module Data.Bits , module Data.Int , module Data.Word , module Foreign.Ptr , module Foreign.ForeignPtr , module Foreign.StablePtr , module Foreign.Storable , module Foreign.Marshal ) where import Data.Bits import Data.Int import Data.Word import Foreign.Ptr import Foreign.ForeignPtr import Foreign.StablePtr import Foreign.Storable import Foreign.Marshal
phischu/fragnix
builtins/base/Foreign.Safe.hs
bsd-3-clause
1,151
0
5
227
116
81
35
19
0
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} module Network.Wai.Handler.Warp.Run where import Control.Arrow (first) import Control.Concurrent (threadDelay) import qualified Control.Concurrent as Conc (yield) import Control.Exception as E import Control.Monad (when, unless, void) import Data.ByteString (ByteString) import qualified Data.ByteString as S import Data.Char (chr) import Data.IP (toHostAddress, toHostAddress6) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Streaming.Network (bindPortTCP) import Network (sClose, Socket) import Network.Socket (accept, withSocketsDo, SockAddr(SockAddrInet, SockAddrInet6)) import qualified Network.Socket.ByteString as Sock import Network.Wai import Network.Wai.Handler.Warp.Buffer import Network.Wai.Handler.Warp.Counter import qualified Network.Wai.Handler.Warp.Date as D import qualified Network.Wai.Handler.Warp.FdCache as F import Network.Wai.Handler.Warp.HTTP2 import Network.Wai.Handler.Warp.Header import Network.Wai.Handler.Warp.ReadInt import Network.Wai.Handler.Warp.Recv import Network.Wai.Handler.Warp.Request import Network.Wai.Handler.Warp.Response import Network.Wai.Handler.Warp.SendFile import Network.Wai.Handler.Warp.Settings import qualified Network.Wai.Handler.Warp.Timeout as T import Network.Wai.Handler.Warp.Types import Network.Wai.Internal (ResponseReceived (ResponseReceived)) import System.Environment (getEnvironment) import System.IO.Error (isFullErrorType, ioeGetErrorType) #if WINDOWS import Network.Wai.Handler.Warp.Windows #else import System.Posix.IO (FdOption(CloseOnExec), setFdOption) import Network.Socket (fdSocket) #endif -- | Creating 'Connection' for plain HTTP based on a given socket. socketConnection :: Socket -> IO Connection socketConnection s = do bufferPool <- newBufferPool writeBuf <- allocateBuffer bufferSize let sendall = Sock.sendAll s return Connection { connSendMany = Sock.sendMany s , connSendAll = sendall , connSendFile = sendFile s writeBuf bufferSize sendall , connClose = sClose s >> freeBuffer writeBuf , connRecv = receive s bufferPool , connRecvBuf = receiveBuf s , connWriteBuffer = writeBuf , connBufferSize = bufferSize } #if __GLASGOW_HASKELL__ < 702 allowInterrupt :: IO () allowInterrupt = unblock $ return () #endif -- | Run an 'Application' on the given port. -- This calls 'runSettings' with 'defaultSettings'. run :: Port -> Application -> IO () run p = runSettings defaultSettings { settingsPort = p } -- | Run an 'Application' on the port present in the @PORT@ -- environment variable. Uses the 'Port' given when the variable is unset. -- This calls 'runSettings' with 'defaultSettings'. -- -- Since 3.0.9 runEnv :: Port -> Application -> IO () runEnv p app = do mp <- fmap (lookup "PORT") getEnvironment maybe (run p app) runReadPort mp where runReadPort :: String -> IO () runReadPort sp = case reads sp of ((p', _):_) -> run p' app _ -> fail $ "Invalid value in $PORT: " ++ sp -- | Run an 'Application' with the given 'Settings'. -- This opens a listen socket on the port defined in 'Settings' and -- calls 'runSettingsSocket'. runSettings :: Settings -> Application -> IO () runSettings set app = withSocketsDo $ bracket (bindPortTCP (settingsPort set) (settingsHost set)) sClose (\socket -> do setSocketCloseOnExec socket runSettingsSocket set socket app) -- | This installs a shutdown handler for the given socket and -- calls 'runSettingsConnection' with the default connection setup action -- which handles plain (non-cipher) HTTP. -- When the listen socket in the second argument is closed, all live -- connections are gracefully shut down. -- -- The supplied socket can be a Unix named socket, which -- can be used when reverse HTTP proxying into your application. -- -- Note that the 'settingsPort' will still be passed to 'Application's via the -- 'serverPort' record. runSettingsSocket :: Settings -> Socket -> Application -> IO () runSettingsSocket set socket app = do settingsInstallShutdownHandler set closeListenSocket runSettingsConnection set getConn app where getConn = do #if WINDOWS (s, sa) <- windowsThreadBlockHack $ accept socket #else (s, sa) <- accept socket #endif setSocketCloseOnExec s conn <- socketConnection s return (conn, sa) closeListenSocket = sClose socket -- | The connection setup action would be expensive. A good example -- is initialization of TLS. -- So, this converts the connection setup action to the connection maker -- which will be executed after forking a new worker thread. -- Then this calls 'runSettingsConnectionMaker' with the connection maker. -- This allows the expensive computations to be performed -- in a separate worker thread instead of the main server loop. -- -- Since 1.3.5 runSettingsConnection :: Settings -> IO (Connection, SockAddr) -> Application -> IO () runSettingsConnection set getConn app = runSettingsConnectionMaker set getConnMaker app where getConnMaker = do (conn, sa) <- getConn return (return conn, sa) -- | This modifies the connection maker so that it returns 'TCP' for 'Transport' -- (i.e. plain HTTP) then calls 'runSettingsConnectionMakerSecure'. runSettingsConnectionMaker :: Settings -> IO (IO Connection, SockAddr) -> Application -> IO () runSettingsConnectionMaker x y = runSettingsConnectionMakerSecure x (go y) where go = fmap (first (fmap (, TCP))) ---------------------------------------------------------------- -- | The core run function which takes 'Settings', -- a connection maker and 'Application'. -- The connection maker can return a connection of either plain HTTP -- or HTTP over TLS. -- -- Since 2.1.4 runSettingsConnectionMakerSecure :: Settings -> IO (IO (Connection, Transport), SockAddr) -> Application -> IO () runSettingsConnectionMakerSecure set getConnMaker app = do settingsBeforeMainLoop set counter <- newCounter D.withDateCache $ \dc -> F.withFdCache fdCacheDurationInSeconds $ \fc -> withTimeoutManager $ \tm -> acceptConnection set getConnMaker app dc fc tm counter where fdCacheDurationInSeconds = settingsFdCacheDuration set * 1000000 withTimeoutManager f = case settingsManager set of Just tm -> f tm Nothing -> bracket (T.initialize $ settingsTimeout set * 1000000) T.stopManager f -- Note that there is a thorough discussion of the exception safety of the -- following code at: https://github.com/yesodweb/wai/issues/146 -- -- We need to make sure of two things: -- -- 1. Asynchronous exceptions are not blocked entirely in the main loop. -- Doing so would make it impossible to kill the Warp thread. -- -- 2. Once a connection maker is received via acceptNewConnection, the -- connection is guaranteed to be closed, even in the presence of -- async exceptions. -- -- Our approach is explained in the comments below. acceptConnection :: Settings -> IO (IO (Connection, Transport), SockAddr) -> Application -> D.DateCache -> Maybe F.MutableFdCache -> T.Manager -> Counter -> IO () acceptConnection set getConnMaker app dc fc tm counter = do -- First mask all exceptions in acceptLoop. This is necessary to -- ensure that no async exception is throw between the call to -- acceptNewConnection and the registering of connClose. void $ mask_ acceptLoop gracefulShutdown counter where acceptLoop = do -- Allow async exceptions before receiving the next connection maker. allowInterrupt -- acceptNewConnection will try to receive the next incoming -- request. It returns a /connection maker/, not a connection, -- since in some circumstances creating a working connection -- from a raw socket may be an expensive operation, and this -- expensive work should not be performed in the main event -- loop. An example of something expensive would be TLS -- negotiation. mx <- acceptNewConnection case mx of Nothing -> return () Just (mkConn, addr) -> do fork set mkConn addr app dc fc tm counter acceptLoop acceptNewConnection = do ex <- try getConnMaker case ex of Right x -> return $ Just x Left e -> do settingsOnException set Nothing $ toException e if isFullErrorType (ioeGetErrorType e) then do -- "resource exhausted (Too many open files)" may -- happen by accept(). Wait a second hoping that -- resource will be available. threadDelay 1000000 acceptNewConnection else -- Assuming the listen socket is closed. return Nothing -- Fork a new worker thread for this connection maker, and ask for a -- function to unmask (i.e., allow async exceptions to be thrown). fork :: Settings -> IO (Connection, Transport) -> SockAddr -> Application -> D.DateCache -> Maybe F.MutableFdCache -> T.Manager -> Counter -> IO () fork set mkConn addr app dc fc tm counter = settingsFork set $ \ unmask -> -- Run the connection maker to get a new connection, and ensure -- that the connection is closed. If the mkConn call throws an -- exception, we will leak the connection. If the mkConn call is -- vulnerable to attacks (e.g., Slowloris), we do nothing to -- protect the server. It is therefore vital that mkConn is well -- vetted. -- -- We grab the connection before registering timeouts since the -- timeouts will be useless during connection creation, due to the -- fact that async exceptions are still masked. bracket mkConn closeConn $ \(conn, transport) -> -- We need to register a timeout handler for this thread, and -- cancel that handler as soon as we exit. bracket (T.registerKillThread tm) T.cancel $ \th -> let ii = InternalInfo th tm fc dc -- We now have fully registered a connection close handler -- in the case of all exceptions, so it is safe to one -- again allow async exceptions. in unmask . -- Call the user-supplied on exception code if any -- exceptions are thrown. handle (settingsOnException set Nothing) . -- Call the user-supplied code for connection open and close events bracket (onOpen addr) (onClose addr) $ \goingon -> -- Actually serve this connection. -- bracket with closeConn above ensures the connection is closed. when goingon $ serveConnection conn ii addr transport set app where closeConn (conn, _transport) = connClose conn onOpen adr = increase counter >> settingsOnOpen set adr onClose adr _ = decrease counter >> settingsOnClose set adr serveConnection :: Connection -> InternalInfo -> SockAddr -> Transport -> Settings -> Application -> IO () serveConnection conn ii origAddr transport settings app = do -- fixme: Upgrading to HTTP/2 should be supported. (h2,bs) <- if isHTTP2 transport then return (True, "") else do bs0 <- connRecv conn if S.length bs0 >= 4 && "PRI " `S.isPrefixOf` bs0 then return (True, bs0) else return (False, bs0) if h2 then do recvN <- makeReceiveN bs (connRecv conn) (connRecvBuf conn) -- fixme: origAddr http2 conn ii origAddr transport settings recvN app else do istatus <- newIORef False src <- mkSource (wrappedRecv conn th istatus (settingsSlowlorisSize settings)) writeIORef istatus True leftoverSource src bs addr <- getProxyProtocolAddr src http1 addr istatus src `E.catch` \e -> do sendErrorResponse addr istatus e throwIO (e :: SomeException) where getProxyProtocolAddr src = case settingsProxyProtocol settings of ProxyProtocolNone -> return origAddr ProxyProtocolRequired -> do seg <- readSource src parseProxyProtocolHeader src seg ProxyProtocolOptional -> do seg <- readSource src if S.isPrefixOf "PROXY " seg then parseProxyProtocolHeader src seg else do leftoverSource src seg return origAddr parseProxyProtocolHeader src seg = do let (header,seg') = S.break (== 0x0d) seg -- 0x0d == CR maybeAddr = case S.split 0x20 header of -- 0x20 == space ["PROXY","TCP4",clientAddr,_,clientPort,_] -> case [x | (x, t) <- reads (decodeAscii clientAddr), null t] of [a] -> Just (SockAddrInet (readInt clientPort) (toHostAddress a)) _ -> Nothing ["PROXY","TCP6",clientAddr,_,clientPort,_] -> case [x | (x, t) <- reads (decodeAscii clientAddr), null t] of [a] -> Just (SockAddrInet6 (readInt clientPort) 0 (toHostAddress6 a) 0) _ -> Nothing ("PROXY":"UNKNOWN":_) -> Just origAddr _ -> Nothing case maybeAddr of Nothing -> throwIO (BadProxyHeader (decodeAscii header)) Just a -> do leftoverSource src (S.drop 2 seg') -- drop CRLF return a decodeAscii = map (chr . fromEnum) . S.unpack th = threadHandle ii sendErrorResponse addr istatus e = do status <- readIORef istatus when status $ void $ sendResponse (settingsServerName settings) conn ii (dummyreq addr) defaultIndexRequestHeader (return S.empty) (errorResponse e) dummyreq addr = defaultRequest { remoteHost = addr } errorResponse e = settingsOnExceptionResponse settings e http1 addr istatus src = do (req', mremainingRef, idxhdr, nextBodyFlush) <- recvRequest settings conn ii addr src let req = req' { isSecure = isTransportSecure transport } keepAlive <- processRequest istatus src req mremainingRef idxhdr nextBodyFlush `E.catch` \e -> do -- Call the user-supplied exception handlers, passing the request. sendErrorResponse addr istatus e settingsOnException settings (Just req) e -- Don't throw the error again to prevent calling settingsOnException twice. return False when keepAlive $ http1 addr istatus src processRequest istatus src req mremainingRef idxhdr nextBodyFlush = do -- Let the application run for as long as it wants T.pause th -- In the event that some scarce resource was acquired during -- creating the request, we need to make sure that we don't get -- an async exception before calling the ResponseSource. keepAliveRef <- newIORef $ error "keepAliveRef not filled" _ <- app req $ \res -> do T.resume th -- FIXME consider forcing evaluation of the res here to -- send more meaningful error messages to the user. -- However, it may affect performance. writeIORef istatus False keepAlive <- sendResponse (settingsServerName settings) conn ii req idxhdr (readSource src) res writeIORef keepAliveRef keepAlive return ResponseReceived keepAlive <- readIORef keepAliveRef -- We just send a Response and it takes a time to -- receive a Request again. If we immediately call recv, -- it is likely to fail and the IO manager works. -- It is very costly. So, we yield to another Haskell -- thread hoping that the next Request will arrive -- when this Haskell thread will be re-scheduled. -- This improves performance at least when -- the number of cores is small. Conc.yield if not keepAlive then return False else -- If there is an unknown or large amount of data to still be read -- from the request body, simple drop this connection instead of -- reading it all in to satisfy a keep-alive request. case settingsMaximumBodyFlush settings of Nothing -> do flushEntireBody nextBodyFlush T.resume th return True Just maxToRead -> do let tryKeepAlive = do -- flush the rest of the request body isComplete <- flushBody nextBodyFlush maxToRead if isComplete then do T.resume th return True else return False case mremainingRef of Just ref -> do remaining <- readIORef ref if remaining <= maxToRead then tryKeepAlive else return False Nothing -> tryKeepAlive flushEntireBody :: IO ByteString -> IO () flushEntireBody src = loop where loop = do bs <- src unless (S.null bs) loop flushBody :: IO ByteString -- ^ get next chunk -> Int -- ^ maximum to flush -> IO Bool -- ^ True == flushed the entire body, False == we didn't flushBody src = loop where loop toRead = do bs <- src let toRead' = toRead - S.length bs case () of () | S.null bs -> return True | toRead' >= 0 -> loop toRead' | otherwise -> return False wrappedRecv :: Connection -> T.Handle -> IORef Bool -> Int -> IO ByteString wrappedRecv Connection { connRecv = recv } th istatus slowlorisSize = do bs <- recv unless (S.null bs) $ do writeIORef istatus True when (S.length bs >= slowlorisSize) $ T.tickle th return bs -- Copied from: https://github.com/mzero/plush/blob/master/src/Plush/Server/Warp.hs setSocketCloseOnExec :: Socket -> IO () #if WINDOWS setSocketCloseOnExec _ = return () #else setSocketCloseOnExec socket = setFdOption (fromIntegral $ fdSocket socket) CloseOnExec True #endif gracefulShutdown :: Counter -> IO () gracefulShutdown counter = waitForZero counter
AndrewRademacher/wai
warp/Network/Wai/Handler/Warp/Run.hs
mit
19,484
8
29
5,909
3,613
1,873
1,740
304
18
{-# LANGUAGE OverloadedStrings #-} module CountdownGame.Players ( isRegistered , registeredPlayer , registerPlayer )where import Control.Monad.IO.Class(liftIO) import Data.Char (toLower) import Data.List(isPrefixOf) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe(isJust) import Data.IORef (IORef(..), newIORef, atomicModifyIORef') import Data.Text (Text, unpack) import Web.Scotty import qualified Web.Scotty as S import Countdown.Game (Player(Player), nickName, playerId) import CountdownGame.Spiel (State (connectionPool)) import CountdownGame.Database as Db import qualified CountdownGame.Cookies as Cookies registeredPlayer :: State -> ActionM (Maybe Player) registeredPlayer state = do cookie <- Cookies.getPlayerCookie case cookie of Nothing -> return Nothing Just c -> liftIO $ Db.checkPlayer (Cookies.playerId c) (Cookies.nickName c) (connectionPool state) registerPlayer :: Text -> State -> ActionM Player registerPlayer nick state = do cookie <- Cookies.getPlayerCookie player <- liftIO $ case cookie of Nothing -> Db.addPlayer nick (connectionPool state) Just c -> Db.updatePlayer (Cookies.playerId c) nick (connectionPool state) let cookie = Cookies.PlayerCookie (nickName player) (playerId player) Cookies.setPlayerCookie cookie return player isRegistered :: State -> ActionM Bool isRegistered state = do player <- registeredPlayer state return $ isJust player fromCookie :: Cookies.PlayerCookie -> Player fromCookie cookie = Player (Cookies.nickName cookie) (Cookies.playerId cookie)
CarstenKoenig/Countdown
src/web/CountdownGame/Players.hs
mit
1,627
0
15
269
493
264
229
40
2
module BankAccount ( BankAccount , openAccount , closeAccount , getBalance , incrementBalance ) where import Control.Concurrent.STM ( TVar , readTVar , newTVar , writeTVar , modifyTVar , atomically ) newtype BankAccount = Account (TVar (Maybe Integer)) openAccount :: IO BankAccount openAccount = atomically $ Account <$> newTVar (Just 0) closeAccount :: BankAccount -> IO () closeAccount (Account var) = atomically $ writeTVar var Nothing getBalance :: BankAccount -> IO (Maybe Integer) getBalance (Account var) = atomically $ readTVar var incrementBalance :: BankAccount -> Integer -> IO (Maybe Integer) incrementBalance (Account var) amount = atomically $ do modifyTVar var $ fmap (+ amount) readTVar var
Bugfry/exercises
exercism/haskell/bank-account/src/BankAccount.hs
mit
745
0
10
141
238
125
113
24
1
-- -- -- ---------------- -- Exercise 7.5. ---------------- -- -- -- module E'7''5 where import Prelude hiding ( product ) product :: [Integer] -> Integer product [] = 1 product ( integer : remainingIntegers ) = integer * (product remainingIntegers)
pascal-knodel/haskell-craft
_/links/E'7''5.hs
mit
264
0
7
54
69
43
26
6
1
module Servant.Server.Auth.Token.Acid( AcidBackendT , runAcidBackendT , deriveAcidHasStorage ) where import Control.Monad.Base import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Acid import Data.Acid.Core import Language.Haskell.TH import Servant.Server import Servant.Server.Auth.Token.Config import Servant.Server.Auth.Token.Model -- | Monad transformer that implements storage backend newtype AcidBackendT st m a = AcidBackendT { unAcidBackendT :: ReaderT (AuthConfig, AcidState st) (ExceptT ServantErr m) a } deriving (Functor, Applicative, Monad, MonadIO, MonadError ServantErr, MonadReader (AuthConfig, AcidState st)) deriving instance MonadBase IO m => MonadBase IO (AcidBackendT st m) instance Monad m => HasAuthConfig (AcidBackendT st m) where getAuthConfig = fmap fst $ AcidBackendT ask newtype StMAcidBackendT st m a = StMAcidBackendT { unStMAcidBackendT :: StM (ReaderT (AuthConfig, AcidState st) (ExceptT ServantErr m)) a } instance MonadBaseControl IO m => MonadBaseControl IO (AcidBackendT st m) where type StM (AcidBackendT st m) a = StMAcidBackendT st m a liftBaseWith f = AcidBackendT $ liftBaseWith $ \q -> f (fmap StMAcidBackendT . q . unAcidBackendT) restoreM = AcidBackendT . restoreM . unStMAcidBackendT -- | Execute backend action with given connection pool. runAcidBackendT :: AuthConfig -> AcidState st -> AcidBackendT st m a -> m (Either ServantErr a) runAcidBackendT cfg db ma = runExceptT $ runReaderT (unAcidBackendT ma) (cfg, db) -- | Derives acid-state 'HasStorage' instance for functions that are generated in 'makeModelAcidic'. -- -- Use this as following: -- @ -- instance HasModelRead MyState where -- askModel = authModel -- -- instance HasModelWrite MyState where -- putModel m v = m { authModel = v } -- -- makeModelAcidic ''MyState -- deriveAcidHasStorage -- @ deriveAcidHasStorage :: Name -> DecsQ deriveAcidHasStorage globalState = [d| -- | Helper to execute DB actions in backend monad liftAcidQuery :: (QueryEvent event, MonadIO m, MethodState event ~ $st) => event -> AcidBackendT $st m (EventResult event) liftAcidQuery e = do (_, db) <- ask liftIO $ query db e -- | Helper to execute DB actions in backend monad liftAcidUpdate :: (UpdateEvent event, MonadIO m, MethodState event ~ $st) => event -> AcidBackendT $st m (EventResult event) liftAcidUpdate e = do (_, db) <- ask liftIO $ update db e instance MonadIO m => HasStorage (AcidBackendT $st m) where getUserImpl = liftAcidQuery . $(conE $ mkName "GetUserImpl") getUserImplByLogin = liftAcidQuery . $(conE $ mkName "GetUserImplByLogin") listUsersPaged page size = liftAcidQuery $ $(conE $ mkName "ListUsersPaged") page size getUserImplPermissions = liftAcidQuery . $(conE $ mkName "GetUserImplPermissions") deleteUserPermissions = liftAcidUpdate . $(conE $ mkName "DeleteUserPermissions") insertUserPerm = liftAcidUpdate . $(conE $ mkName "InsertUserPerm") insertUserImpl = liftAcidUpdate . $(conE $ mkName "InsertUserImpl") replaceUserImpl i v = liftAcidUpdate $ $(conE $ mkName "ReplaceUserImpl") i v deleteUserImpl = liftAcidUpdate . $(conE $ mkName "DeleteUserImpl") hasPerm i p = liftAcidQuery $ $(conE $ mkName "HasPerm") i p getFirstUserByPerm = liftAcidQuery . $(conE $ mkName "GetFirstUserByPerm") selectUserImplGroups = liftAcidQuery . $(conE $ mkName "SelectUserImplGroups") clearUserImplGroups = liftAcidUpdate . $(conE $ mkName "ClearUserImplGroups") insertAuthUserGroup = liftAcidUpdate . $(conE $ mkName "InsertAuthUserGroup") insertAuthUserGroupUsers = liftAcidUpdate . $(conE $ mkName "InsertAuthUserGroupUsers") insertAuthUserGroupPerms = liftAcidUpdate . $(conE $ mkName "InsertAuthUserGroupPerms") getAuthUserGroup = liftAcidQuery . $(conE $ mkName "GetAuthUserGroup") listAuthUserGroupPermissions = liftAcidQuery . $(conE $ mkName "ListAuthUserGroupPermissions") listAuthUserGroupUsers = liftAcidQuery . $(conE $ mkName "ListAuthUserGroupUsers") replaceAuthUserGroup i v = liftAcidUpdate $ $(conE $ mkName "ReplaceAuthUserGroup") i v clearAuthUserGroupUsers = liftAcidUpdate . $(conE $ mkName "ClearAuthUserGroupUsers") clearAuthUserGroupPerms = liftAcidUpdate . $(conE $ mkName "ClearAuthUserGroupPerms") deleteAuthUserGroup = liftAcidUpdate . $(conE $ mkName "DeleteAuthUserGroup") listGroupsPaged page size = liftAcidQuery $ $(conE $ mkName "ListGroupsPaged") page size setAuthUserGroupName i n = liftAcidUpdate $ $(conE $ mkName "SetAuthUserGroupName") i n setAuthUserGroupParent i mp = liftAcidUpdate $ $(conE $ mkName "SetAuthUserGroupParent") i mp insertSingleUseCode = liftAcidUpdate . $(conE $ mkName "InsertSingleUseCode") setSingleUseCodeUsed i mt = liftAcidUpdate $ $(conE $ mkName "SetSingleUseCodeUsed") i mt getUnusedCode c i t = liftAcidQuery $ $(conE $ mkName "GetUnusedCode") c i t invalidatePermamentCodes i t = liftAcidUpdate $ $(conE $ mkName "InvalidatePermamentCodes") i t selectLastRestoreCode i t = liftAcidQuery $ $(conE $ mkName "SelectLastRestoreCode") i t insertUserRestore = liftAcidUpdate . $(conE $ mkName "InsertUserRestore") findRestoreCode i rc t = liftAcidQuery $ $(conE $ mkName "FindRestoreCode") i rc t replaceRestoreCode i v = liftAcidUpdate $ $(conE $ mkName "ReplaceRestoreCode") i v findAuthToken i t = liftAcidQuery $ $(conE $ mkName "FindAuthToken") i t findAuthTokenByValue t = liftAcidQuery $ $(conE $ mkName "FindAuthTokenByValue") t insertAuthToken = liftAcidUpdate . $(conE $ mkName "InsertAuthToken") replaceAuthToken i v = liftAcidUpdate $ $(conE $ mkName "ReplaceAuthToken") i v {-# INLINE getUserImpl #-} {-# INLINE getUserImplByLogin #-} {-# INLINE listUsersPaged #-} {-# INLINE getUserImplPermissions #-} {-# INLINE deleteUserPermissions #-} {-# INLINE insertUserPerm #-} {-# INLINE insertUserImpl #-} {-# INLINE replaceUserImpl #-} {-# INLINE deleteUserImpl #-} {-# INLINE hasPerm #-} {-# INLINE getFirstUserByPerm #-} {-# INLINE selectUserImplGroups #-} {-# INLINE clearUserImplGroups #-} {-# INLINE insertAuthUserGroup #-} {-# INLINE insertAuthUserGroupUsers #-} {-# INLINE insertAuthUserGroupPerms #-} {-# INLINE getAuthUserGroup #-} {-# INLINE listAuthUserGroupPermissions #-} {-# INLINE listAuthUserGroupUsers #-} {-# INLINE replaceAuthUserGroup #-} {-# INLINE clearAuthUserGroupUsers #-} {-# INLINE clearAuthUserGroupPerms #-} {-# INLINE deleteAuthUserGroup #-} {-# INLINE listGroupsPaged #-} {-# INLINE setAuthUserGroupName #-} {-# INLINE setAuthUserGroupParent #-} {-# INLINE insertSingleUseCode #-} {-# INLINE setSingleUseCodeUsed #-} {-# INLINE getUnusedCode #-} {-# INLINE invalidatePermamentCodes #-} {-# INLINE selectLastRestoreCode #-} {-# INLINE insertUserRestore #-} {-# INLINE findRestoreCode #-} {-# INLINE replaceRestoreCode #-} {-# INLINE findAuthToken #-} {-# INLINE findAuthTokenByValue #-} {-# INLINE insertAuthToken #-} {-# INLINE replaceAuthToken #-} |] where st = conT globalState
VyacheslavHashov/servant-auth-token
servant-auth-token-acid/src/Servant/Server/Auth/Token/Acid.hs
bsd-3-clause
7,216
0
12
1,257
495
280
215
-1
-1
-- -- Copyright © 2013-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- | OAuth2 API implementation. -- -- This implementation assumes the use of Shibboleth, which doesn't actually -- mean anything all that specific. This just means that we expect a particular -- header that says who the user is and what permissions they have to delegate. -- -- The intention is to seperate all OAuth2 specific logic from our particular -- way of handling AAA. module Network.OAuth2.Server.API ( -- * API handlers -- -- $ These functions each handle a single endpoint in the OAuth2 Server -- HTTP API. postTokenEndpointR, getAuthorizeEndpointR, postAuthorizeEndpointR, postVerifyEndpointR, -- * Helpers checkClientAuth, checkShibHeaders, ) where import Control.Applicative import Control.Lens import Control.Monad import Control.Monad.Error.Class (MonadError, throwError) import Control.Monad.Reader.Class (MonadReader, ask) import Control.Monad.State.Strict import Control.Monad.Trans.Except (ExceptT (..), runExceptT) import Crypto.Scrypt import qualified Data.ByteString.Char8 as BC import Data.Conduit import Data.Conduit.List import Data.Foldable (traverse_) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Time.Clock (addUTCTime, getCurrentTime) import Formatting (sformat, shown, (%)) import Network.HTTP.Types hiding (Header) import Network.OAuth2.Server.Types as X import System.Log.Logger import Yesod.Core import Network.OAuth2.Server.Foundation import Network.OAuth2.Server.Store hiding (logName) import Network.OAuth2.Server.UI -- | Temporary, until there is an instance in Yesod. instance MonadHandler m => MonadHandler (ExceptT e m) where type HandlerSite (ExceptT e m) = HandlerSite m liftHandlerT = lift . liftHandlerT -- Logging logName :: String logName = "Network.OAuth2.Server.API" -- Wrappers for underlying logging system debugLog, errorLog :: MonadIO m => String -> Text -> m () debugLog = wrapLogger debugM errorLog = wrapLogger errorM wrapLogger :: MonadIO m => (String -> String -> IO a) -> String -> Text -> m a wrapLogger logger component msg = do liftIO $ logger (logName <> " " <> component <> ": ") (T.unpack msg) -- * HTTP Headers -- -- $ The OAuth2 Server API uses HTTP headers to exchange information between -- system components and to control caching behaviour. checkShibHeaders :: (MonadHandler m, MonadReader OAuth2Server m) => m (UserID, Scope) checkShibHeaders = do OAuth2Server{serverOptions=ServerOptions{..}} <- ask uh' <- lookupHeader optUserHeader uid <- case preview userID =<< uh' of Nothing -> error "Shibboleth User header missing" Just uid -> return uid sh' <- headerToScope <$> lookupHeader optUserScopesHeader sc <- case bsToScope =<< sh' of Nothing -> error "Shibboleth User Scope header missing" Just sc -> return sc return (uid,sc) where headerToScope Nothing = Nothing headerToScope (Just hdr) = let components = BC.split ';' hdr in Just $ BC.intercalate " " components -- | Check that the request is valid. If it is we provide an 'AccessResponse', -- otherwise we return an 'OAuth2Error'. -- -- The response headers are mentioned here: -- -- https://tools.ietf.org/html/rfc6749#section-5.1 -- -- The authorization server MUST include the HTTP "Cache-Control" response -- header field [RFC2616] with a value of "no-store" in any response -- containing tokens, credentials, or other sensitive information, as well -- as the "Pragma" response header field [RFC2616] with a value of -- "no-cache". -- -- Any IO exceptions that are thrown are probably catastrophic and unaccounted -- for, and should not be caught. postTokenEndpointR :: Handler Value postTokenEndpointR = wrapError $ do OAuth2Server{serverTokenStore=ref} <- ask -- Lookup client credentials auth_header_t <- lookupHeader "Authorization" `orElseM` invalidRequest "AuthHeader missing" auth_header <- preview authHeader auth_header_t `orElse` invalidRequest "Invalid AuthHeader" client_id <- checkClientAuth ref auth_header `orElseM` invalidRequest "Invalid Client Credentials" (xs,_) <- runRequestBody req <- case decodeAccessRequest xs of Left e -> throwError e Right req -> return req (user, modified_scope, maybe_token_id) <- case req of -- https://tools.ietf.org/html/rfc6749#section-4.1.3 RequestAuthorizationCode auth_code uri client -> do (user, modified_scope) <- checkClientAuthCode ref client_id auth_code uri client return (user, modified_scope, Nothing) -- http://tools.ietf.org/html/rfc6749#section-4.4.2 RequestClientCredentials _ -> unsupportedGrantType "client_credentials is not supported" -- http://tools.ietf.org/html/rfc6749#section-6 RequestRefreshToken tok request_scope -> checkRefreshToken ref client_id tok request_scope t <- liftIO getCurrentTime let expires = Just $ addUTCTime 1800 t access_grant = TokenGrant { grantTokenType = Bearer , grantExpires = expires , grantUserID = user , grantClientID = Just client_id , grantScope = modified_scope } -- Create a refresh token with these details. refresh_expires = Just $ addUTCTime (3600 * 24 * 7) t refresh_grant = access_grant { grantTokenType = Refresh , grantExpires = refresh_expires } -- Save the new tokens to the store. (rid, refresh_details) <- liftIO $ storeCreateToken ref refresh_grant Nothing ( _, access_details) <- liftIO $ storeCreateToken ref access_grant (Just rid) -- Revoke the token iff we got one liftIO $ traverse_ (storeRevokeToken ref) maybe_token_id return . toJSON $ grantResponse t access_details (Just $ tokenDetailsToken refresh_details) where wrapError :: ExceptT OAuth2Error Handler Value -> Handler Value wrapError a = do res <- runExceptT a either (sendResponseStatus badRequest400 . toJSON) return res orElse a e = maybe e return a orElseM a e = do res <- a orElse res e fromMaybeM :: Monad m => m a -> m (Maybe a) -> m a fromMaybeM d x = x >>= maybe d return -- -- Verify client, scope and request code. -- checkClientAuthCode :: TokenStore ref => ref -> ClientID -> Code -> Maybe RedirectURI -> Maybe ClientID -> ExceptT OAuth2Error Handler (Maybe UserID, Scope) checkClientAuthCode _ _ _ _ Nothing = invalidRequest "No client ID supplied." checkClientAuthCode ref client_id auth_code uri (Just purported_client) = do when (client_id /= purported_client) $ unauthorizedClient "Invalid client credentials" request_code <- fromMaybeM (invalidGrant "Request code not found") (liftIO $ storeReadCode ref auth_code) -- Fail if redirect_uri doesn't match what's in the database. case uri of Just uri' | uri' /= (requestCodeRedirectURI request_code) -> do debugLog "checkClientAuthCode" $ sformat ("Redirect URI mismatch verifying access token request: requested" % shown % " but got " % shown ) uri (requestCodeRedirectURI request_code) invalidRequest "Invalid redirect URI" _ -> return () case requestCodeScope request_code of Nothing -> do debugLog "checkClientAuthCode" $ sformat ("No scope found for code " % shown) request_code invalidScope "No scope found" Just code_scope -> return (Just $ requestCodeUserID request_code, code_scope) -- -- Verify scope and request token. -- checkRefreshToken :: TokenStore ref => ref -> ClientID -> Token -> Maybe Scope -> ExceptT OAuth2Error Handler (Maybe UserID, Scope, Maybe TokenID) checkRefreshToken ref client_id tok request_scope = do previous <- liftIO $ storeReadToken ref (Left tok) case previous of Just (tid, TokenDetails{..}) | (Just client_id == tokenDetailsClientID) -> do let scope' = fromMaybe tokenDetailsScope request_scope -- Check scope compatible. -- @TODO(thsutton): The concern with scopes should probably -- be completely removed here. unless (compatibleScope scope' tokenDetailsScope) $ do debugLog "checkRefreshToken" $ sformat ("Refresh requested with incompatible scopes" % shown % " vs " % shown) request_scope tokenDetailsScope invalidScope "Incompatible scope" return (tokenDetailsUserID, scope', Just tid) -- The old token is dead or client_id doesn't match. _ -> do debugLog "checkRefreshToken" $ sformat ("Got passed invalid token " % shown) tok invalidRequest "Invalid token" -- | OAuth2 Authorization Endpoint -- -- Allows authenticated users to review and authorize a code token grant -- request. -- -- http://tools.ietf.org/html/rfc6749#section-3.1 -- -- This handler must be protected by Shibboleth (or other mechanism in the -- front-end proxy). It decodes the client request and presents a UI allowing -- the user to approve or reject a grant request. -- -- TODO: Handle the validation of things more nicely here, preferably -- shifting them out of here entirely. getAuthorizeEndpointR :: Handler Html getAuthorizeEndpointR = wrapError $ do OAuth2Server{serverTokenStore=ref} <- ask (user_id, permissions) <- checkShibHeaders scope' <- (fromPathPiece =<<) <$> lookupGetParam "scope" client_state <- (fromPathPiece =<<) <$> lookupGetParam "state" -- Required: a ClientID value, which identifies a client. client_id_t <- lookupGetParam "client_id" `orElseM` invalidRequest "client_id missing" client_id <- preview clientID (T.encodeUtf8 client_id_t) `orElse` invalidRequest "invalid client_id" client_details@ClientDetails{..} <- liftIO (storeLookupClient ref client_id) `orElseM` invalidRequest "invalid client_id" -- Optional: requested redirect URI. -- https://tools.ietf.org/html/rfc6749#section-3.1.2.3 maybe_redirect_uri_t <- lookupGetParam "redirect_uri" redirect_uri <- case maybe_redirect_uri_t of Nothing -> case clientRedirectURI of redirect':_ -> return redirect' _ -> error $ "No redirect_uri provided and no unique default registered for client " <> show clientClientId Just redirect_uri_t -> do redirect_uri <- preview redirectURI (T.encodeUtf8 redirect_uri_t) `orElse` invalidRequest "invalid redirect_uri" if redirect_uri `elem` clientRedirectURI then return redirect_uri else error $ show redirect_uri <> " /= " <> show clientRedirectURI -- From here on, we have enough inforation to handle errors. -- https://tools.ietf.org/html/rfc6749#section-4.1.2.1 put $ Just (client_state, redirect_uri) -- Required: a supported ResponseType value. response_type <- lookupGetParam "response_type" case T.toLower <$> response_type of Just "code" -> return () Just _ -> invalidRequest "Invalid response type" Nothing -> invalidRequest "Response type is missing" -- Optional (but we currently require): requested scope. requested_scope <- case scope' of Nothing -> invalidRequest "Scope is missing" Just requested_scope | requested_scope `compatibleScope` permissions -> return requested_scope | otherwise -> invalidScope "" -- Create a code for this request. request_code <- liftIO $ storeCreateCode ref user_id clientClientId redirect_uri requested_scope client_state lift . lift . defaultLayout $ renderAuthorizePage request_code client_details where orElse a e = maybe e return a orElseM a e = do res <- a orElse res e wrapError :: ExceptT OAuth2Error (StateT (Maybe (Maybe ClientState, RedirectURI)) Handler) a -> Handler a wrapError handler = do (res, maybe_redirect) <- flip runStateT Nothing . runExceptT $ handler case res of Right x -> return x Left e -> case maybe_redirect of Just (client_state, redirect_uri) -> do let url = addQueryParameters redirect_uri $ renderErrorFormUrlEncoded e <> [("state", state' ^.re clientState) | Just state' <- [client_state]] redirect . T.decodeUtf8 $ url ^.re redirectURI Nothing -> sendResponseStatus badRequest400 $ toJSON e -- | Handle the approval or rejection, we get here from the page served in -- 'authorizeEndpoint' postAuthorizeEndpointR :: Handler () postAuthorizeEndpointR = do OAuth2Server{serverTokenStore=ref} <- ask (user_id, _) <- checkShibHeaders code' <- do res <- (preview code . T.encodeUtf8 =<<) <$> lookupPostParam "code" case res of Nothing -> invalidArgs [] Just x -> return x maybe_request_code <- liftIO $ storeReadCode ref code' case maybe_request_code of Just RequestCode{..} | requestCodeUserID == user_id -> do let state_param = [ ("state", state' ^.re clientState) | state' <- maybeToList requestCodeState ] redirect_uri_st = addQueryParameters requestCodeRedirectURI state_param maybe_act <- lookupPostParam "action" case T.toLower <$> maybe_act of Just "approve" -> do res <- liftIO $ storeActivateCode ref code' case res of -- TODO: Revoke things Nothing -> permissionDenied "You are not authorized to approve this request." Just _ -> do let uri' = addQueryParameters redirect_uri_st [("code", code' ^.re code)] redirect . T.decodeUtf8 $ uri' ^.re redirectURI Just "decline" -> do -- TODO: actually care if deletion succeeded. void . liftIO $ storeDeleteCode ref code' let e = OAuth2Error AccessDenied Nothing Nothing url = addQueryParameters redirect_uri_st $ renderErrorFormUrlEncoded e redirect . T.decodeUtf8 $ url ^.re redirectURI Just act' -> error $ "Invalid action: " <> show act' Nothing -> error "no action" _ -> permissionDenied "You are not authorized to approve this request." -- | Verify a token and return information about the principal and grant. -- -- Restricted to authorized clients. postVerifyEndpointR :: Handler Value postVerifyEndpointR = wrapError $ do OAuth2Server{serverTokenStore=ref} <- ask auth_header_t <- lookupHeader "Authorization" `orElseM` invalidRequest "AuthHeader missing" auth <- preview authHeader auth_header_t `orElse` invalidRequest "Invalid AuthHeader" token_bs <- rawRequestBody $$ fold mappend mempty token' <- case token_bs ^? token of Nothing -> invalidRequest "Invalid Token" Just token' -> return token' -- 1. Check client authentication. maybe_client_id <- checkClientAuth ref auth client_id <- case maybe_client_id of Nothing -> do debugLog "verifyEndpoint" $ sformat ("Invalid client credentials: " % shown) auth invalidClient "Invalid Client" Just client_id -> do return client_id -- 2. Load token information. tok <- liftIO $ storeReadToken ref (Left token') case tok of Nothing -> do debugLog "verifyEndpoint" $ sformat ("Cannot verify token: failed to lookup " % shown) token' notFound Just (_, details) -> do -- 3. Check client authorization. when (Just client_id /= tokenDetailsClientID details) $ do debugLog "verifyEndpoint" $ sformat ("Client " % shown % " attempted to verify someone elses token: " % shown) client_id token' notFound -- 4. Send the access response. now <- liftIO getCurrentTime return . toJSON $ grantResponse now details (Just token') where wrapError :: ExceptT OAuth2Error Handler Value -> Handler Value wrapError a = do res <- runExceptT a either (sendResponseStatus badRequest400 . toJSON) return res orElse a e = maybe e return a orElseM a e = do res <- a orElse res e -- | Given an AuthHeader sent by a client, verify that it authenticates. -- If it does, return the authenticated ClientID; otherwise, Nothing. checkClientAuth :: (MonadIO m, MonadError OAuth2Error m, TokenStore ref) => ref -> AuthHeader -> m (Maybe ClientID) checkClientAuth ref auth = do case preview authDetails auth of Nothing -> do debugLog "checkClientAuth" "Got an invalid auth header." invalidRequest "Invalid auth header provided." Just (client_id, secret) -> do maybe_client <- liftIO $ storeLookupClient ref client_id return $ verifyClientSecret maybe_client secret where verifyClientSecret :: Maybe ClientDetails -> Password -> Maybe ClientID verifyClientSecret Nothing _ = Nothing verifyClientSecret (Just ClientDetails{..}) secret = do let pass = Pass . T.encodeUtf8 $ review password secret -- Verify with default scrypt params. if verifyPass' pass clientSecret then Just clientClientId else Nothing
anchor/oauth2-server
lib/Network/OAuth2/Server/API.hs
bsd-3-clause
19,446
0
30
5,679
3,817
1,913
1,904
307
9
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/ByteString/Short/Internal.hs" #-} {-# LANGUAGE DeriveDataTypeable, CPP, BangPatterns, RankNTypes, ForeignFunctionInterface, MagicHash, UnboxedTuples, UnliftedFFITypes #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE Unsafe #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.ByteString.Short.Internal -- Copyright : (c) Duncan Coutts 2012-2013 -- License : BSD-style -- -- Maintainer : duncan@community.haskell.org -- Stability : stable -- Portability : ghc only -- -- Internal representation of ShortByteString -- module Data.ByteString.Short.Internal ( -- * The @ShortByteString@ type and representation ShortByteString(..), -- * Conversions toShort, fromShort, pack, unpack, -- * Other operations empty, null, length, index, unsafeIndex, -- * Low level operations createFromPtr, copyToPtr ) where import Data.ByteString.Internal (ByteString(..), accursedUnutterablePerformIO) import Data.Typeable (Typeable) import Data.Data (Data(..), mkNoRepType) import Data.Semigroup (Semigroup((<>))) import Data.Monoid (Monoid(..)) import Data.String (IsString(..)) import Control.DeepSeq (NFData(..)) import qualified Data.List as List (length) import Foreign.C.Types (CSize(..), CInt(..)) import Foreign.Ptr import Foreign.ForeignPtr (touchForeignPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified GHC.Exts import GHC.Exts ( Int(I#), Int#, Ptr(Ptr), Addr#, Char(C#) , State#, RealWorld , ByteArray#, MutableByteArray# , newByteArray# , newPinnedByteArray# , byteArrayContents# , unsafeCoerce# , sizeofByteArray# , indexWord8Array#, indexCharArray# , writeWord8Array#, writeCharArray# , unsafeFreezeByteArray# ) import GHC.IO import GHC.ForeignPtr (ForeignPtr(ForeignPtr), ForeignPtrContents(PlainPtr)) import GHC.ST (ST(ST), runST) import GHC.Word import Prelude ( Eq(..), Ord(..), Ordering(..), Read(..), Show(..) , ($), error, (++) , Bool(..), (&&), otherwise , (+), (-), fromIntegral , return ) -- | A compact representation of a 'Word8' vector. -- -- It has a lower memory overhead than a 'ByteString' and and does not -- contribute to heap fragmentation. It can be converted to or from a -- 'ByteString' (at the cost of copying the string data). It supports very few -- other operations. -- -- It is suitable for use as an internal representation for code that needs -- to keep many short strings in memory, but it /should not/ be used as an -- interchange type. That is, it should not generally be used in public APIs. -- The 'ByteString' type is usually more suitable for use in interfaces; it is -- more flexible and it supports a wide range of operations. -- data ShortByteString = SBS ByteArray# deriving Typeable -- The ByteArray# representation is always word sized and aligned but with a -- known byte length. Our representation choice for ShortByteString is to leave -- the 0--3 trailing bytes undefined. This means we can use word-sized writes, -- but we have to be careful with reads, see equateBytes and compareBytes below. instance Eq ShortByteString where (==) = equateBytes instance Ord ShortByteString where compare = compareBytes instance Semigroup ShortByteString where (<>) = append instance Monoid ShortByteString where mempty = empty mappend = (<>) mconcat = concat instance NFData ShortByteString where rnf (SBS {}) = () instance Show ShortByteString where showsPrec p ps r = showsPrec p (unpackChars ps) r instance Read ShortByteString where readsPrec p str = [ (packChars x, y) | (x, y) <- readsPrec p str ] instance IsString ShortByteString where fromString = packChars instance Data ShortByteString where gfoldl f z txt = z packBytes `f` (unpackBytes txt) toConstr _ = error "Data.ByteString.Short.ShortByteString.toConstr" gunfold _ _ = error "Data.ByteString.Short.ShortByteString.gunfold" dataTypeOf _ = mkNoRepType "Data.ByteString.Short.ShortByteString" ------------------------------------------------------------------------ -- Simple operations -- | /O(1)/. The empty 'ShortByteString'. empty :: ShortByteString empty = create 0 (\_ -> return ()) -- | /O(1)/ The length of a 'ShortByteString'. length :: ShortByteString -> Int length (SBS barr#) = I# (sizeofByteArray# barr#) -- | /O(1)/ Test whether a 'ShortByteString' is empty. null :: ShortByteString -> Bool null sbs = length sbs == 0 -- | /O(1)/ 'ShortByteString' index (subscript) operator, starting from 0. index :: ShortByteString -> Int -> Word8 index sbs i | i >= 0 && i < length sbs = unsafeIndex sbs i | otherwise = indexError sbs i unsafeIndex :: ShortByteString -> Int -> Word8 unsafeIndex sbs = indexWord8Array (asBA sbs) indexError :: ShortByteString -> Int -> a indexError sbs i = error $ "Data.ByteString.Short.index: error in array index; " ++ show i ++ " not in range [0.." ++ show (length sbs) ++ ")" ------------------------------------------------------------------------ -- Internal utils asBA :: ShortByteString -> BA asBA (SBS ba# ) = BA# ba# create :: Int -> (forall s. MBA s -> ST s ()) -> ShortByteString create len fill = runST (do mba <- newByteArray len fill mba BA# ba# <- unsafeFreezeByteArray mba return (SBS ba# )) {-# INLINE create #-} ------------------------------------------------------------------------ -- Conversion to and from ByteString -- | /O(n)/. Convert a 'ByteString' into a 'ShortByteString'. -- -- This makes a copy, so does not retain the input string. -- toShort :: ByteString -> ShortByteString toShort !bs = unsafeDupablePerformIO (toShortIO bs) toShortIO :: ByteString -> IO ShortByteString toShortIO (PS fptr off len) = do mba <- stToIO (newByteArray len) let ptr = unsafeForeignPtrToPtr fptr stToIO (copyAddrToByteArray (ptr `plusPtr` off) mba 0 len) touchForeignPtr fptr BA# ba# <- stToIO (unsafeFreezeByteArray mba) return (SBS ba# ) -- | /O(n)/. Convert a 'ShortByteString' into a 'ByteString'. -- fromShort :: ShortByteString -> ByteString fromShort !sbs = unsafeDupablePerformIO (fromShortIO sbs) fromShortIO :: ShortByteString -> IO ByteString fromShortIO sbs = do let len = length sbs mba@(MBA# mba#) <- stToIO (newPinnedByteArray len) stToIO (copyByteArray (asBA sbs) 0 mba 0 len) let fp = ForeignPtr (byteArrayContents# (unsafeCoerce# mba#)) (PlainPtr mba#) return (PS fp 0 len) ------------------------------------------------------------------------ -- Packing and unpacking from lists -- | /O(n)/. Convert a list into a 'ShortByteString' pack :: [Word8] -> ShortByteString pack = packBytes -- | /O(n)/. Convert a 'ShortByteString' into a list. unpack :: ShortByteString -> [Word8] unpack = unpackBytes packChars :: [Char] -> ShortByteString packChars cs = packLenChars (List.length cs) cs packBytes :: [Word8] -> ShortByteString packBytes cs = packLenBytes (List.length cs) cs packLenChars :: Int -> [Char] -> ShortByteString packLenChars len cs0 = create len (\mba -> go mba 0 cs0) where go :: MBA s -> Int -> [Char] -> ST s () go !_ !_ [] = return () go !mba !i (c:cs) = do writeCharArray mba i c go mba (i+1) cs packLenBytes :: Int -> [Word8] -> ShortByteString packLenBytes len ws0 = create len (\mba -> go mba 0 ws0) where go :: MBA s -> Int -> [Word8] -> ST s () go !_ !_ [] = return () go !mba !i (w:ws) = do writeWord8Array mba i w go mba (i+1) ws -- Unpacking bytestrings into lists effeciently is a tradeoff: on the one hand -- we would like to write a tight loop that just blats the list into memory, on -- the other hand we want it to be unpacked lazily so we don't end up with a -- massive list data structure in memory. -- -- Our strategy is to combine both: we will unpack lazily in reasonable sized -- chunks, where each chunk is unpacked strictly. -- -- unpackChars does the lazy loop, while unpackAppendBytes and -- unpackAppendChars do the chunks strictly. unpackChars :: ShortByteString -> [Char] unpackChars bs = unpackAppendCharsLazy bs [] unpackBytes :: ShortByteString -> [Word8] unpackBytes bs = unpackAppendBytesLazy bs [] -- Why 100 bytes you ask? Because on a 64bit machine the list we allocate -- takes just shy of 4k which seems like a reasonable amount. -- (5 words per list element, 8 bytes per word, 100 elements = 4000 bytes) unpackAppendCharsLazy :: ShortByteString -> [Char] -> [Char] unpackAppendCharsLazy sbs cs0 = go 0 (length sbs) cs0 where sz = 100 go off len cs | len <= sz = unpackAppendCharsStrict sbs off len cs | otherwise = unpackAppendCharsStrict sbs off sz remainder where remainder = go (off+sz) (len-sz) cs unpackAppendBytesLazy :: ShortByteString -> [Word8] -> [Word8] unpackAppendBytesLazy sbs ws0 = go 0 (length sbs) ws0 where sz = 100 go off len ws | len <= sz = unpackAppendBytesStrict sbs off len ws | otherwise = unpackAppendBytesStrict sbs off sz remainder where remainder = go (off+sz) (len-sz) ws -- For these unpack functions, since we're unpacking the whole list strictly we -- build up the result list in an accumulator. This means we have to build up -- the list starting at the end. So our traversal starts at the end of the -- buffer and loops down until we hit the sentinal: unpackAppendCharsStrict :: ShortByteString -> Int -> Int -> [Char] -> [Char] unpackAppendCharsStrict !sbs off len cs = go (off-1) (off-1 + len) cs where go !sentinal !i !acc | i == sentinal = acc | otherwise = let !c = indexCharArray (asBA sbs) i in go sentinal (i-1) (c:acc) unpackAppendBytesStrict :: ShortByteString -> Int -> Int -> [Word8] -> [Word8] unpackAppendBytesStrict !sbs off len ws = go (off-1) (off-1 + len) ws where go !sentinal !i !acc | i == sentinal = acc | otherwise = let !w = indexWord8Array (asBA sbs) i in go sentinal (i-1) (w:acc) ------------------------------------------------------------------------ -- Eq and Ord implementations equateBytes :: ShortByteString -> ShortByteString -> Bool equateBytes sbs1 sbs2 = let !len1 = length sbs1 !len2 = length sbs2 in len1 == len2 && 0 == accursedUnutterablePerformIO (memcmp_ByteArray (asBA sbs1) (asBA sbs2) len1) compareBytes :: ShortByteString -> ShortByteString -> Ordering compareBytes sbs1 sbs2 = let !len1 = length sbs1 !len2 = length sbs2 !len = min len1 len2 in case accursedUnutterablePerformIO (memcmp_ByteArray (asBA sbs1) (asBA sbs2) len) of i | i < 0 -> LT | i > 0 -> GT | len2 > len1 -> LT | len2 < len1 -> GT | otherwise -> EQ ------------------------------------------------------------------------ -- Appending and concatenation append :: ShortByteString -> ShortByteString -> ShortByteString append src1 src2 = let !len1 = length src1 !len2 = length src2 in create (len1 + len2) $ \dst -> do copyByteArray (asBA src1) 0 dst 0 len1 copyByteArray (asBA src2) 0 dst len1 len2 concat :: [ShortByteString] -> ShortByteString concat sbss = create (totalLen 0 sbss) (\dst -> copy dst 0 sbss) where totalLen !acc [] = acc totalLen !acc (sbs: sbss) = totalLen (acc + length sbs) sbss copy :: MBA s -> Int -> [ShortByteString] -> ST s () copy !_ !_ [] = return () copy !dst !off (src : sbss) = do let !len = length src copyByteArray (asBA src) 0 dst off len copy dst (off + len) sbss ------------------------------------------------------------------------ -- Exported low level operations copyToPtr :: ShortByteString -- ^ source data -> Int -- ^ offset into source -> Ptr a -- ^ destination -> Int -- ^ number of bytes to copy -> IO () copyToPtr src off dst len = stToIO $ copyByteArrayToAddr (asBA src) off dst len createFromPtr :: Ptr a -- ^ source data -> Int -- ^ number of bytes to copy -> IO ShortByteString createFromPtr !ptr len = stToIO $ do mba <- newByteArray len copyAddrToByteArray ptr mba 0 len BA# ba# <- unsafeFreezeByteArray mba return (SBS ba# ) ------------------------------------------------------------------------ -- Primop wrappers data BA = BA# ByteArray# data MBA s = MBA# (MutableByteArray# s) indexCharArray :: BA -> Int -> Char indexCharArray (BA# ba#) (I# i#) = C# (indexCharArray# ba# i#) indexWord8Array :: BA -> Int -> Word8 indexWord8Array (BA# ba#) (I# i#) = W8# (indexWord8Array# ba# i#) newByteArray :: Int -> ST s (MBA s) newByteArray (I# len#) = ST $ \s -> case newByteArray# len# s of (# s, mba# #) -> (# s, MBA# mba# #) newPinnedByteArray :: Int -> ST s (MBA s) newPinnedByteArray (I# len#) = ST $ \s -> case newPinnedByteArray# len# s of (# s, mba# #) -> (# s, MBA# mba# #) unsafeFreezeByteArray :: MBA s -> ST s BA unsafeFreezeByteArray (MBA# mba#) = ST $ \s -> case unsafeFreezeByteArray# mba# s of (# s, ba# #) -> (# s, BA# ba# #) writeCharArray :: MBA s -> Int -> Char -> ST s () writeCharArray (MBA# mba#) (I# i#) (C# c#) = ST $ \s -> case writeCharArray# mba# i# c# s of s -> (# s, () #) writeWord8Array :: MBA s -> Int -> Word8 -> ST s () writeWord8Array (MBA# mba#) (I# i#) (W8# w#) = ST $ \s -> case writeWord8Array# mba# i# w# s of s -> (# s, () #) copyAddrToByteArray :: Ptr a -> MBA RealWorld -> Int -> Int -> ST RealWorld () copyAddrToByteArray (Ptr src#) (MBA# dst#) (I# dst_off#) (I# len#) = ST $ \s -> case copyAddrToByteArray# src# dst# dst_off# len# s of s -> (# s, () #) copyByteArrayToAddr :: BA -> Int -> Ptr a -> Int -> ST RealWorld () copyByteArrayToAddr (BA# src#) (I# src_off#) (Ptr dst#) (I# len#) = ST $ \s -> case copyByteArrayToAddr# src# src_off# dst# len# s of s -> (# s, () #) copyByteArray :: BA -> Int -> MBA s -> Int -> Int -> ST s () copyByteArray (BA# src#) (I# src_off#) (MBA# dst#) (I# dst_off#) (I# len#) = ST $ \s -> case copyByteArray# src# src_off# dst# dst_off# len# s of s -> (# s, () #) ------------------------------------------------------------------------ -- FFI imports memcmp_ByteArray :: BA -> BA -> Int -> IO CInt memcmp_ByteArray (BA# ba1#) (BA# ba2#) len = c_memcmp_ByteArray ba1# ba2# (fromIntegral len) foreign import ccall unsafe "string.h memcmp" c_memcmp_ByteArray :: ByteArray# -> ByteArray# -> CSize -> IO CInt ------------------------------------------------------------------------ -- Primop replacements copyAddrToByteArray# :: Addr# -> MutableByteArray# RealWorld -> Int# -> Int# -> State# RealWorld -> State# RealWorld copyByteArrayToAddr# :: ByteArray# -> Int# -> Addr# -> Int# -> State# RealWorld -> State# RealWorld copyByteArray# :: ByteArray# -> Int# -> MutableByteArray# s -> Int# -> Int# -> State# s -> State# s -- These exist as real primops in ghc-7.8, and for before that we use -- FFI to C memcpy. copyAddrToByteArray# = GHC.Exts.copyAddrToByteArray# copyByteArrayToAddr# = GHC.Exts.copyByteArrayToAddr# copyByteArray# = GHC.Exts.copyByteArray#
phischu/fragnix
tests/packages/scotty/Data.ByteString.Short.Internal.hs
bsd-3-clause
16,065
0
14
3,979
4,216
2,192
2,024
290
3
{-# LANGUAGE RecordWildCards, DeriveDataTypeable #-} -- | Nix configuration module Stack.Config.Nix (nixOptsFromMonoid ,StackNixException(..) ) where import Control.Applicative import Control.Monad (join, when) import qualified Data.Text as T import Data.Maybe import Data.Typeable import Distribution.System (OS (..)) import Stack.Types import Control.Exception.Lifted import Control.Monad.Catch (throwM,MonadCatch) import Prelude -- | Interprets NixOptsMonoid options. nixOptsFromMonoid :: (Monad m, MonadCatch m) => Maybe Project -> NixOptsMonoid -> OS -> m NixOpts nixOptsFromMonoid mproject NixOptsMonoid{..} os = do let nixEnable = fromMaybe nixMonoidDefaultEnable nixMonoidEnable defaultPure = case os of OSX -> False _ -> True nixPureShell = fromMaybe defaultPure nixMonoidPureShell nixPackages = fromMaybe [] nixMonoidPackages nixInitFile = nixMonoidInitFile nixShellOptions = fromMaybe [] nixMonoidShellOptions ++ prefixAll (T.pack "-I") (fromMaybe [] nixMonoidPath) nixCompiler resolverOverride compilerOverride = let mresolver = resolverOverride <|> fmap projectResolver mproject mcompiler = compilerOverride <|> join (fmap projectCompiler mproject) in case (mresolver, mcompiler) of (_, Just (GhcVersion v)) -> nixCompilerFromVersion v (Just (ResolverCompiler (GhcVersion v)), _) -> nixCompilerFromVersion v (Just (ResolverSnapshot (LTS x y)), _) -> T.pack ("haskell.packages.lts-" ++ show x ++ "_" ++ show y ++ ".ghc") _ -> T.pack "ghc" when (not (null nixPackages) && isJust nixInitFile) $ throwM NixCannotUseShellFileAndPackagesException return NixOpts{..} where prefixAll p (x:xs) = p : x : prefixAll p xs prefixAll _ _ = [] nixCompilerFromVersion v = T.filter (/= '.') $ T.append (T.pack "haskell.compiler.ghc") (versionText v) -- Exceptions thown specifically by Stack.Nix data StackNixException = NixCannotUseShellFileAndPackagesException -- ^ Nix can't be given packages and a shell file at the same time deriving (Typeable) instance Exception StackNixException instance Show StackNixException where show NixCannotUseShellFileAndPackagesException = "You cannot have packages and a shell-file filled at the same time in your nix-shell configuration."
harendra-kumar/stack
src/Stack/Config/Nix.hs
bsd-3-clause
2,482
0
21
580
609
318
291
52
6
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Cmm optimisation -- -- (c) The University of Glasgow 2006 -- ----------------------------------------------------------------------------- module CmmOpt ( constantFoldNode, constantFoldExpr, cmmMachOpFold, cmmMachOpFoldM ) where #include "HsVersions.h" import CmmUtils import Cmm import DynFlags import Outputable import Platform import Data.Bits import Data.Maybe constantFoldNode :: DynFlags -> CmmNode e x -> CmmNode e x constantFoldNode dflags = mapExp (constantFoldExpr dflags) constantFoldExpr :: DynFlags -> CmmExpr -> CmmExpr constantFoldExpr dflags = wrapRecExp f where f (CmmMachOp op args) = cmmMachOpFold dflags op args f (CmmRegOff r 0) = CmmReg r f e = e -- ----------------------------------------------------------------------------- -- MachOp constant folder -- Now, try to constant-fold the MachOps. The arguments have already -- been optimized and folded. cmmMachOpFold :: DynFlags -> MachOp -- The operation from an CmmMachOp -> [CmmExpr] -- The optimized arguments -> CmmExpr cmmMachOpFold dflags op args = fromMaybe (CmmMachOp op args) (cmmMachOpFoldM dflags op args) -- Returns Nothing if no changes, useful for Hoopl, also reduces -- allocation! cmmMachOpFoldM :: DynFlags -> MachOp -> [CmmExpr] -> Maybe CmmExpr cmmMachOpFoldM _ op [CmmLit (CmmInt x rep)] = Just $ case op of MO_S_Neg _ -> CmmLit (CmmInt (-x) rep) MO_Not _ -> CmmLit (CmmInt (complement x) rep) -- these are interesting: we must first narrow to the -- "from" type, in order to truncate to the correct size. -- The final narrow/widen to the destination type -- is implicit in the CmmLit. MO_SF_Conv _from to -> CmmLit (CmmFloat (fromInteger x) to) MO_SS_Conv from to -> CmmLit (CmmInt (narrowS from x) to) MO_UU_Conv from to -> CmmLit (CmmInt (narrowU from x) to) _ -> panic "cmmMachOpFoldM: unknown unary op" -- Eliminate conversion NOPs cmmMachOpFoldM _ (MO_SS_Conv rep1 rep2) [x] | rep1 == rep2 = Just x cmmMachOpFoldM _ (MO_UU_Conv rep1 rep2) [x] | rep1 == rep2 = Just x -- Eliminate nested conversions where possible cmmMachOpFoldM dflags conv_outer [CmmMachOp conv_inner [x]] | Just (rep1,rep2,signed1) <- isIntConversion conv_inner, Just (_, rep3,signed2) <- isIntConversion conv_outer = case () of -- widen then narrow to the same size is a nop _ | rep1 < rep2 && rep1 == rep3 -> Just x -- Widen then narrow to different size: collapse to single conversion -- but remember to use the signedness from the widening, just in case -- the final conversion is a widen. | rep1 < rep2 && rep2 > rep3 -> Just $ cmmMachOpFold dflags (intconv signed1 rep1 rep3) [x] -- Nested widenings: collapse if the signedness is the same | rep1 < rep2 && rep2 < rep3 && signed1 == signed2 -> Just $ cmmMachOpFold dflags (intconv signed1 rep1 rep3) [x] -- Nested narrowings: collapse | rep1 > rep2 && rep2 > rep3 -> Just $ cmmMachOpFold dflags (MO_UU_Conv rep1 rep3) [x] | otherwise -> Nothing where isIntConversion (MO_UU_Conv rep1 rep2) = Just (rep1,rep2,False) isIntConversion (MO_SS_Conv rep1 rep2) = Just (rep1,rep2,True) isIntConversion _ = Nothing intconv True = MO_SS_Conv intconv False = MO_UU_Conv -- ToDo: a narrow of a load can be collapsed into a narrow load, right? -- but what if the architecture only supports word-sized loads, should -- we do the transformation anyway? cmmMachOpFoldM dflags mop [CmmLit (CmmInt x xrep), CmmLit (CmmInt y _)] = case mop of -- for comparisons: don't forget to narrow the arguments before -- comparing, since they might be out of range. MO_Eq _ -> Just $ CmmLit (CmmInt (if x_u == y_u then 1 else 0) (wordWidth dflags)) MO_Ne _ -> Just $ CmmLit (CmmInt (if x_u /= y_u then 1 else 0) (wordWidth dflags)) MO_U_Gt _ -> Just $ CmmLit (CmmInt (if x_u > y_u then 1 else 0) (wordWidth dflags)) MO_U_Ge _ -> Just $ CmmLit (CmmInt (if x_u >= y_u then 1 else 0) (wordWidth dflags)) MO_U_Lt _ -> Just $ CmmLit (CmmInt (if x_u < y_u then 1 else 0) (wordWidth dflags)) MO_U_Le _ -> Just $ CmmLit (CmmInt (if x_u <= y_u then 1 else 0) (wordWidth dflags)) MO_S_Gt _ -> Just $ CmmLit (CmmInt (if x_s > y_s then 1 else 0) (wordWidth dflags)) MO_S_Ge _ -> Just $ CmmLit (CmmInt (if x_s >= y_s then 1 else 0) (wordWidth dflags)) MO_S_Lt _ -> Just $ CmmLit (CmmInt (if x_s < y_s then 1 else 0) (wordWidth dflags)) MO_S_Le _ -> Just $ CmmLit (CmmInt (if x_s <= y_s then 1 else 0) (wordWidth dflags)) MO_Add r -> Just $ CmmLit (CmmInt (x + y) r) MO_Sub r -> Just $ CmmLit (CmmInt (x - y) r) MO_Mul r -> Just $ CmmLit (CmmInt (x * y) r) MO_U_Quot r | y /= 0 -> Just $ CmmLit (CmmInt (x_u `quot` y_u) r) MO_U_Rem r | y /= 0 -> Just $ CmmLit (CmmInt (x_u `rem` y_u) r) MO_S_Quot r | y /= 0 -> Just $ CmmLit (CmmInt (x `quot` y) r) MO_S_Rem r | y /= 0 -> Just $ CmmLit (CmmInt (x `rem` y) r) MO_And r -> Just $ CmmLit (CmmInt (x .&. y) r) MO_Or r -> Just $ CmmLit (CmmInt (x .|. y) r) MO_Xor r -> Just $ CmmLit (CmmInt (x `xor` y) r) MO_Shl r -> Just $ CmmLit (CmmInt (x `shiftL` fromIntegral y) r) MO_U_Shr r -> Just $ CmmLit (CmmInt (x_u `shiftR` fromIntegral y) r) MO_S_Shr r -> Just $ CmmLit (CmmInt (x `shiftR` fromIntegral y) r) _ -> Nothing where x_u = narrowU xrep x y_u = narrowU xrep y x_s = narrowS xrep x y_s = narrowS xrep y -- When possible, shift the constants to the right-hand side, so that we -- can match for strength reductions. Note that the code generator will -- also assume that constants have been shifted to the right when -- possible. cmmMachOpFoldM dflags op [x@(CmmLit _), y] | not (isLit y) && isCommutableMachOp op = Just (cmmMachOpFold dflags op [y, x]) -- Turn (a+b)+c into a+(b+c) where possible. Because literals are -- moved to the right, it is more likely that we will find -- opportunities for constant folding when the expression is -- right-associated. -- -- ToDo: this appears to introduce a quadratic behaviour due to the -- nested cmmMachOpFold. Can we fix this? -- -- Why do we check isLit arg1? If arg1 is a lit, it means that arg2 -- is also a lit (otherwise arg1 would be on the right). If we -- put arg1 on the left of the rearranged expression, we'll get into a -- loop: (x1+x2)+x3 => x1+(x2+x3) => (x2+x3)+x1 => x2+(x3+x1) ... -- -- Also don't do it if arg1 is PicBaseReg, so that we don't separate the -- PicBaseReg from the corresponding label (or label difference). -- cmmMachOpFoldM dflags mop1 [CmmMachOp mop2 [arg1,arg2], arg3] | mop2 `associates_with` mop1 && not (isLit arg1) && not (isPicReg arg1) = Just (cmmMachOpFold dflags mop2 [arg1, cmmMachOpFold dflags mop1 [arg2,arg3]]) where MO_Add{} `associates_with` MO_Sub{} = True mop1 `associates_with` mop2 = mop1 == mop2 && isAssociativeMachOp mop1 -- special case: (a - b) + c ==> a + (c - b) cmmMachOpFoldM dflags mop1@(MO_Add{}) [CmmMachOp mop2@(MO_Sub{}) [arg1,arg2], arg3] | not (isLit arg1) && not (isPicReg arg1) = Just (cmmMachOpFold dflags mop1 [arg1, cmmMachOpFold dflags mop2 [arg3,arg2]]) -- special case: (PicBaseReg + lit) + N ==> PicBaseReg + (lit+N) -- -- this is better because lit+N is a single link-time constant (e.g. a -- CmmLabelOff), so the right-hand expression needs only one -- instruction, whereas the left needs two. This happens when pointer -- tagging gives us label+offset, and PIC turns the label into -- PicBaseReg + label. -- cmmMachOpFoldM _ MO_Add{} [ CmmMachOp op@MO_Add{} [pic, CmmLit lit] , CmmLit (CmmInt n rep) ] | isPicReg pic = Just $ CmmMachOp op [pic, CmmLit $ cmmOffsetLit lit off ] where off = fromIntegral (narrowS rep n) -- Make a RegOff if we can cmmMachOpFoldM _ (MO_Add _) [CmmReg reg, CmmLit (CmmInt n rep)] = Just $ cmmRegOff reg (fromIntegral (narrowS rep n)) cmmMachOpFoldM _ (MO_Add _) [CmmRegOff reg off, CmmLit (CmmInt n rep)] = Just $ cmmRegOff reg (off + fromIntegral (narrowS rep n)) cmmMachOpFoldM _ (MO_Sub _) [CmmReg reg, CmmLit (CmmInt n rep)] = Just $ cmmRegOff reg (- fromIntegral (narrowS rep n)) cmmMachOpFoldM _ (MO_Sub _) [CmmRegOff reg off, CmmLit (CmmInt n rep)] = Just $ cmmRegOff reg (off - fromIntegral (narrowS rep n)) -- Fold label(+/-)offset into a CmmLit where possible cmmMachOpFoldM _ (MO_Add _) [CmmLit lit, CmmLit (CmmInt i rep)] = Just $ CmmLit (cmmOffsetLit lit (fromIntegral (narrowU rep i))) cmmMachOpFoldM _ (MO_Add _) [CmmLit (CmmInt i rep), CmmLit lit] = Just $ CmmLit (cmmOffsetLit lit (fromIntegral (narrowU rep i))) cmmMachOpFoldM _ (MO_Sub _) [CmmLit lit, CmmLit (CmmInt i rep)] = Just $ CmmLit (cmmOffsetLit lit (fromIntegral (negate (narrowU rep i)))) -- Comparison of literal with widened operand: perform the comparison -- at the smaller width, as long as the literal is within range. -- We can't do the reverse trick, when the operand is narrowed: -- narrowing throws away bits from the operand, there's no way to do -- the same comparison at the larger size. cmmMachOpFoldM dflags cmp [CmmMachOp conv [x], CmmLit (CmmInt i _)] | -- powerPC NCG has a TODO for I8/I16 comparisons, so don't try platformArch (targetPlatform dflags) `elem` [ArchX86, ArchX86_64], -- if the operand is widened: Just (rep, signed, narrow_fn) <- maybe_conversion conv, -- and this is a comparison operation: Just narrow_cmp <- maybe_comparison cmp rep signed, -- and the literal fits in the smaller size: i == narrow_fn rep i -- then we can do the comparison at the smaller size = Just (cmmMachOpFold dflags narrow_cmp [x, CmmLit (CmmInt i rep)]) where maybe_conversion (MO_UU_Conv from to) | to > from = Just (from, False, narrowU) maybe_conversion (MO_SS_Conv from to) | to > from = Just (from, True, narrowS) -- don't attempt to apply this optimisation when the source -- is a float; see #1916 maybe_conversion _ = Nothing -- careful (#2080): if the original comparison was signed, but -- we were doing an unsigned widen, then we must do an -- unsigned comparison at the smaller size. maybe_comparison (MO_U_Gt _) rep _ = Just (MO_U_Gt rep) maybe_comparison (MO_U_Ge _) rep _ = Just (MO_U_Ge rep) maybe_comparison (MO_U_Lt _) rep _ = Just (MO_U_Lt rep) maybe_comparison (MO_U_Le _) rep _ = Just (MO_U_Le rep) maybe_comparison (MO_Eq _) rep _ = Just (MO_Eq rep) maybe_comparison (MO_S_Gt _) rep True = Just (MO_S_Gt rep) maybe_comparison (MO_S_Ge _) rep True = Just (MO_S_Ge rep) maybe_comparison (MO_S_Lt _) rep True = Just (MO_S_Lt rep) maybe_comparison (MO_S_Le _) rep True = Just (MO_S_Le rep) maybe_comparison (MO_S_Gt _) rep False = Just (MO_U_Gt rep) maybe_comparison (MO_S_Ge _) rep False = Just (MO_U_Ge rep) maybe_comparison (MO_S_Lt _) rep False = Just (MO_U_Lt rep) maybe_comparison (MO_S_Le _) rep False = Just (MO_U_Le rep) maybe_comparison _ _ _ = Nothing -- We can often do something with constants of 0 and 1 ... cmmMachOpFoldM dflags mop [x, y@(CmmLit (CmmInt 0 _))] = case mop of MO_Add _ -> Just x MO_Sub _ -> Just x MO_Mul _ -> Just y MO_And _ -> Just y MO_Or _ -> Just x MO_Xor _ -> Just x MO_Shl _ -> Just x MO_S_Shr _ -> Just x MO_U_Shr _ -> Just x MO_Ne _ | isComparisonExpr x -> Just x MO_Eq _ | Just x' <- maybeInvertCmmExpr x -> Just x' MO_U_Gt _ | isComparisonExpr x -> Just x MO_S_Gt _ | isComparisonExpr x -> Just x MO_U_Lt _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 (wordWidth dflags)) MO_S_Lt _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 (wordWidth dflags)) MO_U_Ge _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 (wordWidth dflags)) MO_S_Ge _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 (wordWidth dflags)) MO_U_Le _ | Just x' <- maybeInvertCmmExpr x -> Just x' MO_S_Le _ | Just x' <- maybeInvertCmmExpr x -> Just x' _ -> Nothing cmmMachOpFoldM dflags mop [x, (CmmLit (CmmInt 1 rep))] = case mop of MO_Mul _ -> Just x MO_S_Quot _ -> Just x MO_U_Quot _ -> Just x MO_S_Rem _ -> Just $ CmmLit (CmmInt 0 rep) MO_U_Rem _ -> Just $ CmmLit (CmmInt 0 rep) MO_Ne _ | Just x' <- maybeInvertCmmExpr x -> Just x' MO_Eq _ | isComparisonExpr x -> Just x MO_U_Lt _ | Just x' <- maybeInvertCmmExpr x -> Just x' MO_S_Lt _ | Just x' <- maybeInvertCmmExpr x -> Just x' MO_U_Gt _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 (wordWidth dflags)) MO_S_Gt _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 0 (wordWidth dflags)) MO_U_Le _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 (wordWidth dflags)) MO_S_Le _ | isComparisonExpr x -> Just $ CmmLit (CmmInt 1 (wordWidth dflags)) MO_U_Ge _ | isComparisonExpr x -> Just x MO_S_Ge _ | isComparisonExpr x -> Just x _ -> Nothing -- Now look for multiplication/division by powers of 2 (integers). cmmMachOpFoldM dflags mop [x, (CmmLit (CmmInt n _))] = case mop of MO_Mul rep | Just p <- exactLog2 n -> Just (cmmMachOpFold dflags (MO_Shl rep) [x, CmmLit (CmmInt p rep)]) MO_U_Quot rep | Just p <- exactLog2 n -> Just (cmmMachOpFold dflags (MO_U_Shr rep) [x, CmmLit (CmmInt p rep)]) MO_S_Quot rep | Just p <- exactLog2 n, CmmReg _ <- x -> -- We duplicate x below, hence require -- it is a reg. FIXME: remove this restriction. -- shift right is not the same as quot, because it rounds -- to minus infinity, whereasq quot rounds toward zero. -- To fix this up, we add one less than the divisor to the -- dividend if it is a negative number. -- -- to avoid a test/jump, we use the following sequence: -- x1 = x >> word_size-1 (all 1s if -ve, all 0s if +ve) -- x2 = y & (divisor-1) -- result = (x+x2) >>= log2(divisor) -- this could be done a bit more simply using conditional moves, -- but we're processor independent here. -- -- we optimise the divide by 2 case slightly, generating -- x1 = x >> word_size-1 (unsigned) -- return = (x + x1) >>= log2(divisor) let bits = fromIntegral (widthInBits rep) - 1 shr = if p == 1 then MO_U_Shr rep else MO_S_Shr rep x1 = CmmMachOp shr [x, CmmLit (CmmInt bits rep)] x2 = if p == 1 then x1 else CmmMachOp (MO_And rep) [x1, CmmLit (CmmInt (n-1) rep)] x3 = CmmMachOp (MO_Add rep) [x, x2] in Just (cmmMachOpFold dflags (MO_S_Shr rep) [x3, CmmLit (CmmInt p rep)]) _ -> Nothing -- ToDo (#7116): optimise floating-point multiplication, e.g. x*2.0 -> x+x -- Unfortunately this needs a unique supply because x might not be a -- register. See #2253 (program 6) for an example. -- Anything else is just too hard. cmmMachOpFoldM _ _ _ = Nothing -- ----------------------------------------------------------------------------- -- exactLog2 -- This algorithm for determining the $\log_2$ of exact powers of 2 comes -- from GCC. It requires bit manipulation primitives, and we use GHC -- extensions. Tough. exactLog2 :: Integer -> Maybe Integer exactLog2 x = if (x <= 0 || x >= 2147483648) then Nothing else if (x .&. (-x)) /= x then Nothing else Just (pow2 x) where pow2 x | x == 1 = 0 | otherwise = 1 + pow2 (x `shiftR` 1) -- ----------------------------------------------------------------------------- -- Utils isLit :: CmmExpr -> Bool isLit (CmmLit _) = True isLit _ = False isComparisonExpr :: CmmExpr -> Bool isComparisonExpr (CmmMachOp op _) = isComparisonMachOp op isComparisonExpr _ = False isPicReg :: CmmExpr -> Bool isPicReg (CmmReg (CmmGlobal PicBaseReg)) = True isPicReg _ = False
acowley/ghc
compiler/cmm/CmmOpt.hs
bsd-3-clause
16,944
0
20
4,641
4,944
2,455
2,489
230
97
module ShowPublicOrganization where import qualified Github.Organizations as Github main = do possibleOrganization <- Github.publicOrganization "thoughtbot" case possibleOrganization of (Left error) -> putStrLn $ "Error: " ++ (show error) (Right organization) -> putStrLn $ formatOrganization organization formatOrganization organization = (maybe "" (\s -> s ++ "\n") (Github.organizationName organization)) ++ (Github.organizationHtmlUrl organization) ++ (maybe "" (\s -> "\n" ++ s) (Github.organizationBlog organization))
mavenraven/github
samples/Organizations/ShowPublicOrganization.hs
bsd-3-clause
565
0
12
101
165
86
79
12
2
{-# LANGUAGE CPP, BangPatterns, ScopedTypeVariables #-} -- | -- Module : Data.Attoparsec.Internal -- Copyright : Bryan O'Sullivan 2007-2014 -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : unknown -- -- Simple, efficient parser combinators, loosely based on the Parsec -- library. module Data.Attoparsec.Internal ( compareResults , prompt , demandInput , wantInput , endOfInput , atEnd , satisfyElem ) where import Control.Applicative ((<$>)) #if __GLASGOW_HASKELL__ >= 700 import Data.ByteString (ByteString) #endif import Data.Attoparsec.Internal.Types import Prelude hiding (succ) -- | Compare two 'IResult' values for equality. -- -- If both 'IResult's are 'Partial', the result will be 'Nothing', as -- they are incomplete and hence their equality cannot be known. -- (This is why there is no 'Eq' instance for 'IResult'.) compareResults :: (Eq i, Eq r) => IResult i r -> IResult i r -> Maybe Bool compareResults (Fail t0 ctxs0 msg0) (Fail t1 ctxs1 msg1) = Just (t0 == t1 && ctxs0 == ctxs1 && msg0 == msg1) compareResults (Done t0 r0) (Done t1 r1) = Just (t0 == t1 && r0 == r1) compareResults (Partial _) (Partial _) = Nothing compareResults _ _ = Just False -- | Ask for input. If we receive any, pass it to a success -- continuation, otherwise to a failure continuation. prompt :: Chunk t => State t -> Pos -> More -> (State t -> Pos -> More -> IResult t r) -> (State t -> Pos -> More -> IResult t r) -> IResult t r prompt t pos _more lose succ = Partial $ \s -> if nullChunk s then lose t pos Complete else succ (pappendChunk t s) pos Incomplete #if __GLASGOW_HASKELL__ >= 700 {-# SPECIALIZE prompt :: State ByteString -> Pos -> More -> (State ByteString -> Pos -> More -> IResult ByteString r) -> (State ByteString -> Pos -> More -> IResult ByteString r) -> IResult ByteString r #-} #endif -- | Immediately demand more input via a 'Partial' continuation -- result. demandInput :: Chunk t => Parser t () demandInput = Parser $ \t pos more lose succ -> case more of Complete -> lose t pos more [] "not enough input" _ -> let lose' t' pos' more' = lose t' pos' more' [] "not enough input" succ' t' pos' more' = succ t' pos' more' () in prompt t pos more lose' succ' #if __GLASGOW_HASKELL__ >= 700 {-# SPECIALIZE demandInput :: Parser ByteString () #-} #endif -- | This parser always succeeds. It returns 'True' if any input is -- available either immediately or on demand, and 'False' if the end -- of all input has been reached. wantInput :: forall t . Chunk t => Parser t Bool wantInput = Parser $ \t pos more _lose succ -> case () of _ | pos < atBufferEnd (undefined :: t) t -> succ t pos more True | more == Complete -> succ t pos more False | otherwise -> let lose' t' pos' more' = succ t' pos' more' False succ' t' pos' more' = succ t' pos' more' True in prompt t pos more lose' succ' {-# INLINE wantInput #-} -- | Match only if all input has been consumed. endOfInput :: forall t . Chunk t => Parser t () endOfInput = Parser $ \t pos more lose succ -> case () of _| pos < atBufferEnd (undefined :: t) t -> lose t pos more [] "endOfInput" | more == Complete -> succ t pos more () | otherwise -> let lose' t' pos' more' _ctx _msg = succ t' pos' more' () succ' t' pos' more' _a = lose t' pos' more' [] "endOfInput" in runParser demandInput t pos more lose' succ' #if __GLASGOW_HASKELL__ >= 700 {-# SPECIALIZE endOfInput :: Parser ByteString () #-} #endif -- | Return an indication of whether the end of input has been -- reached. atEnd :: Chunk t => Parser t Bool atEnd = not <$> wantInput {-# INLINE atEnd #-} satisfySuspended :: forall t r . Chunk t => (ChunkElem t -> Bool) -> State t -> Pos -> More -> Failure t (State t) r -> Success t (State t) (ChunkElem t) r -> IResult t r satisfySuspended p t pos more lose succ = runParser (demandInput >> go) t pos more lose succ where go = Parser $ \t' pos' more' lose' succ' -> case bufferElemAt (undefined :: t) pos' t' of Just (e, l) | p e -> succ' t' (pos' + Pos l) more' e | otherwise -> lose' t' pos' more' [] "satisfyElem" Nothing -> runParser (demandInput >> go) t' pos' more' lose' succ' #if __GLASGOW_HASKELL__ >= 700 {-# SPECIALIZE satisfySuspended :: (ChunkElem ByteString -> Bool) -> State ByteString -> Pos -> More -> Failure ByteString (State ByteString) r -> Success ByteString (State ByteString) (ChunkElem ByteString) r -> IResult ByteString r #-} #endif -- | The parser @satisfyElem p@ succeeds for any chunk element for which the -- predicate @p@ returns 'True'. Returns the element that is -- actually parsed. satisfyElem :: forall t . Chunk t => (ChunkElem t -> Bool) -> Parser t (ChunkElem t) satisfyElem p = Parser $ \t pos more lose succ -> case bufferElemAt (undefined :: t) pos t of Just (e, l) | p e -> succ t (pos + Pos l) more e | otherwise -> lose t pos more [] "satisfyElem" Nothing -> satisfySuspended p t pos more lose succ {-# INLINE satisfyElem #-}
DavidAlphaFox/ghc
utils/haddock/haddock-library/vendor/attoparsec-0.12.1.1/Data/Attoparsec/Internal.hs
bsd-3-clause
5,639
0
16
1,659
1,402
718
684
77
2
{-# LANGUAGE FlexibleInstances, GADTs #-} module T5858 where class InferOverloaded a where infer :: a -> String -- instance (t1 ~ String, t2 ~ String) => InferOverloaded (t1,t2) where instance (t1 ~ String) => InferOverloaded (t1,t1) where infer = show . fst foo = infer ([],[])
urbanslug/ghc
testsuite/tests/typecheck/should_fail/T5858.hs
bsd-3-clause
288
0
7
55
76
43
33
7
1